mod: answer for our module names, read from the forge

A module path is identity, not an address: `module github.com/hanzoai/o11y` is
what every dependent's go.mod names, so the toolchain took a direct VCS fetch to
github.com and needed a credential valid there. This answers for the name and
reads the source from git.hanzo.ai, so a build resolves the module it already
names with no GitHub credential in it.

Resolution is the toolchain's own — module zips have rules about nested modules,
vendor directories, symlinks, file modes and case collisions, and a zip that gets
one wrong hashes differently and fails every caller's go.sum.

Clients set GOPROXY and GONOSUMDB. Not GOPRIVATE: it means "bypass the proxy AND
the checksum database", and bypassing the proxy is what reaches for github.com.
Skipping the public checksum database for our namespaces is not skipping
verification — go.sum still pins every module and is checked against these bytes.

Inside our namespaces a failure answers 502, never 404: in this protocol 404
means "ask the next proxy", and the next proxy is public.
This commit is contained in:
zooqueen
2026-08-19 22:32:24 -07:00
commit f20c02ec0a
14 changed files with 966 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
.git
.github
.hanzo
README.md
+2
View File
@@ -0,0 +1,2 @@
/mod
/out
+25
View File
@@ -0,0 +1,25 @@
name: CI/CD
# The caller, and deliberately nothing else: triggers plus the import. All real
# config is the repo-root hanzo.yml, which platform.hanzo.ai reads too.
#
# `.hanzo/workflows`, NOT `.github/workflows`: the `git-runner` StatefulSet
# registers against the forge only, and that is the pool advertising the
# `hanzo-build-linux-amd64` label. A job asking for it on github.com is never
# claimed — it waits out the timeout rather than failing.
on:
push:
branches: [main]
# A `v*` tag is a RELEASE and publishes an image named after it, verbatim.
tags: ['v*']
workflow_dispatch:
concurrency:
group: cicd-${{ github.ref }}
cancel-in-progress: true
jobs:
cicd:
uses: hanzoai/ci/.hanzo/workflows/build.yml@v1
secrets: inherit
Symlink
+1
View File
@@ -0,0 +1 @@
LLM.md
+34
View File
@@ -0,0 +1,34 @@
# syntax=docker/dockerfile:1
# mod — the Go module proxy.
#
# The runtime keeps the Go toolchain and git, and that is deliberate: resolution
# is the toolchain's own. A module zip has rules about nested modules, vendor
# directories, symlinks, file modes and case collisions, and a zip that gets any
# of them wrong hashes differently and fails every caller's go.sum. Shipping the
# toolchain costs a bigger image and buys the one implementation of that which is
# known to be right.
#
# Built in CI on the self-hosted amd64 scale set, never on a developer's laptop.
FROM golang:1.26.5-bookworm AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -ldflags="-s -w" -o /out/mod .
FROM golang:1.26.5-bookworm
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build /out/mod /usr/local/bin/mod
# ROOT holds the scratch module and the module cache. Mount durable storage
# here: the cache is what keeps a module available after its origin is gone, and
# nothing prunes it.
ENV ROOT=/var/lib/mod ADDR=:8080
RUN useradd --system --uid 10001 --home-dir /var/lib/mod --create-home mod
USER 10001
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/mod"]
+203
View File
@@ -0,0 +1,203 @@
Copyright (c) 2026 Hanzo AI Inc.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2026 Hanzo AI Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+62
View File
@@ -0,0 +1,62 @@
# mod — working notes
The Go module proxy. Read `README.md` first for what it is and how it is
configured; this file holds the decisions behind it.
## Why this exists rather than the alternatives
Our private Go modules declare github paths, so the toolchain took a direct VCS
fetch to github.com and needed a credential valid there. Every GitHub credential
in the estate is a personal OAuth token. Three ways out were on the table:
1. **A proxy we own** — this. The module path is answered by us and read from the
forge. One change in the client, no credential in the build, and module
identity is untouched.
2. **Migrate the module paths** to a git.hanzo.ai host. Cleanest in principle,
and the blast radius is why it is not the answer: 190 module definitions, 124
dependent `go.mod` files, ~21,500 importing `.go` files in the hanzo tree
alone, plus 33 required paths that are not even checked out locally.
3. **A machine credential at GitHub.** Keeps the dependency, only changes whose
name is on it. It is the only option that serves genuinely public consumers of
our modules — which is what the GitHub mirror is for — but it does nothing for
our own builds.
The forge already had half of (1): `routers/api/packages/goproxy` in `hanzoai/git`
is a read-through cache of the public ecosystem with a server-side private-path
guard, and it is live. It cannot be the build-time proxy, for two reasons worth
keeping: its auth is package-scoped (the build's forge token is
`write:repository`, and broadening it is not on the table), and it is a registry
of what has been PUBLISHED to it — it has no way to resolve a module from the
repository whose source it is holding. Those are different jobs.
## The boundary that matters
`GOPRIVATE` is the wrong knob and reaching for it is the original bug. It means
"bypass the proxy AND the checksum database", and bypassing the proxy is exactly
what sends the toolchain to github.com. Clients set `GOPROXY` and `GONOSUMDB`
and nothing else.
Skipping the public checksum database for our namespaces is not skipping
verification. `go.sum` pins every module, ours included, and is checked against
the bytes served here. The proof is that the hashes this proxy produces are
byte-identical to the ones committed when GitHub served the same tags.
## The 404 rule
In the GOPROXY protocol 404 means "ask the next proxy". Inside our namespaces a
404 would therefore hand an unreleased repository's name to a public service. So
a failure inside our namespaces is 502 and the walk ends. `TestPrivateFailure
NeverFallsThrough` is the test that holds this; do not "fix" it to return 404.
## Retention
The module cache is the retention mechanism and nothing prunes it. Give `ROOT`
durable storage. This is not an optimization: `github.com/hanzoai/s3-go` is
required by `hanzoai/cloud`, `gateway` and `amqp`, and its GitHub repository no
longer exists. It resolves here because the forge holds it.
Two others are in the same state and this proxy does NOT save them, because
nothing holds them: `hanzoai/gh` (required by `docdb/tools`) and `hanzoai/xfail`
(required by `docdb/integration`) are absent from github.com, from the public
proxy, and from the forge. They need a source before any proxy can serve them;
their likely upstreams are `FerretDB/gh` and `FerretDB/xfail`, both public.
+60
View File
@@ -0,0 +1,60 @@
# mod
The Go module proxy for the estate.
A module path is identity, not an address. `module github.com/hanzoai/o11y` is
the name every dependent's `go.mod` writes down, and changing it rewrites every
dependent. The source, meanwhile, lives on git.hanzo.ai. This service is where
those two facts meet: it answers for the name and reads from the forge, so a
build resolves the module it already names without dialing the host in the name.
## Configuration
Clients need two variables:
```sh
GOPROXY=http://mod.hanzo.svc.cluster.local
GONOSUMDB=github.com/hanzoai
```
`GOPROXY` is where modules come from. `GONOSUMDB` names the paths the public
checksum database must not be asked about — it cannot have seen them, and asking
publishes the path. It drops a lookup, not the verification: `go.sum` still pins
every module, including these, and a mismatch still fails the build.
Do not set `GOPRIVATE` for these paths. `GOPRIVATE` is shorthand for "bypass the
proxy AND the checksum database", and bypassing the proxy is what sends the
toolchain to github.com with a credential.
The server reads:
| variable | default | meaning |
|---|---|---|
| `FORGE` | `https://git.hanzo.ai` | where our source lives |
| `FORGE_TOKEN` | — | credential for the forge, from KMS |
| `NAMESPACES` | `github.com/hanzoai` | module prefixes this proxy answers for |
| `UPSTREAM` | `https://proxy.golang.org` | where everything else resolves |
| `ROOT` | `/var/lib/mod` | scratch module and module cache |
| `ADDR` | `:8080` | listen address |
## What it guarantees
**Our namespaces.** Resolved from the forge, which holds the source and its
tags. GitHub is not consulted and no GitHub credential is involved. This is
total, not best-effort: it does not matter what happens to the GitHub repository
— `github.com/hanzoai/s3-go` no longer exists there and still resolves here.
**Everything else.** Resolved from the public proxy and kept. Nothing prunes the
cache, so a module that came through once stays available if its origin
disappears. This covers what we have already served and nothing we have never
fetched — the difference between holding our own copy and trusting someone
else's retention.
**Paths stay in.** A module in our namespaces that cannot be resolved answers
502, never 404. In the GOPROXY protocol 404 means "ask the next proxy", and the
next proxy is public; 502 ends the walk. So a failure here cannot turn into the
name of an unreleased repository travelling to a third party.
**Credentials stay in.** The forge token reaches git through the environment of
each child process — never a config file, never an image layer — and is removed
from any text on its way to a log or a response.
+5
View File
@@ -0,0 +1,5 @@
module github.com/hanzoai/mod
go 1.26
require golang.org/x/mod v0.38.0
+2
View File
@@ -0,0 +1,2 @@
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
+47
View File
@@ -0,0 +1,47 @@
# mod — the ONE file that says how this repo builds, gates and ships.
#
# The only workflow is `.hanzo/workflows/cicd.yml`, which imports hanzoai/ci.
# Everything real is here, and platform.hanzo.ai reads this same file.
# GOWORK=off so a go.work in a parent directory cannot change which modules
# resolve — CI must read this repo's go.mod and nothing else.
test:
- name: go-build
run: |
set -e
export GOWORK=off CGO_ENABLED=0
go build ./...
- name: go-vet
run: |
set -e
export GOWORK=off CGO_ENABLED=0
go vet ./...
- name: go-test
# The tests that matter here answer one question: what does this proxy tell
# the go command to do when it cannot resolve something. A 404 inside our
# namespaces sends the go command to the next proxy carrying the module
# path, and the next proxy is public — so the boundary is asserted, not
# assumed. They need no network: the fixture points at a forge that cannot
# resolve, which is exactly the failing case under test.
run: |
set -e
export GOWORK=off CGO_ENABLED=0
go test -count=1 ./...
version: 0.1.0
images:
- name: mod
context: .
dockerfile: Dockerfile
repo: ghcr.io/hanzoai/mod
# amd64 only: the cluster has no arm64 nodes. Add linux/arm64 when
# something pulls it.
platforms: [linux/amd64]
# No `deploy:`. Which build runs is a reviewed change in hanzoai/universe,
# synced by cd.hanzo.ai. Every Go build in the estate resolves through this
# service, so "which binary is answering for our module names" is not something
# that should move as a CI side effect.
+61
View File
@@ -0,0 +1,61 @@
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
// Configuration is read from the environment because every value here is
// deployment wiring — where the forge is, which namespaces we answer for — and
// none of it is a runtime policy anyone edits.
func main() {
forge := env("FORGE", "https://git.hanzo.ai")
token := os.Getenv("FORGE_TOKEN")
addr := env("ADDR", ":8080")
root := env("ROOT", "/var/lib/mod")
names := strings.Split(env("NAMESPACES", "github.com/hanzoai"), ",")
for i, n := range names {
names[i] = strings.Trim(strings.TrimSpace(n), "/")
}
dir := filepath.Join(root, "scratch")
if err := os.MkdirAll(dir, 0o700); err != nil {
log.Fatal(err)
}
// One scratch module gives the toolchain the module context its resolution
// commands need. It requires nothing and builds nothing.
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module scratch\n"), 0o600); err != nil {
log.Fatal(err)
}
p := &Proxy{
Namespaces: names,
Forge: strings.TrimSuffix(forge, "/"),
Upstream: env("UPSTREAM", "https://proxy.golang.org"),
Token: token,
Dir: dir,
Cache: filepath.Join(root, "cache"),
}
mux := http.NewServeMux()
mux.Handle("/", p)
// Liveness has to answer without touching the forge, or a forge blip
// restarts a proxy that is working.
mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("ok\n"))
})
log.Printf("mod: serving %s from %s on %s", strings.Join(names, " "), p.Forge, addr)
log.Fatal(http.ListenAndServe(addr, mux))
}
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
+288
View File
@@ -0,0 +1,288 @@
// Package main serves the Go module proxy protocol for modules whose source
// lives on our forge.
//
// A module path is identity, not an address: `module github.com/hanzoai/o11y`
// is the name every dependent's go.mod writes down, and renaming it would
// rewrite every dependent. The source, meanwhile, lives on git.hanzo.ai. A
// proxy is where those two facts meet — it answers for the name and reads from
// the forge, so a build resolves the module it already names without ever
// dialing the host in the name.
//
// It answers for every module, not only ours. A module in one of our
// namespaces resolves from the forge; anything else resolves from the public
// proxy. Both land in one module cache and stay there, which is the difference
// between depending on a copy someone else keeps and holding our own: a module
// whose origin disappears is still here. That is not hypothetical —
// github.com/hanzoai/s3-go is a dependency of the forge's own build and its
// GitHub repository no longer exists, while the forge holds the source and its
// tags.
//
// The guarantee has a shape worth stating: for our namespaces it is total,
// because the forge is the source rather than a copy of one. For a third-party
// module it covers what we have already served — this cache does not evict, so
// a module that came through once remains available — and nothing we have never
// fetched.
//
// Protocol: https://go.dev/ref/mod#goproxy-protocol
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"strings"
"golang.org/x/mod/module"
)
// Proxy answers for a set of module namespaces, resolving each from the forge.
type Proxy struct {
// Namespaces are the module path prefixes this proxy is authoritative for,
// each of the form `<host>/<org>`. A module under one of them resolves from
// the forge; anything else is somebody else's to answer.
Namespaces []string
// Forge is the base URL that holds the source, e.g. https://git.hanzo.ai.
Forge string
// Upstream resolves everything outside our namespaces.
Upstream string
// Token authenticates to the forge. It is passed to git through the
// environment of each child process and is never written to a file.
Token string
// Dir is the scratch module the toolchain resolves in, and the HOME those
// children see.
Dir string
// Cache is GOMODCACHE, where resolved modules are kept. Warm, this is the
// whole cost of a request: a file read. Nothing prunes it — retention is the
// point, so give it durable storage.
Cache string
}
// verbs are the five requests the protocol defines.
const (
list = "list"
latest = "latest"
info = "info"
gomod = "mod"
zip = "zip"
)
// ask is one parsed protocol request.
type ask struct {
module string // unescaped module path
verb string
version string // unescaped; empty for list and latest
}
// parse reads a request path. Module paths and versions arrive case-escaped
// (an upper-case letter as "!" + lower), so they are unescaped here and every
// decision below is made on the real path — the alternative is a namespace
// check that `GitHub.com/HanzoAI/x` walks straight past.
func parse(p string) (ask, bool) {
p = strings.TrimPrefix(p, "/")
if raw, ok := strings.CutSuffix(p, "/@latest"); ok {
m, err := module.UnescapePath(raw)
if err != nil {
return ask{}, false
}
return ask{module: m, verb: latest}, true
}
i := strings.Index(p, "/@v/")
if i < 0 {
return ask{}, false
}
m, err := module.UnescapePath(p[:i])
if err != nil {
return ask{}, false
}
rest := p[i+len("/@v/"):]
if rest == list {
return ask{module: m, verb: list}, true
}
ext := path.Ext(rest)
switch ext {
case ".info", ".mod", ".zip":
default:
return ask{}, false
}
v, err := module.UnescapeVersion(strings.TrimSuffix(rest, ext))
if err != nil {
return ask{}, false
}
return ask{module: m, verb: ext[1:], version: v}, true
}
// ours reports whether a module path falls in one of our namespaces.
//
// The trailing separator is what makes this a namespace test rather than a
// string test: without it `github.com/hanzoaiX/evil` is inside
// `github.com/hanzoai`, and a stranger picks the namespace they resolve from.
func (p *Proxy) ours(mod string) bool {
for _, ns := range p.Namespaces {
if mod == ns || strings.HasPrefix(mod, ns+"/") {
return true
}
}
return false
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req, ok := parse(r.URL.Path)
if !ok {
http.NotFound(w, r)
return
}
ours := p.ours(req.module)
err := p.answer(w, req, ours)
if err == nil {
return
}
if !ours {
// A public module we could not resolve. 404 is this protocol's "ask the
// next proxy", and for a public path there is nothing to protect.
http.NotFound(w, r)
return
}
// Inside our namespaces a 404 would send the go command onward carrying the
// module path, and onward is public. Any other status ends the walk, so a
// module we could not resolve stays a module nobody else hears about.
http.Error(w, "resolve "+req.module+": "+err.Error(), http.StatusBadGateway)
}
func (p *Proxy) answer(w http.ResponseWriter, req ask, ours bool) error {
if req.verb == list {
out, err := p.run(ours, "list", "-m", "-versions", req.module)
if err != nil {
return err
}
// `go list -m -versions` prints the path then its versions, space
// separated. The protocol wants one version per line and no path.
fields := strings.Fields(string(out))
if len(fields) == 0 {
return errors.New("no version list for " + req.module)
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
for _, v := range fields[1:] {
fmt.Fprintln(w, v)
}
return nil
}
version := req.version
if req.verb == latest {
version = latest
}
out, err := p.run(ours, "mod", "download", "-json", req.module+"@"+version)
if err != nil {
return err
}
var got struct {
Info, GoMod, Zip, Error string
}
if err := json.Unmarshal(out, &got); err != nil {
return err
}
if got.Error != "" {
return errors.New(scrub(got.Error, p.Token))
}
// The toolchain wrote the three artifacts; serving them is a file read. They
// are byte-identical to what a direct fetch produces, which is what lets the
// caller's go.sum verify them unchanged.
file, mime := got.Info, "application/json"
switch req.verb {
case gomod:
file, mime = got.GoMod, "text/plain; charset=utf-8"
case zip:
file, mime = got.Zip, "application/zip"
}
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
w.Header().Set("Content-Type", mime)
_, err = io.Copy(w, f)
return err
}
// run invokes the toolchain in the scratch module.
//
// Resolution is the toolchain's own, not a second implementation of it: module
// zips have rules about nested modules, vendor directories, symlinks, file
// modes and case collisions, and a zip that gets any of them wrong hashes
// differently and fails every caller's go.sum. The one correct implementation
// of that is the one shipped with Go.
func (p *Proxy) run(ours bool, args ...string) ([]byte, error) {
cmd := exec.Command("go", args...)
cmd.Dir = p.Dir
cmd.Env = p.env(ours)
var stdout, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
if err != nil && stdout.Len() == 0 {
return nil, errors.New(scrub(strings.TrimSpace(stderr.String()), p.Token))
}
return stdout.Bytes(), nil
}
func (p *Proxy) env(ours bool) []string {
// Where the bytes come from is the one thing that differs between a module
// of ours and anyone else's: ours has a forge holding its source, and git
// reaches it directly. Everything else has a public proxy.
from := p.Upstream
if ours {
from = "direct"
}
ns := strings.Join(p.Namespaces, ",")
env := []string{
"HOME=" + p.Dir,
"PATH=" + os.Getenv("PATH"),
"GOMODCACHE=" + p.Cache,
"GOFLAGS=-mod=mod",
"GOPROXY=" + from,
// The public checksum database cannot have seen these modules and asking
// it would publish the path. The caller's go.sum still pins every one of
// them, so this drops a lookup, not the verification.
"GOPRIVATE=" + ns,
"GONOSUMDB=" + ns,
// Resolve with the toolchain in the image. Fetching another one would
// need the network we are the network for.
"GOTOOLCHAIN=local",
}
// Point git at the forge for the length of this process. Config in the
// environment rather than a file keeps the credential out of the image, out
// of any layer, and out of every other process on the box.
var i int
for _, n := range p.Namespaces {
org := n[strings.LastIndex(n, "/")+1:]
env = append(env,
fmt.Sprintf("GIT_CONFIG_KEY_%d=url.%s/%s/.insteadOf", i, p.forgeWithToken(), org),
fmt.Sprintf("GIT_CONFIG_VALUE_%d=https://%s/", i, n),
)
i++
}
env = append(env, fmt.Sprintf("GIT_CONFIG_COUNT=%d", i), "GIT_TERMINAL_PROMPT=0")
return env
}
// forgeWithToken is the forge URL git dials, carrying the credential.
func (p *Proxy) forgeWithToken() string {
host, _ := strings.CutPrefix(p.Forge, "https://")
return "https://x:" + p.Token + "@" + host
}
// scrub removes the credential from text on its way to a log or a response.
// git quotes the URL it was given in most of its errors, and that URL carries
// the token.
func scrub(s, token string) string {
if token == "" {
return s
}
return strings.ReplaceAll(s, token, "…")
}
+172
View File
@@ -0,0 +1,172 @@
package main
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestParse(t *testing.T) {
for _, c := range []struct {
path string
want ask
ok bool
}{
{"/github.com/hanzoai/o11y/@v/list", ask{"github.com/hanzoai/o11y", list, ""}, true},
{"/github.com/hanzoai/o11y/@latest", ask{"github.com/hanzoai/o11y", latest, ""}, true},
{"/github.com/hanzoai/o11y/@v/v1.5.64.info", ask{"github.com/hanzoai/o11y", info, "v1.5.64"}, true},
{"/github.com/hanzoai/o11y/@v/v1.5.64.mod", ask{"github.com/hanzoai/o11y", gomod, "v1.5.64"}, true},
{"/github.com/hanzoai/o11y/@v/v1.5.64.zip", ask{"github.com/hanzoai/o11y", zip, "v1.5.64"}, true},
// Case escaping: the wire spells an upper-case letter "!"+lower. Every
// decision downstream is made on the unescaped path.
{"/github.com/!burnt!sushi/toml/@v/list", ask{"github.com/BurntSushi/toml", list, ""}, true},
{"/github.com/hanzoai/o11y/@v/v1.5.64.tar", ask{}, false},
{"/github.com/hanzoai/o11y", ask{}, false},
{"/", ask{}, false},
} {
got, ok := parse(c.path)
if ok != c.ok || got != c.want {
t.Errorf("parse(%q) = %+v,%v want %+v,%v", c.path, got, ok, c.want, c.ok)
}
}
}
func TestOurs(t *testing.T) {
p := &Proxy{Namespaces: []string{"github.com/hanzoai", "github.com/luxfi"}}
for _, c := range []struct {
mod string
want bool
}{
{"github.com/hanzoai/o11y", true},
{"github.com/hanzoai/kms/sdk/go", true},
{"github.com/luxfi/node", true},
{"github.com/google/uuid", false},
// A namespace is a path prefix, not a string prefix. Were it the latter,
// anyone who can register `hanzoaiX` chooses which forge we read from.
{"github.com/hanzoaiX/evil", false},
{"github.com/hanzoai-evil/x", false},
{"evil.example/github.com/hanzoai/x", false},
} {
if got := p.ours(c.mod); got != c.want {
t.Errorf("ours(%q) = %v want %v", c.mod, got, c.want)
}
}
}
// newProxy builds a proxy whose forge cannot be reached, so every resolution
// inside its namespaces fails. That is the interesting case: what a failure
// tells the go command to do next.
func newProxy(t *testing.T) *Proxy {
t.Helper()
root := t.TempDir()
dir := filepath.Join(root, "scratch")
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module scratch\n"), 0o600); err != nil {
t.Fatal(err)
}
return &Proxy{
Namespaces: []string{"github.com/hanzoai"},
Forge: "https://forge.invalid",
Upstream: "https://upstream.invalid",
Token: "SENTINEL-TOKEN-VALUE",
Dir: dir,
Cache: filepath.Join(root, "cache"),
}
}
// A public module we cannot resolve gets 404, this protocol's "ask the next
// proxy". There is nothing in a public path to protect.
func TestPublicFallsThrough(t *testing.T) {
w := httptest.NewRecorder()
newProxy(t).ServeHTTP(w, httptest.NewRequest("GET", "/github.com/google/uuid/@v/list", nil))
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d want %d", w.Code, http.StatusNotFound)
}
}
// Where a module's bytes come from is decided by the namespace and nothing
// else: ours from the forge, everyone else's from the public proxy.
func TestSourceFollowsNamespace(t *testing.T) {
p := newProxy(t)
if !has(p.env(true), "GOPROXY=direct") {
t.Error("our modules must resolve from the forge, not through a proxy")
}
if !has(p.env(false), "GOPROXY="+p.Upstream) {
t.Error("third-party modules must resolve from the public proxy")
}
}
// The disclosure boundary. A module inside our namespaces that we could not
// resolve must NOT answer 404: 404 sends the go command to the next proxy
// carrying the module path, and the next proxy is public. The path of an
// unreleased repository is exactly what must not travel.
func TestPrivateFailureNeverFallsThrough(t *testing.T) {
for _, path := range []string{
"/github.com/hanzoai/unreleased/@v/list",
"/github.com/hanzoai/unreleased/@latest",
"/github.com/hanzoai/unreleased/@v/v1.0.0.info",
"/github.com/hanzoai/unreleased/@v/v1.0.0.mod",
"/github.com/hanzoai/unreleased/@v/v1.0.0.zip",
} {
w := httptest.NewRecorder()
newProxy(t).ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code == http.StatusNotFound || w.Code == http.StatusGone {
t.Errorf("%s answered %d — the go command would carry this path to the public proxy", path, w.Code)
}
if w.Code != http.StatusBadGateway {
t.Errorf("%s = %d want %d", path, w.Code, http.StatusBadGateway)
}
}
}
// Whatever git says on the way out, it does not say the token. git quotes the
// URL it was handed in most of its errors, and that URL carries the credential.
func TestErrorsCarryNoCredential(t *testing.T) {
p := newProxy(t)
w := httptest.NewRecorder()
p.ServeHTTP(w, httptest.NewRequest("GET", "/github.com/hanzoai/unreleased/@v/list", nil))
if strings.Contains(w.Body.String(), p.Token) {
t.Fatalf("response carries the credential: %s", w.Body.String())
}
}
// The credential reaches git through the environment of the child and nothing
// else, so it never lands in a file, a layer, or another process on the box.
func TestCredentialTravelsInTheEnvironment(t *testing.T) {
p := newProxy(t)
env := p.env(true)
var rule, count string
for _, e := range env {
if k, v, _ := strings.Cut(e, "="); k == "GIT_CONFIG_KEY_0" {
rule = v
} else if k == "GIT_CONFIG_COUNT" {
count = v
}
}
if count != "1" {
t.Fatalf("GIT_CONFIG_COUNT = %q want 1", count)
}
want := "url.https://x:" + p.Token + "@forge.invalid/hanzoai/.insteadOf"
if rule != want {
t.Fatalf("rewrite rule = %q want %q", rule, want)
}
// GOPRIVATE keeps the public checksum database out of the resolution of a
// module it cannot have seen. go.sum still pins every one of them.
if !has(env, "GOPRIVATE=github.com/hanzoai") || !has(env, "GONOSUMDB=github.com/hanzoai") {
t.Fatalf("private namespaces not exempted from the public sum database: %v", env)
}
}
func has(env []string, want string) bool {
for _, e := range env {
if e == want {
return true
}
}
return false
}