Skip to content

Modern Docker Management, Designed for Everyone

feat: ecr registry support (#2078)

Paulo Rocha42cfaa1b4d4d
diff --git a/backend/go.mod b/backend/go.mod
index c5e334676..13f721814 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -5,6 +5,9 @@ go 1.26.0
replace github.com/getarcaneapp/arcane/types => ../types
require (
+ github.com/aws/aws-sdk-go-v2/config v1.32.7
+ github.com/aws/aws-sdk-go-v2/credentials v1.19.7
+ github.com/aws/aws-sdk-go-v2/service/ecr v1.43.0
github.com/cenkalti/backoff/v5 v5.0.3
github.com/compose-spec/compose-go/v2 v2.10.1
github.com/containerd/errdefs v1.0.0
@@ -65,6 +68,18 @@ require (
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.3.0 // indirect
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
+ github.com/aws/aws-sdk-go-v2 v1.41.1 // indirect
+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect
+ github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect
+ github.com/aws/smithy-go v1.24.0 // indirect
github.com/buger/goterm v1.0.4 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 7f252f774..caca1feba 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -29,6 +29,36 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
+github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=
+github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
+github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY=
+github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM=
+github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
+github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
+github.com/aws/aws-sdk-go-v2/service/ecr v1.43.0 h1:Ak4Ggvvbg8WYxPLoyLOtes1cIMQePvCAi/dUGqm8hOY=
+github.com/aws/aws-sdk-go-v2/service/ecr v1.43.0/go.mod h1:iQ1skgw1XRK+6Lgkb0I9ODatAP72WoTILh0zXQ5DtbU=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU=
+github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y=
+github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M=
+github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk=
+github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo=
+github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ=
+github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ=
+github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
+github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ=
diff --git a/backend/internal/huma/handlers/container_registries.go b/backend/internal/huma/handlers/container_registries.go
index 2f21276f8..1262f12c8 100644
--- a/backend/internal/huma/handlers/container_registries.go
+++ b/backend/internal/huma/handlers/container_registries.go
@@ -358,6 +358,21 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryRetrievalError{Err: err}).Error())
}
+ // ECR registries use a different auth flow: generate a temporary token via AWS API.
+ if reg.RegistryType == "ecr" {
+ if err := h.registryService.TestECRRegistry(ctx, reg); err != nil {
+ return nil, huma.Error400BadRequest((&common.RegistryTestError{Err: err}).Error())
+ }
+ return &TestContainerRegistryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "ECR authentication succeeded",
+ },
+ },
+ }, nil
+ }
+
decryptedToken, err := crypto.Decrypt(reg.Token)
if err != nil {
return nil, huma.Error500InternalServerError((&common.TokenDecryptionError{Err: err}).Error())
diff --git a/backend/internal/models/container_registry.go b/backend/internal/models/container_registry.go
index 5f23c5845..07fa228b4 100644
--- a/backend/internal/models/container_registry.go
+++ b/backend/internal/models/container_registry.go
@@ -5,14 +5,20 @@ import (
)
type ContainerRegistry struct {
- URL string `json:"url" sortable:"true"`
- Username string `json:"username" sortable:"true"`
- Token string `json:"token"`
- Description *string `json:"description,omitempty" sortable:"true"`
- Insecure bool `json:"insecure" sortable:"true"`
- Enabled bool `json:"enabled" sortable:"true"`
- CreatedAt time.Time `json:"createdAt" sortable:"true"`
- UpdatedAt time.Time `json:"updatedAt" sortable:"true"`
+ URL string `json:"url" sortable:"true"`
+ Username string `json:"username" sortable:"true"`
+ Token string `json:"token"`
+ Description *string `json:"description,omitempty" sortable:"true"`
+ Insecure bool `json:"insecure" sortable:"true"`
+ Enabled bool `json:"enabled" sortable:"true"`
+ RegistryType string `json:"registryType" sortable:"true"`
+ AWSAccessKeyID string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey string `json:"awsSecretAccessKey"`
+ AWSRegion string `json:"awsRegion"`
+ ECRToken string `json:"ecrToken"`
+ ECRTokenGeneratedAt *time.Time `json:"ecrTokenGeneratedAt"`
+ CreatedAt time.Time `json:"createdAt" sortable:"true"`
+ UpdatedAt time.Time `json:"updatedAt" sortable:"true"`
BaseModel
}
@@ -21,19 +27,27 @@ func (ContainerRegistry) TableName() string {
}
type CreateContainerRegistryRequest struct {
- URL string `json:"url" binding:"required"`
- Username string `json:"username" binding:"required"`
- Token string `json:"token" binding:"required"`
- Description *string `json:"description"`
- Insecure *bool `json:"insecure"`
- Enabled *bool `json:"enabled"`
+ URL string `json:"url" binding:"required"`
+ Username string `json:"username"`
+ Token string `json:"token"`
+ Description *string `json:"description"`
+ Insecure *bool `json:"insecure"`
+ Enabled *bool `json:"enabled"`
+ RegistryType string `json:"registryType"`
+ AWSAccessKeyID string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey string `json:"awsSecretAccessKey"`
+ AWSRegion string `json:"awsRegion"`
}
type UpdateContainerRegistryRequest struct {
- URL *string `json:"url"`
- Username *string `json:"username"`
- Token *string `json:"token"`
- Description *string `json:"description"`
- Insecure *bool `json:"insecure"`
- Enabled *bool `json:"enabled"`
+ URL *string `json:"url"`
+ Username *string `json:"username"`
+ Token *string `json:"token"`
+ Description *string `json:"description"`
+ Insecure *bool `json:"insecure"`
+ Enabled *bool `json:"enabled"`
+ RegistryType *string `json:"registryType"`
+ AWSAccessKeyID *string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey *string `json:"awsSecretAccessKey"`
+ AWSRegion *string `json:"awsRegion"`
}
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index 732f1e0eb..ae671f65c 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -10,6 +10,8 @@ import (
"sync"
"time"
+ "golang.org/x/sync/singleflight"
+
cerrdefs "github.com/containerd/errdefs"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
@@ -26,7 +28,9 @@ import (
)
const (
- registryCacheTTL = 30 * time.Minute
+ registryCacheTTL = 30 * time.Minute
+ registryTypeGeneric string = "generic"
+ registryTypeECR string = "ecr"
)
type RegistryDaemonClient interface {
@@ -53,9 +57,10 @@ type resolvedRegistryCredential struct {
type ContainerRegistryService struct {
db *database.DB
dockerClient registryDaemonGetter
- distributionHTTPClient *http.Client
cache map[string]*cache.Cache[string] // imageRef -> digest cache
cacheMu sync.RWMutex
+ ecrRefreshGroup singleflight.Group
+ distributionHTTPClient *http.Client
}
func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetter) *ContainerRegistryService {
@@ -112,21 +117,45 @@ func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id strin
}
func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req models.CreateContainerRegistryRequest) (*models.ContainerRegistry, error) {
- // Encrypt the token before storing
- encryptedToken, err := crypto.Encrypt(req.Token)
+ registryType, err := normalizeRegistryTypeInternal(req.RegistryType)
if err != nil {
- return nil, fmt.Errorf("failed to encrypt token: %w", err)
+ return nil, err
}
registry := &models.ContainerRegistry{
- URL: req.URL,
- Username: req.Username,
- Token: encryptedToken,
- Description: req.Description,
- Insecure: req.Insecure != nil && *req.Insecure,
- Enabled: req.Enabled == nil || *req.Enabled,
- CreatedAt: time.Now(),
- UpdatedAt: time.Now(),
+ URL: req.URL,
+ Description: req.Description,
+ Insecure: req.Insecure != nil && *req.Insecure,
+ Enabled: req.Enabled == nil || *req.Enabled,
+ RegistryType: registryType,
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
+ }
+
+ if registryType == registryTypeECR {
+ if strings.TrimSpace(req.AWSAccessKeyID) == "" {
+ return nil, &models.ValidationError{Field: "awsAccessKeyId", Message: "AWS Access Key ID is required for ECR registries"}
+ }
+ if strings.TrimSpace(req.AWSRegion) == "" {
+ return nil, &models.ValidationError{Field: "awsRegion", Message: "AWS Region is required for ECR registries"}
+ }
+ if strings.TrimSpace(req.AWSSecretAccessKey) == "" {
+ return nil, &models.ValidationError{Field: "awsSecretAccessKey", Message: "AWS Secret Access Key is required for ECR registries"}
+ }
+ encryptedSecret, err := crypto.Encrypt(req.AWSSecretAccessKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt AWS secret access key: %w", err)
+ }
+ registry.AWSAccessKeyID = req.AWSAccessKeyID
+ registry.AWSSecretAccessKey = encryptedSecret
+ registry.AWSRegion = req.AWSRegion
+ } else {
+ encryptedToken, err := crypto.Encrypt(req.Token)
+ if err != nil {
+ return nil, fmt.Errorf("failed to encrypt token: %w", err)
+ }
+ registry.Username = req.Username
+ registry.Token = encryptedToken
}
if err := s.db.WithContext(ctx).Create(registry).Error; err != nil {
@@ -142,23 +171,24 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
return nil, err
}
- // Update fields
+ // Update common fields
utils.UpdateIfChanged(&registry.URL, req.URL)
- utils.UpdateIfChanged(&registry.Username, req.Username)
-
- if req.Token != nil && *req.Token != "" {
- // Encrypt the new token
- encryptedToken, err := crypto.Encrypt(*req.Token)
- if err != nil {
- return nil, fmt.Errorf("failed to encrypt token: %w", err)
- }
- utils.UpdateIfChanged(&registry.Token, encryptedToken)
- }
-
utils.UpdateIfChanged(&registry.Description, req.Description)
utils.UpdateIfChanged(&registry.Insecure, req.Insecure)
utils.UpdateIfChanged(&registry.Enabled, req.Enabled)
+ if err := s.applyRegistryTypeUpdateInternal(registry, req.RegistryType); err != nil {
+ return nil, err
+ }
+
+ if registry.RegistryType == registryTypeECR {
+ if err := s.updateECRRegistryFieldsInternal(registry, req); err != nil {
+ return nil, err
+ }
+ } else if err := s.updateGenericRegistryFieldsInternal(registry, req); err != nil {
+ return nil, err
+ }
+
registry.UpdatedAt = time.Now()
if err := s.db.WithContext(ctx).Save(registry).Error; err != nil {
@@ -168,6 +198,80 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
return registry, nil
}
+func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *models.ContainerRegistry, registryType *string) error {
+ if registryType == nil {
+ return nil
+ }
+
+ nextType, err := normalizeRegistryTypeInternal(*registryType)
+ if err != nil {
+ return err
+ }
+
+ if nextType == registry.RegistryType {
+ return nil
+ }
+
+ if nextType == registryTypeECR {
+ registry.Username = ""
+ registry.Token = ""
+ } else {
+ registry.AWSAccessKeyID = ""
+ registry.AWSSecretAccessKey = ""
+ registry.AWSRegion = ""
+ registry.ECRToken = ""
+ registry.ECRTokenGeneratedAt = nil
+ }
+
+ registry.RegistryType = nextType
+ return nil
+}
+
+func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *models.ContainerRegistry, req models.UpdateContainerRegistryRequest) error {
+ utils.UpdateIfChanged(&registry.AWSAccessKeyID, req.AWSAccessKeyID)
+ utils.UpdateIfChanged(&registry.AWSRegion, req.AWSRegion)
+
+ if req.AWSSecretAccessKey != nil && *req.AWSSecretAccessKey != "" {
+ encryptedSecret, err := crypto.Encrypt(*req.AWSSecretAccessKey)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt AWS secret access key: %w", err)
+ }
+ utils.UpdateIfChanged(&registry.AWSSecretAccessKey, &encryptedSecret)
+ }
+
+ if strings.TrimSpace(registry.AWSAccessKeyID) == "" {
+ return &models.ValidationError{Field: "awsAccessKeyId", Message: "AWS Access Key ID is required for ECR registries"}
+ }
+ if strings.TrimSpace(registry.AWSRegion) == "" {
+ return &models.ValidationError{Field: "awsRegion", Message: "AWS Region is required for ECR registries"}
+ }
+ if strings.TrimSpace(registry.AWSSecretAccessKey) == "" {
+ return &models.ValidationError{Field: "awsSecretAccessKey", Message: "AWS Secret Access Key is required for ECR registries"}
+ }
+
+ if req.AWSAccessKeyID != nil || req.AWSSecretAccessKey != nil || req.AWSRegion != nil {
+ registry.ECRToken = ""
+ registry.ECRTokenGeneratedAt = nil
+ }
+
+ return nil
+}
+
+func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry *models.ContainerRegistry, req models.UpdateContainerRegistryRequest) error {
+ utils.UpdateIfChanged(&registry.Username, req.Username)
+
+ if req.Token == nil || *req.Token == "" {
+ return nil
+ }
+
+ encryptedToken, err := crypto.Encrypt(*req.Token)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt token: %w", err)
+ }
+ utils.UpdateIfChanged(&registry.Token, encryptedToken)
+ return nil
+}
+
func (s *ContainerRegistryService) DeleteRegistry(ctx context.Context, id string) error {
if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.ContainerRegistry{}).Error; err != nil {
return fmt.Errorf("failed to delete container registry: %w", err)
@@ -238,18 +342,9 @@ func (s *ContainerRegistryService) GetAllRegistryAuthConfigs(ctx context.Context
}
authConfigs := make(map[string]dockerregistry.AuthConfig, len(registries))
- for _, reg := range registries {
- username := strings.TrimSpace(reg.Username)
- if !reg.Enabled || username == "" || reg.Token == "" {
- continue
- }
-
- decryptedToken, decryptErr := crypto.Decrypt(reg.Token)
- if decryptErr != nil {
- return nil, fmt.Errorf("failed to decrypt token for registry %s: %w", reg.URL, decryptErr)
- }
- token := strings.TrimSpace(decryptedToken)
- if token == "" {
+ for i := range registries {
+ reg := &registries[i]
+ if !reg.Enabled {
continue
}
@@ -266,6 +361,32 @@ func (s *ContainerRegistryService) GetAllRegistryAuthConfigs(ctx context.Context
continue
}
+ var username, token string
+
+ if reg.RegistryType == "ecr" {
+ ecrUser, ecrPass, ecrErr := s.GetOrRefreshECRToken(ctx, reg)
+ if ecrErr != nil {
+ slog.WarnContext(ctx, "failed to get ECR token for auth configs", "registry", reg.URL, "error", ecrErr)
+ continue
+ }
+ username = ecrUser
+ token = ecrPass
+ } else {
+ username = strings.TrimSpace(reg.Username)
+ if username == "" || reg.Token == "" {
+ continue
+ }
+ decryptedToken, decryptErr := crypto.Decrypt(reg.Token)
+ if decryptErr != nil {
+ slog.WarnContext(ctx, "failed to decrypt token for registry, skipping", "registry", reg.URL, "error", decryptErr)
+ continue
+ }
+ token = strings.TrimSpace(decryptedToken)
+ if token == "" {
+ continue
+ }
+ }
+
authConfig := dockerregistry.AuthConfig{
Username: username,
Password: token,
@@ -306,6 +427,31 @@ func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURL
return nil
}
+// TestECRRegistry tests connectivity for an ECR registry by generating an auth token
+// and attempting a Docker login.
+func (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *models.ContainerRegistry) error {
+ ecrUser, ecrPass, err := s.GetOrRefreshECRToken(ctx, reg)
+ if err != nil {
+ return fmt.Errorf("failed to obtain ECR token: %w", err)
+ }
+
+ dockerClient, err := s.getDockerClientInternal(ctx)
+ if err != nil {
+ return err
+ }
+
+ _, err = dockerClient.RegistryLogin(ctx, client.RegistryLoginOptions{
+ Username: ecrUser,
+ Password: ecrPass,
+ ServerAddress: normalizeRegistryServerAddressInternal(reg.URL),
+ })
+ if err != nil {
+ return fmt.Errorf("ECR registry login failed: %w", err)
+ }
+
+ return nil
+}
+
// 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 (s *ContainerRegistryService) GetImageDigest(ctx context.Context, imageRef string) (string, error) {
@@ -542,12 +688,27 @@ func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx co
return nil, fmt.Errorf("failed to load enabled registries: %w", err)
}
- credentials := make([]resolvedRegistryCredential, 0, len(registries))
- for _, reg := range registries {
+ creds := make([]resolvedRegistryCredential, 0, len(registries))
+ for i := range registries {
+ reg := &registries[i]
if !utilsregistry.IsRegistryMatch(reg.URL, registryHost) {
continue
}
+ if reg.RegistryType == "ecr" {
+ ecrUser, ecrPass, ecrErr := s.GetOrRefreshECRToken(ctx, reg)
+ if ecrErr != nil {
+ slog.WarnContext(ctx, "failed to get ECR token", "registry", reg.URL, "error", ecrErr)
+ continue
+ }
+ creds = append(creds, resolvedRegistryCredential{
+ Username: ecrUser,
+ Token: ecrPass,
+ ServerAddress: normalizeRegistryServerAddressInternal(reg.URL),
+ })
+ continue
+ }
+
username := strings.TrimSpace(reg.Username)
if username == "" || reg.Token == "" {
continue
@@ -563,14 +724,14 @@ func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx co
continue
}
- credentials = append(credentials, resolvedRegistryCredential{
+ creds = append(creds, resolvedRegistryCredential{
Username: username,
Token: token,
ServerAddress: normalizeRegistryServerAddressInternal(reg.URL),
})
}
- return credentials, nil
+ return creds, nil
}
// SyncRegistries syncs registries from a manager to this agent instance
@@ -619,7 +780,10 @@ func (s *ContainerRegistryService) processSyncItemInternal(ctx context.Context,
}
func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Context, item containerregistry.Sync, existing *models.ContainerRegistry) error {
- needsUpdate := s.checkRegistryNeedsUpdateInternal(item, existing)
+ needsUpdate, err := s.checkRegistryNeedsUpdateInternal(item, existing)
+ if err != nil {
+ return err
+ }
if needsUpdate {
existing.UpdatedAt = time.Now()
@@ -631,41 +795,105 @@ func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Co
return nil
}
-func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item containerregistry.Sync, existing *models.ContainerRegistry) bool {
- needsUpdate := utils.UpdateIfChanged(&existing.URL, item.URL)
- needsUpdate = utils.UpdateIfChanged(&existing.Username, item.Username) || needsUpdate
-
- // Always update token as it comes decrypted from manager
- encryptedToken, err := crypto.Encrypt(item.Token)
- if err == nil {
- needsUpdate = utils.UpdateIfChanged(&existing.Token, encryptedToken) || needsUpdate
+func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item containerregistry.Sync, existing *models.ContainerRegistry) (bool, error) {
+ newType, err := normalizeRegistryTypeInternal(item.RegistryType)
+ if err != nil {
+ return false, err
}
+ needsUpdate := utils.UpdateIfChanged(&existing.URL, item.URL)
needsUpdate = utils.UpdateIfChanged(&existing.Description, item.Description) || needsUpdate
needsUpdate = utils.UpdateIfChanged(&existing.Insecure, item.Insecure) || needsUpdate
needsUpdate = utils.UpdateIfChanged(&existing.Enabled, item.Enabled) || needsUpdate
- return needsUpdate
+ // Clear stale credentials when registry type changes during sync
+ if newType != existing.RegistryType {
+ if newType == registryTypeECR {
+ existing.Username = ""
+ existing.Token = ""
+ } else {
+ existing.AWSAccessKeyID = ""
+ existing.AWSSecretAccessKey = ""
+ existing.AWSRegion = ""
+ existing.ECRToken = ""
+ existing.ECRTokenGeneratedAt = nil
+ }
+ needsUpdate = true
+ }
+
+ needsUpdate = utils.UpdateIfChanged(&existing.RegistryType, newType) || needsUpdate
+
+ if newType == registryTypeGeneric {
+ needsUpdate = utils.UpdateIfChanged(&existing.Username, item.Username) || needsUpdate
+
+ encryptedToken, err := crypto.Encrypt(item.Token)
+ if err != nil {
+ slog.Warn("failed to encrypt token during sync, skipping field", "registry", existing.ID, "error", err)
+ } else {
+ needsUpdate = utils.UpdateIfChanged(&existing.Token, encryptedToken) || needsUpdate
+ }
+
+ return needsUpdate, nil
+ }
+
+ credChanged := utils.UpdateIfChanged(&existing.AWSAccessKeyID, item.AWSAccessKeyID)
+ credChanged = utils.UpdateIfChanged(&existing.AWSRegion, item.AWSRegion) || credChanged
+
+ // Encrypt and update AWS secret if provided
+ if item.AWSSecretAccessKey != "" {
+ encryptedSecret, err := crypto.Encrypt(item.AWSSecretAccessKey)
+ if err != nil {
+ slog.Warn("failed to encrypt AWS secret during sync, skipping field", "registry", existing.ID, "error", err)
+ } else {
+ credChanged = utils.UpdateIfChanged(&existing.AWSSecretAccessKey, encryptedSecret) || credChanged
+ }
+ }
+
+ // Invalidate cached ECR token when credentials change
+ if credChanged {
+ existing.ECRToken = ""
+ existing.ECRTokenGeneratedAt = nil
+ }
+ needsUpdate = credChanged || needsUpdate
+
+ return needsUpdate, nil
}
func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.Context, item containerregistry.Sync) error {
- encryptedToken, err := crypto.Encrypt(item.Token)
+ registryType, err := normalizeRegistryTypeInternal(item.RegistryType)
if err != nil {
- return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, err)
+ return err
}
newRegistry := &models.ContainerRegistry{
BaseModel: models.BaseModel{
ID: item.ID,
},
- URL: item.URL,
- Username: item.Username,
- Token: encryptedToken,
- Description: item.Description,
- Insecure: item.Insecure,
- Enabled: item.Enabled,
- CreatedAt: time.Now(),
- UpdatedAt: time.Now(),
+ URL: item.URL,
+ Description: item.Description,
+ Insecure: item.Insecure,
+ Enabled: item.Enabled,
+ RegistryType: registryType,
+ AWSAccessKeyID: item.AWSAccessKeyID,
+ AWSRegion: item.AWSRegion,
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
+ }
+
+ if registryType == registryTypeGeneric {
+ newRegistry.Username = item.Username
+
+ encryptedToken, err := crypto.Encrypt(item.Token)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, err)
+ }
+ newRegistry.Token = encryptedToken
+ } else if item.AWSSecretAccessKey != "" {
+ encryptedSecret, err := crypto.Encrypt(item.AWSSecretAccessKey)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt AWS secret for new registry %s: %w", item.ID, err)
+ }
+ newRegistry.AWSSecretAccessKey = encryptedSecret
}
if err := s.db.WithContext(ctx).Create(newRegistry).Error; err != nil {
@@ -675,6 +903,23 @@ func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.Context
return nil
}
+func normalizeRegistryTypeInternal(value string) (string, error) {
+ registryType := strings.ToLower(strings.TrimSpace(value))
+ if registryType == "" {
+ return registryTypeGeneric, nil
+ }
+
+ switch registryType {
+ case registryTypeGeneric, registryTypeECR:
+ return registryType, nil
+ default:
+ return "", &models.ValidationError{
+ Field: "registryType",
+ Message: "Registry type must be one of: generic, ecr",
+ }
+ }
+}
+
func (s *ContainerRegistryService) deleteUnsyncedInternal(ctx context.Context, existingMap map[string]*models.ContainerRegistry, syncedIDs map[string]bool) error {
for id := range existingMap {
if !syncedIDs[id] {
diff --git a/backend/internal/services/container_registry_service_test.go b/backend/internal/services/container_registry_service_test.go
index 316374f3b..8df0b2df1 100644
--- a/backend/internal/services/container_registry_service_test.go
+++ b/backend/internal/services/container_registry_service_test.go
@@ -10,6 +10,9 @@ import (
"strings"
"testing"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
+ "github.com/getarcaneapp/arcane/types/containerregistry"
dockerregistry "github.com/moby/moby/api/types/registry"
"github.com/moby/moby/client"
"github.com/opencontainers/go-digest"
@@ -113,6 +116,51 @@ func TestContainerRegistryService_GetAllRegistryAuthConfigs_SkipsInvalidEntries(
assert.Equal(t, "registry.example.com", exampleCfg.ServerAddress)
}
+func TestContainerRegistryService_CreateRegistry_RejectsUnsupportedRegistryType(t *testing.T) {
+ _, db := setupImageServiceAuthTest(t)
+ svc := NewContainerRegistryService(db, nil)
+
+ _, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{
+ URL: "registry.example.com",
+ RegistryType: "ECR-ish",
+ })
+ require.Error(t, err)
+
+ var validationErr *models.ValidationError
+ require.ErrorAs(t, err, &validationErr)
+ assert.Equal(t, "registryType", validationErr.Field)
+}
+
+func TestContainerRegistryService_SyncRegistries_ClearsGenericTokenWhenManagerSendsEmptyValue(t *testing.T) {
+ _, db := setupImageServiceAuthTest(t)
+ createTestPullRegistry(t, db, "https://registry.example.com", "registry-user", "old-token")
+
+ var existing models.ContainerRegistry
+ require.NoError(t, db.WithContext(context.Background()).First(&existing).Error)
+
+ svc := NewContainerRegistryService(db, nil)
+ err := svc.SyncRegistries(context.Background(), []containerregistry.Sync{
+ {
+ ID: existing.ID,
+ URL: existing.URL,
+ Username: existing.Username,
+ Token: "",
+ Enabled: true,
+ RegistryType: registryTypeGeneric,
+ CreatedAt: existing.CreatedAt,
+ UpdatedAt: existing.UpdatedAt,
+ },
+ })
+ require.NoError(t, err)
+
+ var updated models.ContainerRegistry
+ require.NoError(t, db.WithContext(context.Background()).First(&updated, "id = ?", existing.ID).Error)
+
+ decryptedToken, err := crypto.Decrypt(updated.Token)
+ require.NoError(t, err)
+ assert.Empty(t, decryptedToken)
+}
+
func TestContainerRegistryService_TestRegistry_UsesDockerDaemon(t *testing.T) {
svc := NewContainerRegistryService(nil, func(context.Context) (RegistryDaemonClient, error) {
return &fakeRegistryDaemonClient{
diff --git a/backend/internal/services/ecr_token_service.go b/backend/internal/services/ecr_token_service.go
new file mode 100644
index 000000000..cd85461a2
--- /dev/null
+++ b/backend/internal/services/ecr_token_service.go
@@ -0,0 +1,116 @@
+package services
+
+import (
+ "context"
+ "encoding/base64"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/ecr"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
+)
+
+const ecrTokenTTL = 12 * time.Hour
+
+type ecrTokenResult struct {
+ username string
+ password string
+}
+
+// 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 (s *ContainerRegistryService) GetOrRefreshECRToken(ctx context.Context, reg *models.ContainerRegistry) (username, password string, err error) {
+ // Fast path: return cached token if still valid.
+ if reg.ECRTokenGeneratedAt != nil && time.Since(reg.ECRTokenGeneratedAt.UTC()) < ecrTokenTTL {
+ if reg.ECRToken != "" {
+ decrypted, decErr := crypto.Decrypt(reg.ECRToken)
+ if decErr == nil && strings.TrimSpace(decrypted) != "" {
+ return "AWS", decrypted, nil
+ }
+ }
+ }
+
+ // Slow path: deduplicate concurrent refreshes for the same registry.
+ result, sErr, _ := s.ecrRefreshGroup.Do(reg.ID, func() (any, error) {
+ // Detach from the request context so a cancelled caller doesn't
+ // abort the shared refresh for all waiting goroutines.
+ refreshCtx := context.WithoutCancel(ctx)
+ return s.refreshECRTokenInternal(refreshCtx, reg)
+ })
+ if sErr != nil {
+ return "", "", sErr
+ }
+ r := result.(*ecrTokenResult)
+ return r.username, r.password, nil
+}
+
+func (s *ContainerRegistryService) refreshECRTokenInternal(ctx context.Context, reg *models.ContainerRegistry) (*ecrTokenResult, error) {
+ // Decrypt the stored AWS secret access key.
+ secretKey, decErr := crypto.Decrypt(reg.AWSSecretAccessKey)
+ if decErr != nil {
+ return nil, fmt.Errorf("failed to decrypt AWS secret key for registry %s: %w", reg.URL, decErr)
+ }
+ secretKey = strings.TrimSpace(secretKey)
+ if secretKey == "" {
+ return nil, fmt.Errorf("AWS secret access key is empty for registry %s", reg.URL)
+ }
+
+ // Call AWS ECR GetAuthorizationToken.
+ cfg, cfgErr := config.LoadDefaultConfig(ctx,
+ config.WithRegion(reg.AWSRegion),
+ config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
+ reg.AWSAccessKeyID,
+ secretKey,
+ "",
+ )),
+ )
+ if cfgErr != nil {
+ return nil, fmt.Errorf("failed to load AWS config for registry %s: %w", reg.URL, cfgErr)
+ }
+
+ ecrClient := ecr.NewFromConfig(cfg)
+ result, ecrErr := ecrClient.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
+ if ecrErr != nil {
+ return nil, fmt.Errorf("failed to get ECR authorization token for registry %s: %w", reg.URL, ecrErr)
+ }
+ if len(result.AuthorizationData) == 0 || result.AuthorizationData[0].AuthorizationToken == nil {
+ return nil, fmt.Errorf("ECR returned empty authorization data for registry %s", reg.URL)
+ }
+
+ // Decode base64 token → "AWS:<password>".
+ decoded, decodeErr := base64.StdEncoding.DecodeString(*result.AuthorizationData[0].AuthorizationToken)
+ if decodeErr != nil {
+ return nil, fmt.Errorf("failed to decode ECR token for registry %s: %w", reg.URL, decodeErr)
+ }
+ parts := strings.SplitN(string(decoded), ":", 2)
+ if len(parts) != 2 || parts[1] == "" {
+ return nil, fmt.Errorf("unexpected ECR token format for registry %s", reg.URL)
+ }
+ ecrPassword := parts[1]
+
+ // Persist the new token (encrypted) and generation timestamp.
+ encryptedToken, encErr := crypto.Encrypt(ecrPassword)
+ if encErr != nil {
+ return nil, fmt.Errorf("failed to encrypt ECR token for registry %s: %w", reg.URL, encErr)
+ }
+ now := time.Now().UTC()
+ reg.ECRToken = encryptedToken
+ reg.ECRTokenGeneratedAt = &now
+ if saveErr := s.db.WithContext(ctx).Model(reg).Updates(map[string]any{
+ "ecr_token": encryptedToken,
+ "ecr_token_generated_at": now,
+ }).Error; saveErr != nil {
+ // Non-fatal: log but continue — the token is still usable for this call.
+ slog.WarnContext(ctx, "failed to persist ECR token to database", "registry", reg.URL, "error", saveErr)
+ }
+
+ return &ecrTokenResult{username: "AWS", password: ecrPassword}, nil
+}
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 869b8a2be..45ef660cc 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -833,26 +833,47 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en
slog.InfoContext(ctx, "Found registries to sync", "count", len(registries))
- // Prepare sync items with decrypted tokens
+ // Prepare sync items with decrypted credentials
syncItems := make([]containerregistry.Sync, 0, len(registries))
for _, reg := range registries {
- decryptedToken, err := crypto.Decrypt(reg.Token)
- if err != nil {
- slog.WarnContext(ctx, "Failed to decrypt registry token for sync", "registryID", reg.ID, "registryURL", reg.URL, "error", err.Error())
- continue
+ registryType, typeErr := normalizeRegistryTypeInternal(reg.RegistryType)
+ if typeErr != nil {
+ return fmt.Errorf("normalize registry type for sync %s: %w", reg.ID, typeErr)
}
- syncItems = append(syncItems, containerregistry.Sync{
- ID: reg.ID,
- URL: reg.URL,
- Username: reg.Username,
- Token: decryptedToken,
- Description: reg.Description,
- Insecure: reg.Insecure,
- Enabled: reg.Enabled,
- CreatedAt: reg.CreatedAt,
- UpdatedAt: reg.UpdatedAt,
- })
+ syncItem := containerregistry.Sync{
+ ID: reg.ID,
+ URL: reg.URL,
+ Description: reg.Description,
+ Insecure: reg.Insecure,
+ Enabled: reg.Enabled,
+ RegistryType: registryType,
+ CreatedAt: reg.CreatedAt,
+ UpdatedAt: reg.UpdatedAt,
+ }
+
+ if registryType == registryTypeECR {
+ decryptedSecret, err := crypto.Decrypt(reg.AWSSecretAccessKey)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to decrypt ECR secret for sync", "registryID", reg.ID, "registryURL", reg.URL, "error", err.Error())
+ continue
+ }
+
+ syncItem.AWSAccessKeyID = reg.AWSAccessKeyID
+ syncItem.AWSSecretAccessKey = decryptedSecret
+ syncItem.AWSRegion = reg.AWSRegion
+ } else {
+ decryptedToken, err := crypto.Decrypt(reg.Token)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to decrypt registry token for sync", "registryID", reg.ID, "registryURL", reg.URL, "error", err.Error())
+ continue
+ }
+
+ syncItem.Username = reg.Username
+ syncItem.Token = decryptedToken
+ }
+
+ syncItems = append(syncItems, syncItem)
}
// Prepare the sync request
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index e4f607da9..793630637 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -96,13 +96,40 @@ func createTestRegistry(t *testing.T, db *database.DB, id string) {
CreatedAt: now,
UpdatedAt: &now,
},
- URL: "registry.example.com",
- Username: "registry-user",
- Token: encryptedToken,
- Enabled: true,
- Insecure: false,
- CreatedAt: now,
- UpdatedAt: now,
+ URL: "registry.example.com",
+ Username: "registry-user",
+ Token: encryptedToken,
+ Enabled: true,
+ Insecure: false,
+ RegistryType: registryTypeGeneric,
+ CreatedAt: now,
+ UpdatedAt: now,
+ }
+
+ require.NoError(t, db.WithContext(context.Background()).Create(registry).Error)
+}
+
+func createTestECRRegistry(t *testing.T, db *database.DB, id string) {
+ t.Helper()
+
+ encryptedSecret, err := crypto.Encrypt("aws-secret")
+ require.NoError(t, err)
+
+ now := time.Now()
+ registry := &models.ContainerRegistry{
+ BaseModel: models.BaseModel{
+ ID: id,
+ CreatedAt: now,
+ UpdatedAt: &now,
+ },
+ URL: "123456789012.dkr.ecr.us-east-1.amazonaws.com",
+ Enabled: true,
+ RegistryType: registryTypeECR,
+ AWSAccessKeyID: "AKIA1234567890EXAMPLE",
+ AWSSecretAccessKey: encryptedSecret,
+ AWSRegion: "us-east-1",
+ CreatedAt: now,
+ UpdatedAt: now,
}
require.NoError(t, db.WithContext(context.Background()).Create(registry).Error)
@@ -161,6 +188,42 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemo
require.EqualValues(t, 1, env2Calls.Load())
}
+func TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *testing.T) {
+ ctx := context.Background()
+ db := setupEnvironmentServiceTestDB(t)
+ svc := NewEnvironmentService(db, nil, nil, nil, nil)
+
+ createTestECRRegistry(t, db, "reg-ecr")
+
+ token := "token-1"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodPost, r.Method)
+ require.Equal(t, "/api/container-registries/sync", r.URL.Path)
+
+ var syncReq containerregistry.SyncRequest
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq))
+ require.Len(t, syncReq.Registries, 1)
+
+ registry := syncReq.Registries[0]
+ require.Equal(t, registryTypeECR, registry.RegistryType)
+ require.Equal(t, "123456789012.dkr.ecr.us-east-1.amazonaws.com", registry.URL)
+ require.Equal(t, "AKIA1234567890EXAMPLE", registry.AWSAccessKeyID)
+ require.Equal(t, "aws-secret", registry.AWSSecretAccessKey)
+ require.Equal(t, "us-east-1", registry.AWSRegion)
+ require.Empty(t, registry.Username)
+ require.Empty(t, registry.Token)
+
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":{"message":"ok"}}`))
+ }))
+ defer server.Close()
+
+ createTestEnvironment(t, db, "env-1", server.URL, &token)
+
+ err := svc.SyncRegistriesToEnvironment(ctx, "env-1")
+ require.NoError(t, err)
+}
+
func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SkipsRemoteWithoutAccessToken(t *testing.T) {
ctx := context.Background()
db := setupEnvironmentServiceTestDB(t)
diff --git a/backend/internal/services/image_service_test.go b/backend/internal/services/image_service_test.go
index 56af7d648..a55c61ece 100644
--- a/backend/internal/services/image_service_test.go
+++ b/backend/internal/services/image_service_test.go
@@ -80,10 +80,11 @@ func createTestPullRegistry(t *testing.T, db *database.DB, url, username, token
require.NoError(t, err)
reg := &models.ContainerRegistry{
- URL: url,
- Username: username,
- Token: encryptedToken,
- Enabled: true,
+ URL: url,
+ Username: username,
+ Token: encryptedToken,
+ Enabled: true,
+ RegistryType: registryTypeGeneric,
}
require.NoError(t, db.WithContext(context.Background()).Create(reg).Error)
}
diff --git a/backend/resources/migrations/postgres/039_add_ecr_registry_support.down.sql b/backend/resources/migrations/postgres/039_add_ecr_registry_support.down.sql
new file mode 100644
index 000000000..bba8d4964
--- /dev/null
+++ b/backend/resources/migrations/postgres/039_add_ecr_registry_support.down.sql
@@ -0,0 +1,6 @@
+ALTER TABLE container_registries DROP COLUMN IF EXISTS registry_type;
+ALTER TABLE container_registries DROP COLUMN IF EXISTS aws_access_key_id;
+ALTER TABLE container_registries DROP COLUMN IF EXISTS aws_secret_access_key;
+ALTER TABLE container_registries DROP COLUMN IF EXISTS aws_region;
+ALTER TABLE container_registries DROP COLUMN IF EXISTS ecr_token;
+ALTER TABLE container_registries DROP COLUMN IF EXISTS ecr_token_generated_at;
diff --git a/backend/resources/migrations/postgres/039_add_ecr_registry_support.up.sql b/backend/resources/migrations/postgres/039_add_ecr_registry_support.up.sql
new file mode 100644
index 000000000..ba3f1f191
--- /dev/null
+++ b/backend/resources/migrations/postgres/039_add_ecr_registry_support.up.sql
@@ -0,0 +1,6 @@
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS registry_type TEXT NOT NULL DEFAULT 'generic';
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS aws_access_key_id TEXT;
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS aws_secret_access_key TEXT;
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS aws_region TEXT;
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS ecr_token TEXT;
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS ecr_token_generated_at TIMESTAMPTZ;
diff --git a/backend/resources/migrations/sqlite/039_add_ecr_registry_support.down.sql b/backend/resources/migrations/sqlite/039_add_ecr_registry_support.down.sql
new file mode 100644
index 000000000..01840f457
--- /dev/null
+++ b/backend/resources/migrations/sqlite/039_add_ecr_registry_support.down.sql
@@ -0,0 +1,24 @@
+-- Use create-copy-drop-rename to remove ECR columns in SQLite
+-- (SQLite lacks DROP COLUMN IF EXISTS).
+DROP TABLE IF EXISTS container_registries_old;
+
+CREATE TABLE container_registries_old (
+ id TEXT PRIMARY KEY,
+ url TEXT NOT NULL,
+ username TEXT NOT NULL,
+ token TEXT NOT NULL,
+ description TEXT,
+ insecure BOOLEAN NOT NULL DEFAULT false,
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+INSERT INTO container_registries_old (id, url, username, token, description, insecure, enabled, created_at, updated_at)
+SELECT id, url, username, token, description, insecure, enabled, created_at, updated_at
+FROM container_registries;
+
+DROP TABLE container_registries;
+ALTER TABLE container_registries_old RENAME TO container_registries;
+
+CREATE INDEX IF NOT EXISTS idx_container_registries_enabled ON container_registries(enabled);
diff --git a/backend/resources/migrations/sqlite/039_add_ecr_registry_support.up.sql b/backend/resources/migrations/sqlite/039_add_ecr_registry_support.up.sql
new file mode 100644
index 000000000..405e2dc0a
--- /dev/null
+++ b/backend/resources/migrations/sqlite/039_add_ecr_registry_support.up.sql
@@ -0,0 +1,30 @@
+-- Use create-copy-drop-rename for idempotent column additions in SQLite
+-- (SQLite lacks ADD COLUMN IF NOT EXISTS).
+DROP TABLE IF EXISTS container_registries_new;
+
+CREATE TABLE container_registries_new (
+ id TEXT PRIMARY KEY,
+ url TEXT NOT NULL,
+ username TEXT NOT NULL,
+ token TEXT NOT NULL,
+ description TEXT,
+ insecure BOOLEAN NOT NULL DEFAULT false,
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ registry_type TEXT NOT NULL DEFAULT 'generic',
+ aws_access_key_id TEXT,
+ aws_secret_access_key TEXT,
+ aws_region TEXT,
+ ecr_token TEXT,
+ ecr_token_generated_at DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+INSERT INTO container_registries_new (id, url, username, token, description, insecure, enabled, created_at, updated_at)
+SELECT id, url, username, token, description, insecure, enabled, created_at, updated_at
+FROM container_registries;
+
+DROP TABLE container_registries;
+ALTER TABLE container_registries_new RENAME TO container_registries;
+
+CREATE INDEX IF NOT EXISTS idx_container_registries_enabled ON container_registries(enabled);
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 3d1111578..fada831a9 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1325,6 +1325,18 @@
"registry_github_container_registry": "GitHub Container Registry",
"registry_google_container_registry": "Google Container Registry",
"registry_quay_io": "Quay.io Registry",
+ "registry_amazon_ecr": "Amazon ECR",
+ "registries_type_label": "Registry Type",
+ "registries_type_generic": "Generic (Docker / OCI)",
+ "registries_type_ecr": "Amazon ECR",
+ "registries_username_key_label": "Username/Key",
+ "registries_aws_access_key_id_required": "AWS Access Key ID is required for ECR registries",
+ "registries_aws_region_required": "AWS Region is required for ECR registries",
+ "registries_aws_secret_access_key_required": "AWS Secret Access Key is required for ECR registries",
+ "registries_aws_access_key_id": "AWS Access Key ID",
+ "registries_aws_secret_access_key": "AWS Secret Access Key",
+ "registries_aws_region": "AWS Region",
+ "registries_aws_region_placeholder": "e.g. us-east-1",
"registry_docker_hub_url": "docker.io",
"registry_github_url": "ghcr.io",
"registry_google_url": "gcr.io",
diff --git a/frontend/src/lib/components/sheets/container-registry-sheet.svelte b/frontend/src/lib/components/sheets/container-registry-sheet.svelte
index 099af3e4b..ef3abff91 100644
--- a/frontend/src/lib/components/sheets/container-registry-sheet.svelte
+++ b/frontend/src/lib/components/sheets/container-registry-sheet.svelte
@@ -3,13 +3,16 @@
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import FormInput from '$lib/components/form/form-input.svelte';
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
- import { Spinner } from '$lib/components/ui/spinner/index.js';
- import type { ContainerRegistry } from '$lib/types/container-registry.type';
- import type { ContainerRegistryCreateDto, ContainerRegistryUpdateDto } from '$lib/types/container-registry.type';
+ import SelectWithLabel from '$lib/components/form/select-with-label.svelte';
+ import type {
+ ContainerRegistry,
+ ContainerRegistryCreateDto,
+ ContainerRegistryUpdateDto,
+ RegistryType
+ } from '$lib/types/container-registry.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import { m } from '$lib/paraglide/messages';
- import { RegistryIcon } from '$lib/icons';
type ContainerRegistryFormProps = {
open: boolean;
@@ -22,26 +25,67 @@
let isEditMode = $derived(!!registryToEdit);
- const formSchema = z.object({
- url: z.string().min(1, m.registries_url_required()),
- username: z.string().min(1, m.common_username_required()),
- token: z.string().optional(),
- description: z.string().optional(),
- insecure: z.boolean().default(false),
- enabled: z.boolean().default(true)
- });
+ const registryTypeOptions = [
+ { value: 'generic', label: m.registries_type_generic() },
+ { value: 'ecr', label: m.registries_type_ecr() }
+ ];
+
+ const formSchema = z
+ .object({
+ registryType: z.enum(['generic', 'ecr']).default('generic'),
+ url: z.string().min(1, m.registries_url_required()),
+ username: z.string().optional(),
+ token: z.string().optional(),
+ description: z.string().optional(),
+ insecure: z.boolean().default(false),
+ enabled: z.boolean().default(true),
+ awsAccessKeyId: z.string().optional(),
+ awsSecretAccessKey: z.string().optional(),
+ awsRegion: z.string().optional()
+ })
+ .superRefine((data, ctx) => {
+ if (data.registryType === 'ecr') {
+ if (!data.awsAccessKeyId?.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: m.registries_aws_access_key_id_required(),
+ path: ['awsAccessKeyId']
+ });
+ }
+ if (!data.awsRegion?.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: m.registries_aws_region_required(),
+ path: ['awsRegion']
+ });
+ }
+ if (!isEditMode && !data.awsSecretAccessKey?.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: m.registries_aws_secret_access_key_required(),
+ path: ['awsSecretAccessKey']
+ });
+ }
+ }
+ });
let formData = $derived({
+ registryType: (open && registryToEdit ? (registryToEdit.registryType ?? 'generic') : 'generic') as RegistryType,
url: open && registryToEdit ? registryToEdit.url : '',
username: open && registryToEdit ? registryToEdit.username : '',
token: '',
description: open && registryToEdit ? registryToEdit.description || '' : '',
insecure: open && registryToEdit ? (registryToEdit.insecure ?? false) : false,
- enabled: open && registryToEdit ? (registryToEdit.enabled ?? true) : true
+ enabled: open && registryToEdit ? (registryToEdit.enabled ?? true) : true,
+ awsAccessKeyId: open && registryToEdit ? (registryToEdit.awsAccessKeyId ?? '') : '',
+ awsSecretAccessKey: '',
+ awsRegion: open && registryToEdit ? (registryToEdit.awsRegion ?? '') : ''
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+ let isECR = $derived($inputs.registryType.value === 'ecr');
+
function handleSubmit() {
const data = form.validate();
if (!data) return;
@@ -66,6 +110,13 @@
>
{#snippet children()}
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
+ <SelectWithLabel
+ id="registryTypeSelect"
+ label={m.registries_type_label()}
+ options={registryTypeOptions}
+ bind:value={$inputs.registryType.value}
+ />
+
<FormInput
label={m.registries_url()}
type="text"
@@ -73,19 +124,37 @@
description={m.registries_url_description()}
bind:input={$inputs.url}
/>
- <FormInput
- label={m.common_username()}
- type="text"
- description={m.common_username_required()}
- bind:input={$inputs.username}
- />
- <FormInput
- label={m.registries_token_label()}
- type="password"
- placeholder={isEditMode ? m.registries_token_keep_placeholder() : m.registries_token_placeholder()}
- description={m.registries_token_description()}
- bind:input={$inputs.token}
- />
+
+ {#if !isECR}
+ <FormInput
+ label={m.common_username()}
+ type="text"
+ description={m.common_username_required()}
+ bind:input={$inputs.username}
+ />
+ <FormInput
+ label={m.registries_token_label()}
+ type="password"
+ placeholder={isEditMode ? m.registries_token_keep_placeholder() : m.registries_token_placeholder()}
+ description={m.registries_token_description()}
+ bind:input={$inputs.token}
+ />
+ {:else}
+ <FormInput label={m.registries_aws_access_key_id()} type="text" bind:input={$inputs.awsAccessKeyId} />
+ <FormInput
+ label={m.registries_aws_secret_access_key()}
+ type="password"
+ placeholder={isEditMode ? m.registries_token_keep_placeholder() : ''}
+ bind:input={$inputs.awsSecretAccessKey}
+ />
+ <FormInput
+ label={m.registries_aws_region()}
+ type="text"
+ placeholder={m.registries_aws_region_placeholder()}
+ bind:input={$inputs.awsRegion}
+ />
+ {/if}
+
<FormInput
label={m.common_description()}
type="text"
@@ -98,12 +167,14 @@
description={m.registries_enabled_description()}
bind:checked={$inputs.enabled.value}
/>
- <SwitchWithLabel
- id="insecureSwitch"
- label={m.registries_allow_insecure_label()}
- description={m.registries_allow_insecure_description()}
- bind:checked={$inputs.insecure.value}
- />
+ {#if !isECR}
+ <SwitchWithLabel
+ id="insecureSwitch"
+ label={m.registries_allow_insecure_label()}
+ description={m.registries_allow_insecure_description()}
+ bind:checked={$inputs.insecure.value}
+ />
+ {/if}
</form>
{/snippet}
diff --git a/frontend/src/lib/types/container-registry.type.ts b/frontend/src/lib/types/container-registry.type.ts
index 55a063e14..7c09d15db 100644
--- a/frontend/src/lib/types/container-registry.type.ts
+++ b/frontend/src/lib/types/container-registry.type.ts
@@ -1,10 +1,16 @@
+export type RegistryType = 'generic' | 'ecr';
+
export interface ContainerRegistryCreateDto {
url: string;
- username: string;
- token: string;
+ username?: string;
+ token?: string;
description?: string;
insecure?: boolean;
enabled?: boolean;
+ registryType?: RegistryType;
+ awsAccessKeyId?: string;
+ awsSecretAccessKey?: string;
+ awsRegion?: string;
}
export interface ContainerRegistryUpdateDto {
@@ -14,6 +20,10 @@ export interface ContainerRegistryUpdateDto {
description?: string;
insecure?: boolean;
enabled?: boolean;
+ registryType?: RegistryType;
+ awsAccessKeyId?: string;
+ awsSecretAccessKey?: string;
+ awsRegion?: string;
}
export interface ContainerRegistry {
@@ -24,6 +34,9 @@ export interface ContainerRegistry {
description?: string;
insecure?: boolean;
enabled?: boolean;
+ registryType?: RegistryType;
+ awsAccessKeyId?: string;
+ awsRegion?: string;
createdAt?: string;
updatedAt?: string;
}
diff --git a/frontend/src/routes/(app)/customize/registries/registry-table.svelte b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
index d86219c97..ab1bf319f 100644
--- a/frontend/src/routes/(app)/customize/registries/registry-table.svelte
+++ b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
@@ -32,7 +32,15 @@
let removingId = $state<string | null>(null);
let testingId = $state<string | null>(null);
- function getRegistryDisplayName(url: string) {
+ function maskAccessKeyId(keyId: string | undefined): string {
+ if (!keyId) return m.common_na();
+ if (keyId.length <= 4) return keyId;
+ return '*'.repeat(11) + keyId.slice(-4);
+ }
+
+ function getRegistryDisplayName(item: ContainerRegistry) {
+ if (item.registryType === 'ecr') return m.registry_amazon_ecr();
+ const url = item.url;
if (!url || url === 'docker.io') return m.registry_docker_hub();
if (url.includes('ghcr.io')) return m.registry_github_container_registry();
if (url.includes('gcr.io')) return m.registry_google_container_registry();
@@ -130,7 +138,7 @@
},
{
accessorKey: 'username',
- title: m.common_username(),
+ title: m.registries_username_key_label(),
sortable: true,
cell: UsernameCell
},
@@ -156,7 +164,7 @@
const mobileFields = [
{ id: 'id', label: m.common_id(), defaultVisible: false },
- { id: 'username', label: m.common_username(), defaultVisible: true },
+ { id: 'username', label: m.registries_username_key_label(), defaultVisible: true },
{ id: 'description', label: m.common_description(), defaultVisible: true },
{ id: 'enabled', label: m.common_status(), defaultVisible: true },
{ id: 'createdAt', label: m.common_created(), defaultVisible: true }
@@ -184,12 +192,16 @@
{#snippet UrlCell({ item }: { item: ContainerRegistry })}
<div class="flex flex-col">
<span class="font-medium">{item.url || 'docker.io'}</span>
- <span class="text-muted-foreground text-xs">{getRegistryDisplayName(item.url)}</span>
+ <span class="text-muted-foreground text-xs">{getRegistryDisplayName(item)}</span>
</div>
{/snippet}
-{#snippet UsernameCell({ value }: { value: unknown })}
- <span class="font-mono text-sm">{String(value ?? m.common_na())}</span>
+{#snippet UsernameCell({ item }: { item: ContainerRegistry })}
+ {#if item.registryType === 'ecr'}
+ <span class="font-mono text-sm">{maskAccessKeyId(item.awsAccessKeyId)}</span>
+ {:else}
+ <span class="font-mono text-sm">{String(item.username ?? m.common_na())}</span>
+ {/if}
{/snippet}
{#snippet DescriptionCell({ value }: { value: unknown })}
@@ -220,11 +232,14 @@
badges={[{ variant: 'purple' as const, text: m.common_registry() }]}
fields={[
{
- label: m.common_username(),
- getValue: (item: ContainerRegistry) => item.username,
+ label: item.registryType === 'ecr' ? m.registries_username_key_label() : m.common_username(),
+ getValue: (item: ContainerRegistry) =>
+ item.registryType === 'ecr' ? maskAccessKeyId(item.awsAccessKeyId) : item.username,
icon: UserIcon,
iconVariant: 'gray' as const,
- show: (mobileFieldVisibility.username ?? true) && item.username !== undefined
+ show:
+ (mobileFieldVisibility.username ?? true) &&
+ (item.registryType === 'ecr' ? !!item.awsAccessKeyId : item.username !== undefined)
},
{
label: m.common_description(),
diff --git a/types/containerregistry/container_registry.go b/types/containerregistry/container_registry.go
index 63125d4f4..473ddc19d 100644
--- a/types/containerregistry/container_registry.go
+++ b/types/containerregistry/container_registry.go
@@ -34,6 +34,21 @@ type ContainerRegistry struct {
// Required: true
Enabled bool `json:"enabled"`
+ // RegistryType indicates the type of registry (generic, ecr).
+ //
+ // Required: true
+ RegistryType string `json:"registryType"`
+
+ // AWSAccessKeyID is the AWS Access Key ID for ECR registries.
+ //
+ // Required: false
+ AWSAccessKeyID string `json:"awsAccessKeyId,omitempty"`
+
+ // AWSRegion is the AWS region for ECR registries.
+ //
+ // Required: false
+ AWSRegion string `json:"awsRegion,omitempty"`
+
// CreatedAt is the date and time at which the registry was created.
//
// Required: true
@@ -59,12 +74,12 @@ type Sync struct {
// Username for authentication with the container registry.
//
// Required: true
- Username string `json:"username" binding:"required"`
+ Username string `json:"username"`
// Token for authentication with the container registry.
//
// Required: true
- Token string `json:"token" binding:"required"`
+ Token string `json:"token"`
// Description of the container registry.
//
@@ -81,6 +96,27 @@ type Sync struct {
// Required: true
Enabled bool `json:"enabled"`
+ // RegistryType indicates the type of registry (generic, ecr).
+ //
+ // Required: true
+ RegistryType string `json:"registryType"`
+
+ // AWSAccessKeyID is the AWS Access Key ID for ECR registries.
+ //
+ // Required: false
+ AWSAccessKeyID string `json:"awsAccessKeyId,omitempty"`
+
+ // AWSSecretAccessKey is the AWS Secret Access Key for ECR registries.
+ // Sent decrypted between manager and agent for sync purposes.
+ //
+ // Required: false
+ AWSSecretAccessKey string `json:"awsSecretAccessKey,omitempty"`
+
+ // AWSRegion is the AWS region for ECR registries.
+ //
+ // Required: false
+ AWSRegion string `json:"awsRegion,omitempty"`
+
// CreatedAt is the date and time at which the registry was created.
//
// Required: true