Files
netbird/proxy
Maycon Santos fa1e241aea [management, client, proxy] Follow-up fixes for private reverse-proxy services (#6268)
* fix(proxy): gate tunnel-peer fast-path on inbound listener marker

forwardWithTunnelPeer previously accepted any RFC1918 / ULA / CGNAT
source IP, so a public client whose address happened to fall in those
ranges could bypass the configured operator auth scheme by colliding
with a known tunnel IP. The fast-path is now gated on
TunnelLookupFromContext(r.Context()) being present — that context value
is attached only by the per-account inbound (overlay) listener, so the
host-facing listener never enters this branch.

Tests updated to reflect the new requirement: requests that don't
carry the inbound marker now fall through to the regular auth flow.

* fix(proxy): harden inbound listener resource + startup-ctx handling

Three correctness fixes on the per-account inbound path, with tests:

- Close the logrus ErrorLog PipeWriter on tearDown. WriterLevel hands
  back an *io.PipeWriter backed by a pipe + scanner goroutine that the
  caller owns; the two writers per account (https + plain) were never
  closed, leaking the pipe and goroutine on every teardown.
- Run the post-Start hooks on context.Background(). runClientStartup
  is launched in a goroutine from AddPeer and was inheriting the
  caller's request-scoped ctx, so a cancelled request could abort the
  inbound bring-up or fail the management status notification. The
  tail is split into notifyClientReady so the contract is testable.

Tests cover the PipeWriter close behaviour and assert the readyHandler
+ NotifyStatus calls receive a non-cancelled background context.

* feat(proxy): short-circuit peer-own-target loops with 421

When a peer that hosts the target of a private service dials its own
service URL the request was being looped through the proxy and back
over WireGuard to the same peer — twice the WG round-trip for no
benefit, with no signal to the caller that something was wrong.

Add isSelfTargetLoop to ReverseProxy.ServeHTTP: when the request
arrived on the per-account overlay listener (IsOverlayOrigin) and the
source tunnel IP matches the target host, refuse the request with 421
Misdirected Request and a body pointing the operator at the backend
directly.

The gate is scoped to overlay origin so requests on the public
listener that happen to share a source IP with the target host are
forwarded normally.

* fix(management): private-service validation + tunnel-IP lookup semantics

- Require an explicit port for L4 cluster targets. validateL4Target
  exempted TargetTypeCluster from the port check, but buildPathMappings
  serializes every L4 target via net.JoinHostPort(host, port) — port=0
  shipped a ":0" upstream. Cluster targets use the same Host/Port
  fields, so the same requirement applies.
- GetPeerByIP returns NotFound on a tunnel-IP miss instead of mapping
  every error to Internal. The proxy's ValidateTunnelPeer probes IPs
  that legitimately aren't in the roster; the miss is expected and now
  distinguishable from a real store failure.
- Thread ctx into getClusterCapability's gorm query so a cancelled
  request doesn't keep the store busy.

Tests updated for the L4-cluster port requirement and the GetPeerByIP
NotFound path.

* fix(client): include offlinePeers in PeerStateByIP lookup

ReplaceOfflinePeers moves peers into d.offlinePeers but PeerStateByIP
only scanned d.peers. Callers (the local DNS filter via
localPeerConnectivity, embed.Client.IdentityForIP used by the
proxy's tunnel-peer validator) were treating known-but-offline peers
as unknown, which:

- causes the DNS filter to keep returning records pointing at peers
  that have no live tunnel, AND
- makes the proxy's local-roster check deny a request from such a
  peer rather than letting the cached management RPC carry the
  authorisation decision.

Search both slices in PeerStateByIP. Adds a unit test for the IPv4
and IPv6 offline-match paths.

* fix(rest): reject empty Delete path params in reverse-proxy clients

ReverseProxyClustersAPI.Delete and ReverseProxyTokensAPI.Delete passed
the path parameter into url.PathEscape without an empty check.
PathEscape("") returns "" which collapses the request onto the
collection endpoint ("/api/reverse-proxies/clusters/" /
"/api/reverse-proxies/proxy-tokens/"), so a caller bug delete with no
id reached a routable URL with surprising semantics (typically 405).

Short-circuit with a typed error before the request is built. Tests
mount a handler on the collection path that fails the test if hit, so
the regression is impossible to reintroduce silently.

* chore(api,ci,docs,test): private-service schema, proto-check, fixups

Non-functional cleanups and contract/CI hardening around the
private-service work:

API schema (openapi.yml):
- Require a non-empty access_groups and mode=http when private=true,
  on both Service and ServiceRequest, mirroring
  validatePrivateRequirements. mode stays optional-but-constrained
  (empty defaults to http server-side), matching runtime.

CI (proto-version-check.yml):
- Cover renamed .pb.go files (read base via previous_filename).
- Match protoc-gen-go-grpc version headers (optional "- " prefix and
  -gen-go-grpc suffix) so grpc-generated files are in scope.

Docs / comments:
- Reword Config field docs to say defaults are applied at Server.Start
  (initDefaults), not New.
- Rename the obsolete --private-inbound flag to --private across
  comments and the proto doc.

Pre-existing test fixups surfaced by review:
- Repair the integration-tagged validate_session_test.go (SignToken
  signature growth + new Manager interface methods).
- Fix the CI-skip boolean precedence so Windows isn't skipped
  unconditionally.
- Guard the router.HTTPListener type assertion with comma-ok.

* fix(proxy): background ctx for already-started AddPeer notification

The earlier ctx fix covered the async runClientStartup path but missed
the synchronous branch: when a service is added to an already-started
client, AddPeer called NotifyStatus with the caller's request-scoped
ctx. A cancelled request/stream could drop the connected notification
to management. Use context.Background() here too, matching
notifyClientReady.

Extends TestNetBird_AddPeer_ExistingStartedClient_NotifiesStatus to
pass a pre-cancelled caller ctx and assert the notification still ran
on a non-cancelled context.

* use the cmd context for roundtripper
2026-06-02 13:40:09 +02:00
..

Netbird Reverse Proxy

The NetBird Reverse Proxy is a separate service that can act as a public entrypoint to certain resources within a NetBird network. At a high level, the way that it operates is:

  • Configured routes are communicated from the Management server to the proxy.
  • For each route the proxy creates a NetBird connection to the NetBird Peer that hosts the resource.
  • When traffic hits the proxy at the address and path configured for the proxied resource, the NetBird Proxy brings up a relevant authentication method for that resource.
  • On successful authentication the proxy will forward traffic onwards to the NetBird Peer.

Proxy Authentication methods supported are:

  • No authentication
  • Oauth2/OIDC
  • Emailed Magic Link
  • Simple PIN
  • HTTP Basic Auth Username and Password

Management Connection and Authentication

The Proxy communicates with the Management server over a gRPC connection. Proxies act as clients to the Management server, the following RPCs are used:

  • Server-side streaming for proxied service updates.
  • Client-side streaming for proxy logs.

To authenticate with the Management server, the proxy server uses Machine-to-Machine OAuth2. If you are using the embedded IdP //TODO: explain how to get credentials. Otherwise, create a new machine-to-machine profile in your IdP for proxy servers and set the relevant settings in the proxy's environment or flags (see below).

User Authentication

When a request hits the Proxy, it looks up the permitted authentication methods for the Host domain. If no authentication methods are registered for the Host domain, then no authentication will be applied (for fully public resources). If any authentication methods are registered for the Host domain, then the Proxy will first serve an authentication page allowing the user to select an authentication method (from the permitted methods) and enter the required information for that authentication method. If the user is successfully authenticated, their request will be forwarded through to the Proxy to be proxied to the relevant Peer. Successful authentication does not guarantee a successful forwarding of the request as there may be failures behind the Proxy, such as with Peer connectivity or the underlying resource.

TLS

Due to the authentication provided, the Proxy uses HTTPS for its endpoint, even if the underlying service is HTTP. Certificate generation can either be via ACME (by default, using Let's Encrypt, but alternative ACME providers can be used) or through certificate files. When not using ACME, the proxy server attempts to load a certificate and key from the files tls.crt and tls.key in a specified certificate directory. When using ACME, the proxy server will store generated certificates in the specified certificate directory.

Auth UI

The authentication UI is a Vite + React application located in the web/ directory. It is embedded into the Go binary at build time.

To build the UI:

cd web
npm install
npm run build

For UI development with hot reload (served at http://localhost:3031):

npm run dev

The built assets in web/dist/ are embedded via //go:embed and served by the web.ServeHTTP handler.

Configuration

NetBird Proxy deployment configuration is via flags or environment variables, with flags taking precedence over the environment. The following deployment configuration is available:

Flag Env Purpose Default
-debug NB_PROXY_DEBUG_LOGS Enable debug logging false
-mgmt NB_PROXY_MANAGEMENT_ADDRESS The address of the management server for the proxy to get configuration from. "https://api.netbird.io:443"
-addr NB_PROXY_ADDRESS The address that the reverse proxy will listen on. ":443
-url NB_PROXY_URL The URL that the proxy will be reached at (where endpoints will be CNAMEd to). If unset, this will fall back to the proxy address. "proxy.netbird.io"
-cert-dir NB_PROXY_CERTIFICATE_DIRECTORY The location that certificates are stored in. "./certs"
-acme-certs NB_PROXY_ACME_CERTIFICATES Whether to use ACME to generate certificates. false
-acme-addr NB_PROXY_ACME_ADDRESS The HTTP address the proxy will listen on to respond to HTTP-01 ACME challenges ":80"
-acme-dir NB_PROXY_ACME_DIRECTORY The directory URL of the ACME server to be used "https://acme-v02.api.letsencrypt.org/directory"
-oidc-id NB_PROXY_OIDC_CLIENT_ID The OAuth2 Client ID for OIDC User Authentication "netbird-proxy"
-oidc-secret NB_PROXY_OIDC_CLIENT_SECRET The OAuth2 Client Secret for OIDC User Authentication ""
-oidc-endpoint NB_PROXY_OIDC_ENDPOINT The OAuth2 provider endpoint for OIDC User Authentication "https://api.netbird.io/oauth2"
-oidc-scopes NB_PROXY_OIDC_SCOPES The OAuth2 scopes for OIDC User Authentication, comma separated "openid,profile,email"