From 03d8570593f70d00651c649ca8003fd899c7b4e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 10:29:49 +0000 Subject: [PATCH 01/11] feat(hosted-git): land the hosted-git seam without the Durable Object (L16) Self-host landing slice L16 (decision D7: seam only; the HostedGitRepo DO and vendored dgit stay in the self-host build). - services/hosted-git/backend.ts: resolveArtifactsBackend / isArtifactsAvailable and a fallback registration hook for the self-host build. On Cloudflare the result is exactly the Artifacts binding or null. - Route every env.ARTIFACTS caller through it: artifacts-enabled config, project create/seed-cleanup, project delete, runtime git token, and repo browsing via a new repo-hosting `artifacts` port. - C15: an Artifacts project whose remote is not *.artifacts.cloudflare.net gets cloneUrl + repositoryHost. `repository` is now required on the git-source input and every caller passes the row it already holds: no D1 read added. - vm-agent: attach the workspace git token (username "x") and enable the credential helper only for the exact RepositoryHost bound to an artifacts workspace. Co-Authored-By: Claude Opus 5.5 --- .../task-runner/workspace-dispatch-step.ts | 6 +- apps/api/src/index.ts | 3 +- apps/api/src/repo-hosting-ports/artifacts.ts | 13 ++ apps/api/src/repo-hosting-wiring.ts | 7 +- apps/api/src/routes/projects/crud.ts | 8 +- .../api/src/routes/projects/project-create.ts | 8 +- .../routes/workspaces/runtime-git-token.ts | 6 +- .../src/routes/workspaces/workspace-create.ts | 6 +- apps/api/src/services/hosted-git/backend.ts | 43 ++++ .../src/services/instant-restore-workspace.ts | 1 + apps/api/src/services/workspace-git-source.ts | 39 +++- apps/api/tests/setup/repo-hosting-ports.ts | 5 +- ...k-runner-workspace-branch-dispatch.test.ts | 22 +- .../unit/routes/artifacts-config.test.ts | 36 +++- .../routes/project-artifacts-creation.test.ts | 190 ++++++++++++++++++ .../tests/unit/routes/project-delete.test.ts | 38 +++- .../unit/routes/workspace-git-token.test.ts | 40 ++++ .../unit/services/hosted-git-backend.test.ts | 114 +++++++++++ .../workspace-git-source-artifacts.test.ts | 143 +++++++++++++ packages/repo-hosting/src/ports.ts | 15 +- .../repo-hosting/src/repo-browse/artifacts.ts | 4 +- .../repo-hosting/src/repo-browse/index.ts | 3 +- .../repo-browse-artifacts-backend.test.ts | 81 ++++++++ .../vm-agent/internal/bootstrap/bootstrap.go | 12 +- .../bootstrap/hosted_artifacts_host.go | 22 ++ .../bootstrap/hosted_artifacts_host_test.go | 104 ++++++++++ ...2026-11-17-selfhost-l16-hosted-git-seam.md | 55 +++++ 27 files changed, 997 insertions(+), 27 deletions(-) create mode 100644 apps/api/src/repo-hosting-ports/artifacts.ts create mode 100644 apps/api/src/services/hosted-git/backend.ts create mode 100644 apps/api/tests/unit/routes/project-artifacts-creation.test.ts create mode 100644 apps/api/tests/unit/services/hosted-git-backend.test.ts create mode 100644 apps/api/tests/unit/services/workspace-git-source-artifacts.test.ts create mode 100644 packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts create mode 100644 packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go create mode 100644 packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go create mode 100644 tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md diff --git a/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts b/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts index 3fdc60d254..dcbc669a24 100644 --- a/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts +++ b/apps/api/src/durable-objects/task-runner/workspace-dispatch-step.ts @@ -11,13 +11,16 @@ import type { TaskRunnerContext, TaskRunnerState } from './types'; type TaskRunnerProjectRepo = { repoProvider: string | null; + repository: string; }; async function loadTaskRunnerProjectRepo( state: TaskRunnerState, rc: TaskRunnerContext ): Promise { - return rc.env.DATABASE.prepare(`SELECT repo_provider AS repoProvider FROM projects WHERE id = ?`) + return rc.env.DATABASE.prepare( + `SELECT repo_provider AS repoProvider, repository FROM projects WHERE id = ?` + ) .bind(state.projectId) .first(); } @@ -38,6 +41,7 @@ async function createWorkspaceOnVmAgent( const gitSource = await resolveWorkspaceGitSource(drizzle(rc.env.DATABASE, { schema }), { id: state.projectId, repoProvider: projectRepo?.repoProvider ?? 'github', + repository: projectRepo?.repository ?? state.config.repository, }); const checkoutBranch = state.config.outputBranch || state.config.branch; const baseBranch = diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 00b52bc8c9..5eaea7bc6b 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -186,6 +186,7 @@ import { scheduled } from './scheduled/handler'; import { handleInboundAgentEmail } from './services/agent-email/inbound'; import { agentEmailConfig } from './services/agent-email/setup-state'; import { isAgentSignInEnabled } from './services/agent-sign-in/config'; +import { isArtifactsAvailable } from './services/hosted-git/backend'; import { isInstantRuntimeAvailable } from './services/vm-agent-container'; const app = new Hono<{ Bindings: Env }>(); @@ -274,7 +275,7 @@ app.get('/health', (c) => { // Public config — exposes feature flags the UI needs before auth app.get('/api/config/artifacts-enabled', (c) => { applyCacheHeaders(c, 'public-config'); - return c.json({ enabled: c.env.ARTIFACTS_ENABLED === 'true' && !!c.env.ARTIFACTS }); + return c.json({ enabled: isArtifactsAvailable(c.env) }); }); app.route('/api/config', platformCapabilitiesRoutes); diff --git a/apps/api/src/repo-hosting-ports/artifacts.ts b/apps/api/src/repo-hosting-ports/artifacts.ts new file mode 100644 index 0000000000..e4a6673306 --- /dev/null +++ b/apps/api/src/repo-hosting-ports/artifacts.ts @@ -0,0 +1,13 @@ +import type { ArtifactsBackendPort } from '@simple-agent-manager/repo-hosting/ports'; + +import type { Env } from '../env'; +import { resolveArtifactsBackend } from '../services/hosted-git/backend'; + +/** + * Repo hosting resolves the SAM-native repository backend through the worker's hosted-git seam: + * the Cloudflare Artifacts binding, or the backend a self-host build registered. The package hands + * over its narrow env; the full worker env is what reached it. + */ +export const artifactsPort: ArtifactsBackendPort = { + resolve: (env) => resolveArtifactsBackend(env as Env), +}; diff --git a/apps/api/src/repo-hosting-wiring.ts b/apps/api/src/repo-hosting-wiring.ts index 46fa8fa9d7..8afca26f05 100644 --- a/apps/api/src/repo-hosting-wiring.ts +++ b/apps/api/src/repo-hosting-wiring.ts @@ -5,7 +5,12 @@ */ import { configureRepoHostingPorts } from '@simple-agent-manager/repo-hosting/ports'; +import { artifactsPort } from './repo-hosting-ports/artifacts'; import { authPort } from './repo-hosting-ports/auth'; import { platformConfigPort } from './repo-hosting-ports/platform-config'; -configureRepoHostingPorts({ platformConfig: platformConfigPort, auth: authPort }); +configureRepoHostingPorts({ + platformConfig: platformConfigPort, + auth: authPort, + artifacts: artifactsPort, +}); diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index 0c4736d413..efd789880b 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -17,6 +17,7 @@ import { deleteProjectLibraryObjects, getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; +import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; import { registerProjectCreateRoute } from './project-create'; @@ -42,13 +43,16 @@ async function cleanupArtifactsRepoOnProjectDelete( action: 'orphaned_artifacts_repo_on_delete', }; - if (!env.ARTIFACTS || typeof env.ARTIFACTS.delete !== 'function') { + // The Cloudflare binding even when ARTIFACTS_ENABLED was turned off after creation (unchanged), + // else the backend the self-host build registered. + const artifacts = env.ARTIFACTS ?? resolveArtifactsBackend(env); + if (!artifacts || typeof artifacts.delete !== 'function') { log.warn('project_delete.artifacts_delete_unavailable', orphanDetails); return; } try { - const deleted = await env.ARTIFACTS.delete(project.artifactsRepoId); + const deleted = await artifacts.delete(project.artifactsRepoId); if (!deleted) { log.warn('project_delete.artifacts_delete_returned_false', orphanDetails); } diff --git a/apps/api/src/routes/projects/project-create.ts b/apps/api/src/routes/projects/project-create.ts index 3d8cedeede..663f60ad13 100644 --- a/apps/api/src/routes/projects/project-create.ts +++ b/apps/api/src/routes/projects/project-create.ts @@ -20,6 +20,7 @@ import { requireGitLabUserAccessToken, verifyGitLabProjectAccess, } from '../../services/gitlab'; +import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { assertRepositoryAccess, @@ -83,7 +84,8 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): if (!artifactsEnabled) { throw errors.badRequest('Artifacts repo provider is not enabled'); } - if (!c.env.ARTIFACTS) { + const artifacts = resolveArtifactsBackend(c.env); + if (!artifacts) { throw errors.internal('Artifacts binding is not configured'); } @@ -119,7 +121,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): // Must be sanitized: Artifacts rejects uppercase/spaces (the ULID projectId // is uppercase and normalizedName preserves spaces). const repoName = toArtifactsRepoName(normalizedName, projectId); - const created = await c.env.ARTIFACTS.create(repoName, { + const created = await artifacts.create(repoName, { description: description || undefined, setDefaultBranch: defaultBranch, }); @@ -148,7 +150,7 @@ export function registerProjectCreateRoute(crudRoutes: Hono<{ Bindings: Env }>): // Best-effort cleanup: the repo exists but has no usable content, and no // project row will reference it. Delete it so it does not leak quota. try { - await c.env.ARTIFACTS.delete(created.name); + await artifacts.delete(created.name); } catch (cleanupError) { log.error('project_create.artifacts_seed_cleanup_failed', { projectId, diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index 9c20b56109..42dcfd867b 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -19,6 +19,7 @@ import { requireGitLabUserAccessTokenResultForOwner, verifyGitLabProjectAccess, } from '../../services/gitlab'; +import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; import { assertRepositoryAccess } from '../projects/_helpers'; import { assertWorkspaceAcceptsCallback, @@ -221,7 +222,8 @@ runtimeRoutes.post('/:id/git-token', async (c) => { if (c.env.ARTIFACTS_ENABLED !== 'true') { throw errors.forbidden('Artifacts provider is not enabled'); } - if (!c.env.ARTIFACTS || !artifactsRepoId) { + const artifacts = resolveArtifactsBackend(c.env); + if (!artifacts || !artifactsRepoId) { throw errors.internal('Artifacts binding or repo ID missing'); } @@ -232,7 +234,7 @@ runtimeRoutes.post('/:id/git-token', async (c) => { const ttl = Number.isFinite(rawTtl) && rawTtl > 0 && rawTtl <= 86400 ? rawTtl : 3600; // Use requested scope or default to 'write' (agents need push access) const requestedScope = c.req.query('scope') === 'read' ? ('read' as const) : ('write' as const); - const repo = await c.env.ARTIFACTS.get(artifactsRepoId); + const repo = await artifacts.get(artifactsRepoId); await assertWorkspaceCallbackIdentityCurrent(c.env, workspace, 'git_token'); const tokenResult = await repo.createToken(requestedScope, ttl); diff --git a/apps/api/src/routes/workspaces/workspace-create.ts b/apps/api/src/routes/workspaces/workspace-create.ts index 7cbfa8d306..70185b3886 100644 --- a/apps/api/src/routes/workspaces/workspace-create.ts +++ b/apps/api/src/routes/workspaces/workspace-create.ts @@ -550,7 +550,11 @@ export function registerWorkspaceCreateRoute(crudRoutes: Hono<{ Bindings: Env }> resolvedReservation, createdAt: now, }, - linkedProject: { id: linkedProject.id, repoProvider: linkedProject.repoProvider }, + linkedProject: { + id: linkedProject.id, + repoProvider: linkedProject.repoProvider, + repository: linkedProject.repository, + }, taskId: chatTaskId, chatSessionId, mustProvisionNode, diff --git a/apps/api/src/services/hosted-git/backend.ts b/apps/api/src/services/hosted-git/backend.ts new file mode 100644 index 0000000000..857e95ff27 --- /dev/null +++ b/apps/api/src/services/hosted-git/backend.ts @@ -0,0 +1,43 @@ +/** + * The SAM-native repository backend: one answer to "which `Env.ARTIFACTS` does this install use?". + * + * - `ARTIFACTS_ENABLED !== 'true'`: none. + * - A Cloudflare Artifacts binding is present: that binding. This is every Cloudflare deployment. + * - Otherwise, the fallback backend the self-host build registered, if any. The Cloudflare build + * registers none, so on Cloudflare the result is exactly the binding or null. + * + * The self-host build (`apps/api/src/selfhost/`, never imported by `src/index.ts`) registers SAM's own + * git server here. This module holds only the selection, so the Cloudflare bundle carries no + * hosted-git implementation. + * + * Every caller that needs the backend goes through `resolveArtifactsBackend`, so the capability + * flag, project creation, browsing, git tokens and deletion cannot disagree. + */ +import type { Env } from '../../env'; + +export type ArtifactsBackend = NonNullable; + +/** Builds the fallback backend for an install with no Artifacts binding, or returns null. */ +export type ArtifactsBackendFallback = (env: Env) => ArtifactsBackend | null; + +let fallback: ArtifactsBackendFallback | null = null; + +/** + * Installs the backend used when Artifacts is enabled but no Cloudflare binding exists. Called once + * at module load by the self-host build. Passing null removes it (tests). + */ +export function registerArtifactsBackendFallback(factory: ArtifactsBackendFallback | null): void { + fallback = factory; +} + +/** The backend this install uses for SAM-native repositories, or null when it has none. */ +export function resolveArtifactsBackend(env: Env): ArtifactsBackend | null { + if (env.ARTIFACTS_ENABLED !== 'true') return null; + if (env.ARTIFACTS) return env.ARTIFACTS; + return fallback?.(env) ?? null; +} + +/** Whether this install can create and serve SAM-native (Artifacts) repositories. */ +export function isArtifactsAvailable(env: Env): boolean { + return resolveArtifactsBackend(env) !== null; +} diff --git a/apps/api/src/services/instant-restore-workspace.ts b/apps/api/src/services/instant-restore-workspace.ts index 4b0aba571c..990a930c83 100644 --- a/apps/api/src/services/instant-restore-workspace.ts +++ b/apps/api/src/services/instant-restore-workspace.ts @@ -47,6 +47,7 @@ export async function loadInstantRestoreWorkspace( const source = await resolveWorkspaceGitSource(db, { id: input.projectId, repoProvider: row.repoProvider, + repository: row.repository, }); return { workspaceId: input.workspaceId, diff --git a/apps/api/src/services/workspace-git-source.ts b/apps/api/src/services/workspace-git-source.ts index d62772cc79..23d2623dfa 100644 --- a/apps/api/src/services/workspace-git-source.ts +++ b/apps/api/src/services/workspace-git-source.ts @@ -13,7 +13,11 @@ export type WorkspaceGitSource = { repositoryPath: string | null; }; -export type WorkspaceGitSourceProject = Pick; +/** + * `repository` is required so every caller passes the clone URL it already holds: resolving an + * Artifacts project's host must not cost a D1 read on workspace creation. + */ +export type WorkspaceGitSourceProject = Pick; const DEFAULT_GITHUB_SOURCE: WorkspaceGitSource = { repoProvider: 'github', @@ -35,11 +39,43 @@ function normalizeRepoProvider( } } +/** Cloudflare Artifacts hosts; the VM agent recognizes these by name (`gitrepo.IsArtifactsHost`). */ +function isCloudflareArtifactsHost(host: string): boolean { + return host === 'artifacts.cloudflare.net' || host.endsWith('.artifacts.cloudflare.net'); +} + +/** + * An Artifacts project's clone URL is `projects.repository` (the backend's `create().remote`). For a + * Cloudflare Artifacts remote nothing is added: the VM agent knows that host by name. A remote on + * any other host (a self-hosted install's own git server) is bound as `repositoryHost`, the only + * host the VM agent then attaches the workspace's git token to (`isBoundHostedArtifactsHost`). + */ +function resolveArtifactsGitSource(repository: string): WorkspaceGitSource { + const artifactsSource: WorkspaceGitSource = { + ...DEFAULT_GITHUB_SOURCE, + repoProvider: 'artifacts', + }; + let url: URL; + try { + // A direct-provisioning request persisted by NodeLifecycle before this field existed carries + // no repository; `new URL(undefined)` throws, and the project keeps the Cloudflare behaviour. + url = new URL(repository); + } catch { + return artifactsSource; + } + const host = url.host.toLowerCase(); + if (url.protocol !== 'https:' || !host || isCloudflareArtifactsHost(host)) return artifactsSource; + return { ...artifactsSource, cloneUrl: repository, repositoryHost: host }; +} + export async function resolveWorkspaceGitSource( db: Db, project: WorkspaceGitSourceProject ): Promise { const repoProvider = normalizeRepoProvider(project.repoProvider); + if (repoProvider === 'artifacts') { + return resolveArtifactsGitSource(project.repository); + } if (repoProvider !== 'gitlab') { return { ...DEFAULT_GITHUB_SOURCE, @@ -75,6 +111,7 @@ export async function resolveWorkspaceGitSourceByProjectId( .select({ id: schema.projects.id, repoProvider: schema.projects.repoProvider, + repository: schema.projects.repository, }) .from(schema.projects) .where(eq(schema.projects.id, projectId)) diff --git a/apps/api/tests/setup/repo-hosting-ports.ts b/apps/api/tests/setup/repo-hosting-ports.ts index 6047992a74..51349e9c78 100644 --- a/apps/api/tests/setup/repo-hosting-ports.ts +++ b/apps/api/tests/setup/repo-hosting-ports.ts @@ -5,7 +5,7 @@ * have registered, so the ports delegate to whatever worker modules the test mocked (most often * `services/platform-config` and `auth`), as when repo hosting imported them directly. Each port * loads on its own, so a test whose partial mocks break one port's module graph still gets the - * other, and fails only if it reaches the port it broke. + * others, and fails only if it reaches the port it broke. */ import { beforeAll } from 'vitest'; @@ -23,5 +23,8 @@ beforeAll(async () => { import('../../src/repo-hosting-ports/auth') .then((m) => configureRepoHostingPort('auth', m.authPort)) .catch(() => undefined), + import('../../src/repo-hosting-ports/artifacts') + .then((m) => configureRepoHostingPort('artifacts', m.artifactsPort)) + .catch(() => undefined), ]); }, PORT_SETUP_TIMEOUT_MS); diff --git a/apps/api/tests/unit/durable-objects/task-runner-workspace-branch-dispatch.test.ts b/apps/api/tests/unit/durable-objects/task-runner-workspace-branch-dispatch.test.ts index 8e8ab61d34..df10cee616 100644 --- a/apps/api/tests/unit/durable-objects/task-runner-workspace-branch-dispatch.test.ts +++ b/apps/api/tests/unit/durable-objects/task-runner-workspace-branch-dispatch.test.ts @@ -54,11 +54,18 @@ function makeState(branch: string, outputBranch: string): TaskRunnerState { } as TaskRunnerState; } -function makeContext(): TaskRunnerContext { +function makeContext(projectRow?: { repoProvider: string; repository: string }): TaskRunnerContext { const prepare = vi.fn((query: string) => ({ bind: vi.fn(() => ({ first: vi.fn(async () => { if (query.includes('SELECT dispatched_at')) return { dispatched_at: null }; + if (query.includes('FROM projects') && projectRow) { + // Return only the columns the statement actually selects. + return { + repoProvider: projectRow.repoProvider, + ...(/\brepository\b/.test(query) ? { repository: projectRow.repository } : {}), + }; + } if (query.includes('FROM projects')) return { repoProvider: 'github', installationId: 'installation-1' }; return null; @@ -94,6 +101,19 @@ describe('TaskRunner workspace branch dispatch', () => { }); }); + it('passes the Artifacts clone URL from its existing project read to the git-source resolver', async () => { + const remote = 'https://api.sam.example/git/demo-01abc.git'; + await handleWorkspaceDispatch( + makeState('sam/out-1', 'sam/out-1'), + makeContext({ repoProvider: 'artifacts', repository: remote }) + ); + expect(mocks.resolveWorkspaceGitSource).toHaveBeenCalledWith(expect.anything(), { + id: 'project-1', + repoProvider: 'artifacts', + repository: remote, + }); + }); + it.each([ { scenario: 'generated output branch', diff --git a/apps/api/tests/unit/routes/artifacts-config.test.ts b/apps/api/tests/unit/routes/artifacts-config.test.ts index 8c105d46ba..0774ed955f 100644 --- a/apps/api/tests/unit/routes/artifacts-config.test.ts +++ b/apps/api/tests/unit/routes/artifacts-config.test.ts @@ -8,16 +8,20 @@ * See: docs/notes/2026-04-25-artifacts-broken-merge-postmortem.md */ import { Hono } from 'hono'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { + isArtifactsAvailable, + registerArtifactsBackendFallback, +} from '../../../src/services/hosted-git/backend'; describe('/api/config/artifacts-enabled', () => { function createApp(env: Record) { const app = new Hono<{ Bindings: Record }>(); - // Replicate the exact logic from src/index.ts + // src/index.ts answers with exactly this call. app.get('/api/config/artifacts-enabled', (c) => { - return c.json({ - enabled: c.env.ARTIFACTS_ENABLED === 'true' && !!c.env.ARTIFACTS, - }); + return c.json({ enabled: isArtifactsAvailable(c.env as unknown as Env) }); }); return { app, env }; } @@ -86,4 +90,26 @@ describe('/api/config/artifacts-enabled', () => { const body = await res.json(); expect(body.enabled).toBe(false); }); + + describe('with a self-host fallback backend registered', () => { + afterEach(() => registerArtifactsBackendFallback(null)); + + it('returns enabled: true with the flag and no binding', async () => { + registerArtifactsBackendFallback(() => ({}) as never); + const { app } = createApp({}); + const res = await app.request( + '/api/config/artifacts-enabled', + {}, + { ARTIFACTS_ENABLED: 'true' } + ); + expect((await res.json()).enabled).toBe(true); + }); + + it('still returns enabled: false without the flag', async () => { + registerArtifactsBackendFallback(() => ({}) as never); + const { app } = createApp({}); + const res = await app.request('/api/config/artifacts-enabled', {}, {}); + expect((await res.json()).enabled).toBe(false); + }); + }); }); diff --git a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts new file mode 100644 index 0000000000..7678a7da16 --- /dev/null +++ b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts @@ -0,0 +1,190 @@ +import { drizzle } from 'drizzle-orm/d1'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { projectsRoutes } from '../../../src/routes/projects'; +import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; + +/** + * The Artifacts branch of `POST /api/projects` resolves its backend through + * `resolveArtifactsBackend` (self-host landing slice L16): the Cloudflare binding on Cloudflare, or + * the backend a self-host build registered. Real Hono route; D1 and README seeding mocked. + */ + +const mocks = vi.hoisted(() => ({ + createOwnerProjectMembership: vi.fn(), + requireProjectAccess: vi.fn(), + requireProjectCapability: vi.fn(), + seedArtifactsReadme: vi.fn(), +})); + +vi.mock('drizzle-orm/d1'); +vi.mock('../../../src/middleware/auth', () => ({ + rejectAgentSignInSession: () => async (_c: unknown, next: () => Promise) => next(), + assertNotAgentSignInSession: () => undefined, + requireAuth: () => vi.fn((c: any, next: any) => next()), + requireApproved: () => vi.fn((c: any, next: any) => next()), + getUserId: () => 'user-1', +})); +vi.mock('../../../src/middleware/project-auth', () => ({ + createOwnerProjectMembership: mocks.createOwnerProjectMembership, + requireProjectAccess: mocks.requireProjectAccess, + requireProjectCapability: mocks.requireProjectCapability, +})); +vi.mock('../../../src/services/artifacts/seed-readme', () => ({ + seedArtifactsReadme: mocks.seedArtifactsReadme, +})); + +function backend(remote: string) { + return { + create: vi.fn().mockResolvedValue({ + id: 'r1', + name: 'hosted-project-r1', + remote, + token: 'write-token', + default_branch: 'main', + }), + delete: vi.fn().mockResolvedValue(true), + get: vi.fn(), + }; +} + +describe('POST /api/projects — Artifacts provider through the hosted-git seam', () => { + let app: Hono<{ Bindings: Env }>; + let whereResponses: unknown[][]; + let limitResponses: unknown[][]; + let insertedRows: unknown[]; + let deletedProjectIds: unknown[]; + const mockEnv = { DATABASE: {} as D1Database } as Env; + + const createArtifactsProject = ( + env: Env, + body: Record = { name: 'Hosted Project', repoProvider: 'artifacts' } + ) => + app.request( + '/api/projects', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }, + env + ); + + beforeEach(() => { + vi.clearAllMocks(); + whereResponses = []; + limitResponses = []; + insertedRows = []; + deletedProjectIds = []; + + const makeSelectBuilder = () => { + const fromBuilder = { + where: vi.fn(() => + Object.assign(Promise.resolve(whereResponses.shift() ?? []), { + limit: vi.fn(() => Promise.resolve(limitResponses.shift() ?? [])), + }) + ), + }; + return { from: vi.fn(() => fromBuilder) }; + }; + + const mockDB = { + select: vi.fn(() => makeSelectBuilder()), + insert: vi.fn(() => ({ + values: vi.fn((row: unknown) => { + insertedRows.push(row); + return Promise.resolve(undefined); + }), + })), + delete: vi.fn(() => ({ + where: vi.fn((predicate: unknown) => { + deletedProjectIds.push(predicate); + return Promise.resolve(undefined); + }), + })), + }; + (drizzle as unknown as ReturnType).mockReturnValue(mockDB); + + mocks.seedArtifactsReadme.mockResolvedValue(undefined); + mocks.createOwnerProjectMembership.mockResolvedValue(undefined); + + app = new Hono<{ Bindings: Env }>(); + app.onError((err, c) => { + const appError = err as { statusCode?: number; error?: string; message?: string }; + if (typeof appError.statusCode === 'number' && typeof appError.error === 'string') { + return c.json({ error: appError.error, message: appError.message }, appError.statusCode); + } + return c.json({ error: 'INTERNAL_ERROR', message: err.message }, 500); + }); + app.route('/api/projects', projectsRoutes); + }); + + afterEach(() => registerArtifactsBackendFallback(null)); + + it('creates the repository with the Cloudflare binding (unchanged), never the fallback', async () => { + const remote = 'https://acct.artifacts.cloudflare.net/git/default/hosted-project-r1.git'; + const binding = backend(remote); + const fallback = vi.fn(); + registerArtifactsBackendFallback(fallback); + limitResponses.push([], [{ id: 'x', repository: remote }]); + + const res = await createArtifactsProject({ + ...mockEnv, + ARTIFACTS_ENABLED: 'true', + ARTIFACTS: binding, + } as Env); + + expect(res.status).toBe(201); + expect(binding.create).toHaveBeenCalledTimes(1); + expect(fallback).not.toHaveBeenCalled(); + expect(insertedRows[0]).toMatchObject({ repoProvider: 'artifacts', repository: remote }); + }); + + it('creates the repository with a registered self-host backend when no binding exists', async () => { + const remote = 'https://api.sam.example/git/hosted-project-r1.git'; + const hosted = backend(remote); + registerArtifactsBackendFallback(() => hosted as never); + limitResponses.push([], [{ id: 'x', repository: remote }]); + + const res = await createArtifactsProject({ ...mockEnv, ARTIFACTS_ENABLED: 'true' } as Env); + + expect(res.status).toBe(201); + expect(hosted.create).toHaveBeenCalledTimes(1); + expect(mocks.seedArtifactsReadme).toHaveBeenCalledWith( + expect.objectContaining({ remote, token: 'write-token' }) + ); + expect(insertedRows[0]).toMatchObject({ + repoProvider: 'artifacts', + repository: remote, + artifactsRepoId: 'hosted-project-r1', + }); + }); + + it('deletes the new repository through the same backend when seeding fails', async () => { + const hosted = backend('https://api.sam.example/git/hosted-project-r1.git'); + registerArtifactsBackendFallback(() => hosted as never); + mocks.seedArtifactsReadme.mockRejectedValueOnce(new Error('push failed')); + + const res = await createArtifactsProject({ ...mockEnv, ARTIFACTS_ENABLED: 'true' } as Env); + + expect(res.status).toBe(500); + expect(hosted.delete).toHaveBeenCalledWith('hosted-project-r1'); + expect(insertedRows).toHaveLength(0); + }); + + it('fails as before when Artifacts is enabled but no backend exists', async () => { + const res = await createArtifactsProject({ ...mockEnv, ARTIFACTS_ENABLED: 'true' } as Env); + expect(res.status).toBe(500); + expect(insertedRows).toHaveLength(0); + }); + + it('refuses when the flag is off, even with a registered backend', async () => { + const hosted = backend('https://api.sam.example/git/x.git'); + registerArtifactsBackendFallback(() => hosted as never); + const res = await createArtifactsProject(mockEnv); + expect(res.status).toBe(400); + expect(hosted.create).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/tests/unit/routes/project-delete.test.ts b/apps/api/tests/unit/routes/project-delete.test.ts index 44ef3f9dd7..df65042e83 100644 --- a/apps/api/tests/unit/routes/project-delete.test.ts +++ b/apps/api/tests/unit/routes/project-delete.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; import { projectsRoutes } from '../../../src/routes/projects'; +import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; const mocks = vi.hoisted(() => ({ requireProjectCapability: vi.fn(), @@ -58,7 +59,10 @@ describe('DELETE /api/projects/:id', () => { }); // When awaited directly (without .limit()), resolve to data selectChain.then = (resolve: any, reject: any) => { - return Promise.resolve(reservationQuery ? [] : (selectResults.shift() ?? [])).then(resolve, reject); + return Promise.resolve(reservationQuery ? [] : (selectResults.shift() ?? [])).then( + resolve, + reject + ); }; return selectChain; }), @@ -346,6 +350,38 @@ describe('DELETE /api/projects/:id', () => { expect(consoleWarnSpy).not.toHaveBeenCalled(); }); + it('deletes the repository through a registered self-host backend when no binding exists', async () => { + const hostedDelete = vi.fn().mockResolvedValue(true); + registerArtifactsBackendFallback( + () => ({ delete: hostedDelete, create: vi.fn(), get: vi.fn() }) as never + ); + try { + mocks.requireProjectCapability.mockResolvedValueOnce({ + id: 'proj-1', + userId: 'user-1', + name: 'Hosted Project', + installationId: 'system_anonymous_trials_installation', + repository: 'https://api.sam.example/git/artifacts-repo-1.git', + defaultBranch: 'main', + repoProvider: 'artifacts', + artifactsRepoId: 'artifacts-repo-1', + }); + selectResults.push([]); + + const response = await app.request( + '/api/projects/proj-1', + { method: 'DELETE' }, + { ...env, ARTIFACTS_ENABLED: 'true' } + ); + + expect(response.status).toBe(200); + expect(hostedDelete).toHaveBeenCalledWith('artifacts-repo-1'); + expect(consoleWarnSpy).not.toHaveBeenCalled(); + } finally { + registerArtifactsBackendFallback(null); + } + }); + it('logs an orphan and still deletes the project when the Artifacts binding is unavailable', async () => { mocks.requireProjectCapability.mockResolvedValueOnce({ id: 'proj-1', diff --git a/apps/api/tests/unit/routes/workspace-git-token.test.ts b/apps/api/tests/unit/routes/workspace-git-token.test.ts index 0fff29b205..f571997741 100644 --- a/apps/api/tests/unit/routes/workspace-git-token.test.ts +++ b/apps/api/tests/unit/routes/workspace-git-token.test.ts @@ -6,6 +6,7 @@ import type { Env } from '../../../src/env'; import { runtimeRoutes } from '../../../src/routes/workspaces/runtime'; import { getInstallationToken } from '../../../src/services/github-app'; import { GitHubCliPolicyError } from '../../../src/services/github-cli-policy'; +import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; const mocks = vi.hoisted(() => ({ getInstallationToken: vi.fn(), @@ -471,6 +472,45 @@ describe('workspace git-token GitHub scoping', () => { expect(getInstallationToken).not.toHaveBeenCalled(); }); + it('mints through a registered self-host backend when no Artifacts binding exists', async () => { + const remote = 'https://api.sam.example/git/artifacts-repo-1.git'; + const createToken = vi.fn().mockResolvedValue({ + plaintext: 'hosted-token', + expiresAt: '2026-06-06T20:00:00.000Z', + }); + const get = vi.fn().mockResolvedValue({ remote, createToken }); + registerArtifactsBackendFallback(() => ({ get, create: vi.fn(), delete: vi.fn() }) as never); + try { + const hostedEnv = { ...mockEnv, ARTIFACTS_ENABLED: 'true' } as Env; + limitResponses.push([workspaceRow()], [artifactsProjectRow({ repository: remote })]); + + const res = await app.request('/ws/ws-1/git-token', { method: 'POST' }, hostedEnv); + + expect(res.status).toBe(200); + expect(get).toHaveBeenCalledWith('artifacts-repo-1'); + await expect(res.json()).resolves.toEqual({ + token: 'hosted-token', + expiresAt: '2026-06-06T20:00:00.000Z', + cloneUrl: remote, + }); + } finally { + registerArtifactsBackendFallback(null); + } + }); + + it('refuses an Artifacts token when the flag is off, even with a registered backend', async () => { + const get = vi.fn(); + registerArtifactsBackendFallback(() => ({ get, create: vi.fn(), delete: vi.fn() }) as never); + try { + limitResponses.push([workspaceRow()], [artifactsProjectRow()]); + const res = await app.request('/ws/ws-1/git-token', { method: 'POST' }, mockEnv); + expect(res.status).toBe(403); + expect(get).not.toHaveBeenCalled(); + } finally { + registerArtifactsBackendFallback(null); + } + }); + it('does not return an artifacts token when deletion wins after minting', async () => { const createToken = vi.fn().mockResolvedValue({ plaintext: 'must-not-be-returned?expires=ignored', diff --git a/apps/api/tests/unit/services/hosted-git-backend.test.ts b/apps/api/tests/unit/services/hosted-git-backend.test.ts new file mode 100644 index 0000000000..134c3bc9a0 --- /dev/null +++ b/apps/api/tests/unit/services/hosted-git-backend.test.ts @@ -0,0 +1,114 @@ +/** + * The hosted-git seam (self-host landing slice L16). + * + * `resolveArtifactsBackend` is the one answer to "which Artifacts backend does this install use?". + * On Cloudflare it is the binding or nothing; a self-host build may register a fallback that is + * used only when Artifacts is enabled and no binding exists. Every caller (capability flag, + * project creation and deletion, git tokens, repository browsing) goes through it. + */ +import { repoHostingPorts } from '@simple-agent-manager/repo-hosting/ports'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { + type ArtifactsBackend, + isArtifactsAvailable, + registerArtifactsBackendFallback, + resolveArtifactsBackend, +} from '../../../src/services/hosted-git/backend'; + +function backend(label: string): ArtifactsBackend { + return { + create: vi.fn(), + delete: vi.fn(), + get: vi.fn(), + label, + } as unknown as ArtifactsBackend; +} + +function env(fields: Partial): Env { + return { ...fields } as Env; +} + +afterEach(() => { + registerArtifactsBackendFallback(null); +}); + +describe('resolveArtifactsBackend', () => { + it('returns the Cloudflare binding when Artifacts is enabled (unchanged Cloudflare path)', () => { + const binding = backend('cloudflare'); + expect(resolveArtifactsBackend(env({ ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding }))).toBe( + binding + ); + }); + + it('returns null when Artifacts is enabled but no binding and no fallback exist', () => { + expect(resolveArtifactsBackend(env({ ARTIFACTS_ENABLED: 'true' }))).toBeNull(); + }); + + it('returns null whenever ARTIFACTS_ENABLED is not "true", binding or fallback notwithstanding', () => { + const fallback = vi.fn(() => backend('selfhost')); + registerArtifactsBackendFallback(fallback); + for (const enabled of [undefined, '', 'false', 'TRUE', '1']) { + expect( + resolveArtifactsBackend(env({ ARTIFACTS_ENABLED: enabled, ARTIFACTS: backend('cf') })) + ).toBeNull(); + expect(resolveArtifactsBackend(env({ ARTIFACTS_ENABLED: enabled }))).toBeNull(); + } + expect(fallback).not.toHaveBeenCalled(); + }); + + it('uses a registered fallback only when the binding is absent, and passes it the env', () => { + const selfhost = backend('selfhost'); + const fallback = vi.fn(() => selfhost); + registerArtifactsBackendFallback(fallback); + const e = env({ ARTIFACTS_ENABLED: 'true', BASE_DOMAIN: 'sam.example' }); + expect(resolveArtifactsBackend(e)).toBe(selfhost); + expect(fallback).toHaveBeenCalledWith(e); + }); + + it('prefers the Cloudflare binding over a registered fallback', () => { + const binding = backend('cloudflare'); + const fallback = vi.fn(() => backend('selfhost')); + registerArtifactsBackendFallback(fallback); + expect(resolveArtifactsBackend(env({ ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding }))).toBe( + binding + ); + expect(fallback).not.toHaveBeenCalled(); + }); + + it('treats a fallback that declines (not configured on this install) as no backend', () => { + registerArtifactsBackendFallback(() => null); + expect(resolveArtifactsBackend(env({ ARTIFACTS_ENABLED: 'true' }))).toBeNull(); + expect(isArtifactsAvailable(env({ ARTIFACTS_ENABLED: 'true' }))).toBe(false); + }); +}); + +describe('isArtifactsAvailable (the /api/config/artifacts-enabled answer)', () => { + it('is true for flag + binding, false for flag alone, false for binding alone', () => { + expect(isArtifactsAvailable(env({ ARTIFACTS_ENABLED: 'true', ARTIFACTS: backend('cf') }))).toBe( + true + ); + expect(isArtifactsAvailable(env({ ARTIFACTS_ENABLED: 'true' }))).toBe(false); + expect(isArtifactsAvailable(env({ ARTIFACTS: backend('cf') }))).toBe(false); + }); + + it('is true when a self-host fallback serves repositories', () => { + registerArtifactsBackendFallback(() => backend('selfhost')); + expect(isArtifactsAvailable(env({ ARTIFACTS_ENABLED: 'true' }))).toBe(true); + }); +}); + +describe('repo-hosting artifacts port (installed by the worker test setup)', () => { + it('resolves through the same seam: binding, fallback, or nothing', () => { + const port = repoHostingPorts().artifacts; + const binding = backend('cloudflare'); + expect(port.resolve({ ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding } as never)).toBe(binding); + expect(port.resolve({ ARTIFACTS_ENABLED: 'true' } as never)).toBeNull(); + + const selfhost = backend('selfhost'); + registerArtifactsBackendFallback(() => selfhost); + expect(port.resolve({ ARTIFACTS_ENABLED: 'true' } as never)).toBe(selfhost); + expect(port.resolve({ ARTIFACTS_ENABLED: 'false' } as never)).toBeNull(); + }); +}); diff --git a/apps/api/tests/unit/services/workspace-git-source-artifacts.test.ts b/apps/api/tests/unit/services/workspace-git-source-artifacts.test.ts new file mode 100644 index 0000000000..b32026f26c --- /dev/null +++ b/apps/api/tests/unit/services/workspace-git-source-artifacts.test.ts @@ -0,0 +1,143 @@ +/** + * C15 (self-host landing slice L16): an Artifacts project whose remote is not a Cloudflare Artifacts + * host (a self-hosted install's own git server) gets cloneUrl + repositoryHost, so the VM agent + * attaches the workspace's git token to exactly that host. Cloudflare Artifacts remotes, which every + * production Artifacts project uses, are unchanged. + * + * Driven through `resolveWorkspaceGitSourceByProjectId` against a real SQL engine, so the test also + * proves the clone URL comes from the project row the caller already reads (no extra query). + */ +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/d1'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import { + resolveWorkspaceGitSource, + resolveWorkspaceGitSourceByProjectId, +} from '../../../src/services/workspace-git-source'; +import { createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +let sqlite: Database.Database; +let db: ReturnType>; +let queries: string[]; + +function seedProject(id: string, repoProvider: string, repository: string): void { + sqlite + .prepare('INSERT INTO projects (id, repo_provider, repository) VALUES (?, ?, ?)') + .run(id, repoProvider, repository); +} + +beforeEach(() => { + sqlite = new Database(':memory:'); + createSchemaTables(sqlite, [schema.projects]); + const d1 = createSqliteD1(sqlite); + queries = []; + const counting = { + ...d1, + prepare(sql: string) { + queries.push(sql); + return d1.prepare(sql); + }, + } as D1Database; + db = drizzle(counting, { schema }); +}); + +afterEach(() => { + sqlite.close(); +}); + +describe('resolveWorkspaceGitSource for Artifacts projects', () => { + it('leaves a Cloudflare Artifacts remote unchanged (no cloneUrl, no repositoryHost)', async () => { + seedProject('p-cf', 'artifacts', 'https://acct123.artifacts.cloudflare.net/git/default/r.git'); + await expect(resolveWorkspaceGitSourceByProjectId(db, 'p-cf')).resolves.toEqual({ + repoProvider: 'artifacts', + cloneUrl: null, + repositoryHost: null, + repositoryPath: null, + }); + }); + + it('binds a self-hosted git server remote as cloneUrl + repositoryHost', async () => { + const remote = 'https://api.sam.example/git/demo-01abc.git'; + seedProject('p-hosted', 'artifacts', remote); + await expect(resolveWorkspaceGitSourceByProjectId(db, 'p-hosted')).resolves.toEqual({ + repoProvider: 'artifacts', + cloneUrl: remote, + repositoryHost: 'api.sam.example', + repositoryPath: null, + }); + // One read: the project row the resolver already selected. C15 adds no query. + expect(queries).toHaveLength(1); + }); + + it('keeps a non-default port in the bound host (the VM agent compares url.Host)', async () => { + seedProject('p-port', 'artifacts', 'https://API.sam.example:8443/git/demo.git'); + const source = await resolveWorkspaceGitSourceByProjectId(db, 'p-port'); + expect(source.repositoryHost).toBe('api.sam.example:8443'); + }); + + it('binds nothing for a malformed or non-https remote', async () => { + seedProject('p-bad', 'artifacts', 'not a url'); + seedProject('p-http', 'artifacts', 'http://api.sam.example/git/demo.git'); + seedProject('p-empty', 'artifacts', ''); + for (const id of ['p-bad', 'p-http', 'p-empty']) { + const source = await resolveWorkspaceGitSourceByProjectId(db, id); + expect(source).toEqual({ + repoProvider: 'artifacts', + cloneUrl: null, + repositoryHost: null, + repositoryPath: null, + }); + } + }); + + it('does not treat a look-alike host as Cloudflare Artifacts', async () => { + const remote = 'https://artifacts.cloudflare.net.evil.test/git/r.git'; + seedProject('p-lookalike', 'artifacts', remote); + const source = await resolveWorkspaceGitSourceByProjectId(db, 'p-lookalike'); + expect(source.repositoryHost).toBe('artifacts.cloudflare.net.evil.test'); + }); + + it('leaves GitHub projects unchanged, whatever their repository looks like', async () => { + seedProject('p-gh', 'github', 'owner/repo'); + await expect(resolveWorkspaceGitSourceByProjectId(db, 'p-gh')).resolves.toEqual({ + repoProvider: 'github', + cloneUrl: null, + repositoryHost: null, + repositoryPath: null, + }); + // A GitHub project must never pick up an artifacts-style binding. + await expect( + resolveWorkspaceGitSource(db, { + id: 'p-gh2', + repoProvider: 'github', + repository: 'https://api.sam.example/git/x.git', + }) + ).resolves.toMatchObject({ repoProvider: 'github', cloneUrl: null, repositoryHost: null }); + }); + + it('resolves from the repository the caller passes, without reading D1', async () => { + const source = await resolveWorkspaceGitSource(db, { + id: 'not-in-db', + repoProvider: 'artifacts', + repository: 'https://api.sam.example/git/demo.git', + }); + expect(source.repositoryHost).toBe('api.sam.example'); + expect(queries).toHaveLength(0); + }); + + it('keeps Cloudflare behaviour for a NodeLifecycle request persisted before repository was passed', async () => { + // Direct-provisioning inputs are stored in the NodeLifecycle DO; one written by the previous + // deploy has { id, repoProvider } only. + const legacy = { id: 'p-legacy', repoProvider: 'artifacts' } as unknown as Parameters< + typeof resolveWorkspaceGitSource + >[1]; + await expect(resolveWorkspaceGitSource(db, legacy)).resolves.toEqual({ + repoProvider: 'artifacts', + cloneUrl: null, + repositoryHost: null, + repositoryPath: null, + }); + }); +}); diff --git a/packages/repo-hosting/src/ports.ts b/packages/repo-hosting/src/ports.ts index d44fa513e2..5cc25faf79 100644 --- a/packages/repo-hosting/src/ports.ts +++ b/packages/repo-hosting/src/ports.ts @@ -3,7 +3,7 @@ * implementation once at module load (`apps/api/src/repo-hosting-wiring.ts`, which the entry * imports). Methods take the narrow env; the worker widens it at that one boundary. */ -import type { Env } from './env'; +import type { ArtifactsBinding, Env } from './env'; import type { UserAccessTokenResult } from './user-access-token'; export interface GitHubAppConfig { @@ -43,9 +43,19 @@ export interface AuthPort { ): Promise<(UserAccessTokenResult & { tokenType?: string | null }) | null>; } +/** + * The SAM-native repository backend (`ARTIFACTS`). On Cloudflare it is the Artifacts binding; a + * self-hosted install may register its own (the worker's `services/hosted-git/backend.ts`). + */ +export interface ArtifactsBackendPort { + /** The backend this install uses for SAM-native repositories, or null when it has none. */ + resolve(env: Env): ArtifactsBinding | null; +} + export interface RepoHostingPorts { platformConfig: PlatformConfigPort; auth: AuthPort; + artifacts: ArtifactsBackendPort; } /** @@ -74,6 +84,9 @@ function createRegistry(installed: Partial): Registry { get auth() { return requirePort(installed, 'auth'); }, + get artifacts() { + return requirePort(installed, 'artifacts'); + }, }, }; } diff --git a/packages/repo-hosting/src/repo-browse/artifacts.ts b/packages/repo-hosting/src/repo-browse/artifacts.ts index 45161ea6f9..1fa437ea6b 100644 --- a/packages/repo-hosting/src/repo-browse/artifacts.ts +++ b/packages/repo-hosting/src/repo-browse/artifacts.ts @@ -12,6 +12,7 @@ import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; import type { Env } from '../env'; +import { repoHostingPorts } from '../ports'; import { MemoryFS } from './memory-fs'; import type { RepoBrowser } from './types'; import { basename, guessContentType, isBinaryBytes, maxCompareFiles, maxInlineBytes } from './util'; @@ -163,7 +164,8 @@ export class ArtifactsRepoBrowser implements RepoBrowser { private async info(): Promise { if (!this.infoPromise) { this.infoPromise = (async () => { - const binding = this.env.ARTIFACTS; + // The binding as before; otherwise the backend a self-host build registered. + const binding = this.env.ARTIFACTS ?? repoHostingPorts().artifacts.resolve(this.env); if (!binding) throw errors.badRequest('Artifacts is not enabled on this deployment'); const repo = await binding.get(this.repoId); const ttl = diff --git a/packages/repo-hosting/src/repo-browse/index.ts b/packages/repo-hosting/src/repo-browse/index.ts index 9d068d7626..6a0529275f 100644 --- a/packages/repo-hosting/src/repo-browse/index.ts +++ b/packages/repo-hosting/src/repo-browse/index.ts @@ -2,6 +2,7 @@ import { errors } from '@simple-agent-manager/worker-core'; import * as schema from '@simple-agent-manager/worker-core/schema'; import type { Env } from '../env'; +import { repoHostingPorts } from '../ports'; import { GitHubRepoBrowser } from './github'; import type { RepoBrowser } from './types'; @@ -38,7 +39,7 @@ export async function resolveRepoBrowser(opts: { } if (provider === 'artifacts') { - if (env.ARTIFACTS_ENABLED !== 'true' || !env.ARTIFACTS) { + if (!repoHostingPorts().artifacts.resolve(env)) { throw errors.badRequest('Artifacts is not enabled on this deployment'); } if (!project.artifactsRepoId) { diff --git a/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts b/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts new file mode 100644 index 0000000000..af51341062 --- /dev/null +++ b/packages/repo-hosting/tests/unit/repo-browse-artifacts-backend.test.ts @@ -0,0 +1,81 @@ +/** + * Repository browsing reaches the SAM-native repository backend through the worker's `artifacts` + * port (self-host landing slice L16), so a self-hosted install's registered backend serves browsing + * the same way the Cloudflare binding does. + */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { ArtifactsBinding, Env } from '../../src/env'; +import { configureRepoHostingPort } from '../../src/ports'; +import { resolveRepoBrowser } from '../../src/repo-browse'; +import { ArtifactsRepoBrowser } from '../../src/repo-browse/artifacts'; + +const iso = vi.hoisted(() => ({ listServerRefs: vi.fn() })); +vi.mock('isomorphic-git', () => ({ default: iso })); +vi.mock('isomorphic-git/http/web', () => ({ default: {} })); + +const resolve = vi.fn<(env: Env) => ArtifactsBinding | null>(); +configureRepoHostingPort('artifacts', { resolve }); + +function hostedBackend(): ArtifactsBinding { + return { + create: vi.fn(), + delete: vi.fn(), + get: vi.fn().mockResolvedValue({ + id: 'repo-1', + name: 'repo-1', + remote: 'https://api.sam.example/git/repo-1.git', + defaultBranch: 'main', + createToken: vi.fn().mockResolvedValue({ id: 't', plaintext: 'read-token', scope: 'read' }), + }), + }; +} + +const project = { + id: 'p1', + repoProvider: 'artifacts', + artifactsRepoId: 'repo-1', + defaultBranch: 'main', + repository: 'https://api.sam.example/git/repo-1.git', +} as never; + +beforeEach(() => { + vi.clearAllMocks(); + iso.listServerRefs.mockResolvedValue([{ ref: 'refs/heads/main' }]); +}); + +describe('resolveRepoBrowser for Artifacts projects', () => { + it('refuses when the port reports no backend', async () => { + resolve.mockReturnValue(null); + const env = { ARTIFACTS_ENABLED: 'true' } as Env; + await expect(resolveRepoBrowser({ project, env })).rejects.toThrow( + 'Artifacts is not enabled on this deployment' + ); + expect(resolve).toHaveBeenCalledWith(env); + }); + + it('browses through the backend the port resolves when no binding exists', async () => { + const backend = hostedBackend(); + resolve.mockReturnValue(backend); + const env = { ARTIFACTS_ENABLED: 'true' } as Env; + + const browser = await resolveRepoBrowser({ project, env }); + expect(browser).toBeInstanceOf(ArtifactsRepoBrowser); + const res = await browser.listBranches(); + + expect(backend.get).toHaveBeenCalledWith('repo-1'); + expect(res.branches.map((b) => b.name)).toEqual(['main']); + expect(iso.listServerRefs).toHaveBeenCalledWith( + expect.objectContaining({ url: 'https://api.sam.example/git/repo-1.git' }) + ); + }); + + it('uses the Cloudflare binding directly when present (unchanged)', async () => { + const binding = hostedBackend(); + resolve.mockImplementation((env) => env.ARTIFACTS ?? null); + const env = { ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding } as Env; + const browser = await resolveRepoBrowser({ project, env }); + await browser.listBranches(); + expect(binding.get).toHaveBeenCalledWith('repo-1'); + }); +}); diff --git a/packages/vm-agent/internal/bootstrap/bootstrap.go b/packages/vm-agent/internal/bootstrap/bootstrap.go index 2435595d1f..d0a68c38dd 100644 --- a/packages/vm-agent/internal/bootstrap/bootstrap.go +++ b/packages/vm-agent/internal/bootstrap/bootstrap.go @@ -3384,14 +3384,15 @@ func withGitToken(repoURL, token string, cfg *config.Config) (string, error) { isGitLabHost := cfg != nil && strings.EqualFold(strings.TrimSpace(cfg.RepoProvider), "gitlab") && strings.EqualFold(strings.TrimSpace(cfg.RepositoryHost), host) - if !gitrepo.IsKnownGitHost(host) && !isGitLabHost { + hostedArtifactsHost := isBoundHostedArtifactsHost(cfg, host) + if !gitrepo.IsKnownGitHost(host) && !isGitLabHost && !hostedArtifactsHost { return repoURL, nil } - // For GitHub repos use "x-access-token"; for Artifacts use "x"; for - // GitLab OAuth use the conventional "oauth2" username. + // For GitHub repos use "x-access-token"; for Artifacts (Cloudflare or a + // self-hosted SAM git server) use "x"; for GitLab OAuth use "oauth2". username := "x-access-token" - if gitrepo.IsArtifactsHost(host) { + if gitrepo.IsArtifactsHost(host) || hostedArtifactsHost { username = "x" } else if isGitLabHost { username = "oauth2" @@ -3431,6 +3432,9 @@ func needsCredentialHelperForConfig(cfg *config.Config) bool { if strings.TrimSpace(cfg.RepositoryHost) != "" && strings.EqualFold(strings.TrimSpace(cfg.RepoProvider), "gitlab") { return true } + if isBoundHostedArtifactsHost(cfg, cfg.RepositoryHost) { + return true + } return needsCredentialHelper(firstNonEmptyString(cfg.CloneURL, cfg.Repository)) } diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go new file mode 100644 index 0000000000..33ef1db1a5 --- /dev/null +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go @@ -0,0 +1,22 @@ +package bootstrap + +import ( + "strings" + + "github.com/workspace/vm-agent/internal/config" +) + +// isBoundHostedArtifactsHost reports whether host is the repository host the +// control plane bound to an artifacts-provider workspace. Cloudflare Artifacts +// hosts are recognized by name (gitrepo.IsArtifactsHost) and are never bound; +// a self-hosted SAM install serves its own repositories at api., which +// the control plane passes as RepositoryHost (resolveWorkspaceGitSource in +// apps/api/src/services/workspace-git-source.ts). Only that exact host receives +// the workspace's git token. +func isBoundHostedArtifactsHost(cfg *config.Config, host string) bool { + if cfg == nil || !strings.EqualFold(strings.TrimSpace(cfg.RepoProvider), "artifacts") { + return false + } + bound := strings.TrimSpace(cfg.RepositoryHost) + return bound != "" && strings.EqualFold(bound, strings.TrimSpace(host)) +} diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go new file mode 100644 index 0000000000..5ac6f37e84 --- /dev/null +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go @@ -0,0 +1,104 @@ +package bootstrap + +import ( + "testing" + + "github.com/workspace/vm-agent/internal/config" +) + +// A self-hosted SAM install serves artifacts-provider repositories from its own git +// server at api.; the control plane binds that host as RepositoryHost. +func TestWithGitTokenSelfHostedArtifactsHost(t *testing.T) { + t.Parallel() + + cfg := &config.Config{RepoProvider: "artifacts", RepositoryHost: "api.sam.example"} + got, err := withGitToken("https://api.sam.example/git/demo-01abc.git", "samgit1.tok", cfg) + if err != nil { + t.Fatalf("withGitToken: %v", err) + } + if got != "https://x:samgit1.tok@api.sam.example/git/demo-01abc.git" { + t.Fatalf("unexpected tokenized url: %s", got) + } + + // Control: a different host is never given the token. + other, err := withGitToken("https://evil.example/git/demo.git", "samgit1.tok", cfg) + if err != nil { + t.Fatalf("withGitToken other host: %v", err) + } + if other != "https://evil.example/git/demo.git" { + t.Fatalf("token leaked to unbound host: %s", other) + } + + // Control: the same host bound to a non-artifacts provider is not treated as hosted. + github := &config.Config{RepoProvider: "github", RepositoryHost: "api.sam.example"} + plain, err := withGitToken("https://api.sam.example/git/demo.git", "samgit1.tok", github) + if err != nil { + t.Fatalf("withGitToken github provider: %v", err) + } + if plain != "https://api.sam.example/git/demo.git" { + t.Fatalf("token attached for non-artifacts provider: %s", plain) + } +} + +func TestNeedsCredentialHelperSelfHostedArtifacts(t *testing.T) { + t.Parallel() + + hosted := &config.Config{ + RepoProvider: "artifacts", + RepositoryHost: "api.sam.example", + CloneURL: "https://api.sam.example/git/demo-01abc.git", + } + if !needsCredentialHelperForConfig(hosted) { + t.Fatal("expected credential helper for a bound self-hosted artifacts host") + } + unbound := &config.Config{RepoProvider: "artifacts", CloneURL: "https://api.sam.example/git/demo.git"} + if needsCredentialHelperForConfig(unbound) { + t.Fatal("unbound artifacts host must not enable the credential helper") + } +} + +// Cloudflare Artifacts is unchanged: recognized by name, no bound host needed, +// and a bound self-hosted host does not widen to other hosts. +func TestWithGitTokenCloudflareArtifactsUnchanged(t *testing.T) { + t.Parallel() + + cf := "https://acct.artifacts.cloudflare.net/git/repo.git" + for _, cfg := range []*config.Config{ + nil, + {RepoProvider: "artifacts"}, + {RepoProvider: "artifacts", RepositoryHost: "api.sam.example"}, + } { + got, err := withGitToken(cf, "cf.tok", cfg) + if err != nil { + t.Fatalf("withGitToken: %v", err) + } + if got != "https://x:cf.tok@acct.artifacts.cloudflare.net/git/repo.git" { + t.Fatalf("cloudflare artifacts url changed (cfg=%+v): %s", cfg, got) + } + } + if !needsCredentialHelperForConfig(&config.Config{RepoProvider: "artifacts", Repository: cf}) { + t.Fatal("cloudflare artifacts must keep the credential helper") + } +} + +// The bound host matches exactly: a different port or a look-alike subdomain is +// a different host and never receives the token. +func TestWithGitTokenBoundHostIsExact(t *testing.T) { + t.Parallel() + + cfg := &config.Config{RepoProvider: "artifacts", RepositoryHost: "api.sam.example"} + for _, u := range []string{ + "https://api.sam.example:8443/git/demo.git", + "https://api.sam.example.evil.test/git/demo.git", + "https://evil.api.sam.example/git/demo.git", + "http://api.sam.example/git/demo.git", + } { + got, err := withGitToken(u, "samgit1.tok", cfg) + if err != nil { + t.Fatalf("withGitToken(%s): %v", u, err) + } + if got != u { + t.Fatalf("token attached to unbound url %s: %s", u, got) + } + } +} diff --git a/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md b/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md new file mode 100644 index 0000000000..a5b9f8898b --- /dev/null +++ b/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md @@ -0,0 +1,55 @@ +# Self-host landing slice L16: hosted-git seam (no Durable Object) + +SAM task `01M7M9F7A5T7MKX15KV5EYT0T8`; plan idea `01M72M9AEB933ZY8269D376DKC` (LANDING PLAN part 2 row C15, +part 6 row L16, part 7 decision D7); coordinator task `01M7JMXS2JRW6QQMB1356ENPM3`; channel `feature.selfhost-landing`. + +## Problem + +`sam/selfhost-pass-2` serves SAM-native repositories on self-hosted installs from its own git server +(`HostedGitRepo` Durable Object + vendored dgit). Decision D7: do NOT ship that server to production yet; +land only the seam. Raphaël's Nov 14 two-build rule: self-host-only code lives in the self-host build +(`apps/api/src/selfhost/`), never imported by `apps/api/src/index.ts`. On main, Cloudflare Artifacts must keep +working exactly as today. + +## Research findings + +- Every `env.ARTIFACTS` caller on main: `index.ts` (`/api/config/artifacts-enabled`), `routes/projects/project-create.ts` + (create, seed-cleanup delete), `routes/projects/crud.ts` (delete on project delete), `routes/workspaces/runtime-git-token.ts` + (token mint), `packages/repo-hosting/src/repo-browse/index.ts` + `artifacts.ts` (browse). Each checks enabled/binding + slightly differently. +- Integration `services/hosted-git/backend.ts` mixes the seam (`resolveArtifactsBackend`) with the DO backend + (`createDurableObjectArtifactsBackend`, tokens, http handler, in-process fetch). Only the seam lands; the DO + backend registers itself from the self-host build. +- C15 (`workspace-git-source.ts`): integration adds a D1 read when `repository` is not passed. Every caller already + holds the project row or can add the column to a select it already makes, so the read is unnecessary: + instant-restore (`row.repository`), instant-session (`input.project`), `_helpers.scheduleWorkspaceCreateOnNode` + (`linkedProject` row), TaskRunner `loadTaskRunnerProjectRepo` (add column), `resolveWorkspaceGitSourceByProjectId` + (add column). I/O added per request: 0. +- Production (read-only, sam-prod D1, 2026-11-17): 47 projects, 10 `repo_provider='artifacts'`, 10/10 remotes + `https://.artifacts.cloudflare.net/...`, 0 empty. C15's new branch never fires on Cloudflare. +- VM agent: `withGitToken` attaches the token only to known hosts; a self-hosted remote `api.` needs the + bound `RepositoryHost` for `repoProvider=artifacts`. Server-side credential helper already honours + `RepositoryHost` (`git_credential.go:isAllowedCredentialHostForWorkspace`). Rollout: new agent + old control plane + never gets RepositoryHost for artifacts; old agent + new control plane on Cloudflare: C15 never sets it. Compatible. +- `bootstrap.go` is a grandfathered >800-line file: put the new helper in its own file. + +## Checklist + +- [ ] `apps/api/src/services/hosted-git/backend.ts`: `resolveArtifactsBackend`, `isArtifactsAvailable`, self-host + registration hook (`registerArtifactsBackendFallback`) +- [ ] Route all `env.ARTIFACTS` callers through it (index, project-create, crud delete, runtime-git-token) +- [ ] repo-hosting `artifacts` port (`resolve`) + wiring; repo-browse uses it +- [ ] C15 in `workspace-git-source.ts`, `repository` required on the source type, callers pass it (no new D1 reads) +- [ ] vm-agent `isBoundHostedArtifactsHost` in its own file; `withGitToken` + `needsCredentialHelperForConfig` use it +- [ ] Tests: backend resolution (enabled/disabled/binding/fallback/binding-wins), C15 (CF host, hosted host, malformed, + github unchanged) through real callers, Go withGitToken + credential helper with controls, repo-browse port +- [ ] Docs sync + +## Acceptance criteria + +- Cloudflare Artifacts create / clone / push / browse / delete unchanged (staging). +- GitHub project clone unchanged (staging). +- A registered fallback backend is used only when Artifacts is enabled and no binding exists (unit). +- An Artifacts project whose remote is not `*.artifacts.cloudflare.net` gets cloneUrl + repositoryHost; the VM agent + attaches the token only to that bound host (unit, Go). +- No D1 read added to any workspace-creation path. From caef0e15e87baf9953b298969165c6d3e4024be9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 10:45:03 +0000 Subject: [PATCH 02/11] fix(hosted-git): address L16 review findings - Mount /api/config/artifacts-enabled from routes/artifacts-config.ts and test the real route - Return username x from the git-token route for a bound self-hosted Artifacts host - Explicit guard for NodeLifecycle payloads persisted without repository - More vm-agent bound-host cases (case, port, empty host, provider) Co-Authored-By: Claude Opus 5.5 --- apps/api/src/index.ts | 7 +- apps/api/src/routes/artifacts-config.ts | 17 +++ .../routes/workspaces/runtime-git-token.ts | 5 + apps/api/src/services/workspace-git-source.ts | 32 +++-- .../unit/routes/artifacts-config.test.ts | 129 ++++++------------ .../unit/routes/workspace-git-token.test.ts | 2 + .../bootstrap/hosted_artifacts_host_test.go | 45 ++++++ ...2026-11-17-selfhost-l16-hosted-git-seam.md | 30 +++- 8 files changed, 158 insertions(+), 109 deletions(-) create mode 100644 apps/api/src/routes/artifacts-config.ts diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 5eaea7bc6b..5ad2fec527 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -81,6 +81,7 @@ import { aiProxyAnthropicRoutes } from './routes/ai-proxy-anthropic'; import { aiProxyPassthroughRoutes } from './routes/ai-proxy-passthrough'; import { analyticsIngestRoutes } from './routes/analytics-ingest'; import { apiTokenRoutes } from './routes/api-tokens'; +import { artifactsConfigRoutes } from './routes/artifacts-config'; import { authRoutes } from './routes/auth'; import { bootstrapRoutes } from './routes/bootstrap'; import { cachedCommandRoutes } from './routes/cached-commands'; @@ -186,7 +187,6 @@ import { scheduled } from './scheduled/handler'; import { handleInboundAgentEmail } from './services/agent-email/inbound'; import { agentEmailConfig } from './services/agent-email/setup-state'; import { isAgentSignInEnabled } from './services/agent-sign-in/config'; -import { isArtifactsAvailable } from './services/hosted-git/backend'; import { isInstantRuntimeAvailable } from './services/vm-agent-container'; const app = new Hono<{ Bindings: Env }>(); @@ -273,10 +273,7 @@ app.get('/health', (c) => { }); // Public config — exposes feature flags the UI needs before auth -app.get('/api/config/artifacts-enabled', (c) => { - applyCacheHeaders(c, 'public-config'); - return c.json({ enabled: isArtifactsAvailable(c.env) }); -}); +app.route('/api/config', artifactsConfigRoutes); app.route('/api/config', platformCapabilitiesRoutes); diff --git a/apps/api/src/routes/artifacts-config.ts b/apps/api/src/routes/artifacts-config.ts new file mode 100644 index 0000000000..8674a45f8b --- /dev/null +++ b/apps/api/src/routes/artifacts-config.ts @@ -0,0 +1,17 @@ +import { Hono } from 'hono'; + +import type { Env } from '../env'; +import { applyCacheHeaders } from '../lib/cache-headers'; +import { isArtifactsAvailable } from '../services/hosted-git/backend'; + +/** + * Public config: whether this install can create SAM-native (Artifacts) repositories. True only + * when ARTIFACTS_ENABLED is set and a backend exists (the Cloudflare binding, or the backend a + * self-host build registered), so the UI never offers a provider that would fail on use. + */ +export const artifactsConfigRoutes = new Hono<{ Bindings: Env }>(); + +artifactsConfigRoutes.get('/artifacts-enabled', (c) => { + applyCacheHeaders(c, 'public-config'); + return c.json({ enabled: isArtifactsAvailable(c.env) }); +}); diff --git a/apps/api/src/routes/workspaces/runtime-git-token.ts b/apps/api/src/routes/workspaces/runtime-git-token.ts index 42dcfd867b..f8ee409d8f 100644 --- a/apps/api/src/routes/workspaces/runtime-git-token.ts +++ b/apps/api/src/routes/workspaces/runtime-git-token.ts @@ -20,6 +20,7 @@ import { verifyGitLabProjectAccess, } from '../../services/gitlab'; import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; +import { boundArtifactsRepositoryHost } from '../../services/workspace-git-source'; import { assertRepositoryAccess } from '../projects/_helpers'; import { assertWorkspaceAcceptsCallback, @@ -271,6 +272,10 @@ runtimeRoutes.post('/:id/git-token', async (c) => { token: tokenSecret, expiresAt: tokenResult.expiresAt ?? tokenResult.expires_at, cloneUrl, + // The VM agent's credential helper answers with username "x" only for Cloudflare Artifacts + // hosts it knows by name. For a bound self-hosted host, name it here so a refresh presents + // the same username the clone used. Cloudflare responses are unchanged. + ...(boundArtifactsRepositoryHost(cloneUrl) ? { username: 'x' } : {}), }); } diff --git a/apps/api/src/services/workspace-git-source.ts b/apps/api/src/services/workspace-git-source.ts index 23d2623dfa..2845ec40bc 100644 --- a/apps/api/src/services/workspace-git-source.ts +++ b/apps/api/src/services/workspace-git-source.ts @@ -49,22 +49,36 @@ function isCloudflareArtifactsHost(host: string): boolean { * Cloudflare Artifacts remote nothing is added: the VM agent knows that host by name. A remote on * any other host (a self-hosted install's own git server) is bound as `repositoryHost`, the only * host the VM agent then attaches the workspace's git token to (`isBoundHostedArtifactsHost`). + * + * This trusts `repository` because SAM assigns it: `project-create.ts` stores the backend's remote + * and no route lets a user edit it for an Artifacts project. A route that ever does must validate + * the host, or it lets a user send a workspace token to any https host. */ -function resolveArtifactsGitSource(repository: string): WorkspaceGitSource { - const artifactsSource: WorkspaceGitSource = { - ...DEFAULT_GITHUB_SOURCE, - repoProvider: 'artifacts', - }; +/** + * The host the VM agent must be bound to for an Artifacts remote, or null when none is needed: a + * Cloudflare Artifacts host (the VM agent knows those by name), a non-https or unparseable remote, + * or a direct-provisioning request persisted by NodeLifecycle before `repository` was passed. + */ +export function boundArtifactsRepositoryHost(repository: string | undefined): string | null { + if (typeof repository !== 'string') return null; let url: URL; try { - // A direct-provisioning request persisted by NodeLifecycle before this field existed carries - // no repository; `new URL(undefined)` throws, and the project keeps the Cloudflare behaviour. url = new URL(repository); } catch { - return artifactsSource; + return null; } const host = url.host.toLowerCase(); - if (url.protocol !== 'https:' || !host || isCloudflareArtifactsHost(host)) return artifactsSource; + if (url.protocol !== 'https:' || !host || isCloudflareArtifactsHost(host)) return null; + return host; +} + +function resolveArtifactsGitSource(repository: string | undefined): WorkspaceGitSource { + const artifactsSource: WorkspaceGitSource = { + ...DEFAULT_GITHUB_SOURCE, + repoProvider: 'artifacts', + }; + const host = boundArtifactsRepositoryHost(repository); + if (!host || !repository) return artifactsSource; return { ...artifactsSource, cloneUrl: repository, repositoryHost: host }; } diff --git a/apps/api/tests/unit/routes/artifacts-config.test.ts b/apps/api/tests/unit/routes/artifacts-config.test.ts index 0774ed955f..1ac9911dd9 100644 --- a/apps/api/tests/unit/routes/artifacts-config.test.ts +++ b/apps/api/tests/unit/routes/artifacts-config.test.ts @@ -1,115 +1,68 @@ /** - * Regression test for /api/config/artifacts-enabled endpoint. + * Regression test for /api/config/artifacts-enabled. * - * This endpoint must check BOTH the ARTIFACTS_ENABLED env flag AND the - * ARTIFACTS binding. Without the binding check, the UI enables an artifacts - * feature that crashes at runtime because env.ARTIFACTS is undefined. + * The endpoint must report Artifacts only when ARTIFACTS_ENABLED is set AND a backend exists. + * Without the backend check the UI offers a provider that crashes on use (the 2026-04-25 + * Artifacts post-mortem). Since L16 the backend is the Cloudflare binding or, on a self-hosted + * install, the backend its build registered. * - * See: docs/notes/2026-04-25-artifacts-broken-merge-postmortem.md + * Mounts the real route module at the same path `src/index.ts` uses. */ import { Hono } from 'hono'; import { afterEach, describe, expect, it } from 'vitest'; import type { Env } from '../../../src/env'; -import { - isArtifactsAvailable, - registerArtifactsBackendFallback, -} from '../../../src/services/hosted-git/backend'; +import { artifactsConfigRoutes } from '../../../src/routes/artifacts-config'; +import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; + +const app = new Hono<{ Bindings: Env }>(); +app.route('/api/config', artifactsConfigRoutes); + +async function enabled(env: Partial): Promise { + const res = await app.request('/api/config/artifacts-enabled', {}, env as Env); + expect(res.status).toBe(200); + return ((await res.json()) as { enabled: boolean }).enabled; +} + +const binding = { create: () => null, delete: () => null, get: () => null } as never; + +afterEach(() => registerArtifactsBackendFallback(null)); describe('/api/config/artifacts-enabled', () => { - function createApp(env: Record) { - const app = new Hono<{ Bindings: Record }>(); - // src/index.ts answers with exactly this call. - app.get('/api/config/artifacts-enabled', (c) => { - return c.json({ enabled: isArtifactsAvailable(c.env as unknown as Env) }); - }); - return { app, env }; - } + it('returns false when both flag and binding are absent', async () => { + expect(await enabled({})).toBe(false); + }); - it('returns enabled: false when both flag and binding are absent', async () => { - const { app } = createApp({}); - const res = await app.request('/api/config/artifacts-enabled', {}, {}); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.enabled).toBe(false); + it('returns false when the flag is true but no binding exists (binding silently missing)', async () => { + expect(await enabled({ ARTIFACTS_ENABLED: 'true' })).toBe(false); }); - it('returns enabled: false when flag is true but binding is absent', async () => { - const { app } = createApp({ ARTIFACTS_ENABLED: 'true' }); - const res = await app.request( - '/api/config/artifacts-enabled', - {}, - { ARTIFACTS_ENABLED: 'true' } - ); - expect(res.status).toBe(200); - const body = await res.json(); - // This is the critical case: flag is on but Wrangler didn't inject the - // binding (e.g. Wrangler v3 silently ignores [[artifacts]]). The endpoint - // MUST return false so the UI doesn't offer a broken feature. - expect(body.enabled).toBe(false); + it('returns true when both flag and binding are present', async () => { + expect(await enabled({ ARTIFACTS_ENABLED: 'true', ARTIFACTS: binding })).toBe(true); }); - it('returns enabled: true when both flag and binding are present', async () => { - const mockArtifacts = { list: () => ({}) }; - const { app } = createApp({ - ARTIFACTS_ENABLED: 'true', - ARTIFACTS: mockArtifacts, - }); - const res = await app.request( - '/api/config/artifacts-enabled', - {}, - { ARTIFACTS_ENABLED: 'true', ARTIFACTS: mockArtifacts } - ); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.enabled).toBe(true); + it('returns false when the binding exists but the flag is not set', async () => { + expect(await enabled({ ARTIFACTS: binding })).toBe(false); }); - it('returns enabled: false when binding exists but flag is not set', async () => { - const mockArtifacts = { list: () => ({}) }; - const { app } = createApp({}); - const res = await app.request( - '/api/config/artifacts-enabled', - {}, - { ARTIFACTS: mockArtifacts } - ); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.enabled).toBe(false); + it('returns false when the flag is explicitly "false"', async () => { + expect(await enabled({ ARTIFACTS_ENABLED: 'false', ARTIFACTS: binding })).toBe(false); }); - it('returns enabled: false when flag is explicitly "false"', async () => { - const mockArtifacts = { list: () => ({}) }; - const { app } = createApp({}); - const res = await app.request( - '/api/config/artifacts-enabled', - {}, - { ARTIFACTS_ENABLED: 'false', ARTIFACTS: mockArtifacts } - ); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.enabled).toBe(false); + it('sets public-config cache headers', async () => { + const res = await app.request('/api/config/artifacts-enabled', {}, {} as Env); + expect(res.headers.get('Cache-Control')).toBeTruthy(); }); describe('with a self-host fallback backend registered', () => { - afterEach(() => registerArtifactsBackendFallback(null)); - - it('returns enabled: true with the flag and no binding', async () => { - registerArtifactsBackendFallback(() => ({}) as never); - const { app } = createApp({}); - const res = await app.request( - '/api/config/artifacts-enabled', - {}, - { ARTIFACTS_ENABLED: 'true' } - ); - expect((await res.json()).enabled).toBe(true); + it('returns true with the flag and no binding', async () => { + registerArtifactsBackendFallback(() => binding); + expect(await enabled({ ARTIFACTS_ENABLED: 'true' })).toBe(true); }); - it('still returns enabled: false without the flag', async () => { - registerArtifactsBackendFallback(() => ({}) as never); - const { app } = createApp({}); - const res = await app.request('/api/config/artifacts-enabled', {}, {}); - expect((await res.json()).enabled).toBe(false); + it('still returns false without the flag', async () => { + registerArtifactsBackendFallback(() => binding); + expect(await enabled({})).toBe(false); }); }); }); diff --git a/apps/api/tests/unit/routes/workspace-git-token.test.ts b/apps/api/tests/unit/routes/workspace-git-token.test.ts index f571997741..c20c399168 100644 --- a/apps/api/tests/unit/routes/workspace-git-token.test.ts +++ b/apps/api/tests/unit/routes/workspace-git-token.test.ts @@ -492,6 +492,8 @@ describe('workspace git-token GitHub scoping', () => { token: 'hosted-token', expiresAt: '2026-06-06T20:00:00.000Z', cloneUrl: remote, + // The bound self-hosted host gets the same username the clone used. + username: 'x', }); } finally { registerArtifactsBackendFallback(null); diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go index 5ac6f37e84..a3d0019841 100644 --- a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go @@ -102,3 +102,48 @@ func TestWithGitTokenBoundHostIsExact(t *testing.T) { } } } + +// Positive cases the exact match must keep accepting: the control plane binds +// url.host (lowercased, port included), and git may present either case. +func TestWithGitTokenBoundHostCaseAndPort(t *testing.T) { + t.Parallel() + + cases := []struct { + bound, url, want string + }{ + {"API.Sam.Example", "https://api.sam.example/git/d.git", "https://x:t@api.sam.example/git/d.git"}, + {"api.sam.example", "https://API.SAM.EXAMPLE/git/d.git", "https://x:t@API.SAM.EXAMPLE/git/d.git"}, + {"api.sam.example:8443", "https://api.sam.example:8443/git/d.git", "https://x:t@api.sam.example:8443/git/d.git"}, + } + for _, tc := range cases { + cfg := &config.Config{RepoProvider: "artifacts", RepositoryHost: tc.bound} + got, err := withGitToken(tc.url, "t", cfg) + if err != nil { + t.Fatalf("withGitToken(%s): %v", tc.url, err) + } + if got != tc.want { + t.Fatalf("bound %q url %q: got %s want %s", tc.bound, tc.url, got, tc.want) + } + } +} + +// An empty bound host never matches, and only the artifacts provider binds a +// hosted host for the credential helper. +func TestBoundHostedArtifactsHostGuards(t *testing.T) { + t.Parallel() + + if isBoundHostedArtifactsHost(&config.Config{RepoProvider: "artifacts"}, "") { + t.Fatal("empty bound host must not match an empty url host") + } + if isBoundHostedArtifactsHost(nil, "api.sam.example") { + t.Fatal("nil config must not match") + } + github := &config.Config{ + RepoProvider: "github", + RepositoryHost: "api.sam.example", + CloneURL: "https://api.sam.example/git/demo.git", + } + if needsCredentialHelperForConfig(github) { + t.Fatal("a bound host on a non-artifacts provider must not enable the credential helper") + } +} diff --git a/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md b/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md index a5b9f8898b..dbd25d21e6 100644 --- a/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md +++ b/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md @@ -35,15 +35,17 @@ working exactly as today. ## Checklist -- [ ] `apps/api/src/services/hosted-git/backend.ts`: `resolveArtifactsBackend`, `isArtifactsAvailable`, self-host +- [x] `apps/api/src/services/hosted-git/backend.ts`: `resolveArtifactsBackend`, `isArtifactsAvailable`, self-host registration hook (`registerArtifactsBackendFallback`) -- [ ] Route all `env.ARTIFACTS` callers through it (index, project-create, crud delete, runtime-git-token) -- [ ] repo-hosting `artifacts` port (`resolve`) + wiring; repo-browse uses it -- [ ] C15 in `workspace-git-source.ts`, `repository` required on the source type, callers pass it (no new D1 reads) -- [ ] vm-agent `isBoundHostedArtifactsHost` in its own file; `withGitToken` + `needsCredentialHelperForConfig` use it -- [ ] Tests: backend resolution (enabled/disabled/binding/fallback/binding-wins), C15 (CF host, hosted host, malformed, +- [x] Route all `env.ARTIFACTS` callers through it (index, project-create, crud delete, runtime-git-token) +- [x] repo-hosting `artifacts` port (`resolve`) + wiring; repo-browse uses it +- [x] C15 in `workspace-git-source.ts`, `repository` required on the source type, callers pass it (no new D1 reads) +- [x] vm-agent `isBoundHostedArtifactsHost` in its own file; `withGitToken` + `needsCredentialHelperForConfig` use it +- [x] Tests: backend resolution (enabled/disabled/binding/fallback/binding-wins), C15 (CF host, hosted host, malformed, github unchanged) through real callers, Go withGitToken + credential helper with controls, repo-browse port -- [ ] Docs sync +- [x] Docs sync: no user-facing doc impact. Cloudflare behaviour is unchanged and + `guides/project-files.md` (ARTIFACTS_ENABLED gate) stays accurate; self-host hosted-git docs ship with the + self-host build. ## Acceptance criteria @@ -53,3 +55,17 @@ working exactly as today. - An Artifacts project whose remote is not `*.artifacts.cloudflare.net` gets cloneUrl + repositoryHost; the VM agent attaches the token only to that bound host (unit, Go). - No D1 read added to any workspace-creation path. + +## Review fixes + +- cloudflare-specialist: the config test copied the handler, so `/api/config/artifacts-enabled` moved to + `routes/artifacts-config.ts` and the test mounts the real module; legacy NodeLifecycle payload guard made explicit + (`typeof repository !== 'string'`). +- go-specialist: the credential helper would answer a bound self-hosted host with username `x-access-token` while the + clone used `x`; the git-token route now returns `username: 'x'` for a bound (non-Cloudflare) host only, so Cloudflare + responses are unchanged and already-deployed agents get it. Added Go cases for case, port, empty bound host, + non-artifacts provider. +- security-auditor: documented that `projects.repository` for Artifacts projects is server-assigned (LOW-1). +- Old agent + new control plane on a self-hosted install cannot clone a hosted repository (no token attached): not + reachable on Cloudflare, and self-host placement already rejects nodes whose agent build differs from the required + release (rule 54), so hosted projects only land on agents with this change. From 9406993ba9a4ee1baee9abdfe8e089a248d61d78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 11:28:49 +0000 Subject: [PATCH 03/11] task: archive L16 hosted-git seam task Co-Authored-By: Claude Opus 5.5 --- .../2026-11-17-selfhost-l16-hosted-git-seam.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-17-selfhost-l16-hosted-git-seam.md (100%) diff --git a/tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md similarity index 100% rename from tasks/active/2026-11-17-selfhost-l16-hosted-git-seam.md rename to tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md From 9a40c5c593635038a63ae2b5b636689e43324637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 18:41:22 +0000 Subject: [PATCH 04/11] fix: retain hosted repository cleanup when Artifacts is disabled --- apps/api/src/routes/projects/crud.ts | 7 +-- apps/api/src/services/hosted-git/backend.ts | 11 +++- .../routes/project-artifacts-creation.test.ts | 49 ++++++--------- .../tests/unit/routes/project-delete.test.ts | 61 ++++++++++--------- .../unit/services/hosted-git-backend.test.ts | 3 +- ...2026-11-17-selfhost-l16-hosted-git-seam.md | 10 ++- 6 files changed, 73 insertions(+), 68 deletions(-) diff --git a/apps/api/src/routes/projects/crud.ts b/apps/api/src/routes/projects/crud.ts index efd789880b..37ab252899 100644 --- a/apps/api/src/routes/projects/crud.ts +++ b/apps/api/src/routes/projects/crud.ts @@ -17,7 +17,7 @@ import { deleteProjectLibraryObjects, getProjectDeleteCleanupBatchSize, } from '../../services/file-library'; -import { resolveArtifactsBackend } from '../../services/hosted-git/backend'; +import { resolveArtifactsBackendForCleanup } from '../../services/hosted-git/backend'; import { getRuntimeLimits } from '../../services/limits'; import { deleteWorkspaceResourceHistoryObjectsForProject } from '../../services/workspace-resource-history'; import { registerProjectCreateRoute } from './project-create'; @@ -43,9 +43,8 @@ async function cleanupArtifactsRepoOnProjectDelete( action: 'orphaned_artifacts_repo_on_delete', }; - // The Cloudflare binding even when ARTIFACTS_ENABLED was turned off after creation (unchanged), - // else the backend the self-host build registered. - const artifacts = env.ARTIFACTS ?? resolveArtifactsBackend(env); + // Disabling Artifacts stops serving, but must not prevent cleanup of existing repositories. + const artifacts = resolveArtifactsBackendForCleanup(env); if (!artifacts || typeof artifacts.delete !== 'function') { log.warn('project_delete.artifacts_delete_unavailable', orphanDetails); return; diff --git a/apps/api/src/services/hosted-git/backend.ts b/apps/api/src/services/hosted-git/backend.ts index 857e95ff27..40aa4feb0a 100644 --- a/apps/api/src/services/hosted-git/backend.ts +++ b/apps/api/src/services/hosted-git/backend.ts @@ -11,7 +11,8 @@ * hosted-git implementation. * * Every caller that needs the backend goes through `resolveArtifactsBackend`, so the capability - * flag, project creation, browsing, git tokens and deletion cannot disagree. + * flag, project creation, browsing and git tokens cannot disagree. Deletion uses the same + * selection without the enable flag, so disabling the feature cannot orphan existing repositories. */ import type { Env } from '../../env'; @@ -33,8 +34,12 @@ export function registerArtifactsBackendFallback(factory: ArtifactsBackendFallba /** The backend this install uses for SAM-native repositories, or null when it has none. */ export function resolveArtifactsBackend(env: Env): ArtifactsBackend | null { if (env.ARTIFACTS_ENABLED !== 'true') return null; - if (env.ARTIFACTS) return env.ARTIFACTS; - return fallback?.(env) ?? null; + return resolveArtifactsBackendForCleanup(env); +} + +/** Existing repositories still need cleanup after the feature is disabled. Never use for serving. */ +export function resolveArtifactsBackendForCleanup(env: Env): ArtifactsBackend | null { + return env.ARTIFACTS ?? fallback?.(env) ?? null; } /** Whether this install can create and serve SAM-native (Artifacts) repositories. */ diff --git a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts index 7678a7da16..db8dd78d23 100644 --- a/apps/api/tests/unit/routes/project-artifacts-creation.test.ts +++ b/apps/api/tests/unit/routes/project-artifacts-creation.test.ts @@ -3,7 +3,8 @@ import { Hono } from 'hono'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Env } from '../../../src/env'; -import { projectsRoutes } from '../../../src/routes/projects'; +import { AppError } from '../../../src/middleware/error'; +import { registerProjectCreateRoute } from '../../../src/routes/projects/project-create'; import { registerArtifactsBackendFallback } from '../../../src/services/hosted-git/backend'; /** @@ -20,17 +21,9 @@ const mocks = vi.hoisted(() => ({ })); vi.mock('drizzle-orm/d1'); -vi.mock('../../../src/middleware/auth', () => ({ - rejectAgentSignInSession: () => async (_c: unknown, next: () => Promise) => next(), - assertNotAgentSignInSession: () => undefined, - requireAuth: () => vi.fn((c: any, next: any) => next()), - requireApproved: () => vi.fn((c: any, next: any) => next()), - getUserId: () => 'user-1', -})); +vi.mock('../../../src/middleware/auth', () => ({ getUserId: () => 'user-1' })); vi.mock('../../../src/middleware/project-auth', () => ({ createOwnerProjectMembership: mocks.createOwnerProjectMembership, - requireProjectAccess: mocks.requireProjectAccess, - requireProjectCapability: mocks.requireProjectCapability, })); vi.mock('../../../src/services/artifacts/seed-readme', () => ({ seedArtifactsReadme: mocks.seedArtifactsReadme, @@ -79,19 +72,15 @@ describe('POST /api/projects — Artifacts provider through the hosted-git seam' insertedRows = []; deletedProjectIds = []; - const makeSelectBuilder = () => { - const fromBuilder = { - where: vi.fn(() => - Object.assign(Promise.resolve(whereResponses.shift() ?? []), { - limit: vi.fn(() => Promise.resolve(limitResponses.shift() ?? [])), - }) - ), - }; - return { from: vi.fn(() => fromBuilder) }; - }; - const mockDB = { - select: vi.fn(() => makeSelectBuilder()), + select: vi.fn(() => ({ + from: () => ({ + where: () => + Object.assign(Promise.resolve(whereResponses.shift() ?? []), { + limit: () => Promise.resolve(limitResponses.shift() ?? []), + }), + }), + })), insert: vi.fn(() => ({ values: vi.fn((row: unknown) => { insertedRows.push(row); @@ -111,14 +100,14 @@ describe('POST /api/projects — Artifacts provider through the hosted-git seam' mocks.createOwnerProjectMembership.mockResolvedValue(undefined); app = new Hono<{ Bindings: Env }>(); - app.onError((err, c) => { - const appError = err as { statusCode?: number; error?: string; message?: string }; - if (typeof appError.statusCode === 'number' && typeof appError.error === 'string') { - return c.json({ error: appError.error, message: appError.message }, appError.statusCode); - } - return c.json({ error: 'INTERNAL_ERROR', message: err.message }, 500); - }); - app.route('/api/projects', projectsRoutes); + app.onError((err, c) => + err instanceof AppError + ? c.json(err.toJSON(), err.statusCode) + : c.json({ error: 'INTERNAL_ERROR' }, 500) + ); + const createRoute = new Hono<{ Bindings: Env }>(); + registerProjectCreateRoute(createRoute); + app.route('/api/projects', createRoute); }); afterEach(() => registerArtifactsBackendFallback(null)); diff --git a/apps/api/tests/unit/routes/project-delete.test.ts b/apps/api/tests/unit/routes/project-delete.test.ts index df65042e83..14a66c1a2d 100644 --- a/apps/api/tests/unit/routes/project-delete.test.ts +++ b/apps/api/tests/unit/routes/project-delete.test.ts @@ -350,37 +350,40 @@ describe('DELETE /api/projects/:id', () => { expect(consoleWarnSpy).not.toHaveBeenCalled(); }); - it('deletes the repository through a registered self-host backend when no binding exists', async () => { - const hostedDelete = vi.fn().mockResolvedValue(true); - registerArtifactsBackendFallback( - () => ({ delete: hostedDelete, create: vi.fn(), get: vi.fn() }) as never - ); - try { - mocks.requireProjectCapability.mockResolvedValueOnce({ - id: 'proj-1', - userId: 'user-1', - name: 'Hosted Project', - installationId: 'system_anonymous_trials_installation', - repository: 'https://api.sam.example/git/artifacts-repo-1.git', - defaultBranch: 'main', - repoProvider: 'artifacts', - artifactsRepoId: 'artifacts-repo-1', - }); - selectResults.push([]); - - const response = await app.request( - '/api/projects/proj-1', - { method: 'DELETE' }, - { ...env, ARTIFACTS_ENABLED: 'true' } + it.each(['true', 'false', undefined])( + 'deletes through the fallback with ARTIFACTS_ENABLED=%s', + async (enabled) => { + const hostedDelete = vi.fn().mockResolvedValue(true); + registerArtifactsBackendFallback( + () => ({ delete: hostedDelete, create: vi.fn(), get: vi.fn() }) as never ); - - expect(response.status).toBe(200); - expect(hostedDelete).toHaveBeenCalledWith('artifacts-repo-1'); - expect(consoleWarnSpy).not.toHaveBeenCalled(); - } finally { - registerArtifactsBackendFallback(null); + try { + mocks.requireProjectCapability.mockResolvedValueOnce({ + id: 'proj-1', + userId: 'user-1', + name: 'Hosted Project', + installationId: 'system_anonymous_trials_installation', + repository: 'https://api.sam.example/git/artifacts-repo-1.git', + defaultBranch: 'main', + repoProvider: 'artifacts', + artifactsRepoId: 'artifacts-repo-1', + }); + selectResults.push([]); + + const response = await app.request( + '/api/projects/proj-1', + { method: 'DELETE' }, + { ...env, ARTIFACTS_ENABLED: enabled } + ); + + expect(response.status).toBe(200); + expect(hostedDelete).toHaveBeenCalledWith('artifacts-repo-1'); + expect(consoleWarnSpy).not.toHaveBeenCalled(); + } finally { + registerArtifactsBackendFallback(null); + } } - }); + ); it('logs an orphan and still deletes the project when the Artifacts binding is unavailable', async () => { mocks.requireProjectCapability.mockResolvedValueOnce({ diff --git a/apps/api/tests/unit/services/hosted-git-backend.test.ts b/apps/api/tests/unit/services/hosted-git-backend.test.ts index 134c3bc9a0..ba87fa85e5 100644 --- a/apps/api/tests/unit/services/hosted-git-backend.test.ts +++ b/apps/api/tests/unit/services/hosted-git-backend.test.ts @@ -4,7 +4,8 @@ * `resolveArtifactsBackend` is the one answer to "which Artifacts backend does this install use?". * On Cloudflare it is the binding or nothing; a self-host build may register a fallback that is * used only when Artifacts is enabled and no binding exists. Every caller (capability flag, - * project creation and deletion, git tokens, repository browsing) goes through it. + * project creation, git tokens, repository browsing) goes through it. Deletion uses + * cleanup-only resolution so disabling the flag cannot orphan existing repositories. */ import { repoHostingPorts } from '@simple-agent-manager/repo-hosting/ports'; import { afterEach, describe, expect, it, vi } from 'vitest'; diff --git a/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md index dbd25d21e6..4785bc4497 100644 --- a/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md +++ b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md @@ -51,7 +51,7 @@ working exactly as today. - Cloudflare Artifacts create / clone / push / browse / delete unchanged (staging). - GitHub project clone unchanged (staging). -- A registered fallback backend is used only when Artifacts is enabled and no binding exists (unit). +- A registered fallback backend serves repositories only when Artifacts is enabled and no binding exists (unit). Deletion cleanup remains available after disabling the flag, matching the Cloudflare binding. - An Artifacts project whose remote is not `*.artifacts.cloudflare.net` gets cloneUrl + repositoryHost; the VM agent attaches the token only to that bound host (unit, Go). - No D1 read added to any workspace-creation path. @@ -69,3 +69,11 @@ working exactly as today. - Old agent + new control plane on a self-hosted install cannot clone a hosted repository (no token attached): not reachable on Cloudflare, and self-host placement already rejects nodes whose agent build differs from the required release (rule 54), so hosted projects only land on agents with this change. + +## Takeover validation + +- Merged safe deploy main including #2841 (`0c672ddbf`); `quality:no-secret-readback` passes. +- Codex comment 4598971932 addressed: cleanup-only backend resolution preserves disabled-feature deletion without widening serving, creation or token access. Surgical revert: disabled/absent DELETE cases fail, 13 controls pass; restored suite passes. +- Consolidated copied Artifacts creation test setup (Sonar); tests still enter the real production route/schema. +- Focused Cloudflare/security/completion reviews PASS; Go implementation unchanged, prior review retained. +- Staging fresh VM/clone/push and GitHub clone remain pending; production merge hold remains until coordinator lifts it. From 7495af677e168024cb8ed3a62a639a96a29ddef2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Tue, 17 Nov 2026 23:27:26 +0000 Subject: [PATCH 05/11] test(api): allow shared CI budget for speech import graph --- apps/api/tests/unit/selfhost/speech-selfhost-only.test.ts | 3 ++- tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/api/tests/unit/selfhost/speech-selfhost-only.test.ts b/apps/api/tests/unit/selfhost/speech-selfhost-only.test.ts index d80520c0b0..5e0159ef38 100644 --- a/apps/api/tests/unit/selfhost/speech-selfhost-only.test.ts +++ b/apps/api/tests/unit/selfhost/speech-selfhost-only.test.ts @@ -15,13 +15,14 @@ import { } from '../../helpers/selfhost-only-modules'; describe('self-host speech backend placement', () => { + // Walking the full Worker graph can exceed Vitest's default under shared CI load. it('the Worker entry reaches the speech seam but no self-host speech module', () => { const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); expect(graph.files).toContain('apps/api/src/services/speech-backend.ts'); expect(graph.files.filter((file) => file.startsWith('apps/api/src/selfhost/speech/'))).toEqual( [] ); - }); + }, 30_000); it('positive control: the speech module is flagged as self-host-only when walked', () => { const graph = collectImportGraph(resolve(API_SRC, 'selfhost/speech/index.ts')); diff --git a/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md index 4785bc4497..9f5cfa31c1 100644 --- a/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md +++ b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md @@ -76,4 +76,5 @@ working exactly as today. - Codex comment 4598971932 addressed: cleanup-only backend resolution preserves disabled-feature deletion without widening serving, creation or token access. Surgical revert: disabled/absent DELETE cases fail, 13 controls pass; restored suite passes. - Consolidated copied Artifacts creation test setup (Sonar); tests still enter the real production route/schema. - Focused Cloudflare/security/completion reviews PASS; Go implementation unchanged, prior review retained. -- Staging fresh VM/clone/push and GitHub clone remain pending; production merge hold remains until coordinator lifts it. +- Coordinator lifted the #2841 production hold at 21:31 UTC after production deploy 44174587033 succeeded. Staging fresh VM/clone/push, GitHub clone and current-head CI remain pending. +- Main #2840 introduced a speech import-graph test that exceeded Vitest’s default 5-second budget under shared CI load (5695 ms; API shard 1 otherwise 5406 passed / 1 skipped). Added a 30-second budget only to that graph walk; assertions and positive control are unchanged. Focused 2/2 tests and ESLint PASS; Cloudflare delta review PASS. This is an unrelated test-only CI fix, not an L16 runtime change. From fcdd51c9fc166f3d100dd05ebe83dd8dd4105657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 00:07:01 +0000 Subject: [PATCH 06/11] fix(vm-agent): honor callback username for standalone clones --- .../internal/server/standalone_workspace.go | 1 + .../server/standalone_workspace_test.go | 52 +++++++++++++++++++ ...2026-11-17-selfhost-l16-hosted-git-seam.md | 3 ++ 3 files changed, 56 insertions(+) diff --git a/packages/vm-agent/internal/server/standalone_workspace.go b/packages/vm-agent/internal/server/standalone_workspace.go index 59bf25e58d..aba99f46c1 100644 --- a/packages/vm-agent/internal/server/standalone_workspace.go +++ b/packages/vm-agent/internal/server/standalone_workspace.go @@ -297,6 +297,7 @@ func standaloneCloneSpecForURL(repositoryURL string, tokenResponse *gitTokenResp } if tokenResponse != nil { spec.Token = strings.TrimSpace(tokenResponse.Token) + spec.Username = strings.TrimSpace(tokenResponse.Username) } if parsed.User != nil { diff --git a/packages/vm-agent/internal/server/standalone_workspace_test.go b/packages/vm-agent/internal/server/standalone_workspace_test.go index 103f7b7896..e983d2f218 100644 --- a/packages/vm-agent/internal/server/standalone_workspace_test.go +++ b/packages/vm-agent/internal/server/standalone_workspace_test.go @@ -2,7 +2,10 @@ package server import ( "context" + "encoding/json" "errors" + "net/http" + "net/http/httptest" "os" "path/filepath" "slices" @@ -12,6 +15,55 @@ import ( "github.com/workspace/vm-agent/internal/config" ) +func TestStandaloneCloneUsesCallbackUsername(t *testing.T) { + original := runStandaloneGitCommand + t.Cleanup(func() { runStandaloneGitCommand = original }) + for _, tc := range []struct { + name, cloneURL, username, wantUsername string + }{ + {"hosted fallback", "https://hosted.example.test/git/repo.git", " x ", "x"}, + {"GitHub default", "https://github.com/owner/repo.git", "", "x-access-token"}, + {"Artifacts default", "https://acct.artifacts.cloudflare.net/git/default/repo.git", "", "x"}, + } { + t.Run(tc.name, func(t *testing.T) { + const token = "standalone-clone-test-token" + called := false + controlPlane := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/workspaces/ws/git-token" || r.Header.Get("Authorization") != "Bearer callback" { + t.Error("clone requested credentials without its workspace binding") + w.WriteHeader(http.StatusUnauthorized) + return + } + called = true + _ = json.NewEncoder(w).Encode(gitTokenResponse{Token: token, CloneURL: tc.cloneURL, Username: tc.username}) + })) + defer controlPlane.Close() + cloned := false + runStandaloneGitCommand = func(_ context.Context, _ string, env []string, args ...string) (string, error) { + if !slices.Contains(args, "clone") { + return "", nil + } + cloned = true + if !slices.Contains(args, tc.cloneURL) || !envContains(env, "SAM_CLONE_CREDENTIAL_USERNAME="+tc.wantUsername) || !envContains(env, "SAM_CLONE_CREDENTIAL_TOKEN="+token) { + t.Error("clone did not receive the callback URL and matching credential pair") + } + if strings.Contains(strings.Join(args, " "), token) { + t.Error("clone exposed its token in command arguments") + } + return "", nil + } + s := &Server{config: &config.Config{ControlPlaneURL: controlPlane.URL}} + runtime := &WorkspaceRuntime{ID: "ws", Repository: "owner/repo", CallbackToken: "callback"} + if err := s.cloneStandaloneRepository(context.Background(), runtime, filepath.Join(t.TempDir(), "repo")); err != nil { + t.Fatal(err) + } + if !called || !cloned { + t.Fatal("credential callback and standalone clone must both run") + } + }) + } +} + func TestStandaloneCloneWarnings(t *testing.T) { cases := []struct { name string diff --git a/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md index 9f5cfa31c1..2b9f846108 100644 --- a/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md +++ b/tasks/archive/2026-11-17-selfhost-l16-hosted-git-seam.md @@ -78,3 +78,6 @@ working exactly as today. - Focused Cloudflare/security/completion reviews PASS; Go implementation unchanged, prior review retained. - Coordinator lifted the #2841 production hold at 21:31 UTC after production deploy 44174587033 succeeded. Staging fresh VM/clone/push, GitHub clone and current-head CI remain pending. - Main #2840 introduced a speech import-graph test that exceeded Vitest’s default 5-second budget under shared CI load (5695 ms; API shard 1 otherwise 5406 passed / 1 skipped). Added a 30-second budget only to that graph walk; assertions and positive control are unchanged. Focused 2/2 tests and ESLint PASS; Cloudflare delta review PASS. This is an unrelated test-only CI fix, not an L16 runtime change. + +- Final review reconciliation found Codex P1 4604144749: standalone/Instant initial clones ignored the callback username on custom hosted fallback hosts. Copy the trimmed username into the existing clone spec; embedded-URL precedence and provider defaults remain intact. Regression drives the real clone entry through its authenticated HTTP callback and git command boundary. Surgical pre-fix run: only hosted fallback fails; GitHub/Artifacts controls pass. Fixed standalone suite and targeted race tests PASS; independent Go/security delta reviews PASS. Fresh staging uses the resulting new VM-agent release; full current-head CI remains required. +- Standalone username follow-up: full Go server package PASS (72.666 s); focused race PASS; completion delta review PASS. Current-head CI and agreed live checks still block merge. From 4bd1f57b4561ec312aa8fb46650be2be6b9e9077 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 00:50:10 +0000 Subject: [PATCH 07/11] test(vm-agent): simplify standalone callback regression --- .../server/standalone_workspace_test.go | 73 ++++++++++--------- 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/packages/vm-agent/internal/server/standalone_workspace_test.go b/packages/vm-agent/internal/server/standalone_workspace_test.go index e983d2f218..54fc8aca98 100644 --- a/packages/vm-agent/internal/server/standalone_workspace_test.go +++ b/packages/vm-agent/internal/server/standalone_workspace_test.go @@ -26,44 +26,49 @@ func TestStandaloneCloneUsesCallbackUsername(t *testing.T) { {"Artifacts default", "https://acct.artifacts.cloudflare.net/git/default/repo.git", "", "x"}, } { t.Run(tc.name, func(t *testing.T) { - const token = "standalone-clone-test-token" - called := false - controlPlane := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/workspaces/ws/git-token" || r.Header.Get("Authorization") != "Bearer callback" { - t.Error("clone requested credentials without its workspace binding") - w.WriteHeader(http.StatusUnauthorized) - return - } - called = true - _ = json.NewEncoder(w).Encode(gitTokenResponse{Token: token, CloneURL: tc.cloneURL, Username: tc.username}) - })) - defer controlPlane.Close() - cloned := false - runStandaloneGitCommand = func(_ context.Context, _ string, env []string, args ...string) (string, error) { - if !slices.Contains(args, "clone") { - return "", nil - } - cloned = true - if !slices.Contains(args, tc.cloneURL) || !envContains(env, "SAM_CLONE_CREDENTIAL_USERNAME="+tc.wantUsername) || !envContains(env, "SAM_CLONE_CREDENTIAL_TOKEN="+token) { - t.Error("clone did not receive the callback URL and matching credential pair") - } - if strings.Contains(strings.Join(args, " "), token) { - t.Error("clone exposed its token in command arguments") - } - return "", nil - } - s := &Server{config: &config.Config{ControlPlaneURL: controlPlane.URL}} - runtime := &WorkspaceRuntime{ID: "ws", Repository: "owner/repo", CallbackToken: "callback"} - if err := s.cloneStandaloneRepository(context.Background(), runtime, filepath.Join(t.TempDir(), "repo")); err != nil { - t.Fatal(err) - } - if !called || !cloned { - t.Fatal("credential callback and standalone clone must both run") - } + assertStandaloneCallbackClone(t, tc.cloneURL, tc.username, tc.wantUsername) }) } } +func assertStandaloneCallbackClone(t *testing.T, cloneURL, username, wantUsername string) { + t.Helper() + const token = "standalone-clone-test-token" + called := false + controlPlane := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/workspaces/ws/git-token" || r.Header.Get("Authorization") != "Bearer callback" { + t.Error("clone requested credentials without its workspace binding") + w.WriteHeader(http.StatusUnauthorized) + return + } + called = true + _ = json.NewEncoder(w).Encode(gitTokenResponse{Token: token, CloneURL: cloneURL, Username: username}) + })) + defer controlPlane.Close() + cloned := false + runStandaloneGitCommand = func(_ context.Context, _ string, env []string, args ...string) (string, error) { + if !slices.Contains(args, "clone") { + return "", nil + } + cloned = true + if !slices.Contains(args, cloneURL) || !envContains(env, "SAM_CLONE_CREDENTIAL_USERNAME="+wantUsername) || !envContains(env, "SAM_CLONE_CREDENTIAL_TOKEN="+token) { + t.Error("clone did not receive the callback URL and matching credential pair") + } + if strings.Contains(strings.Join(args, " "), token) { + t.Error("clone exposed its token in command arguments") + } + return "", nil + } + s := &Server{config: &config.Config{ControlPlaneURL: controlPlane.URL}} + runtime := &WorkspaceRuntime{ID: "ws", Repository: "owner/repo", CallbackToken: "callback"} + if err := s.cloneStandaloneRepository(context.Background(), runtime, filepath.Join(t.TempDir(), "repo")); err != nil { + t.Fatal(err) + } + if !called || !cloned { + t.Fatal("credential callback and standalone clone must both run") + } +} + func TestStandaloneCloneWarnings(t *testing.T) { cases := []struct { name string From da9f91b32c9a633cc316a6d083e47270e441873f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 03:14:13 +0000 Subject: [PATCH 08/11] fix(vm-agent): normalize hosted git HTTPS ports --- .../bootstrap/hosted_artifacts_host.go | 27 +++++++++++++++++-- .../bootstrap/hosted_artifacts_host_test.go | 14 ++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go index 33ef1db1a5..16bdac17b5 100644 --- a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go @@ -1,6 +1,8 @@ package bootstrap import ( + "net" + "strconv" "strings" "github.com/workspace/vm-agent/internal/config" @@ -17,6 +19,27 @@ func isBoundHostedArtifactsHost(cfg *config.Config, host string) bool { if cfg == nil || !strings.EqualFold(strings.TrimSpace(cfg.RepoProvider), "artifacts") { return false } - bound := strings.TrimSpace(cfg.RepositoryHost) - return bound != "" && strings.EqualFold(bound, strings.TrimSpace(host)) + bound := canonicalHostedArtifactsAuthority(cfg.RepositoryHost) + // WHATWG URL.host in the control plane omits HTTPS's default port, while + // Go's URL.Host preserves it. Other ports still require an exact match. + return bound != "" && strings.EqualFold(bound, canonicalHostedArtifactsAuthority(host)) +} + +func canonicalHostedArtifactsAuthority(authority string) string { + authority = strings.TrimSpace(authority) + host, port, err := net.SplitHostPort(authority) + if err != nil { + return authority + } + if port == "" { + return strings.TrimSuffix(authority, ":") + } + number, err := strconv.ParseUint(port, 10, 16) + if err != nil { + return "" + } + if number == 443 { + return strings.TrimSuffix(authority, ":"+port) + } + return net.JoinHostPort(host, strconv.FormatUint(number, 10)) } diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go index a3d0019841..65d7760323 100644 --- a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host_test.go @@ -101,6 +101,13 @@ func TestWithGitTokenBoundHostIsExact(t *testing.T) { t.Fatalf("token attached to unbound url %s: %s", u, got) } } + custom := &config.Config{RepoProvider: "artifacts", RepositoryHost: "api.sam.example:8443"} + for _, u := range []string{"https://api.sam.example/git/d.git", "https://api.sam.example:443/git/d.git"} { + got, err := withGitToken(u, "samgit1.tok", custom) + if err != nil || got != u { + t.Fatalf("custom-port binding must reject default HTTPS origin: got %q, err %v", got, err) + } + } } // Positive cases the exact match must keep accepting: the control plane binds @@ -114,6 +121,13 @@ func TestWithGitTokenBoundHostCaseAndPort(t *testing.T) { {"API.Sam.Example", "https://api.sam.example/git/d.git", "https://x:t@api.sam.example/git/d.git"}, {"api.sam.example", "https://API.SAM.EXAMPLE/git/d.git", "https://x:t@API.SAM.EXAMPLE/git/d.git"}, {"api.sam.example:8443", "https://api.sam.example:8443/git/d.git", "https://x:t@api.sam.example:8443/git/d.git"}, + // WHATWG URL.host in the control plane removes the default HTTPS port. + {"api.sam.example", "https://api.sam.example:443/git/d.git", "https://x:t@api.sam.example:443/git/d.git"}, + {"api.sam.example:443", "https://api.sam.example/git/d.git", "https://x:t@api.sam.example/git/d.git"}, + {"[2001:db8::1]", "https://[2001:db8::1]:443/git/d.git", "https://x:t@[2001:db8::1]:443/git/d.git"}, + {"api.sam.example", "https://api.sam.example:0443/git/d.git", "https://x:t@api.sam.example:0443/git/d.git"}, + {"api.sam.example", "https://api.sam.example:/git/d.git", "https://x:t@api.sam.example:/git/d.git"}, + {"api.sam.example:8443", "https://api.sam.example:08443/git/d.git", "https://x:t@api.sam.example:08443/git/d.git"}, } for _, tc := range cases { cfg := &config.Config{RepoProvider: "artifacts", RepositoryHost: tc.bound} From bcc37353f3673d42dd6c7dacdc048ad397f09457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 03:35:39 +0000 Subject: [PATCH 09/11] fix(vm-agent): preserve hosted git credentials across port forms --- .../vm-agent/internal/bootstrap/bootstrap.go | 13 +- .../hosted_artifacts_helper_ports_test.go | 56 +++++++++ .../bootstrap/hosted_artifacts_host.go | 25 +--- .../internal/gitrepo/https_authority.go | 34 ++++++ .../internal/server/git_credential.go | 12 +- .../git_credential_hosted_ports_test.go | 114 ++++++++++++++++++ 6 files changed, 229 insertions(+), 25 deletions(-) create mode 100644 packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go create mode 100644 packages/vm-agent/internal/gitrepo/https_authority.go create mode 100644 packages/vm-agent/internal/server/git_credential_hosted_ports_test.go diff --git a/packages/vm-agent/internal/bootstrap/bootstrap.go b/packages/vm-agent/internal/bootstrap/bootstrap.go index d0a68c38dd..45d117b579 100644 --- a/packages/vm-agent/internal/bootstrap/bootstrap.go +++ b/packages/vm-agent/internal/bootstrap/bootstrap.go @@ -2313,6 +2313,10 @@ func renderGitCredentialHelperScript(cfg *config.Config, exchangeToken string) ( // Hostnames are case-insensitive; normalize once here and lowercase the // requested host in the shell so the comparison cannot fail on casing. allowedGitLabHost := strings.ToLower(strings.TrimSpace(cfg.RepositoryHost)) + // Hosted Artifacts authority checks have one owner: the authenticated local + // exchange validates both the workspace binding and the resolved credential. + // Forward the raw host rather than duplicating Go's port parser in POSIX sh. + delegateHostedArtifacts := isBoundHostedArtifactsHost(cfg, cfg.RepositoryHost) // When TLS is enabled on the VM agent, the credential helper must use https:// // with -k (skip cert verification) because the TLS cert is issued for the @@ -2337,14 +2341,20 @@ fi requested_host="" requested_path="" +requested_protocol="" while IFS= read -r line; do [ -z "$line" ] && break case "$line" in host=*) requested_host="${line#host=}" ;; path=*) requested_path="${line#path=}" ;; + protocol=*) requested_protocol="${line#protocol=}" ;; esac done +delegate_host_filter=%t +if [ "$delegate_host_filter" = true ]; then + [ "$requested_protocol" = https ] || exit 0 +else case "$requested_host" in ""|github.com|api.github.com|artifacts.cloudflare.net|*.artifacts.cloudflare.net) ;; *) @@ -2355,6 +2365,7 @@ case "$requested_host" in fi ;; esac +fi credential_query="%s" exchange_token=%s @@ -2398,7 +2409,7 @@ for target in host.docker.internal "$gateway" 172.17.0.1; do done exit 0 -`, shellSingleQuote(allowedGitLabHost), query, shellSingleQuote(exchangeToken), credentialTimeoutSeconds, curlTLSFlag, scheme, cfg.Port), nil +`, delegateHostedArtifacts, shellSingleQuote(allowedGitLabHost), query, shellSingleQuote(exchangeToken), credentialTimeoutSeconds, curlTLSFlag, scheme, cfg.Port), nil } // sanitizeWorkspaceID strips characters that are not alphanumeric or hyphens diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go new file mode 100644 index 0000000000..5362d903c6 --- /dev/null +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go @@ -0,0 +1,56 @@ +package bootstrap + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/workspace/vm-agent/internal/config" +) + +func TestHostedArtifactsHelperPorts(t *testing.T) { + for _, host := range []string{"api.sam.example", "api.sam.example:443", "api.sam.example:0443", "api.sam.example:"} { + t.Run(host, func(t *testing.T) { assertHostedArtifactsHelper(t, "https", host, true) }) + } + t.Run("HTTP refused", func(t *testing.T) { assertHostedArtifactsHelper(t, "http", "api.sam.example:443", false) }) +} + +func assertHostedArtifactsHelper(t *testing.T, protocol, host string, allowed bool) { + t.Helper() + cfg := &config.Config{Port: 8080, CallbackToken: "callback-not-in-script", WorkspaceID: "ws-helper-ports", RepoProvider: "artifacts", RepositoryHost: "api.sam.example"} + script, err := renderGitCredentialHelperScript(cfg, testGitCredentialExchangeToken) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + logPath := filepath.Join(dir, "curl.log") + // The local exchange network boundary records the untouched query. Its real + // binding/response refusal cases are exercised by the server route tests. + shim := fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$@\" > %s\nprintf 'username=x\\npassword=test-only\\n'\n", shellSingleQuote(logPath)) + if err := os.WriteFile(filepath.Join(dir, "curl"), []byte(shim), 0o755); err != nil { + t.Fatal(err) + } + cmd := exec.Command("sh", "-c", script, "git-credential-sam", "get") + cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH")) + cmd.Stdin = strings.NewReader("protocol=" + protocol + "\nhost=" + host + "\npath=git/repo.git\n\n") + output, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("helper execution: %v", err) + } + args, readErr := os.ReadFile(logPath) + if !allowed { + if len(output) != 0 || !os.IsNotExist(readErr) { + t.Fatal("HTTP request reached the credential exchange") + } + return + } + if readErr != nil || !strings.Contains(string(args), "host="+host) || !strings.Contains(string(output), "password=test-only") { + t.Fatal("HTTPS authority did not reach the local credential exchange unchanged") + } + if strings.Contains(script, cfg.CallbackToken) { + t.Fatal("helper exposed the broader callback bearer") + } +} diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go index 16bdac17b5..2e4e733393 100644 --- a/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_host.go @@ -1,11 +1,10 @@ package bootstrap import ( - "net" - "strconv" "strings" "github.com/workspace/vm-agent/internal/config" + "github.com/workspace/vm-agent/internal/gitrepo" ) // isBoundHostedArtifactsHost reports whether host is the repository host the @@ -19,27 +18,7 @@ func isBoundHostedArtifactsHost(cfg *config.Config, host string) bool { if cfg == nil || !strings.EqualFold(strings.TrimSpace(cfg.RepoProvider), "artifacts") { return false } - bound := canonicalHostedArtifactsAuthority(cfg.RepositoryHost) // WHATWG URL.host in the control plane omits HTTPS's default port, while // Go's URL.Host preserves it. Other ports still require an exact match. - return bound != "" && strings.EqualFold(bound, canonicalHostedArtifactsAuthority(host)) -} - -func canonicalHostedArtifactsAuthority(authority string) string { - authority = strings.TrimSpace(authority) - host, port, err := net.SplitHostPort(authority) - if err != nil { - return authority - } - if port == "" { - return strings.TrimSuffix(authority, ":") - } - number, err := strconv.ParseUint(port, 10, 16) - if err != nil { - return "" - } - if number == 443 { - return strings.TrimSuffix(authority, ":"+port) - } - return net.JoinHostPort(host, strconv.FormatUint(number, 10)) + return gitrepo.HTTPSAuthoritiesEqual(cfg.RepositoryHost, host) } diff --git a/packages/vm-agent/internal/gitrepo/https_authority.go b/packages/vm-agent/internal/gitrepo/https_authority.go new file mode 100644 index 0000000000..cd9118e56b --- /dev/null +++ b/packages/vm-agent/internal/gitrepo/https_authority.go @@ -0,0 +1,34 @@ +package gitrepo + +import ( + "net" + "strconv" + "strings" +) + +// HTTPSAuthoritiesEqual compares HTTPS origins using the control plane's WHATWG +// port representation. Empty authorities or invalid ports never match each other. +func HTTPSAuthoritiesEqual(left, right string) bool { + left = canonicalHTTPSAuthority(left) + right = canonicalHTTPSAuthority(right) + return left != "" && right != "" && strings.EqualFold(left, right) +} + +func canonicalHTTPSAuthority(authority string) string { + authority = strings.TrimSpace(authority) + host, port, err := net.SplitHostPort(authority) + if err != nil { + return authority + } + if port == "" { + return strings.TrimSuffix(authority, ":") + } + number, err := strconv.ParseUint(port, 10, 16) + if err != nil { + return "" + } + if number == 443 { + return strings.TrimSuffix(authority, ":"+port) + } + return net.JoinHostPort(host, strconv.FormatUint(number, 10)) +} diff --git a/packages/vm-agent/internal/server/git_credential.go b/packages/vm-agent/internal/server/git_credential.go index 55051ca535..0093738cbe 100644 --- a/packages/vm-agent/internal/server/git_credential.go +++ b/packages/vm-agent/internal/server/git_credential.go @@ -114,7 +114,11 @@ func (s *Server) handleGitCredential(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) return } - if requestedHost != "" && !credentialHostMatchesRequest(host, requestedHost) { + hostMatches := credentialHostMatchesRequest(host, requestedHost) + if strings.EqualFold(boundProvider, "artifacts") && (resp.Provider == "" || strings.EqualFold(resp.Provider, "artifacts")) { + hostMatches = requestedHost == "" || gitrepo.HTTPSAuthoritiesEqual(host, requestedHost) + } + if requestedHost != "" && !hostMatches { w.WriteHeader(http.StatusNoContent) return } @@ -149,8 +153,14 @@ func (s *Server) isAllowedCredentialHostForWorkspace(workspaceID, requestedHost return true } if runtime, ok := s.getWorkspaceRuntime(workspaceID); ok { + if strings.EqualFold(runtime.RepoProvider, "artifacts") { + return gitrepo.HTTPSAuthoritiesEqual(runtime.RepositoryHost, requestedHost) + } return strings.EqualFold(strings.TrimSpace(runtime.RepositoryHost), requestedHost) } + if strings.EqualFold(s.config.RepoProvider, "artifacts") { + return gitrepo.HTTPSAuthoritiesEqual(s.config.RepositoryHost, requestedHost) + } return strings.EqualFold(strings.TrimSpace(s.config.RepositoryHost), requestedHost) } diff --git a/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go b/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go new file mode 100644 index 0000000000..aea66f1e8c --- /dev/null +++ b/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go @@ -0,0 +1,114 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/workspace/vm-agent/internal/bootstrap" + "github.com/workspace/vm-agent/internal/config" +) + +func TestHostedArtifactsCredentialPorts(t *testing.T) { + for _, mode := range []string{"vm", "standalone"} { + for _, tc := range []struct { + name, bound, request, resolved string + status, calls int + }{ + {"default", "api.sam.example", "api.sam.example", "api.sam.example", 200, 1}, + {"explicit", "api.sam.example", "api.sam.example:443", "api.sam.example", 200, 1}, + {"padded", "api.sam.example", "api.sam.example:0443", "api.sam.example", 200, 1}, + {"empty port", "api.sam.example", "api.sam.example:", "api.sam.example", 200, 1}, + {"padded custom", "api.sam.example:8443", "api.sam.example:08443", "api.sam.example:8443", 200, 1}, + {"unbound", "api.sam.example", "evil.example:443", "api.sam.example", 204, 0}, + {"wrong custom", "api.sam.example:8443", "api.sam.example:443", "api.sam.example:8443", 204, 0}, + {"response mismatch", "api.sam.example", "api.sam.example:443", "evil.example", 204, 1}, + } { + t.Run(mode+"/"+tc.name, func(t *testing.T) { + assertHostedArtifactsCredentialPort(t, mode, tc.bound, tc.request, tc.resolved, tc.status, tc.calls) + }) + } + } +} + +func assertHostedArtifactsCredentialPort(t *testing.T, mode, bound, requested, resolved string, status, calls int) { + t.Helper() + var fetched atomic.Int32 + control := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fetched.Add(1) + if r.Method != http.MethodPost || r.URL.Path != "/api/workspaces/ws-ports/git-token" || r.Header.Get("Authorization") != "Bearer callback" { + t.Error("incorrect authenticated git-token callback") + } + _ = json.NewEncoder(w).Encode(gitTokenResponse{Provider: "artifacts", Token: "hosted-token", Host: resolved, Username: "x"}) + })) + defer control.Close() + s := &Server{config: &config.Config{ControlPlaneURL: control.URL, WorkspaceID: "ws-ports", CallbackToken: "callback", RepoProvider: "artifacts", RepositoryHost: bound}} + if mode == "vm" { + // The node config deliberately disagrees: VM exchanges must use the workspace binding. + s.config.WorkspaceID = "node" + s.config.RepositoryHost = "other.example" + s.workspaces = map[string]*WorkspaceRuntime{"ws-ports": {ID: "ws-ports", RepoProvider: "artifacts", RepositoryHost: bound, CallbackToken: "callback"}} + } else { + s.config.Role = config.RoleStandalone + } + req := httptest.NewRequest(http.MethodGet, "/git-credential?workspaceId=ws-ports&host="+url.QueryEscape(requested), nil) + req.Header.Set("Authorization", "Bearer callback") + rec := httptest.NewRecorder() + if mode == "standalone" { + code, output := fillHostedStandaloneCredential(t, s, requested) + rec.Code = code + _, _ = rec.Body.WriteString(output) + } else { + s.handleGitCredential(rec, req) + } + if rec.Code != status || int(fetched.Load()) != calls { + t.Fatalf("status %d, callback calls %d; want %d/%d", rec.Code, fetched.Load(), status, calls) + } + if status == http.StatusOK { + if !strings.Contains(rec.Body.String(), "username=x\npassword=hosted-token\n") { + t.Fatal("matching authority did not receive the resolved credential") + } + } else if rec.Body.Len() != 0 { + t.Fatal("refused authority received credential output") + } +} + +// Enter the standalone exchange the way a subsequent fetch/push does: Git calls +// the production shell helper, which authenticates to the real local handler. +func fillHostedStandaloneCredential(t *testing.T, agent *Server, host string) (int, string) { + t.Helper() + const workspace = "ws-ports" + lockStandaloneExchange(t, workspace) + if err := bootstrap.InstallGitCredentialExchange(workspace, testStandaloneGitCredentialExchangeToken); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = bootstrap.RemoveCredentialHelperFromHost(workspace) }) + var code atomic.Int32 + local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rec := httptest.NewRecorder() + agent.handleGitCredential(rec, r) + code.Store(int32(rec.Code)) + w.WriteHeader(rec.Code) + _, _ = w.Write(rec.Body.Bytes()) + })) + defer local.Close() + helper := filepath.Join(t.TempDir(), "helper") + if err := writeStandaloneGitCredentialHelper(helper, time.Second, testStandaloneGitCredentialExchangeToken); err != nil { + t.Fatal(err) + } + cmd := exec.Command("git", "-c", "credential.helper="+helper, "-c", "credential.useHttpPath=true", "credential", "fill") + cmd.Env = hermeticEnv("SAM_WORKSPACE_ID="+workspace, "SAM_GIT_CREDENTIAL_ENDPOINT="+local.URL+"/git-credential", "HOME="+t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0") + cmd.Stdin = strings.NewReader("protocol=https\nhost=" + host + "\npath=git/repo.git\n\n") + output, err := cmd.Output() + if (code.Load() == http.StatusOK) != (err == nil) { + t.Fatalf("Git credential fill success disagrees with the exchange status %d", code.Load()) + } + return int(code.Load()), string(output) +} From 2de1924513ed3a06ca6696b2a37107f2b1edadbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 05:03:23 +0000 Subject: [PATCH 10/11] fix(vm-agent): require HTTPS for hosted git credentials --- .../vm-agent/internal/bootstrap/bootstrap.go | 2 + .../hosted_artifacts_helper_ports_test.go | 2 +- .../internal/server/git_credential.go | 16 +++++++ .../git_credential_hosted_ports_test.go | 47 +++++++++++++++---- .../internal/server/git_credential_test.go | 2 +- .../internal/server/standalone_git.go | 5 +- 6 files changed, 62 insertions(+), 12 deletions(-) diff --git a/packages/vm-agent/internal/bootstrap/bootstrap.go b/packages/vm-agent/internal/bootstrap/bootstrap.go index 45d117b579..9e55ed5911 100644 --- a/packages/vm-agent/internal/bootstrap/bootstrap.go +++ b/packages/vm-agent/internal/bootstrap/bootstrap.go @@ -2372,6 +2372,8 @@ exchange_token=%s url_encode_query_value() { printf '%%s' "$1" | sed 's/%%/%%25/g; s/&/%%26/g; s/=/%%3D/g; s/?/%%3F/g; s/#/%%23/g; s/+/%%2B/g; s/ /%%20/g' } +encoded_protocol=$(url_encode_query_value "$requested_protocol") +credential_query="${credential_query}&protocol=${encoded_protocol}" if [ -n "$requested_host" ]; then encoded_host=$(url_encode_query_value "$requested_host") if [ -n "$credential_query" ]; then diff --git a/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go b/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go index 5362d903c6..d6a9d6179f 100644 --- a/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go +++ b/packages/vm-agent/internal/bootstrap/hosted_artifacts_helper_ports_test.go @@ -47,7 +47,7 @@ func assertHostedArtifactsHelper(t *testing.T, protocol, host string, allowed bo } return } - if readErr != nil || !strings.Contains(string(args), "host="+host) || !strings.Contains(string(output), "password=test-only") { + if readErr != nil || !strings.Contains(string(args), "host="+host) || !strings.Contains(string(args), "protocol=https") || !strings.Contains(string(output), "password=test-only") { t.Fatal("HTTPS authority did not reach the local credential exchange unchanged") } if strings.Contains(script, cfg.CallbackToken) { diff --git a/packages/vm-agent/internal/server/git_credential.go b/packages/vm-agent/internal/server/git_credential.go index 0093738cbe..648daba90b 100644 --- a/packages/vm-agent/internal/server/git_credential.go +++ b/packages/vm-agent/internal/server/git_credential.go @@ -50,6 +50,13 @@ func (s *Server) handleGitCredential(w http.ResponseWriter, r *http.Request) { // it is requesting credentials for. GitHub/Artifacts keep the empty-allow // behavior because the gh wrapper flow sends host=github.com with no path. boundProvider, _ := s.credentialPathBinding(workspaceID) + // Hosted repository write credentials are never valid for a cleartext Git + // request. Require the helper's explicit protocol before fetching a token. + requestedProtocol := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("protocol"))) + if strings.EqualFold(boundProvider, "artifacts") && requestedProtocol != "https" { + w.WriteHeader(http.StatusNoContent) + return + } if strings.EqualFold(boundProvider, "gitlab") && (requestedHost == "" || requestedPath == "") { slog.Warn("Git credential request refused: gitlab-bound workspace requires host and path", "workspaceID", workspaceID, @@ -104,6 +111,15 @@ func (s *Server) handleGitCredential(w http.ResponseWriter, r *http.Request) { // the control plane resolved. An empty resolved repositoryPath means we // cannot verify the binding — refuse rather than vend a broad OAuth token. gitlabResponse := strings.EqualFold(strings.TrimSpace(resp.Provider), "gitlab") + // The Artifacts callback predates provider tags: it returns cloneUrl while + // GitHub omits it and GitLab identifies itself explicitly. Preserve this + // legacy response contract when local provider metadata is unavailable. + artifactsResponse := strings.EqualFold(strings.TrimSpace(resp.Provider), "artifacts") || + (strings.TrimSpace(resp.Provider) == "" && strings.TrimSpace(resp.CloneURL) != "") + if artifactsResponse && requestedProtocol != "https" { + w.WriteHeader(http.StatusNoContent) + return + } if gitlabResponse && (requestedHost == "" || requestedPath == "" || repositoryPath == "") { slog.Warn("Git credential response withheld: gitlab credential requires verified host and path", "workspaceID", workspaceID, diff --git a/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go b/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go index aea66f1e8c..f0ca9ba1ba 100644 --- a/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go +++ b/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go @@ -32,13 +32,30 @@ func TestHostedArtifactsCredentialPorts(t *testing.T) { {"response mismatch", "api.sam.example", "api.sam.example:443", "evil.example", 204, 1}, } { t.Run(mode+"/"+tc.name, func(t *testing.T) { - assertHostedArtifactsCredentialPort(t, mode, tc.bound, tc.request, tc.resolved, tc.status, tc.calls) + assertHostedArtifactsCredentialPort(t, mode, "https", tc.bound, tc.request, tc.resolved, tc.status, tc.calls) }) } } } -func assertHostedArtifactsCredentialPort(t *testing.T, mode, bound, requested, resolved string, status, calls int) { +func TestHostedArtifactsCredentialProtocols(t *testing.T) { + for _, mode := range []string{"vm", "standalone", "standalone response"} { + for _, protocol := range []string{"http", "", "https"} { + t.Run(mode+"/"+protocol, func(t *testing.T) { + status, calls := 204, 0 + if mode == "standalone response" { + calls = 1 + } + if protocol == "https" { + status, calls = 200, 1 + } + assertHostedArtifactsCredentialPort(t, mode, protocol, "api.sam.example", "api.sam.example", "api.sam.example", status, calls) + }) + } + } +} + +func assertHostedArtifactsCredentialPort(t *testing.T, mode, protocol, bound, requested, resolved string, status, calls int) { t.Helper() var fetched atomic.Int32 control := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -46,7 +63,9 @@ func assertHostedArtifactsCredentialPort(t *testing.T, mode, bound, requested, r if r.Method != http.MethodPost || r.URL.Path != "/api/workspaces/ws-ports/git-token" || r.Header.Get("Authorization") != "Bearer callback" { t.Error("incorrect authenticated git-token callback") } - _ = json.NewEncoder(w).Encode(gitTokenResponse{Provider: "artifacts", Token: "hosted-token", Host: resolved, Username: "x"}) + // Match the production Artifacts callback: cloneUrl and username, no + // provider discriminator. GitLab supplies an explicit provider instead. + _ = json.NewEncoder(w).Encode(gitTokenResponse{Token: "hosted-token", CloneURL: "https://" + resolved + "/git/repo.git", Username: "x"}) })) defer control.Close() s := &Server{config: &config.Config{ControlPlaneURL: control.URL, WorkspaceID: "ws-ports", CallbackToken: "callback", RepoProvider: "artifacts", RepositoryHost: bound}} @@ -57,12 +76,17 @@ func assertHostedArtifactsCredentialPort(t *testing.T, mode, bound, requested, r s.workspaces = map[string]*WorkspaceRuntime{"ws-ports": {ID: "ws-ports", RepoProvider: "artifacts", RepositoryHost: bound, CallbackToken: "callback"}} } else { s.config.Role = config.RoleStandalone + if mode == "standalone response" { + // Legacy/absent local provider metadata must not bypass the resolved + // Artifacts credential's response-side HTTPS requirement. + s.config.RepoProvider = "" + } } - req := httptest.NewRequest(http.MethodGet, "/git-credential?workspaceId=ws-ports&host="+url.QueryEscape(requested), nil) + req := httptest.NewRequest(http.MethodGet, "/git-credential?workspaceId=ws-ports&protocol="+url.QueryEscape(protocol)+"&host="+url.QueryEscape(requested), nil) req.Header.Set("Authorization", "Bearer callback") rec := httptest.NewRecorder() - if mode == "standalone" { - code, output := fillHostedStandaloneCredential(t, s, requested) + if mode != "vm" { + code, output := fillHostedStandaloneCredential(t, s, requested, protocol) rec.Code = code _, _ = rec.Body.WriteString(output) } else { @@ -82,7 +106,7 @@ func assertHostedArtifactsCredentialPort(t *testing.T, mode, bound, requested, r // Enter the standalone exchange the way a subsequent fetch/push does: Git calls // the production shell helper, which authenticates to the real local handler. -func fillHostedStandaloneCredential(t *testing.T, agent *Server, host string) (int, string) { +func fillHostedStandaloneCredential(t *testing.T, agent *Server, host, protocol string) (int, string) { t.Helper() const workspace = "ws-ports" lockStandaloneExchange(t, workspace) @@ -104,10 +128,15 @@ func fillHostedStandaloneCredential(t *testing.T, agent *Server, host string) (i t.Fatal(err) } cmd := exec.Command("git", "-c", "credential.helper="+helper, "-c", "credential.useHttpPath=true", "credential", "fill") + if protocol == "" { + // Git refuses an absent protocol before invoking helpers; drive the real + // helper directly to verify the exchange also refuses that input. + cmd = exec.Command(helper, "get") + } cmd.Env = hermeticEnv("SAM_WORKSPACE_ID="+workspace, "SAM_GIT_CREDENTIAL_ENDPOINT="+local.URL+"/git-credential", "HOME="+t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0") - cmd.Stdin = strings.NewReader("protocol=https\nhost=" + host + "\npath=git/repo.git\n\n") + cmd.Stdin = strings.NewReader("protocol=" + protocol + "\nhost=" + host + "\npath=git/repo.git\n\n") output, err := cmd.Output() - if (code.Load() == http.StatusOK) != (err == nil) { + if protocol != "" && (code.Load() == http.StatusOK) != (err == nil) { t.Fatalf("Git credential fill success disagrees with the exchange status %d", code.Load()) } return int(code.Load()), string(output) diff --git a/packages/vm-agent/internal/server/git_credential_test.go b/packages/vm-agent/internal/server/git_credential_test.go index e5f5708870..5ec2031aab 100644 --- a/packages/vm-agent/internal/server/git_credential_test.go +++ b/packages/vm-agent/internal/server/git_credential_test.go @@ -164,7 +164,7 @@ func TestHandleGitCredentialRespectsRequestedHostProvider(t *testing.T) { }, } - req := httptest.NewRequest(http.MethodGet, "/git-credential?workspaceId=ws-123&host="+tc.queryHost, nil) + req := httptest.NewRequest(http.MethodGet, "/git-credential?workspaceId=ws-123&protocol=https&host="+tc.queryHost, nil) req.Header.Set("Authorization", "Bearer callback-token") rec := httptest.NewRecorder() diff --git a/packages/vm-agent/internal/server/standalone_git.go b/packages/vm-agent/internal/server/standalone_git.go index eb7688ebe2..ab373d1d7f 100644 --- a/packages/vm-agent/internal/server/standalone_git.go +++ b/packages/vm-agent/internal/server/standalone_git.go @@ -32,11 +32,13 @@ const standaloneGitCredentialHelperScriptTemplate = `#!/bin/sh [ "${1:-get}" = "get" ] || exit 0 host="" path="" +protocol="" while IFS= read -r line; do [ -z "$line" ] && break case "$line" in host=*) host="${line#host=}" ;; path=*) path="${line#path=}" ;; + protocol=*) protocol="${line#protocol=}" ;; esac done [ -n "$host" ] || exit 0 @@ -61,7 +63,8 @@ fi workspace_id=$(url_encode_query_value "$SAM_WORKSPACE_ID") encoded_host=$(url_encode_query_value "$host") -credential_query="workspaceId=${workspace_id}&host=${encoded_host}" +encoded_protocol=$(url_encode_query_value "$protocol") +credential_query="workspaceId=${workspace_id}&host=${encoded_host}&protocol=${encoded_protocol}" if [ -n "$path" ]; then encoded_path=$(url_encode_query_value "$path") credential_query="${credential_query}&path=${encoded_path}" From 5ced63386992ce4fac75f9af33174cd64044bdd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Wed, 18 Nov 2026 05:13:20 +0000 Subject: [PATCH 11/11] test(vm-agent): group hosted credential expectations --- .../server/git_credential_hosted_ports_test.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go b/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go index f0ca9ba1ba..5b4f17acc4 100644 --- a/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go +++ b/packages/vm-agent/internal/server/git_credential_hosted_ports_test.go @@ -32,7 +32,7 @@ func TestHostedArtifactsCredentialPorts(t *testing.T) { {"response mismatch", "api.sam.example", "api.sam.example:443", "evil.example", 204, 1}, } { t.Run(mode+"/"+tc.name, func(t *testing.T) { - assertHostedArtifactsCredentialPort(t, mode, "https", tc.bound, tc.request, tc.resolved, tc.status, tc.calls) + assertHostedArtifactsCredentialPort(t, mode, "https", tc.bound, tc.request, tc.resolved, hostedCredentialExpectation{tc.status, tc.calls}) }) } } @@ -49,13 +49,17 @@ func TestHostedArtifactsCredentialProtocols(t *testing.T) { if protocol == "https" { status, calls = 200, 1 } - assertHostedArtifactsCredentialPort(t, mode, protocol, "api.sam.example", "api.sam.example", "api.sam.example", status, calls) + assertHostedArtifactsCredentialPort(t, mode, protocol, "api.sam.example", "api.sam.example", "api.sam.example", hostedCredentialExpectation{status, calls}) }) } } } -func assertHostedArtifactsCredentialPort(t *testing.T, mode, protocol, bound, requested, resolved string, status, calls int) { +type hostedCredentialExpectation struct { + status, calls int +} + +func assertHostedArtifactsCredentialPort(t *testing.T, mode, protocol, bound, requested, resolved string, expected hostedCredentialExpectation) { t.Helper() var fetched atomic.Int32 control := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -92,10 +96,10 @@ func assertHostedArtifactsCredentialPort(t *testing.T, mode, protocol, bound, re } else { s.handleGitCredential(rec, req) } - if rec.Code != status || int(fetched.Load()) != calls { - t.Fatalf("status %d, callback calls %d; want %d/%d", rec.Code, fetched.Load(), status, calls) + if rec.Code != expected.status || int(fetched.Load()) != expected.calls { + t.Fatalf("status %d, callback calls %d; want %d/%d", rec.Code, fetched.Load(), expected.status, expected.calls) } - if status == http.StatusOK { + if expected.status == http.StatusOK { if !strings.Contains(rec.Body.String(), "username=x\npassword=hosted-token\n") { t.Fatal("matching authority did not receive the resolved credential") }