services

package
v2.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2026 License: BSD-3-Clause Imports: 154 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultArcaneToolsImage is the shared Arcane toolbox image used for
	// helper commands and Trivy-based vulnerability scans.
	DefaultArcaneToolsImage = "ghcr.io/getarcaneapp/tools:latest"
	// DefaultTrivyImage preserves the existing setting name, but now points at
	// the shared Arcane tools image that includes the Trivy binary.
	DefaultTrivyImage       = DefaultArcaneToolsImage
	DefaultTrivyNetworkMode = "bridge"

	DefaultTrivyDBRepository           = "ghcr.io/getarcaneapp/trivy-db:2"
	DefaultTrivyJavaDBRepository       = "ghcr.io/getarcaneapp/trivy-java-db:1"
	DefaultTrivyChecksBundleRepository = "ghcr.io/getarcaneapp/trivy-checks:1"
)
View Source
const KVKeySwarmEnabled = "swarm.enabled"

Variables

View Source
var (
	ErrApiKeyNotFound  = errors.New("API key not found")
	ErrApiKeyExpired   = errors.New("API key has expired")
	ErrApiKeyInvalid   = errors.New("invalid API key")
	ErrApiKeyProtected = errors.New("API key is protected")
)
View Source
var (
	ErrInvalidCredentials   = errors.New("invalid credentials")
	ErrUserNotFound         = errors.New("user not found")
	ErrInvalidToken         = errors.New("invalid token")
	ErrExpiredToken         = errors.New("token expired")
	ErrTokenVersionMismatch = errors.New("token version mismatch")
	ErrLocalAuthDisabled    = errors.New("local authentication is disabled")
	ErrOidcAuthDisabled     = errors.New("OIDC authentication is disabled")
)
View Source
var (
	ErrEnvironmentAccessTokenRequired = errors.New("environment access token required")
	ErrInvalidEnvironmentAccessToken  = errors.New("invalid environment access token")
)
View Source
var (
	ErrWebhookNotFound      = errors.New("webhook not found")
	ErrWebhookInvalid       = errors.New("invalid webhook token")
	ErrWebhookDisabled      = errors.New("webhook is disabled")
	ErrWebhookInvalidType   = errors.New("invalid webhook target type")
	ErrWebhookInvalidAction = errors.New("invalid webhook action type")
	ErrWebhookMissingTarget = errors.New("target ID is required for container, project, and gitops webhook types")
)
View Source
var ErrActivityNotCancelable = errors.New("activity is not cancelable")

ErrActivityNotCancelable indicates the activity has already reached a terminal state and can no longer be cancelled.

View Source
var ErrApiKeyPermissionEscalation = errors.New("cannot grant a permission you do not have")

ErrApiKeyPermissionEscalation is returned when a caller attempts to grant an API key permissions they themselves do not hold.

View Source
var ErrCannotRemoveLastAdmin = errors.New("cannot remove the last admin user")
View Source
var ErrUnauthorizedNotificationDispatch = errors.New("unauthorized notification dispatch")
View Source
var ErrUnsupportedDispatchKind = errors.New("unsupported notification dispatch kind")

Functions

func ApplyEnvironmentRuntimeState

func ApplyEnvironmentRuntimeState(env *environmenttypes.Environment)

ApplyEnvironmentRuntimeState normalizes edge environment runtime status using in-memory tunnel and poll registries without mutating persisted state.

func DefaultSettingsConfig

func DefaultSettingsConfig() *models.Settings

DefaultSettingsConfig returns the canonical default settings model used by Arcane.

func RedactNotificationConfigCredentials

func RedactNotificationConfigCredentials(provider models.NotificationProvider, config models.JSON) models.JSON

RedactNotificationConfigCredentials returns a copy of config with provider credential fields blanked for API responses.

Types

type ActivityService

type ActivityService struct {
	// contains filtered or unexported fields
}

func NewActivityService

func NewActivityService(db *database.DB) *ActivityService

func (*ActivityService) AppendMessage

func (s *ActivityService) AppendMessage(ctx context.Context, activityID string, req AppendActivityMessageRequest) (*activitytypes.Message, error)

func (*ActivityService) CancelActivity

func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, activityID, requestedBy string) (*activitytypes.Activity, error)

CancelActivity requests cancellation of a running or queued activity. When the activity's work is running in this process it interrupts it (the work finalizes its own terminal status); otherwise it marks the activity cancelled directly, but only if it is still active. Returns ErrActivityNotCancelable if the activity has already reached a terminal state, or gorm.ErrRecordNotFound if it is unknown.

func (*ActivityService) CompleteActivity

func (s *ActivityService) CompleteActivity(ctx context.Context, activityID string, status models.ActivityStatus, finalMessage string, errMessage *string, finalStep ...string) (*activitytypes.Activity, error)

func (*ActivityService) DeleteHistory

func (s *ActivityService) DeleteHistory(ctx context.Context, environmentID string) (int64, error)

func (*ActivityService) FailStaleImageUpdateChecks

func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64, error)

FailStaleImageUpdateChecks marks image update checks that were left running across a prior process lifetime as failed. It intentionally scopes cleanup to old image-update-check activities so startup repair cannot affect other work.

func (*ActivityService) GetActivityDetail

func (s *ActivityService) GetActivityDetail(ctx context.Context, environmentID, activityID string, limit int) (*activitytypes.Detail, error)

func (*ActivityService) ListActivitiesPaginated

func (s *ActivityService) ListActivitiesPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]activitytypes.Activity, pagination.Response, error)

func (*ActivityService) PruneHistory

func (s *ActivityService) PruneHistory(ctx context.Context, retentionDays, maxEntries int) (int64, error)

func (*ActivityService) RequestCancel

func (s *ActivityService) RequestCancel(activityID string) bool

RequestCancel cancels the work context registered for activityID, signalling activitylib.ErrCanceled as the cause. It returns whether a running activity was found in this process.

func (*ActivityService) StartActivity

func (*ActivityService) Subscribe

func (s *ActivityService) Subscribe(environmentID string) (<-chan activitytypes.StreamEvent, func() bool, func())

func (*ActivityService) Track

func (s *ActivityService) Track(ctx context.Context, activityID string) context.Context

Track derives a cancelable work context bound to activityID and registers its cancel function so RequestCancel can interrupt the work. The registration is released when the activity is completed (see CompleteActivity) or when the returned context is otherwise no longer needed. Implements activitylib.Tracker.

func (*ActivityService) UpdateActivity

func (s *ActivityService) UpdateActivity(ctx context.Context, activityID string, req UpdateActivityRequest) (*activitytypes.Activity, error)

type ApiKeyService

type ApiKeyService struct {
	// contains filtered or unexported fields
}

func NewApiKeyService

func NewApiKeyService(db *database.DB, userService *UserService) *ApiKeyService

func (*ApiKeyService) CreateApiKey

func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apikey.CreateApiKey) (*apikey.ApiKeyCreatedDto, error)

func (*ApiKeyService) CreateDefaultAdminAPIKey

func (s *ApiKeyService) CreateDefaultAdminAPIKey(ctx context.Context, userID, rawKey string) (*apikey.ApiKeyCreatedDto, error)

func (*ApiKeyService) CreateEnvironmentApiKey

func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentID string, userID string) (*apikey.ApiKeyCreatedDto, error)

func (*ApiKeyService) DeleteApiKey

func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error

func (*ApiKeyService) GetApiKey

func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKey, error)

func (*ApiKeyService) GetEnvironmentByApiKey

func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey string) (*string, error)

func (*ApiKeyService) ListApiKeys

func (*ApiKeyService) ListApiKeysByUser

func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([]apikey.ApiKey, error)

ListApiKeysByUser returns every non-static, non-bootstrap API key owned by userID. Used by the self-service personal-keys flow.

func (*ApiKeyService) ReconcileDefaultAdminAPIKey

func (s *ApiKeyService) ReconcileDefaultAdminAPIKey(ctx context.Context, rawKey string) error

func (*ApiKeyService) UpdateApiKey

func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerUserID, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error)

func (*ApiKeyService) ValidateApiKey

func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error)

func (*ApiKeyService) ValidateApiKeyWithID

func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, string, error)

ValidateApiKeyWithID is like ValidateApiKey but additionally returns the API key's database ID so callers can resolve per-key permissions.

func (*ApiKeyService) WithRoleService

func (s *ApiKeyService) WithRoleService(roleService *RoleService) *ApiKeyService

WithRoleService wires the RoleService dependency. Separated from the constructor to break the bootstrap-ordering cycle between ApiKeyService and RoleService (RoleService.BackfillApiKeyPermissions needs ApiKeyService to exist when it runs, while permission-validated CreateApiKey needs the RoleService).

type AppendActivityMessageRequest

type AppendActivityMessageRequest = activitylib.AppendMessageRequest

type ApplicationImagesService

type ApplicationImagesService struct {
	// contains filtered or unexported fields
}

func NewApplicationImagesService

func NewApplicationImagesService(embeddedFS embed.FS, settingsService *SettingsService) *ApplicationImagesService

func (*ApplicationImagesService) GetImageWithColor

func (s *ApplicationImagesService) GetImageWithColor(name string, colorOverride string) ([]byte, string, error)

type Argon2Params

type Argon2Params struct {
	// contains filtered or unexported fields
}

func DefaultArgon2Params

func DefaultArgon2Params() *Argon2Params

type AuthService

type AuthService struct {
	// contains filtered or unexported fields
}

func NewAuthService

func NewAuthService(userService *UserService, settingsService *SettingsService, eventService *EventService, sessionService *SessionService, roleService *RoleService, jwtSecret string, cfg *config.Config) *AuthService

func (*AuthService) ChangePassword

func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword, currentSessionID string) error

func (*AuthService) GetOidcConfig

func (s *AuthService) GetOidcConfig(ctx context.Context) (*models.OidcConfig, error)

func (*AuthService) GetOidcConfigurationStatus

func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*auth.OidcStatusInfo, error)

func (*AuthService) GetSessionTimeout

func (s *AuthService) GetSessionTimeout(ctx context.Context) (int, error)

func (*AuthService) InvalidateUserTokenCache

func (s *AuthService) InvalidateUserTokenCache(userID string)

InvalidateUserTokenCache purges all cached token verifications for a user. Call this after admin-initiated role changes, account disable, or user deletion so stale verifications cannot grant access for the cache TTL.

func (*AuthService) IsLocalAuthEnabled

func (s *AuthService) IsLocalAuthEnabled(ctx context.Context) (bool, error)

func (*AuthService) IsOidcEnabled

func (s *AuthService) IsOidcEnabled(ctx context.Context) (bool, error)

func (*AuthService) IssueFederatedToken

func (s *AuthService) IssueFederatedToken(ctx context.Context, user *models.User, credentialID string, ttlSeconds int) (*TokenPair, error)

func (*AuthService) LogLogout

func (s *AuthService) LogLogout(ctx context.Context, user *models.User)

func (*AuthService) Login

func (s *AuthService) Login(ctx context.Context, username, password string, meta auth.SessionMeta) (*models.User, *TokenPair, error)

func (*AuthService) LogoutAllOtherSessions

func (s *AuthService) LogoutAllOtherSessions(ctx context.Context, userID, currentSessionID string) error

LogoutAllOtherSessions revokes every active session for userID except currentSessionID, so the caller stays signed in on their current device.

func (*AuthService) OidcLogin

func (s *AuthService) OidcLogin(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse, meta auth.SessionMeta) (*models.User, *TokenPair, error)

func (*AuthService) RefreshToken

func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, meta auth.SessionMeta) (*TokenPair, error)

func (*AuthService) RevokeSession

func (s *AuthService) RevokeSession(ctx context.Context, sessionID string) error

func (*AuthService) VerifyToken

func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*models.User, string, error)

type AuthSettings

type AuthSettings struct {
	LocalAuthEnabled bool               `json:"localAuthEnabled"`
	OidcEnabled      bool               `json:"oidcEnabled"`
	SessionTimeout   int                `json:"sessionTimeout"`
	Oidc             *models.OidcConfig `json:"oidc,omitempty"`
}

type BuildService

type BuildService struct {
	// contains filtered or unexported fields
}

func NewBuildService

func NewBuildService(
	db *database.DB,
	settings *SettingsService,
	dockerService *DockerClientService,
	registryService *ContainerRegistryService,
	gitRepository *GitRepositoryService,
	eventService *EventService,
) *BuildService

func (*BuildService) BuildImage

func (s *BuildService) BuildImage(ctx context.Context, environmentID string, req imagetypes.BuildRequest, progressWriter io.Writer, serviceName string, user *models.User) (*imagetypes.BuildResult, error)

