Skip to content

Modern Docker Management, Designed for Everyone

feat: simplify build registry image references (#3243)

trae.lib10cbc772c4a
diff --git a/backend/internal/models/container_registry.go b/backend/internal/models/container_registry.go
index 5495d0182..0600d0eed 100644
--- a/backend/internal/models/container_registry.go
+++ b/backend/internal/models/container_registry.go
@@ -7,20 +7,21 @@ import (
type ContainerRegistry struct {
BaseModel
- URL string `json:"url" sortable:"true"`
- Username string `json:"username" sortable:"true"`
- Token string `json:"token"`
- Description *string `json:"description,omitempty" sortable:"true"`
- Insecure bool `json:"insecure" sortable:"true"`
- Enabled bool `json:"enabled" sortable:"true"`
- RegistryType string `json:"registryType" sortable:"true"`
- AWSAccessKeyID string `json:"awsAccessKeyId"`
- AWSSecretAccessKey string `json:"awsSecretAccessKey"`
- AWSRegion string `json:"awsRegion"`
- ECRToken string `json:"ecrToken"`
- ECRTokenGeneratedAt *time.Time `json:"ecrTokenGeneratedAt"`
- CreatedAt time.Time `json:"createdAt" sortable:"true"`
- UpdatedAt time.Time `json:"updatedAt" sortable:"true"`
+ URL string `json:"url" sortable:"true"`
+ Username string `json:"username" sortable:"true"`
+ Token string `json:"token"`
+ Description *string `json:"description,omitempty" sortable:"true"`
+ Insecure bool `json:"insecure" sortable:"true"`
+ Enabled bool `json:"enabled" sortable:"true"`
+ RegistryType string `json:"registryType" sortable:"true"`
+ RepositoryNames StringSlice `json:"repositoryNames" gorm:"column:repository_names;type:text;not null;default:'[]'"`
+ AWSAccessKeyID string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey string `json:"awsSecretAccessKey"`
+ AWSRegion string `json:"awsRegion"`
+ ECRToken string `json:"ecrToken"`
+ ECRTokenGeneratedAt *time.Time `json:"ecrTokenGeneratedAt"`
+ CreatedAt time.Time `json:"createdAt" sortable:"true"`
+ UpdatedAt time.Time `json:"updatedAt" sortable:"true"`
}
func (ContainerRegistry) TableName() string {
@@ -28,27 +29,29 @@ func (ContainerRegistry) TableName() string {
}
type CreateContainerRegistryRequest struct {
- URL string `json:"url" binding:"required"`
- Username string `json:"username"`
- Token string `json:"token"`
- Description *string `json:"description"`
- Insecure *bool `json:"insecure"`
- Enabled *bool `json:"enabled"`
- RegistryType string `json:"registryType"`
- AWSAccessKeyID string `json:"awsAccessKeyId"`
- AWSSecretAccessKey string `json:"awsSecretAccessKey"`
- AWSRegion string `json:"awsRegion"`
+ URL string `json:"url" binding:"required"`
+ Username string `json:"username"`
+ Token string `json:"token"`
+ Description *string `json:"description"`
+ Insecure *bool `json:"insecure"`
+ Enabled *bool `json:"enabled"`
+ RegistryType string `json:"registryType"`
+ RepositoryNames []string `json:"repositoryNames"`
+ AWSAccessKeyID string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey string `json:"awsSecretAccessKey"`
+ AWSRegion string `json:"awsRegion"`
}
type UpdateContainerRegistryRequest struct {
- URL *string `json:"url"`
- Username *string `json:"username"`
- Token *string `json:"token"`
- Description *string `json:"description"`
- Insecure *bool `json:"insecure"`
- Enabled *bool `json:"enabled"`
- RegistryType *string `json:"registryType"`
- AWSAccessKeyID *string `json:"awsAccessKeyId"`
- AWSSecretAccessKey *string `json:"awsSecretAccessKey"`
- AWSRegion *string `json:"awsRegion"`
+ URL *string `json:"url"`
+ Username *string `json:"username"`
+ Token *string `json:"token"`
+ Description *string `json:"description"`
+ Insecure *bool `json:"insecure"`
+ Enabled *bool `json:"enabled"`
+ RegistryType *string `json:"registryType"`
+ RepositoryNames *[]string `json:"repositoryNames"`
+ AWSAccessKeyID *string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey *string `json:"awsSecretAccessKey"`
+ AWSRegion *string `json:"awsRegion"`
}
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index f231853a7..f473064da 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/cenkalti/backoff/v5"
+ ref "github.com/distribution/reference"
"github.com/samber/hot"
"github.com/samber/mo"
"golang.org/x/sync/singleflight"
@@ -174,15 +175,20 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req model
if err != nil {
return nil, err
}
+ repositoryNames, err := normalizeRepositoryNamesInternal(req.RepositoryNames)
+ if err != nil {
+ return nil, err
+ }
registryRecord := &models.ContainerRegistry{
- 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(),
+ URL: req.URL,
+ Description: req.Description,
+ Insecure: req.Insecure != nil && *req.Insecure,
+ Enabled: req.Enabled == nil || *req.Enabled,
+ RegistryType: registryType,
+ RepositoryNames: repositoryNames,
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
}
if registryType == registryTypeECR {
@@ -263,6 +269,15 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
utils.ApplyChanged(&registryRecord.Insecure, mo.PointerToOption(req.Insecure))
utils.ApplyChanged(&registryRecord.Enabled, mo.PointerToOption(req.Enabled))
+ // RepositoryNames: nil pointer means "don't touch"; empty slice means "clear".
+ if req.RepositoryNames != nil {
+ repositoryNames, err := normalizeRepositoryNamesInternal(*req.RepositoryNames)
+ if err != nil {
+ return nil, err
+ }
+ registryRecord.RepositoryNames = repositoryNames
+ }
+
if registryRecord.RegistryType == registryTypeECR {
if err := s.updateECRRegistryFieldsInternal(registryRecord, req); err != nil {
return nil, err
@@ -1192,6 +1207,14 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item contain
needsUpdate = utils.ApplyChanged(&existing.Insecure, mo.Some(item.Insecure)) || needsUpdate
needsUpdate = utils.ApplyChanged(&existing.Enabled, mo.Some(item.Enabled)) || needsUpdate
+ // Normalizing first gives the manager and the local copy the same
+ // representation, so the comparison below only reports real changes.
+ repositoryNames, err := normalizeRepositoryNamesInternal(item.RepositoryNames)
+ if err != nil {
+ return false, err
+ }
+ needsUpdate = utils.ApplySliceChanged(&existing.RepositoryNames, mo.Some(repositoryNames)) || needsUpdate
+
// Clear stale credentials when registry type changes during sync
if newType != existing.RegistryType {
if newType == registryTypeECR {
@@ -1250,20 +1273,25 @@ func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.Context
if err != nil {
return err
}
+ repositoryNames, err := normalizeRepositoryNamesInternal(item.RepositoryNames)
+ if err != nil {
+ return err
+ }
newRegistry := &models.ContainerRegistry{
BaseModel: models.BaseModel{
ID: item.ID,
},
- 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(),
+ URL: item.URL,
+ Description: item.Description,
+ Insecure: item.Insecure,
+ Enabled: item.Enabled,
+ RegistryType: registryType,
+ RepositoryNames: repositoryNames,
+ AWSAccessKeyID: item.AWSAccessKeyID,
+ AWSRegion: item.AWSRegion,
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
}
if registryType == registryTypeGeneric {
@@ -1303,6 +1331,24 @@ func normalizeRegistryTypeInternal(value string) (string, error) {
}
}
+// normalizeRepositoryNamesInternal trims, filters and deduplicates the given
+// entries (preserving first-occurrence order) and validates what remains. It
+// returns a non-nil slice so that GORM always serializes to a JSON array.
+func normalizeRepositoryNamesInternal(raw []string) (models.StringSlice, error) {
+ names := utils.UniqueNonEmptyStrings(raw)
+ result := make(models.StringSlice, 0, len(names))
+ for _, name := range names {
+ // A repository name is only a path, so pair it with placeholder domain
+ // and tag segments to validate it against the reference grammar.
+ if _, err := ref.ParseNormalizedNamed("registry.invalid/" + name + "/placeholder:latest"); err != nil {
+ return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("invalid repository name %q", name), "field", "repositoryNames"))
+ }
+ result = append(result, name)
+ }
+
+ return result, nil
+}
+
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 d53515f9c..9345875e5 100644
--- a/backend/internal/services/container_registry_service_test.go
+++ b/backend/internal/services/container_registry_service_test.go
@@ -12,6 +12,7 @@ import (
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
dockerregistry "github.com/moby/moby/api/types/registry"
@@ -1043,3 +1044,71 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthori
assert.Contains(t, err.Error(), "status: 401")
assert.Contains(t, err.Error(), "failed to load enabled registries")
}
+
+func createRegistryWithRepositoryNames(t *testing.T, svc *ContainerRegistryService, repositoryNames ...string) *models.ContainerRegistry {
+ t.Helper()
+
+ registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{
+ URL: "https://registry.example.com",
+ Username: "my-user",
+ Token: "my-token",
+ RepositoryNames: repositoryNames,
+ })
+ require.NoError(t, err)
+
+ return registry
+}
+
+func fetchRegistry(t *testing.T, db *database.DB, id string) models.ContainerRegistry {
+ t.Helper()
+
+ var fetched models.ContainerRegistry
+ require.NoError(t, db.WithContext(context.Background()).First(&fetched, "id = ?", id).Error)
+
+ return fetched
+}
+
+func TestContainerRegistryService_CreateRegistry_NormalizesAndPersistsRepositoryNames(t *testing.T) {
+ _, db := setupImageServiceAuthTest(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+
+ // Entries are trimmed, empties dropped and duplicates removed while
+ // preserving first-occurrence order.
+ registry := createRegistryWithRepositoryNames(t, svc, " team ", "", "team", "team/platform", " team ")
+ assert.Equal(t, models.StringSlice{"team", "team/platform"}, registry.RepositoryNames)
+ assert.Equal(t, models.StringSlice{"team", "team/platform"}, fetchRegistry(t, db, registry.ID).RepositoryNames)
+}
+
+func TestContainerRegistryService_CreateRegistry_RejectsInvalidRepositoryName(t *testing.T) {
+ _, db := setupImageServiceAuthTest(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+
+ _, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{
+ URL: "https://registry.example.com",
+ RepositoryNames: []string{"team:latest"},
+ })
+ require.ErrorIs(t, err, common.ErrValidation)
+ assert.Contains(t, errors.GetDetails(err), "repositoryNames")
+}
+
+func TestContainerRegistryService_UpdateRegistry_RepositoryNamesPointerSemantics(t *testing.T) {
+ _, db := setupImageServiceAuthTest(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+
+ registry := createRegistryWithRepositoryNames(t, svc, "team", "team/platform")
+
+ // A nil pointer leaves the existing names untouched.
+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{
+ Username: new("updated-user"),
+ })
+ require.NoError(t, err)
+ assert.Equal(t, models.StringSlice{"team", "team/platform"}, updated.RepositoryNames)
+
+ // An empty slice clears them.
+ updated, err = svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{
+ RepositoryNames: &[]string{},
+ })
+ require.NoError(t, err)
+ assert.Empty(t, updated.RepositoryNames)
+ assert.Empty(t, fetchRegistry(t, db, registry.ID).RepositoryNames)
+}
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 125fc42a9..260df93b1 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -2160,14 +2160,15 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en
}
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,
+ ID: reg.ID,
+ URL: reg.URL,
+ Description: reg.Description,
+ Insecure: reg.Insecure,
+ Enabled: reg.Enabled,
+ RegistryType: registryType,
+ RepositoryNames: reg.RepositoryNames,
+ CreatedAt: reg.CreatedAt,
+ UpdatedAt: reg.UpdatedAt,
}
if registryType == registryTypeECR {
diff --git a/backend/pkg/utils/update_value_util.go b/backend/pkg/utils/update_value_util.go
index 89637ce94..5fd7b1725 100644
--- a/backend/pkg/utils/update_value_util.go
+++ b/backend/pkg/utils/update_value_util.go
@@ -1,6 +1,10 @@
package utils
-import "github.com/samber/mo"
+import (
+ "slices"
+
+ "github.com/samber/mo"
+)
// ApplyChanged updates target when value is present and differs from the current value.
func ApplyChanged[T comparable](target *T, value mo.Option[T]) bool {
@@ -13,6 +17,18 @@ func ApplyChanged[T comparable](target *T, value mo.Option[T]) bool {
return true
}
+// ApplySliceChanged updates target when value is present and its elements differ
+// from the current slice. Nil and empty slices are treated as equal.
+func ApplySliceChanged[S ~[]E, E comparable](target *S, value mo.Option[S]) bool {
+ next, ok := value.Get()
+ if !ok || slices.Equal(*target, next) {
+ return false
+ }
+
+ *target = next
+ return true
+}
+
// ApplyNullable updates target to the optional value when it differs from the current value.
func ApplyNullable[T comparable](target **T, value mo.Option[T]) bool {
if mo.PointerToOption(*target) == value {
diff --git a/backend/pkg/utils/update_value_util_test.go b/backend/pkg/utils/update_value_util_test.go
index 8de7d87f4..bfaf174b1 100644
--- a/backend/pkg/utils/update_value_util_test.go
+++ b/backend/pkg/utils/update_value_util_test.go
@@ -17,6 +17,17 @@ func TestApplyChanged(t *testing.T) {
assert.Equal(t, "new", target)
}
+func TestApplySliceChanged(t *testing.T) {
+ target := []string{"a"}
+
+ assert.True(t, ApplySliceChanged(&target, mo.Some([]string{"a", "b"})))
+ assert.Equal(t, []string{"a", "b"}, target)
+ assert.False(t, ApplySliceChanged(&target, mo.Some([]string{"a", "b"})))
+ assert.False(t, ApplySliceChanged(&target, mo.None[[]string]()))
+ assert.True(t, ApplySliceChanged(&target, mo.Some([]string{})))
+ assert.False(t, ApplySliceChanged(&target, mo.Some[[]string](nil)))
+}
+
func TestApplyNullable(t *testing.T) {
target := new("initial")
diff --git a/backend/resources/migrations/postgres/069_add_container_registry_repository_names.sql b/backend/resources/migrations/postgres/069_add_container_registry_repository_names.sql
new file mode 100644
index 000000000..29167ab7f
--- /dev/null
+++ b/backend/resources/migrations/postgres/069_add_container_registry_repository_names.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE container_registries ADD COLUMN IF NOT EXISTS repository_names TEXT NOT NULL DEFAULT '[]';
+
+-- +goose Down
+ALTER TABLE container_registries DROP COLUMN IF EXISTS repository_names;
diff --git a/backend/resources/migrations/sqlite/069_add_container_registry_repository_names.sql b/backend/resources/migrations/sqlite/069_add_container_registry_repository_names.sql
new file mode 100644
index 000000000..e05f3755a
--- /dev/null
+++ b/backend/resources/migrations/sqlite/069_add_container_registry_repository_names.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE container_registries ADD COLUMN repository_names TEXT NOT NULL DEFAULT '[]';
+
+-- +goose Down
+ALTER TABLE container_registries DROP COLUMN repository_names;
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 60c10a43c..2619cc6fb 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1663,6 +1663,9 @@
"registries_aws_secret_access_key": "AWS Secret Access Key",
"registries_aws_region": "AWS Region",
"registries_aws_region_placeholder": "e.g. us-east-1",
+ "registries_repository_names": "Repository Names",
+ "registries_repository_names_placeholder": "team/api\nteam/platform/api",
+ "registries_repository_names_description": "One complete repository name per line. Used when pushing images from the build page.",
"registry_docker_hub_url": "docker.io",
"registry_github_url": "ghcr.io",
"registry_google_url": "gcr.io",
@@ -2578,6 +2581,16 @@
"image_tags_placeholder": "my-image:latest",
"image_tags_description": "Comma-separated list of tags",
"image_tags_required": "At least one tag is required",
+ "tag_placeholder": "1.0.0",
+ "tag_required": "Tag is required",
+ "image_reference": "Image reference",
+ "repository_name": "Repository name",
+ "select_a_registry": "Select a registry",
+ "select_a_repository_name": "Select a repository name",
+ "repository_name_not_configured": "Select a repository name configured for this registry",
+ "registries_none_enabled": "No enabled registries. Configure one in Registry settings.",
+ "registries_no_list_permission": "No permission to list registries. Ask an administrator for access.",
+ "registries_no_repository_names": "No repository names configured for this registry. Add them in Registry settings.",
"dockerfile": "Dockerfile",
"dockerfile_description": "Path to Dockerfile (relative to context)",
"target": "Target",
diff --git a/frontend/src/lib/components/sheets/container-registry-sheet.svelte b/frontend/src/lib/components/sheets/container-registry-sheet.svelte
index 45ba5c06e..1d1fc8a78 100644
--- a/frontend/src/lib/components/sheets/container-registry-sheet.svelte
+++ b/frontend/src/lib/components/sheets/container-registry-sheet.svelte
@@ -12,6 +12,7 @@
} from '#lib/types/docker';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '#lib/utils/settings';
+ import { parseLines } from '#lib/utils/form-parsers';
import { m } from '#lib/paraglide/messages';
type ContainerRegistryFormProps = {
@@ -37,6 +38,7 @@
username: z.string().optional(),
token: z.string().optional(),
description: z.string().optional(),
+ repositoryNames: z.string().optional(),
insecure: z.boolean().default(false),
enabled: z.boolean().default(true),
awsAccessKeyId: z.string().optional(),
@@ -90,6 +92,7 @@
username: open && registryToEdit ? registryToEdit.username : '',
token: '',
description: open && registryToEdit ? registryToEdit.description || '' : '',
+ repositoryNames: open && registryToEdit ? (registryToEdit.repositoryNames?.join('\n') ?? '') : '',
insecure: open && registryToEdit ? (registryToEdit.insecure ?? false) : false,
enabled: open && registryToEdit ? (registryToEdit.enabled ?? true) : true,
awsAccessKeyId: open && registryToEdit ? (registryToEdit.awsAccessKeyId ?? '') : '',
@@ -104,7 +107,7 @@
function handleSubmit() {
const data = form.validate();
if (!data) return;
- onSubmit({ registry: data, isEditMode });
+ onSubmit({ registry: { ...data, repositoryNames: parseLines(data.repositoryNames ?? '') }, isEditMode });
}
function handleOpenChange(newOpenState: boolean) {
@@ -177,6 +180,14 @@
placeholder={m.registries_description_placeholder()}
bind:input={$inputs.description}
/>
+ <FormInput
+ label={m.registries_repository_names()}
+ type="textarea"
+ rows={3}
+ placeholder={m.registries_repository_names_placeholder()}
+ description={m.registries_repository_names_description()}
+ bind:input={$inputs.repositoryNames}
+ />
<SwitchWithLabel
id="isEnabledSwitch"
label={m.common_enabled()}
diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.ts
index 553729e5c..b7c3ea6de 100644
--- a/frontend/src/lib/types/docker.ts
+++ b/frontend/src/lib/types/docker.ts
@@ -837,6 +837,7 @@ export interface ContainerRegistryCreateDto {
insecure?: boolean;
enabled?: boolean;
registryType?: RegistryType;
+ repositoryNames?: string[];
awsAccessKeyId?: string;
awsSecretAccessKey?: string;
awsRegion?: string;
@@ -850,6 +851,7 @@ export interface ContainerRegistryUpdateDto {
insecure?: boolean;
enabled?: boolean;
registryType?: RegistryType;
+ repositoryNames?: string[];
awsAccessKeyId?: string;
awsSecretAccessKey?: string;
awsRegion?: string;
@@ -864,6 +866,7 @@ export interface ContainerRegistry {
insecure?: boolean;
enabled?: boolean;
registryType?: RegistryType;
+ repositoryNames?: string[];
awsAccessKeyId?: string;
awsRegion?: string;
createdAt?: string;
diff --git a/frontend/src/lib/utils/form-parsers.ts b/frontend/src/lib/utils/form-parsers.ts
index 2f902a0c5..edaeb4907 100644
--- a/frontend/src/lib/utils/form-parsers.ts
+++ b/frontend/src/lib/utils/form-parsers.ts
@@ -1,3 +1,21 @@
+/** Splits textarea content into trimmed, non-empty lines. */
+export function parseLines(text: string): string[] {
+ return splitAndTrim(text, '\n');
+}
+
+/** Splits newline or comma separated input into trimmed, non-empty values. */
+export function parseList(text: string): string[] {
+ return splitAndTrim(text, /[\n,]/);
+}
+
+function splitAndTrim(text: string, separator: string | RegExp): string[] {
+ if (!text) return [];
+ return text
+ .split(separator)
+ .map((value) => value.trim())
+ .filter(Boolean);
+}
+
export function parseKeyValuePairs(text: string): Record<string, string> {
if (!text?.trim()) return {};
diff --git a/frontend/src/lib/utils/registry.ts b/frontend/src/lib/utils/registry.ts
new file mode 100644
index 000000000..f6156f6c5
--- /dev/null
+++ b/frontend/src/lib/utils/registry.ts
@@ -0,0 +1,31 @@
+import { m } from '#lib/paraglide/messages';
+import type { ContainerRegistry } from '#lib/types/docker';
+
+type RegistryIdentity = Pick<ContainerRegistry, 'url' | 'registryType'>;
+
+/** Human readable name for a registry, falling back to its URL. */
+export function getRegistryDisplayName(registry: RegistryIdentity): string {
+ if (registry.registryType === 'ecr') return m.amazon_ecr();
+ const url = registry.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();
+ if (url.includes('quay.io')) return m.registry_quay_io();
+ return url;
+}
+
+/** Strips the scheme and trailing slashes so a registry URL can be used as an image host. */
+export function normalizeRegistryHost(url: string): string {
+ return url.replace(/^https?:\/\//, '').replace(/\/+$/, '');
+}
+
+/**
+ * Builds a `host/repository:tag` reference, or an empty string when the
+ * repository name or tag is missing.
+ */
+export function buildImageReference(registryUrl: string, repositoryName: string, tag: string): string {
+ const repository = repositoryName.trim();
+ const trimmedTag = tag.trim();
+ if (!repository || !trimmedTag) return '';
+ return `${normalizeRegistryHost(registryUrl)}/${repository}:${trimmedTag}`;
+}
diff --git a/frontend/src/routes/(app)/customize/registries/registry-table.svelte b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
index 141c4161a..8be84ce9d 100644
--- a/frontend/src/routes/(app)/customize/registries/registry-table.svelte
+++ b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
@@ -17,6 +17,7 @@
import { containerRegistryService } from '#lib/services/container-registry-service';
import { RegistryIcon, UserIcon, ExternalLinkIcon, EditIcon, TrashIcon, TestIcon } from '#lib/icons';
import { hasPermission } from '#lib/utils/auth';
+ import { getRegistryDisplayName } from '#lib/utils/registry';
import IfPermitted from '#lib/components/if-permitted.svelte';
let {
@@ -44,16 +45,6 @@
return '*'.repeat(11) + keyId.slice(-4);
}
- function getRegistryDisplayName(item: ContainerRegistry) {
- if (item.registryType === 'ecr') return m.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();
- if (url.includes('quay.io')) return m.registry_quay_io();
- return url;
- }
-
function formatPullUsage(item: ContainerRegistry) {
const usage = pullUsageByRegistry[item.id];
if (!usage) return m.common_unavailable();
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index eae5c695d..762b91ec6 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -39,8 +39,11 @@
import BuildWorkspacePanel from './components/build-workspace-panel.svelte';
import BuildConfigPanel from './components/build-config-panel.svelte';
import BuildOutputPanel from './components/build-output-panel.svelte';
- import type { BuildProviderOption } from './components/build-form.types';
+ import type { BuildProviderOption, SelectOption } from './components/build-form.types';
import { imageService } from '#lib/services/image-service';
+ import { containerRegistryService } from '#lib/services/container-registry-service';
+ import { buildImageReference, getRegistryDisplayName } from '#lib/utils/registry';
+ import { parseList } from '#lib/utils/form-parsers';
import type { ImageBuildRecord, ImageBuildStatus } from '#lib/types/docker';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';
import { queryKeys } from '#lib/query/query-keys';
@@ -91,7 +94,10 @@
const formSchema = z.object({
dockerfile: z.string().optional().default(''),
- tags: z.string().min(1, m.image_tags_required()),
+ tags: z.string().optional().default(''),
+ registryId: z.string().default(''),
+ repositoryName: z.string().default(''),
+ pushTag: z.string().default(''),
target: z.string().optional().default(''),
buildArgs: z.string().optional().default(''),
labels: z.string().optional().default(''),
@@ -115,6 +121,9 @@
const { inputs, ...form } = createForm<typeof formSchema>(formSchema, {
dockerfile: '',
tags: '',
+ registryId: '',
+ repositoryName: '',
+ pushTag: '',
target: '',
buildArgs: '',
labels: '',
@@ -175,6 +184,56 @@
}));
const buildHistoryItems = $derived<Paginated<ImageBuildRecord>>(buildHistoryQuery.data ?? EMPTY_BUILD_HISTORY);
+ const resolvedProvider = $derived(depotAvailable ? $inputs.provider.value : 'local');
+ const isPushMode = $derived(resolvedProvider === 'depot' ? true : $inputs.push.value);
+
+ const registryRequestOptions = {
+ pagination: { page: 1, limit: 100 },
+ sort: { column: 'url', direction: 'asc' }
+ } satisfies SearchPaginationSortRequest;
+
+ const registriesQuery = createQuery(() => ({
+ queryKey: queryKeys.containerRegistries.list(registryRequestOptions),
+ enabled: isPushMode,
+ queryFn: () => containerRegistryService.getRegistries(registryRequestOptions)
+ }));
+
+ const registries = $derived(registriesQuery.data?.data ?? []);
+
+ const registryOptions = $derived<SelectOption[]>(
+ registries
+ .filter((registry) => registry.enabled)
+ .map((registry) => {
+ const displayName = getRegistryDisplayName(registry);
+ return {
+ label: registry.url,
+ value: registry.id,
+ description: displayName === registry.url ? undefined : displayName
+ };
+ })
+ );
+
+ const selectedRegistry = $derived(registries.find((registry) => registry.id === $inputs.registryId.value));
+
+ const repositoryOptions = $derived<SelectOption[]>(
+ (selectedRegistry?.repositoryNames ?? []).map((name) => ({ label: name, value: name }))
+ );
+
+ const fullImageReference = $derived(
+ isPushMode && selectedRegistry
+ ? buildImageReference(selectedRegistry.url, $inputs.repositoryName.value, $inputs.pushTag.value)
+ : ''
+ );
+
+ // Clear the repository name when registry changes to prevent cross-registry mismatches.
+ let lastRegistryId = $state($inputs.registryId.value);
+ $effect(() => {
+ const current = $inputs.registryId.value;
+ if (current !== lastRegistryId) {
+ lastRegistryId = current;
+ $inputs.repositoryName.value = '';
+ }
+ });
let buildHistoryQueryLastError: string | null = null;
@@ -428,20 +487,6 @@
logLines = [...logLines, line];
}
- function parseTags(raw: string): string[] {
- return raw
- .split(/[\n,]/)
- .map((t) => t.trim())
- .filter(Boolean);
- }
-
- function parsePlatforms(raw: string): string[] {
- return raw
- .split(/[\n,]/)
- .map((t) => t.trim())
- .filter(Boolean);
- }
-
function parseBuildArgs(raw: string): Record<string, string> {
const result: Record<string, string> = {};
for (const line of raw.split('\n')) {
@@ -457,13 +502,6 @@
return result;
}
- function parseList(raw: string): string[] {
- return raw
- .split(/[\n,]/)
- .map((value) => value.trim())
- .filter(Boolean);
- }
-
function parseOptionalBytes(raw: string): number | undefined {
const trimmed = raw.trim();
if (!trimmed) return undefined;
@@ -472,6 +510,31 @@
return parsed;
}
+ // Push builds target a configured registry, so their reference is assembled
+ // from the selected registry, repository name and tag rather than the
+ // free-form tags field.
+ function resolveBuildTags(
+ data: z.infer<typeof formSchema>,
+ push: boolean
+ ): { tags: string[]; error?: undefined } | { tags?: undefined; error: string } {
+ if (!push) {
+ const tags = parseList(data.tags);
+ return tags.length > 0 ? { tags } : { error: m.image_tags_required() };
+ }
+
+ const registry = registries.find((item) => item.id === data.registryId);
+ if (!registry) return { error: m.select_a_registry() };
+
+ const repositoryName = data.repositoryName.trim();
+ if (!repositoryName) return { error: m.select_a_repository_name() };
+ if (!registry.repositoryNames?.includes(repositoryName)) return { error: m.repository_name_not_configured() };
+
+ const reference = buildImageReference(registry.url, repositoryName, data.pushTag);
+ if (!reference) return { error: m.tag_required() };
+
+ return { tags: [reference] };
+ }
+
function validateProviderCompatibility(
provider: 'local' | 'depot',
values: {
@@ -723,17 +786,25 @@
buildStatusText = m.starting_build();
appendLog(m.using_context({ context: contextDir }));
- const tags = parseTags(data.tags);
+ const resolvedProvider = depotAvailable ? data.provider : 'local';
+ const push = resolvedProvider === 'depot' ? true : data.push;
+ const load = resolvedProvider === 'depot' ? false : data.load;
+
+ const resolvedTags = resolveBuildTags(data, push);
+ if (resolvedTags.error) {
+ toast.error(resolvedTags.error);
+ isBuilding = false;
+ return;
+ }
+ const tags = resolvedTags.tags;
+
const parsedCacheTo = parseList(data.cacheTo || '');
const parsedEntitlements = parseList(data.entitlements || '');
- const parsedPlatforms = parsePlatforms(data.platforms || '');
+ const parsedPlatforms = parseList(data.platforms || '');
const parsedExtraHosts = parseList(data.extraHosts || '');
const parsedUlimits = parseBuildArgs(data.ulimits || '');
const parsedShmSize = parseOptionalBytes(data.shmSize || '');
- const resolvedProvider = depotAvailable ? data.provider : 'local';
- const push = resolvedProvider === 'depot' ? true : data.push;
- const load = resolvedProvider === 'depot' ? false : data.load;
const network = data.network?.trim() || undefined;
const isolation = data.isolation?.trim() || undefined;
@@ -819,6 +890,20 @@
</Card.Root>
{/snippet}
+{#snippet configPanel()}
+ <BuildConfigPanel
+ {inputs}
+ provider={$inputs.provider.value}
+ bind:showAdvanced
+ {isPushMode}
+ {registryOptions}
+ {repositoryOptions}
+ {fullImageReference}
+ registryLoadFailed={Boolean(registriesQuery.error)}
+ onSubmit={handleSubmit}
+ />
+{/snippet}
+
{#snippet BuildHistoryStatusCell({ value }: { value: unknown })}
<Badge variant={getStatusBadgeVariant(value as ImageBuildStatus)} size="sm" minWidth="20"
>{buildHistoryStatusLabel(value as ImageBuildStatus)}</Badge
@@ -1212,7 +1297,7 @@
</div>
<Tabs.Content value="config" class="mt-0 min-h-0 flex-1 overflow-auto">
- <BuildConfigPanel {inputs} provider={$inputs.provider.value} bind:showAdvanced onSubmit={handleSubmit} />
+ {@render configPanel()}
</Tabs.Content>
<Tabs.Content value="output" class="mt-0 min-h-0 flex-1 overflow-hidden">
<BuildOutputPanel
@@ -1323,7 +1408,7 @@
{@render workspaceCard()}
{:else if buildTabValue === 'configuration'}
<Card.Root class="overflow-hidden">
- <BuildConfigPanel {inputs} provider={$inputs.provider.value} bind:showAdvanced onSubmit={handleSubmit} />
+ {@render configPanel()}
</Card.Root>
{:else}
<Card.Root class="flex h-full min-h-[500px] flex-col overflow-hidden">
diff --git a/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte b/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte
index 7a966bf57..24e20f2ff 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-config-panel.svelte
@@ -2,19 +2,30 @@
import * as Collapsible from '#lib/components/ui/collapsible/index.js';
import { ArrowDownIcon } from '#lib/icons';
import FormInput from '#lib/components/form/form-input.svelte';
+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
import { preventDefault } from '#lib/utils/settings';
import { m } from '#lib/paraglide/messages';
- import type { BuildFormInputsStore } from './build-form.types';
+ import type { BuildFormInputsStore, SelectOption } from './build-form.types';
let {
inputs,
provider,
showAdvanced = $bindable(false),
+ isPushMode = false,
+ registryOptions = [],
+ repositoryOptions = [],
+ fullImageReference = '',
+ registryLoadFailed = false,
onSubmit
}: {
inputs: BuildFormInputsStore;
provider: 'local' | 'depot';
showAdvanced?: boolean;
+ isPushMode?: boolean;
+ registryOptions?: SelectOption[];
+ repositoryOptions?: SelectOption[];
+ fullImageReference?: string;
+ registryLoadFailed?: boolean;
onSubmit?: () => void;
} = $props();
@@ -25,13 +36,47 @@
<div class="space-y-7 p-8">
<form onsubmit={preventDefault(() => onSubmit?.())} class="space-y-7">
<div class="space-y-4">
- <FormInput
- label={m.image_tags()}
- type="text"
- placeholder={m.image_tags_placeholder()}
- description={m.image_tags_description()}
- bind:input={$inputs.tags}
- />
+ {#if isPushMode}
+ <SelectWithLabel
+ id="build-push-registry"
+ label={m.common_registry()}
+ placeholder={m.select_a_registry()}
+ options={registryOptions}
+ description={!registryLoadFailed && registryOptions.length === 0 ? m.registries_none_enabled() : undefined}
+ error={registryLoadFailed ? m.registries_no_list_permission() : null}
+ bind:value={$inputs.registryId.value}
+ />
+
+ <SelectWithLabel
+ id="build-push-repository"
+ label={m.repository_name()}
+ placeholder={m.select_a_repository_name()}
+ options={repositoryOptions}
+ description={$inputs.registryId.value && !registryLoadFailed && repositoryOptions.length === 0
+ ? m.registries_no_repository_names()
+ : undefined}
+ bind:value={$inputs.repositoryName.value}
+ />
+
+ <FormInput label={m.tag()} type="text" placeholder={m.tag_placeholder()} bind:input={$inputs.pushTag} />
+
+ {#if fullImageReference}
+ <div class="space-y-1">
+ <span class="text-xs font-medium text-muted-foreground">{m.image_reference()}</span>
+ <div class="rounded-md bg-muted/50 px-3 py-2">
+ <code class="text-xs break-all">{fullImageReference}</code>
+ </div>
+ </div>
+ {/if}
+ {:else}
+ <FormInput
+ label={m.image_tags()}
+ type="text"
+ placeholder={m.image_tags_placeholder()}
+ description={m.image_tags_description()}
+ bind:input={$inputs.tags}
+ />
+ {/if}
<Collapsible.Root bind:open={showAdvanced}>
<Collapsible.Trigger
diff --git a/frontend/src/routes/(app)/images/builds/components/build-form.types.ts b/frontend/src/routes/(app)/images/builds/components/build-form.types.ts
index 524a6b0cf..7eea58876 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-form.types.ts
+++ b/frontend/src/routes/(app)/images/builds/components/build-form.types.ts
@@ -1,15 +1,22 @@
import type { FormInput } from '#lib/utils/settings';
import type { Writable } from 'svelte/store';
-export type BuildProviderOption = {
+export type SelectOption = {
label: string;
- value: 'local' | 'depot';
+ value: string;
description?: string;
};
+export type BuildProviderOption = SelectOption & {
+ value: 'local' | 'depot';
+};
+
export type BuildFormInputs = {
dockerfile: FormInput<string>;
tags: FormInput<string>;
+ registryId: FormInput<string>;
+ repositoryName: FormInput<string>;
+ pushTag: FormInput<string>;
target: FormInput<string>;
buildArgs: FormInput<string>;
labels: FormInput<string>;
diff --git a/tests/spec/builds.spec.ts b/tests/spec/builds.spec.ts
index 5f566bf44..8462988a2 100644
--- a/tests/spec/builds.spec.ts
+++ b/tests/spec/builds.spec.ts
@@ -147,6 +147,67 @@ async function mockDepotConfiguredSettings(page: Page) {
});
}
+const BUILD_REGISTRY_URL = 'registry.example.com';
+
+/**
+ * Serves a single enabled registry to the push target pickers. Pass a function
+ * for `repositoryNames` to change the configured names between requests, and
+ * use the returned counter to wait for a refetch.
+ */
+async function mockBuildRegistry(
+ page: Page,
+ repositoryNames: string[] | (() => string[]) = ['team/build']
+) {
+ const registryRequests = { count: 0 };
+
+ await page.route(/\/api\/container-registries(?:\?.*)?$/, async (route) => {
+ if (route.request().method() !== 'GET') {
+ await route.fallback();
+ return;
+ }
+
+ registryRequests.count += 1;
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ data: [
+ {
+ id: 'e2e-build-registry',
+ url: BUILD_REGISTRY_URL,
+ username: 'e2e-user',
+ token: '',
+ description: 'Build test registry',
+ insecure: false,
+ enabled: true,
+ registryType: 'generic',
+ repositoryNames:
+ typeof repositoryNames === 'function' ? repositoryNames() : repositoryNames
+ }
+ ],
+ pagination: {
+ totalPages: 1,
+ totalItems: 1,
+ currentPage: 1,
+ itemsPerPage: 100,
+ grandTotalItems: 1
+ }
+ })
+ });
+ });
+
+ return registryRequests;
+}
+
+async function selectBuildPushReference(page: Page, repositoryName = 'team/build') {
+ await page.locator('#build-push-registry:visible').click();
+ await page.locator('[data-slot="select-item"]').filter({ hasText: BUILD_REGISTRY_URL }).click();
+ await page.locator('#build-push-repository:visible').click();
+ await page.locator('[data-slot="select-item"]').filter({ hasText: repositoryName }).click();
+ await page.locator('#tag:visible').fill('v1');
+}
+
test.describe('Build workspace provider flows', () => {
test('persists the selected primary tab in the URL', async ({ page }) => {
await navigateToBuildWorkspace(page);
@@ -191,6 +252,7 @@ test.describe('Build workspace provider flows', () => {
});
test('submits local provider build payload from UI controls', async ({ page }) => {
+ await mockBuildRegistry(page);
await navigateToBuildWorkspace(page);
await setRequiredBuildInputs(page);
@@ -202,6 +264,7 @@ test.describe('Build workspace provider flows', () => {
await ensureSwitchState(pushSwitch, true);
await ensureSwitchState(loadSwitch, true);
+ await selectBuildPushReference(page);
const buildRequest = { payload: null as Record<string, unknown> | null };
@@ -227,12 +290,48 @@ test.describe('Build workspace provider flows', () => {
await expect(page.getByText('Build completed').first()).toBeVisible();
});
+ test('blocks a stale repository value after registry options change', async ({ page }) => {
+ let repositoryNames = ['team/legacy'];
+ const registryRequests = await mockBuildRegistry(page, () => repositoryNames);
+
+ await navigateToBuildWorkspace(page);
+ const pushSwitch = page.locator('#build-push');
+ await ensureSwitchState(pushSwitch, true);
+ await expect.poll(() => registryRequests.count).toBeGreaterThan(0);
+
+ await selectBuildPushReference(page, 'team/legacy');
+
+ repositoryNames = ['team/current'];
+ await ensureSwitchState(pushSwitch, false);
+ await ensureSwitchState(pushSwitch, true);
+ await expect.poll(() => registryRequests.count).toBeGreaterThan(1);
+ await expect(page.locator('#build-push-repository:visible')).toContainText(
+ 'Select a repository name'
+ );
+
+ let buildRequests = 0;
+ await page.route('**/api/environments/*/images/build', async (route) => {
+ buildRequests += 1;
+ await route.abort();
+ });
+
+ await getBuildButton(page).click();
+ await expect(
+ getToastTitle(page).filter({
+ hasText: 'Select a repository name configured for this registry'
+ })
+ ).toBeVisible();
+ expect(buildRequests).toBe(0);
+ });
+
test('uses provider selector via UI and enforces depot push/load behavior', async ({ page }) => {
await mockDepotConfiguredSettings(page);
+ await mockBuildRegistry(page);
await navigateToBuildWorkspace(page);
await setRequiredBuildInputs(page);
await selectBuildProvider(page, 'depot');
+ await selectBuildPushReference(page);
const loadSwitch = page.locator('#build-load');
await expect(loadSwitch).toBeDisabled();
@@ -332,10 +431,12 @@ test.describe('Build workspace provider flows', () => {
page
}) => {
await mockDepotConfiguredSettings(page);
+ await mockBuildRegistry(page);
await navigateToBuildWorkspace(page);
await setRequiredBuildInputs(page, `e2e/depot-advanced:${Date.now()}`);
await openAdvancedBuildOptions(page);
await selectBuildProvider(page, 'depot');
+ await selectBuildPushReference(page);
await expect(page.locator('#build-load')).toBeDisabled();
await page
@@ -419,6 +520,7 @@ test.describe('Build workspace provider flows', () => {
page
}) => {
await mockDepotConfiguredSettings(page);
+ await mockBuildRegistry(page);
await navigateToBuildWorkspace(page);
await setRequiredBuildInputs(page, `e2e/depot-unsupported:${Date.now()}`);
await openAdvancedBuildOptions(page);
@@ -430,6 +532,7 @@ test.describe('Build workspace provider flows', () => {
await page.getByLabel(FIELD_LABELS.extraHosts).fill('registry.local=10.0.0.5');
await selectBuildProvider(page, 'depot');
+ await selectBuildPushReference(page);
let buildRequests = 0;
await page.route('**/api/environments/*/images/build', async (route) => {
diff --git a/types/containerregistry/container_registry.go b/types/containerregistry/container_registry.go
index 7388e89d2..3f079e5b0 100644
--- a/types/containerregistry/container_registry.go
+++ b/types/containerregistry/container_registry.go
@@ -39,6 +39,12 @@ type ContainerRegistry struct {
// Required: true
RegistryType string `json:"registryType"`
+ // RepositoryNames is the list of pre-configured repository namespace
+ // strings available for selection when pushing images from the build page.
+ //
+ // Required: false
+ RepositoryNames []string `json:"repositoryNames"`
+
// AWSAccessKeyID is the AWS Access Key ID for ECR registries.
//
// Required: false
@@ -185,6 +191,12 @@ type Sync struct {
// Required: true
RegistryType string `json:"registryType"`
+ // RepositoryNames is the list of pre-configured repository namespace
+ // strings available for selection when pushing images from the build page.
+ //
+ // Required: false
+ RepositoryNames []string `json:"repositoryNames"`
+
// AWSAccessKeyID is the AWS Access Key ID for ECR registries.
//
// Required: false