diff --git a/.github/workflows/dev-containers.yml b/.github/workflows/dev-containers.yml index e4507ec73..31334e525 100644 --- a/.github/workflows/dev-containers.yml +++ b/.github/workflows/dev-containers.yml @@ -44,7 +44,8 @@ jobs: path: ${{ env.TGZ }} tests-matrix: name: Tests Matrix - runs-on: ubuntu-latest + # Ubuntu 26.04 (ubuntu-latest) breaks Compose builds (https://github.com/devcontainers/cli/issues/1320), the Docker-in-Docker Feature and Podman builds. + runs-on: ubuntu-24.04 timeout-minutes: 30 strategy: fail-fast: false diff --git a/.github/workflows/test-docker-v29.yml b/.github/workflows/test-docker-v29.yml index 2b4ea9623..da5cf8674 100644 --- a/.github/workflows/test-docker-v29.yml +++ b/.github/workflows/test-docker-v29.yml @@ -12,7 +12,8 @@ permissions: jobs: test-docker-v29: name: Docker v29.0.0 Compatibility - runs-on: ubuntu-latest + # Docker 29.0.0 has no package for Ubuntu 26.04 (ubuntu-latest). + runs-on: ubuntu-24.04 timeout-minutes: 20 steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index 174214383..08c0db35a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ Notable changes. +## November 2026 + +### [0.91.0] +- Add `--docker-arg` option for global Docker CLI arguments. (https://github.com/devcontainers/cli/pull/1304) +- Report the lookup kinds and reasons for blocked OCI authentication lookups in diagnostics, and include the diagnostics in failed `up` results. (https://github.com/devcontainers/cli/pull/1361) + ## October 2026 ### [0.90.0] diff --git a/package.json b/package.json index a7a7f2f50..ef09149ca 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@devcontainers/cli", "description": "Dev Containers CLI", - "version": "0.90.0", + "version": "0.91.0", "bin": { "devcontainer": "devcontainer.js" }, diff --git a/src/spec-common/ociAuth.ts b/src/spec-common/ociAuth.ts index b0817da38..cff1bf0e8 100644 --- a/src/spec-common/ociAuth.ts +++ b/src/spec-common/ociAuth.ts @@ -3,8 +3,19 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +export type OCIAuthLookupKind = 'image' | 'feature' | 'template'; + +// Why OCI auth hardening would block a token realm, checked in this order: +// - httpRealm: The realm does not use HTTPS. +// - differentPort: The realm is on the registry's hostname, but on a different port. +// - parentDomain: The realm is on a parent domain of the registry's hostname (e.g., registry.example.com and example.com). +// - differentHost: The realm is on any other host. +export type OCIAuthLookupBlockedReason = 'httpRealm' | 'differentPort' | 'parentDomain' | 'differentHost'; + export interface OCIAuthDiagnostics { authLookupWouldBeBlocked: boolean; + authLookupBlockedKinds: OCIAuthLookupKind[]; + authLookupBlockedReasons: OCIAuthLookupBlockedReason[]; registryRedirectWouldPreventCredentialForwarding: boolean; authServerRedirect: boolean; } @@ -12,6 +23,8 @@ export interface OCIAuthDiagnostics { export function createOCIAuthDiagnostics(): OCIAuthDiagnostics { return { authLookupWouldBeBlocked: false, + authLookupBlockedKinds: [], + authLookupBlockedReasons: [], registryRedirectWouldPreventCredentialForwarding: false, authServerRedirect: false, }; diff --git a/src/spec-configuration/containerCollectionsOCI.ts b/src/spec-configuration/containerCollectionsOCI.ts index 892a929af..729fd331a 100644 --- a/src/spec-configuration/containerCollectionsOCI.ts +++ b/src/spec-configuration/containerCollectionsOCI.ts @@ -8,7 +8,7 @@ import { Log, LogLevel } from '../spec-utils/log'; import { isLocalFile, mkdirpLocal, readLocalFile, writeLocalFile } from '../spec-utils/pfs'; import { requestEnsureAuthenticated } from './httpOCIRegistry'; import { GoARCH, GoOS, PlatformInfo } from '../spec-common/commonUtils'; -import { OCIAuthDiagnostics } from '../spec-common/ociAuth'; +import { OCIAuthDiagnostics, OCIAuthLookupKind } from '../spec-common/ociAuth'; export const DEVCONTAINER_MANIFEST_MEDIATYPE = 'application/vnd.devcontainers'; export const DEVCONTAINER_TAR_LAYER_MEDIATYPE = 'application/vnd.devcontainers.layer.v1+tar'; @@ -22,6 +22,7 @@ export interface CommonParams { allowedCrossOriginAuthHosts?: string[]; ociAuthHardening?: boolean; ociAuthDiagnostics: OCIAuthDiagnostics; + ociAuthLookupKind: OCIAuthLookupKind; } // Represents the unique OCI identifier for a Feature or Template. diff --git a/src/spec-configuration/containerFeaturesConfiguration.ts b/src/spec-configuration/containerFeaturesConfiguration.ts index 38d93a1a8..64c87133f 100644 --- a/src/spec-configuration/containerFeaturesConfiguration.ts +++ b/src/spec-configuration/containerFeaturesConfiguration.ts @@ -199,6 +199,7 @@ export interface ContainerFeatureInternalParams { allowedCrossOriginAuthHosts?: string[]; ociAuthHardening?: boolean; ociAuthDiagnostics: OCIAuthDiagnostics; + ociAuthLookupKind: 'feature'; } // TODO: Move to node layer. diff --git a/src/spec-configuration/httpOCIRegistry.ts b/src/spec-configuration/httpOCIRegistry.ts index 57b8dc6c7..06f8f38f5 100644 --- a/src/spec-configuration/httpOCIRegistry.ts +++ b/src/spec-configuration/httpOCIRegistry.ts @@ -7,7 +7,7 @@ import { requestResolveHeaders, requestResolveHeadersNoRedirects } from '../spec import { LogLevel } from '../spec-utils/log'; import { isLocalFile, readLocalFile } from '../spec-utils/pfs'; import { CommonParams, OCICollectionRef, OCIRef } from './containerCollectionsOCI'; -import { OCIAuthDiagnostics } from '../spec-common/ociAuth'; +import { OCIAuthLookupBlockedReason } from '../spec-common/ociAuth'; export type HEADERS = { 'authorization'?: string; 'user-agent'?: string; 'content-type'?: string; 'Accept'?: string; 'content-length'?: string }; @@ -126,17 +126,58 @@ export function isAllowedTokenServiceRealm(realm: string, registryUrl: string, c } } -function recordOCIAuthDiagnostic(params: CommonParams, key: keyof OCIAuthDiagnostics, message: string) { +function recordOCIAuthDiagnostic(params: CommonParams, key: 'registryRedirectWouldPreventCredentialForwarding' | 'authServerRedirect', message: string) { if (!params.ociAuthDiagnostics[key]) { params.ociAuthDiagnostics[key] = true; params.output.write(`[httpOci] OCI auth diagnostics: ${message}`, LogLevel.Info); } } +export function getAuthLookupBlockedReason(registryUrl: URL, realmUrl: URL): OCIAuthLookupBlockedReason { + if (realmUrl.protocol !== 'https:') { + return 'httpRealm'; + } + const registryHostname = registryUrl.hostname.toLowerCase(); + const realmHostname = realmUrl.hostname.toLowerCase(); + if (realmHostname === registryHostname) { + return 'differentPort'; + } + if (registryHostname.endsWith(`.${realmHostname}`)) { + return 'parentDomain'; + } + return 'differentHost'; +} + +function addSortedUnique(values: T[], value: T) { + if (values.includes(value)) { + return false; + } + values.push(value); + values.sort(); + return true; +} + +function recordAuthLookupWouldBeBlocked(params: CommonParams, registryUrl: URL, realmUrl: URL) { + const diagnostics = params.ociAuthDiagnostics; + const kind = params.ociAuthLookupKind; + const reason = getAuthLookupBlockedReason(registryUrl, realmUrl); + diagnostics.authLookupWouldBeBlocked = true; + const newKind = addSortedUnique(diagnostics.authLookupBlockedKinds, kind); + const newReason = addSortedUnique(diagnostics.authLookupBlockedReasons, reason); + if (newKind || newReason) { + params.output.write(`[httpOci] OCI auth diagnostics: Authentication lookup for ${kind} from registry '${registryUrl.host}' to realm origin '${realmUrl.origin}' would be blocked by OCI auth hardening (${reason}).`, LogLevel.Info); + } +} + function withOCIAuthDiagnostics(params: CommonParams, result: T) { + const diagnostics = params.ociAuthDiagnostics; return { ...result, - ociAuthDiagnostics: { ...params.ociAuthDiagnostics }, + ociAuthDiagnostics: { + ...diagnostics, + authLookupBlockedKinds: [...diagnostics.authLookupBlockedKinds], + authLookupBlockedReasons: [...diagnostics.authLookupBlockedReasons], + }, }; } @@ -237,7 +278,7 @@ export async function requestEnsureAuthenticated(params: CommonParams, httpOptio const crossOriginAuthHosts = parseCrossOriginAuthHosts([...builtInCrossOriginAuthHosts, ...(params.allowedCrossOriginAuthHosts || [])]); const authLookupWouldBeBlocked = !isAllowedTokenServiceRealmForPolicy(realmUrl, registryUrl, crossOriginAuthHosts); if (authLookupWouldBeBlocked) { - recordOCIAuthDiagnostic(params, 'authLookupWouldBeBlocked', `Authentication lookup from registry '${registryUrl.host}' to realm origin '${realmUrl.origin}' would be blocked by OCI auth hardening.`); + recordAuthLookupWouldBeBlocked(params, registryUrl, realmUrl); if (params.ociAuthHardening) { delete cachedAuthHeader[ociRef.registry]; const allowHint = realmUrl.protocol === 'https:' diff --git a/src/spec-node/containerFeatures.ts b/src/spec-node/containerFeatures.ts index eebb793f2..43de30bd2 100644 --- a/src/spec-node/containerFeatures.ts +++ b/src/spec-node/containerFeatures.ts @@ -148,7 +148,7 @@ export async function getExtendImageBuildInfo(params: DockerResolverParameters, const cacheFolder = await getCacheFolder(params.common.cliHost); const { noLockfile, frozenLockfile } = params; - const featuresConfig = await generateFeaturesConfig({ ...params.common, platform, cacheFolder, noLockfile, frozenLockfile }, dstFolder, config.config, additionalFeatures); + const featuresConfig = await generateFeaturesConfig({ ...params.common, platform, cacheFolder, noLockfile, frozenLockfile, ociAuthLookupKind: 'feature' }, dstFolder, config.config, additionalFeatures); if (!featuresConfig) { if (canAddLabelsToContainer && !imageBuildInfo.dockerfile) { return { diff --git a/src/spec-node/devContainers.ts b/src/spec-node/devContainers.ts index 11ab285c3..06c56e62c 100644 --- a/src/spec-node/devContainers.ts +++ b/src/spec-node/devContainers.ts @@ -8,7 +8,7 @@ import * as crypto from 'crypto'; import * as os from 'os'; import { mapNodeOSToGOOS, mapNodeArchitectureToGOARCH } from '../spec-configuration/containerCollectionsOCI'; -import { createOCIAuthDiagnostics } from '../spec-common/ociAuth'; +import { createOCIAuthDiagnostics, OCIAuthDiagnostics } from '../spec-common/ociAuth'; import { DockerResolverParameters, DevContainerAuthority, UpdateRemoteUserUIDDefault, BindMountConsistency, getCacheFolder, GPUAvailability } from './utils'; import { createNullLifecycleHook, finishBackgroundTasks, ResolverParameters, UserEnvProbe } from '../spec-common/injectHeadless'; import { GoARCH, GoOS, getCLIHost, loadNativeModule } from '../spec-common/commonUtils'; @@ -78,6 +78,7 @@ export interface ProvisionOptions { includeMergedConfig?: boolean; allowedCrossOriginAuthHosts?: string[]; ociAuthHardening?: boolean; + ociAuthDiagnostics?: OCIAuthDiagnostics; } export async function launch(options: ProvisionOptions, providedIdLabels: string[] | undefined, disposables: (() => Promise | undefined)[]) { @@ -169,7 +170,7 @@ export async function createDockerParams(options: ProvisionOptions, disposables: omitSyntaxDirective: options.omitSyntaxDirective, allowedCrossOriginAuthHosts: options.allowedCrossOriginAuthHosts, ociAuthHardening: options.ociAuthHardening, - ociAuthDiagnostics: createOCIAuthDiagnostics(), + ociAuthDiagnostics: options.ociAuthDiagnostics || createOCIAuthDiagnostics(), }; const dockerPath = options.dockerPath || 'docker'; diff --git a/src/spec-node/devContainersSpecCLI.ts b/src/spec-node/devContainersSpecCLI.ts index 221f9e3fa..89113938c 100644 --- a/src/spec-node/devContainersSpecCLI.ts +++ b/src/spec-node/devContainersSpecCLI.ts @@ -361,8 +361,9 @@ async function doProvision(options: ProvisionOptions, providedIdLabels: string[] const dispose = async () => { await Promise.all(disposables.map(d => d())); }; + const ociAuthDiagnostics = options.ociAuthDiagnostics || createOCIAuthDiagnostics(); try { - const result = await launch(options, providedIdLabels, disposables); + const result = await launch({ ...options, ociAuthDiagnostics }, providedIdLabels, disposables); return { outcome: 'success' as 'success', dispose, @@ -385,6 +386,7 @@ async function doProvision(options: ProvisionOptions, providedIdLabels: string[] disallowedFeatureId: err.data.disallowedFeatureId, didStopContainer: err.data.didStopContainer, learnMoreUrl: err.data.learnMoreUrl, + ociAuthDiagnostics, dispose, }; } @@ -1284,6 +1286,7 @@ async function outdated({ allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), + ociAuthLookupKind: 'feature' as 'feature', }; const outdated = await loadVersionInfo(params, configs.config.config); diff --git a/src/spec-node/featureUtils.ts b/src/spec-node/featureUtils.ts index f52ca0be7..ee297a0b9 100644 --- a/src/spec-node/featureUtils.ts +++ b/src/spec-node/featureUtils.ts @@ -21,5 +21,6 @@ export async function readFeaturesConfig(params: DockerCLIParameters, pkg: Packa allowedCrossOriginAuthHosts: params.allowedCrossOriginAuthHosts, ociAuthHardening: params.ociAuthHardening, ociAuthDiagnostics: params.ociAuthDiagnostics, + ociAuthLookupKind: 'feature', }, featuresTmpFolder, config, additionalFeatures); } \ No newline at end of file diff --git a/src/spec-node/featuresCLI/info.ts b/src/spec-node/featuresCLI/info.ts index 2ee958726..21c35c943 100644 --- a/src/spec-node/featuresCLI/info.ts +++ b/src/spec-node/featuresCLI/info.ts @@ -54,7 +54,7 @@ async function featuresInfo({ terminalDimensions: undefined, }, pkg, new Date(), disposables, true); - const params = { output, env: process.env, outputFormat, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics() }; + const params = { output, env: process.env, outputFormat, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), ociAuthLookupKind: 'feature' as 'feature' }; const jsonOutput: InfoJsonOutput = {}; diff --git a/src/spec-node/featuresCLI/publish.ts b/src/spec-node/featuresCLI/publish.ts index 46f38ea14..3e74ddce8 100644 --- a/src/spec-node/featuresCLI/publish.ts +++ b/src/spec-node/featuresCLI/publish.ts @@ -52,7 +52,7 @@ async function featuresPublish({ terminalDimensions: undefined, }, pkg, new Date(), disposables); - const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics() }; + const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), ociAuthLookupKind: 'feature' as 'feature' }; // Package features const outputDir = path.join(os.tmpdir(), `/features-output-${Date.now()}`); diff --git a/src/spec-node/featuresCLI/resolveDependencies.ts b/src/spec-node/featuresCLI/resolveDependencies.ts index 1c183ba30..06810b3a3 100644 --- a/src/spec-node/featuresCLI/resolveDependencies.ts +++ b/src/spec-node/featuresCLI/resolveDependencies.ts @@ -79,6 +79,7 @@ async function featuresResolveDependencies({ allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), + ociAuthLookupKind: 'feature' as 'feature', }; const cwd = workspaceFolder || process.cwd(); diff --git a/src/spec-node/templatesCLI/apply.ts b/src/spec-node/templatesCLI/apply.ts index 507c74f97..037b02b39 100644 --- a/src/spec-node/templatesCLI/apply.ts +++ b/src/spec-node/templatesCLI/apply.ts @@ -90,7 +90,7 @@ async function templateApply({ omitPaths, }; - const files = await fetchTemplate({ output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics() }, selectedTemplate, workspaceFolder, userProvidedTmpDir); + const files = await fetchTemplate({ output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), ociAuthLookupKind: 'template' }, selectedTemplate, workspaceFolder, userProvidedTmpDir); if (!files) { output.write(`Failed to fetch template '${id}'.`, LogLevel.Error); process.exit(1); diff --git a/src/spec-node/templatesCLI/metadata.ts b/src/spec-node/templatesCLI/metadata.ts index 3fea84f89..11b82037c 100644 --- a/src/spec-node/templatesCLI/metadata.ts +++ b/src/spec-node/templatesCLI/metadata.ts @@ -42,7 +42,7 @@ async function templateMetadata({ terminalDimensions: undefined, }, pkg, new Date(), disposables); - const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics() }; + const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), ociAuthLookupKind: 'template' as 'template' }; output.write(`Fetching metadata for ${templateId}`, LogLevel.Trace); const templateRef = getRef(output, templateId); diff --git a/src/spec-node/templatesCLI/publish.ts b/src/spec-node/templatesCLI/publish.ts index 1e6ad3c9e..74d3c0ba5 100644 --- a/src/spec-node/templatesCLI/publish.ts +++ b/src/spec-node/templatesCLI/publish.ts @@ -53,7 +53,7 @@ async function templatesPublish({ terminalDimensions: undefined, }, pkg, new Date(), disposables); - const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics() }; + const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics: createOCIAuthDiagnostics(), ociAuthLookupKind: 'template' as 'template' }; // Package templates const outputDir = path.join(os.tmpdir(), `/templates-output-${Date.now()}`); diff --git a/src/spec-node/upgradeCommand.ts b/src/spec-node/upgradeCommand.ts index a48b2c686..cac2891ac 100644 --- a/src/spec-node/upgradeCommand.ts +++ b/src/spec-node/upgradeCommand.ts @@ -125,6 +125,7 @@ async function featuresUpgrade({ allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics, + ociAuthLookupKind: 'feature' as 'feature', }; if (feature && targetVersion) { diff --git a/src/spec-node/utils.ts b/src/spec-node/utils.ts index 88e2dccc8..90b0c9868 100644 --- a/src/spec-node/utils.ts +++ b/src/spec-node/utils.ts @@ -332,7 +332,7 @@ function logErrorStdoutStderr(err: any, output: Log) { export async function inspectImageInRegistry(output: Log, platformInfo: PlatformInfo, name: string, allowedCrossOriginAuthHosts?: string[], ociAuthHardening?: boolean, ociAuthDiagnostics: OCIAuthDiagnostics = createOCIAuthDiagnostics()): Promise { const resourceAndVersion = qualifyImageName(name); - const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics }; + const params = { output, env: process.env, allowedCrossOriginAuthHosts, ociAuthHardening, ociAuthDiagnostics, ociAuthLookupKind: 'image' as 'image' }; const ref = getRef(output, resourceAndVersion); if (!ref) { throw new Error(`Could not parse image name '${name}'`); diff --git a/src/test/cli.up.test.ts b/src/test/cli.up.test.ts index 688a4c84d..5fda4584f 100644 --- a/src/test/cli.up.test.ts +++ b/src/test/cli.up.test.ts @@ -7,6 +7,7 @@ import * as assert from 'assert'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; +import { createOCIAuthDiagnostics } from '../spec-common/ociAuth'; import { devContainerDown, devContainerUp, shellExec, UpResult } from './testUtils'; const pkg = require('../../package.json'); @@ -65,6 +66,7 @@ describe('Dev Containers CLI', function () { const res = JSON.parse(error.stdout); assert.equal(res.outcome, 'error'); assert.match(res.message, /Dev container config \(.*\) not found./); + assert.deepEqual(res.ociAuthDiagnostics, createOCIAuthDiagnostics()); } assert.equal(success, false, 'expect non-successful call'); }); diff --git a/src/test/httpOCIRegistry.test.ts b/src/test/httpOCIRegistry.test.ts index 7e28d14b4..a9809a484 100644 --- a/src/test/httpOCIRegistry.test.ts +++ b/src/test/httpOCIRegistry.test.ts @@ -10,7 +10,7 @@ import { promisify } from 'util'; import { assert } from 'chai'; import { OCICollectionRef } from '../spec-configuration/containerCollectionsOCI'; -import { isAllowedTokenServiceRealm, isOCIRegistryOrigin, parseCrossOriginAuthHosts, requestEnsureAuthenticated } from '../spec-configuration/httpOCIRegistry'; +import { getAuthLookupBlockedReason, isAllowedTokenServiceRealm, isOCIRegistryOrigin, parseCrossOriginAuthHosts, requestEnsureAuthenticated } from '../spec-configuration/httpOCIRegistry'; import { nullLog } from '../spec-utils/log'; import { createTestCommonParams } from './testUtils'; @@ -93,6 +93,25 @@ describe('OCI registry authentication', () => { }); }); + describe('getAuthLookupBlockedReason', () => { + const cases = [ + { realm: 'http://registry.example/token', registryUrl: 'https://registry.example/v2/', expected: 'httpRealm' }, + { realm: 'http://auth.example/token', registryUrl: 'https://registry.example/v2/', expected: 'httpRealm' }, + { realm: 'https://registry.example:8443/token', registryUrl: 'https://registry.example/v2/', expected: 'differentPort' }, + { realm: 'https://gitlab.example/jwt/auth', registryUrl: 'https://gitlab.example:5050/v2/', expected: 'differentPort' }, + { realm: 'https://gitlab.example/jwt/auth', registryUrl: 'https://registry.gitlab.example/v2/', expected: 'parentDomain' }, + { realm: 'https://gitlab.example/jwt/auth', registryUrl: 'https://notgitlab.example/v2/', expected: 'differentHost' }, + { realm: 'https://docker-auth.example/auth', registryUrl: 'https://docker.example/v2/', expected: 'differentHost' }, + { realm: 'https://registry.example.attacker.example/token', registryUrl: 'https://registry.example/v2/', expected: 'differentHost' }, + ]; + + for (const { realm, registryUrl, expected } of cases) { + it(`classifies '${realm}' for '${registryUrl}' as '${expected}'`, () => { + assert.equal(getAuthLookupBlockedReason(new URL(registryUrl), new URL(realm)), expected); + }); + } + }); + describe('parseCrossOriginAuthHosts', () => { it('normalizes authorities and preserves ports', () => { const parsed = parseCrossOriginAuthHosts(['REGISTRY.EXAMPLE:8443=AUTH.EXAMPLE:9443']); @@ -293,6 +312,63 @@ describe('OCI registry authentication', () => { } }); + it('records the kinds and reasons of blocked authentication lookups', async () => { + let tokenRequests = 0; + const registryServer = http.createServer((request, response) => { + if (request.url?.startsWith('/token')) { + tokenRequests++; + response.end(JSON.stringify({ token: 'registry-token' })); + return; + } + const registryPort = (registryServer.address() as AddressInfo).port; + const realm = request.url?.startsWith('/v2/test/image/') + ? 'https://127.0.0.1:1/token' + : `http://localhost:${registryPort}/token`; + response.writeHead(401, { + 'WWW-Authenticate': `Bearer realm="${realm}",service="registry.example",scope="repository:test:pull"`, + }); + response.end(); + }); + const registryPort = await listen(registryServer); + const registry = `127.0.0.1:${registryPort}`; + const logMessages: string[] = []; + const output = { + ...nullLog, + write: (text: string) => logMessages.push(text), + }; + const params = { ...createTestCommonParams(output, {}), ociAuthHardening: true }; + const lookup = (path: string, ociAuthLookupKind: 'image' | 'feature') => requestEnsureAuthenticated({ ...params, ociAuthLookupKind }, { + type: 'GET', + url: `http://${registry}/v2/${path}/manifests/latest`, + headers: {}, + }, { + scheme: 'http', + registry, + path, + resource: `${registry}/${path}`, + tag: 'latest', + version: 'latest', + }); + + try { + assert.isUndefined(await lookup('test/image', 'image')); + assert.isUndefined(await lookup('test/features', 'feature')); + assert.isUndefined(await lookup('test/image', 'feature')); + + assert.equal(tokenRequests, 0); + assert.deepEqual(params.ociAuthDiagnostics, { + authLookupWouldBeBlocked: true, + authLookupBlockedKinds: ['feature', 'image'], + authLookupBlockedReasons: ['differentPort', 'httpRealm'], + registryRedirectWouldPreventCredentialForwarding: false, + authServerRedirect: false, + }); + assert.lengthOf(logMessages.filter(message => message.includes('OCI auth diagnostics:')), 2); + } finally { + await close(registryServer); + } + }); + it('surfaces shadow diagnostics when hardening is disabled', async () => { const token = 'registry-token'; const bearerScheme = 'Bearer'; @@ -362,6 +438,8 @@ describe('OCI registry authentication', () => { assert.equal(redirectTargetRequests, 1); assert.deepEqual(result?.ociAuthDiagnostics, { authLookupWouldBeBlocked: true, + authLookupBlockedKinds: ['feature'], + authLookupBlockedReasons: ['httpRealm'], registryRedirectWouldPreventCredentialForwarding: true, authServerRedirect: true, }); @@ -547,6 +625,8 @@ describe('OCI registry authentication', () => { assert.equal(tokenRequests, 1); assert.deepEqual(result.ociAuthDiagnostics, { authLookupWouldBeBlocked: false, + authLookupBlockedKinds: [], + authLookupBlockedReasons: [], registryRedirectWouldPreventCredentialForwarding: false, authServerRedirect: false, }); diff --git a/src/test/testUtils.ts b/src/test/testUtils.ts index 1eaaded55..da601096c 100644 --- a/src/test/testUtils.ts +++ b/src/test/testUtils.ts @@ -178,11 +178,12 @@ export const testSubstitute: SubstituteConfig = value => { export const output = makeLog(createPlainLog(text => process.stdout.write(text), () => LogLevel.Trace)); -export function createTestCommonParams(output: Log, env: NodeJS.ProcessEnv = process.env): CommonParams { +export function createTestCommonParams(output: Log, env: NodeJS.ProcessEnv = process.env): CommonParams & { ociAuthLookupKind: 'feature' } { return { output, env, ociAuthDiagnostics: createOCIAuthDiagnostics(), + ociAuthLookupKind: 'feature', }; }