mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-12 15:46:06 +00:00
feat(node): node hardening — mTLS, hashed+zstd reconcile transport, per-node net metrics (#5382)
* fix(api-docs): document clientIpsByGuid route
Restores a green `go test ./...` baseline: TestAPIRoutesDocumented
flagged POST /panel/api/clients/clientIpsByGuid (added in 9385b6c6)
as undocumented in endpoints.ts.
* test(node): characterize current node TLS + API auth behavior
Phase 0 regression net for the mTLS work. These pass on unchanged
production code and lock the pre-mTLS contracts so later phases can be
proven additive:
- tlsConfigForNode: skip -> InsecureSkipVerify (no VerifyConnection);
pin -> VerifyConnection installed.
- checkAPIAuth: bearer match -> Next + api_authed; unauthenticated ->
401 (XHR) / 404; valid session -> Next.
- panel HTTPS listener with no ClientAuth accepts a client that presents
no client certificate (the browsers-keep-working invariant).
* feat(crypto): node-auth CA + client-cert minting (TDD)
Stdlib-only ECDSA P-256 helpers for the node mTLS work:
- GenerateNodeCA: self-signed CA (IsCA, CertSign, path len 0)
- IssueClientCert: client-auth leaf (ExtKeyUsageClientAuth) signed by CA
- LoadCAFromPEM: parse a CA cert+key for issuing / trust-pool building
Tests assert the contract (leaf verifies against the issuing CA with
ExtKeyUsageClientAuth), seen failing on the assertion before impl.
* feat(node): lazy node mTLS CA + client cert in settings (TDD)
SettingService gains opt-in mTLS material, all stored as Setting rows
with empty defaults and kept out of entity.AllSetting (so private keys
never reach the settings UI/export):
- EnsureNodeMtlsCA: mint+persist the node-auth CA once, reuse thereafter
- EnsureMasterClientCert: issue the master client cert from the CA, idempotent
- NodeMtlsClientCAPool: ClientCAs trust pool for the listener; nil when
unconfigured so the no-mTLS path is unchanged
Tests assert idempotency and that the client cert verifies against the CA
for client auth; seen failing on the assertion before impl.
* feat(node): mtls client TLS config + master-cert provider (TDD)
tlsConfigForNode gains an 'mtls' branch that presents the master client
certificate and verifies the node server against system roots (no
InsecureSkipVerify, no custom RootCAs). The cert is supplied via an
injected MasterClientCertProvider so runtime need not import service;
it fails closed when unconfigured. skip/pin contracts unchanged.
* feat(node): allow tokenless mtls nodes in remote do() (TDD)
mtls nodes authenticate with a client certificate, so the bearer token
becomes optional for them: do() no longer rejects an empty ApiToken when
TlsVerifyMode is mtls, and the Authorization header is omitted when no
token is set. Every other mode still requires a token (regression kept).
* feat(node): authenticate verified client certs in checkAPIAuth (TDD)
A completed mTLS handshake (non-empty r.TLS.VerifiedChains) now
authenticates an API request, equivalent to a valid bearer token, and
sets api_authed so the CSRF middleware lets cert-authed mutations
through. Bearer/session/reject paths unchanged. The accept-path assert
was mutation-checked (guard flipped -> test red -> reverted).
* feat(node): opt-in mTLS on the panel listener (TDD; mutation-checked)
web.go now applies VerifyClientCertIfGiven + ClientCAs to the HTTPS
listener when a node trust CA is configured, and wires the master client
cert provider for outbound mtls calls. With no CA the listener is
byte-identical to before (browsers unaffected).
applyNodeMtls is covered end-to-end: no-cert client handshakes (browsers
keep working), a CA-signed client cert verifies, a foreign-CA cert is
rejected at the handshake. Mutation-checked:
- RequireAndVerifyClientCert -> no-cert client rejected (red) -> reverted
- drop ClientCAs -> master cert no longer trusted (red) -> reverted
* feat(node): accept mtls verify-mode + CA reveal endpoint (TDD)
- model.Node.TlsVerifyMode validator now accepts 'mtls'
- normalize() preserves mtls and requires the node scheme to be https
(fail closed), instead of clamping mtls back to verify
- NodeService.NodeMtlsCaCert + POST /panel/api/nodes/mtls/ca return this
panel's node-auth CA cert (public) to paste into a node, minting the CA
+ master client cert on first call
- endpoints.ts documents the new route (doc-sync test)
No model column added (enum is a string), so no migration/codegen.
* feat(node): node mTLS UI + trust-CA setter (TDD)
Backend:
- NodeService.SetNodeMtlsTrustCA + POST /panel/api/nodes/mtls/trustCA
store the CA this panel trusts for incoming node-API client certs
(validates PEM, empty clears); applied on next restart
- endpoints.ts + regenerated openapi.json document both mtls routes
Frontend:
- node form: 'mtls' TLS-verify option + setup hint (zod enum updated)
- Nodes page 'Node mTLS' card: copy this panel's CA, and paste/save the
trusted parent CA
- en-US i18n keys (other locales fall back to en-US)
Gates green: go build (native+windows), vet, go test ./...; frontend
typecheck, lint, vitest (541).
* style(node): gofmt web_mtls_test doc comment
* feat(node): hashed+zstd reconcile transport (TDD, negotiated, mixed-version safe)
Adds an integrity + compression envelope to node config pushes:
- internal/util/wirecodec: shared zstd codec (bomb-capped decode) +
SHA-256 hashing + the header/capability constants
- Remote.do(): always attaches X-Config-Sha256 of the uncompressed body;
zstd-compresses only when the node advertised support (learned from its
X-3x-Node-Caps response header) and the body is >=1KiB
- ConfigEnvelopeMiddleware on /panel/api: advertises the cap, decompresses
and verifies the hash (handler not invoked on mismatch) before binding
Mixed-version safe: old nodes never advertise the cap -> plain bodies;
the hash header is verify-if-present so any panel/node mix interoperates
(existing reconcile tests stay green). klauspost/compress promoted to a
direct dep. Hash-mismatch reject was mutation-checked (compare defeated
-> test red -> reverted).
* feat(node): per-node network throughput metrics (TDD)
The node status response already carries gopsutil netIO.up/down (summed
non-virtual interfaces), so no node-side change is needed:
- probe() parses netIO.up/down into HeartbeatPatch.NetUp/NetDown
- Node gains net_up/net_down columns (AutoMigrate); UpdateHeartbeat
persists them and appends netUp/netDown to the per-node metric history
- NodeMetricKeys whitelists netUp/netDown so the history endpoint serves them
- NodeHistoryPanel renders Net Up/Down sparklines (KB/s, no 0-100 clamp)
- regenerated frontend types + openapi.json for the new Node fields
* feat(node): move node mTLS controls into a toolbar button + modal
The Node mTLS panel was an always-visible card cluttering the nodes
page. Replace it with a 'Node mTLS' button beside 'Add node' that opens
a modal with the same copy-CA + trusted-parent-CA controls; the modal
closes on a successful save. No backend/i18n changes.
* i18n(node): translate mTLS + net-metrics keys for all locales
Adds the node mTLS strings (tlsMtls, mtlsFormHint, mtls.* dialog + the
saveMtls toast) and the netUp/netDown chart labels to all 12 non-English
catalogs (ar, es, fa, id, ja, pt, ru, tr, uk, vi, zh-CN, zh-TW), matching
each catalog's existing terminology. Technical tokens (mTLS/TLS/CA/API/
KB/s) kept verbatim.
* fix(node): address Copilot review on node-hardening PR
- setting_mtls: fail closed on a half-present CA/master-cert pair instead of
silently regenerating (which would rotate the CA and break fleet trust).
- config_envelope: reject non-zstd Content-Encoding on the envelope path
rather than hashing/forwarding a still-encoded body to the handler.
- node mTLS: support tokenless mTLS end-to-end — apiToken is now
required_unless tlsVerifyMode=mtls (model) with matching conditional
validation in NodeFormSchema, so the runtime allowance is actually reachable.
- NodesPage: add a catch block to onSaveTrustCa so save failures surface.
This commit is contained in:
@@ -18,11 +18,16 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/wirecodec"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
const remoteHTTPTimeout = 10 * time.Second
|
||||
|
||||
// zstdMinBodyBytes is the smallest body worth compressing; below it the framing
|
||||
// overhead can outweigh the savings.
|
||||
const zstdMinBodyBytes = 1024
|
||||
|
||||
type envelope struct {
|
||||
Success bool `json:"success"`
|
||||
Msg string `json:"msg"`
|
||||
@@ -34,6 +39,10 @@ type Remote struct {
|
||||
|
||||
mu sync.RWMutex
|
||||
remoteIDByTag map[string]int
|
||||
// supportsZstd is learned from the node's X-3x-Node-Caps response header; once
|
||||
// seen, config pushes to this node are zstd-compressed. Old nodes never set
|
||||
// it, so they keep receiving plain bodies (mixed-version safe).
|
||||
supportsZstd bool
|
||||
|
||||
// Per-node client honoring the TLS verify mode, built once and reused; a
|
||||
// node config change drops the cached Remote so the next one rebuilds it.
|
||||
@@ -61,6 +70,23 @@ func NewRemote(n *model.Node, r NodeEgressResolver) *Remote {
|
||||
|
||||
func (r *Remote) Name() string { return "node:" + r.node.Name }
|
||||
|
||||
func (r *Remote) nodeSupportsZstd() bool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.supportsZstd
|
||||
}
|
||||
|
||||
// recordCaps learns the node's capabilities from a response header so later
|
||||
// pushes can use the negotiated envelope.
|
||||
func (r *Remote) recordCaps(h http.Header) {
|
||||
if !strings.Contains(h.Get(wirecodec.CapsHeader), wirecodec.CapZstd) {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.supportsZstd = true
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// httpClient lazily builds and caches the per-node client honoring the TLS
|
||||
// verify mode, so Remote ops don't fall back to system CA on skip/pin (#5264).
|
||||
func (r *Remote) httpClient() (*http.Client, error) {
|
||||
@@ -99,7 +125,9 @@ func (r *Remote) baseURL() (string, error) {
|
||||
}
|
||||
|
||||
func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelope, error) {
|
||||
if r.node.ApiToken == "" {
|
||||
// mtls nodes authenticate via the client certificate, so a bearer token is
|
||||
// optional for them; every other mode still requires one.
|
||||
if r.node.ApiToken == "" && r.node.TlsVerifyMode != "mtls" {
|
||||
return nil, errors.New("node has no API token configured")
|
||||
}
|
||||
|
||||
@@ -110,34 +138,59 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo
|
||||
target := base + strings.TrimPrefix(path, "/")
|
||||
|
||||
var (
|
||||
reqBody io.Reader
|
||||
bodyBytes []byte
|
||||
contentType string
|
||||
)
|
||||
switch b := body.(type) {
|
||||
case nil:
|
||||
case url.Values:
|
||||
reqBody = strings.NewReader(b.Encode())
|
||||
bodyBytes = []byte(b.Encode())
|
||||
contentType = "application/x-www-form-urlencoded"
|
||||
default:
|
||||
buf, jerr := json.Marshal(b)
|
||||
if jerr != nil {
|
||||
return nil, fmt.Errorf("marshal body: %w", jerr)
|
||||
}
|
||||
reqBody = bytes.NewReader(buf)
|
||||
bodyBytes = buf
|
||||
contentType = "application/json"
|
||||
}
|
||||
|
||||
// Attach the integrity hash of the uncompressed body unconditionally (a new
|
||||
// node verifies it, an old one ignores it), and zstd-compress only when the
|
||||
// node advertised support and the body is worth it.
|
||||
var (
|
||||
reqBody io.Reader
|
||||
hashHex string
|
||||
zstdEncoded bool
|
||||
)
|
||||
if bodyBytes != nil {
|
||||
hashHex = wirecodec.Sha256Hex(bodyBytes)
|
||||
if len(bodyBytes) >= zstdMinBodyBytes && r.nodeSupportsZstd() {
|
||||
bodyBytes = wirecodec.Compress(bodyBytes)
|
||||
zstdEncoded = true
|
||||
}
|
||||
reqBody = bytes.NewReader(bodyBytes)
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(netsafe.ContextWithAllowPrivate(ctx, r.node.AllowPrivateAddress), remoteHTTPTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(cctx, method, target, reqBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+r.node.ApiToken)
|
||||
if r.node.ApiToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+r.node.ApiToken)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if hashHex != "" {
|
||||
req.Header.Set(wirecodec.HashHeader, hashHex)
|
||||
}
|
||||
if zstdEncoded {
|
||||
req.Header.Set("Content-Encoding", wirecodec.EncodingZstd)
|
||||
}
|
||||
|
||||
client, err := r.httpClient()
|
||||
if err != nil {
|
||||
@@ -148,6 +201,7 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo
|
||||
return nil, fmt.Errorf("%s %s: %w", method, path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
r.recordCaps(resp.Header)
|
||||
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/wirecodec"
|
||||
)
|
||||
|
||||
// TestRemoteSendsEnvelopeWhenNodeAdvertisesCap: once a node has advertised the
|
||||
// zstd capability (via a response header on any prior call), a large push is
|
||||
// sent zstd-compressed with an X-Config-Sha256 of the *uncompressed* body.
|
||||
func TestRemoteSendsEnvelopeWhenNodeAdvertisesCap(t *testing.T) {
|
||||
var capturedEnc, capturedHash string
|
||||
var capturedBody []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(wirecodec.CapsHeader, wirecodec.CapZstd) // advertise on every response
|
||||
if r.Method == http.MethodPost {
|
||||
capturedEnc = r.Header.Get("Content-Encoding")
|
||||
capturedHash = r.Header.Get(wirecodec.HashHeader)
|
||||
capturedBody, _ = io.ReadAll(r.Body)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
|
||||
|
||||
// Prime: a prior call learns the cap from the response header.
|
||||
if _, err := r.do(context.Background(), http.MethodGet, "ping", nil); err != nil {
|
||||
t.Fatalf("prime call: %v", err)
|
||||
}
|
||||
|
||||
body := url.Values{}
|
||||
body.Set("settings", strings.Repeat("x", 4096))
|
||||
if _, err := r.do(context.Background(), http.MethodPost, "panel/api/inbounds/add", body); err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
|
||||
if capturedEnc != wirecodec.EncodingZstd {
|
||||
t.Fatalf("Content-Encoding = %q, want %q", capturedEnc, wirecodec.EncodingZstd)
|
||||
}
|
||||
if len(capturedHash) != 64 {
|
||||
t.Fatalf("missing/short X-Config-Sha256: %q", capturedHash)
|
||||
}
|
||||
raw, err := wirecodec.Decompress(capturedBody, 1<<20)
|
||||
if err != nil {
|
||||
t.Fatalf("server could not decompress the body: %v", err)
|
||||
}
|
||||
if string(raw) != body.Encode() {
|
||||
t.Fatalf("decompressed body mismatch: %q != %q", string(raw), body.Encode())
|
||||
}
|
||||
if wirecodec.Sha256Hex(raw) != capturedHash {
|
||||
t.Fatal("X-Config-Sha256 does not match the decompressed body")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteSendsPlainWhenNoCap: a node that never advertises the cap (old
|
||||
// build) receives a plain body — but the integrity hash is still attached
|
||||
// (harmless to old nodes, verified by new ones).
|
||||
func TestRemoteSendsPlainWhenNoCap(t *testing.T) {
|
||||
var capturedEnc, capturedHash string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
capturedEnc = r.Header.Get("Content-Encoding")
|
||||
capturedHash = r.Header.Get(wirecodec.HashHeader)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
|
||||
body := url.Values{}
|
||||
body.Set("settings", strings.Repeat("x", 4096))
|
||||
if _, err := r.do(context.Background(), http.MethodPost, "panel/api/inbounds/add", body); err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
|
||||
if capturedEnc != "" {
|
||||
t.Fatalf("a no-cap node must receive a plain body, got Content-Encoding=%q", capturedEnc)
|
||||
}
|
||||
if len(capturedHash) != 64 {
|
||||
t.Fatalf("integrity hash should always be sent, got %q", capturedHash)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// nodeForPlainServer builds an http (non-TLS) node so do()'s token handling can
|
||||
// be exercised without TLS scaffolding.
|
||||
func nodeForPlainServer(t *testing.T, srv *httptest.Server, mode, token string) *model.Node {
|
||||
t.Helper()
|
||||
u, err := url.Parse(srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("parse url: %v", err)
|
||||
}
|
||||
port, err := strconv.Atoi(u.Port())
|
||||
if err != nil {
|
||||
t.Fatalf("parse port: %v", err)
|
||||
}
|
||||
return &model.Node{
|
||||
Id: 1, Name: "n1", Scheme: "http", Address: u.Hostname(), Port: port,
|
||||
BasePath: "/", ApiToken: token, Enable: true, AllowPrivateAddress: true,
|
||||
TlsVerifyMode: mode,
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteDo_MTLSNodeNoBearer asserts that an mtls node with no API token
|
||||
// sends its request with NO Authorization header and does not trip the
|
||||
// empty-token precondition; while a non-mtls node with no token still errors.
|
||||
func TestRemoteDo_MTLSNodeNoBearer(t *testing.T) {
|
||||
var reached bool
|
||||
var gotAuth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reached = true
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
t.Run("mtls without token sends no Authorization header", func(t *testing.T) {
|
||||
reached, gotAuth = false, "sentinel"
|
||||
r := NewRemote(nodeForPlainServer(t, srv, "mtls", ""), nil)
|
||||
if _, err := r.do(context.Background(), http.MethodGet, "ping", nil); err != nil {
|
||||
t.Fatalf("mtls node with no token must not error on the token precondition: %v", err)
|
||||
}
|
||||
if !reached {
|
||||
t.Fatal("request did not reach the server")
|
||||
}
|
||||
if gotAuth != "" {
|
||||
t.Fatalf("Authorization header = %q, want empty for a tokenless mtls node", gotAuth)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("non-mtls without token still errors", func(t *testing.T) {
|
||||
reached = false
|
||||
r := NewRemote(nodeForPlainServer(t, srv, "verify", ""), nil)
|
||||
if _, err := r.do(context.Background(), http.MethodGet, "ping", nil); err == nil {
|
||||
t.Fatal("non-mtls node with no token must still error")
|
||||
}
|
||||
if reached {
|
||||
t.Fatal("non-mtls tokenless request must not reach the server")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
@@ -16,6 +17,34 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
|
||||
)
|
||||
|
||||
// MasterClientCertProvider supplies the master client certificate this panel
|
||||
// presents to nodes in mtls mode. It is injected by the web layer so the
|
||||
// runtime package need not import service.
|
||||
type MasterClientCertProvider func() (tls.Certificate, error)
|
||||
|
||||
var (
|
||||
masterClientCertMu sync.RWMutex
|
||||
masterClientCert MasterClientCertProvider
|
||||
)
|
||||
|
||||
// SetMasterClientCertProvider installs the provider used to obtain the master
|
||||
// client certificate for mtls nodes. Passing nil disables it.
|
||||
func SetMasterClientCertProvider(p MasterClientCertProvider) {
|
||||
masterClientCertMu.Lock()
|
||||
defer masterClientCertMu.Unlock()
|
||||
masterClientCert = p
|
||||
}
|
||||
|
||||
func getMasterClientCert() (tls.Certificate, error) {
|
||||
masterClientCertMu.RLock()
|
||||
p := masterClientCert
|
||||
masterClientCertMu.RUnlock()
|
||||
if p == nil {
|
||||
return tls.Certificate{}, common.NewError("mtls: master client certificate provider not configured")
|
||||
}
|
||||
return p()
|
||||
}
|
||||
|
||||
// defaultNodeHTTPClient reaches nodes trusting the system CA store ("verify"
|
||||
// mode or plain http); shared so connections pool across nodes.
|
||||
var defaultNodeHTTPClient = &http.Client{
|
||||
@@ -70,6 +99,19 @@ func HTTPClientForNode(n *model.Node, proxyURL string) (*http.Client, error) {
|
||||
}
|
||||
|
||||
func tlsConfigForNode(n *model.Node) (*tls.Config, error) {
|
||||
if n.TlsVerifyMode == "mtls" {
|
||||
// Present the master client cert; verify the node's server cert against
|
||||
// the system roots (no InsecureSkipVerify). mtls authenticates the
|
||||
// caller — it does not change how the node's server identity is checked.
|
||||
cert, err := getMasterClientCert()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}, nil
|
||||
}
|
||||
tlsCfg := &tls.Config{InsecureSkipVerify: true} // lgtm[go/disabled-certificate-check]
|
||||
if n.TlsVerifyMode == "pin" {
|
||||
want, err := DecodeCertPin(n.PinnedCertSha256)
|
||||
|
||||
@@ -3,6 +3,7 @@ package runtime
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
@@ -13,8 +14,59 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
|
||||
)
|
||||
|
||||
// masterCertForTest builds a real CA-signed client certificate for mtls tests.
|
||||
func masterCertForTest(t *testing.T) tls.Certificate {
|
||||
t.Helper()
|
||||
ca, err := crypto.GenerateNodeCA("test ca")
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateNodeCA: %v", err)
|
||||
}
|
||||
client, err := crypto.IssueClientCert(ca, "master")
|
||||
if err != nil {
|
||||
t.Fatalf("IssueClientCert: %v", err)
|
||||
}
|
||||
cert, err := tls.X509KeyPair(client.CertPEM, client.KeyPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("X509KeyPair: %v", err)
|
||||
}
|
||||
return cert
|
||||
}
|
||||
|
||||
// TestTLSConfigForNode_MTLS_PresentsClientCert asserts the mtls branch presents
|
||||
// the master client cert and verifies the node's server cert against system
|
||||
// roots (no InsecureSkipVerify, no custom RootCAs).
|
||||
func TestTLSConfigForNode_MTLS_PresentsClientCert(t *testing.T) {
|
||||
cert := masterCertForTest(t)
|
||||
SetMasterClientCertProvider(func() (tls.Certificate, error) { return cert, nil })
|
||||
t.Cleanup(func() { SetMasterClientCertProvider(nil) })
|
||||
|
||||
cfg, err := tlsConfigForNode(&model.Node{TlsVerifyMode: "mtls"})
|
||||
if err != nil {
|
||||
t.Fatalf("tlsConfigForNode(mtls): %v", err)
|
||||
}
|
||||
if len(cfg.Certificates) != 1 {
|
||||
t.Fatalf("mtls config must present exactly one client certificate, got %d", len(cfg.Certificates))
|
||||
}
|
||||
if cfg.InsecureSkipVerify {
|
||||
t.Fatal("mtls must NOT skip server verification")
|
||||
}
|
||||
if cfg.RootCAs != nil {
|
||||
t.Fatal("mtls verifies the node server against system roots (RootCAs must be nil)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTLSConfigForNode_MTLS_NoProviderFailsClosed asserts mtls fails closed when
|
||||
// no master client certificate is available, rather than silently dropping auth.
|
||||
func TestTLSConfigForNode_MTLS_NoProviderFailsClosed(t *testing.T) {
|
||||
SetMasterClientCertProvider(nil)
|
||||
if _, err := tlsConfigForNode(&model.Node{TlsVerifyMode: "mtls"}); err == nil {
|
||||
t.Fatal("mtls without a configured client cert provider must fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
// nodeForServer builds a node pointing at a loopback test server (loopback is
|
||||
// SSRF-blocked, so AllowPrivateAddress is set for the guarded dialer).
|
||||
func nodeForServer(t *testing.T, srv *httptest.Server, mode, pin string) *model.Node {
|
||||
@@ -180,6 +232,34 @@ func TestHTTPClientForNode_ProxyVerifyNoPin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestTLSConfigForNode_CurrentContract locks the pre-mTLS behavior of
|
||||
// tlsConfigForNode so the "mtls" branch added later cannot silently regress the
|
||||
// existing skip/pin modes (characterization — passes on unchanged code).
|
||||
func TestTLSConfigForNode_CurrentContract(t *testing.T) {
|
||||
t.Run("skip disables verification with no VerifyConnection", func(t *testing.T) {
|
||||
cfg, err := tlsConfigForNode(&model.Node{TlsVerifyMode: "skip"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !cfg.InsecureSkipVerify {
|
||||
t.Fatal("skip mode must set InsecureSkipVerify")
|
||||
}
|
||||
if cfg.VerifyConnection != nil {
|
||||
t.Fatal("skip mode must not install a VerifyConnection")
|
||||
}
|
||||
})
|
||||
t.Run("pin installs a VerifyConnection", func(t *testing.T) {
|
||||
pin := base64.StdEncoding.EncodeToString(make([]byte, sha256.Size))
|
||||
cfg, err := tlsConfigForNode(&model.Node{TlsVerifyMode: "pin", PinnedCertSha256: pin})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cfg.VerifyConnection == nil {
|
||||
t.Fatal("pin mode must install a VerifyConnection")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDecodeCertPin(t *testing.T) {
|
||||
raw := sha256.Sum256([]byte("cert"))
|
||||
hexColon := strings.ToUpper(hex.EncodeToString(raw[:]))
|
||||
|
||||
Reference in New Issue
Block a user