func (*BuildService) BuildSettings

func (s *BuildService) BuildSettings() buildtypes.BuildSettings

func (*BuildService) GetAllRegistryAuthConfigs

func (s *BuildService) GetAllRegistryAuthConfigs(ctx context.Context) (map[string]dockerregistry.AuthConfig, error)

func (*BuildService) GetImageBuildByID

func (s *BuildService) GetImageBuildByID(ctx context.Context, environmentID, buildID string) (*imagetypes.BuildRecord, error)

func (*BuildService) GetRegistryAuthForHost

func (s *BuildService) GetRegistryAuthForHost(ctx context.Context, registryHost string) (string, error)

func (*BuildService) GetRegistryAuthForImage

func (s *BuildService) GetRegistryAuthForImage(ctx context.Context, imageRef string) (string, error)

func (*BuildService) ListImageBuildsByEnvironmentPaginated

func (s *BuildService) ListImageBuildsByEnvironmentPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]imagetypes.BuildRecord, pagination.Response, error)

type BuildWorkspaceService

type BuildWorkspaceService struct {
	// contains filtered or unexported fields
}

BuildWorkspaceService provides file operations for the manual build workspace.

func NewBuildWorkspaceService

func NewBuildWorkspaceService(settings *SettingsService) *BuildWorkspaceService

func (*BuildWorkspaceService) CreateDirectory

func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath string) error

func (*BuildWorkspaceService) DeleteFile

func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string) error

func (*BuildWorkspaceService) DownloadFile

func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath string) (io.ReadCloser, int64, error)

func (*BuildWorkspaceService) GetFileContent

func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath string, maxBytes int64) ([]byte, string, error)

func (*BuildWorkspaceService) ListDirectory

func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath string) ([]volumetypes.FileEntry, error)

func (*BuildWorkspaceService) UploadFile

func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string, content io.Reader, filename string) error

type ContainerListResult

type ContainerListResult struct {
	Items      []containertypes.Summary
	Groups     []containertypes.SummaryGroup
	Pagination pagination.Response
	Counts     containertypes.StatusCounts
}

type ContainerRegistryService

type ContainerRegistryService struct {
	// contains filtered or unexported fields
}

func NewContainerRegistryService

func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetter, kvService *KVService) *ContainerRegistryService

NewContainerRegistryService creates a registry service. kvService may be nil in tests that do not need pull tracking or rate-limit caching.

func (*ContainerRegistryService) CreateRegistry

func (*ContainerRegistryService) DeleteRegistry

func (s *ContainerRegistryService) DeleteRegistry(ctx context.Context, id string) error

func (*ContainerRegistryService) GetAllRegistries

func (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]models.ContainerRegistry, error)

func (*ContainerRegistryService) GetAllRegistryAuthConfigs

func (s *ContainerRegistryService) GetAllRegistryAuthConfigs(ctx context.Context) (map[string]dockerregistry.AuthConfig, error)

func (*ContainerRegistryService) GetDecryptedToken

func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id string) (string, error)

GetDecryptedToken returns the decrypted token for a registry

func (*ContainerRegistryService) GetEnabledRegistries

func (s *ContainerRegistryService) GetEnabledRegistries(ctx context.Context) ([]models.ContainerRegistry, error)

GetEnabledRegistries returns all enabled registries

func (*ContainerRegistryService) GetImageDigest

func (s *ContainerRegistryService) GetImageDigest(ctx context.Context, imageRef string) (string, error)

GetImageDigest fetches the current digest for an image:tag from the registry This is used for digest-based update detection for non-semver tags

func (*ContainerRegistryService) GetOrRefreshECRToken

func (s *ContainerRegistryService) GetOrRefreshECRToken(ctx context.Context, reg *models.ContainerRegistry) (username, password string, err error)

GetOrRefreshECRToken returns a valid ECR auth token (username + password) for the given registry. If the cached token (stored encrypted in the DB) is still within its 12-hour 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 (*ContainerRegistryService) GetRegistriesPaginated

func (*ContainerRegistryService) GetRegistryAuthForHost

func (s *ContainerRegistryService) GetRegistryAuthForHost(ctx context.Context, registryHost string) (string, error)

GetRegistryAuthForHost returns X-Registry-Auth for a configured and enabled registry.

func (*ContainerRegistryService) GetRegistryAuthForImage

func (s *ContainerRegistryService) GetRegistryAuthForImage(ctx context.Context, imageRef string) (string, error)

GetRegistryAuthForImage returns X-Registry-Auth for the image's registry host.

func (*ContainerRegistryService) GetRegistryByID

func (*ContainerRegistryService) GetRegistryPullUsage

GetRegistryPullUsage returns pull usage visibility for configured registries.

func (*ContainerRegistryService) RecordImagePull

func (s *ContainerRegistryService) RecordImagePull(ctx context.Context, imageRef string) error

RecordImagePull increments Arcane's observed successful pull counter for an image registry.

func (*ContainerRegistryService) SyncRegistries

func (s *ContainerRegistryService) SyncRegistries(ctx context.Context, syncItems []containerregistry.Sync) error

SyncRegistries syncs registries from a manager to this agent instance It creates, updates, or deletes registries to match the provided list

func (*ContainerRegistryService) TestECRRegistry

func (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *models.ContainerRegistry) error

TestECRRegistry tests connectivity for an ECR registry by generating an auth token and attempting a Docker login.

func (*ContainerRegistryService) TestRegistry

func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURL, username, token string) error

func (*ContainerRegistryService) UpdateRegistry

type ContainerService

type ContainerService struct {
	// contains filtered or unexported fields
}

func NewContainerService

func NewContainerService(ctx context.Context, db *database.DB, eventService *EventService, dockerService *DockerClientService, imageService *ImageService, settingsService *SettingsService, projectService *ProjectService) *ContainerService

func (*ContainerService) AttachExec

func (s *ContainerService) AttachExec(ctx context.Context, containerID, execID string) (*ExecSession, error)

AttachExec attaches to an exec instance and returns an ExecSession for lifecycle management.

func (*ContainerService) CreateContainer

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 (*ContainerService) CreateExec

func (s *ContainerService) CreateExec(ctx context.Context, containerID string, cmd []string) (string, error)

CreateExec creates an exec instance in the container

func (*ContainerService) DeleteContainer

func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force bool, removeVolumes bool, user models.User) error

func (*ContainerService) GetContainerByID

func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*container.InspectResponse, error)

func (*ContainerService) GetContainerByReference

func (s *ContainerService) GetContainerByReference(ctx context.Context, ref string) (*container.InspectResponse, error)

func (*ContainerService) GetContainerDetails

func (s *ContainerService) GetContainerDetails(ctx context.Context, id string) (containertypes.Details, error)

func (*ContainerService) GetContainerNameByID

func (s *ContainerService) GetContainerNameByID(ctx context.Context, id string) (string, error)

GetContainerNameByID resolves a container's clean name from its Docker ID.

func (*ContainerService) GetContainerNameByReference

func (s *ContainerService) GetContainerNameByReference(ctx context.Context, ref string) (string, error)

GetContainerNameByReference resolves a container's clean name from a Docker ID or name.

func (*ContainerService) ListContainersPaginated

func (s *ContainerService) ListContainersPaginated(
	ctx context.Context,
	params pagination.QueryParams,
	includeAll bool,
	includeInternal bool,
	groupBy string,
) (ContainerListResult, error)

func (*ContainerService) RedeployContainer

func (s *ContainerService) RedeployContainer(ctx context.Context, containerID string, user models.User) (string, error)

func (*ContainerService) RestartContainer

func (s *ContainerService) RestartContainer(ctx context.Context, containerID string, user models.User) error

func (*ContainerService) StartContainer

func (s *ContainerService) StartContainer(ctx context.Context, containerID string, user models.User) error

func (*ContainerService) StopContainer

func (s *ContainerService) StopContainer(ctx context.Context, containerID string, user models.User) error

func (*ContainerService) StreamLogs

func (s *ContainerService) StreamLogs(ctx context.Context, containerID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error

func (*ContainerService) StreamStats

func (s *ContainerService) StreamStats(ctx context.Context, containerID string, statsChan chan<- any) error

type CreateEventRequest

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"`
}

type CustomizeSearchService

type CustomizeSearchService struct {
	// contains filtered or unexported fields
}

func NewCustomizeSearchService

func NewCustomizeSearchService() *CustomizeSearchService

func (*CustomizeSearchService) GetCustomizeCategories

func (s *CustomizeSearchService) GetCustomizeCategories() []category.Category

GetCustomizeCategories returns all available customization categories with their metadata

func (*CustomizeSearchService) Search

func (s *CustomizeSearchService) Search(query string) search.Response

Search performs a relevance-scored search across all customization categories and items

type DashboardActionItemsOptions

type DashboardActionItemsOptions struct {
	DebugAllGood bool
}

type DashboardService

type DashboardService struct {
	// contains filtered or unexported fields
}

func NewDashboardService

func NewDashboardService(
	db *database.DB,
	dockerService *DockerClientService,
	containerService *ContainerService,
	projectService *ProjectService,
	imageService *ImageService,
	settingsService *SettingsService,
	vulnerabilityService *VulnerabilityService,
	environmentService *EnvironmentService,
	versionService *VersionService,
) *DashboardService

func (*DashboardService) GetSnapshot

type DeploymentSnippetFile

type DeploymentSnippetFile struct {
	Name          string
	Content       string
	ContainerPath string
	Permissions   string
}

type DeploymentSnippetMTLS

type DeploymentSnippetMTLS struct {
	DockerRun     string
	DockerCompose string
	Files         []DeploymentSnippetFile
	HostDirHint   string
}

type DeploymentSnippets

type DeploymentSnippets struct {
	DockerRun     string
	DockerCompose string
	MTLS          *DeploymentSnippetMTLS
}

DeploymentSnippets contains deployment configuration snippets for an environment.

type DiagnosticsService

type DiagnosticsService struct {
	// contains filtered or unexported fields
}

DiagnosticsService gathers Go runtime, memory, and garbage-collector statistics for the diagnostics endpoints. It holds no external dependencies; WebSocket metrics and worker-goroutine counts are merged in at the handler layer to avoid an import cycle with the api/ws package.

func NewDiagnosticsService

func NewDiagnosticsService() *DiagnosticsService

NewDiagnosticsService returns a DiagnosticsService. startedAt is captured at construction (≈ process start) and used to report uptime.

func (*DiagnosticsService) Collect

Collect samples the current runtime, memory, and GC state.

type DockerClientService

type DockerClientService struct {
	// contains filtered or unexported fields
}

func NewDockerClientService

func NewDockerClientService(ctx context.Context, db *database.DB, cfg *config.Config, settingsService *SettingsService) *DockerClientService

func (*DockerClientService) Close

func (s *DockerClientService) Close()

Close stops Docker event subscriptions owned by this service and closes the cached Docker client.

func (*DockerClientService) DockerHost

func (s *DockerClientService) DockerHost() string

DockerHost returns the configured DOCKER_HOST value.

func (*DockerClientService) EventBus

func (*DockerClientService) GetAllContainers

func (s *DockerClientService) GetAllContainers(ctx context.Context) ([]container.Summary, int, int, int, error)

func (*DockerClientService) GetAllImages

func (s *DockerClientService) GetAllImages(ctx context.Context) ([]image.Summary, int, int, int, error)

func (*DockerClientService) GetAllNetworks

func (s *DockerClientService) GetAllNetworks(ctx context.Context) ([]network.Summary, int, int, int, error)

func (*DockerClientService) GetAllVolumes

func (s *DockerClientService) GetAllVolumes(ctx context.Context) ([]*volume.Volume, int, int, int, error)

func (*DockerClientService) GetClient

func (s *DockerClientService) GetClient(ctx context.Context) (*client.Client, error)

GetClient returns a singleton Docker client instance. It initializes the client on the first call.

func (*DockerClientService) GetSnapshot

func (*DockerClientService) RefreshClient

func (s *DockerClientService) RefreshClient(ctx context.Context) error

RefreshClient probes the Docker daemon and recreates the cached client when the daemon's effective API version changed.

func (*DockerClientService) WatchEvents

func (s *DockerClientService) WatchEvents(ctx context.Context)

type DynamicScheduler

type DynamicScheduler interface {
	AddJob(ctx context.Context, job schedulertypes.Job) error
	RemoveJob(ctx context.Context, name string)
	HasJob(name string) bool
}

