Files
coder/codersdk/deployment_registry_test.go
T
Jeremy Ruppel c73f34c35d feat: honor the deployment registry mirror in template builder bases (#28727)
## Summary

Threads the deployment's configured module registry
(`CODER_TEMPLATE_BUILDER_REGISTRY_URL`) into template-builder **base**
rendering, so a base that embeds a catalog module (e.g. the quickstart
base's `git-clone`) resolves its `source` through a registry mirror the
same way wizard-composed modules already do. Previously base-embedded
module sources hardcoded `registry.coder.com`, so on a
mirror/private-registry deployment a base-embedded module reached the
public registry while wizard modules used the mirror.

Implements [DOCS-610](https://linear.app/codercom/issue/DOCS-610).

## What changed

* `BaseRenderContext.RegistryBase` (new field), mirroring
`ModuleRenderContext.RegistryBase`. `Compose` threads the deployment
registry through `renderBase` into the base render context, and the four
hardcoded base module sources (`quickstart` git-clone,
`azure-linux`/`gcp-linux`/`gcp-windows` region modules) now use `{{
.RegistryBase }}`. Because the value defaults back to
`registry.coder.com`, rendered sources stay byte-identical; the only
golden change is the removal of the now-stale quickstart "follow-up"
note.
* **Boot-time validation.**
`codersdk.ValidateTemplateBuilderRegistryURL` runs in
`DeploymentValues.Validate()`, gated on the builder being enabled,
matching the chat-hook precedent. A malformed value fails at server
start naming the option, instead of surfacing as a per-request error to
a template author who cannot fix it. It uses `net/url` in authority form
to reject a scheme, path, query, fragment, trailing slash, or
credentials and accept a bare `host[:port]`; it does not canonicalize
the host.
* `Compose` **trusts the validated value**, defaulting an unset one and
defensively rejecting a malformed one for direct callers that bypass
boot.

## Tests

* `codersdk`: validator accept/reject matrix (incl.
credentials-without-echo) and a `DeploymentValues.Validate` boundary
test with a disabled-skips-validation case.
* `templatebuilder`: a base honors the mirror and falls back to the
default when unset, plus a defensive-reject case; existing compose tests
updated to bare-host registry values.

<details><summary>Design decision log</summary>

This PR is a deliberately minimal reimplementation of the
[DOCS-610](https://linear.app/codercom/issue/DOCS-610/template-builder-base-embedded-modules-should-honor-the-deployment)
scope, started fresh from `main` rather than carrying forward an
earlier, larger draft (coder/coder#28480). Key decisions:

* **Scope kept to the ticket.** The ticket's fix is three bullets: add a
registry field to `BaseRenderContext`, thread the deployment
`RegistryURL` through `Compose` -> `renderBase`, and use it in base
module sources. Independent hardening explored in the earlier draft was
dropped as out of scope: `terraform-svchost`-based IDN/punycode/port
canonicalization, a rendered-HCL backstop with a 500 mapping, and HCL
module-source extraction helpers. Telemetry misclassification of mirror
modules is tracked separately
([DOCS-712](https://linear.app/codercom/issue/DOCS-712/telemetry-misclassifies-registry-mirror-modules-as-non-coder))
and is not addressed here.
* **Default lives in the render layer.**
`templatebuilder.DefaultRegistryBase` holds the fallback host;
`codersdk` keeps its own option-default literal. An earlier version
exported the constant from `codersdk`, which only emitted a dead
`typesGenerated.ts` entry that nothing in the frontend consumed, so it
was moved out. The `codersdk` validator is a function, so it generates
no TS type.
* **Validate at the config boundary, fail fast.** The repo convention is
to hard-fail structurally invalid config in
`DeploymentValues.Validate()` (access URL, OAuth lifetimes, chat hook
URL) and to warn only for functional-but-risky settings. A malformed
registry host is structurally invalid, so it fails at boot. This also
puts the error in front of the admin who set it, rather than a template
author hitting a per-request error they cannot fix.
* `net/url`**, not a regex.** The codebase validates identifiers/names
with regexes but host/URL-shaped config with `url.Parse` (chat hook URL,
OAuth redirect URIs, AI provider base URL). This value is host-shaped,
so it follows that convention. `url.Parse("//" + v)` with `u.Host == v`
rejects a scheme/path/query/fragment/trailing-slash in one check.

</details>

> This PR was created with AI assistance (Coder Agents).
2026-08-31 09:32:24 -04:00

129 lines
4.4 KiB
Go

package codersdk_test
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func TestNormalizeTemplateBuilderRegistryURL(t *testing.T) {
t.Parallel()
t.Run("Accepts", func(t *testing.T) {
t.Parallel()
cases := []struct {
name string
in string
want string
}{
{"Empty", "", ""},
{"WhitespaceOnly", " ", ""},
{"BareHost", "registry.coder.com", "registry.coder.com"},
{"SurroundingSpaceTrimmed", " mirror.internal ", "mirror.internal"},
{"HostPort", "mirror.example.com:8443", "mirror.example.com:8443"},
{"IPv6HostPort", "[::1]:8443", "[::1]:8443"},
// An accidental scheme and trailing slash are stripped rather than
// rejected, so a value pasted as a URL still resolves to a host.
{"HTTPSStripped", "https://mirror.example.com", "mirror.example.com"},
{"HTTPStripped", "http://mirror.example.com", "mirror.example.com"},
{"TrailingSlashStripped", "mirror.example.com/", "mirror.example.com"},
{"SchemePortAndSlash", "https://mirror.example.com:8443/", "mirror.example.com:8443"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got, err := codersdk.NormalizeTemplateBuilderRegistryURL(tc.in)
require.NoError(t, err)
require.Equal(t, tc.want, got)
})
}
})
t.Run("Rejects", func(t *testing.T) {
t.Parallel()
cases := []struct {
name string
in string
}{
{"Path", "mirror.example.com/coder"},
{"NonHTTPScheme", "git://mirror.example.com"},
{"UppercaseScheme", "HTTPS://mirror.example.com"},
{"SchemeAndPath", "https://mirror.example.com/coder"},
{"Query", "mirror.example.com?a=b"},
{"Fragment", "mirror.example.com#frag"},
{"DoubledScheme", "https://https://mirror.example.com"},
{"InteriorSpace", "mirror .example.com"},
{"PortOnly", ":8443"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
_, err := codersdk.NormalizeTemplateBuilderRegistryURL(tc.in)
require.ErrorContains(t, err, "bare host")
})
}
})
t.Run("RejectsCredentialsWithoutEcho", func(t *testing.T) {
t.Parallel()
// Userinfo survives the scheme strip and must be rejected, not accepted,
// and the rejection must not echo the credential.
_, err := codersdk.NormalizeTemplateBuilderRegistryURL("https://user:s3cr3t-token@mirror.example.com")
require.ErrorContains(t, err, "bare host")
require.NotContains(t, err.Error(), "s3cr3t-token")
})
}
// TestDeploymentValues_Validate_TemplateBuilderRegistryURL covers the config
// boundary: a malformed CODER_TEMPLATE_BUILDER_REGISTRY_URL must fail at server
// start naming the option, but must not block boot when the builder is disabled.
func TestDeploymentValues_Validate_TemplateBuilderRegistryURL(t *testing.T) {
t.Parallel()
// mkValid returns a DeploymentValues that passes Validate() except for the
// template builder registry URL, so that check is what each case exercises.
mkValid := func() *codersdk.DeploymentValues {
dv := &codersdk.DeploymentValues{}
dv.Sessions.DefaultDuration = serpent.Duration(time.Hour)
dv.Sessions.RefreshDefaultDuration = serpent.Duration(48 * time.Hour)
return dv
}
cases := []struct {
name string
url string
disabled bool
wantErr string
}{
{name: "EmptyOK"},
{name: "BareHostOK", url: "mirror.internal.example"},
{name: "HostPortOK", url: "mirror.internal.example:8443"},
// A scheme is stripped, not rejected, so an existing deployment that set
// a scheme'd value keeps booting after upgrade.
{name: "SchemeStrippedOK", url: "https://mirror.internal.example"},
{name: "PathRejected", url: "mirror.internal.example/coder", wantErr: "bare host"},
{name: "CredentialsRejected", url: "https://user:tok@mirror.example.com", wantErr: "bare host"},
// A disabled template builder must not block boot on an inert value, so
// tightening the check in an upgrade cannot take down a disabled deployment.
{name: "DisabledSkipsValidation", url: "https://user:tok@mirror.example.com/bad", disabled: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
dv := mkValid()
dv.TemplateBuilder.Disabled = serpent.Bool(tc.disabled)
dv.TemplateBuilder.RegistryURL = serpent.String(tc.url)
err := dv.Validate()
if tc.wantErr == "" {
require.NoError(t, err)
return
}
require.ErrorContains(t, err, tc.wantErr)
})
}
}