mirror of
https://github.com/mudler/LocalAI.git
synced 2026-09-12 22:33:54 -04:00
* test: make coverage failures observable Keep per-root logs, reject concurrent coverage runs, and avoid relying on /bin/sleep in the worker timeout test. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: parallelize coverage without remote fixtures Assisted-by: Codex:gpt-5 [apply_patch] [exec_command] Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: add offline resource infrastructure Introduce versioned resource manifests, a checksum-verified CAS preparer, offline test wrappers, and a guarded network transport. Replace live Hugging Face, GitHub, and OCI cases with deterministic fixtures and inject fixture metadata into importer discovery. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: enforce offline resource replay Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: harden offline resource refresh Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: expose slow coverage waits Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: eliminate avoidable wall-clock waits Inject a clock into Hugging Face retry handling, reuse a process-scoped PostgreSQL container with per-spec schemas in the nodes suite, and poll local import jobs promptly. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: remove repeated fixture startup waits Share PostgreSQL fixtures across parallel endpoint and agent suite workers, and make the worker Free deadline injectable so the wedged-backend test does not spend five seconds on wall-clock time. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: fix offline resource CI portability Normalize Docker archive metadata before content addressing, derive archive checksums during explicit refreshes, make network lint portable to macOS, and prepare distributed images before running their offline suite. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * ci: cache Go modules before offline tests Warm the complete module graph before the Linux and macOS test jobs enter offline replay mode, so tool dependencies such as Ginkgo are not fetched through the guarded proxy. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: drop the static network lint in favour of real isolation The offline test suite already prevents tests from reaching the network twice over: run-test-linux-offline.sh puts the test process in a cgroup and REJECTs egress outside the private ranges, and HardenedTransport installs testnetwork.LocalGuard to refuse dials that resolve to a public address. Both fail the test with a precise error at the moment of the dial. test-network-lint.sh added neither. Its diff stage defaulted to a HEAD base, so on a clean checkout it compared the tree against itself and inspected nothing; the branch's own commits were never examined. It only produced output when an earlier job step dirtied the tree, and then it matched a bare https?:// against whatever changed. make react-ui runs npm install rather than npm ci, so CI rewrote core/http/react-ui/package-lock.json and the lint reported an npm registry URL as forbidden test network access: + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.25.tgz", Its fingerprint stage was self-defeating in a quieter way: hashing the whole tree's network-mechanism inventory meant every rebase onto a master that touched any _test.go needed a manual baseline bump, so the check mostly caught its own staleness. Remove the script, its make target and the two prerequisite edges, along with the test-network: fixture markers that existed only to suppress it. The isolation itself is untouched. Assisted-by: Claude:claude-opus-5 [go vet] Signed-off-by: Richard Palethorpe <io@richiejp.com> * ci: keep hidden files in the offline test bundle artifact Cherry-picked from15a37b0acon the remote branch. The offline bundle lives under .cache/, which actions/upload-artifact skips by default, so the Linux job packed an artifact missing the very file the next step restores. The other half of15a37b0acmoved test-network-lint out of the `test` and `test-coverage` prerequisite lists into a recipe line, so parallel make could not fingerprint the tree while generated fixtures were still changing. That is dropped: the preceding commit removes the lint entirely, and the race it worked around is one more reason a whole-tree fingerprint was the wrong mechanism. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * refactor: share bounded exponential backoff Use overflow-safe saturating arithmetic for retry delays across model import polling, downloads, registration, node operations, and model loading. Keep model import status checks responsive initially while capping their interval at 500ms. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * ci: mirror Jetson Python wheels Keep the CUDA aarch64 wheel subset in GHCR and serve it as a local PEP 503 index during L4T backend builds, preserving last-known-good packages through upstream outages. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * docs(agents): index the Jetson wheels mirror Mention the GHCR-hosted L4T wheel mirror in the CI caching guide summary so maintainers can find its outage and cache documentation. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * ci: add defensive build network proxy Record build destinations and byte counts, retry observable idempotent HTTP downloads, and isolate explorer database tests that race under coverage. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(kokoros): implement updated backend trait Return unimplemented for image upscaling, matching the backend's other unsupported modalities after the protobuf API update. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): clear recovered proxy errors Do not mark a request failed when a later safe retry succeeds. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * ci: require HTTPS build interception Inject a short-lived proxy CA into BuildKit and Dockerfile RUN steps, reject plain HTTP and opaque tunnels, and retain method/status/byte telemetry for verified HTTPS traffic. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): preserve system trust in unproxied builds Mount the generated interception CA at a dedicated secret path and add it to the trust bundle only in proxy-aware dependency stages. This prevents optional secret mounts from masking the system CA bundle in ordinary backend test builds. Install the requested Go toolchain before starting the proxy and satisfy cleanup error checks found by CI lint. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): persist build proxy trust Install the generated proxy CA through the system-managed local certificate directory so ca-certificates upgrades retain it. Avoid turning canceled matrix jobs into proxy cleanup failures. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): trust proxy in nested build scripts Install the build proxy CA before nested source fetches, route the DS4 package setup through the HTTPS mirror helper, and avoid repeated OCI setup in gallery behavior tests. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): use HTTPS apt sources for Bonsai Rewrite ARM64 package sources before installing GCC and check gallery fixture cleanup errors so the optimized tests satisfy errcheck. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(privacy-filter): trust build proxy CA Install the mounted build proxy certificate before privacy-filter's make target fetches its HTTPS sources, for both source and prebuilt builder paths.\n\nAssisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * test: fail on hidden offline egress Count cgroup-scoped firewall rejects and fail the offline test harness with bounded aggregate diagnostics. Inject the gen-audio GGUF probe so fixture-backed importer tests do not attempt real network access. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> * fix(ci): preserve system CA trust Build a combined runner certificate bundle instead of replacing public roots with the generated proxy CA. Centralize additive container installation in the shared proxy CA helper. Assisted-by: Codex:gpt-5 Signed-off-by: Richard Palethorpe <io@richiejp.com> --------- Signed-off-by: Richard Palethorpe <io@richiejp.com> Co-authored-by: localai-org-maint-bot <306269227+localai-org-maint-bot@users.noreply.github.com>
236 lines
9.3 KiB
Go
236 lines
9.3 KiB
Go
// Package httpclient provides hardened *http.Client constructors for all
|
|
// outbound HTTP traffic in LocalAI.
|
|
//
|
|
// Direct use of net/http's default client (http.DefaultClient, http.Get,
|
|
// http.Post, ...) or a bare http.Client{} is forbidden by lint (forbidigo).
|
|
// The reason is GHSA-3mj3-57v2-4636: the standard client follows up to 10
|
|
// redirects by default, and on a *cross-host* redirect Go forwards custom
|
|
// request headers — including credential headers such as Anthropic's
|
|
// x-api-key — to the redirect target. (Go strips Authorization, Cookie and
|
|
// WWW-Authenticate cross-host, but NOT arbitrary custom headers.) An attacker
|
|
// who can elicit a redirect from an upstream then harvests the credential.
|
|
//
|
|
// Every client built here refuses redirects by default (see NoRedirect). The
|
|
// rare caller that genuinely must follow redirects should opt in with
|
|
// WithFollowRedirects, which still strips credential headers on host change.
|
|
//
|
|
// Streaming note: New() intentionally sets NO client-level Timeout, because a
|
|
// global timeout also bounds the response body and would truncate long-lived
|
|
// SSE streams (chat completions can stream for minutes). Per-request deadlines
|
|
// belong on the request context. Use NewWithTimeout for simple, non-streaming
|
|
// request/response calls.
|
|
package httpclient
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/mudler/LocalAI/pkg/testnetwork"
|
|
)
|
|
|
|
const (
|
|
// Transport-level bounds. These cap connection setup, NOT the response
|
|
// body, so they are safe for streaming responses.
|
|
dialTimeout = 30 * time.Second
|
|
dialKeepAlive = 30 * time.Second
|
|
tlsHandshakeTimeout = 10 * time.Second
|
|
idleConnTimeout = 90 * time.Second
|
|
expectContinueTimeout = 1 * time.Second
|
|
maxIdleConns = 100
|
|
|
|
// maxRedirects bounds WithFollowRedirects chains (mirrors the net/http
|
|
// default) so an opt-in follower can't be spun forever by a redirect loop.
|
|
maxRedirects = 10
|
|
)
|
|
|
|
// sensitiveHeaders are credential-bearing request headers that must never be
|
|
// replayed to a different host on a redirect. Go already drops the first three
|
|
// cross-host; the rest are custom headers Go does not know about. Compared
|
|
// case-insensitively via http.Header canonicalisation.
|
|
var sensitiveHeaders = []string{
|
|
"Authorization",
|
|
"Www-Authenticate",
|
|
"Cookie",
|
|
"Proxy-Authorization",
|
|
"X-Api-Key", // Anthropic, and many OpenAI-compatible providers
|
|
"Api-Key", // Azure OpenAI
|
|
"X-Auth-Token", // common custom scheme
|
|
"X-Goog-Api-Key", // Google
|
|
}
|
|
|
|
// ErrRedirectBlocked is wrapped by the error NoRedirect returns, so callers can
|
|
// distinguish "the upstream tried to redirect us" from other transport errors
|
|
// via errors.Is.
|
|
var ErrRedirectBlocked = errors.New("httpclient: redirect blocked")
|
|
|
|
// NoRedirect is an http.Client.CheckRedirect policy that refuses to follow any
|
|
// redirect, surfacing it as an error instead. This is the default for clients
|
|
// built by New/NewWithTimeout. The error uses URL.Redacted() so userinfo in
|
|
// the target URL is not written to logs.
|
|
func NoRedirect(req *http.Request, _ []*http.Request) error {
|
|
return fmt.Errorf("%w: refusing to follow redirect to %s (set httpclient.WithFollowRedirects to opt in)", ErrRedirectBlocked, req.URL.Redacted())
|
|
}
|
|
|
|
// stripAuthOnRedirect follows redirects but deletes credential headers whenever
|
|
// the redirect crosses to a different host, closing the cross-host credential
|
|
// leak while still allowing same-host or non-authenticated redirect chains.
|
|
func stripAuthOnRedirect(req *http.Request, via []*http.Request) error {
|
|
if len(via) >= maxRedirects {
|
|
return fmt.Errorf("httpclient: stopped after %d redirects", maxRedirects)
|
|
}
|
|
prev := via[len(via)-1]
|
|
if !sameOrigin(prev.URL, req.URL) {
|
|
for _, h := range sensitiveHeaders {
|
|
req.Header.Del(h)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sameOrigin reports whether two URLs share scheme AND host (including port).
|
|
// Deliberately strict: a different port or scheme is treated as a different
|
|
// origin so credential headers are stripped. This avoids the curl
|
|
// CVE-2022-27774 class of bug where ports were ignored and credentials leaked
|
|
// to a different service on the same hostname.
|
|
func sameOrigin(a, b *url.URL) bool {
|
|
return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host)
|
|
}
|
|
|
|
// HardenedTransport returns a fresh *http.Transport with a TLS 1.2 floor and
|
|
// bounded connection setup. Callers that need to wrap or extend the transport
|
|
// (e.g. a credential-injecting RoundTripper) should base it on this rather than
|
|
// http.DefaultTransport so the TLS floor and timeouts are preserved.
|
|
func HardenedTransport() *http.Transport {
|
|
dialContext := (&net.Dialer{
|
|
Timeout: dialTimeout,
|
|
KeepAlive: dialKeepAlive,
|
|
}).DialContext
|
|
// This is set only by the test-resource supervisor before it starts the
|
|
// child process; production configuration does not cross this boundary.
|
|
if os.Getenv("LOCALAI_TEST_OFFLINE") == "1" { //nolint:forbidigo
|
|
guard := testnetwork.LocalGuard()
|
|
guard.Dial = dialContext
|
|
dialContext = guard.DialContext
|
|
}
|
|
return &http.Transport{
|
|
Proxy: http.ProxyFromEnvironment,
|
|
DialContext: dialContext,
|
|
ForceAttemptHTTP2: true,
|
|
MaxIdleConns: maxIdleConns,
|
|
IdleConnTimeout: idleConnTimeout,
|
|
TLSHandshakeTimeout: tlsHandshakeTimeout,
|
|
ExpectContinueTimeout: expectContinueTimeout,
|
|
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
|
|
}
|
|
}
|
|
|
|
type options struct {
|
|
timeout time.Duration
|
|
responseHeaderTimeout time.Duration
|
|
transport http.RoundTripper
|
|
followRedirects bool
|
|
}
|
|
|
|
// Option configures a client built by New.
|
|
type Option func(*options)
|
|
|
|
// WithTimeout sets an overall client Timeout (covers the entire exchange
|
|
// including reading the body). Do NOT use this for streaming endpoints; prefer
|
|
// a per-request context deadline there. Equivalent to NewWithTimeout.
|
|
func WithTimeout(d time.Duration) Option { return func(o *options) { o.timeout = d } }
|
|
|
|
// WithTransport supplies a custom RoundTripper (e.g. an IP-pinned dialer or a
|
|
// credential-injecting wrapper). The caller is responsible for the transport's
|
|
// TLS configuration; base it on HardenedTransport to keep the TLS floor.
|
|
func WithTransport(rt http.RoundTripper) Option { return func(o *options) { o.transport = rt } }
|
|
|
|
// WithResponseHeaderTimeout bounds how long the transport waits for a
|
|
// response's headers after the request has been written. Unlike WithTimeout it
|
|
// does NOT bound the response body, so it is safe for long transfers: it only
|
|
// catches a peer that accepts the connection and then never answers, which
|
|
// would otherwise park Do() for the process lifetime.
|
|
//
|
|
// Opt-in rather than a default in HardenedTransport, because a streaming
|
|
// endpoint may legitimately withhold headers until it has something to say (a
|
|
// queued or slow-to-first-token completion), and capping that would break
|
|
// streaming clients. Use it for request/response traffic and bulk downloads.
|
|
func WithResponseHeaderTimeout(d time.Duration) Option {
|
|
return func(o *options) { o.responseHeaderTimeout = d }
|
|
}
|
|
|
|
// WithFollowRedirects opts into following redirects, while still stripping
|
|
// credential headers on any cross-host hop. Use only when an endpoint legitimately
|
|
// redirects (e.g. some download CDNs) and the request carries a secret.
|
|
func WithFollowRedirects() Option { return func(o *options) { o.followRedirects = true } }
|
|
|
|
// New returns a hardened *http.Client. By default it refuses redirects, sets a
|
|
// TLS 1.2 floor, bounds connection setup, and imposes no body deadline (safe
|
|
// for streaming). Apply Options to adjust.
|
|
func New(opts ...Option) *http.Client {
|
|
o := options{}
|
|
for _, fn := range opts {
|
|
fn(&o)
|
|
}
|
|
|
|
rt := o.transport
|
|
if rt == nil {
|
|
rt = HardenedTransport()
|
|
}
|
|
// Only an *http.Transport carries the knob; a caller-supplied wrapper
|
|
// (bearer-token RoundTripper, IP-pinned dialer) is left untouched rather
|
|
// than silently ignored-with-a-lie, so it must set the field itself.
|
|
if o.responseHeaderTimeout > 0 {
|
|
if t, ok := rt.(*http.Transport); ok {
|
|
t.ResponseHeaderTimeout = o.responseHeaderTimeout
|
|
}
|
|
}
|
|
|
|
check := NoRedirect
|
|
if o.followRedirects {
|
|
check = stripAuthOnRedirect
|
|
}
|
|
|
|
return &http.Client{
|
|
Transport: rt,
|
|
Timeout: o.timeout, // zero == no overall deadline (streaming-safe)
|
|
CheckRedirect: check,
|
|
}
|
|
}
|
|
|
|
// NewWithTimeout returns a hardened client with an overall Timeout. Use for
|
|
// simple request/response calls; for streaming, use New with a context deadline.
|
|
func NewWithTimeout(timeout time.Duration, opts ...Option) *http.Client {
|
|
return New(append([]Option{WithTimeout(timeout)}, opts...)...)
|
|
}
|
|
|
|
// Harden applies the default hardening (refuse redirects, TLS 1.2 floor) to an
|
|
// existing client in place, for the cases where a third-party library hands us
|
|
// a *http.Client to configure rather than letting us construct one. It returns
|
|
// the same client for convenience. A nil client is left nil.
|
|
func Harden(c *http.Client) *http.Client {
|
|
if c == nil {
|
|
return nil
|
|
}
|
|
if c.CheckRedirect == nil {
|
|
c.CheckRedirect = NoRedirect
|
|
}
|
|
switch t := c.Transport.(type) {
|
|
case nil:
|
|
c.Transport = HardenedTransport()
|
|
case *http.Transport:
|
|
if t.TLSClientConfig == nil {
|
|
t.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
|
|
} else if t.TLSClientConfig.MinVersion == 0 {
|
|
t.TLSClientConfig.MinVersion = tls.VersionTLS12
|
|
}
|
|
}
|
|
return c
|
|
}
|