DynamicScheduler is the subset of the job scheduler used by services that register per-entity jobs at runtime (GitOps syncs, environment health). It is a consumer-side interface satisfied by *pkg/scheduler.JobScheduler; the scheduler is injected post-construction via SetScheduler because it is created after the service graph is built (and pkg/scheduler imports this package, so it cannot be a wire input here).

type EnvironmentService

type EnvironmentService struct {
	// contains filtered or unexported fields
}

func NewEnvironmentService

func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService, apiKeyService *ApiKeyService) *EnvironmentService

func (*EnvironmentService) CreateEnvironment

func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *models.Environment, userID, username *string) (*models.Environment, error)

func (*EnvironmentService) DeleteEnvironment

func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, userID, username *string) error

func (*EnvironmentService) EnsureLocalEnvironment

func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl string) error

func (*EnvironmentService) EnsureSwarmNodeAgentEnvironment

func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(
	ctx context.Context,
	parentEnvironmentID, nodeID, hostname, userID, username string,
	rotate bool,
) (*models.Environment, string, error)

func (*EnvironmentService) ExecuteRemoteRequest

func (s *EnvironmentService) ExecuteRemoteRequest(ctx context.Context, envID string, method string, path string, body []byte) (*remenv.Response, error)

func (*EnvironmentService) GenerateDeploymentSnippets

func (s *EnvironmentService) GenerateDeploymentSnippets(ctx context.Context, envID string, envAddress string, apiKey string) (*DeploymentSnippets, error)

GenerateDeploymentSnippets generates Docker deployment snippets for an environment.

func (*EnvironmentService) GenerateEdgeDeploymentSnippets

func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context, envID string, managerURL string, apiKey string, edgeCfg *edge.Config) (*DeploymentSnippets, error)

GenerateEdgeDeploymentSnippets generates Docker deployment snippets for an edge agent. Edge agents connect outbound to the manager and don't require exposed ports.

func (*EnvironmentService) GetDB

func (s *EnvironmentService) GetDB() *database.DB

func (*EnvironmentService) GetEnabledRegistryCredentials

func (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context) ([]containerregistry.Credential, error)

func (*EnvironmentService) GetEnvironmentByID

func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string) (*models.Environment, error)

func (*EnvironmentService) ListEnvironmentsPaginated

func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams) ([]environment.Environment, pagination.Response, error)

func (*EnvironmentService) ListRemoteEnvironments

func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]models.Environment, error)

ListRemoteEnvironments returns all non-local, enabled environments for syncing purposes.

func (*EnvironmentService) ListSwarmNodeAgentEnvironments

func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context, parentEnvironmentID string) ([]models.Environment, error)

func (*EnvironmentService) ListVisibleEnvironments

func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]environment.Environment, error)

func (*EnvironmentService) ProxyJSONRequest

func (s *EnvironmentService) ProxyJSONRequest(ctx context.Context, envID string, method string, path string, body []byte, out any) error

func (*EnvironmentService) ProxyRequest

func (s *EnvironmentService) ProxyRequest(ctx context.Context, envID string, method string, path string, body []byte) ([]byte, int, error)

ProxyRequest sends a request to a remote environment's API.

func (*EnvironmentService) ReconcileEdgeStatusesOnStartup

func (s *EnvironmentService) ReconcileEdgeStatusesOnStartup(ctx context.Context) error

ReconcileEdgeStatusesOnStartup resets edge environments to offline when the manager starts. 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 (*EnvironmentService) RegenerateEnvironmentApiKey

func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID string, newApiKeyID string, encryptedKey string, userID, username string, envName string) error

func (*EnvironmentService) RegisterHealthJobsOnStartup

func (s *EnvironmentService) RegisterHealthJobsOnStartup(ctx context.Context)

RegisterHealthJobsOnStartup registers a health-check job for every enabled environment. Replaces the old global environment-health job.

func (*EnvironmentService) RescheduleHealthJobs

func (s *EnvironmentService) RescheduleHealthJobs(ctx context.Context)

RescheduleHealthJobs re-registers all enabled environments' health jobs, picking up a changed global interval. Wired from the Jobs UI via JobService.

func (*EnvironmentService) ResolveEdgeEnvironmentByToken

func (s *EnvironmentService) ResolveEdgeEnvironmentByToken(ctx context.Context, token string) (string, error)

func (*EnvironmentService) ResolveEnvironmentByAccessToken

func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error)

func (*EnvironmentService) RunHealthChecksNow

func (s *EnvironmentService) RunHealthChecksNow(ctx context.Context) error

RunHealthChecksNow runs every enabled environment's health check synchronously. Backs the "run now" button for the environment-health job in the Jobs UI.

func (*EnvironmentService) SetScheduler

func (s *EnvironmentService) SetScheduler(ctx context.Context, scheduler DynamicScheduler)

SetScheduler injects the job scheduler and app lifecycle context. Called during bootstrap on the manager only (agent mode leaves scheduler nil, so all health-job registration becomes a no-op).

func (*EnvironmentService) SyncRegistriesToEnvironment

func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, environmentID string) error

SyncRegistriesToEnvironment syncs all registries from this manager to a remote environment

func (*EnvironmentService) SyncRegistriesToRemoteEnvironments

func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Context) error

SyncRegistriesToRemoteEnvironments syncs container registries to all eligible remote environments. Eligibility requires a non-local, enabled environment with a configured access token.

func (*EnvironmentService) SyncRepositoriesToEnvironment

func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context, environmentID string) error

SyncRepositoriesToEnvironment syncs all git repositories from this manager to a remote environment

func (*EnvironmentService) TestConnection

func (s *EnvironmentService) TestConnection(ctx context.Context, id string, customApiUrl *string) (string, error)

func (*EnvironmentService) UpdateEnvironment

func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]any, userID, username *string) (*models.Environment, error)

func (*EnvironmentService) UpdateEnvironmentConnectionState

func (s *EnvironmentService) UpdateEnvironmentConnectionState(ctx context.Context, id string, connected bool) error

UpdateEnvironmentConnectionState updates runtime connectivity status without creating a generic "environment updated" event. This is used for edge tunnel connect/disconnect.

func (*EnvironmentService) UpdateEnvironmentHeartbeat

func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id string) error

func (*EnvironmentService) UpdateSwarmNodeIdentity

func (s *EnvironmentService) UpdateSwarmNodeIdentity(ctx context.Context, envID, swarmNodeID string) error

type EventService

type EventService struct {
	// contains filtered or unexported fields
}

func NewEventService

func NewEventService(db *database.DB, cfg *config.Config, httpClient *http.Client) *EventService

func (*EventService) CreateEvent

func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest) (*models.Event, error)

func (*EventService) DeleteEvent

func (s *EventService) DeleteEvent(ctx context.Context, eventID string) error

func (*EventService) DeleteOldEvents

func (s *EventService) DeleteOldEvents(ctx context.Context, olderThan time.Duration) error

func (*EventService) GetEventsByEnvironmentPaginated

func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]event.Event, pagination.Response, error)

func (*EventService) ListEventsPaginated

func (s *EventService) ListEventsPaginated(ctx context.Context, params pagination.QueryParams) ([]event.Event, pagination.Response, error)

func (*EventService) LogContainerEvent

func (s *EventService) LogContainerEvent(ctx context.Context, eventType models.EventType, containerID, containerName, userID, username, environmentID string, metadata models.JSON) error

func (*EventService) LogErrorEvent

func (s *EventService) LogErrorEvent(ctx context.Context, eventType models.EventType, resourceType, resourceID, resourceName, userID, username, environmentID string, err error, metadata models.JSON)

func (*EventService) LogImageEvent

func (s *EventService) LogImageEvent(ctx context.Context, eventType models.EventType, imageID, imageName, userID, username, environmentID string, metadata models.JSON) error

func (*EventService) LogNetworkEvent

func (s *EventService) LogNetworkEvent(ctx context.Context, eventType models.EventType, networkID, networkName, userID, username, environmentID string, metadata models.JSON) error

func (*EventService) LogProjectEvent

func (s *EventService) LogProjectEvent(ctx context.Context, eventType models.EventType, projectID, projectName, userID, username, environmentID string, metadata models.JSON) error

func (*EventService) LogUserEvent

func (s *EventService) LogUserEvent(ctx context.Context, eventType models.EventType, userID, username string, metadata models.JSON) error

func (*EventService) LogVolumeEvent

func (s *EventService) LogVolumeEvent(ctx context.Context, eventType models.EventType, volumeID, volumeName, userID, username, environmentID string, metadata models.JSON) error

type ExecSession

type ExecSession struct {
	// contains filtered or unexported fields
}

ExecSession manages the lifecycle of a Docker exec session.

func (*ExecSession) Close

func (e *ExecSession) Close(ctx context.Context) error

Close terminates the exec session and kills the process if still running.

func (*ExecSession) Stdin

func (e *ExecSession) Stdin() io.WriteCloser

func (*ExecSession) Stdout

func (e *ExecSession) Stdout() io.Reader

type FederatedCredentialService

type FederatedCredentialService struct {
	// contains filtered or unexported fields
}

func NewFederatedCredentialService

func NewFederatedCredentialService(
	db *database.DB,
	authService *AuthService,
	userService *UserService,
	settingsService *SettingsService,
	eventService *EventService,
	httpClient *http.Client,
) *FederatedCredentialService

func (*FederatedCredentialService) Create

func (*FederatedCredentialService) Delete

func (*FederatedCredentialService) Get

func (*FederatedCredentialService) List

func (*FederatedCredentialService) Update

func (*FederatedCredentialService) WithRoleService

func (s *FederatedCredentialService) WithRoleService(roleService *RoleService) *FederatedCredentialService

type GitOpsSyncService

type GitOpsSyncService struct {
	// contains filtered or unexported fields
}

func NewGitOpsSyncService

func NewGitOpsSyncService(db *database.DB, repoService *GitRepositoryService, projectService *ProjectService, swarmService *SwarmService, eventService *EventService, settingsService *SettingsService) *GitOpsSyncService

func (*GitOpsSyncService) BrowseFiles

func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id string, path string) (*gitops.BrowseResponse, error)

func (*GitOpsSyncService) CreateSync

func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string, req gitops.CreateSyncRequest, actor models.User) (*models.GitOpsSync, error)

func (*GitOpsSyncService) DeleteSync

func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id string, actor models.User) error

func (*GitOpsSyncService) GetSyncByID

func (s *GitOpsSyncService) GetSyncByID(ctx context.Context, environmentID, id string) (*models.GitOpsSync, error)

func (*GitOpsSyncService) GetSyncStatus

func (s *GitOpsSyncService) GetSyncStatus(ctx context.Context, environmentID, id string) (*gitops.SyncStatus, error)

func (*GitOpsSyncService) GetSyncsPaginated

func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]gitops.GitOpsSync, pagination.Response, gitops.SyncCounts, error)

func (*GitOpsSyncService) ImportSyncs

func (*GitOpsSyncService) PerformSync

func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id string, actor models.User) (*gitops.SyncResult, error)

func (*GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup

func (s *GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup(ctx context.Context) error

func (*GitOpsSyncService) RegisterAutoSyncJobsOnStartup

func (s *GitOpsSyncService) RegisterAutoSyncJobsOnStartup(ctx context.Context)

RegisterAutoSyncJobsOnStartup registers a dynamic job for every auto-sync-enabled sync and kicks an immediate run for any that are overdue. This replaces the old global polling job so existing syncs keep running after upgrade.

func (*GitOpsSyncService) SetScheduler

func (s *GitOpsSyncService) SetScheduler(ctx context.Context, scheduler DynamicScheduler)

SetScheduler injects the job scheduler and the app lifecycle context. It must be called during bootstrap (after the service graph is built) before any per-sync jobs are registered. The lifecycle context is used for background sync kicks so they outlive the request/bootstrap goroutine that triggered them.

func (*GitOpsSyncService) UpdateSync

func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id string, req gitops.UpdateSyncRequest, actor models.User) (*models.GitOpsSync, error)

type GitRepositoryService

type GitRepositoryService struct {
	// contains filtered or unexported fields
}

func NewGitRepositoryService

func NewGitRepositoryService(db *database.DB, workDir string, eventService *EventService, settingsService *SettingsService) *GitRepositoryService

func (*GitRepositoryService) BrowseFiles

func (s *GitRepositoryService) BrowseFiles(ctx context.Context, id, branch, path string) (*gitops.BrowseResponse, error)

func (*GitRepositoryService) CreateRepository

func (*GitRepositoryService) DeleteRepository

func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string, actor models.User) error

func (*GitRepositoryService) FindEnabledRepositoryByURL

func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, rawURL string) (*models.GitRepository, error)

