Files
pmg/test/proxye2e/harness.go
T
b19473945b Add experimental Go module proxy support (#358)
* feat: add experimental Go module support via pmg go

Adds Go modules as a proxy-guarded ecosystem, opt-in only: the command
runs solely when invoked explicitly as `pmg go ...` and is deliberately
excluded from setup aliases and PATH shims so existing users are
unaffected.

- packagemanager: goPackageManager with fail-safe command classification
  (vet/fix excluded from non-download since they can fetch on a cold
  cache) and pinned-version extraction where only canonical semver
  counts as explicit.
- GOPROXY normalization (fail-closed): effective GOPROXY read via
  `go env` (honors go env -w), rebuilt comma-joined with `direct`
  dropped so a 403 block is terminal and nothing silently falls back to
  unanalyzed VCS fetches. GOPRIVATE/GONOPROXY surface a warning;
  GOINSECURE is cleared. Contributed to the proxy flow through a new
  ProxyRoutingProvider hook (extra child env + dynamic MITM hosts).
- Go interceptor with dynamic host matching from the user's effective
  GOPROXY via InterceptorContext.GoProxyHosts. Malware analysis runs on
  .zip only (the sole endpoint that delivers code); .info/.mod/@latest/
  list pass through; /sumdb/ traffic and sum.golang.org are never
  touched so checksum-db verification stays intact; golang.org/toolchain
  is allowed on Go's own checksum verification.
- Dependency cooldown: publish time captured from .info responses
  (body unmodified), in-window .zip blocked with 403; fails open for
  cooldown only when the publish time was never observed.
- Cert gate: on macOS/Windows `pmg go` fails fast with actionable
  guidance unless the persisted PMG CA is OS-trusted (Go ignores
  SSL_CERT_FILE there); Linux works via the injected bundle.
- proxye2e: GOPROXY-protocol mock registry, Go driver and 10 hermetic
  cases (allow/block/confirm, case-escaped paths, cooldown block and
  fail-open, toolchain, sumdb passthrough).

Verified end-to-end on Linux: `pmg go get github.com/google/uuid@v1.6.0`
MITMs proxy.golang.org, analyzes the decoded module at the .zip fetch,
and go.sum verification succeeds through the tunneled checksum db.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014xuhBeTVpfU4SdqVaarvuK

* fix(go): address review findings on experimental Go support

- Drop fmt/clean from NonDownloadCommands: both load packages via go
  list and can download modules on a cold cache, which would bypass the
  proxy under install_only.
- Support GOPROXY entries with a base path (e.g. corp Athens/JFrog at
  https://corp/goproxy): the interceptor now receives host -> base URL
  and strips the path prefix before parsing module URLs, so verdicts
  and cooldown key on the real module path.
- Default unschemed GOPROXY entries to https, matching go's own
  behavior, so corp mirrors configured as bare hosts are intercepted
  instead of silently unanalyzed.
- Memoize the final verdict per module zip: go re-requests a failed
  zip during go get's load phase, which double-recorded stats (the
  report showed the same blocked module twice) and would have
  re-prompted on Confirm verdicts.
- Fetch .info out-of-band on a cooldown cache miss: go serves .info
  from its local module cache on any machine that used go before PMG,
  which silently disabled cooldown. Failure of the side-fetch still
  fails open for cooldown only.
- Move the noop package resolver into packagemanager.

Verified live: cold-cache cooldown block now records once; warm-cache
rerun is blocked via the side-fetch instead of failing open.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014xuhBeTVpfU4SdqVaarvuK

* docs: collapse Go proxy-mode details by default

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014xuhBeTVpfU4SdqVaarvuK

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-03 18:19:31 +05:30

233 lines
6.8 KiB
Go

package proxye2e
import (
"context"
"crypto/tls"
"crypto/x509"
"io"
"net"
"net/http"
"net/url"
"sync"
"testing"
"time"
packagev1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/package/v1"
"github.com/safedep/pmg/analyzer"
"github.com/safedep/pmg/internal/models"
"github.com/safedep/pmg/proxy"
"github.com/safedep/pmg/proxy/certmanager"
"github.com/safedep/pmg/proxy/interceptors"
"github.com/stretchr/testify/require"
)
// Harness wires the real proxy, interceptors and analyzer against an in-process
// mock registry and a stub malysis client. It is the single entry point a test
// case uses to register fixtures, drive traffic and assert outcomes.
type Harness struct {
t *testing.T
Registry *Registry
Analyzer *AnalyzerRecorder
Confirm *ConfirmController
stats *interceptors.AnalysisStatsCollector
proxy proxy.ProxyServer
client *http.Client
confChan chan *interceptors.ConfirmationRequest
dialMu sync.Mutex
dialedAddrs []string
}
type options struct {
pinnedVersions map[string]string
}
type Option func(*options)
// WithPinnedVersions seeds the interceptor's pinned-version context, which
// cooldown uses to report when an explicitly requested version is blocked.
func WithPinnedVersions(pinned map[string]string) Option {
return func(o *options) { o.pinnedVersions = pinned }
}
func New(t *testing.T, opts ...Option) *Harness {
t.Helper()
var o options
for _, opt := range opts {
opt(&o)
}
caCert, err := certmanager.GenerateCA(certmanager.DefaultCertManagerConfig())
require.NoError(t, err)
certMgr, err := certmanager.NewCertificateManagerWithCA(caCert, certmanager.DefaultCertManagerConfig())
require.NoError(t, err)
registry := newRegistry()
rec := newAnalyzerRecorder()
confirm := newConfirmController()
stats := interceptors.NewAnalysisStatsCollector()
malysisAnalyzer, err := analyzer.NewMalysisQueryAnalyzerWithClient(
&stubAnalyzerClient{rec: rec}, analyzer.MalysisQueryAnalyzerConfig{}, true)
require.NoError(t, err)
confChan := make(chan *interceptors.ConfirmationRequest, 10)
go interceptors.HandleConfirmationRequests(confChan, confirm.interaction(), nil)
factory := interceptors.NewInterceptorFactory(
malysisAnalyzer,
interceptors.NewInMemoryAnalysisCache(),
stats,
confChan,
interceptors.InterceptorContext{
PinnedVersions: o.pinnedVersions,
// proxy.golang.org serves at the root of the plain-HTTP mock (also
// the base for out-of-band .info fetches); corp.example.com serves
// under a base path to exercise GOPROXY path-prefix stripping.
GoProxyBaseURLs: map[string]string{
"proxy.golang.org": registry.goBaseURL(),
"corp.example.com": registry.goBaseURL() + "/goproxy",
},
},
)
interceptorList := []proxy.Interceptor{interceptors.NewAuditLoggerInterceptor()}
for _, eco := range []packagev1.Ecosystem{packagev1.Ecosystem_ECOSYSTEM_NPM, packagev1.Ecosystem_ECOSYSTEM_PYPI, packagev1.Ecosystem_ECOSYSTEM_GO} {
ic, ierr := factory.CreateInterceptor(eco)
require.NoError(t, ierr)
interceptorList = append(interceptorList, ic)
}
h := &Harness{
t: t,
Registry: registry,
Analyzer: rec,
Confirm: confirm,
stats: stats,
confChan: confChan,
}
h.proxy = buildProxy(t, certMgr, registry.addr(), interceptorList, h.recordDial)
caPool := x509.NewCertPool()
caPool.AddCert(caCert.X509Cert)
proxyURL, err := url.Parse("http://" + h.proxy.Address())
require.NoError(t, err)
h.client = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
TLSClientConfig: &tls.Config{RootCAs: caPool},
},
}
return h
}
func buildProxy(t *testing.T, certMgr certmanager.CertificateManager, upstreamAddr string, interceptorList []proxy.Interceptor, recordDial func(string)) proxy.ProxyServer {
t.Helper()
cfg := proxy.DefaultProxyConfig()
cfg.CertManager = certMgr
cfg.Interceptors = interceptorList
// All upstream connections — MITM'd round-trips and CONNECT tunnels for
// non-MITM hosts alike — terminate at the mock registry, so no test reaches
// the network regardless of the hostname being proxied.
cfg.UpstreamDialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
recordDial(addr)
return (&net.Dialer{}).DialContext(ctx, network, upstreamAddr)
}
// Test-only: the mock's self-signed cert cannot match the real registry SNIs
// the proxy presents upstream, so verification is skipped for this in-process
// hop (the same approach proxy/scale_test.go uses).
cfg.UpstreamTLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402
server, err := proxy.NewProxyServer(cfg)
require.NoError(t, err)
require.NoError(t, server.Start())
return server
}
// Close stops the proxy first so no interceptor can send on the confirmation
// channel after it is closed.
func (h *Harness) Close() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = h.proxy.Stop(ctx)
close(h.confChan)
h.Registry.close()
}
func (h *Harness) Npm() NpmDriver { return NpmDriver{h: h} }
func (h *Harness) Pypi() PypiDriver { return PypiDriver{h: h} }
func (h *Harness) Go() GoDriver { return GoDriver{h: h} }
func (h *Harness) Stats() interceptors.AnalysisStats { return h.stats.GetStats() }
func (h *Harness) BlockedPackages() []*analyzer.PackageVersionAnalysisResult {
return h.stats.GetBlockedPackages()
}
func (h *Harness) CooldownBlocks() []models.CooldownBlock { return h.stats.GetCooldownBlocks() }
func (h *Harness) recordDial(addr string) {
h.dialMu.Lock()
defer h.dialMu.Unlock()
h.dialedAddrs = append(h.dialedAddrs, addr)
}
// DialedAddrs returns the upstream addresses the proxy was asked to connect to,
// before redirection to the mock. A non-MITM host appearing here proves its
// CONNECT tunnel went through the override rather than the real network.
func (h *Harness) DialedAddrs() []string {
h.dialMu.Lock()
defer h.dialMu.Unlock()
out := make([]string, len(h.dialedAddrs))
copy(out, h.dialedAddrs)
return out
}
// RawClient returns an HTTP client wired through the proxy and trusting the MITM
// CA, for edge cases the install drivers do not model.
func (h *Harness) RawClient() *http.Client { return h.client }
func (h *Harness) get(rawURL string, headers map[string]string) RequestOutcome {
h.t.Helper()
out := RequestOutcome{URL: rawURL}
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
if err != nil {
out.Err = err
return out
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := h.client.Do(req)
if err != nil {
out.Err = err
return out
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
out.Err = err
return out
}
out.StatusCode = resp.StatusCode
out.Blocked = resp.StatusCode == http.StatusForbidden
out.Body = string(body)
return out
}