ipn: add FunnelAuth config to HTTPHandler for authenticated funnel

Add an optional Auth field to HTTPHandler so a Funnel HTTP handler can
require visitors to authenticate with Login With Tailscale before being
proxied. FunnelAuth carries the identity provider (v1: "tailscale"), an
optional allowlist of emails/email-domains/tailnets, and a session TTL.

The field is JSON omitempty, so existing serve configs are unchanged on
the wire and old nodes simply ignore it. This change is inert: nothing
reads the field yet. The gate itself lands separately in ipn/ipnlocal.

Updates tailscale/corp#38806

Change-Id: I83f47b65e4c625e3034bc41a62c747194efdff59
Signed-off-by: Kabir Sikand <[email protected]>
This commit is contained in:
Kabir Sikand committed 2026-07-27 18:09:18 +00:00
1 parent 514e50bd1b
commit 148a187d3c
5 files changed
+204 -2

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
//go:generate go run tailscale.com/cmd/viewer -type=LoginProfile,Prefs,ServeConfig,ServiceConfig,TCPPortHandler,HTTPHandler,WebServerConfig
//go:generate go run tailscale.com/cmd/viewer -type=LoginProfile,Prefs,ServeConfig,ServiceConfig,TCPPortHandler,HTTPHandler,FunnelAuth,WebServerConfig
// Package ipn implements the interactions between the Tailscale cloud
// control plane and the local network stack.
+21
View File
@@ -239,6 +239,7 @@ func (src *HTTPHandler) Clone() *HTTPHandler {
dst := new(HTTPHandler)
*dst = *src
dst.AcceptAppCaps = append(src.AcceptAppCaps[:0:0], src.AcceptAppCaps...)
dst.Auth = src.Auth.Clone()
return dst
}
@@ -249,6 +250,26 @@ var _HTTPHandlerCloneNeedsRegeneration = HTTPHandler(struct {
Text string
AcceptAppCaps []tailcfg.PeerCapability
Redirect string
Auth *FunnelAuth
}{})
// Clone makes a deep copy of FunnelAuth.
// The result aliases no memory with the original.
func (src *FunnelAuth) Clone() *FunnelAuth {
if src == nil {
return nil
}
dst := new(FunnelAuth)
*dst = *src
dst.Allow = append(src.Allow[:0:0], src.Allow...)
return dst
}
// A compilation failure here means this code must be regenerated, with the command at the top of this file.
var _FunnelAuthCloneNeedsRegeneration = FunnelAuth(struct {
Provider string
Allow []string
SessionTTL time.Duration
}{})
// Clone makes a deep copy of WebServerConfig.
+99 -1
View File
@@ -21,7 +21,7 @@ import (
"tailscale.com/types/views"
)
//go:generate go run tailscale.com/cmd/cloner -clonefunc=false -type=LoginProfile,Prefs,ServeConfig,ServiceConfig,TCPPortHandler,HTTPHandler,WebServerConfig
//go:generate go run tailscale.com/cmd/cloner -clonefunc=false -type=LoginProfile,Prefs,ServeConfig,ServiceConfig,TCPPortHandler,HTTPHandler,FunnelAuth,WebServerConfig
// View returns a read-only view of LoginProfile.
func (p *LoginProfile) View() LoginProfileView {
@@ -945,6 +945,14 @@ func (v HTTPHandlerView) AcceptAppCaps() views.Slice[tailcfg.PeerCapability] {
// - ${REQUEST_URI}: replaced with the request's full URI (path and query string)
func (v HTTPHandlerView) Redirect() string { return v.ж.Redirect }
// Auth, if non-nil, configures authentication for Funnel requests to
// this handler. Visitors from the public internet are redirected to
// Login With Tailscale and admitted only with a valid session,
// optionally filtered by Auth.Allow. Nil means unauthenticated
// (the default; today's behavior). It has no effect on requests
// arriving over the tailnet.
func (v HTTPHandlerView) Auth() FunnelAuthView { return v.ж.Auth.View() }
// A compilation failure here means this code must be regenerated, with the command at the top of this file.
var _HTTPHandlerViewNeedsRegeneration = HTTPHandler(struct {
Path string
@@ -952,6 +960,96 @@ var _HTTPHandlerViewNeedsRegeneration = HTTPHandler(struct {
Text string
AcceptAppCaps []tailcfg.PeerCapability
Redirect string
Auth *FunnelAuth
}{})
// View returns a read-only view of FunnelAuth.
func (p *FunnelAuth) View() FunnelAuthView {
return FunnelAuthView{ж: p}
}
// FunnelAuthView provides a read-only view over FunnelAuth.
//
// Its methods should only be called if `Valid()` returns true.
type FunnelAuthView struct {
// ж is the underlying mutable value, named with a hard-to-type
// character that looks pointy like a pointer.
// It is named distinctively to make you think of how dangerous it is to escape
// to callers. You must not let callers be able to mutate it.
ж *FunnelAuth
}
// Valid reports whether v's underlying value is non-nil.
func (v FunnelAuthView) Valid() bool { return v.ж != nil }
// AsStruct returns a clone of the underlying value which aliases no memory with
// the original.
func (v FunnelAuthView) AsStruct() *FunnelAuth {
if v.ж == nil {
return nil
}
return v.ж.Clone()
}
// MarshalJSON implements [jsonv1.Marshaler].
func (v FunnelAuthView) MarshalJSON() ([]byte, error) {
return jsonv1.Marshal(v.ж)
}
// MarshalJSONTo implements [jsonv2.MarshalerTo].
func (v FunnelAuthView) MarshalJSONTo(enc *jsontext.Encoder) error {
return jsonv2.MarshalEncode(enc, v.ж)
}
// UnmarshalJSON implements [jsonv1.Unmarshaler].
func (v *FunnelAuthView) UnmarshalJSON(b []byte) error {
if v.ж != nil {
return errors.New("already initialized")
}
if len(b) == 0 {
return nil
}
var x FunnelAuth
if err := jsonv1.Unmarshal(b, &x); err != nil {
return err
}
v.ж = &x
return nil
}
// UnmarshalJSONFrom implements [jsonv2.UnmarshalerFrom].
func (v *FunnelAuthView) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if v.ж != nil {
return errors.New("already initialized")
}
var x FunnelAuth
if err := jsonv2.UnmarshalDecode(dec, &x); err != nil {
return err
}
v.ж = &x
return nil
}
// Provider is the identity provider. v1 supports only "tailscale".
func (v FunnelAuthView) Provider() string { return v.ж.Provider }
// Allow is an optional allowlist. Empty = any Tailscale user.
// Each entry is one of:
//
// "[email protected]" exact email
// "*@example.com" email domain (requires a verified email)
// "tailnet:example.com" a specific tailnet
func (v FunnelAuthView) Allow() views.Slice[string] { return views.SliceOf(v.ж.Allow) }
// SessionTTL is how long a browser session cookie is valid.
// Zero means a default of 12 hours.
func (v FunnelAuthView) SessionTTL() time.Duration { return v.ж.SessionTTL }
// A compilation failure here means this code must be regenerated, with the command at the top of this file.
var _FunnelAuthViewNeedsRegeneration = FunnelAuth(struct {
Provider string
Allow []string
SessionTTL time.Duration
}{})
// View returns a read-only view of WebServerConfig.
+27
View File
@@ -14,6 +14,7 @@ import (
"slices"
"strconv"
"strings"
"time"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
@@ -182,10 +183,36 @@ type HTTPHandler struct {
// - ${REQUEST_URI}: replaced with the request's full URI (path and query string)
Redirect string `json:",omitempty"`
// Auth, if non-nil, configures authentication for Funnel requests to
// this handler. Visitors from the public internet are redirected to
// Login With Tailscale and admitted only with a valid session,
// optionally filtered by Auth.Allow. Nil means unauthenticated
// (the default; today's behavior). It has no effect on requests
// arriving over the tailnet.
Auth *FunnelAuth `json:",omitempty"`
// TODO(bradfitz): bool to not enumerate directories? TTL on mapping for
// temporary ones? Error codes?
}
// FunnelAuth configures authentication for a Funnel HTTP handler.
// Nil means unauthenticated (today's behavior).
type FunnelAuth struct {
// Provider is the identity provider. v1 supports only "tailscale".
Provider string `json:",omitempty"`
// Allow is an optional allowlist. Empty = any Tailscale user.
// Each entry is one of:
// "[email protected]" exact email
// "*@example.com" email domain (requires a verified email)
// "tailnet:example.com" a specific tailnet
Allow []string `json:",omitempty"`
// SessionTTL is how long a browser session cookie is valid.
// Zero means a default of 12 hours.
SessionTTL time.Duration `json:",omitempty"`
}
// WebHandlerExists reports whether if the ServeConfig Web handler exists for
// the given host:port and mount point.
func (sc *ServeConfig) WebHandlerExists(svcName tailcfg.ServiceName, hp HostPort, mount string) bool {
+56
View File
@@ -4,12 +4,68 @@
package ipn
import (
"encoding/json"
"reflect"
"testing"
"time"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
)
// TestFunnelAuthJSONRoundTrip verifies that HTTPHandler.Auth survives a
// JSON round trip (ServeConfig persists as JSON in the StateStore) and
// that configs without Auth are unaffected by the new field.
func TestFunnelAuthJSONRoundTrip(t *testing.T) {
sc := &ServeConfig{
Web: map[HostPort]*WebServerConfig{
"foo.test.ts.net:443": {
Handlers: map[string]*HTTPHandler{
"/": {
Proxy: "http://127.0.0.1:3000",
Auth: &FunnelAuth{
Provider: "tailscale",
Allow: []string{"[email protected]", "*@example.com", "tailnet:example.com"},
SessionTTL: 12 * time.Hour,
},
},
"/public": {Proxy: "http://127.0.0.1:3001"},
},
},
},
}
j, err := json.Marshal(sc)
if err != nil {
t.Fatal(err)
}
var got ServeConfig
if err := json.Unmarshal(j, &got); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(sc, &got) {
t.Errorf("round trip mismatch:\n got: %+v\nwant: %+v", &got, sc)
}
// A handler without Auth must not emit the field (old nodes ignore
// unknown fields, but keeping the wire format identical is cheaper).
hj, err := json.Marshal(got.Web["foo.test.ts.net:443"].Handlers["/public"])
if err != nil {
t.Fatal(err)
}
if want := `{"Proxy":"http://127.0.0.1:3001"}`; string(hj) != want {
t.Errorf("handler without Auth marshals to %s; want %s", hj, want)
}
// An old config (no Auth anywhere) still loads with Auth == nil.
var old ServeConfig
if err := json.Unmarshal([]byte(`{"Web":{"foo.test.ts.net:443":{"Handlers":{"/":{"Proxy":"http://127.0.0.1:3000"}}}}}`), &old); err != nil {
t.Fatal(err)
}
if h := old.Web["foo.test.ts.net:443"].Handlers["/"]; h.Auth != nil {
t.Errorf("old config unexpectedly has Auth: %+v", h.Auth)
}
}
func TestCheckFunnelAccess(t *testing.T) {
caps := func(c ...tailcfg.NodeCapability) []tailcfg.NodeCapability { return c }
const portAttr tailcfg.NodeCapability = "https://tailscale.com/cap/funnel-ports?ports=443,8080-8090,8443,"