func (*GitRepositoryService) GetAuthConfig

func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *models.GitRepository) (git.AuthConfig, error)

func (*GitRepositoryService) GetRepositoriesPaginated

func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, params pagination.QueryParams) ([]gitops.GitRepository, pagination.Response, error)

func (*GitRepositoryService) GetRepositoryByID

func (s *GitRepositoryService) GetRepositoryByID(ctx context.Context, id string) (*models.GitRepository, error)

func (*GitRepositoryService) GetRepositoryByName

func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name string) (*models.GitRepository, error)

func (*GitRepositoryService) ListBranches

func (s *GitRepositoryService) ListBranches(ctx context.Context, id string) ([]gitops.BranchInfo, error)

func (*GitRepositoryService) SyncRepositories

func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems []gitops.RepositorySync) error

SyncRepositories syncs repositories from a manager to this agent instance. It creates, updates, or deletes repositories to match the provided list.

func (*GitRepositoryService) TestConnection

func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, branch string, actor models.User) error

func (*GitRepositoryService) UpdateRepository

type ImageParts

type ImageParts struct {
	Registry   string
	Repository string
	Tag        string
}

type ImageService

type ImageService struct {
	// contains filtered or unexported fields
}

func NewImageService

func NewImageService(db *database.DB, dockerService *DockerClientService, registryService *ContainerRegistryService, imageUpdateService *ImageUpdateService, vulnerabilityService *VulnerabilityService, eventService *EventService) *ImageService

func (*ImageService) BuildProjectIDMap

func (s *ImageService) BuildProjectIDMap(ctx context.Context, containers []container.Summary) map[string]string

BuildProjectIDMap returns a map of compose project name → project ID for any containers that carry the com.docker.compose.project label. The lookup uses a short-TTL cache shared across all callers of this ImageService instance.

func (*ImageService) GetImageDetail

func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypes.DetailSummary, error)

GetImageDetail returns a DetailSummary for the given image ID. It fetches ImageInspect and ImageList concurrently so the size field reflects the same metric shown in the image table (docker image ls / docker system df).

func (*ImageService) GetTotalImageSize

func (s *ImageService) GetTotalImageSize(ctx context.Context) (int64, error)

func (*ImageService) GetUpdateInfoByImageIDs

func (s *ImageService) GetUpdateInfoByImageIDs(ctx context.Context, imageIDs []string) (map[string]*imagetypes.UpdateInfo, error)

GetUpdateInfoByImageIDs returns a map of image ID to UpdateInfo for the given image IDs. This is used by the container service to populate update info for containers.

func (*ImageService) GetUpdateInfoByImageRefs

func (s *ImageService) GetUpdateInfoByImageRefs(ctx context.Context, imageRefs []string) (map[string]*imagetypes.UpdateInfo, error)

GetUpdateInfoByImageRefs returns persisted update information keyed by the original image reference string.

func (*ImageService) ImageExistsLocally

func (s *ImageService) ImageExistsLocally(ctx context.Context, imageName string) (bool, error)

func (*ImageService) ListImagesPaginated

func (s *ImageService) ListImagesPaginated(ctx context.Context, params pagination.QueryParams) ([]imagetypes.Summary, pagination.Response, error)

func (*ImageService) LoadImageFromReader

func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Reader, fileName string, user models.User, maxSizeBytes int64) (*imagetypes.LoadResult, error)

func (*ImageService) PruneImages

func (*ImageService) PullImage

func (s *ImageService) PullImage(ctx context.Context, imageName string, progressWriter io.Writer, user models.User, externalCreds []containerregistry.Credential) error

func (*ImageService) ReconcilePulledImageUpdate

func (s *ImageService) ReconcilePulledImageUpdate(ctx context.Context, imageName string) error

func (*ImageService) RemoveImage

func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, user models.User) error

type ImageUpdateService

type ImageUpdateService struct {
	// contains filtered or unexported fields
}

func NewImageUpdateService

func NewImageUpdateService(db *database.DB, settingsService *SettingsService, registryService *ContainerRegistryService, dockerService *DockerClientService, eventService *EventService, notificationService *NotificationService, activityService *ActivityService) *ImageUpdateService

func (*ImageUpdateService) CheckAllImages

func (s *ImageUpdateService) CheckAllImages(ctx context.Context, limit int, externalCreds []containerregistry.Credential) (map[string]*imageupdate.Response, error)

func (*ImageUpdateService) CheckImageUpdate

func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef string) (*imageupdate.Response, error)

func (*ImageUpdateService) CheckImageUpdateByID

func (s *ImageUpdateService) CheckImageUpdateByID(ctx context.Context, imageID string) (*imageupdate.Response, error)

func (*ImageUpdateService) CheckMultipleImages

func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs []string, externalCreds []containerregistry.Credential) (map[string]*imageupdate.Response, error)

func (*ImageUpdateService) CleanupOrphanedRecords

func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error

func (*ImageUpdateService) GetUnnotifiedUpdates

func (s *ImageUpdateService) GetUnnotifiedUpdates(ctx context.Context) (map[string]*models.ImageUpdateRecord, error)

GetUnnotifiedUpdates returns a map of image IDs that have updates but haven't been notified yet

func (*ImageUpdateService) GetUpdateSummary

func (s *ImageUpdateService) GetUpdateSummary(ctx context.Context) (*imageupdate.Summary, error)

func (*ImageUpdateService) MarkImageRefUpToDateAfterPull

func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context, imageRef string) error

func (*ImageUpdateService) MarkUpdatesAsNotified

func (s *ImageUpdateService) MarkUpdatesAsNotified(ctx context.Context, imageIDs []string) error

MarkUpdatesAsNotified marks the given image IDs as having been notified

type JobRunner

type JobRunner interface {
	GetJob(jobID string) (schedulertypes.Job, bool)
	RescheduleJob(ctx context.Context, job schedulertypes.Job) error
}

type JobService

type JobService struct {

	// environment-health is no longer a single scheduler job — it fans out to one
	// dynamic job per environment owned by EnvironmentService. These bridge the Jobs
	// UI (which addresses jobs by ID) back to that service. Set during bootstrap on
	// the manager only.
	OnEnvironmentHealthReschedule func(ctx context.Context)
	RunEnvironmentHealthNow       func(ctx context.Context) error
	// contains filtered or unexported fields
}

JobService manages configuration for background job schedules.

Intervals are persisted in the existing settings table as individual keys. After updates, the SettingsService cache is reloaded and active jobs are rescheduled through the configured scheduler.

NOTE: This is intentionally separate from SettingsService to keep the API surface job-focused and to centralize schedule validation/rescheduling.

func NewJobService

func NewJobService(db *database.DB, settings *SettingsService, cfg *config.Config) *JobService

func (*JobService) GetJobSchedules

func (s *JobService) GetJobSchedules(ctx context.Context) jobschedule.Config

func (*JobService) ListJobs

func (*JobService) RescheduleJobsForSettingKeys

func (s *JobService) RescheduleJobsForSettingKeys(ctx context.Context, changedKeys []string)

func (*JobService) RunJobNowInline

func (s *JobService) RunJobNowInline(ctx context.Context, jobID string) error

func (*JobService) SetScheduler

func (s *JobService) SetScheduler(ctx context.Context, scheduler JobRunner)

func (*JobService) UpdateJobSchedules

func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedule.Update) (jobschedule.Config, error)

type KVService

type KVService struct {
	// contains filtered or unexported fields
}

KVService persists lightweight application state in the kv table.

func NewKVService

func NewKVService(db *database.DB) *KVService

func (*KVService) Get

func (s *KVService) Get(ctx context.Context, key string) (string, bool, error)

func (*KVService) GetBool

func (s *KVService) GetBool(ctx context.Context, key string, defaultValue bool) (bool, error)

func (*KVService) GetInt64

func (s *KVService) GetInt64(ctx context.Context, key string, defaultValue int64) (int64, error)

func (*KVService) IncrementInt64

func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64) (int64, error)

func (*KVService) Set

func (s *KVService) Set(ctx context.Context, key, value string) error

func (*KVService) SetBool

func (s *KVService) SetBool(ctx context.Context, key string, value bool) error

type NetworkService

type NetworkService struct {
	// contains filtered or unexported fields
}

func NewNetworkService

func NewNetworkService(db *database.DB, dockerService *DockerClientService, eventService *EventService) *NetworkService

func (*NetworkService) CreateNetwork

func (s *NetworkService) CreateNetwork(ctx context.Context, name string, options client.NetworkCreateOptions, user models.User) (*network.CreateResponse, error)

func (*NetworkService) GetNetworkByID

func (s *NetworkService) GetNetworkByID(ctx context.Context, id string) (*network.Inspect, error)

func (*NetworkService) GetNetworkTopology

func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.Topology, error)

func (*NetworkService) PruneNetworks

func (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneReport, error)

func (*NetworkService) RemoveNetwork

func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user models.User) error

type NotificationService

type NotificationService struct {
	// contains filtered or unexported fields
}

func NewNotificationService

func NewNotificationService(db *database.DB, cfg *config.Config, environmentSvc *EnvironmentService) *NotificationService

func (*NotificationService) CreateOrUpdateSettings

func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider models.NotificationProvider, enabled bool, config models.JSON) (*models.NotificationSettings, error)

func (*NotificationService) DeleteSettings

func (s *NotificationService) DeleteSettings(ctx context.Context, provider models.NotificationProvider) error

func (*NotificationService) DispatchNotification

func (s *NotificationService) DispatchNotification(ctx context.Context, accessToken string, payload notificationdto.DispatchRequest) error

func (*NotificationService) GetAllSettings

func (*NotificationService) GetSettingsByProvider

func (s *NotificationService) GetSettingsByProvider(ctx context.Context, provider models.NotificationProvider) (*models.NotificationSettings, error)

func (*NotificationService) ResolveNotificationTarget

func (s *NotificationService) ResolveNotificationTarget(ctx context.Context, environmentID string) (NotificationTarget, error)

func (*NotificationService) SendAutoHealNotification

func (s *NotificationService) SendAutoHealNotification(ctx context.Context, containerName, containerID string) error

SendAutoHealNotification sends a notification when a container is auto-healed.

func (*NotificationService) SendBatchImageUpdateNotification

func (s *NotificationService) SendBatchImageUpdateNotification(ctx context.Context, updates map[string]*imageupdate.Response) error

func (*NotificationService) SendContainerUpdateNotification

func (s *NotificationService) SendContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string) error

func (*NotificationService) SendImageUpdateNotification

func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) error

func (*NotificationService) SendPruneReportNotification

func (s *NotificationService) SendPruneReportNotification(ctx context.Context, result *system.PruneAllResult) error

func (*NotificationService) SendVulnerabilityNotification

func (s *NotificationService) SendVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload) error

SendVulnerabilityNotification notifies all enabled providers that have vulnerability_found event enabled. Only daily summary payloads are sent; legacy per-CVE payloads are ignored.

func (*NotificationService) TestNotification

func (s *NotificationService) TestNotification(ctx context.Context, environmentID string, provider models.NotificationProvider, testType string) error

type NotificationTarget

type NotificationTarget struct {
	EnvironmentID   string
	EnvironmentName string
}

type OidcService

type OidcService struct {
	// contains filtered or unexported fields
}

func NewOidcService

func NewOidcService(authService *AuthService, settingsService *SettingsService, cfg *config.Config, httpClient *http.Client) *OidcService

func (*OidcService) ExchangeDeviceToken

func (s *OidcService) ExchangeDeviceToken(ctx context.Context, deviceCode string) (*auth.OidcUserInfo, *auth.OidcTokenResponse, error)

ExchangeDeviceToken exchanges a device code for tokens.

func (*OidcService) GenerateAuthURL

func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, origin string, mobileRedirectURI string) (string, string, error)

func (*OidcService) GetMobileRedirectAllowlist

func (s *OidcService) GetMobileRedirectAllowlist(ctx context.Context) []string

GetMobileRedirectAllowlist returns the configured list of acceptable mobile OAuth redirect URIs.

func (*OidcService) GetOidcRedirectURL

func (s *OidcService) GetOidcRedirectURL(origin string) string

func (*OidcService) HandleCallback

func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedState, origin, mobileRedirectURI string) (*auth.OidcUserInfo, *auth.OidcTokenResponse, error)

func (*OidcService) InitiateDeviceAuth

func (s *OidcService) InitiateDeviceAuth(ctx context.Context) (*auth.OidcDeviceAuthResponse, error)

InitiateDeviceAuth initiates the OIDC device authorization flow.

func (*OidcService) ValidateMobileRedirectURI

