registryserver

package
v1.10.21 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0

Documentation

Overview

Package registryserver runs and authorizes the platform's built-in, multi-tenant Docker registry. The registry runs on the platform's private network and requires Basic auth there, which only the gateway holds; a TENANT's request is authorized at the edge by a Goma forwardAuth middleware calling Authorize. Distinct from services/registry (external credentials).

Index

Constants

View Source
const (
	ContainerName = "mb-registry"
	Alias         = "mb-registry"
	Port          = 5000
)

ContainerName / Alias are the registry container's name and its DNS alias on the platform's private network (the route upstream is http://mb-registry:5000).

View Source
const (
	// DefaultTagPreview is how many of a repository's newest tags the browse
	// list carries. The list exists to find a repository, not to read its
	// history — the rest are one click away on the repository page.
	DefaultTagPreview = 4
)

Tag-preview and enrichment bounds.

View Source
const Realm = `Basic realm="Miabi Registry"`

Realm is advertised in the WWW-Authenticate challenge on the login handshake.

Variables

View Source
var (
	// ErrInvalidRepository rejects a repository name that is not a name at all. The browse API takes
	// it from a query parameter and joins it under the caller's namespace, so a name carrying `..`
	// or its own slashes would address a path the caller was never scoped to.
	ErrInvalidRepository = errors.New("invalid repository name")
	// ErrInvalidTag rejects a tag outside the distribution grammar, for the same reason.
	ErrInvalidTag = errors.New("invalid tag")
)
View Source
var (
	// ErrForeignNamespace is returned when an image reference addresses this registry under a namespace
	// belonging to a different workspace. It is a tenant boundary violation, not a typo: the platform
	// credential used to pull distributed images is authorized for every namespace.
	ErrForeignNamespace = errors.New("image belongs to another workspace's registry namespace")
	// ErrUnknownNamespace is returned when an internal-registry reference names a namespace that resolves to
	// no workspace. It is refused rather than passed through: a namespace that is free today can be claimed
	// by a rename tomorrow, which would silently turn a broken reference into a foreign one.
	ErrUnknownNamespace = errors.New("image names an unknown workspace registry namespace")
	// ErrHostInvalid is returned when the configured registry hostname is not a
	// usable Docker registry host.
	ErrHostInvalid = config.ErrRegistryHostInvalid
)
View Source
var (
	// ErrNotFound is returned when a repository, tag, or manifest is absent.
	ErrNotFound = errors.New("registry: not found")
	// ErrDeleteDisabled is returned when the registry's delete API is off
	// (REGISTRY_STORAGE_DELETE_ENABLED=false / the DeleteEnabled setting).
	ErrDeleteDisabled = errors.New("registry: delete is not enabled")
	// ErrTagInUse is returned when the tag resolves to an image a live deployment or a pinned release still
	// holds. Deleting it would leave that release unpullable, and the failure would surface later, on a node,
	// as a mystery.
	ErrTagInUse = errors.New("registry: this image is used by a live deployment or a pinned release")
)
View Source
var ErrNoInternalNetwork = errors.New(
	"refusing to start the internal registry: it has no private network to join, and the shared proxy " +
		"network is not a substitute — it is reachable by every app container. Add the platform's private " +
		"network to your stack (labelled " + docker.LabelRole + "=" + docker.RolePlatformInternal + "), or " +
		"name it explicitly with MIABI_INTERNAL_NETWORK")

ErrNoInternalNetwork refuses to start the registry when the platform has no private network to put it on. It used to fall back to the shared proxy network with a warning, which meant every app container could pull any workspace's images from http://mb-registry:5000 with no credential — the warning was the only thing standing between a Compose install and a cross-tenant image leak.

Functions

func Namespace

func Namespace(workspaceID uint) string

Namespace is the immutable storage namespace for a workspace — the repository prefix the gateway rewrites the (mutable) workspace name to before forwarding to the registry, so images survive a workspace rename. e.g. ws_1.

func NormalizeHost added in v1.6.8

func NormalizeHost(raw string) (string, error)

NormalizeHost validates a registry hostname and returns its canonical form, or "" for an unset one. The rule lives in the config package because boot has to apply it before this service exists; this is the same check, reachable from the registry code that depends on it.

func SortTags added in v1.6.8

func SortTags(tags []string)

SortTags orders a repository's tags for display: "latest" first, then newest version first. Plain lexicographic order puts v10 before v9 and buries "latest" in the middle. Runs of digits are compared numerically and reversed; tags with no digits end up reverse-alphabetical, which is arbitrary but stable.

Types

type AuthInput

type AuthInput struct {
	Authorization string // raw Authorization header
	Method        string // X-Forwarded-Method (else the request method)
	URI           string // X-Forwarded-Uri (the /v2/... path)
}

AuthInput is the forwarded registry request context (from Goma forwardAuth).

type AuthResult

type AuthResult struct {
	Status      int    // 200 allow, 401 unauthenticated, 403 forbidden
	Challenge   bool   // emit WWW-Authenticate: Basic on a 401
	Workspace   string // workspace name (docker username) on allow
	WorkspaceID uint   // workspace id on allow
	UserID      uint   // token owner's user id on allow
	Namespace   string // ws_<id> — the namespace the gateway rewrites to
	Reason      string // human reason (denials)
}

AuthResult is the authorization decision the auth endpoint translates to HTTP. On allow it also carries the rewrite target: the gateway sets the request's repository namespace segment to Namespace (ws_<id>) before forwarding, so storage keys off the immutable id while users address by name.

func (AuthResult) Allowed

func (r AuthResult) Allowed() bool

Allowed reports whether the request is authorized.

type Catalog added in v1.6.8

type Catalog interface {
	ProtectedDigests() (map[string]bool, error)
	ByDigests(workspaceID uint, digests []string) (map[string]models.Image, error)
}

Catalog supplies what the platform knows about the images it built: which digests must not be deleted, and the build behind a digest. Implemented by image.Service. nil-safe — without it tags still list, just unannotated, and tag deletion loses its in-use guard.

type Client

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

Client is a minimal client for the internal registry (reached over the platform's private network at http://mb-registry:5000). Used for the workspace repository view and tag deletion, never exposed to tenants directly.

The registry requires Basic auth even on that network, so the control plane is a credentialed client like the gateway. The credential is resolved per request rather than captured, because it derives from the master key and this client is built before crypto.Init has run.

func NewClient

func NewClient(baseURL string, authHeader func() string) *Client

NewClient builds a registry client for baseURL (e.g. http://mb-registry:5000). authHeader supplies the Authorization value on every request; nil or an empty result sends none.

func (*Client) BlobSizes

func (c *Client) BlobSizes(ctx context.Context, repo, ref string) (map[string]int64, error)

BlobSizes returns the (digest → size) of the blobs a tag references — the config and layers — so a namespace's usage can be summed with cross-tag dedup. For a multi-arch index it recurses into the child manifests.

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context) ([]string, error)

Catalog returns every repository in the registry (all namespaces), following the Distribution pagination Link headers.

func (*Client) DeleteManifest

func (c *Client) DeleteManifest(ctx context.Context, repo, digest string) error

DeleteManifest deletes a manifest by digest (the registry has no delete-by-tag; requires REGISTRY_STORAGE_DELETE_ENABLED). Deleting the manifest untags every tag pointing at it.

func (*Client) ManifestDigest

func (c *Client) ManifestDigest(ctx context.Context, repo, ref string) (string, error)

ManifestDigest resolves a tag to its content digest (needed to delete it).

func (*Client) ManifestInfo added in v1.6.8

func (c *Client) ManifestInfo(ctx context.Context, repo, ref string) (digest string, sizeBytes int64, err error)

ManifestInfo resolves a reference to its content digest and the total size of the blobs it references, from a single manifest fetch. Listing a page of tags needs both, and the registry returns them from the same request — resolving them separately would double the round trips per tag.

func (*Client) TagManifest

func (c *Client) TagManifest(ctx context.Context, repo, digest, tag string) error

TagManifest points tag at an existing digest in repo without re-uploading any blobs: it fetches the digest's manifest and re-PUTs the identical bytes under the tag. Used to add a human-readable release tag to an already-pushed build image. repo is the internal storage path (ws_<id>/<app-name>).

func (*Client) Tags

func (c *Client) Tags(ctx context.Context, repo string) ([]string, error)

Tags returns the tags of a repository (empty when the repo has none).

type Locks added in v1.7.3

type Locks struct {
	Enabled bool `json:"enabled"`
	Host    bool `json:"host"`
	Storage bool `json:"storage"`
	// S3 is per-field: an install may pin the bucket in the environment and leave
	// the credentials to the UI, or the reverse.
	S3Endpoint  bool `json:"s3_endpoint"`
	S3Bucket    bool `json:"s3_bucket"`
	S3Region    bool `json:"s3_region"`
	S3AccessKey bool `json:"s3_access_key"`
	S3SecretKey bool `json:"s3_secret_key"`
	S3ForcePath bool `json:"s3_force_path_style"`
}

Locks reports which fields the environment has pinned. A locked field is read-only: Save ignores it, and the admin UI renders it as fixed with the variable that owns it, rather than offering an input whose value the server would discard.

func (Locks) Any added in v1.7.3

func (l Locks) Any() bool

Any reports whether the environment pins anything at all.

type Repository

type Repository struct {
	Name string   `json:"name"`
	Tags []string `json:"tags"`
}

Repository is a workspace repository and its tags, with the immutable ws_<id> storage namespace stripped so callers see the user-facing image name.

type RepositoryOverview added in v1.6.8

type RepositoryOverview struct {
	Name      string   `json:"name"`
	TagCount  int      `json:"tag_count"`
	Tags      []string `json:"tags"` // preview, display order
	LatestTag *TagInfo `json:"latest_tag,omitempty"`
}

RepositoryOverview is the summary shown on a repository's page. It deliberately does not total the repository's size: that would mean one manifest read per tag, and a repository accumulating build tags has hundreds. The newest tag's size is both cheap and the number people actually mean.

type RepositorySummary added in v1.6.8

type RepositorySummary struct {
	Name string `json:"name"`
	// TagCount is the repository's full tag count; Tags carries only the newest
	// DefaultTagPreview of them, in display order.
	TagCount int      `json:"tag_count"`
	Tags     []string `json:"tags"`
}

RepositorySummary is a repository as it appears in the browse list.

type Runtime added in v1.7.3

type Runtime struct {
	// Running is the single question the UI leads with: is the registry actually
	// serving? Configured-and-enabled says nothing about that.
	Running bool `json:"running"`
	// State / Status are Docker's own words ("running", "Up 3 days"), shown as-is
	// so a stuck container is recognisable rather than flattened to "not running".
	State  string `json:"state,omitempty"`
	Status string `json:"status,omitempty"`
	Health string `json:"health,omitempty"`
	// RestartCount surfaces a crash-looping registry, which otherwise looks
	// healthy in snapshots taken between restarts.
	RestartCount int    `json:"restart_count,omitempty"`
	StartedAt    string `json:"started_at,omitempty"`
	Image        string `json:"image,omitempty"`

	// Stats is a live sample; zero when the container is not running.
	Stats *docker.StatsSample `json:"stats,omitempty"`
	// StatsError explains a sample that could not be taken, so the UI can say
	// "usage unavailable" instead of rendering a confident 0%.
	StatsError string `json:"stats_error,omitempty"`
}

Runtime is the live state of the registry container: whether it is running, and what it is costing. The registry is infrastructure an admin can't see with the app-level tooling — it belongs to no workspace — so this is the only place its resource usage surfaces.

type SaveInput

type SaveInput struct {
	DeleteEnabled       bool
	PerWorkspaceQuotaMB int

	// Platform configuration. Written only where the environment is silent.
	Enabled     *bool
	Host        *string
	StorageType *string

	S3Endpoint       *string
	S3Bucket         *string
	S3Region         *string
	S3AccessKey      *string
	S3ForcePathStyle *bool
	// S3SecretKey rotates the stored secret. Empty (or nil) keeps the current one,
	// so a form that never reads the value back can be saved without wiping it.
	S3SecretKey *string
}

SaveInput carries a settings update. Every field is optional in the sense that an environment-pinned one is ignored — see Locks. Pointers mark "the client sent this"; nil leaves the stored value alone.

type Service

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

Service manages the registry settings, container lifecycle, and per-request authorization.

func NewService

func NewService(
	repo *repositories.RegistrySettingsRepository,
	images imageResolver,
	external externalAccessReader,
	keys keyVerifier,
	ws workspaceFinder,
	proxyMgr proxy.Manager,
	network string,
	controlURL string,
	cfg config.RegistryConfig,
) *Service

NewService wires the registry service. network is the gateway Docker network; controlURL is the address the gateway reaches Miabi at (forwardAuth fallback).

func (*Service) Authorize

func (s *Service) Authorize(in AuthInput) AuthResult

Authorize decides whether a forwarded registry request is allowed. The docker password is an API token and the username is advisory. The repository's first path segment names the target workspace: a workspace-scoped token may act only on its own; a user token on any it is a member of, gated by role.

func (*Service) BuildRef

func (s *Service) BuildRef(workspaceID uint, appName string, deploymentID uint) string

BuildRef is the registry reference a built image is distributed under: <host>/ws_<id>/<app-name>:<deploymentID>. The namespace is the immutable ws_<id> form because the reference is recorded on the deployment and pulled again later, when a rename could have broken it.

func (*Service) DeleteTag

func (s *Service) DeleteTag(ctx context.Context, workspaceID uint, image, tag string) error

DeleteTag deletes a tag from a workspace repository by resolving it to its manifest digest and deleting the manifest (the registry has no delete-by-tag). image is the user-facing name. A tag a live deployment or pinned release still holds is refused with ErrTagInUse, since the breakage would surface on a node.

func (*Service) DistributionEnabled

func (s *Service) DistributionEnabled() bool

DistributionEnabled reports whether built images can be pushed to and pulled from the registry: it must be enabled, have a resolvable host, and have a platform token configured. When false the build/deploy flow uses node-local images, so single-node installs are unaffected.

func (*Service) DistributionUnavailableReason

func (s *Service) DistributionUnavailableReason() string

DistributionUnavailableReason returns "" when image distribution is ready, or a user-facing sentence naming the specific missing piece. Keeping the diagnosis here means a git-source deploy can tell the operator exactly what to configure rather than re-suggesting a flag they already set.

func (*Service) Ensure

func (s *Service) Ensure(ctx context.Context, dc docker.Client) error

Ensure (re)creates the registry container per the current settings on the platform's private network and seeds its gateway route. Idempotent. A no-op (teardown) when disabled. dc is the control-plane Docker client.

func (*Service) GarbageCollect

func (s *Service) GarbageCollect(ctx context.Context, dc docker.Client) error

GarbageCollect reclaims storage from deleted or overwritten manifests. To run safely it flips the registry read-only (pulls keep working, pushes pause), runs `registry garbage-collect` as a one-shot against the same storage, then restores read-write. A no-op unless the registry is enabled with deletes on.

func (*Service) Get

func (s *Service) Get() (*models.RegistrySettings, error)

Get returns the current settings (an empty, disabled default when unset), never exposing the S3 secret — only the S3SecretSet presence flag.

func (*Service) HostFor

func (s *Service) HostFor(st *models.RegistrySettings) string

HostFor returns the effective registry hostname: MIABI_REGISTRY_HOST, else registry.<default cluster's external domain>, else empty. Both candidates are validated — an unusable host resolves to "", so distribution reports itself unavailable with a reason rather than silently failing to match any image reference.

func (*Service) HostSource added in v1.6.8

func (s *Service) HostSource(st *models.RegistrySettings) string

HostSource names where the effective host came from: "env" (pinned by MIABI_REGISTRY_HOST), "stored" (set in the console), "base_domain" (derived from the platform's external base domain), or "unset".

func (*Service) IsBuildRef

func (s *Service) IsBuildRef(ref string) bool

IsBuildRef reports whether ref is one of this registry's distributed image refs

func (*Service) IsInternalRef added in v1.6.8

func (s *Service) IsInternalRef(ref string) bool

IsInternalRef reports whether ref addresses this platform's built-in registry. It says nothing about who may pull it — use ResolveImageRef for that.

func (*Service) ListRepositories

func (s *Service) ListRepositories(ctx context.Context, workspaceID uint) ([]Repository, error)

ListRepositories returns the workspace's repositories (its ws_<id> namespace, filtered from the registry catalog) with their tags.

func (*Service) ListRepositoriesPage added in v1.6.8

func (s *Service) ListRepositoriesPage(ctx context.Context, workspaceID uint, q string, offset, limit, tagPreview int) ([]RepositorySummary, int, error)

ListRepositoriesPage returns one page of the workspace's repositories, each with its tag count and a preview of its newest tags, plus the total matching q. Only the page's repositories have their tags fetched — listing every repository with every tag cost one round trip per repository.

func (*Service) ListTagsPage added in v1.6.8

func (s *Service) ListTagsPage(ctx context.Context, workspaceID uint, image, q string, offset, limit int) ([]TagInfo, int, error)

ListTagsPage returns one page of a repository's tags in display order, enriched with digest, size, in-use state, and build provenance, plus the total number of tags matching q.

func (*Service) Locks added in v1.7.3

func (s *Service) Locks() Locks

Locks returns the environment-pinned fields for this install.

func (*Service) NamespaceUsageBytes

func (s *Service) NamespaceUsageBytes(ctx context.Context, workspaceID uint) (int64, error)

NamespaceUsageBytes computes a workspace's registry usage: the sum of the unique blob sizes across all its repositories' tags (deduped by digest). It is an estimate (manifest-reported sizes), suitable for soft quota enforcement.

func (*Service) Overview added in v1.6.8

func (s *Service) Overview(ctx context.Context, workspaceID uint, image string) (*RepositoryOverview, error)

Overview returns a repository's summary: its tag count, a preview of the newest tags, and the newest tag enriched with digest, size, and provenance.

func (*Service) PushAuth

func (s *Service) PushAuth() *docker.RegistryAuth

PushAuth is the credential the worker uses to push/pull built images (the platform token). Returns nil when distribution is unconfigured.

func (*Service) RegistryHost

func (s *Service) RegistryHost() string

RegistryHost returns the resolved registry host — the explicit setting, else registry.<external-base-domain>, else "". It is the host a runner must both log into and push to; deriving it here rather than trusting the raw env keeps the login host and push host identical.

func (*Service) RepositoryCount added in v1.7.3

func (s *Service) RepositoryCount(ctx context.Context) (int, error)

RepositoryCount is the number of repositories the registry holds across every workspace. It answers one question: would changing where blobs live strand anything? A registry that is down or empty reports 0, which is the same answer for that purpose.

func (*Service) ResolveImageRef added in v1.6.8

func (s *Service) ResolveImageRef(workspaceID uint, ref string) (string, error)

ResolveImageRef authorizes an image reference for a workspace and returns the reference to actually pull. External references pass through unchanged. An internal one is allowed only when its namespace resolves to workspaceID, and comes back rewritten to ws_<id> so it survives a workspace rename.

func (*Service) RuntimeStatus added in v1.7.3

func (s *Service) RuntimeStatus(ctx context.Context, dc docker.Client) (*Runtime, error)

RuntimeStatus inspects the registry container and samples its resource usage. A missing container is not an error: a registry that is disabled, or enabled but held down by a storage problem, simply reports Running=false. Only a Docker failure is surfaced as one.

func (*Service) S3Entitled added in v1.7.0

func (s *Service) S3Entitled() bool

S3Entitled reports whether this install may use the S3 storage driver.

func (*Service) Save

func (s *Service) Save(in SaveInput) (*models.RegistrySettings, error)

Save persists the settings an admin may change, skipping every field the environment pins, so an install configured by compose or Helm keeps behaving as declared. Validating a *change* — S3 entitlement, host usability, whether switching storage strands blobs — belongs to the caller, where confirmation happens.

func (*Service) SetApps added in v1.10.2

func (s *Service) SetApps(a appNamer)

SetApps wires the application lookup used to hold an app-bound job credential to its own repository. Without it such a key is refused on push, not waved through.

func (*Service) SetCatalog added in v1.6.8

func (s *Service) SetCatalog(c Catalog)

SetCatalog wires the image catalog: in-use protection for tag deletion, and build provenance on tag listings. See Catalog in browse.go.

func (*Service) SetEntitlements added in v1.7.0

func (s *Service) SetEntitlements(ee entitlementChecker)

func (*Service) SetInternalNetwork added in v1.9.2

func (s *Service) SetInternalNetwork(name string)

SetInternalNetwork names the platform's private network: the only network the registry joins, and how the control plane and gateway reach it. Unset on a stack that has nothing but the proxy network.

func (*Service) StorageSource added in v1.7.0

func (s *Service) StorageSource(st *models.RegistrySettings) string

StorageSource names where the effective storage driver came from, so the admin UI can say why a field is fixed or which value it is editing: "env" (MIABI_REGISTRY_STORAGE pins it), "stored" (configured in the console), or "default" (the filesystem driver, nothing configured).

func (*Service) StorageUnavailableReason added in v1.7.0

func (s *Service) StorageUnavailableReason(st *models.RegistrySettings) string

StorageUnavailableReason returns "" when the configured storage driver can be used, else a sentence naming exactly what is wrong.

func (*Service) SyncGateway added in v1.10.0

func (s *Service) SyncGateway(ctx context.Context) error

SyncGateway re-publishes the registry's gateway route, so a change to the default cluster's external domain or certificate provider takes effect without a restart.

func (*Service) TagReleaseVersion

func (s *Service) TagReleaseVersion(ctx context.Context, workspaceID uint, appName, digest string, version int) error

TagReleaseVersion adds a v<version> tag to an already-pushed build image so the registry mirrors the release number shown in the UI, alongside the immutable build tag. Best-effort and a no-op when distribution is off. It talks to the registry directly, so it uses the ws_<id>/<app-name> storage path.

func (*Service) Teardown

func (s *Service) Teardown(ctx context.Context, dc docker.Client) error

Teardown removes the registry container and its gateway route (best-effort). Data volumes are kept.

func (*Service) ValidateImageRef added in v1.6.8

func (s *Service) ValidateImageRef(workspaceID uint, ref string) error

ValidateImageRef reports whether workspaceID may use ref, without rewriting it. It is the write-time guard on app create and update: refusing a foreign reference when it is typed gives the user the error where they can act on it, instead of at deploy time on a node.

type TagInfo added in v1.6.8

type TagInfo struct {
	Name      string `json:"name"`
	Digest    string `json:"digest,omitempty"`
	SizeBytes int64  `json:"size_bytes,omitempty"`
	// InUse marks a tag whose image a live deployment or pinned release holds.
	// Deleting it is refused, so the UI can say so before the user tries.
	InUse         bool       `json:"in_use"`
	BuiltAt       *time.Time `json:"built_at,omitempty"`
	Commit        string     `json:"commit,omitempty"`
	ApplicationID *uint      `json:"application_id,omitempty"`
	PipelineRunID *uint      `json:"pipeline_run_id,omitempty"`
}

TagInfo is one tag on a repository's tags page, enriched with what the platform knows about it. Digest and SizeBytes come from the registry; the provenance fields come from the image catalog and are absent for images pushed by hand rather than built by a pipeline.

Jump to

Keyboard shortcuts

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