mirror of
https://github.com/MengMengCode/CLICD.git
synced 2026-12-06 13:16:00 +08:00
fix(security): constrain image downloads and patch docs dependencies (#64)
Require explicit server approval for private image origins, pin and validate every connection and redirect, preserve HTTPS hostname verification, and require administrator capability for versioned image management. Update docs Vite to 6.4.5 and nanoid to 3.3.20. Validation: full Go tests and vet; Windows/Linux security regressions; real HTTPS redirect download with certificate verification; docs build and npm audit (zero vulnerabilities); amd64/arm64 CI builds; CodeQL Go, JS/TS and Actions all report zero alerts. Private mirrors now require CLICD_IMAGE_MIRROR_ORIGINS, as documented.
This commit is contained in:
@@ -2,17 +2,24 @@ package safehttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxRedirects = 10
|
||||
const imageMirrorOriginsEnv = "CLICD_IMAGE_MIRROR_ORIGINS"
|
||||
|
||||
var sharedAddressPrefix = netip.MustParsePrefix("100.64.0.0/10")
|
||||
|
||||
var blockedDownloadPrefixes = []netip.Prefix{
|
||||
netip.MustParsePrefix("0.0.0.0/8"),
|
||||
@@ -49,6 +56,9 @@ func ValidateURL(rawURL string) (*url.URL, error) {
|
||||
if len(rawURL) == 0 || len(rawURL) > 4096 {
|
||||
return nil, fmt.Errorf("download URL must be between 1 and 4096 characters")
|
||||
}
|
||||
if strings.Contains(rawURL, "#") {
|
||||
return nil, fmt.Errorf("download URL must not include a fragment")
|
||||
}
|
||||
parsed, err := url.ParseRequestURI(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid download URL: %v", err)
|
||||
@@ -77,93 +87,251 @@ func ValidateURL(rawURL string) (*url.URL, error) {
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
// Get retrieves a resource only when every resolved destination is safe for
|
||||
// image downloads. Private network image mirrors are allowed; loopback,
|
||||
// link-local, metadata, multicast and reserved destinations remain blocked.
|
||||
// Get downloads an image through approved, pinned network endpoints. Private
|
||||
// mirrors require a server-approved origin and are limited to its initially
|
||||
// resolved addresses; redirects and DNS changes cannot grant new private access.
|
||||
func Get(ctx context.Context, rawURL, userAgent string, timeout time.Duration) (*http.Response, error) {
|
||||
parsed, err := ValidateURL(rawURL)
|
||||
trustedOrigins, err := parseImageMirrorOrigins(os.Getenv(imageMirrorOriginsEnv))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateHost(ctx, net.DefaultResolver, parsed.Hostname()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header.Set("User-Agent", userAgent)
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: restrictedTransport(net.DefaultResolver),
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxRedirects {
|
||||
return fmt.Errorf("too many redirects")
|
||||
}
|
||||
redirect, err := ValidateURL(req.URL.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateHost(req.Context(), net.DefaultResolver, redirect.Hostname()); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(via) > 0 {
|
||||
req.Header.Set("User-Agent", via[0].Header.Get("User-Agent"))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// The URL, redirects, DNS answers and dial destinations are constrained
|
||||
// above and in restrictedTransport. CodeQL cannot infer those checks across
|
||||
// the custom transport boundary.
|
||||
// codeql[go/request-forgery]
|
||||
return client.Do(request)
|
||||
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return (downloader{resolver: net.DefaultResolver, dialContext: dialer.DialContext, trustedOrigins: trustedOrigins}).get(ctx, rawURL, userAgent, timeout)
|
||||
}
|
||||
|
||||
func restrictedTransport(resolver *net.Resolver) *http.Transport {
|
||||
dialer := &net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
func parseImageMirrorOrigins(value string) (map[string]bool, error) {
|
||||
origins := make(map[string]bool)
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return origins, nil
|
||||
}
|
||||
return &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid download destination: %v", err)
|
||||
for _, raw := range strings.Split(value, ",") {
|
||||
parsed, err := ValidateURL(strings.TrimSpace(raw))
|
||||
if err != nil || (parsed != nil && (parsed.Path != "" && parsed.Path != "/" || parsed.RawQuery != "" || parsed.ForceQuery)) {
|
||||
return nil, fmt.Errorf("%s must contain comma-separated HTTP(S) origins without paths, queries, fragments or credentials", imageMirrorOriginsEnv)
|
||||
}
|
||||
origins[downloadOrigin(parsed)] = true
|
||||
}
|
||||
return origins, nil
|
||||
}
|
||||
|
||||
type hostResolver interface {
|
||||
LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
|
||||
}
|
||||
|
||||
type downloader struct {
|
||||
resolver hostResolver
|
||||
dialContext func(context.Context, string, string) (net.Conn, error)
|
||||
tlsConfig *tls.Config
|
||||
trustedOrigins map[string]bool
|
||||
}
|
||||
|
||||
type downloadPolicy struct {
|
||||
privateOrigin string
|
||||
privateAddresses map[netip.Addr]bool
|
||||
}
|
||||
|
||||
func newDownloadPolicy(source *url.URL, addresses []netip.Addr, trustedOrigins map[string]bool) (downloadPolicy, error) {
|
||||
policy := downloadPolicy{privateAddresses: make(map[netip.Addr]bool)}
|
||||
privateCount := 0
|
||||
for _, address := range addresses {
|
||||
if isPrivateDownloadAddress(address) {
|
||||
privateCount++
|
||||
policy.privateAddresses[address] = true
|
||||
}
|
||||
}
|
||||
if len(policy.privateAddresses) > 0 {
|
||||
if !trustedOrigins[downloadOrigin(source)] {
|
||||
return downloadPolicy{}, fmt.Errorf("private image mirror must be explicitly approved in %s", imageMirrorOriginsEnv)
|
||||
}
|
||||
if privateCount != len(addresses) {
|
||||
return downloadPolicy{}, fmt.Errorf("download host mixes public and private addresses")
|
||||
}
|
||||
policy.privateOrigin = downloadOrigin(source)
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func (policy downloadPolicy) approve(target *url.URL, addresses []netip.Addr) error {
|
||||
origin := downloadOrigin(target)
|
||||
for _, address := range addresses {
|
||||
if policy.privateOrigin != "" && origin == policy.privateOrigin {
|
||||
if !policy.privateAddresses[address] {
|
||||
return fmt.Errorf("private image mirror address changed during download")
|
||||
}
|
||||
addresses, err := resolveAllowedHost(ctx, resolver, host)
|
||||
} else if isPrivateDownloadAddress(address) {
|
||||
return fmt.Errorf("download redirect or DNS change targets an unapproved private address")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isPrivateDownloadAddress(address netip.Addr) bool {
|
||||
address = address.Unmap()
|
||||
return address.IsPrivate() || sharedAddressPrefix.Contains(address)
|
||||
}
|
||||
|
||||
func downloadPort(target *url.URL) int {
|
||||
if value := target.Port(); value != "" {
|
||||
port, _ := strconv.Atoi(value) // ValidateURL has already checked the range.
|
||||
return port
|
||||
}
|
||||
if target.Scheme == "https" {
|
||||
return 443
|
||||
}
|
||||
return 80
|
||||
}
|
||||
|
||||
func downloadOrigin(target *url.URL) string {
|
||||
host := strings.ToLower(strings.TrimSuffix(target.Hostname(), "."))
|
||||
if address, err := netip.ParseAddr(host); err == nil {
|
||||
host = address.String()
|
||||
}
|
||||
return target.Scheme + "://" + net.JoinHostPort(host, strconv.Itoa(downloadPort(target)))
|
||||
}
|
||||
|
||||
func (d downloader) get(ctx context.Context, rawURL, userAgent string, timeout time.Duration) (*http.Response, error) {
|
||||
var cancel context.CancelFunc
|
||||
if timeout > 0 {
|
||||
ctx, cancel = context.WithTimeout(ctx, timeout)
|
||||
} else {
|
||||
ctx, cancel = context.WithCancel(ctx)
|
||||
}
|
||||
logicalURL, err := ValidateURL(rawURL)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
addresses, err := resolveAllowedHost(ctx, d.resolver, logicalURL.Hostname())
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
policy, err := newDownloadPolicy(logicalURL, addresses, d.trustedOrigins)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
for hop := 0; hop < maxRedirects; hop++ {
|
||||
if err := policy.approve(logicalURL, addresses); err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
// The request authority is constructed from an approved IP and numeric
|
||||
// port. User-controlled path and query are appended only after that
|
||||
// complete authority; the transport dials this same frozen address set.
|
||||
scheme := "http"
|
||||
if logicalURL.Scheme == "https" {
|
||||
scheme = "https"
|
||||
}
|
||||
endpoint := scheme + "://" + net.JoinHostPort(addresses[0].String(), strconv.Itoa(downloadPort(logicalURL)))
|
||||
requestURL := endpoint + "/" + strings.TrimPrefix(logicalURL.EscapedPath(), "/")
|
||||
if logicalURL.RawQuery != "" || logicalURL.ForceQuery {
|
||||
requestURL += "?" + logicalURL.RawQuery
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
request.Host = logicalURL.Host
|
||||
request.Header.Set("User-Agent", userAgent)
|
||||
transport := d.transport(logicalURL, addresses)
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
transport.CloseIdleConnections()
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
// Relative Location values and downstream response validation refer to
|
||||
// the logical URL, while the actual connection used the pinned endpoint.
|
||||
logicalCopy := *logicalURL
|
||||
response.Request = request.Clone(ctx)
|
||||
response.Request.URL = &logicalCopy
|
||||
if isDownloadRedirect(response.StatusCode) && response.Header.Get("Location") != "" {
|
||||
next, redirectErr := response.Location()
|
||||
_ = response.Body.Close()
|
||||
transport.CloseIdleConnections()
|
||||
if redirectErr != nil {
|
||||
cancel()
|
||||
return nil, redirectErr
|
||||
}
|
||||
if hop+1 >= maxRedirects {
|
||||
cancel()
|
||||
return nil, fmt.Errorf("too many redirects")
|
||||
}
|
||||
logicalURL, err = ValidateURL(next.String())
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
addresses, err = resolveAllowedHost(ctx, d.resolver, logicalURL.Hostname())
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
response.Body = &downloadBody{ReadCloser: response.Body, close: func() {
|
||||
cancel()
|
||||
transport.CloseIdleConnections()
|
||||
}}
|
||||
return response, nil
|
||||
}
|
||||
cancel()
|
||||
return nil, fmt.Errorf("too many redirects")
|
||||
}
|
||||
|
||||
func isDownloadRedirect(status int) bool {
|
||||
return status == http.StatusMovedPermanently || status == http.StatusFound ||
|
||||
status == http.StatusSeeOther || status == http.StatusTemporaryRedirect || status == http.StatusPermanentRedirect
|
||||
}
|
||||
|
||||
type downloadBody struct {
|
||||
io.ReadCloser
|
||||
close func()
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (body *downloadBody) Close() error {
|
||||
err := body.ReadCloser.Close()
|
||||
body.once.Do(body.close)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d downloader) transport(logicalURL *url.URL, addresses []netip.Addr) *http.Transport {
|
||||
port := strconv.Itoa(downloadPort(logicalURL))
|
||||
tlsConfig := &tls.Config{}
|
||||
if d.tlsConfig != nil {
|
||||
tlsConfig = d.tlsConfig.Clone()
|
||||
}
|
||||
tlsConfig.ServerName = strings.TrimSuffix(logicalURL.Hostname(), ".")
|
||||
return &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
var lastErr error
|
||||
for _, addr := range addresses {
|
||||
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(addr.String(), port))
|
||||
for _, address := range addresses {
|
||||
conn, err := d.dialContext(ctx, network, net.JoinHostPort(address.String(), port))
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("host has no usable public addresses")
|
||||
}
|
||||
return nil, lastErr
|
||||
},
|
||||
TLSClientConfig: tlsConfig,
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSHandshakeTimeout: 30 * time.Second,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func validateHost(ctx context.Context, resolver *net.Resolver, host string) error {
|
||||
_, err := resolveAllowedHost(ctx, resolver, host)
|
||||
return err
|
||||
}
|
||||
|
||||
func resolveAllowedHost(ctx context.Context, resolver *net.Resolver, host string) ([]netip.Addr, error) {
|
||||
func resolveAllowedHost(ctx context.Context, resolver hostResolver, host string) ([]netip.Addr, error) {
|
||||
host = strings.TrimSpace(strings.TrimSuffix(host, "."))
|
||||
if host == "" {
|
||||
return nil, fmt.Errorf("download URL host is empty")
|
||||
|
||||
@@ -21,6 +21,7 @@ func TestValidateURLRejectsUnsafeDestinations(t *testing.T) {
|
||||
"http://100.100.100.200/latest/meta-data",
|
||||
"http://[fd00:ec2::254]/latest/meta-data",
|
||||
"http://example.com:99999/image",
|
||||
"http://example.com/image#fragment",
|
||||
} {
|
||||
if _, err := ValidateURL(rawURL); err == nil {
|
||||
t.Fatalf("ValidateURL(%q) succeeded, want rejection", rawURL)
|
||||
@@ -101,6 +102,7 @@ func TestGetAllowsPrivateNetworkMirror(t *testing.T) {
|
||||
t.Fatalf("failed to listen on private interface: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
t.Setenv(imageMirrorOriginsEnv, "http://"+listener.Addr().String())
|
||||
|
||||
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, "private mirror ok")
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
package safehttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type lookupFunc func(context.Context, string, string) ([]netip.Addr, error)
|
||||
|
||||
func (lookup lookupFunc) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error) {
|
||||
return lookup(ctx, network, host)
|
||||
}
|
||||
|
||||
func TestParseImageMirrorOrigins(t *testing.T) {
|
||||
for _, invalid := range []string{
|
||||
"mirror.test", "ftp://mirror.test", "http://user:pass@mirror.test",
|
||||
"http://mirror.test/images", "http://mirror.test?key=value", "http://mirror.test?",
|
||||
"http://mirror.test/#fragment", "http://mirror.test:65536", "http://mirror.test,",
|
||||
"http://127.0.0.1", "http://169.254.169.254",
|
||||
} {
|
||||
if _, err := parseImageMirrorOrigins(invalid); err == nil || !strings.Contains(err.Error(), imageMirrorOriginsEnv) {
|
||||
t.Errorf("parseImageMirrorOrigins(%q) = %v, want configuration error", invalid, err)
|
||||
}
|
||||
}
|
||||
origins, err := parseImageMirrorOrigins(" HTTP://Mirror.test:80/, https://[fd00::10]:443 ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !origins["http://mirror.test:80"] || !origins["https://[fd00::10]:443"] || len(origins) != 2 {
|
||||
t.Fatalf("unexpected normalized origins: %v", origins)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPrivateMirrorRequiresServerApproval(t *testing.T) {
|
||||
t.Setenv(imageMirrorOriginsEnv, "")
|
||||
_, err := Get(context.Background(), "http://10.0.0.10/image", "test", time.Second)
|
||||
if err == nil || !strings.Contains(err.Error(), imageMirrorOriginsEnv) {
|
||||
t.Fatalf("unapproved private mirror error = %v", err)
|
||||
}
|
||||
t.Setenv(imageMirrorOriginsEnv, "http://mirror.test/not-an-origin")
|
||||
if _, err := Get(context.Background(), "http://10.0.0.10/image", "test", time.Second); err == nil || !strings.Contains(err.Error(), imageMirrorOriginsEnv) {
|
||||
t.Fatalf("invalid mirror configuration error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateMirrorPolicyAllowsRepeatedDNSAnswers(t *testing.T) {
|
||||
source, err := ValidateURL("http://mirror.test/image")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := netip.MustParseAddr("10.0.0.10")
|
||||
addresses := []netip.Addr{address, address}
|
||||
policy, err := newDownloadPolicy(source, addresses, map[string]bool{"http://mirror.test:80": true})
|
||||
if err != nil {
|
||||
t.Fatalf("duplicate private answers were treated as mixed addresses: %v", err)
|
||||
}
|
||||
if err := policy.approve(source, addresses); err != nil {
|
||||
t.Fatalf("approved repeated answers were rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateMirrorApprovalMatchesExactOrigin(t *testing.T) {
|
||||
for _, allowed := range []string{
|
||||
"http://other.test:8080", "http://mirror.test:8081", "https://mirror.test:8080",
|
||||
} {
|
||||
t.Run(allowed, func(t *testing.T) {
|
||||
d := downloader{
|
||||
resolver: lookupFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("10.0.0.10")}, nil
|
||||
}),
|
||||
trustedOrigins: map[string]bool{allowed: true},
|
||||
dialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||
t.Error("unapproved private origin was dialed")
|
||||
return nil, errors.New("unexpected connection")
|
||||
},
|
||||
}
|
||||
if _, err := d.get(context.Background(), "http://mirror.test:8080/image", "test", time.Second); err == nil {
|
||||
t.Fatal("private origin accepted a different host, scheme or port")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRejectsPrivateRedirectsAndDNSChanges(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
redirect string
|
||||
initialIP string
|
||||
nextIP string
|
||||
allowlist string
|
||||
}{
|
||||
{"public to private", "http://public.test/image", "http://10.0.0.10/secret", "8.8.8.8", "", ""},
|
||||
{"public to CGNAT", "http://public.test/image", "http://100.64.0.10/secret", "8.8.8.8", "", ""},
|
||||
{"public to ULA", "http://public.test/image", "http://[fd00::10]/secret", "8.8.8.8", "", ""},
|
||||
{"public DNS becomes private", "http://public.test/image", "/next", "8.8.8.8", "10.0.0.10", "http://public.test:80"},
|
||||
{"private DNS address changes", "http://mirror.test/image", "/next", "10.0.0.10", "10.0.0.11", "http://mirror.test:80"},
|
||||
{"private mirror changes host", "http://mirror.test/image", "http://other.test/secret", "10.0.0.10", "10.0.0.10", "http://mirror.test:80"},
|
||||
{"private mirror changes port", "http://mirror.test/image", "http://mirror.test:81/secret", "10.0.0.10", "10.0.0.10", "http://mirror.test:80"},
|
||||
{"private mirror changes scheme", "http://mirror.test/image", "https://mirror.test:80/secret", "10.0.0.10", "10.0.0.10", "http://mirror.test:80"},
|
||||
{"loopback redirect", "http://public.test/image", "http://127.0.0.1/secret", "8.8.8.8", "", ""},
|
||||
{"mapped loopback redirect", "http://public.test/image", "http://[::ffff:127.0.0.1]/secret", "8.8.8.8", "", ""},
|
||||
{"metadata redirect", "http://public.test/image", "http://169.254.169.254/secret", "8.8.8.8", "", ""},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, test.redirect, http.StatusFound)
|
||||
}))
|
||||
defer server.Close()
|
||||
lookups, dials := 0, 0
|
||||
d := downloader{
|
||||
resolver: lookupFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||
lookups++
|
||||
address := test.initialIP
|
||||
if lookups > 1 && test.nextIP != "" {
|
||||
address = test.nextIP
|
||||
}
|
||||
return []netip.Addr{netip.MustParseAddr(address)}, nil
|
||||
}),
|
||||
dialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
dials++
|
||||
if address != net.JoinHostPort(test.initialIP, "80") {
|
||||
return nil, fmt.Errorf("unapproved dial endpoint: %s", address)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
},
|
||||
trustedOrigins: map[string]bool{test.allowlist: true},
|
||||
}
|
||||
response, err := d.get(context.Background(), test.source, "test", time.Second)
|
||||
if response != nil {
|
||||
response.Body.Close()
|
||||
}
|
||||
if err == nil || dials != 1 {
|
||||
t.Fatalf("redirect was not stopped before a second connection: err=%v dials=%d", err, dials)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadPinsInitialDNSAnswerAndRejectsMixedAnswers(t *testing.T) {
|
||||
for _, addresses := range [][]netip.Addr{
|
||||
{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("127.0.0.1")},
|
||||
{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("10.0.0.10")},
|
||||
} {
|
||||
d := downloader{
|
||||
resolver: lookupFunc(func(context.Context, string, string) ([]netip.Addr, error) { return addresses, nil }),
|
||||
trustedOrigins: map[string]bool{"http://mirror.test:80": true},
|
||||
dialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||
t.Error("unsafe DNS answer was dialed")
|
||||
return nil, errors.New("unexpected connection")
|
||||
},
|
||||
}
|
||||
if _, err := d.get(context.Background(), "http://mirror.test/image", "test", time.Second); err == nil {
|
||||
t.Fatalf("mixed DNS answers accepted: %v", addresses)
|
||||
}
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "ok") }))
|
||||
defer server.Close()
|
||||
lookups := 0
|
||||
d := downloader{
|
||||
resolver: lookupFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||
lookups++
|
||||
if lookups != 1 {
|
||||
t.Error("transport re-resolved the hostname instead of dialing the approved address")
|
||||
}
|
||||
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
|
||||
}),
|
||||
dialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if address != "8.8.8.8:80" {
|
||||
return nil, fmt.Errorf("dial endpoint = %q, want frozen IP", address)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
},
|
||||
}
|
||||
response, err := d.get(context.Background(), "http://public.test/image", "test", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if lookups != 1 {
|
||||
t.Fatalf("initial request performed %d DNS resolutions", lookups)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRedirectPreservesLogicalURLHostAndEscaping(t *testing.T) {
|
||||
for _, private := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("private=%v", private), func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/start" {
|
||||
http.Redirect(w, r, "/image%2Fpart?token=a%2Fb&next=%2F%2Fevil.test", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, "%s %s %s", r.Host, r.RequestURI, r.UserAgent())
|
||||
}))
|
||||
defer server.Close()
|
||||
address := "8.8.8.8"
|
||||
if private {
|
||||
address = "10.0.0.10"
|
||||
}
|
||||
d := downloader{
|
||||
resolver: lookupFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr(address)}, nil
|
||||
}),
|
||||
dialContext: func(ctx context.Context, network, endpoint string) (net.Conn, error) {
|
||||
if endpoint != net.JoinHostPort(address, "8080") {
|
||||
return nil, fmt.Errorf("unexpected endpoint %s", endpoint)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
},
|
||||
trustedOrigins: map[string]bool{"http://mirror.test:8080": true},
|
||||
}
|
||||
response, err := d.get(context.Background(), "http://mirror.test:8080/start", "image-agent", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/image%2Fpart?token=a%2Fb&next=%2F%2Fevil.test"
|
||||
if string(body) != "mirror.test:8080 "+path+" image-agent" || response.Request.URL.String() != "http://mirror.test:8080"+path {
|
||||
t.Fatalf("logical request semantics changed: body=%q responseURL=%s", body, response.Request.URL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadIgnoresEnvironmentProxy(t *testing.T) {
|
||||
t.Setenv("HTTP_PROXY", "http://127.0.0.1:1")
|
||||
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:1")
|
||||
t.Setenv("ALL_PROXY", "http://127.0.0.1:1")
|
||||
t.Setenv("NO_PROXY", "")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "ok") }))
|
||||
defer server.Close()
|
||||
d := downloader{
|
||||
dialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if address != "8.8.8.8:80" {
|
||||
return nil, fmt.Errorf("proxy used as endpoint: %s", address)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
},
|
||||
}
|
||||
response, err := d.get(context.Background(), "http://8.8.8.8/image", "test", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
}
|
||||
|
||||
func TestDownloadHTTPSUsesLogicalSNIAndVerifiesCertificate(t *testing.T) {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
|
||||
DNSNames: []string{"mirror.test"}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(certificate)
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, r.Host) }))
|
||||
server.Config.ErrorLog = log.New(io.Discard, "", 0)
|
||||
server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
d := downloader{
|
||||
resolver: lookupFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
|
||||
}),
|
||||
dialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if address != "8.8.8.8:443" {
|
||||
return nil, fmt.Errorf("unexpected TLS endpoint: %s", address)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
},
|
||||
tlsConfig: &tls.Config{RootCAs: roots},
|
||||
}
|
||||
response, err := d.get(context.Background(), "https://mirror.test/image", "test", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil || string(body) != "mirror.test" || response.TLS.ServerName != "mirror.test" || len(response.TLS.VerifiedChains) == 0 {
|
||||
t.Fatalf("logical HTTPS identity lost: body=%q TLS=%+v err=%v", body, response.TLS, err)
|
||||
}
|
||||
if response, err := d.get(context.Background(), "https://wrong.test/image", "test", time.Second); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("HTTPS accepted a certificate for a different logical hostname")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadTimeoutCoversRedirectsAndReturnedBody(t *testing.T) {
|
||||
var handlers sync.WaitGroup
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
handlers.Add(1)
|
||||
defer handlers.Done()
|
||||
if r.URL.Path == "/start" {
|
||||
http.Redirect(w, r, "/body", http.StatusFound)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, "started")
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer server.Close()
|
||||
d := downloader{dialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
}}
|
||||
response, err := d.get(context.Background(), "http://8.8.8.8/start", "test", 300*time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if string(body) != "started" || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("response body lost the total download deadline: body=%q err=%v", body, err)
|
||||
}
|
||||
handlers.Wait()
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"clicd/internal/config"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func TestImageManagementRoutesRequireAdministratorAndOperationScope(t *testing.T) {
|
||||
previous := config.AppConfig
|
||||
t.Cleanup(func() { config.AppConfig = previous })
|
||||
config.AppConfig = &config.ClicdConfig{
|
||||
JWTSecret: "image-permission-test",
|
||||
SubUsers: []config.SubUser{{Username: "tenant"}},
|
||||
ApiKeys: []config.ApiKeyConfig{{
|
||||
ID: "limited-images",
|
||||
// Legacy fixture is migrated by authentication on its first use.
|
||||
KeyHash: "636c6963645f736b5f73656375726974795f626f756e646172795f7465737400",
|
||||
}},
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
setupRoutes(mux)
|
||||
for _, route := range []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/v1/images/custom"},
|
||||
{http.MethodPost, "/api/v1/images/download"},
|
||||
{http.MethodPost, "/api/v1/images/cancel"},
|
||||
{http.MethodDelete, "/api/v1/images/delete"},
|
||||
{http.MethodPut, "/api/v1/images/toggle"},
|
||||
} {
|
||||
for _, access := range []struct {
|
||||
name, token string
|
||||
scopes []string
|
||||
want int
|
||||
}{
|
||||
{"image scope without administrator", "", []string{"image:*"}, http.StatusForbidden},
|
||||
{"administrator without image scope", "", []string{"admin:access"}, http.StatusForbidden},
|
||||
{"administrator with image scope", "", []string{"admin:access", "image:*"}, http.StatusBadRequest},
|
||||
{"administrator session", imageAccessToken(t, ""), nil, http.StatusBadRequest},
|
||||
{"tenant session", imageAccessToken(t, "tenant"), nil, http.StatusForbidden},
|
||||
} {
|
||||
t.Run(route.path+"/"+access.name, func(t *testing.T) {
|
||||
config.AppConfig.ApiKeys[0].Scopes = access.scopes
|
||||
req := httptest.NewRequest(route.method, route.path, strings.NewReader("{"))
|
||||
if access.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+access.token)
|
||||
} else {
|
||||
req.Header.Set("X-API-Key", "clicd_sk_security_boundary_test")
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
if rec.Code != access.want {
|
||||
t.Fatalf("status=%d, want %d: %s", rec.Code, access.want, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
config.AppConfig.ApiKeys[0].Scopes = []string{"image:read"}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/images/enabled", nil)
|
||||
req.Header.Set("X-API-Key", "clicd_sk_security_boundary_test")
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("read-only image access status=%d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func imageAccessToken(t *testing.T, tenant string) string {
|
||||
t.Helper()
|
||||
claims := jwt.MapClaims{"username": "admin", "exp": time.Now().Add(time.Minute).Unix()}
|
||||
if tenant != "" {
|
||||
claims["sub_user"] = tenant
|
||||
}
|
||||
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(config.AppConfig.JWTSecret))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
@@ -103,11 +103,11 @@ func setupRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/v1/containers/", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleSingleContainer))))
|
||||
mux.HandleFunc("/api/v1/templates", corsMiddleware(api.AuthMiddleware(api.HandleTemplates)))
|
||||
mux.HandleFunc("/api/v1/images", corsMiddleware(api.AuthMiddleware(api.HandleImages)))
|
||||
mux.HandleFunc("/api/v1/images/custom", corsMiddleware(api.AuthMiddleware(api.HandleCustomKVMImages)))
|
||||
mux.HandleFunc("/api/v1/images/download", corsMiddleware(api.AuthMiddleware(api.HandleImageDownload)))
|
||||
mux.HandleFunc("/api/v1/images/cancel", corsMiddleware(api.AuthMiddleware(api.HandleImageCancel)))
|
||||
mux.HandleFunc("/api/v1/images/delete", corsMiddleware(api.AuthMiddleware(api.HandleImageDelete)))
|
||||
mux.HandleFunc("/api/v1/images/toggle", corsMiddleware(api.AuthMiddleware(api.HandleImageToggle)))
|
||||
mux.HandleFunc("/api/v1/images/custom", corsMiddleware(api.AdminMiddleware(api.HandleCustomKVMImages)))
|
||||
mux.HandleFunc("/api/v1/images/download", corsMiddleware(api.AdminMiddleware(api.HandleImageDownload)))
|
||||
mux.HandleFunc("/api/v1/images/cancel", corsMiddleware(api.AdminMiddleware(api.HandleImageCancel)))
|
||||
mux.HandleFunc("/api/v1/images/delete", corsMiddleware(api.AdminMiddleware(api.HandleImageDelete)))
|
||||
mux.HandleFunc("/api/v1/images/toggle", corsMiddleware(api.AdminMiddleware(api.HandleImageToggle)))
|
||||
mux.HandleFunc("/api/v1/images/enabled", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleEnabledImages))))
|
||||
mux.HandleFunc("/api/v1/host-info", corsMiddleware(api.AuthMiddleware(api.HandleHostInfo)))
|
||||
mux.HandleFunc("/api/v1/host-history", corsMiddleware(api.AuthMiddleware(api.HandleHostHistory)))
|
||||
|
||||
@@ -24,6 +24,21 @@ PUT /api/v1/images/toggle
|
||||
- `delete` 删除本地镜像缓存。
|
||||
- `toggle` 控制模板是否对创建流程可用。
|
||||
|
||||
镜像源创建、下载、取消、删除和启用管理需要管理员权限。使用外部 API Key 时,需同时授予 `admin:access` 和对应的 `image:*` 操作权限。
|
||||
|
||||
## 私网镜像源
|
||||
|
||||
下载器默认只连接公网镜像。要使用内网镜像站,请在服务器上设置 `CLICD_IMAGE_MIRROR_ORIGINS`,列出允许访问的来源,多个来源用逗号分隔:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
Environment="CLICD_IMAGE_MIRROR_ORIGINS=http://192.168.1.10:8080,https://mirror.example.lan"
|
||||
```
|
||||
|
||||
systemd 部署可通过 `sudo systemctl edit clicd` 添加上述配置,再执行 `sudo systemctl daemon-reload` 和 `sudo systemctl restart clicd`。
|
||||
|
||||
每项只填写协议、主机和可选端口,不填写镜像路径、查询参数或登录凭据。镜像的完整下载 URL 仍在面板中填写。协议或端口不同的来源需要单独批准;重定向不会扩大内网访问范围。本机回环、链路本地和云元数据地址始终禁止访问。
|
||||
|
||||
## Windows 镜像说明
|
||||
|
||||
- ISO 镜像用于安装 Windows,可通过 WebVNC 查看安装过程。
|
||||
|
||||
Generated
+6
-6
@@ -2063,9 +2063,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"version": "3.3.20",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
|
||||
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -2473,9 +2473,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
|
||||
"version": "6.4.5",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.5.tgz",
|
||||
"integrity": "sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"vitepress": "^1.6.4"
|
||||
},
|
||||
"overrides": {
|
||||
"vite": "6.4.3",
|
||||
"vite": "6.4.5",
|
||||
"esbuild": "0.28.1",
|
||||
"postcss": "8.5.23"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user