func (s *OidcService) ValidateMobileRedirectURI(ctx context.Context, uri string) error

ValidateMobileRedirectURI returns nil if uri exactly matches one of the configured mobile redirect URIs. Full-string match is required — partial matches on scheme or host could be abused for open-redirect attacks.

type OidcState

type OidcState struct {
	State        string    `json:"state"`
	Nonce        string    `json:"nonce"`
	CodeVerifier string    `json:"code_verifier"`
	RedirectTo   string    `json:"redirect_to"`
	CreatedAt    time.Time `json:"created_at"`
}

type PortService

type PortService struct {
	// contains filtered or unexported fields
}

func NewPortService

func NewPortService(dockerService *DockerClientService) *PortService

func (*PortService) ListPortsPaginated

type ProjectBuildOptions

type ProjectBuildOptions struct {
	Services []string
	Provider string
	Push     *bool
	Load     *bool
}

type ProjectService

type ProjectService struct {
	// contains filtered or unexported fields
}

func NewProjectService

func NewProjectService(db *database.DB, settingsService *SettingsService, eventService *EventService, imageService *ImageService, dockerService *DockerClientService, buildService *BuildService, cfg *config.Config) *ProjectService

func (*ProjectService) ApplyGitSyncProjectFiles

func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID string, composeContent string, gitEnvContent *string, user models.User) (*models.Project, error)

func (*ProjectService) ArchiveProject

func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, user models.User) error

func (*ProjectService) BackfillProjectImageRefs

func (s *ProjectService) BackfillProjectImageRefs(ctx context.Context)

func (*ProjectService) BuildProjectServices

func (s *ProjectService) BuildProjectServices(ctx context.Context, projectID string, options ProjectBuildOptions, progressWriter io.Writer, user *models.User) error

func (*ProjectService) CreateProject

func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, user models.User) (*models.Project, error)

func (*ProjectService) DeployProject

func (s *ProjectService) DeployProject(ctx context.Context, projectID string, user models.User, options *project.DeployOptions) error

func (*ProjectService) DestroyProject

func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, removeFiles, removeVolumes bool, user models.User) error

func (*ProjectService) DownProject

func (s *ProjectService) DownProject(ctx context.Context, projectID string, user models.User) error

func (*ProjectService) EnsureProjectImagesPresent

func (s *ProjectService) EnsureProjectImagesPresent(ctx context.Context, projectID string, progressWriter io.Writer, user models.User, credentials []containerregistry.Credential) error

EnsureProjectImagesPresent checks all compose service images for the project and pulls based on service pull policy: - 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 (*ProjectService) GetProjectByComposeName

func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name string) (*models.Project, error)

func (*ProjectService) GetProjectContent

func (s *ProjectService) GetProjectContent(ctx context.Context, projectID string) (composeContent, envContent string, err error)

func (*ProjectService) GetProjectDetails

func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string, opts project.DetailsOptions) (project.Details, error)

func (*ProjectService) GetProjectFileContent

func (s *ProjectService) GetProjectFileContent(ctx context.Context, projectID, relativePath string) (project.IncludeFile, error)

func (*ProjectService) GetProjectFromDatabaseByID

func (s *ProjectService) GetProjectFromDatabaseByID(ctx context.Context, id string) (*models.Project, error)

func (*ProjectService) GetProjectRelativePath

func (s *ProjectService) GetProjectRelativePath(ctx context.Context, projectPath string) string

func (*ProjectService) GetProjectServices

func (s *ProjectService) GetProjectServices(ctx context.Context, projectID string) ([]ProjectServiceInfo, error)

func (*ProjectService) GetProjectStatusCounts

func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCount, runningProjects, stoppedProjects, totalProjects, archivedProjects int, err error)

func (*ProjectService) HandleProjectFilesChanged

func (s *ProjectService) HandleProjectFilesChanged(ctx context.Context, paths []string)

func (*ProjectService) ListAllProjects

func (s *ProjectService) ListAllProjects(ctx context.Context) ([]models.Project, error)

func (*ProjectService) ListProjects

func (*ProjectService) PullProjectImages

func (s *ProjectService) PullProjectImages(ctx context.Context, projectID string, progressWriter io.Writer, user models.User, credentials []containerregistry.Credential) error

func (*ProjectService) RedeployProject

func (s *ProjectService) RedeployProject(ctx context.Context, projectID string, user models.User, options *project.DeployOptions) error

func (*ProjectService) RestartProject

func (s *ProjectService) RestartProject(ctx context.Context, projectID string, user models.User) error

func (*ProjectService) StreamProjectLogs

func (s *ProjectService) StreamProjectLogs(ctx context.Context, projectID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error

func (*ProjectService) SyncProjectsFromFileSystem

func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error

func (*ProjectService) UnarchiveProject

func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string, user models.User) error

func (*ProjectService) UpdateProject

func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent *string, user models.User) (*models.Project, error)

func (*ProjectService) UpdateProjectIncludeFile

func (s *ProjectService) UpdateProjectIncludeFile(ctx context.Context, projectID, relativePath, content string, user models.User) error

func (*ProjectService) UpdateProjectServices

func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID string, servicesToUpdate []string, user models.User) error

func (*ProjectService) WithRegistryCredentialsProvider

func (s *ProjectService) WithRegistryCredentialsProvider(provider func(context.Context) ([]containerregistry.Credential, error)) *ProjectService

type ProjectServiceInfo

type ProjectServiceInfo struct {
	Name             string                      `json:"name"`
	Image            string                      `json:"image"`
	Status           string                      `json:"status"`
	ContainerID      string                      `json:"container_id"`
	ContainerName    string                      `json:"container_name"`
	Ports            []string                    `json:"ports"`
	Health           *string                     `json:"health,omitempty"`
	IconLightURL     string                      `json:"icon_light_url,omitempty"`
	IconDarkURL      string                      `json:"icon_dark_url,omitempty"`
	ServiceConfig    *composetypes.ServiceConfig `json:"service_config,omitempty"`
	Labels           map[string]string           `json:"labels,omitempty"`
	RedeployDisabled bool                        `json:"redeploy_disabled,omitempty"`
}

type RegistryDaemonClient

type RegistryDaemonClient interface {
	RegistryLogin(ctx context.Context, options client.RegistryLoginOptions) (client.RegistryLoginResult, error)
	DistributionInspect(ctx context.Context, imageRef string, options client.DistributionInspectOptions) (client.DistributionInspectResult, error)
}

type RoleService

type RoleService struct {
	// contains filtered or unexported fields
}

RoleService owns role definitions, user role assignments, OIDC role mappings, and API key permissions. It resolves a caller's effective PermissionSet on demand and caches the result per-user / per-key for a short TTL to keep the hot path off the database.

func NewRoleService

func NewRoleService(db *database.DB) *RoleService

func (*RoleService) AssertGlobalAdminExists

func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error

AssertGlobalAdminExists returns a *common.NoGlobalAdminRemainsError if zero non-service users resolve to global administrator permissions. Called at boot after the backfill migration; also called from inside mutation paths.

func (*RoleService) BackfillApiKeyPermissions

func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error

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.

func (*RoleService) BackfillLegacyRoleAssignments

func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error

BackfillLegacyRoleAssignments migrates the pre-RBAC users.roles JSON column into rows in user_role_assignments. Safe to call on every boot: a no-op once the column is gone.

Users with "admin" in their legacy roles get a global Admin assignment; every other user gets a global Viewer assignment. The NULL environment_id lands the perms in PermissionSet.Global, which is what ps.Allows(perm, "") consults for org-level checks (list environments, read settings, list users, etc.) AND for env-scoped checks at the union step. Inserting per-environment viewer rows instead would lock non-admins out of the settings area entirely.

Lives here (not as a SQL migration) so the column-existence check is trivial in Go and the same code path covers both postgres and sqlite. Idempotent via ON CONFLICT DO NOTHING on the (user_id, role_id, env) unique index, so a half-finished prior run can be safely retried.

func (*RoleService) CountGlobalAdminsExcludingUser

func (s *RoleService) CountGlobalAdminsExcludingUser(ctx context.Context, excludedUserID string) (int, error)

CountGlobalAdminsExcludingUser returns the number of non-service users (other than excludedUserID) whose resolved global permissions satisfy IsGlobalAdmin. Used as the authoritative check for "removing this user / demoting this assignment would leave the system with no admin."

func (*RoleService) CountUsersAssignedToRole

func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID string) (int, error)

CountUsersAssignedToRole returns how many distinct users hold an assignment to the given role (any source, any environment scope).

func (*RoleService) CreateOidcMapping

func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error)

func (*RoleService) CreateRole

func (s *RoleService) CreateRole(ctx context.Context, name string, description *string, permissions []string) (*models.Role, error)

func (*RoleService) DeleteOidcMapping

func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error

func (*RoleService) DeleteRole

func (s *RoleService) DeleteRole(ctx context.Context, id string) error

func (*RoleService) EnsureBuiltInRoles

func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error

EnsureBuiltInRoles overwrites the permission set on every built-in role to match the Go constants. Idempotent. Called at boot after migrations succeed.

func (*RoleService) GetOidcMapping

func (s *RoleService) GetOidcMapping(ctx context.Context, id string) (*models.OidcRoleMapping, error)

func (*RoleService) GetRole

func (s *RoleService) GetRole(ctx context.Context, id string) (*models.Role, error)

func (*RoleService) InvalidateApiKey

func (s *RoleService) InvalidateApiKey(apiKeyID string)

InvalidateApiKey drops the cached PermissionSet for one API key.

func (*RoleService) InvalidateUser

func (s *RoleService) InvalidateUser(userID string)

InvalidateUser drops the cached PermissionSet for one user. Called from auth_service after a login that mutates assignments, and from any mutation path that doesn't already invalidate explicitly.

func (*RoleService) ListAllRoles

func (s *RoleService) ListAllRoles(ctx context.Context) ([]models.Role, error)

func (*RoleService) ListOidcMappings

func (s *RoleService) ListOidcMappings(ctx context.Context) ([]models.OidcRoleMapping, error)

func (*RoleService) ListRoles

func (*RoleService) ListUserAssignments

func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([]models.UserRoleAssignment, error)

func (*RoleService) ReconcileEnvOidcMappings

func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec string) error

ReconcileEnvOidcMappings replaces every source='env' row in oidc_role_mappings with the set declared by `rawSpec` (a JSON array of role.OidcRoleMappingSpec). Called once at boot. Behavior is declarative:

  • rawSpec empty / unset → leaves DB rows alone (purely UI-managed mode).
  • rawSpec is `[]` → wipes any previously-env-managed rows.
  • rawSpec is a valid JSON array → upserts each spec, deletes stale env rows.

Manual rows (source='manual') are never touched. Bad JSON or an unknown role ID returns an error so a misconfigured deployment fails loudly rather than silently dropping mappings.

func (*RoleService) ReplaceOidcAssignments

func (s *RoleService) ReplaceOidcAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error

ReplaceOidcAssignments replaces the user's source='oidc' assignments. Manual assignments are untouched. Enforces the global-admin guard after the swap.

func (*RoleService) ResolveApiKeyPermissions

func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID string) (*authz.PermissionSet, error)

ResolveApiKeyPermissions returns the PermissionSet for an API key. Caches per-key. Falls back to an empty set (deny-all) if the key has no perms.

func (*RoleService) ResolvePermissions

func (s *RoleService) ResolvePermissions(ctx context.Context, user *models.User) (*authz.PermissionSet, error)

ResolvePermissions returns the effective PermissionSet for a user, caching the result per-user for permissionCacheTTL.

func (*RoleService) SetApiKeyPermissions

func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string, grants []models.ApiKeyPermission) error

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 (*RoleService) SetUserAssignments

func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error

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 (*RoleService) UpdateOidcMapping

func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error)

func (*RoleService) UpdateRole

func (s *RoleService) UpdateRole(ctx context.Context, id, name string, description *string, permissions []string) (*models.Role, error)

func (*RoleService) ValidatePermissionsAgainstCaller

func (s *RoleService) ValidatePermissionsAgainstCaller(caller *authz.PermissionSet, desired []string) error

ValidatePermissionsAgainstCaller rejects any permission in `desired` that the caller does not hold at global scope. Sudo callers (agent / env access tokens, bootstrap paths) bypass entirely. Holding a permission only inside a specific environment is intentionally insufficient: roles are reusable templates that can later be assigned globally, so an env-scoped grant must not let the caller mint a global-capable role.

