Skip to content

Modern Docker Management, Designed for Everyone

feat(registries): browse repositories and tags of configured registries (#4162)

Laval_130b39ad4eb094
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 18706723c..065000ba5 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -105,6 +105,7 @@ var (
ErrOidcMappingEnvManaged = Classify(ErrConflict, errors.Sentinel("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))
ErrNoGlobalAdminRemains = Classify(ErrConflict, errors.Sentinel("At least one user must retain a global Admin role assignment"))
ErrProjectNotFound = Classify(ErrNotFound, errors.Sentinel("Project not found"))
+ ErrContainerRegistryNotFound = Classify(ErrNotFound, errors.Sentinel("Container registry not found"))
ErrProjectArchived = Classify(ErrConflict, errors.Sentinel("project is archived and must be unarchived before this action"))
ErrProjectMustBeStopped = Classify(ErrConflict, errors.Sentinel("project must be stopped before archiving"))
ErrProjectWorkspaceConflict = Classify(ErrConflict, errors.Sentinel("Project workspace changed; refresh it and try again"))
diff --git a/backend/internal/registry/browse.go b/backend/internal/registry/browse.go
new file mode 100644
index 000000000..ebf8c52a8
--- /dev/null
+++ b/backend/internal/registry/browse.go
@@ -0,0 +1,321 @@
+package registry
+
+import (
+ "cmp"
+ "context"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+
+ "emperror.dev/errors"
+ "github.com/google/go-containerregistry/pkg/authn"
+ "github.com/google/go-containerregistry/pkg/name"
+ v1 "github.com/google/go-containerregistry/pkg/v1"
+ "github.com/google/go-containerregistry/pkg/v1/remote"
+ "github.com/google/go-containerregistry/pkg/v1/remote/transport"
+ "golang.org/x/sync/errgroup"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/types/v2/containerregistry"
+)
+
+const tagDetailsConcurrency = 4
+
+// browseTargetInternal is a configured registry resolved for the distribution API.
+type browseTargetInternal struct {
+ registry name.Registry
+ // prefix is the repository namespace configured in the registry URL, if any.
+ prefix string
+ nameOptions []name.Option
+ options []remote.Option
+}
+
+// ListRepositories lists the repositories of a configured registry through the
+// catalog API, limited to the namespace of the registry URL.
+func (s *ContainerRegistryService) ListRepositories(ctx context.Context, id string, params pagination.QueryParams) ([]containerregistry.Repository, pagination.Response, error) {
+ lookupCtx, cancel := s.tagLookupContextInternal(ctx)
+ defer cancel()
+
+ target, err := s.browseTargetInternal(lookupCtx, id)
+ if err != nil {
+ return nil, pagination.Response{}, err
+ }
+
+ names, err := remote.Catalog(lookupCtx, target.registry, target.options...)
+ if err != nil {
+ return nil, pagination.Response{}, classifyBrowseErrorInternal(err, "failed to list repositories (the registry may not support the catalog API)")
+ }
+ if target.prefix != "" {
+ names = slices.DeleteFunc(names, func(repositoryName string) bool {
+ return !strings.HasPrefix(repositoryName, target.prefix+"/")
+ })
+ }
+
+ page, response := paginateNamesInternal(names, params)
+ items := make([]containerregistry.Repository, 0, len(page))
+ for _, repositoryName := range page {
+ items = append(items, containerregistry.Repository{Name: repositoryName})
+ }
+ return items, response, nil
+}
+
+// ListRepositoryTags lists the tags of a repository. Manifest details are only
+// fetched for the requested page, and a failure is recorded on the tag itself
+// so one unreadable manifest does not hide the rest of the page.
+func (s *ContainerRegistryService) ListRepositoryTags(ctx context.Context, id, repository string, params pagination.QueryParams) ([]containerregistry.RepositoryTag, pagination.Response, error) {
+ lookupCtx, cancel := s.tagLookupContextInternal(ctx)
+ defer cancel()
+
+ target, err := s.browseTargetInternal(lookupCtx, id)
+ if err != nil {
+ return nil, pagination.Response{}, err
+ }
+ repo, err := target.repositoryInternal(repository)
+ if err != nil {
+ return nil, pagination.Response{}, err
+ }
+
+ names, err := remote.List(repo, target.options...)
+ if err != nil {
+ return nil, pagination.Response{}, classifyBrowseErrorInternal(err, "failed to list tags")
+ }
+
+ page, response := paginateNamesInternal(names, params)
+ items := make([]containerregistry.RepositoryTag, len(page))
+ group := errgroup.Group{}
+ group.SetLimit(tagDetailsConcurrency)
+ for i, tagName := range page {
+ group.Go(func() error {
+ tag, err := tagDetailsInternal(repo, target.options, tagName)
+ if err != nil {
+ tag.Error = err.Error()
+ }
+ items[i] = tag
+ return nil
+ })
+ }
+ _ = group.Wait()
+
+ return items, response, nil
+}
+
+// DeleteRepositoryTag deletes the manifest a tag points to. Registries delete
+// manifests by digest, so every tag sharing that digest is removed too.
+func (s *ContainerRegistryService) DeleteRepositoryTag(ctx context.Context, id, repository, tag string) (string, error) {
+ lookupCtx, cancel := s.tagLookupContextInternal(ctx)
+ defer cancel()
+
+ target, err := s.browseTargetInternal(lookupCtx, id)
+ if err != nil {
+ return "", err
+ }
+ repo, err := target.repositoryInternal(repository)
+ if err != nil {
+ return "", err
+ }
+ tagRef, err := name.NewTag(repo.Name()+":"+strings.TrimSpace(tag), target.nameOptions...)
+ if err != nil {
+ return "", common.Classify(common.ErrValidation, errors.WrapIff(err, "invalid tag %q", tag))
+ }
+
+ descriptor, err := remote.Head(tagRef, target.options...)
+ if err != nil {
+ return "", classifyBrowseErrorInternal(err, "failed to resolve tag digest")
+ }
+ digest := descriptor.Digest.String()
+ if err := remote.Delete(repo.Digest(digest), target.options...); err != nil {
+ return "", classifyBrowseErrorInternal(err, "failed to delete manifest")
+ }
+ return digest, nil
+}
+
+// browseTargetInternal resolves a stored registry into a registry name, its
+// namespace prefix, and the remote options carrying auth and transport.
+func (s *ContainerRegistryService) browseTargetInternal(ctx context.Context, id string) (*browseTargetInternal, error) {
+ reg, err := s.GetRegistryByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+
+ host, prefix := utilsregistry.SplitRegistryURL(reg.URL)
+ nameOptions := []name.Option{name.StrictValidation}
+ if reg.Insecure {
+ nameOptions = append(nameOptions, name.Insecure)
+ }
+ registryName, err := name.NewRegistry(host, nameOptions...)
+ if err != nil {
+ return nil, common.Classify(common.ErrValidation, errors.WrapIff(err, "invalid registry URL %q", reg.URL))
+ }
+
+ credential, err := s.credentialForRegistryInternal(ctx, reg)
+ if err != nil {
+ return nil, err
+ }
+ authenticator := authn.Anonymous
+ if credential != nil {
+ authenticator = authn.FromConfig(authn.AuthConfig{Username: credential.Username, Password: credential.Token})
+ }
+ options := []remote.Option{remote.WithContext(ctx), remote.WithAuth(authenticator)}
+ if s.distributionHTTPClient.Transport != nil {
+ options = append(options, remote.WithTransport(s.distributionHTTPClient.Transport))
+ }
+
+ return &browseTargetInternal{
+ registry: registryName,
+ prefix: prefix,
+ nameOptions: nameOptions,
+ options: options,
+ }, nil
+}
+
+// repositoryInternal parses a repository name and keeps it inside the registry namespace.
+func (t *browseTargetInternal) repositoryInternal(repository string) (name.Repository, error) {
+ repository = strings.Trim(strings.TrimSpace(repository), "/")
+ if repository == "" {
+ return name.Repository{}, common.Classify(common.ErrValidation, errors.New("repository is required"))
+ }
+ if t.prefix != "" && !strings.HasPrefix(repository, t.prefix+"/") {
+ return name.Repository{}, common.Classify(common.ErrValidation, errors.Errorf("repository %q is outside the registry namespace %q", repository, t.prefix))
+ }
+ repo, err := name.NewRepository(t.registry.Name()+"/"+repository, t.nameOptions...)
+ if err != nil {
+ return name.Repository{}, common.Classify(common.ErrValidation, errors.WrapIff(err, "invalid repository %q", repository))
+ }
+ return repo, nil
+}
+
+func paginateNamesInternal(names []string, params pagination.QueryParams) ([]string, pagination.Response) {
+ config := pagination.Config[string]{
+ SearchAccessors: []pagination.SearchAccessor[string]{
+ func(item string) (string, error) { return item, nil },
+ },
+ SortBindings: []pagination.SortBinding[string]{
+ {Key: "name", Fn: strings.Compare},
+ },
+ }
+ result := config.SearchOrderAndPaginate(names, params)
+ return result.Items, pagination.BuildResponse(result.TotalCount, result.TotalAvailable, params)
+}
+
+// tagDetailsInternal resolves the manifest behind a tag. A single image yields
+// one platform; an index yields one per platform image, skipping attestations.
+func tagDetailsInternal(repo name.Repository, options []remote.Option, tagName string) (containerregistry.RepositoryTag, error) {
+ tag := containerregistry.RepositoryTag{Name: tagName, Platforms: []containerregistry.TagPlatform{}}
+
+ descriptor, err := remote.Get(repo.Tag(tagName), options...)
+ if err != nil {
+ return tag, err
+ }
+ tag.Digest = descriptor.Digest.String()
+ tag.MediaType = string(descriptor.MediaType)
+
+ if !descriptor.MediaType.IsIndex() {
+ img, err := descriptor.Image()
+ if err != nil {
+ return tag, err
+ }
+ config, err := img.ConfigFile()
+ if err != nil {
+ return tag, err
+ }
+ platform, err := tagPlatformInternal(img, config.Platform(), descriptor.Digest)
+ if err != nil {
+ return tag, err
+ }
+ tag.Platforms = []containerregistry.TagPlatform{platform}
+ tag.Size = platform.Size
+ if !config.Created.IsZero() {
+ created := config.Created.UTC()
+ tag.Created = &created
+ }
+ return tag, nil
+ }
+
+ index, err := descriptor.ImageIndex()
+ if err != nil {
+ return tag, err
+ }
+ manifest, err := index.IndexManifest()
+ if err != nil {
+ return tag, err
+ }
+
+ var mu sync.Mutex
+ group := errgroup.Group{}
+ group.SetLimit(tagDetailsConcurrency)
+ for _, child := range manifest.Manifests {
+ if child.Platform == nil || child.Platform.OS == "unknown" || !child.MediaType.IsImage() {
+ continue
+ }
+ group.Go(func() error {
+ img, err := index.Image(child.Digest)
+ if err != nil {
+ return err
+ }
+ platform, err := tagPlatformInternal(img, child.Platform, child.Digest)
+ if err != nil {
+ return err
+ }
+ mu.Lock()
+ tag.Platforms = append(tag.Platforms, platform)
+ tag.Size += platform.Size
+ mu.Unlock()
+ return nil
+ })
+ }
+ if err := group.Wait(); err != nil {
+ return tag, err
+ }
+
+ slices.SortFunc(tag.Platforms, func(a, b containerregistry.TagPlatform) int {
+ return cmp.Or(
+ strings.Compare(a.OS, b.OS),
+ strings.Compare(a.Architecture, b.Architecture),
+ strings.Compare(a.Variant, b.Variant),
+ )
+ })
+ return tag, nil
+}
+
+// tagPlatformInternal describes one platform image with its compressed config and layer size.
+func tagPlatformInternal(img v1.Image, platform *v1.Platform, digest v1.Hash) (containerregistry.TagPlatform, error) {
+ manifest, err := img.Manifest()
+ if err != nil {
+ return containerregistry.TagPlatform{}, err
+ }
+ result := containerregistry.TagPlatform{Digest: digest.String(), Size: manifest.Config.Size}
+ for _, layer := range manifest.Layers {
+ result.Size += layer.Size
+ }
+ if platform != nil {
+ result.OS = platform.OS
+ result.Architecture = platform.Architecture
+ result.Variant = platform.Variant
+ }
+ return result, nil
+}
+
+// classifyBrowseErrorInternal maps distribution API failures to API error kinds.
+func classifyBrowseErrorInternal(err error, message string) error {
+ if errors.Is(err, context.DeadlineExceeded) {
+ return common.Classify(common.ErrTimeout, errors.WrapIf(err, message))
+ }
+ // Upstream auth failures are not Arcane permission failures, so they must not map to 401/403.
+ if isUnauthorizedRegistryErrorInternal(err) {
+ return common.Classify(common.ErrBadRequest, errors.WrapIf(err, message+": the registry denied access with the configured credentials"))
+ }
+
+ var transportErr *transport.Error
+ if errors.As(err, &transportErr) {
+ switch transportErr.StatusCode {
+ case http.StatusNotFound:
+ return common.Classify(common.ErrNotFound, errors.WrapIf(err, message))
+ case http.StatusMethodNotAllowed:
+ return common.Classify(common.ErrBadRequest, errors.WrapIf(err, message+": the registry does not allow this operation"))
+ }
+ }
+ return common.Classify(common.ErrUnavailable, errors.WrapIf(err, message))
+}
diff --git a/backend/internal/registry/browse_handler.go b/backend/internal/registry/browse_handler.go
new file mode 100644
index 000000000..9e645e0d5
--- /dev/null
+++ b/backend/internal/registry/browse_handler.go
@@ -0,0 +1,128 @@
+package registry
+
+import (
+ "context"
+
+ "emperror.dev/errors"
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
+ "github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/containerregistry"
+)
+
+// ListRegistryRepositoriesInput is the input for listing the repositories of a registry.
+type ListRegistryRepositoriesInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction"`
+ Start int `query:"start" default:"0" doc:"Start index"`
+ Limit int `query:"limit" default:"20" doc:"Items per page"`
+}
+
+// ListRegistryTagsInput is the input for listing the tags of a registry repository.
+type ListRegistryTagsInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+ Repository string `query:"repository" required:"true" minLength:"1" doc:"Repository name"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction"`
+ Start int `query:"start" default:"0" doc:"Start index"`
+ Limit int `query:"limit" default:"20" doc:"Items per page"`
+}
+
+// DeleteRegistryTagInput is the input for deleting a tag from a registry repository.
+type DeleteRegistryTagInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+ Repository string `query:"repository" required:"true" minLength:"1" doc:"Repository name"`
+ Tag string `query:"tag" required:"true" minLength:"1" doc:"Tag to delete"`
+}
+
+func registerContainerRegistryBrowseInternal(api huma.API, h *ContainerRegistryHandler) {
+ middleware.RegisterWithPermission(api, huma.Operation{
+ OperationID: "listContainerRegistryRepositories",
+ Method: "GET",
+ Path: "/container-registries/{id}/repositories",
+ Summary: "List registry repositories",
+ Description: "List the repositories stored in a container registry through its catalog API",
+ Tags: []string{"Container Registries"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermRegistriesBrowse, h.ListRepositories)
+
+ middleware.RegisterWithPermission(api, huma.Operation{
+ OperationID: "listContainerRegistryTags",
+ Method: "GET",
+ Path: "/container-registries/{id}/tags",
+ Summary: "List repository tags",
+ Description: "List the tags of a registry repository with their manifest details",
+ Tags: []string{"Container Registries"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermRegistriesBrowse, h.ListTags)
+
+ middleware.RegisterWithPermission(api, huma.Operation{
+ OperationID: "deleteContainerRegistryTag",
+ Method: "DELETE",
+ Path: "/container-registries/{id}/tags",
+ Summary: "Delete a repository tag",
+ Description: "Delete the manifest a tag points to, which also removes every tag sharing its digest",
+ Tags: []string{"Container Registries"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermRegistriesDeleteTags, h.DeleteTag)
+}
+
+// ListRepositories returns a paginated list of repositories stored in a registry.
+func (h *ContainerRegistryHandler) ListRepositories(ctx context.Context, input *ListRegistryRepositoriesInput) (*handlerutil.Page[containerregistry.Repository], error) {
+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
+
+ repositories, paginationResp, err := h.registryService.ListRepositories(ctx, input.ID, params)
+ if err != nil {
+ apiErr := common.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to list repositories").Error())
+ }
+
+ return &handlerutil.Page[containerregistry.Repository]{
+ Body: base.Paginated[containerregistry.Repository]{
+ Success: true,
+ Data: repositories,
+ Pagination: handlerutil.PaginationResponse(paginationResp),
+ },
+ }, nil
+}
+
+// ListTags returns a paginated list of tags of a registry repository.
+func (h *ContainerRegistryHandler) ListTags(ctx context.Context, input *ListRegistryTagsInput) (*handlerutil.Page[containerregistry.RepositoryTag], error) {
+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
+
+ tags, paginationResp, err := h.registryService.ListRepositoryTags(ctx, input.ID, input.Repository, params)
+ if err != nil {
+ apiErr := common.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to list tags").Error())
+ }
+
+ return &handlerutil.Page[containerregistry.RepositoryTag]{
+ Body: base.Paginated[containerregistry.RepositoryTag]{
+ Success: true,
+ Data: tags,
+ Pagination: handlerutil.PaginationResponse(paginationResp),
+ },
+ }, nil
+}
+
+// DeleteTag deletes the manifest a repository tag points to.
+func (h *ContainerRegistryHandler) DeleteTag(ctx context.Context, input *DeleteRegistryTagInput) (*handlerutil.Out[containerregistry.DeleteTagResponse], error) {
+ digest, err := h.registryService.DeleteRepositoryTag(ctx, input.ID, input.Repository, input.Tag)
+ if err != nil {
+ apiErr := common.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to delete tag").Error())
+ }
+
+ return &handlerutil.Out[containerregistry.DeleteTagResponse]{
+ Body: base.ApiResponse[containerregistry.DeleteTagResponse]{
+ Success: true,
+ Data: containerregistry.DeleteTagResponse{Digest: digest},
+ },
+ }, nil
+}
diff --git a/backend/internal/registry/browse_test.go b/backend/internal/registry/browse_test.go
new file mode 100644
index 000000000..1ef815917
--- /dev/null
+++ b/backend/internal/registry/browse_test.go
@@ -0,0 +1,312 @@
+package registry
+
+import (
+ "context"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/types/v2/containerregistry"
+ "github.com/google/go-containerregistry/pkg/authn"
+ "github.com/google/go-containerregistry/pkg/name"
+ ggcrregistry "github.com/google/go-containerregistry/pkg/registry"
+ v1 "github.com/google/go-containerregistry/pkg/v1"
+ "github.com/google/go-containerregistry/pkg/v1/empty"
+ "github.com/google/go-containerregistry/pkg/v1/mutate"
+ "github.com/google/go-containerregistry/pkg/v1/random"
+ "github.com/google/go-containerregistry/pkg/v1/remote"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.getarcane.app/sys/crypto"
+)
+
+func createBrowseTestRegistryInternal(t *testing.T, db *database.DB, registryURL, username, token string) string {
+ t.Helper()
+
+ record := &ContainerRegistry{URL: registryURL, Username: username, Enabled: true, RegistryType: RegistryTypeGeneric}
+ if token != "" {
+ encryptedToken, err := crypto.Encrypt(token)
+ require.NoError(t, err)
+ record.Token = encryptedToken
+ }
+ require.NoError(t, db.WithContext(context.Background()).Create(record).Error)
+ return record.ID
+}
+
+func platformImageInternal(t *testing.T, platform v1.Platform, created time.Time) v1.Image {
+ t.Helper()
+
+ img, err := random.Image(128, 2)
+ require.NoError(t, err)
+ cfg, err := img.ConfigFile()
+ require.NoError(t, err)
+ cfg = cfg.DeepCopy()
+ cfg.OS = platform.OS
+ cfg.Architecture = platform.Architecture
+ cfg.Variant = platform.Variant
+ cfg.Created = v1.Time{Time: created}
+ img, err = mutate.ConfigFile(img, cfg)
+ require.NoError(t, err)
+ return img
+}
+
+func mustParseReferenceInternal(t *testing.T, imageRef string) name.Reference {
+ t.Helper()
+ ref, err := name.ParseReference(imageRef)
+ require.NoError(t, err)
+ return ref
+}
+
+func writeImageInternal(t *testing.T, imageRef string, img v1.Image, options ...remote.Option) {
+ t.Helper()
+ require.NoError(t, remote.Write(mustParseReferenceInternal(t, imageRef), img, options...))
+}
+
+func imageSizeInternal(t *testing.T, img v1.Image) int64 {
+ t.Helper()
+ digest, err := img.Digest()
+ require.NoError(t, err)
+ platform, err := tagPlatformInternal(img, nil, digest)
+ require.NoError(t, err)
+ return platform.Size
+}
+
+func browseParamsInternal(search string) pagination.QueryParams {
+ return pagination.QueryParams{
+ SearchQuery: pagination.SearchQuery{Search: search},
+ Params: pagination.Params{Start: 0, Limit: 20},
+ }
+}
+
+func TestContainerRegistryService_ListRepositoriesInternal(t *testing.T) {
+ host := newLabelTestRegistryInternal(t)
+ img := platformImageInternal(t, v1.Platform{OS: "linux", Architecture: "amd64"}, time.Now())
+ writeImageInternal(t, host+"/team/api:1.0", img)
+ writeImageInternal(t, host+"/team/web:1.0", img)
+ writeImageInternal(t, host+"/other/tool:1.0", img)
+
+ db := setupContainerRegistryTestDBInternal(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+ ctx := context.Background()
+
+ id := createBrowseTestRegistryInternal(t, db, host, "", "")
+ repositories, page, err := svc.ListRepositories(ctx, id, browseParamsInternal(""))
+ require.NoError(t, err)
+ assert.Equal(t, []string{"other/tool", "team/api", "team/web"}, repositoryNamesInternal(repositories))
+ assert.EqualValues(t, 3, page.TotalItems)
+
+ repositories, _, err = svc.ListRepositories(ctx, id, browseParamsInternal("web"))
+ require.NoError(t, err)
+ assert.Equal(t, []string{"team/web"}, repositoryNamesInternal(repositories))
+
+ namespacedID := createBrowseTestRegistryInternal(t, db, "http://"+host+"/team/", "", "")
+ repositories, _, err = svc.ListRepositories(ctx, namespacedID, browseParamsInternal(""))
+ require.NoError(t, err)
+ assert.Equal(t, []string{"team/api", "team/web"}, repositoryNamesInternal(repositories))
+}
+
+func TestContainerRegistryService_ListRepositoryTagsSingleImageInternal(t *testing.T) {
+ host := newLabelTestRegistryInternal(t)
+ created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
+ img := platformImageInternal(t, v1.Platform{OS: "linux", Architecture: "arm64", Variant: "v8"}, created)
+ writeImageInternal(t, host+"/team/api:1.0", img)
+ writeImageInternal(t, host+"/team/api:2.0", img)
+
+ db := setupContainerRegistryTestDBInternal(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+ id := createBrowseTestRegistryInternal(t, db, host, "", "")
+
+ tags, page, err := svc.ListRepositoryTags(context.Background(), id, "team/api", pagination.QueryParams{Params: pagination.Params{Start: 0, Limit: 1}})
+ require.NoError(t, err)
+ assert.EqualValues(t, 2, page.TotalItems)
+ require.Len(t, tags, 1)
+
+ digest, err := img.Digest()
+ require.NoError(t, err)
+ size := imageSizeInternal(t, img)
+
+ tag := tags[0]
+ assert.Equal(t, "1.0", tag.Name)
+ assert.Empty(t, tag.Error)
+ assert.Equal(t, digest.String(), tag.Digest)
+ assert.Equal(t, size, tag.Size)
+ require.NotNil(t, tag.Created)
+ assert.True(t, created.Equal(*tag.Created))
+ require.Len(t, tag.Platforms, 1)
+ assert.Equal(t, "linux", tag.Platforms[0].OS)
+ assert.Equal(t, "arm64", tag.Platforms[0].Architecture)
+ assert.Equal(t, "v8", tag.Platforms[0].Variant)
+}
+
+func TestContainerRegistryService_ListRepositoryTagsIndexInternal(t *testing.T) {
+ host := newLabelTestRegistryInternal(t)
+ amd64 := v1.Platform{OS: "linux", Architecture: "amd64"}
+ arm64 := v1.Platform{OS: "linux", Architecture: "arm64"}
+ amd64Image := platformImageInternal(t, amd64, time.Now())
+ arm64Image := platformImageInternal(t, arm64, time.Now())
+ attestation, err := random.Image(32, 1)
+ require.NoError(t, err)
+
+ index := mutate.AppendManifests(empty.Index,
+ mutate.IndexAddendum{Add: arm64Image, Descriptor: v1.Descriptor{Platform: &arm64}},
+ mutate.IndexAddendum{Add: amd64Image, Descriptor: v1.Descriptor{Platform: &amd64}},
+ mutate.IndexAddendum{Add: attestation, Descriptor: v1.Descriptor{Platform: &v1.Platform{OS: "unknown", Architecture: "unknown"}}},
+ )
+ ref, err := name.ParseReference(host + "/team/api:multi")
+ require.NoError(t, err)
+ require.NoError(t, remote.WriteIndex(ref, index))
+
+ db := setupContainerRegistryTestDBInternal(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+ id := createBrowseTestRegistryInternal(t, db, host, "", "")
+
+ tags, _, err := svc.ListRepositoryTags(context.Background(), id, "team/api", browseParamsInternal(""))
+ require.NoError(t, err)
+ require.Len(t, tags, 1)
+
+ amd64Size := imageSizeInternal(t, amd64Image)
+ arm64Size := imageSizeInternal(t, arm64Image)
+
+ tag := tags[0]
+ assert.Empty(t, tag.Error)
+ assert.Nil(t, tag.Created)
+ assert.Equal(t, amd64Size+arm64Size, tag.Size)
+ require.Len(t, tag.Platforms, 2)
+ assert.Equal(t, "amd64", tag.Platforms[0].Architecture)
+ assert.Equal(t, amd64Size, tag.Platforms[0].Size)
+ assert.Equal(t, "arm64", tag.Platforms[1].Architecture)
+}
+
+func TestContainerRegistryService_DeleteRepositoryTagInternal(t *testing.T) {
+ host := newLabelTestRegistryInternal(t)
+ deleted := platformImageInternal(t, v1.Platform{OS: "linux", Architecture: "amd64"}, time.Now())
+ writeImageInternal(t, host+"/team/api:1.0", deleted)
+ writeImageInternal(t, host+"/team/api:2.0", platformImageInternal(t, v1.Platform{OS: "linux", Architecture: "amd64"}, time.Now()))
+
+ db := setupContainerRegistryTestDBInternal(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+ id := createBrowseTestRegistryInternal(t, db, host, "", "")
+ ctx := context.Background()
+
+ digest, err := svc.DeleteRepositoryTag(ctx, id, "team/api", "1.0")
+ require.NoError(t, err)
+ deletedDigest, err := deleted.Digest()
+ require.NoError(t, err)
+ assert.Equal(t, deletedDigest.String(), digest)
+
+ _, err = remote.Head(mustParseReferenceInternal(t, host+"/team/api@"+digest))
+ require.Error(t, err)
+ _, err = remote.Head(mustParseReferenceInternal(t, host+"/team/api:2.0"))
+ require.NoError(t, err)
+}
+
+func TestContainerRegistryService_BrowseUsesStoredCredentialsInternal(t *testing.T) {
+ registryHandler := ggcrregistry.New(ggcrregistry.Logger(log.New(io.Discard, "", 0)))
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ username, password, ok := r.BasicAuth()
+ if !ok || username != "robot" || password != "secret" {
+ w.Header().Set("WWW-Authenticate", `Basic realm="test"`)
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ registryHandler.ServeHTTP(w, r)
+ }))
+ t.Cleanup(server.Close)
+ serverURL, err := url.Parse(server.URL)
+ require.NoError(t, err)
+ host := "localhost:" + serverURL.Port()
+
+ writeImageInternal(t, host+"/private/app:1.0", platformImageInternal(t, v1.Platform{OS: "linux", Architecture: "amd64"}, time.Now()),
+ remote.WithAuth(&authn.Basic{Username: "robot", Password: "secret"}))
+
+ db := setupContainerRegistryTestDBInternal(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+ ctx := context.Background()
+
+ id := createBrowseTestRegistryInternal(t, db, host, "robot", "secret")
+ repositories, _, err := svc.ListRepositories(ctx, id, browseParamsInternal(""))
+ require.NoError(t, err)
+ assert.Equal(t, []string{"private/app"}, repositoryNamesInternal(repositories))
+
+ anonymousID := createBrowseTestRegistryInternal(t, db, host, "", "")
+ _, _, err = svc.ListRepositories(ctx, anonymousID, browseParamsInternal(""))
+ assert.ErrorIs(t, err, common.ErrBadRequest)
+}
+
+func TestContainerRegistryService_BrowseErrorsInternal(t *testing.T) {
+ host := newLabelTestRegistryInternal(t)
+ writeImageInternal(t, host+"/team/api:1.0", platformImageInternal(t, v1.Platform{OS: "linux", Architecture: "amd64"}, time.Now()))
+
+ db := setupContainerRegistryTestDBInternal(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+ id := createBrowseTestRegistryInternal(t, db, host, "", "")
+ namespacedID := createBrowseTestRegistryInternal(t, db, "http://"+host+"/team/", "", "")
+
+ tests := []struct {
+ name string
+ call func(ctx context.Context) error
+ wantErr error
+ }{
+ {
+ name: "unknown registry",
+ call: func(ctx context.Context) error {
+ _, _, err := svc.ListRepositories(ctx, "missing", browseParamsInternal(""))
+ return err
+ },
+ wantErr: common.ErrNotFound,
+ },
+ {
+ name: "empty repository",
+ call: func(ctx context.Context) error {
+ _, _, err := svc.ListRepositoryTags(ctx, id, " / ", browseParamsInternal(""))
+ return err
+ },
+ wantErr: common.ErrValidation,
+ },
+ {
+ name: "tags outside registry namespace",
+ call: func(ctx context.Context) error {
+ _, _, err := svc.ListRepositoryTags(ctx, namespacedID, "other/tool", browseParamsInternal(""))
+ return err
+ },
+ wantErr: common.ErrValidation,
+ },
+ {
+ name: "delete outside registry namespace",
+ call: func(ctx context.Context) error {
+ _, err := svc.DeleteRepositoryTag(ctx, namespacedID, "other/tool", "1.0")
+ return err
+ },
+ wantErr: common.ErrValidation,
+ },
+ {
+ name: "delete missing tag",
+ call: func(ctx context.Context) error {
+ _, err := svc.DeleteRepositoryTag(ctx, id, "team/api", "missing")
+ return err
+ },
+ wantErr: common.ErrNotFound,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.ErrorIs(t, tt.call(t.Context()), tt.wantErr)
+ })
+ }
+}
+
+func repositoryNamesInternal(repositories []containerregistry.Repository) []string {
+ names := make([]string, 0, len(repositories))
+ for _, repository := range repositories {
+ names = append(names, repository.Name)
+ }
+ return names
+}
diff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.go
index 3f7a2c5df..107511f19 100644
--- a/backend/internal/registry/handler.go
+++ b/backend/internal/registry/handler.go
@@ -159,6 +159,8 @@ func RegisterContainerRegistries(api huma.API, h *ContainerRegistryHandler) {
Security: handlerutil.DefaultOperationSecurity(),
Middlewares: middleware.RequirePermission(api, authz.PermRegistriesTest),
}, h.TestRegistry)
+
+ registerContainerRegistryBrowseInternal(api, h)
}
// ============================================================================
diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.go
index 72bbd716b..4b2d29e45 100644
--- a/backend/internal/registry/service.go
+++ b/backend/internal/registry/service.go
@@ -37,6 +37,7 @@ import (
"go.getarcane.app/updater/digest"
"go.getarcane.app/updater/refs"
"go.getarcane.app/updater/registry"
+ "gorm.io/gorm"
)
const (
@@ -178,6 +179,9 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, p
func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id string) (*ContainerRegistry, error) {
var registryRecord ContainerRegistry
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&registryRecord).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, common.ErrContainerRegistryNotFound
+ }
return nil, errors.WrapIf(err, "failed to get container registry")
}
return &registryRecord, nil
@@ -1049,43 +1053,53 @@ func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx co
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),
- })
+ credential, credErr := s.credentialForRegistryInternal(ctx, reg)
+ if credErr != nil {
+ slog.WarnContext(ctx, "failed to resolve registry credential", "registry", reg.URL, "error", credErr)
continue
}
-
- username := strings.TrimSpace(reg.Username)
- if username == "" || reg.Token == "" {
- continue
+ if credential != nil {
+ creds = append(creds, *credential)
}
+ }
- token, decryptErr := crypto.Decrypt(reg.Token)
- if decryptErr != nil {
- slog.WarnContext(ctx, "failed to decrypt registry token", "registry", reg.URL, "error", decryptErr)
- continue
- }
- token = strings.TrimSpace(token)
- if token == "" {
- continue
- }
+ return creds, nil
+}
- creds = append(creds, resolvedRegistryCredential{
- Username: username,
- Token: token,
+// credentialForRegistryInternal resolves the stored credential of one registry.
+// It returns nil when the registry is configured for anonymous access.
+func (s *ContainerRegistryService) credentialForRegistryInternal(ctx context.Context, reg *ContainerRegistry) (*resolvedRegistryCredential, error) {
+ if reg.RegistryType == RegistryTypeECR {
+ ecrUser, ecrPass, err := s.GetOrRefreshECRToken(ctx, reg)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to get ECR token")
+ }
+ return &resolvedRegistryCredential{
+ Username: ecrUser,
+ Token: ecrPass,
ServerAddress: normalizeRegistryServerAddressInternal(reg.URL),
- })
+ }, nil
}
- return creds, nil
+ username := strings.TrimSpace(reg.Username)
+ if username == "" || reg.Token == "" {
+ return nil, nil
+ }
+
+ token, err := crypto.Decrypt(reg.Token)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to decrypt registry token")
+ }
+ token = strings.TrimSpace(token)
+ if token == "" {
+ return nil, nil
+ }
+
+ return &resolvedRegistryCredential{
+ Username: username,
+ Token: token,
+ ServerAddress: normalizeRegistryServerAddressInternal(reg.URL),
+ }, nil
}
// SyncRegistries syncs registries from a manager to this agent instance
diff --git a/backend/internal/registry/tags.go b/backend/internal/registry/tags.go
index f7da83291..72f784609 100644
--- a/backend/internal/registry/tags.go
+++ b/backend/internal/registry/tags.go
@@ -21,11 +21,7 @@ func (s *ContainerRegistryService) ListImageTags(ctx context.Context, imageRef s
if err != nil {
return nil, err
}
- timeoutSeconds := 0
- if s.settingsService != nil {
- timeoutSeconds = s.settingsService.GetSettingsConfig().RegistryTagTimeout.AsInt()
- }
- lookupCtx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(timeoutSeconds, timeouts.DefaultRegistryTags))
+ lookupCtx, cancel := s.tagLookupContextInternal(ctx)
defer cancel()
tags, _, err := registryOperationWithCredentialsInternal(lookupCtx, s, parts.RegistryHost, "registry tag listing of "+parts.NormalizedRef, externalCreds,
@@ -38,3 +34,12 @@ func (s *ContainerRegistryService) ListImageTags(ctx context.Context, imageRef s
})
return tags, err
}
+
+// tagLookupContextInternal bounds tag and manifest walks by the configured registry tag timeout.
+func (s *ContainerRegistryService) tagLookupContextInternal(ctx context.Context) (context.Context, context.CancelFunc) {
+ timeoutSeconds := 0
+ if s.settingsService != nil {
+ timeoutSeconds = s.settingsService.GetSettingsConfig().RegistryTagTimeout.AsInt()
+ }
+ return context.WithTimeout(ctx, timeouts.GetDuration(timeoutSeconds, timeouts.DefaultRegistryTags))
+}
diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.go
index 59d3fe557..13bb83acc 100644
--- a/backend/pkg/authz/access_policy.go
+++ b/backend/pkg/authz/access_policy.go
@@ -91,10 +91,11 @@ var accessSurfacesInternal = []AccessSurface{
routeSurfaceInternal("route.swarm.secrets", "/swarm/secrets", "Secrets", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 0),
routeSurfaceInternal("route.events", "/events", "Events", AccessScopeModeGlobalOnly, []string{PermEventsRead}, 110),
routeSurfaceInternal("route.activities", "", "Activities", AccessScopeModeAnyEffectiveScope, []string{PermActivitiesRead}, 0),
- globalAdminRouteSurfaceInternal("route.oidc-role-mappings", "", "OIDC Role Mappings"),
+ allOfRouteSurfaceInternal("route.oidc-role-mappings", "", "OIDC Role Mappings", AllPermissions()),
routeSurfaceInternal("route.customize.templates.create", "/customize/templates/create", "Create template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
routeSurfaceInternal("route.customize.templates.default", "/customize/templates/default", "Default template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
routeSurfaceInternal("route.customize.templates.detail", "/customize/templates/{id}", "Template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
+ allOfRouteSurfaceInternal("route.customize.registries.browse", "/customize/registries/{id}", "Registry browser", []string{PermRegistriesRead, PermRegistriesBrowse}),
settingsCategorySurfaceInternal("activity", "/settings/activity", "Activity", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),
settingsCategorySurfaceInternal("apikeys", "/settings/api-keys", "API Keys", AccessScopeModeGlobalOnly, []string{PermApiKeysList, PermApiKeysRead}),
@@ -243,8 +244,8 @@ func routeSurfaceInternal(id, url, label, scopeMode string, permissions []string
}
}
-func globalAdminRouteSurfaceInternal(id, url, label string) AccessSurface {
- surface := routeSurfaceInternal(id, url, label, AccessScopeModeGlobalOnly, AllPermissions(), 0)
+func allOfRouteSurfaceInternal(id, url, label string, permissions []string) AccessSurface {
+ surface := routeSurfaceInternal(id, url, label, AccessScopeModeGlobalOnly, permissions, 0)
surface.MatchMode = AccessMatchModeAllOf
return surface
}
diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.go
index 53575b91c..cba8a2087 100644
--- a/backend/pkg/authz/catalog.go
+++ b/backend/pkg/authz/catalog.go
@@ -69,6 +69,8 @@ var permissionCatalog = []PermissionCatalogResource{
{"update", PermRegistriesUpdate, "Update", ""},
{"delete", PermRegistriesDelete, "Delete", ""},
{"test", PermRegistriesTest, "Test", ""},
+ {"browse", PermRegistriesBrowse, "Browse", "Browse repositories and tags stored in the registry (the pages also require Read)"},
+ {"delete-tags", PermRegistriesDeleteTags, "Delete tags", "Delete image manifests from the registry"},
}},
{"templates", "Templates", PermissionScopeGlobal, []PermissionCatalogAction{
{"list", PermTemplatesList, "List", ""},
diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.go
index 7f222d529..5631d88e9 100644
--- a/backend/pkg/authz/permissions.go
+++ b/backend/pkg/authz/permissions.go
@@ -56,12 +56,14 @@ const (
PermEnvironmentsPair = "environments:pair"
PermEnvironmentsSync = "environments:sync"
- PermRegistriesList = "registries:list"
- PermRegistriesRead = "registries:read"
- PermRegistriesCreate = "registries:create"
- PermRegistriesUpdate = "registries:update"
- PermRegistriesDelete = "registries:delete"
- PermRegistriesTest = "registries:test"
+ PermRegistriesList = "registries:list"
+ PermRegistriesRead = "registries:read"
+ PermRegistriesCreate = "registries:create"
+ PermRegistriesUpdate = "registries:update"
+ PermRegistriesDelete = "registries:delete"
+ PermRegistriesTest = "registries:test"
+ PermRegistriesBrowse = "registries:browse"
+ PermRegistriesDeleteTags = "registries:delete-tags"
PermTemplatesList = "templates:list"
PermTemplatesRead = "templates:read"
@@ -323,7 +325,7 @@ func BuiltInEditorPermissions() []string {
PermFederatedList, PermFederatedRead,
PermSettingsRead,
PermEnvironmentsList, PermEnvironmentsRead, PermEnvironmentsSync,
- PermRegistriesList, PermRegistriesRead,
+ PermRegistriesList, PermRegistriesRead, PermRegistriesBrowse,
PermTemplatesList, PermTemplatesRead, PermTemplatesCreate, PermTemplatesUpdate, PermTemplatesDelete,
PermVariablesRead, PermVariablesCreate, PermVariablesUpdate, PermVariablesDelete, PermVariablesSync,
PermGitReposList, PermGitReposRead,
diff --git a/backend/pkg/libarcane/registryauth/helpers.go b/backend/pkg/libarcane/registryauth/helpers.go
index bb43376d3..acfa6312a 100644
--- a/backend/pkg/libarcane/registryauth/helpers.go
+++ b/backend/pkg/libarcane/registryauth/helpers.go
@@ -38,34 +38,38 @@ func ExtractRegistryHost(imageRef string) string {
return hostCandidate
}
-func NormalizeRegistryForComparison(url string) string {
- url = strings.TrimSpace(strings.ToLower(url))
+// SplitRegistryURL separates a registry URL into its comparison host and an
+// optional repository namespace: "https://ghcr.io/acme/" yields ("ghcr.io", "acme").
+func SplitRegistryURL(url string) (host, namespace string) {
+ url = strings.TrimSpace(url)
url = strings.TrimPrefix(url, "https://")
url = strings.TrimPrefix(url, "http://")
- url = strings.TrimSuffix(url, "/")
-
- if slash := strings.Index(url, "/"); slash != -1 {
- url = url[:slash]
+ host, namespace, _ = strings.Cut(strings.Trim(url, "/"), "/")
+ host = strings.ToLower(host)
+ if host == "registry-1.docker.io" || host == "index.docker.io" {
+ host = "docker.io"
}
-
- if url == "docker.io" || url == "registry-1.docker.io" || url == "index.docker.io" {
- return "docker.io"
+ // "https://index.docker.io/v1/" is Docker Hub's API path, not a namespace.
+ if host == "docker.io" && (namespace == "v1" || strings.HasPrefix(namespace, "v1/")) {
+ namespace = strings.TrimPrefix(namespace[2:], "/")
}
- return url
+ return host, namespace
+}
+
+func NormalizeRegistryForComparison(url string) string {
+ host, _ := SplitRegistryURL(url)
+ return host
}
func NormalizeRegistryURL(url string) string {
- normalized := NormalizeRegistryForComparison(url)
- if normalized == "docker.io" {
+ host, namespace := SplitRegistryURL(url)
+ if host == "docker.io" {
return "https://index.docker.io/v1/"
}
-
- result := strings.TrimSpace(url)
- result = strings.TrimPrefix(result, "https://")
- result = strings.TrimPrefix(result, "http://")
- result = strings.TrimSuffix(result, "/")
-
- return result
+ if namespace != "" {
+ return host + "/" + namespace
+ }
+ return host
}
func IsRegistryMatch(left, right string) bool {
diff --git a/backend/pkg/libarcane/registryauth/helpers_test.go b/backend/pkg/libarcane/registryauth/helpers_test.go
index 771a5ec0d..ba4f278d4 100644
--- a/backend/pkg/libarcane/registryauth/helpers_test.go
+++ b/backend/pkg/libarcane/registryauth/helpers_test.go
@@ -41,6 +41,24 @@ func TestNormalizeRegistryForComparison(t *testing.T) {
}
}
+func TestSplitRegistryURL(t *testing.T) {
+ tests := []struct{ in, host, namespace string }{
+ {"ghcr.io", "ghcr.io", ""},
+ {"https://ghcr.io/acme/", "ghcr.io", "acme"},
+ {"http://localhost:5000/team/sub", "localhost:5000", "team/sub"},
+ {"registry-1.docker.io", "docker.io", ""},
+ {"https://index.docker.io/v1/", "docker.io", ""},
+ {"https://index.docker.io/v1/acme", "docker.io", "acme"},
+ {"docker.io/acme", "docker.io", "acme"},
+ {"docker.io/v1team", "docker.io", "v1team"},
+ }
+ for _, tt := range tests {
+ host, namespace := SplitRegistryURL(tt.in)
+ assert.Equal(t, tt.host, host, tt.in)
+ assert.Equal(t, tt.namespace, namespace, tt.in)
+ }
+}
+
func TestNormalizeRegistryURL(t *testing.T) {
assert.Equal(t, "https://index.docker.io/v1/", NormalizeRegistryURL("docker.io"))
assert.Equal(t, "ghcr.io", NormalizeRegistryURL("https://ghcr.io/"))
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index e65512e5b..02ea53ad7 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -168,6 +168,7 @@
"common_save": "Save",
"common_saving": "Saving…",
"common_clear": "Clear",
+ "common_error_details": "Error details",
"common_view_all": "View All",
"common_password": "Password",
"common_passkey": "Passkey",
@@ -217,6 +218,7 @@
"common_resize_panels": "Resize panels",
"common_show_left_panel": "Show left panel",
"common_show_right_panel": "Show right panel",
+ "common_select": "Select",
"common_select_all": "Select all",
"common_select_row": "Select row",
"common_showing_of_total": "Showing {shown} of {total} item(s).",
@@ -2006,6 +2008,25 @@
"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.",
+ "registries_browse": "Browse",
+ "registries_repositories": "Repositories",
+ "registries_catalog_unavailable_title": "This registry does not list its repositories",
+ "registries_catalog_unavailable_description": "Docker Hub, GHCR and similar registries do not expose a catalog. Enter a repository name above to browse its tags, or add repository names to this registry so they show up here.",
+ "registries_catalog_unavailable_configured": "This registry does not list its repositories. Showing the names configured on the registry.",
+ "registries_open_repository": "Open Repository",
+ "registries_open_repository_placeholder": "{namespace}/api",
+ "registries_tags_load_failed": "Failed to load the tags of {repository}",
+ "registries_tag_details_unavailable": "Details unavailable",
+ "registries_copy_reference": "Copy image reference",
+ "registries_delete_tag_title": "Delete Tag {tag}",
+ "registries_delete_tag_message": "Delete {reference} from the registry? The manifest is deleted by digest, so every other tag pointing to it is removed too. Storage is reclaimed only after the registry runs garbage collection. This action cannot be undone.",
+ "registries_delete_tag_success": "Deleted {reference}",
+ "registries_delete_tag_failed": "Failed to delete {reference}",
+ "registries_delete_tags_selected_title": "Delete {count} Tag(s)",
+ "registries_delete_tags_selected_message": "Delete the selected tags from the registry? Every other tag pointing to the same manifests is removed too. This action cannot be undone.",
+ "registries_delete_tags_selected_count": "Delete Selected ({count})",
+ "registries_bulk_delete_tags_success": "Deleted {count} tags",
+ "registries_bulk_delete_tags_failed": "Failed to delete {count} tags",
"registry_docker_hub_url": "docker.io",
"registry_github_url": "ghcr.io",
"registry_google_url": "gcr.io",
diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.ts
index 77ea88bb1..5194acaab 100644
--- a/frontend/src/lib/query/query-keys.ts
+++ b/frontend/src/lib/query/query-keys.ts
@@ -72,7 +72,12 @@ export const queryKeys = {
containerRegistries: {
all: ['container-registries'] as const,
list: (options: SearchPaginationSortRequest) => ['container-registries', stableSerialize(options)] as const,
- pullUsage: () => ['container-registries', 'pull-usage'] as const
+ pullUsage: () => ['container-registries', 'pull-usage'] as const,
+ detail: (registryId: string) => ['container-registries', 'detail', registryId] as const,
+ repositories: (registryId: string, options: SearchPaginationSortRequest) =>
+ ['container-registries', 'repositories', registryId, stableSerialize(options)] as const,
+ tags: (registryId: string, repository: string, options: SearchPaginationSortRequest) =>
+ ['container-registries', 'tags', registryId, repository, stableSerialize(options)] as const
},
templates: {
all: ['templates'] as const,
diff --git a/frontend/src/lib/services/container-registry-service.ts b/frontend/src/lib/services/container-registry-service.ts
index 0ea9a4755..f3be98360 100644
--- a/frontend/src/lib/services/container-registry-service.ts
+++ b/frontend/src/lib/services/container-registry-service.ts
@@ -2,7 +2,9 @@ import BaseAPIService from './api-service';
import type {
ContainerRegistryCreateDto,
ContainerRegistryPullUsageResponse,
- ContainerRegistryUpdateDto
+ ContainerRegistryUpdateDto,
+ RegistryRepository,
+ RegistryTag
} from '#lib/types/docker.js';
import type { ContainerRegistry } from '#lib/types/docker.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -38,6 +40,24 @@ class ContainerRegistryService extends BaseAPIService {
async testRegistry(id: string): Promise<unknown> {
return this.handleResponse(this.api.post(`/container-registries/${id}/test`));
}
+
+ async getRepositories(id: string, options?: SearchPaginationSortRequest): Promise<Paginated<RegistryRepository>> {
+ const params = transformPaginationParams(options);
+ const res = await this.api.get(`/container-registries/${id}/repositories`, { params });
+ const page: Paginated<Omit<RegistryRepository, 'id'>> = res.data;
+ return { ...page, data: page.data.map((repository) => ({ ...repository, id: repository.name })) };
+ }
+
+ async getTags(id: string, repository: string, options?: SearchPaginationSortRequest): Promise<Paginated<RegistryTag>> {
+ const params = { ...transformPaginationParams(options), repository };
+ const res = await this.api.get(`/container-registries/${id}/tags`, { params });
+ const page: Paginated<Omit<RegistryTag, 'id'>> = res.data;
+ return { ...page, data: page.data.map((tag) => ({ ...tag, id: tag.name })) };
+ }
+
+ async deleteTag(id: string, repository: string, tag: string): Promise<{ digest: string }> {
+ return this.handleResponse(this.api.delete(`/container-registries/${id}/tags`, { params: { repository, tag } }));
+ }
}
export const containerRegistryService = new ContainerRegistryService();
diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.ts
index e8b51e120..ae0d945fd 100644
--- a/frontend/src/lib/types/docker.ts
+++ b/frontend/src/lib/types/docker.ts
@@ -1046,6 +1046,30 @@ export interface ContainerRegistry {
updatedAt?: string;
}
+export interface RegistryRepository {
+ id: string;
+ name: string;
+}
+
+export interface RegistryTagPlatform {
+ os: string;
+ architecture: string;
+ variant?: string;
+ digest: string;
+ size: number;
+}
+
+export interface RegistryTag {
+ id: string;
+ name: string;
+ digest?: string;
+ mediaType?: string;
+ size: number;
+ created?: string;
+ platforms: RegistryTagPlatform[];
+ error?: string;
+}
+
export interface ContainerRegistryPullUsageResponse {
registries: ContainerRegistryPullUsage[];
}
diff --git a/frontend/src/lib/utils/registry.ts b/frontend/src/lib/utils/registry.ts
index 9a4007e5d..edb011558 100644
--- a/frontend/src/lib/utils/registry.ts
+++ b/frontend/src/lib/utils/registry.ts
@@ -45,6 +45,16 @@ function normalizeRegistryHost(url: string): string {
return url.replace(/^https?:\/\//, '').replace(/\/+$/, '');
}
+/**
+ * Splits a registry URL into its host and the repository namespace in its path.
+ * Docker Hub's `/v1/` API path is not a namespace.
+ */
+export function splitRegistryUrl(url: string): { host: string; namespace: string } {
+ const [host = '', ...path] = normalizeRegistryHost(url || 'docker.io').split('/');
+ if (/^(index\.|registry-1\.)?docker\.io$/i.test(host) && path[0] === 'v1') path.shift();
+ return { host, namespace: path.join('/') };
+}
+
/**
* Builds a `host/repository:tag` reference, or an empty string when the
* repository name or tag is missing.
diff --git a/frontend/src/routes/(app)/customize/registries/[id]/+page.svelte b/frontend/src/routes/(app)/customize/registries/[id]/+page.svelte
new file mode 100644
index 000000000..74fcd3345
--- /dev/null
+++ b/frontend/src/routes/(app)/customize/registries/[id]/+page.svelte
@@ -0,0 +1,397 @@
+<script lang="ts">
+ import { goto, refreshAll } from '$app/navigation';
+ import { toast } from 'svelte-sonner';
+ import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import { EmptyState } from '#lib/components/states/index.js';
+ import * as Alert from '#lib/components/ui/alert/index.js';
+ import { Badge } from '#lib/components/ui/badge/index.js';
+ import * as Breadcrumb from '#lib/components/ui/breadcrumb/index.js';
+ import { Checkbox } from '#lib/components/ui/checkbox/index.js';
+ import { CopyButton } from '#lib/components/ui/copy-button/index.js';
+ import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
+ import * as InputGroup from '#lib/components/ui/input-group/index.js';
+ import { Spinner } from '#lib/components/ui/spinner/index.js';
+ import { ResourceDetailLayout, type DetailAction } from '#lib/layouts/index.js';
+ import { AlertTriangleIcon, ArrowRightIcon, RegistryIcon, SearchIcon, TagIcon, TrashIcon } from '#lib/icons/index.js';
+ import { m } from '#lib/paraglide/messages.js';
+ import { containerRegistryService } from '#lib/services/container-registry-service.js';
+ import type { RegistryTag } from '#lib/types/docker.js';
+ import { cn } from '#lib/utils.js';
+ import { hasPermission } from '#lib/utils/auth.js';
+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions.js';
+ import { bytes, formatRelativeTime } from '#lib/utils/formatting.js';
+ import { buildImageReference, splitRegistryUrl } from '#lib/utils/registry.js';
+ import { debounced } from '#lib/utils/ws.js';
+
+ let { data } = $props();
+
+ const registry = $derived(data.registry);
+ const registryLabel = $derived(registry.url || 'docker.io');
+ // Repository names already carry any namespace from the registry URL.
+ const { host: registryHost, namespace: registryNamespace } = $derived(splitRegistryUrl(registry.url));
+ const repository = $derived(data.repository);
+ const tags = $derived(data.tags);
+ const canDeleteTags = $derived(hasPermission('registries:delete-tags'));
+
+ let selecting = $state(false);
+ let selected = $state<string[]>([]);
+ let deletingTag = $state<string | null>(null);
+ let bulkDeleting = $state(false);
+ let refreshing = $state(false);
+
+ // Configured names are relative to the registry URL namespace, like the build flow.
+ const configuredNames = $derived(
+ (registry.repositoryNames ?? []).map((name) => (registryNamespace ? `${registryNamespace}/${name}` : name))
+ );
+ const repositories = $derived(data.catalog?.data.map((item) => item.name) ?? configuredNames);
+
+ function navigate(patch: { repository?: string; search?: string; page?: number }) {
+ const params = new URLSearchParams();
+ const target = patch.repository ?? repository;
+ if (target) params.set('repository', target);
+ const search = patch.search ?? data.search;
+ if (search) params.set('search', search);
+ if ((patch.page ?? 1) > 1) params.set('page', String(patch.page));
+ selecting = false;
+ selected = [];
+ goto(`/customize/registries/${registry.id}?${params}`, { reset: false });
+ }
+
+ const search = debounced((value: string) => navigate({ search: value.trim(), page: 1 }), 300);
+
+ function submitRepositoryQuery(event: SubmitEvent) {
+ event.preventDefault();
+ const value = String(new FormData(event.currentTarget as HTMLFormElement).get('query') ?? '')
+ .trim()
+ .replace(/^\/+|\/+$/g, '');
+ if (data.catalog) {
+ navigate({ search: value, page: 1 });
+ } else if (value) {
+ navigate({ repository: value, search: '', page: 1 });
+ }
+ }
+
+ function tagReference(tag: string) {
+ return buildImageReference(registryHost, repository, tag);
+ }
+
+ function platformLabel(platform: RegistryTag['platforms'][number]) {
+ return [platform.os, platform.architecture, platform.variant].filter(Boolean).join('/');
+ }
+
+ function tagMeta(tag: RegistryTag) {
+ if (tag.error) return m.registries_tag_details_unavailable();
+ const parts = [bytes.format(tag.size)];
+ if (tag.created) parts.push(formatRelativeTime(tag.created));
+ return parts.join(' · ');
+ }
+
+ function toggleSelected(tag: string, checked: boolean) {
+ if (checked) {
+ selected = [...selected, tag];
+ } else {
+ selected = selected.filter((name) => name !== tag);
+ }
+ }
+
+ async function refresh() {
+ refreshing = true;
+ await refreshAll();
+ refreshing = false;
+ }
+
+ function handleDeleteOne(tag: string) {
+ const reference = tagReference(tag);
+ confirmAndRun({
+ title: m.registries_delete_tag_title({ tag }),
+ message: m.registries_delete_tag_message({ reference }),
+ confirmLabel: m.common_delete(),
+ destructive: true,
+ setLoading: (loading) => (deletingTag = loading ? tag : null),
+ run: () => containerRegistryService.deleteTag(registry.id, repository, tag),
+ failureMessage: m.registries_delete_tag_failed({ reference }),
+ onSuccess: async () => {
+ toast.success(m.registries_delete_tag_success({ reference }));
+ await refreshAll();
+ }
+ });
+ }
+
+ function handleDeleteSelected() {
+ const ids = selected;
+ if (!ids.length) return;
+ // Tags sharing a digest are deleted together, so a second request for the same digest would 404.
+ const digestByTag = new Map(tags.data.map((tag) => [tag.name, tag.digest]));
+ const seenDigests = new Set<string>();
+ const tagsToDelete = ids.filter((tag) => {
+ const digest = digestByTag.get(tag);
+ if (!digest) return true;
+ if (seenDigests.has(digest)) return false;
+ seenDigests.add(digest);
+ return true;
+ });
+
+ bulkConfirmAndRun({
+ ids: tagsToDelete,
+ title: m.registries_delete_tags_selected_title({ count: ids.length }),
+ message: m.registries_delete_tags_selected_message(),
+ confirmLabel: m.common_delete(),
+ destructive: true,
+ run: (tag) => containerRegistryService.deleteTag(registry.id, repository, tag),
+ messages: {
+ success: () => m.registries_bulk_delete_tags_success({ count: ids.length }),
+ partial: (success, total, failed) => m.common_bulk_delete_partial({ success, total, failed, resource: m.common_tags() }),
+ failure: () => m.registries_bulk_delete_tags_failed({ count: ids.length })
+ },
+ setLoading: (loading) => (bulkDeleting = loading),
+ onComplete: async ({ success }) => {
+ if (success > 0) await refreshAll();
+ },
+ clearSelection: () => {
+ selected = [];
+ selecting = false;
+ },
+ sequential: true
+ });
+ }
+
+ const actions: DetailAction[] = $derived([
+ {
+ id: 'refresh',
+ action: 'refresh',
+ label: m.common_refresh(),
+ loading: refreshing,
+ disabled: refreshing,
+ onclick: refresh
+ }
+ ]);
+</script>
+
+{#snippet repositoryGrid()}
+ <div class="space-y-4">
+ <form class="flex flex-wrap items-center gap-2" onsubmit={submitRepositoryQuery}>
+ <InputGroup.Root class="min-w-0 flex-1 md:w-80 md:flex-none">
+ <InputGroup.Addon>
+ <SearchIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ {#if data.catalog}
+ <InputGroup.Input
+ name="query"
+ value={data.search}
+ placeholder={m.common_search()}
+ oninput={(e) => search(e.currentTarget.value)}
+ />
+ {:else}
+ <InputGroup.Input
+ name="query"
+ placeholder={m.registries_open_repository_placeholder({ namespace: registryNamespace })}
+ />
+ {/if}
+ </InputGroup.Root>
+ {#if data.catalogError}
+ <ArcaneButton action="inspect" type="submit" customLabel={m.registries_open_repository()} />
+ {/if}
+ </form>
+
+ {#if data.catalogError && repositories.length > 0}
+ <p class="text-sm text-muted-foreground">{m.registries_catalog_unavailable_configured()}</p>
+ {/if}
+
+ {#if repositories.length > 0}
+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
+ {#each repositories as name (name)}
+ <button
+ type="button"
+ class="group flex items-center gap-3 rounded-xl border border-border/50 bg-card/30 p-4 text-left transition-colors hover:bg-muted/40"
+ onclick={() => navigate({ repository: name, search: '', page: 1 })}
+ >
+ <span
+ class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary ring-1 ring-primary/20 ring-inset group-hover:bg-primary/15"
+ >
+ <RegistryIcon class="size-5" />
+ </span>
+ <span class="min-w-0 flex-1">
+ <span class="block truncate font-medium">{name}</span>
+ <span class="block truncate text-xs text-muted-foreground">{registryHost}/{name}</span>
+ </span>
+ <ArrowRightIcon class="size-4 shrink-0 text-muted-foreground" />
+ </button>
+ {/each}
+ </div>
+ {#if data.catalog && data.catalog.pagination.totalItems > repositories.length}
+ <p class="text-xs text-muted-foreground">
+ {m.common_showing_of_total({ shown: repositories.length, total: data.catalog.pagination.totalItems })}
+ </p>
+ {/if}
+ {:else if data.catalog}
+ <EmptyState icon={SearchIcon} title={m.common_no_results_found()} description={m.common_no_results_hint()} />
+ {:else if data.catalogError}
+ <EmptyState
+ icon={RegistryIcon}
+ title={m.registries_catalog_unavailable_title()}
+ description={m.registries_catalog_unavailable_description()}
+ >
+ <details class="w-full max-w-2xl rounded-lg border border-border/60 bg-muted/15 text-left">
+ <summary class="cursor-pointer px-4 py-2 text-sm font-medium select-none">{m.common_error_details()}</summary>
+ <p class="border-t px-4 py-3 font-mono text-xs break-all text-muted-foreground">{data.catalogError}</p>
+ </details>
+ </EmptyState>
+ {/if}
+ </div>
+{/snippet}
+
+{#snippet tagList()}
+ <div class="space-y-4">
+ <div class="flex flex-wrap items-center gap-3">
+ <Breadcrumb.Root class="min-w-0 flex-1">
+ <Breadcrumb.List>
+ <Breadcrumb.Item>
+ <Breadcrumb.Link onclick={() => navigate({ repository: '', search: '', page: 1 })} class="cursor-pointer">
+ {m.registries_repositories()}
+ </Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Page><span class="font-mono">{repository}</span></Breadcrumb.Page>
+ </Breadcrumb.Item>
+ </Breadcrumb.List>
+ </Breadcrumb.Root>
+ <CopyButton text={`${registryHost}/${repository}`} class="size-7" title={m.registries_copy_reference()} />
+ </div>
+
+ <div class="flex flex-wrap items-center gap-2">
+ <InputGroup.Root class="min-w-0 flex-1 md:w-80 md:flex-none">
+ <InputGroup.Addon>
+ <SearchIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ <InputGroup.Input value={data.search} placeholder={m.common_search()} oninput={(e) => search(e.currentTarget.value)} />
+ </InputGroup.Root>
+ {#if canDeleteTags && tags.data.length > 0}
+ <div class="ml-auto flex items-center gap-2">
+ {#if selecting}
+ <ArcaneButton
+ action="remove"
+ size="sm"
+ customLabel={m.registries_delete_tags_selected_count({ count: selected.length })}
+ disabled={selected.length === 0 || bulkDeleting}
+ loading={bulkDeleting}
+ onclick={handleDeleteSelected}
+ />
+ <ArcaneButton
+ action="cancel"
+ size="sm"
+ onclick={() => {
+ selecting = false;
+ selected = [];
+ }}
+ />
+ {:else}
+ <ArcaneButton action="base" size="sm" customLabel={m.common_select()} onclick={() => (selecting = true)} />
+ {/if}
+ </div>
+ {/if}
+ </div>
+
+ {#if data.tagsError}
+ <Alert.Root variant="destructive">
+ <AlertTriangleIcon class="size-4" />
+ <Alert.Title>{m.registries_tags_load_failed({ repository })}</Alert.Title>
+ <Alert.Description>{data.tagsError}</Alert.Description>
+ </Alert.Root>
+ {:else if tags.data.length === 0}
+ <EmptyState icon={TagIcon} title={m.common_no_results_found()} description={m.common_no_results_hint()} />
+ {:else}
+ <div class="divide-y divide-border/60 overflow-hidden rounded-lg border border-border/60">
+ {#each tags.data as tag (tag.name)}
+ <div
+ class={cn(
+ 'group flex flex-wrap items-center gap-x-3 gap-y-1.5 px-4 py-3 transition-colors hover:bg-muted/40 lg:flex-nowrap',
+ selected.includes(tag.name) && 'bg-muted/40'
+ )}
+ >
+ {#if selecting}
+ <Checkbox
+ checked={selected.includes(tag.name)}
+ onCheckedChange={(checked) => toggleSelected(tag.name, checked === true)}
+ aria-label={m.common_select_row()}
+ />
+ {:else}
+ <TagIcon class="size-4 shrink-0 text-muted-foreground" />
+ {/if}
+ <div class="min-w-0 flex-1">
+ <div class="flex items-center gap-1">
+ <span class="truncate font-medium">{tag.name}</span>
+ <span class="opacity-0 group-hover:opacity-100 focus-within:opacity-100">
+ <CopyButton text={tagReference(tag.name)} class="size-6" title={m.registries_copy_reference()} />
+ </span>
+ </div>
+ <p class="truncate text-xs text-muted-foreground" title={tag.error}>{tagMeta(tag)}</p>
+ </div>
+ {#if tag.digest}
+ <div class="order-2 flex w-full min-w-0 items-center gap-1 lg:order-none lg:w-auto lg:flex-1">
+ <code class="truncate font-mono text-xs text-muted-foreground" title={tag.digest}>{tag.digest}</code>
+ <CopyButton text={tag.digest} class="size-6 shrink-0" title={m.images_attestations_digest()} />
+ </div>
+ {/if}
+ {#if tag.platforms.length > 0}
+ <div class="order-3 flex w-full flex-wrap gap-1 lg:order-none lg:w-auto lg:justify-end">
+ {#each tag.platforms as platform (platform.digest)}
+ <Badge variant="outline">{platformLabel(platform)}</Badge>
+ {/each}
+ </div>
+ {/if}
+ {#if canDeleteTags && !selecting}
+ <RowActionsMenu
+ triggerClass="order-1 size-8 shrink-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 lg:order-none"
+ >
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteOne(tag.name)}
+ disabled={deletingTag === tag.name}
+ >
+ {#if deletingTag === tag.name}
+ <Spinner class="size-4" />
+ {:else}
+ <TrashIcon class="size-4" />
+ {/if}
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </RowActionsMenu>
+ {/if}
+ </div>
+ {/each}
+ </div>
+
+ {#if tags.pagination.totalPages > 1}
+ <div class="flex items-center justify-between text-sm text-muted-foreground">
+ <span>{m.common_page_of({ page: tags.pagination.currentPage, total: tags.pagination.totalPages })}</span>
+ <div class="flex gap-2">
+ <ArcaneButton
+ action="base"
+ size="sm"
+ customLabel={m.common_previous()}
+ disabled={tags.pagination.currentPage <= 1}
+ onclick={() => navigate({ page: tags.pagination.currentPage - 1 })}
+ />
+ <ArcaneButton
+ action="base"
+ size="sm"
+ customLabel={m.common_next()}
+ disabled={tags.pagination.currentPage >= tags.pagination.totalPages}
+ onclick={() => navigate({ page: tags.pagination.currentPage + 1 })}
+ />
+ </div>
+ </div>
+ {/if}
+ {/if}
+ </div>
+{/snippet}
+
+<ResourceDetailLayout backUrl="/customize/registries" backLabel={m.registries_title()} title={registryLabel} {actions}>
+ {#if repository}
+ {@render tagList()}
+ {:else}
+ {@render repositoryGrid()}
+ {/if}
+</ResourceDetailLayout>
diff --git a/frontend/src/routes/(app)/customize/registries/[id]/+page.ts b/frontend/src/routes/(app)/customize/registries/[id]/+page.ts
new file mode 100644
index 000000000..061829ede
--- /dev/null
+++ b/frontend/src/routes/(app)/customize/registries/[id]/+page.ts
@@ -0,0 +1,91 @@
+import { tryCatch } from '#lib/utils/try-catch.js';
+import { containerRegistryService } from '#lib/services/container-registry-service.js';
+import { queryKeys } from '#lib/query/query-keys.js';
+import type { RegistryRepository, RegistryTag } from '#lib/types/docker.js';
+import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
+import { extractApiErrorMessage, throwPageLoadError } from '#lib/utils/api.js';
+import { m } from '#lib/paraglide/messages.js';
+import type { PageLoad } from './$types';
+
+const catalogPageSize = 500;
+const tagsPageSize = 50;
+
+export const load: PageLoad = async ({ params, parent, url }) => {
+ const { queryClient } = await parent();
+
+ const registryResult = await tryCatch(
+ queryClient.query({
+ queryKey: queryKeys.containerRegistries.detail(params.id),
+ queryFn: () => containerRegistryService.getRegistry(params.id)
+ })
+ );
+ if (registryResult.error !== null) {
+ throwPageLoadError(registryResult.error, m.common_load_failed({ resource: m.resource_registry() }));
+ }
+
+ const repository =
+ url.searchParams
+ .get('repository')
+ ?.trim()
+ .replace(/^\/+|\/+$/g, '') ?? '';
+ const search = url.searchParams.get('search')?.trim() ?? '';
+ const page = Math.max(1, Number(url.searchParams.get('page')) || 1);
+
+ // The catalog is only needed for the repository grid. Registries without a
+ // catalog API fail here, and the page offers opening a repository by name instead.
+ let catalog: Paginated<RegistryRepository> | null = null;
+ let catalogError: string | null = null;
+ if (!repository) {
+ const catalogRequest: SearchPaginationSortRequest = {
+ search,
+ pagination: { page: 1, limit: catalogPageSize },
+ sort: { column: 'name', direction: 'asc' }
+ };
+ const catalogResult = await tryCatch(
+ queryClient.query({
+ queryKey: queryKeys.containerRegistries.repositories(params.id, catalogRequest),
+ queryFn: () => containerRegistryService.getRepositories(params.id, catalogRequest),
+ staleTime: 30_000
+ })
+ );
+ if (catalogResult.error === null) {
+ catalog = catalogResult.data;
+ } else {
+ catalogError = extractApiErrorMessage(catalogResult.error);
+ }
+ }
+ const tagsRequest: SearchPaginationSortRequest = {
+ search,
+ pagination: { page, limit: tagsPageSize },
+ sort: { column: 'name', direction: 'asc' }
+ };
+
+ let tags: Paginated<RegistryTag> = {
+ data: [],
+ pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: tagsPageSize }
+ };
+ let tagsError: string | null = null;
+ if (repository) {
+ const tagsResult = await tryCatch(
+ queryClient.query({
+ queryKey: queryKeys.containerRegistries.tags(params.id, repository, tagsRequest),
+ queryFn: () => containerRegistryService.getTags(params.id, repository, tagsRequest)
+ })
+ );
+ if (tagsResult.error === null) {
+ tags = tagsResult.data;
+ } else {
+ tagsError = extractApiErrorMessage(tagsResult.error);
+ }
+ }
+
+ return {
+ registry: registryResult.data,
+ catalog,
+ catalogError,
+ repository,
+ search,
+ tags,
+ tagsError
+ };
+};
diff --git a/frontend/src/routes/(app)/customize/registries/registry-table.svelte b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
index d0788ecd9..1a8ca692b 100644
--- a/frontend/src/routes/(app)/customize/registries/registry-table.svelte
+++ b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
@@ -14,7 +14,8 @@
import CreatedAtCell from '#lib/components/arcane-table/cells/created-at-cell.svelte';
import { m } from '#lib/paraglide/messages.js';
import { containerRegistryService } from '#lib/services/container-registry-service.js';
- import { RegistryIcon, UserIcon, ExternalLinkIcon, EditIcon, TrashIcon, TestIcon } from '#lib/icons/index.js';
+ import { RegistryIcon, UserIcon, ExternalLinkIcon, EditIcon, TrashIcon, TestIcon, FolderOpenIcon } from '#lib/icons/index.js';
+ import { goto } from '$app/navigation';
import { hasPermission } from '#lib/utils/auth.js';
import { getRegistryDisplayName } from '#lib/utils/registry.js';
import IfPermitted from '#lib/components/if-permitted.svelte';
@@ -38,6 +39,7 @@
let testingId = $state<string | null>(null);
const canDeleteRegistry = $derived(hasPermission('registries:delete'));
+ const canBrowseRegistry = $derived(hasPermission('registries:read') && hasPermission('registries:browse'));
function maskAccessKeyId(keyId: string | undefined): string {
if (!keyId) return m.common_na();
@@ -188,7 +190,11 @@
{#snippet UrlCell({ item }: { item: ContainerRegistry })}
<div class="flex flex-col">
- <span class="font-medium">{item.url || 'docker.io'}</span>
+ {#if canBrowseRegistry}
+ <a class="font-medium hover:underline" href="/customize/registries/{item.id}">{item.url || 'docker.io'}</a>
+ {:else}
+ <span class="font-medium">{item.url || 'docker.io'}</span>
+ {/if}
<span class="text-xs text-muted-foreground">{getRegistryDisplayName(item)}</span>
</div>
{/snippet}
@@ -221,6 +227,7 @@
icon={{ component: RegistryIcon, variant: 'purple' as const }}
title={(item) => item.url}
subtitle={(item) => ((mobileFieldVisibility['id'] ?? true) ? item.id : null)}
+ onclick={canBrowseRegistry ? (item: ContainerRegistry) => goto(`/customize/registries/${item.id}`) : undefined}
badges={[{ variant: 'purple' as const, text: m.common_registry() }]}
fields={[
{
@@ -254,6 +261,13 @@
{#snippet RowActions({ item }: { item: ContainerRegistry })}
<RowActionsMenu>
+ {#if canBrowseRegistry}
+ <DropdownMenu.Item onclick={() => goto(`/customize/registries/${item.id}`)}>
+ <FolderOpenIcon class="size-4" />
+ {m.registries_browse()}
+ </DropdownMenu.Item>
+ {/if}
+
<IfPermitted perm="registries:test">
<DropdownMenu.Item onclick={() => handleTest(item.id, item.url)} disabled={testingId === item.id}>
{#if testingId === item.id}
diff --git a/types/containerregistry/browse.go b/types/containerregistry/browse.go
new file mode 100644
index 000000000..c685cddfc
--- /dev/null
+++ b/types/containerregistry/browse.go
@@ -0,0 +1,85 @@
+package containerregistry
+
+import "time"
+
+// Repository is an image repository stored in a container registry.
+type Repository struct {
+ // Name of the repository, without the registry host.
+ //
+ // Required: true
+ Name string `json:"name"`
+}
+
+// RepositoryTag describes a tag of a repository and the manifest it points to.
+type RepositoryTag struct {
+ // Name of the tag.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // Digest of the manifest the tag points to.
+ //
+ // Required: false
+ Digest string `json:"digest,omitempty"`
+
+ // MediaType of the manifest the tag points to.
+ //
+ // Required: false
+ MediaType string `json:"mediaType,omitempty"`
+
+ // Size is the compressed size in bytes of every platform image.
+ //
+ // Required: true
+ Size int64 `json:"size"`
+
+ // Created is the creation date of the image, when a single platform is published.
+ //
+ // Required: false
+ Created *time.Time `json:"created,omitempty"`
+
+ // Platforms published under the tag.
+ //
+ // Required: true
+ Platforms []TagPlatform `json:"platforms"`
+
+ // Error explains why the manifest details could not be loaded.
+ //
+ // Required: false
+ Error string `json:"error,omitempty"`
+}
+
+// TagPlatform describes one platform image published under a tag.
+type TagPlatform struct {
+ // OS of the platform image.
+ //
+ // Required: true
+ OS string `json:"os"`
+
+ // Architecture of the platform image.
+ //
+ // Required: true
+ Architecture string `json:"architecture"`
+
+ // Variant of the platform architecture.
+ //
+ // Required: false
+ Variant string `json:"variant,omitempty"`
+
+ // Digest of the platform image manifest.
+ //
+ // Required: true
+ Digest string `json:"digest"`
+
+ // Size is the compressed size in bytes of the platform image.
+ //
+ // Required: true
+ Size int64 `json:"size"`
+}
+
+// DeleteTagResponse reports the manifest removed from the registry.
+type DeleteTagResponse struct {
+ // Digest of the deleted manifest. Every tag pointing to it is removed.
+ //
+ // Required: true
+ Digest string `json:"digest"`
+}