Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(images): allow custom private registries with credentials (#3194)

silverzkia080b2280ad8
diff --git a/apps/api/.env.example b/apps/api/.env.example
index 8d08222b9..cd989e607 100644
--- a/apps/api/.env.example
+++ b/apps/api/.env.example
@@ -85,12 +85,9 @@ GCS_PROJECT_ID=
REGISTRY_SECRET_STORE=
REGISTRY_SECRET_DIR=
-# The registry proxy a private image is pulled through, and the registries a
-# login may be registered for (default ghcr.io,docker.io,quay.io,gcr.io and
-# Container Registry's us.gcr.io,eu.gcr.io,asia.gcr.io — the proxy reads the
-# same variable). An unset host routes nothing through it.
+# The registry proxy used for private images with matching credentials.
+# An unset host routes nothing through it.
REGISTRY_PROXY_HOST=
-REGISTRY_PROXY_UPSTREAM_HOSTS=
ENVIRONMENT=dev
diff --git a/apps/api/src/boxlite-rest/boxlite-registry.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-registry.controller.spec.ts
index de6ae43b5..ed07c99eb 100644
--- a/apps/api/src/boxlite-rest/boxlite-registry.controller.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-registry.controller.spec.ts
@@ -118,8 +118,12 @@ describe('BoxliteRegistryController', () => {
expect(await refusals({ ...BODY, repository_prefix: undefined })).toEqual([])
})
+ it('accepts credentials for a custom registry hostname', async () => {
+ expect(await refusals({ ...BODY, registry_host: 'registry.example.com' })).toEqual([])
+ })
+
it.each([
- ['a registry no login is taken for', { registry_host: 'registry.example.com' }, 'registry_host'],
+ ['a URL in place of a registry hostname', { registry_host: 'https://registry.example.com' }, 'registry_host'],
['a prefix that is not whole path segments', { repository_prefix: 'acme' }, 'repository_prefix'],
['no username', { username: '' }, 'username'],
['no password', { password: '' }, 'password'],
diff --git a/apps/api/src/boxlite-rest/dto/create-registry.dto.ts b/apps/api/src/boxlite-rest/dto/create-registry.dto.ts
index 0575a8752..88bb48691 100644
--- a/apps/api/src/boxlite-rest/dto/create-registry.dto.ts
+++ b/apps/api/src/boxlite-rest/dto/create-registry.dto.ts
@@ -3,9 +3,9 @@
* SPDX-License-Identifier: AGPL-3.0
*/
-import { IsIn, IsNotEmpty, IsOptional, IsString, Matches, MaxLength } from 'class-validator'
+import { IsNotEmpty, IsOptional, IsString, Matches, MaxLength } from 'class-validator'
import { REPOSITORY_PREFIX } from '../../registry/dto/registry-credential.dto'
-import { credentialedRegistryHosts } from '../../registry/utils/registry-proxy.util'
+import { REGISTRY_HOSTNAME } from '../../registry/utils/registry-proxy.util'
/**
* A new registry login, in the box API's snake_case. The rules are the
@@ -14,7 +14,7 @@ import { credentialedRegistryHosts } from '../../registry/utils/registry-proxy.u
* value, so no refusal repeats the password.
*/
export class CreateRegistryDto {
- @IsIn(credentialedRegistryHosts())
+ @Matches(REGISTRY_HOSTNAME, { message: 'registry_host must be a lowercase registry domain name' })
registry_host: string
@IsOptional()
diff --git a/apps/api/src/image/services/image-admission.service.ts b/apps/api/src/image/services/image-admission.service.ts
index 7a3cfed3f..7c6cd106d 100644
--- a/apps/api/src/image/services/image-admission.service.ts
+++ b/apps/api/src/image/services/image-admission.service.ts
@@ -11,7 +11,7 @@ import { IsNull, Repository } from 'typeorm'
import { BadRequestError } from '../../exceptions/bad-request.exception'
import { Organization } from '../../organization/entities/organization.entity'
import { RegistryCredentialService } from '../../registry/services/registry-credential.service'
-import { credentialedRegistryHosts, registryProxyHost } from '../../registry/utils/registry-proxy.util'
+import { REGISTRY_HOSTNAME, registryProxyHost } from '../../registry/utils/registry-proxy.util'
import { Image } from '../entities/image.entity'
import { ImageColdPullRateLimitedError, ImageCountLimitReachedError } from '../errors/image-admission.error'
import {
@@ -146,9 +146,8 @@ function positiveIntegerFromEnv(name: string, fallback: number): number {
* A registered login is a second way in, beside the allowlist. A host off the
* list is admitted when the organization registered a login that covers the
* repository, because then the pull goes through the registry proxy with that
- * login rather than out from a runner. Only the hosts a login may be registered
- * for take that path, so a login cannot open the metadata endpoint or any other
- * address the allowlist keeps out.
+ * login rather than out from a runner. The proxy checks the resolved
+ * destination before connecting.
*
* Curated selectors skip all of it and touch neither Redis nor the database:
* they are operator-chosen refs that were already allowed, and making the
@@ -192,10 +191,7 @@ export class ImageAdmissionService {
!allowlist.includes(host) &&
!(await this.registryCredentials.routesThroughProxy(organization.id, host, repository))
) {
- // A host a login could open is told so, and both places to add one: the
- // console and the SDK's runtime handle. Any other host gets the
- // allowlist's own refusal.
- if (registryProxyHost() && credentialedRegistryHosts().includes(host)) {
+ if (registryProxyHost() && REGISTRY_HOSTNAME.test(host)) {
throw new BadRequestError(
`Image registry '${host}' is reachable only with a registered credential for this repository; add one under Registries in the console, or with the SDK's runtime registries handle`,
)
diff --git a/apps/api/src/image/utils/image-ref.util.spec.ts b/apps/api/src/image/utils/image-ref.util.spec.ts
index dddc51526..0d9fd791c 100644
--- a/apps/api/src/image/utils/image-ref.util.spec.ts
+++ b/apps/api/src/image/utils/image-ref.util.spec.ts
@@ -175,6 +175,16 @@ describe('image ref utilities', () => {
)
})
+ it('rejects a proxy repository name longer than the proxy can parse', () => {
+ const prefix = `${ORG}/registry.example.com/`
+ const repository = 'r'.repeat(255 - prefix.length)
+
+ expect(proxyRefOf(PROXY, ORG, parseImageRef(`registry.example.com/${repository}:v1`))).toBe(
+ `${PROXY}/${prefix}${repository}:v1`,
+ )
+ expect(() => proxyRefOf(PROXY, ORG, parseImageRef(`registry.example.com/${repository}r:v1`))).toThrow(/255/)
+ })
+
it('reads a proxy ref back as the upstream ref it stands for', () => {
const proxied = proxyRefOf(PROXY, ORG, parseImageRef('ghcr.io/acme/app:1.2'))
diff --git a/apps/api/src/image/utils/image-ref.util.ts b/apps/api/src/image/utils/image-ref.util.ts
index 50222e38e..604b8b5e9 100644
--- a/apps/api/src/image/utils/image-ref.util.ts
+++ b/apps/api/src/image/utils/image-ref.util.ts
@@ -26,6 +26,8 @@ const FALLBACK_ALLOWLIST = ['docker.io', 'quay.io', 'gcr.io', 'public.ecr.aws']
/** A registry ref is at most this long; anything beyond is a probe, not a name. */
const MAX_REF_LENGTH = 512
+// The proxy includes the organization and upstream host in its OCI name.
+const MAX_PROXY_REPOSITORY_LENGTH = 255
export const DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/
export const TAG_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$/
@@ -184,8 +186,14 @@ export function catalogNameOf(ref: string | undefined | null): string | undefine
* `library/alpine:3.20` — come out as one path.
*/
export function proxyRefOf(proxyHost: string, organizationId: string, parsed: ParsedImageRef): string {
+ const name = `${organizationId}/${parsed.host}/${parsed.repository}`
+ if (name.length > MAX_PROXY_REPOSITORY_LENGTH) {
+ throw new BadRequestError(
+ `Image repository through the registry proxy exceeds ${MAX_PROXY_REPOSITORY_LENGTH} characters`,
+ )
+ }
const reference = parsed.digest ? `@${parsed.digest}` : parsed.tag ? `:${parsed.tag}` : ''
- return `${proxyHost}/${organizationId}/${parsed.host}/${parsed.repository}${reference}`
+ return `${proxyHost}/${name}${reference}`
}
/**
@@ -273,9 +281,8 @@ function isInternalAddress(host: string): boolean {
/**
* The allowlist is the gate for a pull a runner makes directly: a host on it is
* reachable, a host off it is not, whatever the host looks like. The one other
- * way in is a registered login, and that pull goes through the registry proxy
- * instead, for the hosts a login is accepted for — see
- * `ImageAdmissionService`.
+ * way in is a matching registered login, which routes the pull through the
+ * registry proxy. See `ImageAdmissionService`.
*
* Internal addresses are therefore not a second check — an earlier version
* refused them separately, which changed nothing, because a host off the list
diff --git a/apps/api/src/registry/controllers/runner-registry-credential.controller.ts b/apps/api/src/registry/controllers/runner-registry-credential.controller.ts
index 4cd2787af..5491461ae 100644
--- a/apps/api/src/registry/controllers/runner-registry-credential.controller.ts
+++ b/apps/api/src/registry/controllers/runner-registry-credential.controller.ts
@@ -22,9 +22,8 @@ import { RegistryCredentialService } from '../services/registry-credential.servi
* proxy spends a login only on that answer — see `runnerServes` for why a
* runner key alone is not enough.
*
- * No `AuthenticatedRateLimitGuard`, as on the job routes: the caller is the
- * proxy on a runner's behalf, which keeps every answer here — a login, "none"
- * and a refusal — for a minute per runner, and meters each runner's pulls.
+ * The proxy calls on behalf of a runner and meters its pulls before lookup.
+ * It may cache negative answers for hosts on the anonymous upstream list.
*/
@ApiExcludeController()
@ApiTags('runners')
@@ -41,8 +40,7 @@ export class RunnerRegistryCredentialController {
})
@ApiResponse({ status: 200, type: RunnerRegistryCredentialDto })
@ApiResponse({ status: 403, description: 'The runner hosts no box of that organization' })
- // 404 for "none" rather than another 403, so the proxy can tell a pull with
- // no login, which goes on anonymously, from one it must refuse.
+ // A missing login only permits anonymous access to an allowlisted upstream.
@ApiResponse({ status: 404, description: 'The organization has no credential for this repository' })
async find(
@RunnerContextDecorator() runner: RunnerContext,
diff --git a/apps/api/src/registry/dto/registry-credential.dto.spec.ts b/apps/api/src/registry/dto/registry-credential.dto.spec.ts
index b9f2f7dc3..380c2dfb3 100644
--- a/apps/api/src/registry/dto/registry-credential.dto.spec.ts
+++ b/apps/api/src/registry/dto/registry-credential.dto.spec.ts
@@ -22,6 +22,10 @@ describe('CreateRegistryCredentialDto', () => {
expect(await messagesFor({ ...valid, repositoryPrefix: undefined })).toEqual([])
})
+ it('accepts credentials for a custom registry hostname', async () => {
+ expect(await messagesFor({ ...valid, registryHost: 'registry.example.com' })).toEqual([])
+ })
+
// Container Registry serves from a host per region, as well as gcr.io itself.
it.each(['ghcr.io', 'docker.io', 'quay.io', 'gcr.io', 'us.gcr.io', 'eu.gcr.io', 'asia.gcr.io'])(
'accepts a login for %s',
@@ -30,7 +34,7 @@ describe('CreateRegistryCredentialDto', () => {
},
)
- it.each(['public.ecr.aws', 'us-docker.pkg.dev', '169.254.169.254', 'registry-1.docker.io'])(
+ it.each(['registry', '169.254.169.254', 'Registry.example.com', 'registry.example.com:5000', 'bad-.example.com'])(
'refuses a login for %s',
async (registryHost) => {
expect(await messagesFor({ ...valid, registryHost })).not.toEqual([])
diff --git a/apps/api/src/registry/dto/registry-credential.dto.ts b/apps/api/src/registry/dto/registry-credential.dto.ts
index bc4f540d3..2d2663678 100644
--- a/apps/api/src/registry/dto/registry-credential.dto.ts
+++ b/apps/api/src/registry/dto/registry-credential.dto.ts
@@ -4,10 +4,10 @@
*/
import { ApiProperty, ApiPropertyOptional, ApiSchema, PickType } from '@nestjs/swagger'
-import { IsIn, IsNotEmpty, IsOptional, IsString, Matches, MaxLength } from 'class-validator'
+import { IsNotEmpty, IsOptional, IsString, Matches, MaxLength } from 'class-validator'
import { RegistryCredential } from '../entities/registry-credential.entity'
import { RegistryCredentialKind } from '../enums/registry-credential-kind.enum'
-import { credentialedRegistryHosts } from '../utils/registry-proxy.util'
+import { REGISTRY_HOSTNAME } from '../utils/registry-proxy.util'
/**
* Whole path segments ending in '/', or nothing for the whole host — the shape
@@ -23,7 +23,7 @@ export const REPOSITORY_PREFIX = /^([a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*\/)*$/
@ApiSchema({ name: 'CreateRegistryCredential' })
export class CreateRegistryCredentialDto {
@ApiProperty({ description: 'Registry the login is for', example: 'ghcr.io' })
- @IsIn(credentialedRegistryHosts())
+ @Matches(REGISTRY_HOSTNAME, { message: 'registryHost must be a lowercase registry domain name' })
registryHost: string
@ApiPropertyOptional({
diff --git a/apps/api/src/registry/services/registry-credential.service.spec.ts b/apps/api/src/registry/services/registry-credential.service.spec.ts
index 768449b3e..431ceba03 100644
--- a/apps/api/src/registry/services/registry-credential.service.spec.ts
+++ b/apps/api/src/registry/services/registry-credential.service.spec.ts
@@ -120,11 +120,12 @@ describe('RegistryCredentialService.routesThroughProxy', () => {
expect(find).not.toHaveBeenCalled()
})
- it('takes the hosts from the variable the proxy reads too', async () => {
+ it('routes a custom registry by repository scope regardless of the deployment list', async () => {
process.env.REGISTRY_PROXY_UPSTREAM_HOSTS = 'quay.io'
- const { service } = serviceWith([{ repositoryPrefix: '' }])
+ const { service, find } = serviceWith([{ repositoryPrefix: 'acme/' }])
- await expect(service.routesThroughProxy(ORG_ID, 'ghcr.io', 'acme/app')).resolves.toBe(false)
- await expect(service.routesThroughProxy(ORG_ID, 'quay.io', 'acme/app')).resolves.toBe(true)
+ await expect(service.routesThroughProxy(ORG_ID, 'registry.example.com', 'acme/app')).resolves.toBe(true)
+ expect(find).toHaveBeenCalledWith({ where: { organizationId: ORG_ID, registryHost: 'registry.example.com' } })
+ await expect(service.routesThroughProxy(ORG_ID, 'registry.example.com', 'other/app')).resolves.toBe(false)
})
})
diff --git a/apps/api/src/registry/services/registry-credential.service.ts b/apps/api/src/registry/services/registry-credential.service.ts
index 8f9ae45e2..42817358e 100644
--- a/apps/api/src/registry/services/registry-credential.service.ts
+++ b/apps/api/src/registry/services/registry-credential.service.ts
@@ -9,7 +9,7 @@ import { Not, Repository } from 'typeorm'
import { Box } from '../../box/entities/box.entity'
import { BoxDesiredState } from '../../box/enums/box-desired-state.enum'
import { RegistryCredential } from '../entities/registry-credential.entity'
-import { credentialedRegistryHosts, registryProxyHost } from '../utils/registry-proxy.util'
+import { REGISTRY_HOSTNAME, registryProxyHost } from '../utils/registry-proxy.util'
import { matchingCredential } from '../utils/matching-credential'
@Injectable()
@@ -56,15 +56,11 @@ export class RegistryCredentialService {
/**
* Whether a pull of this repository goes through the registry proxy with the
- * organization's login: the deployment runs a proxy, the host is one a login
- * may be registered for, and one is registered for a prefix of it.
- *
- * The host list is checked before the database, so a host no login can
- * exist for — the metadata endpoint, a private address — costs no query and
- * never reaches the proxy, whatever rows someone managed to write.
+ * organization's login. A proxy must be deployed, the ref must name a
+ * registry domain, and the organization's login must cover the repository.
*/
async routesThroughProxy(organizationId: string, registryHost: string, repository: string): Promise<boolean> {
- if (!registryProxyHost() || !credentialedRegistryHosts().includes(registryHost)) {
+ if (!registryProxyHost() || !REGISTRY_HOSTNAME.test(registryHost)) {
return false
}
return (await this.findForRepository(organizationId, registryHost, repository)) !== null
diff --git a/apps/api/src/registry/utils/registry-proxy.util.ts b/apps/api/src/registry/utils/registry-proxy.util.ts
index c791a4f47..cd626a7b6 100644
--- a/apps/api/src/registry/utils/registry-proxy.util.ts
+++ b/apps/api/src/registry/utils/registry-proxy.util.ts
@@ -7,40 +7,14 @@
const REGISTRY_PROXY_HOST_ENV = 'REGISTRY_PROXY_HOST'
/**
- * Env var naming the registries a login may be registered for. The registry
- * proxy reads the same variable as the upstreams it will pull from, and the
- * stack writes it once for both: a host the API accepted a login for and the
- * proxy then refuses is a private pull that fails with a 403 nobody expected.
+ * A lowercase DNS name that fits a proxy repository segment. The dot
+ * distinguishes a registry from a Docker Hub namespace, and the last label
+ * starts with a letter to exclude numeric TLDs and IP literals.
*/
-const CREDENTIALED_HOSTS_ENV = 'REGISTRY_PROXY_UPSTREAM_HOSTS'
-
-/**
- * The registries that take a username and a token or password: ghcr.io, Docker
- * Hub, quay.io, and Container Registry, which serves from gcr.io and from a host
- * per region. `public.ecr.aws` holds only public images, and Artifact Registry
- * is left to keyless access, so neither is here. The proxy's own default is the
- * same list.
- */
-const FALLBACK_CREDENTIALED_HOSTS = [
- 'ghcr.io',
- 'docker.io',
- 'quay.io',
- 'gcr.io',
- 'us.gcr.io',
- 'eu.gcr.io',
- 'asia.gcr.io',
-]
+export const REGISTRY_HOSTNAME =
+ /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/
/** The registry proxy's host, or undefined when this deployment runs none. */
export function registryProxyHost(): string | undefined {
return process.env[REGISTRY_PROXY_HOST_ENV]?.trim() || undefined
}
-
-/** The registries a login may be registered for, and so reached through the proxy. */
-export function credentialedRegistryHosts(): string[] {
- const configured = (process.env[CREDENTIALED_HOSTS_ENV] ?? '')
- .split(',')
- .map((entry) => entry.trim())
- .filter(Boolean)
- return configured.length > 0 ? configured : FALLBACK_CREDENTIALED_HOSTS
-}
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md
index 481e98b2a..617d4a6c6 100644
--- a/apps/dashboard/README.md
+++ b/apps/dashboard/README.md
@@ -608,9 +608,15 @@ where it has to be right. It is built per registry: GitHub, Docker Hub, Quay
and each Container Registry host get their own steps (where to make the token,
which scope, what the username is), and the scope a credential will cover is
shown as it is typed (`ghcr.io/acme/*`), with an unterminated prefix completed
-rather than refused. The registries offered are the API's default
-`REGISTRY_PROXY_UPSTREAM_HOSTS`; a stack configured with others needs
-`PROVIDERS` changed with it.
+rather than refused.
+
+Select a provider from **Presets** or type a hostname in
+**Registry**. For a custom registry, enter its lowercase domain name and the
+username and pull token it issued. The registry must use HTTPS and serve its
+Bearer token endpoint on the same host.
+
+The **Connect a registry** link on a Box with a failed private pull opens the
+form with the registry hostname filled in, including custom hostnames.
Refusals are named in the reader's terms: a duplicate says which scope already
has a credential, and a removal refused because boxes pull through it names
diff --git a/apps/dashboard/src/components/images/RegistriesPanel.test.tsx b/apps/dashboard/src/components/images/RegistriesPanel.test.tsx
index d859540db..a119a36ec 100644
--- a/apps/dashboard/src/components/images/RegistriesPanel.test.tsx
+++ b/apps/dashboard/src/components/images/RegistriesPanel.test.tsx
@@ -91,6 +91,7 @@ async function renderPanel(entry = '/dashboard/images/registries') {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ Element.prototype.scrollIntoView = vi.fn()
state.credentials = [CREDENTIAL]
state.listError = null
state.byId = new Map()
@@ -328,6 +329,44 @@ describe('connecting a registry', () => {
expect(mocks.reset).toHaveBeenCalled()
})
+ it('submits a custom registry typed into the hostname field', async () => {
+ await renderPanel()
+ open()
+
+ const registry = field('registry-host')
+ expect(registry).toBeInstanceOf(HTMLInputElement)
+ act(() => typeInto(registry, ' Registry.Example.com '))
+ expect(document.querySelector('label[for="registry-password"]')?.textContent).toBe('Password or access token')
+ await fillAndSubmit({ prefix: 'team/' })
+
+ expect(mocks.create).toHaveBeenCalledWith({
+ credential: {
+ registryHost: 'registry.example.com',
+ repositoryPrefix: 'team/',
+ username: 'acme-bot',
+ password: PASSWORD,
+ },
+ organizationId: 'org-1',
+ })
+ })
+
+ it('fills the editable hostname from the existing presets', async () => {
+ await renderPanel()
+ open()
+
+ const presets = document.querySelector('[aria-label="Registry presets"]')
+ expect(presets).not.toBeNull()
+ await act(async () => presets?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })))
+ const gcr = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (option) => option.textContent?.trim() === 'Google Container Registry (gcr.io)',
+ )
+ expect(gcr).toBeDefined()
+ await act(async () => gcr?.click())
+
+ expect(field('registry-host').value).toBe('gcr.io')
+ expect(document.body.textContent).toContain('oauth2accesstoken')
+ })
+
// The API takes whole path segments ending in a slash; one left off is
// completed rather than refused.
it('completes a repository prefix typed without its trailing slash', async () => {
@@ -383,12 +422,19 @@ describe('connecting a registry', () => {
await renderPanel('/dashboard/images/registries?connect=gcr.io')
expect(field('registry-username')).not.toBeNull()
- expect(document.body.textContent).toContain('Google Container Registry (gcr.io)')
+ expect(field('registry-host').value).toBe('gcr.io')
expect(document.body.textContent).toContain('oauth2accesstoken')
})
- it('ignores a link naming a registry the API does not accept', async () => {
- await renderPanel('/dashboard/images/registries?connect=evil.example.com')
+ it('opens a connect link for a custom registry with the hostname prefilled', async () => {
+ await renderPanel('/dashboard/images/registries?connect=registry.example.com')
+
+ expect(field('registry-host')?.value).toBe('registry.example.com')
+ expect(document.body.textContent).toContain('Bearer token endpoint on the same host')
+ })
+
+ it('ignores a connect link containing a URL instead of a hostname', async () => {
+ await renderPanel('/dashboard/images/registries?connect=https%3A%2F%2Fregistry.example.com')
expect(document.getElementById('registry-username')).toBeNull()
})
diff --git a/apps/dashboard/src/components/images/RegistriesPanel.tsx b/apps/dashboard/src/components/images/RegistriesPanel.tsx
index 102d3de9d..2675f747c 100644
--- a/apps/dashboard/src/components/images/RegistriesPanel.tsx
+++ b/apps/dashboard/src/components/images/RegistriesPanel.tsx
@@ -34,7 +34,7 @@ import { Dialog, DialogDescription, DialogTitle } from '@/components/ui/dialog'
import { Server, Trash } from '@/components/ui/icon'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
+import { Select, SelectContent, SelectItem, SelectTrigger } from '@/components/ui/select'
import {
useCreateRegistryMutation,
useDeleteRegistryMutation,
@@ -53,11 +53,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { toast } from 'sonner'
-/**
- * How to get a pull token from each registry the API accepts by default
- * (REGISTRY_PROXY_UPSTREAM_HOSTS). The API has the final say on the host; a
- * stack configured with others needs this list changed with it.
- */
+/** Presets with instructions for obtaining a pull credential. */
interface Provider {
host: string
label: string
@@ -148,7 +144,8 @@ export const PROVIDERS: Provider[] = [
GCR_STEPS('asia.gcr.io'),
]
-export const REGISTRY_HOSTS = PROVIDERS.map((p) => p.host)
+// Match the credential API's bare DNS hostname rule for recovery links.
+const REGISTRY_HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/
const ROW_GRID =
'grid min-w-[680px] grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.2fr)_110px] items-center gap-6'
@@ -207,8 +204,8 @@ export function RegistriesPanel() {
// A box's pull error links here with the host it failed on.
useEffect(() => {
- const host = searchParams.get('connect')
- if (host && canWrite && REGISTRY_HOSTS.includes(host)) {
+ const host = searchParams.get('connect')?.trim().toLowerCase()
+ if (host && canWrite && REGISTRY_HOSTNAME.test(host)) {
setForm({ ...EMPTY_FORM, registryHost: host })
setFormOpen(true)
setSearchParams({}, { replace: true })
@@ -232,9 +229,10 @@ export function RegistriesPanel() {
updateRegistry.reset()
}
- const provider = PROVIDERS.find((p) => p.host === form.registryHost) ?? PROVIDERS[0]
+ const registryHost = form.registryHost.trim().toLowerCase()
+ const provider = PROVIDERS.find((p) => p.host === registryHost)
const prefix = normalizePrefix(form.repositoryPrefix)
- const scope = `${form.registryHost}/${prefix}*`
+ const scope = `${registryHost}/${prefix}*`
const handleSave = async (event: React.FormEvent) => {
event.preventDefault()
@@ -258,7 +256,7 @@ export function RegistriesPanel() {
}
await createRegistry.mutateAsync({
credential: {
- registryHost: form.registryHost,
+ registryHost,
repositoryPrefix: prefix,
username: form.username.trim(),
password: form.password,
@@ -278,7 +276,7 @@ export function RegistriesPanel() {
}
handleApiError(
error,
- editing ? `Could not update the credential for ${form.registryHost}` : `Could not connect ${form.registryHost}`,
+ editing ? `Could not update the credential for ${registryHost}` : `Could not connect ${registryHost}`,
)
} finally {
saveInFlight.current = false
@@ -439,44 +437,68 @@ export function RegistriesPanel() {
<FormDialogBody>
<div className="space-y-1">
<Label htmlFor="registry-host">Registry</Label>
- <Select
- disabled={!!editing}
- value={form.registryHost}
- onValueChange={(value) => setForm({ ...form, registryHost: value })}
- >
- <SelectTrigger id="registry-host" className="h-10 w-full font-mono">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {PROVIDERS.map((option) => (
- <SelectItem key={option.host} value={option.host} className="font-mono">
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <div className="flex">
+ <Input
+ id="registry-host"
+ aria-describedby={provider ? undefined : 'registry-host-help'}
+ value={form.registryHost}
+ onChange={(event) => setForm({ ...form, registryHost: event.target.value })}
+ placeholder="registry.example.com"
+ disabled={!!editing}
+ spellCheck={false}
+ autoCapitalize="none"
+ className="h-10 rounded-r-none font-mono focus-visible:z-10"
+ required
+ />
+ <Select
+ disabled={!!editing}
+ value={provider?.host ?? ''}
+ onValueChange={(value) => setForm({ ...form, registryHost: value })}
+ >
+ <SelectTrigger
+ aria-label="Registry presets"
+ className="w-auto shrink-0 gap-2 rounded-l-none border-l-0"
+ >
+ <span>Presets</span>
+ </SelectTrigger>
+ <SelectContent align="end">
+ {PROVIDERS.map((option) => (
+ <SelectItem key={option.host} value={option.host} className="font-mono">
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {!provider && (
+ <p id="registry-host-help" className="text-meta text-muted-foreground">
+ Custom registries must use HTTPS and serve a Bearer token endpoint on the same host.
+ </p>
+ )}
</div>
- <ol className="list-decimal space-y-1 pl-5 font-sans text-meta text-muted-foreground">
- {provider.steps.map((step, index) => (
- <li key={index}>{step}</li>
- ))}
- </ol>
+ {provider && (
+ <ol className="list-decimal space-y-1 pl-5 font-sans text-meta text-muted-foreground">
+ {provider.steps.map((step, index) => (
+ <li key={index}>{step}</li>
+ ))}
+ </ol>
+ )}
<div className="space-y-1">
- <Label htmlFor="registry-username">{provider.usernameLabel}</Label>
+ <Label htmlFor="registry-username">{provider?.usernameLabel ?? 'Username'}</Label>
<Input
id="registry-username"
value={form.username}
onChange={(event) => setForm({ ...form, username: event.target.value })}
- placeholder={provider.usernamePlaceholder}
+ placeholder={provider?.usernamePlaceholder}
spellCheck={false}
className="font-mono"
required
/>
</div>
<div className="space-y-1">
- <Label htmlFor="registry-password">{provider.secretLabel}</Label>
+ <Label htmlFor="registry-password">{provider?.secretLabel ?? 'Password or access token'}</Label>
<Input
id="registry-password"
type="password"
@@ -516,7 +538,7 @@ export function RegistriesPanel() {
<Button
data-console-action={editing ? 'update_registry' : 'connect_registry'}
type="submit"
- disabled={saving || createRegistry.isPending || updateRegistry.isPending}
+ disabled={!registryHost || saving || createRegistry.isPending || updateRegistry.isPending}
>
{editing ? 'Save changes' : 'Connect'}
</Button>
diff --git a/apps/e2e/cases/test_images_private.py b/apps/e2e/cases/test_images_private.py
index 9e99faf4a..b7bd9c172 100644
--- a/apps/e2e/cases/test_images_private.py
+++ b/apps/e2e/cases/test_images_private.py
@@ -7,10 +7,10 @@ reference exactly as it is written, reads it back that way, and the login
cannot be removed while that box stands. The password goes up once and is
never seen again.
-It needs a real private image, because the registry proxy pulls only from the
-registries a login is accepted for, by default ghcr.io, docker.io, quay.io and
-Container Registry's gcr.io hosts, and refuses a private address: the local
-registry box cannot stand in.
+The image must live on a public HTTPS registry with compatible Bearer
+authentication. The registry proxy refuses private network addresses, so
+the local registry box cannot stand in.
+
Without the first three variables below the file skips. A stack that keeps no
registry credentials refuses step 2 as unsupported, which fails: setting them
is asking for a stack that does.
diff --git a/apps/image-service/README.md b/apps/image-service/README.md
index 8aa483218..3696603b4 100644
--- a/apps/image-service/README.md
+++ b/apps/image-service/README.md
@@ -13,10 +13,9 @@ served, so the digest a client verifies still holds.
- Place in the platform: [hosted platform](../../docs/contributing/architecture/platform/README.md)
-> **Private images.** An organization's login for ghcr.io, Docker Hub, quay.io
-> or one of Container Registry's gcr.io hosts is read from the credential store
-> when a pull needs it. The proxy can read those passwords and write none; the
-> API is the reverse.
+> **Private images.** The proxy reads the organization's matching login from
+> the credential store when a pull needs it. The proxy reads these passwords
+> and the API writes them.
## Endpoints
@@ -78,17 +77,16 @@ proxy", without its address.
## What a pull passes through
```
-GET /v2/acme/ghcr.io/acme/app/manifests/1.2 Authorization: Basic …
+GET /v2/<org-id>/registry.example.com/acme/app/manifests/1.2 Authorization: Basic …
│
├─ route <org>/<host>/<repo> split out 400 if it carries no route
├─ authenticate runner API key → control plane, cached 401 · 503 if it cannot be asked
- ├─ authorize is ghcr.io a host we pull from? 403
├─ meter this runner's and organization's rate 429 + Retry-After
│
- ├─ login? current metadata from the control plane 403 if no hosted box · 503 if unavailable
- │ └─ only negative lookups are cached; private lookups are fresh
+ ├─ lookup scoped login from the control plane 403 if no hosted box · 503 if unavailable
+ ├─ authorize matching login or anonymous host list 403 if neither applies
├─ token reuse only when the secret version matches
- ├─ forward GET https://ghcr.io/v2/acme/app/manifests/1.2
+ ├─ forward GET https://registry.example.com/v2/acme/app/manifests/1.2
│ └─ 401 → read the challenge, fetch a token, retry once
│ the token is kept per (runner, org, endpoint, repository), with its secret version
│ ├─ secret Secret Manager, only on a token miss
@@ -101,19 +99,19 @@ The caller's own credential stops at `authenticate`: it identifies a runner to
this proxy and means nothing upstream, so it is never forwarded.
A runner is given an organization's login only while it hosts a box of that
-organization. Lookups and cached tokens are scoped per runner, so one runner's token never serves another's pull.
-A runner key alone is not enough: an organization can run
-runners of its own, and one of those naming another organization in a pull
-path would otherwise be handed that organization's private images. A path
-whose organization is not an organization id is pulled anonymously without
-asking.
+organization. Lookups and cached tokens are scoped per runner.
+
+A path without a valid organization ID can use only the anonymous host list.
The credential finder calls the internal control-plane route
`GET /api/runners/me/images/registry-credentials` directly with the runner's bearer
token. This operation and its secret-version response model are excluded from
the customer OpenAPI document and generated SDKs. The proxy reuses its configured
-control-plane HTTP client and base URL; 404 means anonymous access, while 403
-refuses the pull and other failures report the credential as unavailable.
+control-plane HTTP client and base URL.
+
+A credential lookup returning 404 can continue anonymously for hosts on the
+anonymous list. A 403 refuses the pull. Other failures report the credential
+as unavailable.
An organization's login travels to one place, the registry's token endpoint,
and only when that endpoint is the registry's own host or one it is known to
@@ -122,14 +120,23 @@ login bought, never the login. A token bought with a login is kept five
minutes at most, whatever the registry states — gcr.io states twelve hours —
as an additional lifetime bound; credential versions are checked before private bearer reuse.
+A custom registry that requests Basic authentication for the image pull
+receives a denial that explains the same-host HTTPS Bearer token requirement.
+
Credential rotation commits the new username/secret pointer before retiring the old secret.
-Every private pull reads current metadata before selecting a bearer; a version mismatch forces a new token exchange with the replacement login.
-This works across replicas and when old-secret retirement fails; secret payloads are read only on token misses.
+Every private pull reads current metadata before selecting a bearer. A version mismatch forces a new token exchange with the replacement login.
+
+This works across replicas and when old-secret retirement fails. Secret payloads are read only on token misses.
Normally, each private manifest/blob request adds one API lookup and fails closed during control-plane lookup outages, even with a warm token.
-Anonymous/negative lookups retain their existing TTL; upstream-issued tokens themselves are not revoked.
+
+Upstreams on the anonymous list can cache negative lookups. Upstreams outside
+that list query the current credential on each request, including after a miss.
+Upstream-issued tokens themselves are not revoked.
+
If a version is retired during an authentication challenge, the proxy refreshes authorized metadata and retries the secret read once.
-A failed refresh or second read fails the pull; in-flight requests may still need a caller retry.
-Upgrade all proxy replicas before relying on this behavior; older replicas retain the previous cache delay.
+A failed refresh or second read fails the pull. In-flight requests may still need a caller retry.
+
+Upgrade all proxy replicas before relying on this behavior. Older replicas retain the previous cache delay.
Unmodified takes one deliberate act. Go's HTTP transport offers `gzip` on any
request that did not ask for an encoding itself, then decodes the answer and
@@ -139,12 +146,14 @@ different bytes under a digest that no longer covers them. Compression is
therefore disabled on the upstream transport, and what the caller asks for is
forwarded so the answer is the caller's own to decode.
-Two things are refused rather than forwarded. An upstream host that is not on
-the list, because the host arrives in the request path and an authenticated
-caller would otherwise choose what this process connects to. And any connection
-to an address off the public internet — checked after DNS resolution, on the
-resolved address, for the first request and for every redirect a registry
-chooses, since a blob handed off with a `302` names an address we did not pick.
+The upstream list permits anonymous forwarding. To reach any other upstream,
+the authenticated Runner must have a matching organization credential for the
+requested repository. The proxy checks the resolved address before connecting,
+including on redirects and token requests.
+
+For upstreams outside the anonymous list, every hop uses HTTPS. A cross-origin
+blob redirect drops the Authorization header. A credentialed token exchange
+stays on its original origin.
## Layout
@@ -167,8 +176,8 @@ steps.
| `REGISTRY_PROXY_PORT` | `4100` | Listen port. Not 5000, the registry convention, because macOS binds it for AirPlay. |
| `SHUTDOWN_TIMEOUT_SEC` | `3600` | How long a drain may take. A blob is one long response, so this has to outlast the longest pull in flight or a deploy truncates an image mid-layer. |
| `BOXLITE_API_URL` | — | **Required.** The control plane. A runner API key is an opaque column rather than a signed token, so a caller can only be checked by asking. |
-| `REGISTRY_PROXY_UPSTREAM_HOSTS` | `ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io` | Registries this proxy will pull from, written as the names an operator knows — never `registry-1.docker.io`. |
-| `REGISTRY_SECRET_STORE` | — | Where organizations' registry passwords are read from: `gcp` (Secret Manager) or `file`. Unset, every pull is anonymous. The API writes them under the same name. |
+| `REGISTRY_PROXY_UPSTREAM_HOSTS` | `ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io` | Registries eligible for anonymous forwarding. Use published registry names such as `docker.io`. |
+| `REGISTRY_SECRET_STORE` | — | Credential store, either `gcp` (Secret Manager) or `file`. When unset, only anonymous hosts are eligible. |
| `REGISTRY_SECRET_DIR` | — | The directory the `file` store reads, on a local stack. |
| `REGISTRY_PROXY_CREDENTIAL_TTL` | `60s` | How long a verified caller is taken on trust. Also the delay between revoking a runner and this proxy noticing. |
| `REGISTRY_PROXY_REJECTION_TTL` | `30s` | How long a refused credential is remembered, so a caller with a bad key cannot turn this proxy into a load generator aimed at the control plane. |
@@ -237,11 +246,9 @@ nothing else in Secret Manager.
- Nothing caps how many relays run at once. The meter bounds how fast pulls
arrive, and a blob is a single long response, so concurrent streams are
governed by the instance count and its memory rather than by this service.
-- The organization in the path is not yet bound to the caller. Nothing links a
- runner to an organization — runners are shared and belong to none — so the
- organization meter is a number the caller can choose, and only the runner
- meter beside it actually bounds anyone. It becomes enforceable when the
- control plane says whose pull this is.
+- The organization segment for an anonymous pull can be chosen by the runner,
+ so the per-runner rate limit bounds anonymous forwarding. A credentialed pull
+ checks that the runner hosts a box for the named organization.
- Addresses in `198.18.0.0/15` are reachable, although that block is reserved
for benchmarking. VPN and split-DNS resolvers hand it out for ordinary public
hosts — on a machine running one, `ghcr.io` resolves into it — and refusing
diff --git a/apps/image-service/cmd/registry-proxy/config/config.go b/apps/image-service/cmd/registry-proxy/config/config.go
index 2eac0286d..6a851a2a6 100644
--- a/apps/image-service/cmd/registry-proxy/config/config.go
+++ b/apps/image-service/cmd/registry-proxy/config/config.go
@@ -25,14 +25,13 @@ type Config struct {
// rather than a signed token, so there is no way to check a caller without
// asking, and no point starting without somewhere to ask.
BoxliteApiUrl string `envconfig:"BOXLITE_API_URL" validate:"required,url"`
- // UpstreamHosts are the registries this proxy will pull from. The upstream
- // arrives in the request path, so without a list the caller chooses what
- // this process connects to.
+ // UpstreamHosts permits anonymous pulls to these registries. Other
+ // registries require a matching organization credential.
UpstreamHosts []string `envconfig:"REGISTRY_PROXY_UPSTREAM_HOSTS" default:"ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io" validate:"required,min=1"`
// SecretStore is where the passwords organizations registered are read
// from: gcp for Secret Manager, file for SecretDir on a local stack. The
- // API writes them under the same two names. Unset leaves every pull
- // anonymous.
+ // API writes them under the same two names. Unset permits only pulls
+ // allowed by the anonymous upstream list.
SecretStore string `envconfig:"REGISTRY_SECRET_STORE" validate:"omitempty,oneof=gcp file"`
SecretDir string `envconfig:"REGISTRY_SECRET_DIR" validate:"required_if=SecretStore file"`
// CredentialTTL is how long a verified caller is taken on trust before the
diff --git a/apps/image-service/cmd/registry-proxy/config/config_test.go b/apps/image-service/cmd/registry-proxy/config/config_test.go
index 5600cc43a..2b0a129e1 100644
--- a/apps/image-service/cmd/registry-proxy/config/config_test.go
+++ b/apps/image-service/cmd/registry-proxy/config/config_test.go
@@ -29,12 +29,10 @@ func TestGetConfigFallsBackToRunnableDefaults(t *testing.T) {
if config.ShutdownTimeoutSec != 3600 {
t.Errorf("ShutdownTimeoutSec = %d, want 3600", config.ShutdownTimeoutSec)
}
- // The upstream set has to be closed by default. An empty one would let the
- // request path choose what this process connects to. It is the registries
- // an organization may register a login for, Container Registry's regional
- // hosts included.
+ // Default destinations eligible for anonymous forwarding, including
+ // Container Registry's regional hosts.
if got := strings.Join(config.UpstreamHosts, ","); got != "ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io" {
- t.Errorf("UpstreamHosts = %v, want every registry a login is accepted for", got)
+ t.Errorf("UpstreamHosts = %v, want the default anonymous upstreams", got)
}
if config.CredentialTTL != 60*time.Second {
t.Errorf("CredentialTTL = %v, want 60s", config.CredentialTTL)
diff --git a/apps/image-service/internal/proxy/authorize.go b/apps/image-service/internal/proxy/authorize.go
index 2385846e3..23b1ea1c5 100644
--- a/apps/image-service/internal/proxy/authorize.go
+++ b/apps/image-service/internal/proxy/authorize.go
@@ -4,6 +4,7 @@
package proxy
import (
+ "context"
"errors"
"fmt"
"strings"
@@ -12,19 +13,16 @@ import (
// ErrHostRefused means the registry proxy will not pull from that upstream.
var ErrHostRefused = errors.New("upstream host refused")
-// upstreamAllowlist is the set of registries the proxy will pull from.
-//
-// The upstream host arrives in the request path, so without this the caller
-// chooses what the proxy connects to and the proxy is a request relay that
-// happens to speak a registry protocol. The address rule in guard.go stops it
-// reaching the network it sits on; this stops it reaching the rest of the
-// internet on a caller's say-so.
-//
-// It is a flat set, the same for every caller. An organization's login does not
-// widen it: a login is registered only for one of these hosts, and it changes
-// what a pull may see there, not where the proxy connects.
+// upstreamAllowlist permits anonymous forwarding to operator-selected
+// registries. A custom upstream requires a matching organization credential.
type upstreamAllowlist map[string]struct{}
+type customRegistryKey struct{}
+
+func isCustomRegistry(ctx context.Context) bool {
+ return ctx.Value(customRegistryKey{}) != nil
+}
+
func newUpstreamAllowlist(hosts []string) upstreamAllowlist {
allowed := upstreamAllowlist{}
for _, host := range hosts {
@@ -36,7 +34,7 @@ func newUpstreamAllowlist(hosts []string) upstreamAllowlist {
return allowed
}
-// permit reports whether a pull may be forwarded to host.
+// permit reports whether an anonymous pull may be forwarded to host.
//
// host is the published registry name from the path, not the endpoint it
// resolves to: an operator allows docker.io, which is the name they know, and
diff --git a/apps/image-service/internal/proxy/authorize_test.go b/apps/image-service/internal/proxy/authorize_test.go
index 27535ba26..3e6a21182 100644
--- a/apps/image-service/internal/proxy/authorize_test.go
+++ b/apps/image-service/internal/proxy/authorize_test.go
@@ -8,8 +8,7 @@ import (
"testing"
)
-// The upstream host arrives in the request path, so an allowlist is the only
-// thing between an authenticated caller and any host they care to name.
+// Anonymous forwarding is limited to the operator's published registry names.
func TestUpstreamAllowlistPermitsOnlyWhatItWasGiven(t *testing.T) {
allowed := newUpstreamAllowlist([]string{"ghcr.io", " docker.io ", ""})
diff --git a/apps/image-service/internal/proxy/credentials.go b/apps/image-service/internal/proxy/credentials.go
index f72b75813..2712ee4e1 100644
--- a/apps/image-service/internal/proxy/credentials.go
+++ b/apps/image-service/internal/proxy/credentials.go
@@ -28,8 +28,7 @@ var (
)
// organizationID is the shape of an organization's id. A path naming anything
-// else names no organization, so it has no login to look up and is pulled
-// anonymously, as every pull was before logins existed.
+// else names no organization, so it can use only the anonymous host list.
var organizationID = regexp.MustCompile(`^(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
// registryLogin is what an organization registered for one upstream repository.
@@ -45,7 +44,8 @@ type registryLogin struct {
// where its password is kept; Secret Manager holds the password, readable by
// this process and not by the control plane. Positive metadata is read before
// every pull so rotation stops old bearer reuse across proxy replicas. Passwords
-// are read only when a token must be exchanged; negative lookups keep their TTL.
+// are read only for token exchanges. Only the anonymous host list can use a
+// cached negative lookup.
type credentialFinder struct {
api *apiclient.APIClient
secrets secrets.Reader
@@ -62,8 +62,8 @@ type foundCredential struct {
secretVersion string
}
-// newCredentialFinder returns nil when there is no secret store, and a nil
-// finder finds nothing: every pull is then anonymous, as before credentials.
+// newCredentialFinder returns nil when there is no secret store, leaving only
+// anonymous pulls to hosts on the anonymous list.
func newCredentialFinder(api *apiclient.APIClient, reader secrets.Reader, ttl time.Duration) *credentialFinder {
if reader == nil {
return nil
@@ -86,12 +86,15 @@ func (f *credentialFinder) lookup(ctx context.Context, from caller, org, host, r
}
key := from.runnerID + "\x00" + org + "\x00" + host + "\x00" + repository
found, known := f.found.get(key)
- if !known {
+ customRegistry := isCustomRegistry(ctx)
+ if !known || customRegistry {
var err error
if found, err = f.ask(ctx, from.apiKey, org, host, repository); err != nil {
return foundCredential{}, err
}
- if found.none || found.forbidden {
+ // Custom upstreams need a current answer even after a miss, so a
+ // newly registered credential takes effect on the next request.
+ if !customRegistry && (found.none || found.forbidden) {
f.found.put(key, found, f.ttl)
}
}
diff --git a/apps/image-service/internal/proxy/credentials_test.go b/apps/image-service/internal/proxy/credentials_test.go
index 298796dbb..74308cca1 100644
--- a/apps/image-service/internal/proxy/credentials_test.go
+++ b/apps/image-service/internal/proxy/credentials_test.go
@@ -7,8 +7,10 @@ import (
"context"
"encoding/base64"
"errors"
+ "net"
"net/http"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -169,6 +171,114 @@ func TestAPrivatePullPresentsTheOrganizationsLoginToTheTokenEndpoint(t *testing.
}
}
+func TestCustomRegistryRequiresAMatchingCredential(t *testing.T) {
+ const host = "registry.example.com"
+ repository := "/v2/" + acmeOrg + "/" + host + "/acme/app"
+ manifest := repository + "/manifests/1.2"
+ upstream := newStubUpstream(t)
+ router, _, plane, _ := privateProxy(t, upstream)
+ loginKey := acmeOrg + " " + host + " acme/app"
+
+ if response := pull(router, http.MethodGet, manifest, runnerKey); response.Code != http.StatusForbidden || len(upstream.seen()) != 0 {
+ t.Fatalf("unapproved registry returned %d and made %d upstream requests", response.Code, len(upstream.seen()))
+ }
+
+ plane.logins.Store(loginKey, acmeVersion)
+ if response := pull(router, http.MethodGet, manifest, runnerKey); response.Code != http.StatusOK || response.Body.String() != string(upstream.manifest) {
+ t.Fatalf("private manifest returned %d: %s", response.Code, response.Body.String())
+ }
+ if response := pull(router, http.MethodGet, repository+"/blobs/"+digestOf(upstream.blob), runnerKey); response.Code != http.StatusOK || response.Body.String() != string(upstream.blob) {
+ t.Fatalf("private layer returned %d: %s", response.Code, response.Body.String())
+ }
+ wantLogin := "Basic " + base64.StdEncoding.EncodeToString([]byte("acme-bot:"+acmePassword))
+ if exchanges := tokenRequests(upstream); len(exchanges) != 1 || exchanges[0].authorization != wantLogin {
+ t.Fatalf("wanted one organization credential exchange, got %d exchanges", len(exchanges))
+ }
+
+ previousRequests := len(upstream.seen())
+ assignment := runnerKey + " " + acmeOrg
+ plane.hosting.Delete(assignment)
+ if response := pull(router, http.MethodGet, manifest, runnerKey); response.Code != http.StatusForbidden || len(upstream.seen()) != previousRequests {
+ t.Fatalf("after runner reassignment the same ref returned %d and made %d new upstream requests", response.Code, len(upstream.seen())-previousRequests)
+ }
+ plane.hosting.Store(assignment, true)
+ plane.logins.Delete(loginKey)
+ if response := pull(router, http.MethodGet, manifest, runnerKey); response.Code != http.StatusForbidden || len(upstream.seen()) != previousRequests {
+ t.Fatalf("after removing the credential the same ref returned %d and made %d new upstream requests", response.Code, len(upstream.seen())-previousRequests)
+ }
+}
+
+func TestCustomRegistryExplainsAnUnsupportedBasicChallenge(t *testing.T) {
+ const host = "registry.example.com"
+ upstream := newStubUpstream(t)
+ var requests atomic.Int64
+ upstream.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ if r.Header.Get("Authorization") != "" {
+ t.Error("unexpected authorization on a request to a Basic-only registry")
+ }
+ w.Header().Set("Www-Authenticate", `Basic realm="registry"`)
+ w.WriteHeader(http.StatusUnauthorized)
+ })
+ router, _, plane, _ := privateProxy(t, upstream)
+ plane.logins.Store(acmeOrg+" "+host+" acme/app", acmeVersion)
+
+ response := pull(router, http.MethodGet, "/v2/"+acmeOrg+"/"+host+"/acme/app/manifests/1.2", runnerKey)
+
+ if response.Code != http.StatusForbidden || !strings.Contains(response.Body.String(), "Bearer token endpoint on the same host") {
+ t.Fatalf("wanted a denial explaining the Bearer requirement, got %d: %s", response.Code, response.Body.String())
+ }
+ if count := requests.Load(); count != 1 {
+ t.Fatalf("made %d upstream requests, want 1", count)
+ }
+}
+
+func TestCustomRegistryRedirectPolicy(t *testing.T) {
+ const host = "registry.example.com"
+ const cdn = "cdn." + host
+ for _, tc := range []struct {
+ name, blobRedirect, tokenRedirect, authorization string
+ status int
+ cdnDial bool
+ }{
+ {"same origin", "https://" + host + "/cdn-layer", "", "Bearer upstream-issued-token", http.StatusOK, false},
+ {"CDN receives no bearer", "https://" + cdn + "/cdn-layer", "", "", http.StatusOK, true},
+ {"cleartext denied", "http://" + cdn + "/cdn-layer", "", "", http.StatusForbidden, false},
+ {"password stays at the token origin", "", "https://" + cdn + "/token", "", http.StatusBadGateway, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ upstream := newStubUpstream(t)
+ upstream.redirectBlob = tc.blobRedirect
+ upstream.redirectToken = tc.tokenRedirect
+ router, proxy, plane, _ := privateProxy(t, upstream)
+ plane.logins.Store(acmeOrg+" "+host+" acme/app", acmeVersion)
+ var dialedCDN atomic.Bool
+ proxy.upstream = oci.NewClient(upstream.clientDialing(func(_ context.Context, _, address string) (bool, error) {
+ name, _, err := net.SplitHostPort(address)
+ if name == cdn {
+ dialedCDN.Store(true)
+ }
+ return name == host || name == cdn, err
+ }))
+ proxy.tokens = newTokenBroker(proxy.upstream)
+ path := "/v2/" + acmeOrg + "/" + host + "/acme/app/blobs/" + digestOf(upstream.blob)
+
+ response := pull(router, http.MethodGet, path, runnerKey)
+
+ if response.Code != tc.status || dialedCDN.Load() != tc.cdnDial {
+ t.Fatalf("got HTTP %d with CDN dial %v: %s", response.Code, dialedCDN.Load(), response.Body.String())
+ }
+ if tc.status == http.StatusOK {
+ seen := upstream.seen()
+ redirected := seen[len(seen)-1]
+ if redirected.path != "/cdn-layer" || redirected.authorization != tc.authorization {
+ t.Fatalf("unexpected redirect request: %+v", redirected)
+ }
+ }
+ })
+ }
+}
+
func TestATokenBoughtWithALoginIsKeptFiveMinutesAtMost(t *testing.T) {
upstream := newStubUpstream(t)
// gcr.io's, measured: twelve hours. Kept that long, a deleted login would
diff --git a/apps/image-service/internal/proxy/guard.go b/apps/image-service/internal/proxy/guard.go
index 1df870527..925e4cdd6 100644
--- a/apps/image-service/internal/proxy/guard.go
+++ b/apps/image-service/internal/proxy/guard.go
@@ -9,6 +9,8 @@ import (
"fmt"
"net"
"net/http"
+ "net/url"
+ "strings"
"syscall"
"time"
)
@@ -82,15 +84,40 @@ func upstreamClient(dial func(context.Context, string, string) (net.Conn, error)
ResponseHeaderTimeout: timeout,
ExpectContinueTimeout: time.Second,
},
- CheckRedirect: func(_ *http.Request, via []*http.Request) error {
+ CheckRedirect: func(next *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return fmt.Errorf("stopped after %d redirects", maxRedirects)
}
+ if initial := via[0]; isCustomRegistry(initial.Context()) {
+ return checkCustomRegistryRedirect(initial, next)
+ }
return nil
},
}
}
+func checkCustomRegistryRedirect(initial, next *http.Request) error {
+ if next.URL.Scheme != "https" || next.URL.User != nil {
+ return fmt.Errorf("%w: custom registry redirects require HTTPS without user information", ErrAddressRefused)
+ }
+ if httpsOrigin(next.URL) == httpsOrigin(initial.URL) {
+ return nil
+ }
+ if strings.HasPrefix(initial.Header.Get("Authorization"), "Basic ") {
+ return fmt.Errorf("%w: credentialed token redirect changes origin", ErrRealmRefused)
+ }
+ next.Header.Del("Authorization")
+ return nil
+}
+
+func httpsOrigin(target *url.URL) string {
+ port := target.Port()
+ if port == "" {
+ port = "443"
+ }
+ return net.JoinHostPort(strings.ToLower(target.Hostname()), port)
+}
+
// routable reports whether the registry proxy may open a connection to ip.
//
// Everything that is not a public address is refused. A registry has no reason
diff --git a/apps/image-service/internal/proxy/handler.go b/apps/image-service/internal/proxy/handler.go
index 01288ef91..e4af65797 100644
--- a/apps/image-service/internal/proxy/handler.go
+++ b/apps/image-service/internal/proxy/handler.go
@@ -6,6 +6,7 @@ package proxy
import (
"context"
"errors"
+ "fmt"
"io"
"log/slog"
"net/http"
@@ -71,10 +72,6 @@ func (p *registryProxy) pull(c *gin.Context) {
if !ok {
return
}
- if err := p.allowlist.permit(route.PublishedHost); err != nil {
- refuse(c, http.StatusForbidden, oci.CodeDenied, err.Error())
- return
- }
if retryAfter, allowed := p.limits.allow(caller.runnerID, route.Org); !allowed {
c.Header("Retry-After", strconv.Itoa(int(retryAfter.Round(time.Second)/time.Second)+1))
// Which meter tripped is this proxy's business, not the caller's: it
@@ -84,7 +81,11 @@ func (p *registryProxy) pull(c *gin.Context) {
return
}
- response, presentedLogin, err := p.forward(c.Request.Context(), route, c.Request.Method, c.Request.Header, caller)
+ ctx := c.Request.Context()
+ if p.allowlist.permit(route.PublishedHost) != nil {
+ ctx = context.WithValue(ctx, customRegistryKey{}, true)
+ }
+ response, presentedLogin, err := p.forward(ctx, route, c.Request.Method, c.Request.Header, caller)
if err != nil {
p.refuseUpstream(c, route, presentedLogin, err)
return
@@ -127,7 +128,7 @@ func (p *registryProxy) forward(
from caller,
) (*http.Response, bool, error) {
header := upstreamHeader(inbound)
- credential, err := p.credentials.lookup(ctx, from, route.Org, route.PublishedHost, route.Upstream.Repository)
+ credential, err := p.credentialForPull(ctx, from, route)
if err != nil {
return nil, false, err
}
@@ -146,7 +147,7 @@ func (p *registryProxy) forward(
login, err := p.credentials.loginFrom(ctx, credential)
if errors.Is(err, ErrCredentialUnavailable) {
// Rotation may have retired the selected version during the challenge round trip.
- credential, err = p.credentials.lookup(ctx, from, route.Org, route.PublishedHost, route.Upstream.Repository)
+ credential, err = p.credentialForPull(ctx, from, route)
if err != nil {
return nil, false, err
}
@@ -163,6 +164,17 @@ func (p *registryProxy) forward(
return response, login != nil, err
}
+func (p *registryProxy) credentialForPull(ctx context.Context, from caller, route Route) (foundCredential, error) {
+ credential, err := p.credentials.lookup(ctx, from, route.Org, route.PublishedHost, route.Upstream.Repository)
+ if err != nil {
+ return foundCredential{}, err
+ }
+ if isCustomRegistry(ctx) && credential.none {
+ return foundCredential{}, fmt.Errorf("%w: a matching registry credential is required for %s", ErrHostRefused, route.PublishedHost)
+ }
+ return credential, nil
+}
+
// relay copies the upstream answer to the caller.
//
// Untouched, and streamed. The digest a client verifies covers the manifest
@@ -295,6 +307,10 @@ func (p *registryProxy) refuseRoute(c *gin.Context, err error) {
}
func (p *registryProxy) refuseUpstream(c *gin.Context, route Route, presentedLogin bool, err error) {
+ if errors.Is(err, ErrHostRefused) {
+ refuse(c, http.StatusForbidden, oci.CodeDenied, err.Error())
+ return
+ }
slog.WarnContext(c.Request.Context(), "Upstream pull failed",
"upstream", route.Upstream.Endpoint, "repository", route.Upstream.Repository, "error", err)
if errors.Is(err, ErrCredentialUnavailable) {
@@ -314,6 +330,10 @@ func (p *registryProxy) refuseUpstream(c *gin.Context, route Route, presentedLog
"upstream "+route.PublishedHost+" named a token endpoint on another host; the organization's credential was not sent")
return
}
+ if errors.Is(err, errCustomRegistryRequiresBearer) {
+ refuse(c, http.StatusForbidden, oci.CodeDenied, route.PublishedHost+": "+err.Error())
+ return
+ }
if presentedLogin && errors.Is(err, oci.ErrCredentialRejected) {
refuse(c, http.StatusForbidden, oci.CodeDenied, upstreamRefusal(route, presentedLogin))
return
diff --git a/apps/image-service/internal/proxy/handler_stub_test.go b/apps/image-service/internal/proxy/handler_stub_test.go
index 1c52e5aa5..88a654523 100644
--- a/apps/image-service/internal/proxy/handler_stub_test.go
+++ b/apps/image-service/internal/proxy/handler_stub_test.go
@@ -44,6 +44,7 @@ type stubUpstream struct {
// tokenExpiresIn is the lifetime the token endpoint states, in seconds.
tokenExpiresIn int
redirectBlob string
+ redirectToken string
mutex sync.Mutex
requests []stubRequest
@@ -90,6 +91,10 @@ func (u *stubUpstream) serve(w http.ResponseWriter, r *http.Request) {
u.mutex.Unlock()
if r.URL.Path == "/token" {
+ if u.redirectToken != "" {
+ http.Redirect(w, r, u.redirectToken, http.StatusFound)
+ return
+ }
u.mutex.Lock()
u.tokens++
u.mutex.Unlock()
@@ -98,6 +103,11 @@ func (u *stubUpstream) serve(w http.ResponseWriter, r *http.Request) {
return
}
+ if r.URL.Path == "/cdn-layer" {
+ _, _ = w.Write(u.blob)
+ return
+ }
+
if u.requireToken && r.Header.Get("Authorization") != "Bearer "+u.issuedToken {
w.Header().Set("Www-Authenticate",
`Bearer realm="https://`+r.Host+`/token",service="`+r.Host+`"`)
diff --git a/apps/image-service/internal/proxy/server.go b/apps/image-service/internal/proxy/server.go
index 2fe3cd877..18183cbc0 100644
--- a/apps/image-service/internal/proxy/server.go
+++ b/apps/image-service/internal/proxy/server.go
@@ -98,8 +98,8 @@ func acceptedProtocols() *http.Protocols {
}
// NewRouter builds the registry proxy's HTTP surface. It is separate from Start
-// so the surface can be exercised without binding a port. A nil reader leaves
-// every pull anonymous.
+// so the surface can be exercised without binding a port. A nil reader
+// permits only allowlisted anonymous pulls.
func NewRouter(cfg *config.Config, api *apiclient.APIClient, reader secrets.Reader) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
diff --git a/apps/image-service/internal/proxy/token.go b/apps/image-service/internal/proxy/token.go
index 9ce7bed10..40d0e2909 100644
--- a/apps/image-service/internal/proxy/token.go
+++ b/apps/image-service/internal/proxy/token.go
@@ -27,6 +27,8 @@ const credentialedTokenLifetime = 5 * time.Minute
// send an organization's login to.
var ErrRealmRefused = errors.New("token endpoint refused for a login")
+var errCustomRegistryRequiresBearer = errors.New("custom registry requires HTTPS and a Bearer token endpoint on the same host")
+
// tokenHostsBeyond names the hosts a registry's token endpoint may sit on
// other than the registry itself. Docker Hub's is `auth.docker.io`; ghcr.io,
// quay.io and gcr.io each issue tokens from their own host, as do gcr.io's
@@ -101,8 +103,9 @@ func (b *tokenBroker) acquire(
return "", err
}
if challenge.Scheme != oci.SchemeBearer {
- // Basic, or something nobody here speaks. Every registry a login is
- // accepted for answers Bearer, so there is no token to fetch.
+ if login != nil && isCustomRegistry(ctx) {
+ return "", errCustomRegistryRequiresBearer
+ }
return "", nil
}
if login != nil {
diff --git a/apps/image-service/internal/secrets/secrets.go b/apps/image-service/internal/secrets/secrets.go
index 09308d20f..4bb8d749a 100644
--- a/apps/image-service/internal/secrets/secrets.go
+++ b/apps/image-service/internal/secrets/secrets.go
@@ -36,7 +36,7 @@ type Reader interface {
// NewReader returns the reader store names: "gcp" for Secret Manager, "file"
// for a directory on a local stack. An empty store returns nil, which leaves
-// private registries off and every pull anonymous.
+// private registries off and permits only configured anonymous upstreams.
func NewReader(ctx context.Context, store, directory string) (Reader, error) {
switch store {
case "":
diff --git a/apps/infra/mdeploy/README.md b/apps/infra/mdeploy/README.md
index b886a7907..7d83684fa 100644
--- a/apps/infra/mdeploy/README.md
+++ b/apps/infra/mdeploy/README.md
@@ -185,6 +185,18 @@ the Proxy and ClickStack backend `healthChecks` fields take the health-check res
These fields are not arrays, despite their plural names. Kubernetes, firewall and forwarding-rule port lists retain their separate array contracts.
The provider-shape regressions inspect actual constructor inputs; a successful preview must also be checked for type warnings before apply.
+### Private registry upstreams
+
+On GCP stages with a registry proxy, an organization's matching credential
+allows private pulls from a custom HTTPS registry with a same-host Bearer token
+endpoint. Deploy the registry proxy before the API when enabling custom private
+registries.
+
+The optional `REGISTRY_PROXY_UPSTREAM_HOSTS` setting in the stage's `deploy`
+group controls anonymous pulls through the proxy. A nonempty value replaces the
+default hosts. Anonymous pulls that go directly through a Runner use the API's
+separate `BOXLITE_IMAGE_REGISTRY_ALLOWLIST`.
+
## CI orchestration
[mdeploy-all.yml](../../../.github/workflows/mdeploy-all.yml) resolves the requested ref, ensures
diff --git a/apps/infra/mdeploy/src/api-environment.ts b/apps/infra/mdeploy/src/api-environment.ts
index 37d8b33ab..4c277d2ec 100644
--- a/apps/infra/mdeploy/src/api-environment.ts
+++ b/apps/infra/mdeploy/src/api-environment.ts
@@ -285,6 +285,11 @@ const systemImagesFrom = (environment: Environment): Record<string, string> => {
// API on its built-in list, so an operator only sets this to widen or
// narrow it, with no code change.
...passthrough('BOXLITE_IMAGE_REGISTRY_ALLOWLIST'),
+ REGISTRY_PROXY_UPSTREAM_HOSTS: (optional(environment, 'REGISTRY_PROXY_UPSTREAM_HOSTS') ?? '')
+ .split(',')
+ .map((host) => host.trim().toLowerCase())
+ .filter(Boolean)
+ .join(','),
// The per-organization cold-pull budget. Unset keeps the API's 6 per 60s.
...passthrough('BOXLITE_IMAGE_COLD_PULL_LIMIT'),
...passthrough('BOXLITE_IMAGE_COLD_PULL_WINDOW_SECONDS'),
diff --git a/apps/infra/mdeploy/stack/index.ts b/apps/infra/mdeploy/stack/index.ts
index 941629598..154bf5b4c 100644
--- a/apps/infra/mdeploy/stack/index.ts
+++ b/apps/infra/mdeploy/stack/index.ts
@@ -395,17 +395,15 @@ export const deployStack = ({
* exists, so nothing of the API's is needed to build it. Until the API
* answers, a caller is told to retry, as during any restart of it.
*
- * Its whole environment is the stack's. The logins it presents upstream are
- * read from the credential store at pull time rather than delivered here,
- * and it reads nothing a stage would tune, so there is no store group for it
- * — one with nothing in it would be a place for a stale copy to sit. It is
- * told which store and which registries, as the API is, so the two cannot
- * name different ones.
+ * The proxy reads organization logins from the credential store and uses
+ * its configured host list for anonymous pulls.
*
* Telemetry on, for the reason the edge proxy's note further down gives: the
* binary declares both switches without a default, and one left unset ships
* nothing while looking healthy.
*/
+ const { [REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE]: anonymousUpstreamHosts, ...baseApiEnvironment } =
+ inputs.apiEnvironment
const registryProxy: RegistryProxy = providers.registryProxy({
network,
dependsOn: placed,
@@ -419,7 +417,7 @@ export const deployStack = ({
ENVIRONMENT: inputs.stage,
[REGISTRY_PROXY_PORT_VARIABLE]: String(REGISTRY_PROXY_PORT),
[REGISTRY_PROXY_CONTROL_PLANE_VARIABLE]: runnerApiUrl(`https://${publicHostsFor({ domain: inputs.domain }).api}`),
- [REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE]: REGISTRY_PROXY_UPSTREAM_HOSTS.join(','),
+ [REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE]: anonymousUpstreamHosts || REGISTRY_PROXY_UPSTREAM_HOSTS.join(','),
...registryCredentialEnvironment(registryCredentials),
},
})
@@ -438,7 +436,7 @@ export const deployStack = ({
const platformDomain = inputs.userDomain?.domain ?? null
const apiEnvironment = {
- ...inputs.apiEnvironment,
+ ...baseApiEnvironment,
// The first host's token, which is the one row the API seeds itself. Every
// later host is registered explicitly — see `runner-registration.ts`.
[API_RUNNER_TOKEN_VARIABLE]: defaultRunnerToken,
@@ -450,7 +448,6 @@ export const deployStack = ({
...(registryProxyHost
? {
[REGISTRY_PROXY_HOST_VARIABLE]: registryProxyHost,
- [REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE]: REGISTRY_PROXY_UPSTREAM_HOSTS.join(','),
}
: {}),
/*
diff --git a/apps/infra/mdeploy/stack/registry-proxy.ts b/apps/infra/mdeploy/stack/registry-proxy.ts
index 541868d9d..16bf5628e 100644
--- a/apps/infra/mdeploy/stack/registry-proxy.ts
+++ b/apps/infra/mdeploy/stack/registry-proxy.ts
@@ -60,10 +60,7 @@ export const REGISTRY_PROXY_CONTROL_PLANE_VARIABLE = 'BOXLITE_API_URL'
export const REGISTRY_PROXY_HEALTH_PATH = '/health'
/**
- * The registries a login may be registered for, which are also the ones the
- * proxy pulls from. Said once and written to both the API and the proxy: a
- * host the API accepted a login for and the proxy then refuses is a private
- * pull that fails with a 403 nobody expected.
+ * Default upstream hosts for anonymous pulls through the proxy.
*/
export const REGISTRY_PROXY_UPSTREAM_HOSTS = [
'ghcr.io',
diff --git a/apps/infra/mdeploy/test/gcp-pitfalls.test.ts b/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
index 718c1e64d..f06966c1e 100644
--- a/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
+++ b/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
@@ -1922,13 +1922,7 @@ test('the registry proxy can read registry passwords and write none', () => {
assert.match(grants[0], /condition: registryCredentials\.binding\.condition,/, 'the read is not bounded')
})
-test('the proxy, the API and the runner read the same registries and the same host', () => {
- /*
- * Said four times: here, in the proxy's config, in the API's fallback, and
- * in the runner's config. The stack writes both variables, so the defaults
- * matter where it writes nothing — a local stack — and a mismatch there is a
- * login the API accepts for a registry the proxy then refuses.
- */
+test('the proxy has stable anonymous defaults and the API and runner agree on the proxy host variable', () => {
const service = fileURLToPath(new URL('../../../image-service/', import.meta.url))
const api = fileURLToPath(new URL('../../../api/src/', import.meta.url))
const runner = fileURLToPath(new URL('../../../runner/', import.meta.url))
@@ -1939,13 +1933,6 @@ test('the proxy, the API and the runner read the same registries and the same ho
)
assert.equal(proxyDefault?.[1], REGISTRY_PROXY_UPSTREAM_HOSTS.join(','))
const apiProxy = readFileSync(`${api}registry/utils/registry-proxy.util.ts`, 'utf8')
- assert.match(apiProxy, new RegExp(`'${REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE}'`))
- // However the formatter wraps the array: the same hosts, in the same order.
- const fallback = apiProxy.match(/FALLBACK_CREDENTIALED_HOSTS = \[([^\]]*)\]/)
- assert.deepEqual(
- [...(fallback?.[1] ?? '').matchAll(/'([^']*)'/g)].map((quoted) => quoted[1]),
- REGISTRY_PROXY_UPSTREAM_HOSTS,
- )
assert.match(apiProxy, new RegExp(`'${REGISTRY_PROXY_HOST_VARIABLE}'`))
assert.match(
readFileSync(`${runner}cmd/runner/config/config.go`, 'utf8'),
diff --git a/apps/infra/mdeploy/test/stack.test.ts b/apps/infra/mdeploy/test/stack.test.ts
index 72ef79b97..00e4cff3e 100644
--- a/apps/infra/mdeploy/test/stack.test.ts
+++ b/apps/infra/mdeploy/test/stack.test.ts
@@ -13,8 +13,13 @@
*/
import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+import { parseBase } from 'mstage/config'
+import { valuesOfGroup } from 'mstage/select-group'
import { deployStack, type StackInputs, type StackProviders } from '../stack/index.ts'
+import { apiEnvironmentFrom } from '../src/api-environment.ts'
import { parseDeployConfig, type DeployConfig } from '../src/config.ts'
import type { ClickHouse } from '../stack/clickhouse.ts'
@@ -736,24 +741,15 @@ test('the registry proxy is built before the API, which writes its host into pri
assert.equal(read(seen.api.request.environment.REGISTRY_PROXY_HOST), 'registry-proxy-123.run.app')
})
-test('the API, the proxy and the runners agree on the proxy and its registries', () => {
- /*
- * One host and one list, each written to everything that reads it. A runner
- * with another host has no key for the refs it is handed; an API that accepts
- * a login for a registry the proxy will not pull from is a private pull that
- * fails with a 403 nobody expected.
- */
+test('the API and runners agree on the proxy host, and only the proxy gets the anonymous list', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
assert.equal(read(seen.runners.request.registryProxyHost), 'registry-proxy-123.run.app')
- assert.equal(
- seen.api.request.environment.REGISTRY_PROXY_UPSTREAM_HOSTS,
- 'ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io',
- )
+ assert.equal('REGISTRY_PROXY_UPSTREAM_HOSTS' in seen.api.request.environment, false)
assert.equal(
seen.registryProxy.request.environment.REGISTRY_PROXY_UPSTREAM_HOSTS,
- seen.api.request.environment.REGISTRY_PROXY_UPSTREAM_HOSTS,
+ 'ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io',
)
})
@@ -765,6 +761,48 @@ test('a stage with no registry proxy hands its host to nobody', () => {
assert.equal(seen.runners.request.registryProxyHost, null)
})
+test('a stored anonymous upstream list reaches the registry proxy', () => {
+ const key = 'REGISTRY_PROXY_UPSTREAM_HOSTS'
+ const path = fileURLToPath(new URL('../../mstage.env.json', import.meta.url))
+ const stage = parseBase(path, readFileSync(path, 'utf8'))
+ const optional = stage.envOptional.deploy ?? []
+ const required = Object.fromEntries(
+ stage.envSelectGroup.deploy.filter((name) => !optional.includes(name)).map((name) => [name, 'test-fixture']),
+ )
+
+ for (const [configured, expected] of [
+ [' GHCR.IO , , Registry.Example.com ', 'ghcr.io,registry.example.com'],
+ [' , ', 'ghcr.io,docker.io,quay.io,gcr.io,us.gcr.io,eu.gcr.io,asia.gcr.io'],
+ ]) {
+ const selected = valuesOfGroup({
+ group: 'deploy',
+ groups: stage.envSelectGroup,
+ optional,
+ where: path,
+ values: {
+ ...required,
+ STACK_DOMAIN: 'dev.boxlite.ai',
+ OIDC_ISSUER_BASE_URL: 'https://auth.dev.boxlite.ai',
+ [key]: configured,
+ },
+ })
+ assert.equal(selected[key], configured, 'mstage selects the stored override')
+
+ const { environment: apiEnvironment } = apiEnvironmentFrom({
+ environment: selected,
+ declaration: { groups: { deploy: stage.envSelectGroup.deploy, api: [] }, where: path },
+ region: 'asia-southeast1',
+ stage: 'dev',
+ home: 'gcp',
+ })
+ const { providers, seen } = bundle()
+ deployStack({ providers, config, inputs: inputs({ apiEnvironment }) })
+
+ assert.equal(key in seen.api.request.environment, false)
+ assert.equal(seen.registryProxy.request.environment[key], expected)
+ }
+})
+
test('the registry proxy is handed the API as its control plane', () => {
const { providers, seen } = bundle()
deployStack({ providers, config, inputs: inputs() })
diff --git a/apps/infra/mstage.env.json b/apps/infra/mstage.env.json
index d409e8c03..643b8ce0a 100644
--- a/apps/infra/mstage.env.json
+++ b/apps/infra/mstage.env.json
@@ -74,6 +74,7 @@
"BOXLITE_IMAGE_COLD_PULL_LIMIT",
"BOXLITE_IMAGE_COLD_PULL_WINDOW_SECONDS",
"BOXLITE_IMAGE_REGISTRY_ALLOWLIST",
+ "REGISTRY_PROXY_UPSTREAM_HOSTS",
"BOXLITE_SYSTEM_BASE_IMAGE",
"BOXLITE_SYSTEM_IMAGES",
"BOXLITE_SYSTEM_IMAGE_TAG",
diff --git a/src/boxlite/src/images/mod.rs b/src/boxlite/src/images/mod.rs
index d7af0a0f2..ddc06ee1b 100644
--- a/src/boxlite/src/images/mod.rs
+++ b/src/boxlite/src/images/mod.rs
@@ -22,7 +22,7 @@ pub use object::{ImageObject, ResolvedImage};
pub(crate) mod test_support {
use super::ImageManager;
- pub(crate) use super::store::tests::registry_answering;
+ pub(crate) use super::store::tests::{registry_answering, registry_serving};
/// Put a build in `images`' cache under `image_ref`, as a pull leaves it.
pub(crate) async fn seed_cached_build(images: &ImageManager, image_ref: &str, digest: &str) {
diff --git a/src/boxlite/src/images/store.rs b/src/boxlite/src/images/store.rs
index e77536b81..2680fcd8d 100644
--- a/src/boxlite/src/images/store.rs
+++ b/src/boxlite/src/images/store.rs
@@ -2145,7 +2145,9 @@ pub(super) mod tests {
/// A registry that answers each path in `routes` and 404s the rest, so a
/// test can let the first exchanges of a pull through and fail a later one.
/// Every body is sent with its own digest, as a registry would.
- async fn registry_serving(routes: Vec<(String, u16, &'static str, Vec<u8>)>) -> String {
+ pub(crate) async fn registry_serving(
+ routes: Vec<(String, u16, &'static str, Vec<u8>)>,
+ ) -> String {
use sha2::{Digest, Sha256};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
diff --git a/src/boxlite/src/litebox/init/tasks/container_rootfs.rs b/src/boxlite/src/litebox/init/tasks/container_rootfs.rs
index 56e0e241a..206644d0b 100644
--- a/src/boxlite/src/litebox/init/tasks/container_rootfs.rs
+++ b/src/boxlite/src/litebox/init/tasks/container_rootfs.rs
@@ -476,12 +476,15 @@ async fn prepare_disk_rootfs(
mod tests {
use super::{
apply_user_overrides, image_for_new_disk, image_for_restart, names_one_build, pinned_ref,
- records_resolved_image,
+ records_resolved_image, run_container_rootfs,
};
use crate::db::Database;
- use crate::images::test_support::{registry_answering, seed_cached_build};
+ use crate::images::test_support::{registry_answering, registry_serving, seed_cached_build};
use crate::images::{ContainerImageConfig, ImageManager, ResolvedImage};
- use crate::runtime::options::{ImageRegistry, RootfsSpec};
+ use crate::runtime::layout::{BoxFilesystemLayout, FsLayoutConfig};
+ use crate::runtime::options::{BoxliteOptions, ImageRegistry, RootfsSpec};
+ use crate::runtime::rt_impl::RuntimeImpl;
+ use sha2::{Digest, Sha256};
const DIGEST: &str = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const FIRST: &str = "sha256:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0";
@@ -615,6 +618,84 @@ mod tests {
assert_eq!(image.manifest_digest(), NEWER);
}
+ #[tokio::test]
+ async fn an_old_box_with_a_cold_cache_repulls_its_digest_at_the_saved_endpoint() {
+ const MANIFEST_TYPE: &str = "application/vnd.oci.image.manifest.v1+json";
+ let config = br#"{"architecture":"amd64","os":"linux","config":{"Cmd":["saved-build"]},"rootfs":{"type":"layers","diff_ids":[]}}"#;
+ let digest_of = |bytes: &[u8]| format!("sha256:{}", hex::encode(Sha256::digest(bytes)));
+ let config_digest = digest_of(config);
+ let manifest = serde_json::json!({
+ "schemaVersion": 2,
+ "mediaType": MANIFEST_TYPE,
+ "config": {
+ "mediaType": "application/vnd.oci.image.config.v1+json",
+ "digest": config_digest,
+ "size": config.len(),
+ },
+ "layers": [],
+ })
+ .to_string()
+ .into_bytes();
+ let digest = digest_of(&manifest);
+
+ // The fixture serves only the recorded digest under the saved path.
+ for repository in [
+ "team/app",
+ "0aaa0000-0000-4000-8000-000000000001/ghcr.io/team/app",
+ ] {
+ let host = registry_serving(vec![
+ (
+ format!("/v2/{repository}/manifests/{digest}"),
+ 200,
+ MANIFEST_TYPE,
+ manifest.clone(),
+ ),
+ (
+ format!("/v2/{repository}/blobs/{config_digest}"),
+ 200,
+ "application/json",
+ config.to_vec(),
+ ),
+ ])
+ .await;
+ let home = tempfile::tempdir().unwrap();
+ let runtime = RuntimeImpl::new_for_test(BoxliteOptions {
+ home_dir: home.path().join("runtime"),
+ image_registries: vec![ImageRegistry::http(&host)],
+ ..Default::default()
+ })
+ .unwrap();
+ let layout = BoxFilesystemLayout::new(
+ home.path().join("box"),
+ FsLayoutConfig::without_bind_mount(),
+ false,
+ );
+ let disk_path = layout.disk_path();
+ std::fs::create_dir_all(disk_path.parent().unwrap()).unwrap();
+ std::fs::write(&disk_path, b"existing disk").unwrap();
+
+ let (image_config, _disk, build) = run_container_rootfs(
+ &RootfsSpec::Image(format!("{host}/{repository}:v1")),
+ &[],
+ &runtime,
+ &layout,
+ true,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(&recorded(&digest)),
+ )
+ .await
+ .unwrap_or_else(|err| panic!("{repository} did not recover: {err}"));
+
+ assert_eq!(image_config.final_cmd(), ["saved-build"]);
+ assert_eq!(std::fs::read(&disk_path).unwrap(), b"existing disk");
+ assert!(build.is_none());
+ }
+ }
+
/// A recorded build this host can no longer read — gone from the cache,
/// and the registry will not give it back — leaves the ref to answer.
#[tokio::test]