Unknown permission strings are rejected first with an UnknownPermissionError so a caller typo-ing a permission gets a descriptive 400 instead of a misleading 403 from the escalation guard below (which would always fire on an unknown perm because no PermissionSet contains it). This also gives the escalation loop a clean invariant: every perm reaching it is real.

Callers should run this before persisting role permissions to defend against privilege escalation if the role mutation endpoints are ever exposed beyond global admins.

func (*RoleService) ValidateRoleAssignmentAgainstCaller

func (s *RoleService) ValidateRoleAssignmentAgainstCaller(ctx context.Context, caller *authz.PermissionSet, roleID string, environmentID *string) error

ValidateRoleAssignmentAgainstCaller rejects assigning a role at the requested scope when the caller does not hold every permission in that role at that same scope.

type SessionService

type SessionService struct {
	// contains filtered or unexported fields
}

func NewSessionService

func NewSessionService(db *database.DB) *SessionService

func (*SessionService) CreateFederatedSession

func (s *SessionService) CreateFederatedSession(ctx context.Context, userID string, expiresAt time.Time, credentialID string) (*models.UserSession, error)

func (*SessionService) CreateSession

func (s *SessionService) CreateSession(ctx context.Context, userID string, expiresAt time.Time, meta auth.SessionMeta) (*models.UserSession, string, error)

func (*SessionService) DeleteExpiredSessions

func (s *SessionService) DeleteExpiredSessions(ctx context.Context, revokedRetention time.Duration) (int64, error)

func (*SessionService) GetSessionByID

func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (*models.UserSession, error)

func (*SessionService) RevokeAllUserSessionsExcept

func (s *SessionService) RevokeAllUserSessionsExcept(ctx context.Context, userID, exceptSessionID string) error

RevokeAllUserSessionsExcept revokes every active session for userID, leaving exceptSessionID active. Pass "" to revoke all sessions.

func (*SessionService) RevokeSession

func (s *SessionService) RevokeSession(ctx context.Context, sessionID string) error

func (*SessionService) RotateRefreshToken

func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID string, refreshJTI string, meta auth.SessionMeta) (*models.UserSession, string, error)

type SettingsSearchService

type SettingsSearchService struct {
	// contains filtered or unexported fields
}

func NewSettingsSearchService

func NewSettingsSearchService() *SettingsSearchService

func (*SettingsSearchService) GetSettingsCategories

func (s *SettingsSearchService) GetSettingsCategories() []category.Category

GetSettingsCategories returns all available settings categories with their metadata

func (*SettingsSearchService) Search

func (s *SettingsSearchService) Search(query string) search.Response

Search performs a relevance-scored search across settings categories and individual settings

type SettingsService

type SettingsService struct {
	OnImagePollingSettingsChanged      func(ctx context.Context)
	OnAutoUpdateSettingsChanged        func(ctx context.Context)
	OnProjectsDirectoryChanged         func(ctx context.Context)
	OnTemplatesDirectoryChanged        func(ctx context.Context)
	OnScheduledPruneSettingsChanged    func(ctx context.Context)
	OnVulnerabilityScanSettingsChanged func(ctx context.Context)
	OnAutoHealSettingsChanged          func(ctx context.Context)
	OnTimeoutSettingsChanged           func(ctx context.Context, timeoutSettings []libarcane.SettingUpdate)
	// contains filtered or unexported fields
}

func NewSettingsService

func NewSettingsService(ctx context.Context, db *database.DB) (*SettingsService, error)

func (*SettingsService) EnsureDefaultSettings

func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error

func (*SettingsService) EnsureEncryptionKey

func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, error)

func (*SettingsService) GetBoolSetting

func (s *SettingsService) GetBoolSetting(ctx context.Context, key string, defaultValue bool) bool

func (*SettingsService) GetIntSetting

func (s *SettingsService) GetIntSetting(ctx context.Context, key string, defaultValue int) int

func (*SettingsService) GetSettingType

func (s *SettingsService) GetSettingType(key string) string

GetSettingType returns the type from the setting metadata

func (*SettingsService) GetSettings

func (s *SettingsService) GetSettings(ctx context.Context) (*models.Settings, error)

func (*SettingsService) GetSettingsConfig

func (s *SettingsService) GetSettingsConfig() *models.Settings

func (*SettingsService) GetSettingsOrDefaults

func (s *SettingsService) GetSettingsOrDefaults(ctx context.Context) *models.Settings

GetSettingsOrDefaults is a convenience for hot paths that need a snapshot but cannot 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 (*SettingsService) GetStringSetting

func (s *SettingsService) GetStringSetting(ctx context.Context, key, defaultValue string) string

func (*SettingsService) ListSettings

func (s *SettingsService) ListSettings(visibility models.SettingVisibility) []models.SettingVariable

func (*SettingsService) LoadDatabaseSettings

func (s *SettingsService) LoadDatabaseSettings(ctx context.Context) (err error)

func (*SettingsService) NormalizeBuildsDirectory

func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error

func (*SettingsService) NormalizeProjectsDirectory

func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projectsDirEnv string) error

func (*SettingsService) PersistEnvSettingsIfMissing

func (s *SettingsService) PersistEnvSettingsIfMissing(ctx context.Context) error

func (*SettingsService) PruneUnknownSettings

func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error

func (*SettingsService) SetBoolSetting

func (s *SettingsService) SetBoolSetting(ctx context.Context, key string, value bool) error

func (*SettingsService) SetContainerAutoUpdateExclusionInternal

func (s *SettingsService) SetContainerAutoUpdateExclusionInternal(ctx context.Context, containerName string, excluded bool) error

SetContainerAutoUpdateExclusionInternal adds or removes a container name from the autoUpdateExcludedContainers setting. When excluded is true the container is added to the list; when false it is removed.

func (*SettingsService) SetIntSetting

func (s *SettingsService) SetIntSetting(ctx context.Context, key string, value int) error

func (*SettingsService) SetStringSetting

func (s *SettingsService) SetStringSetting(ctx context.Context, key, value string) error

func (*SettingsService) UpdateSetting

func (s *SettingsService) UpdateSetting(ctx context.Context, key, value string) error

func (*SettingsService) UpdateSettings

func (s *SettingsService) UpdateSettings(ctx context.Context, updates settings.Update) ([]models.SettingVariable, error)

type StartActivityRequest

type StartActivityRequest = activitylib.StartRequest

type SwarmNodeIdentity

type SwarmNodeIdentity struct {
	SwarmNodeID   string `json:"swarmNodeId"`
	Hostname      string `json:"hostname"`
	Role          string `json:"role"`
	EngineVersion string `json:"engineVersion"`
	SwarmActive   bool   `json:"swarmActive"`
}

type SwarmService

type SwarmService struct {
	// contains filtered or unexported fields
}

SwarmService provides Docker Swarm related operations.

func NewSwarmService

func NewSwarmService(
	dockerService *DockerClientService,
	settingsService *SettingsService,
	kvService *KVService,
	registryService *ContainerRegistryService,
	environmentService *EnvironmentService,
) *SwarmService

func (*SwarmService) CreateConfig

func (*SwarmService) CreateSecret

func (*SwarmService) DemoteNode

func (s *SwarmService) DemoteNode(ctx context.Context, nodeID string) error

func (*SwarmService) DeployStack

func (*SwarmService) GetConfig

func (s *SwarmService) GetConfig(ctx context.Context, configID string) (*swarmtypes.ConfigSummary, error)

func (*SwarmService) GetLocalNodeIdentity

func (s *SwarmService) GetLocalNodeIdentity(ctx context.Context) (*SwarmNodeIdentity, error)

func (*SwarmService) GetNode

func (s *SwarmService) GetNode(ctx context.Context, environmentID, nodeID string) (*swarmtypes.NodeSummary, error)

func (*SwarmService) GetSecret

func (s *SwarmService) GetSecret(ctx context.Context, secretID string) (*swarmtypes.SecretSummary, error)

func (*SwarmService) GetService

func (s *SwarmService) GetService(ctx context.Context, serviceID string) (*swarmtypes.ServiceInspect, error)

func (*SwarmService) GetStack

func (s *SwarmService) GetStack(ctx context.Context, environmentID, stackName string) (*swarmtypes.StackInspect, error)

func (*SwarmService) GetStackSource

func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackName string) (*swarmtypes.StackSource, error)

func (*SwarmService) GetSwarmInfo

func (s *SwarmService) GetSwarmInfo(ctx context.Context) (*swarmtypes.SwarmInfo, error)

func (*SwarmService) GetSwarmJoinTokens

func (s *SwarmService) GetSwarmJoinTokens(ctx context.Context) (*swarmtypes.SwarmJoinTokensResponse, error)

func (*SwarmService) GetSwarmUnlockKey

func (s *SwarmService) GetSwarmUnlockKey(ctx context.Context) (*swarmtypes.SwarmUnlockKeyResponse, error)

func (*SwarmService) InitSwarm

func (*SwarmService) IsEnabled

func (s *SwarmService) IsEnabled(ctx context.Context) (bool, error)

func (*SwarmService) JoinSwarm

func (*SwarmService) LeaveSwarm

func (*SwarmService) ListConfigs

func (s *SwarmService) ListConfigs(ctx context.Context) ([]swarmtypes.ConfigSummary, error)

func (*SwarmService) ListNodeTasksPaginated

func (s *SwarmService) ListNodeTasksPaginated(ctx context.Context, nodeID string, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error)

func (*SwarmService) ListNodesPaginated

func (s *SwarmService) ListNodesPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]swarmtypes.NodeSummary, pagination.Response, error)

func (*SwarmService) ListSecrets

func (s *SwarmService) ListSecrets(ctx context.Context) ([]swarmtypes.SecretSummary, error)

func (*SwarmService) ListServiceTasksPaginated

func (s *SwarmService) ListServiceTasksPaginated(ctx context.Context, serviceID string, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error)

func (*SwarmService) ListServicesPaginated

func (*SwarmService) ListStackServicesPaginated

func (s *SwarmService) ListStackServicesPaginated(ctx context.Context, stackName string, params pagination.QueryParams) ([]swarmtypes.ServiceSummary, pagination.Response, error)

func (*SwarmService) ListStackTasksPaginated

func (s *SwarmService) ListStackTasksPaginated(ctx context.Context, stackName string, params pagination.QueryParams) ([]swarmtypes.TaskSummary, pagination.Response, error)

func (*SwarmService) ListStacksPaginated

func (s *SwarmService) ListStacksPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]swarmtypes.StackSummary, pagination.Response, error)

func (*SwarmService) ListTasksPaginated

func (*SwarmService) PromoteNode

func (s *SwarmService) PromoteNode(ctx context.Context, nodeID string) error

func (*SwarmService) RemoveConfig

func (s *SwarmService) RemoveConfig(ctx context.Context, configID string) error

func (*SwarmService) RemoveNode

func (s *SwarmService) RemoveNode(ctx context.Context, nodeID string, force bool) error

func (*SwarmService) RemoveSecret

func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) error

func (*SwarmService) RemoveService

func (s *SwarmService) RemoveService(ctx context.Context, serviceID string) error

func (*SwarmService) RemoveStack

func (s *SwarmService) RemoveStack(ctx context.Context, environmentID, stackName string) error

func (*SwarmService) RollbackService

func (s *SwarmService) RollbackService(ctx context.Context, serviceID string) (*swarmtypes.ServiceUpdateResponse, error)

func (*SwarmService) RotateSwarmJoinTokens

func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypes.SwarmRotateJoinTokensRequest) error

func (*SwarmService) ScaleService

func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, replicas uint64) (*swarmtypes.ServiceUpdateResponse, error)

func (*SwarmService) StreamServiceLogs

func (s *SwarmService) StreamServiceLogs(ctx context.Context, serviceID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error

func (*SwarmService) SyncSwarmEnabledState

func (s *SwarmService) SyncSwarmEnabledState(ctx context.Context) error

func (*SwarmService) UnlockSwarm

func (*SwarmService) UpdateConfig

func (s *SwarmService) UpdateConfig(ctx context.Context, configID string, req swarmtypes.ConfigUpdateRequest) error

func (*SwarmService) UpdateNode

func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtypes.NodeUpdateRequest) error

func (*SwarmService) UpdateSecret

func (s *SwarmService) UpdateSecret(ctx context.Context, secretID string, req swarmtypes.SecretUpdateRequest) error

func (*SwarmService) UpdateService

func (*SwarmService) UpdateStackSource

func (s *SwarmService) UpdateStackSource(ctx context.Context, environmentID, stackName string, req swarmtypes.StackSourceUpdateRequest) (*swarmtypes.StackSource, error)

func (*SwarmService) UpdateSwarmSpec

func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.SwarmUpdateRequest) error

type SystemService

type SystemService struct {
	// contains filtered or unexported fields
}

func NewSystemService

func NewSystemService(
	db *database.DB,
	dockerService *DockerClientService,
	containerService *ContainerService,
	imageService *ImageService,
	volumeService *VolumeService,
	networkService *NetworkService,
	settingsService *SettingsService,
	activityService *ActivityService,
) *SystemService

func (*SystemService) ConvertToDockerCompose

func (s *SystemService) ConvertToDockerCompose(parsed *system.DockerRunCommand) (string, string, string, error)

func (*SystemService) GetDiskUsagePath

func (s *SystemService) GetDiskUsagePath(ctx context.Context) string

func (*SystemService) ParseDockerRunCommand

func (s *SystemService) ParseDockerRunCommand(command string) (*system.DockerRunCommand, error)

func (*SystemService) PruneAll

func (s *SystemService) PruneAll(ctx context.Context, environmentID string, req system.PruneAllRequest) (*system.PruneAllResult, bool, error)

func (*SystemService) StartAllContainers

func (s *SystemService) StartAllContainers(ctx context.Context, environmentID string) (*containertypes.ActionResult, error)

func (*SystemService) StartAllStoppedContainers

func (s *SystemService) StartAllStoppedContainers(ctx context.Context, environmentID string) (*containertypes.ActionResult, error)

func (*SystemService) StartPruneAll

func (s *SystemService) StartPruneAll(ctx context.Context, environmentID string, req system.PruneAllRequest) *system.PruneAllResult

func (*SystemService) StopAllContainers

func (s *SystemService) StopAllContainers(ctx context.Context, environmentID string) (*containertypes.ActionResult, error)

type SystemUpgradeService

type SystemUpgradeService struct {
	// contains filtered or unexported fields
}

func NewSystemUpgradeService

func NewSystemUpgradeService(
	dockerService *DockerClientService,
	versionService *VersionService,
	eventService *EventService,
	settingsService *SettingsService,
) *SystemUpgradeService

func (*SystemUpgradeService) CanUpgrade

func (s *SystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error)

CanUpgrade checks if self-upgrade is possible

func (*SystemUpgradeService) TriggerUpgradeViaCLI

func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user models.User) error

TriggerUpgradeViaCLI spawns the upgrade CLI command in a separate container This avoids self-termination issues by running the upgrade from outside

type TemplateService

type TemplateService struct {
	// contains filtered or unexported fields
}

func NewTemplateService

func NewTemplateService(ctx context.Context, db *database.DB, httpClient *http.Client, settingsService *SettingsService) *TemplateService

func (*TemplateService) CreateRegistry

func (s *TemplateService) CreateRegistry(ctx context.Context, registry *models.TemplateRegistry) error

func (*TemplateService) CreateTemplate

func (s *TemplateService) CreateTemplate(ctx context.Context, template *models.ComposeTemplate) error

func (*TemplateService) DeleteRegistry

func (s *TemplateService) DeleteRegistry(ctx context.Context, id string) error

func (*TemplateService) DeleteTemplate

func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error

func (*TemplateService) DownloadTemplate

func (s *TemplateService) DownloadTemplate(ctx context.Context, remoteTemplate *models.ComposeTemplate) (*models.ComposeTemplate, error)

func (*TemplateService) FetchRaw

func (s *TemplateService) FetchRaw(ctx context.Context, url string) ([]byte, error)

func (*TemplateService) FetchTemplateContent

func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *models.ComposeTemplate) (string, string, error)

func (*TemplateService) GetAllTemplates

func (s *TemplateService) GetAllTemplates(ctx context.Context) ([]models.ComposeTemplate, error)

func (*TemplateService) GetAllTemplatesPaginated

func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params pagination.QueryParams) ([]tmpl.Template, pagination.Response, error)

func (*TemplateService) GetComposeTemplate

func (s *TemplateService) GetComposeTemplate() string

func (*TemplateService) GetEnvTemplate

func (s *TemplateService) GetEnvTemplate() string

func (*TemplateService) GetGlobalVariables

func (s *TemplateService) GetGlobalVariables(ctx context.Context) ([]env.Variable, error)

func (*TemplateService) GetRegistries

func (s *TemplateService) GetRegistries(ctx context.Context) ([]models.TemplateRegistry, error)

func (*TemplateService) GetRegistryFetchErrors

func (s *TemplateService) GetRegistryFetchErrors() map[string]string

GetRegistryFetchErrors returns a snapshot of the last fetch error per registry ID. An absent entry means the registry fetched successfully (or has never been attempted).

func (*TemplateService) GetSwarmStackEnvTemplate

func (s *TemplateService) GetSwarmStackEnvTemplate() string

func (*TemplateService) GetSwarmStackTemplate

func (s *TemplateService) GetSwarmStackTemplate() string

func (*TemplateService) GetTemplate

func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.ComposeTemplate, error)

func (*TemplateService) GetTemplateContentWithParsedData

func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context, id string) (*tmpl.TemplateContent, error)

GetTemplateContentWithParsedData returns template content along with parsed metadata

func (*TemplateService) ParseComposeServices

func (s *TemplateService) ParseComposeServices(ctx context.Context, composeContent string) []string

ParseComposeServices extracts service names from a compose file content using compose-go

func (*TemplateService) SaveComposeTemplate

func (s *TemplateService) SaveComposeTemplate(content string) error

func (*TemplateService) SaveEnvTemplate

func (s *TemplateService) SaveEnvTemplate(content string) error

func (*TemplateService) SyncLocalTemplatesFromFilesystem

func (s *TemplateService) SyncLocalTemplatesFromFilesystem(ctx context.Context) error

func (*TemplateService) UpdateGlobalVariables

func (s *TemplateService) UpdateGlobalVariables(ctx context.Context, vars []env.Variable) error

func (*TemplateService) UpdateRegistry

func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updates *models.TemplateRegistry) error

func (*TemplateService) UpdateTemplate

func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updates *models.ComposeTemplate) error

type TokenPair

type TokenPair struct {
	AccessToken  string    `json:"accessToken"`
	RefreshToken string    `json:"refreshToken"`
	ExpiresAt    time.Time `json:"expiresAt"`
}

type UpdateActivityRequest

type UpdateActivityRequest = activitylib.UpdateRequest

type UpdaterService

type UpdaterService struct {
	// contains filtered or unexported fields
}

UpdaterService is Arcane's handler-facing service for the standalone updater engine.

func NewUpdaterService

func NewUpdaterService(
	db *database.DB,
	settings *SettingsService,
	docker *DockerClientService,
	projects *ProjectService,
	imageUpdates *ImageUpdateService,
	registries *ContainerRegistryService,
	events *EventService,
	imageSvc *ImageService,
	notifications *NotificationService,
	upgrade selfUpgradeServiceInternal,
	activityService *ActivityService,
) *UpdaterService

NewUpdaterService constructs the Arcane updater facade.

func (*UpdaterService) ApplyPending

func (s *UpdaterService) ApplyPending(ctx context.Context, options updater.Options) (out *updater.Result, err error)

ApplyPending executes pending image updates.

func (*UpdaterService) BeginContainerUpdate

func (s *UpdaterService) BeginContainerUpdate(containerID string) func()

BeginContainerUpdate marks a container as updating.

func (*UpdaterService) BeginProjectUpdate

func (s *UpdaterService) BeginProjectUpdate(projectID string) func()

BeginProjectUpdate marks a project as updating.

func (*UpdaterService) ClearImageUpdateRecord

func (s *UpdaterService) ClearImageUpdateRecord(ctx context.Context, record moduletypes.ImageUpdateRecord) error

ClearImageUpdateRecord clears a pending image update record after it is handled.

func (*UpdaterService) CollectUsedImages

func (s *UpdaterService) CollectUsedImages(ctx context.Context) (map[string]struct{}, error)

CollectUsedImages returns normalized image references used by running Arcane resources.

func (*UpdaterService) DockerClient

func (s *UpdaterService) DockerClient(ctx context.Context) (*client.Client, error)

DockerClient returns Arcane's configured Docker client for the updater engine.

func (*UpdaterService) ExcludedContainers

func (s *UpdaterService) ExcludedContainers(ctx context.Context) ([]string, error)

ExcludedContainers returns auto-update exclusions from Arcane settings.

func (*UpdaterService) GetHistory

func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]models.AutoUpdateRecord, error)

GetHistory returns the most recent auto-update history records, newest first.

func (*UpdaterService) GetStatus

func (s *UpdaterService) GetStatus() updater.Status

GetStatus returns the current in-memory update activity snapshot.

func (*UpdaterService) Notify

func (s *UpdaterService) Notify(ctx context.Context, notification moduletypes.Notification) error

Notify sends Arcane's container update notification.

func (*UpdaterService) PendingImageUpdates

func (s *UpdaterService) PendingImageUpdates(ctx context.Context) ([]moduletypes.ImageUpdateRecord, error)

PendingImageUpdates returns pending image update records from Arcane's database.

func (*UpdaterService) ProjectByComposeName

func (s *UpdaterService) ProjectByComposeName(ctx context.Context, composeName string) (moduletypes.ComposeProject, error)

ProjectByComposeName resolves an Arcane project from a Docker Compose project name.

func (*UpdaterService) PullImage

func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progress io.Writer) error

PullImage pulls an image through Arcane's image service.

func (*UpdaterService) RecordEvent

func (s *UpdaterService) RecordEvent(ctx context.Context, event moduletypes.Event) error

RecordEvent records updater lifecycle events in Arcane's event stream.

func (*UpdaterService) RecordUpdateRun

func (s *UpdaterService) RecordUpdateRun(ctx context.Context, result moduletypes.ResourceResult) error

RecordUpdateRun persists one updater resource result into Arcane history.

func (*UpdaterService) RestartContainersUsingOldIDs

func (s *UpdaterService) RestartContainersUsingOldIDs(ctx context.Context, oldIDToNewRef map[string]string, oldRefToNewRef map[string]string) ([]updater.ResourceResult, error)

RestartContainersUsingOldIDs restarts containers matching old image IDs or refs.

func (*UpdaterService) TriggerSelfUpdate

func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target moduletypes.SelfUpdateTarget) error

TriggerSelfUpdate runs Arcane's CLI-backed self-update hook.

func (*UpdaterService) TriggerSelfUpdateViaCLI

func (s *UpdaterService) TriggerSelfUpdateViaCLI(ctx context.Context, source, containerID, containerName string, labelMap map[string]string) error

TriggerSelfUpdateViaCLI triggers Arcane's detached CLI self-update path.

func (*UpdaterService) UpdateServices

func (s *UpdaterService) UpdateServices(ctx context.Context, projectID string, services []string) error

UpdateServices redeploys selected services through Arcane's project service.

func (*UpdaterService) UpdateSingleContainer

func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID string) (out *updater.Result, err error)

UpdateSingleContainer updates a single container by ID to the latest available image.

type UserService

type UserService struct {
	// contains filtered or unexported fields
}

func NewUserService

func NewUserService(db *database.DB) *UserService

func (*UserService) AttachOidcSubjectTransactional

func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID string, subject string, updateFn func(u *models.User)) (*models.User, error)

AttachOidcSubjectTransactional safely links an OIDC subject to the given user inside a DB transaction. It uses a row lock (FOR UPDATE) to prevent concurrent merges from racing and validates that the user isn't already linked to a different subject. The provided updateFn can mutate the user (e.g., roles, display name, tokens, last login) before persisting.

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 (*UserService) CreateDefaultAdmin

func (s *UserService) CreateDefaultAdmin(ctx context.Context) error

func (*UserService) CreateUser

func (s *UserService) CreateUser(ctx context.Context, user *models.User) (*models.User, error)

func (*UserService) DeleteUser

func (s *UserService) DeleteUser(ctx context.Context, id string) error

func (*UserService) GetUser

func (s *UserService) GetUser(ctx context.Context, userID string) (*models.User, error)

func (*UserService) GetUserByEmail

func (s *UserService) GetUserByEmail(ctx context.Context, email string) (*models.User, error)

func (*UserService) GetUserByID

func (s *UserService) GetUserByID(ctx context.Context, id string) (*models.User, error)

func (*UserService) GetUserByOidcSubjectId

func (s *UserService) GetUserByOidcSubjectId(ctx context.Context, subjectId string) (*models.User, error)

func (*UserService) GetUserByUsername

func (s *UserService) GetUserByUsername(ctx context.Context, username string) (*models.User, error)

func (*UserService) HashPassword

func (s *UserService) HashPassword(password string) (string, error)

func (*UserService) ListUsersPaginated

func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.QueryParams) ([]user.User, pagination.Response, error)

func (*UserService) NeedsPasswordUpgrade

func (s *UserService) NeedsPasswordUpgrade(hash string) bool

func (*UserService) ToUserResponseDto

func (s *UserService) ToUserResponseDto(ctx context.Context, u models.User) (user.User, error)

func (*UserService) UpdateUser

func (s *UserService) UpdateUser(ctx context.Context, user *models.User) (*models.User, error)

func (*UserService) UpgradePasswordHash

func (s *UserService) UpgradePasswordHash(ctx context.Context, userID, password string) error

func (*UserService) ValidatePassword

func (s *UserService) ValidatePassword(encodedHash, password string) error

func (*UserService) WithRoleService

func (s *UserService) WithRoleService(roleService *RoleService) *UserService

WithRoleService wires the RoleService dependency. Separated from the constructor so the bootstrap can construct UserService first (RoleService itself has no UserService dependency).

type VersionService

type VersionService struct {
	// contains filtered or unexported fields
}

func NewVersionService

func NewVersionService(httpClient *http.Client, disabled bool, version string, revision string, containerRegistryService *ContainerRegistryService, dockerService *DockerClientService, imageUpdateService *ImageUpdateService) *VersionService

func (*VersionService) GetAppVersionInfo

func (s *VersionService) GetAppVersionInfo(ctx context.Context) *version.Info

GetAppVersionInfo returns application version information including display version

func (*VersionService) GetLatestVersion

func (s *VersionService) GetLatestVersion(ctx context.Context) (string, error)

func (*VersionService) GetVersionInformation

func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersion string) (*version.Check, error)

func (*VersionService) IsNewer

func (s *VersionService) IsNewer(latest, current string) bool

func (*VersionService) ReleaseURL

func (s *VersionService) ReleaseURL(version string) string

type VolumeService

type VolumeService struct {
	// contains filtered or unexported fields
}

func NewVolumeService

func NewVolumeService(db *database.DB, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService, containerService *ContainerService, imageService *ImageService, backupVolumeName string) *VolumeService

func (*VolumeService) BackupHasPath

func (s *VolumeService) BackupHasPath(ctx context.Context, backupID string, filePath string) (bool, error)

func (*VolumeService) BackupMountWarning

func (s *VolumeService) BackupMountWarning(ctx context.Context) string

func (*VolumeService) CleanupHelperContainers

func (s *VolumeService) CleanupHelperContainers(ctx context.Context)

func (*VolumeService) CleanupOrphanedVolumeHelpers

func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) (int, error)

func (*VolumeService) CreateBackup

func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, user models.User) (*models.VolumeBackup, error)

func (*VolumeService) CreateDirectory

func (s *VolumeService) CreateDirectory(ctx context.Context, volumeName, dirPath string, user *models.User) error

func (*VolumeService) CreateVolume

func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeCreateOptions, user models.User) (*volumetypes.Volume, error)

func (*VolumeService) DeleteBackup

func (s *VolumeService) DeleteBackup(ctx context.Context, backupID string, user *models.User) error

func (*VolumeService) DeleteFile

func (s *VolumeService) DeleteFile(ctx context.Context, volumeName, filePath string, user *models.User) error

func (*VolumeService) DeleteVolume

func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force bool, user models.User) error

func (*VolumeService) DownloadBackup

func (s *VolumeService) DownloadBackup(ctx context.Context, backupID string, user *models.User) (io.ReadCloser, int64, error)

func (*VolumeService) DownloadFile

func (s *VolumeService) DownloadFile(ctx context.Context, volumeName, filePath string) (io.ReadCloser, int64, error)

func (*VolumeService) GetFileContent

func (s *VolumeService) GetFileContent(ctx context.Context, volumeName, filePath string, maxBytes int64) ([]byte, string, error)

func (*VolumeService) GetVolumeByName

func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*volumetypes.Volume, error)

func (*VolumeService) GetVolumeSizes

func (s *VolumeService) GetVolumeSizes(ctx context.Context) (map[string]VolumeSizeData, error)

GetVolumeSizes returns disk usage data for all volumes. This is a slow operation as it calls Docker's DiskUsage API.

func (*VolumeService) GetVolumeUsage

func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool, []string, error)

func (*VolumeService) ListBackupFiles

func (s *VolumeService) ListBackupFiles(ctx context.Context, backupID string) ([]string, error)

func (*VolumeService) ListBackups

func (s *VolumeService) ListBackups(ctx context.Context, volumeName string) ([]models.VolumeBackup, error)

func (*VolumeService) ListBackupsPaginated

func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName string, params pagination.QueryParams) ([]models.VolumeBackup, pagination.Response, error)

func (*VolumeService) ListDirectory

func (s *VolumeService) ListDirectory(ctx context.Context, volumeName, dirPath string) ([]volumetypes.FileEntry, error)

func (*VolumeService) ListVolumesPaginated

func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params pagination.QueryParams, includeInternal bool) ([]volumetypes.Volume, pagination.Response, volumetypes.UsageCounts, error)

func (*VolumeService) PruneVolumes

func (s *VolumeService) PruneVolumes(ctx context.Context) (*volumetypes.PruneReport, error)

func (*VolumeService) PruneVolumesWithOptions

func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (*volumetypes.PruneReport, error)

func (*VolumeService) ReapIdleHelpers

func (s *VolumeService) ReapIdleHelpers(ctx context.Context, idleTimeout time.Duration) (int, error)

ReapIdleHelpers removes reused read-only browse helper containers that have not serviced a request within idleTimeout. It is map-driven (orphaned helpers not tracked in helperByVolume are left to the startup orphan sweep). Entries are removed from the map before the container is removed, so a concurrent request simply gets a cache miss and re-creates a fresh helper.

func (*VolumeService) RestoreBackup

func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID string, user models.User) error

func (*VolumeService) RestoreBackupFiles

func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backupID string, paths []string, user models.User) error

func (*VolumeService) StopHelper

func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) error

StopHelper removes the reused read-only browse helper for a single volume, if one exists. It is idempotent: stopping a volume with no active helper returns nil.

func (*VolumeService) UploadAndRestore

func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string, archive io.Reader, filename string, user models.User) error

func (*VolumeService) UploadFile

func (s *VolumeService) UploadFile(ctx context.Context, volumeName, destPath string, content io.Reader, filename string, user *models.User) error

type VolumeSizeData

type VolumeSizeData struct {
	Size     int64
	RefCount int64
}

VolumeSizeData holds size information for a volume.

type VulnerabilityNotificationPayload

type VulnerabilityNotificationPayload struct {
	CVEID            string // e.g. CVE-2024-1234
	CVELink          string // e.g. https://nvd.nist.gov/vuln/detail/CVE-2024-1234
	Severity         string // CRITICAL, HIGH, MEDIUM, LOW, UNKNOWN
	ImageName        string // e.g. nginx:latest
	FixedVersion     string
	PkgName          string // optional
	InstalledVersion string // optional
}

VulnerabilityNotificationPayload is the data sent to all providers for vulnerability_found events. Only vulnerabilities with a fixed version should trigger this notification.

type VulnerabilityService

type VulnerabilityService struct {
	// contains filtered or unexported fields
}

VulnerabilityService handles vulnerability scanning of container images

func NewVulnerabilityService

func NewVulnerabilityService(db *database.DB, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService, notificationService *NotificationService, activityService *ActivityService, registryService *ContainerRegistryService) *VulnerabilityService

NewVulnerabilityService creates a new VulnerabilityService instance

func (*VulnerabilityService) CleanupOrphanedScanRecords

func (s *VulnerabilityService) CleanupOrphanedScanRecords(ctx context.Context) (deleted int64, err error)

CleanupOrphanedScanRecords removes vulnerability scan records for images that no longer exist in Docker. This keeps "images scanned" counts in sync (e.g. avoids "5/3" when images were deleted after being scanned). Safe to call even when no images exist; returns the number of records deleted.

func (*VulnerabilityService) DeleteScanResult

func (s *VulnerabilityService) DeleteScanResult(ctx context.Context, imageID string) error

DeleteScanResult deletes the scan result for an image

func (*VulnerabilityService) DeleteScanResultsByImageIDs

func (s *VulnerabilityService) DeleteScanResultsByImageIDs(ctx context.Context, imageIDs []string) error

DeleteScanResultsByImageIDs deletes scan results for multiple images in one query.

func (*VulnerabilityService) GetEnvironmentSummary

GetEnvironmentSummary returns aggregated vulnerability counts across all images.

func (*VulnerabilityService) GetIgnoreRecordsForImage

func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envID string, imageID string) ([]models.VulnerabilityIgnore, error)

GetIgnoreRecordsForImage retrieves all ignore records for a specific image

func (*VulnerabilityService) GetScanResult

func (s *VulnerabilityService) GetScanResult(ctx context.Context, imageID string) (*vulnerability.ScanResult, error)

GetScanResult retrieves the most recent scan result for an image

func (*VulnerabilityService) GetScanSummariesByImageIDs

func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, imageIDs []string) (map[string]*vulnerability.ScanSummary, error)

GetScanSummariesByImageIDs retrieves scan summaries for multiple images

func (*VulnerabilityService) GetScanSummary

func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID string) (*vulnerability.ScanSummary, error)

GetScanSummary retrieves just the summary for an image (for list views)

func (*VulnerabilityService) GetTrivyVersion

func (s *VulnerabilityService) GetTrivyVersion(ctx context.Context) string

GetTrivyVersion returns the Trivy version from the configured scanner image.

func (*VulnerabilityService) IgnoreVulnerability

func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID string, payload *vulnerability.IgnorePayload) (*models.VulnerabilityIgnore, error)

IgnoreVulnerability creates a new ignore record for a vulnerability

func (*VulnerabilityService) ListAllVulnerabilities

ListAllVulnerabilities returns a paginated list of vulnerabilities across all scanned images.

func (*VulnerabilityService) ListAllVulnerabilityImageOptions

func (s *VulnerabilityService) ListAllVulnerabilityImageOptions(ctx context.Context, severityFilter string) ([]string, error)

ListAllVulnerabilityImageOptions returns unique image names (or image IDs when name is empty) for vulnerability filtering, optionally constrained by severity.

func (*VulnerabilityService) ListIgnoredVulnerabilities

ListIgnoredVulnerabilities returns a list of ignored vulnerabilities for an environment

func (*VulnerabilityService) ListVulnerabilities

ListVulnerabilities returns a paginated, filtered list of vulnerabilities for an image.

func (*VulnerabilityService) ScanAllImages

func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string, user models.User) (scanned, failed int, err error)

ScanAllImages scans all Docker images for vulnerabilities. It is intended for use by the scheduled vulnerability scan job. A single long-running Trivy 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 (*VulnerabilityService) ScanImage

func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imageID string, user models.User) (*vulnerability.ScanResult, error)

ScanImage scans an image for vulnerabilities using Trivy

func (*VulnerabilityService) UnignoreVulnerability

func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envID string, ignoreID string) error

UnignoreVulnerability removes an ignore record

type WebhookService

type WebhookService struct {
	// contains filtered or unexported fields
}

func NewWebhookService

func NewWebhookService(db *database.DB, containerService *ContainerService, updaterService *UpdaterService, projectService *ProjectService, gitOpsSyncService *GitOpsSyncService, eventService *EventService) *WebhookService

func (*WebhookService) CreateWebhook

func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, actionType, targetID, environmentID string, actor models.User) (*models.Webhook, string, error)

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 (*WebhookService) DeleteWebhook

func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID string, actor models.User) error

DeleteWebhook removes a webhook by ID, scoped to an environment.

func (*WebhookService) GetWebhookByID

func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID string) (*models.Webhook, error)

GetWebhookByID returns a single webhook by ID, scoped to an environment.

func (*WebhookService) ListWebhookSummaries

func (s *WebhookService) ListWebhookSummaries(ctx context.Context, environmentID string) ([]webhooktypes.Summary, error)

func (*WebhookService) ListWebhooks

func (s *WebhookService) ListWebhooks(ctx context.Context, environmentID string) ([]models.Webhook, error)

ListWebhooks returns all webhooks for an environment.

func (*WebhookService) TriggerByToken

func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) (*updater.Result, error)

TriggerByToken looks up a webhook by its raw token and executes the configured action. Returns an updater result for "updater" webhooks; nil for "project" and "gitops".

func (*WebhookService) UpdateWebhook

func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID string, enabled bool, actor models.User) (*models.Webhook, error)

UpdateWebhook updates the enabled state of a webhook, scoped to an environment.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL