From e6ed02754abc76b010a20b6d9af3f993bb9ae356 Mon Sep 17 00:00:00 2001 From: Oli Strik Date: Mon, 4 May 2026 15:09:40 +0200 Subject: [PATCH 1/3] feat: add support for grant replacement Signed-off-by: Oli Strik --- .gitignore | 2 + README.md | 50 +++++++++++---- auth.go | 57 +++++++++++++++++ cel_test.go | 174 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 272 insertions(+), 11 deletions(-) create mode 100644 .gitignore create mode 100644 cel_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3195517 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.test +*.test.exe diff --git a/README.md b/README.md index 08d5fb1..5a8ebfe 100644 --- a/README.md +++ b/README.md @@ -329,25 +329,53 @@ The following fields are set on the Caddy user object: - `user.tailscale_name`: the display name of the Tailscale user - `user.tailscale_profile_picture`: the URL of the Tailscale user's profile picture - `user.tailscale_tailnet`: the name of the Tailscale network the user is a member of +- `user.tailscale_grants`: JSON string of the peer's granted [application capabilities](#application-capabilities), if any These values can be mapped to HTTP headers that are then passed to an application that supports proxy authentication such as [Gitea] or [Grafana]. -You might have something like the following in your Caddyfile: -```caddyfile -:80 { - bind tailscale/gitea - tailscale_auth - reverse_proxy http://localhost:3000 { - header_up X-Webauth-User {http.auth.user.tailscale_login} - header_up X-Webauth-Email {http.auth.user.tailscale_user} - header_up X-Webauth-Name {http.auth.user.tailscale_name} +When used with a Tailscale listener (described above), that Tailscale node is used to identify the remote user. +Otherwise, the authentication provider will attempt to connect to the Tailscale daemon running on the local machine. + +## Application Capabilities + +[Tailscale application capabilities](https://tailscale.com/kb/1537/grants-app-capabilities) (grants) allow you to pass +application-specific data defined in your Tailscale ACL policy file to your Caddy site. +These are exposed through the `{tailscale.grants}` [Caddy placeholder](https://caddyserver.com/docs/conventions#placeholders) +for use in [CEL expression matchers](https://caddyserver.com/docs/caddyfile/matchers#expression). + +For example, given the following grant in your Tailscale ACL policy: + +```json +{ + "src": "autogroup:admins", + "dst": "tag:caddy", + "app": { + "example.com/app": [ + { "admin": true } + ] } } ``` -When used with a Tailscale listener (described above), that Tailscale node is used to identify the remote user. -Otherwise, the authentication provider will attempt to connect to the Tailscale daemon running on the local machine. +You can route requests based on grant values in a Caddyfile: + +```caddyfile +handle /admin { + @admin expression `{tailscale.grants}["example.com/app"][0].admin == true` + respond @admin "Welcome admin" + respond "not authorized" 401 +} +``` + +Or forward the grants to a backend application using the user metadata: + +```caddyfile +reverse_proxy localhost:3000 { + header_up X-Tailscale-User {http.auth.user.tailscale_login} + header_up X-Tailscale-App-Caps {http.auth.user.tailscale_grants} +} +``` [tagged devices]: https://tailscale.com/kb/1068/acl-tags [Gitea]: https://docs.gitea.com/usage/authentication#reverse-proxy diff --git a/auth.go b/auth.go index c84ac09..d9f0afc 100644 --- a/auth.go +++ b/auth.go @@ -6,6 +6,7 @@ package tscaddy // auth.go contains the TailscaleAuth module and supporting logic. import ( + "encoding/json" "fmt" "net" "net/http" @@ -18,6 +19,7 @@ import ( "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth" "tailscale.com/client/local" + "tailscale.com/tailcfg" "tailscale.com/tsnet" ) @@ -132,6 +134,7 @@ type tsnetListener interface { // - tailscale_name: the user's display name // - tailscale_profile_picture: the user's profile picture URL // - tailscale_tailnet: the user's tailnet name (if the user is not connecting to a shared node) +// - tailscale_grants: JSON string of the peer's granted capabilities (if any) func (ta Auth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.User, bool, error) { user := caddyauth.User{} @@ -156,6 +159,31 @@ func (ta Auth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.U } } + // Extract grants from CapMap + grants := extractGrants(info.CapMap) + + // Register replacer mapping for {tailscale.grants} + repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) + repl.Map(func(key string) (any, bool) { + if key == "tailscale.grants" { + if len(grants) == 0 { + // Return empty map so CEL operations like "in" work without "no such overload" + return map[string]any{}, true + } + return grants, true + } + return nil, false + }) + + // Marshal grants to JSON for metadata + var grantsJSON string + if len(grants) > 0 { + b, err := json.Marshal(grants) + if err == nil { + grantsJSON = string(b) + } + } + user.ID = info.UserProfile.LoginName user.Metadata = map[string]string{ "tailscale_login": strings.Split(info.UserProfile.LoginName, "@")[0], @@ -163,10 +191,39 @@ func (ta Auth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.U "tailscale_name": info.UserProfile.DisplayName, "tailscale_profile_picture": info.UserProfile.ProfilePicURL, "tailscale_tailnet": tailnet, + "tailscale_grants": grantsJSON, } return user, true, nil } +// extractGrants filters the CapMap based on acceptAppCaps and returns a map suitable for JSON marshaling. +// If acceptAppCaps is empty, all capabilities are included. +func extractGrants(capMap tailcfg.PeerCapMap) map[string]any { + if len(capMap) == 0 { + return nil + } + + grants := make(map[string]any) + + for cap, vals := range capMap { + var parsed []any + for _, v := range vals { + var obj any + if err := json.Unmarshal([]byte(v), &obj); err == nil { + parsed = append(parsed, obj) + } else { + parsed = append(parsed, string(v)) + } + } + grants[string(cap)] = parsed + } + + if len(grants) == 0 { + return nil + } + return grants +} + func parseAuthConfig(_ httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var ta Auth diff --git a/cel_test.go b/cel_test.go new file mode 100644 index 0000000..72b7738 --- /dev/null +++ b/cel_test.go @@ -0,0 +1,174 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: Apache-2.0 + +package tscaddy + +import ( + "context" + "net/http/httptest" + "testing" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" +) + +// TestTailscaleGrantsCEL verifies that the tailscale.grants placeholder +// can be used in CEL expressions via the expression matcher. +func TestTailscaleGrantsCEL(t *testing.T) { + testGrants := map[string]any{ + "example.com/app": []any{ + map[string]any{ + "admin": true, + "role": "admin", + }, + }, + "example.com/cap/sql": []any{ + map[string]any{ + "access": "read", + }, + }, + } + + req := httptest.NewRequest("GET", "http://example.com", nil) + + // Create a replacer with the tailscale.grants placeholder handler, + // as Auth.Authenticate does during request processing. + repl := caddy.NewReplacer() + repl.Map(func(key string) (any, bool) { + if key == "tailscale.grants" { + return testGrants, true + } + return nil, false + }) + ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) + req = req.WithContext(ctx) + + caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) + defer cancel() + + t.Run("in_operator_key_exists", func(t *testing.T) { + expr := &caddyhttp.MatchExpression{ + Expr: `"example.com/app" in {tailscale.grants}`, + } + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(req) + if err != nil { + t.Fatalf("CEL evaluation failed: %v", err) + } + if !matches { + t.Error("expected 'example.com/app' in grants") + } + }) + + t.Run("map_index_with_list_size", func(t *testing.T) { + expr := &caddyhttp.MatchExpression{ + Expr: `{tailscale.grants}["example.com/app"].size() == 1`, + } + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(req) + if err != nil { + t.Fatalf("CEL evaluation failed: %v", err) + } + if !matches { + t.Error("expected grants map indexing to return list with 1 element") + } + }) + + t.Run("deep_field_access", func(t *testing.T) { + // Access a nested field: grants["example.com/app"][0].admin == true + expr := &caddyhttp.MatchExpression{ + Expr: `{tailscale.grants}["example.com/app"][0].admin == true`, + } + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(req) + if err != nil { + t.Fatalf("CEL evaluation failed: %v", err) + } + if !matches { + t.Error("expected admin to be true") + } + }) + + t.Run("in_operator_missing_key", func(t *testing.T) { + expr := &caddyhttp.MatchExpression{ + Expr: `"example.com/nonexistent" in {tailscale.grants}`, + } + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(req) + if err != nil { + t.Fatalf("CEL evaluation failed: %v", err) + } + if matches { + t.Error("expected nonexistent key not to be in grants") + } + }) + + t.Run("grants_empty_when_not_set", func(t *testing.T) { + // Request without grants in context should get nil from replacer + emptyReq := httptest.NewRequest("GET", "http://example.com", nil) + emptyRepl := caddy.NewReplacer() + emptyCtx := context.WithValue(emptyReq.Context(), caddy.ReplacerCtxKey, emptyRepl) + emptyReq = emptyReq.WithContext(emptyCtx) + + emptyRepl.Map(func(key string) (any, bool) { + if key == "tailscale.grants" { + // Return empty map, as Auth.Authenticate now does + return map[string]any{}, true + } + return nil, false + }) + + // Check that in operator returns false (not an error) when grants are nil + expr := &caddyhttp.MatchExpression{ + Expr: `"example.com/app" in {tailscale.grants}`, + } + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(emptyReq) + if err != nil { + t.Fatalf("CEL evaluation failed with 'no such overload': %v", err) + } + if matches { + t.Error("expected in operator to return false when grants are empty") + } + }) + + t.Run("null_check_empty_grants", func(t *testing.T) { + // Same setup: empty grants + emptyReq := httptest.NewRequest("GET", "http://example.com", nil) + emptyRepl := caddy.NewReplacer() + emptyCtx := context.WithValue(emptyReq.Context(), caddy.ReplacerCtxKey, emptyRepl) + emptyReq = emptyReq.WithContext(emptyCtx) + + emptyRepl.Map(func(key string) (any, bool) { + if key == "tailscale.grants" { + return map[string]any{}, true + } + return nil, false + }) + + // Empty map is not null, so == null should be false + expr := &caddyhttp.MatchExpression{ + Expr: `{tailscale.grants} == null`, + } + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(emptyReq) + if err != nil { + t.Fatalf("CEL evaluation failed: %v", err) + } + if matches { + t.Error("expected tailscale.grants to not be null when grants are empty") + } + }) +} From 47d2583d84f14d054b45c9170093d0a8002cb319 Mon Sep 17 00:00:00 2001 From: olistrik Date: Wed, 21 Oct 2026 20:10:40 +0200 Subject: [PATCH 2/3] fix: render {tailscale.grants} as JSON outside CEL The placeholder returned a bare map[string]any, which caddy.ToString formats with %+v, so `header_up X {tailscale.grants}` sent Go debug output such as `map[example.com/app:[map[admin:true]]]`. Return a named Grants map type that implements fmt.Stringer. CEL still sees a map, while headers and other string contexts get the same JSON object that tailscale serve sends in Tailscale-App-Capabilities, or {} when there are no grants. Non-ASCII characters are escaped as \uXXXX so the header value is always ASCII and valid JSON. The tailscale_grants user metadata now uses the same encoding, and the tests exercise the real replacer func instead of a copy of it. Signed-off-by: olistrik --- README.md | 32 ++++++- auth.go | 94 +++++++++++++----- cel_test.go | 271 +++++++++++++++++++++++++--------------------------- 3 files changed, 226 insertions(+), 171 deletions(-) diff --git a/README.md b/README.md index 5a8ebfe..06e4e33 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ The following fields are set on the Caddy user object: - `user.tailscale_name`: the display name of the Tailscale user - `user.tailscale_profile_picture`: the URL of the Tailscale user's profile picture - `user.tailscale_tailnet`: the name of the Tailscale network the user is a member of -- `user.tailscale_grants`: JSON string of the peer's granted [application capabilities](#application-capabilities), if any +- `user.tailscale_grants`: JSON string of the peer's granted [application capabilities](#application-capabilities), or `{}` if none These values can be mapped to HTTP headers that are then passed to an application that supports proxy authentication such as [Gitea] or [Grafana]. @@ -368,15 +368,39 @@ handle /admin { } ``` -Or forward the grants to a backend application using the user metadata: +Or forward the grants to a backend application in a header: ```caddyfile reverse_proxy localhost:3000 { - header_up X-Tailscale-User {http.auth.user.tailscale_login} - header_up X-Tailscale-App-Caps {http.auth.user.tailscale_grants} + header_up Tailscale-User-Login {http.auth.user.tailscale_user} + header_up Tailscale-App-Capabilities {tailscale.grants} } ``` +When used outside of a CEL expression, `{tailscale.grants}` (and `{http.auth.user.tailscale_grants}`) +renders as the same JSON object that `tailscale serve` sends in its `Tailscale-App-Capabilities` header, +mapping each capability name to an array of its values, or `{}` if the user has no grants. +For example: + +```json +{"example.com/app":[{"admin":true}]} +``` + +Some differences from `tailscale serve` to be aware of: + +- `tailscale serve` only forwards the capabilities listed in `--accept-app-caps`. + `{tailscale.grants}` contains all of the user's capabilities, for every application. +- `tailscale serve` [RFC 2047] Q-encodes the header value if it contains non-ASCII characters. + `{tailscale.grants}` instead escapes non-ASCII characters as JSON `\uXXXX` sequences, + so the value is always plain ASCII and valid JSON. + Decoding it as RFC 2047 leaves it unchanged, so a backend written for `tailscale serve` can read it either way. +- `tailscale serve` removes `Tailscale-*` headers sent by the client. + `header_up` overwrites a header sent by the client, but any route that does not pass through + `tailscale_auth` should remove these headers itself (for example, `header_up -Tailscale-*`), + or a client could forge them. + +[RFC 2047]: https://www.rfc-editor.org/rfc/rfc2047 + [tagged devices]: https://tailscale.com/kb/1068/acl-tags [Gitea]: https://docs.gitea.com/usage/authentication#reverse-proxy [Grafana]: https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/auth-proxy/ diff --git a/auth.go b/auth.go index d9f0afc..dd3ebf0 100644 --- a/auth.go +++ b/auth.go @@ -12,6 +12,8 @@ import ( "net/http" "reflect" "strings" + "unicode/utf16" + "unicode/utf8" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" @@ -134,7 +136,7 @@ type tsnetListener interface { // - tailscale_name: the user's display name // - tailscale_profile_picture: the user's profile picture URL // - tailscale_tailnet: the user's tailnet name (if the user is not connecting to a shared node) -// - tailscale_grants: JSON string of the peer's granted capabilities (if any) +// - tailscale_grants: JSON object of the peer's granted capabilities ("{}" if none) func (ta Auth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.User, bool, error) { user := caddyauth.User{} @@ -164,25 +166,7 @@ func (ta Auth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.U // Register replacer mapping for {tailscale.grants} repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) - repl.Map(func(key string) (any, bool) { - if key == "tailscale.grants" { - if len(grants) == 0 { - // Return empty map so CEL operations like "in" work without "no such overload" - return map[string]any{}, true - } - return grants, true - } - return nil, false - }) - - // Marshal grants to JSON for metadata - var grantsJSON string - if len(grants) > 0 { - b, err := json.Marshal(grants) - if err == nil { - grantsJSON = string(b) - } - } + repl.Map(grantsReplacer(grants)) user.ID = info.UserProfile.LoginName user.Metadata = map[string]string{ @@ -191,22 +175,80 @@ func (ta Auth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.U "tailscale_name": info.UserProfile.DisplayName, "tailscale_profile_picture": info.UserProfile.ProfilePicURL, "tailscale_tailnet": tailnet, - "tailscale_grants": grantsJSON, + "tailscale_grants": grants.String(), } return user, true, nil } -// extractGrants filters the CapMap based on acceptAppCaps and returns a map suitable for JSON marshaling. -// If acceptAppCaps is empty, all capabilities are included. -func extractGrants(capMap tailcfg.PeerCapMap) map[string]any { +// Grants holds a peer's application capabilities, keyed by capability name, +// with each value being the list of that capability's parsed JSON values. +// +// It is a map so that CEL expressions can index into it, and implements +// fmt.Stringer so that it renders as JSON when used in a header or other +// string context. +type Grants map[string]any + +// String returns the grants as a JSON object, matching the format of the +// Tailscale-App-Capabilities header sent by tailscale serve. Non-ASCII +// characters are escaped as \uXXXX so the value is safe to use as an HTTP +// header while remaining valid JSON. +func (g Grants) String() string { + if g == nil { + return "{}" + } + b, err := json.Marshal(map[string]any(g)) + if err != nil { + return "{}" + } + return asciiJSON(b) +} + +// asciiJSON escapes all non-ASCII characters in the JSON document b as +// \uXXXX sequences. Non-ASCII bytes can only appear inside JSON strings, so +// the result is an equivalent JSON document. +func asciiJSON(b []byte) string { + var sb strings.Builder + sb.Grow(len(b)) + for _, r := range string(b) { + switch { + case r < utf8.RuneSelf: + sb.WriteRune(r) + case r > 0xFFFF: + r1, r2 := utf16.EncodeRune(r) + fmt.Fprintf(&sb, `\u%04x\u%04x`, r1, r2) + default: + fmt.Fprintf(&sb, `\u%04x`, r) + } + } + return sb.String() +} + +// grantsReplacer returns a replacer func that resolves {tailscale.grants}. +// It always returns a non-nil Grants, so that CEL operations like "in" work +// without "no such overload" errors and headers render as "{}". +func grantsReplacer(grants Grants) caddy.ReplacerFunc { + if grants == nil { + grants = Grants{} + } + return func(key string) (any, bool) { + if key == "tailscale.grants" { + return grants, true + } + return nil, false + } +} + +// extractGrants converts a PeerCapMap into Grants, parsing each capability +// value as JSON. Values that are not valid JSON are kept as strings. +func extractGrants(capMap tailcfg.PeerCapMap) Grants { if len(capMap) == 0 { return nil } - grants := make(map[string]any) + grants := make(Grants) for cap, vals := range capMap { - var parsed []any + parsed := make([]any, 0, len(vals)) for _, v := range vals { var obj any if err := json.Unmarshal([]byte(v), &obj); err == nil { diff --git a/cel_test.go b/cel_test.go index 72b7738..51ce871 100644 --- a/cel_test.go +++ b/cel_test.go @@ -5,170 +5,159 @@ package tscaddy import ( "context" + "encoding/json" + "net/http" "net/http/httptest" "testing" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" + "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers" + "tailscale.com/tailcfg" ) -// TestTailscaleGrantsCEL verifies that the tailscale.grants placeholder -// can be used in CEL expressions via the expression matcher. -func TestTailscaleGrantsCEL(t *testing.T) { - testGrants := map[string]any{ - "example.com/app": []any{ - map[string]any{ - "admin": true, - "role": "admin", - }, - }, - "example.com/cap/sql": []any{ - map[string]any{ - "access": "read", - }, - }, - } +var testCapMap = tailcfg.PeerCapMap{ + "example.com/app": []tailcfg.RawMessage{ + `{"admin":true,"role":"admin"}`, + }, + "example.com/cap/sql": []tailcfg.RawMessage{ + `{"access":"read"}`, + }, +} +// newGrantsRequest returns a request whose replacer resolves +// {tailscale.grants} as Auth.Authenticate does for the given CapMap. +func newGrantsRequest(capMap tailcfg.PeerCapMap) (*http.Request, *caddy.Replacer) { req := httptest.NewRequest("GET", "http://example.com", nil) - - // Create a replacer with the tailscale.grants placeholder handler, - // as Auth.Authenticate does during request processing. repl := caddy.NewReplacer() - repl.Map(func(key string) (any, bool) { - if key == "tailscale.grants" { - return testGrants, true - } - return nil, false - }) + repl.Map(grantsReplacer(extractGrants(capMap))) ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl) - req = req.WithContext(ctx) + return req.WithContext(ctx), repl +} +// TestTailscaleGrantsCEL verifies that the tailscale.grants placeholder +// can be used in CEL expressions via the expression matcher. +func TestTailscaleGrantsCEL(t *testing.T) { caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() - t.Run("in_operator_key_exists", func(t *testing.T) { - expr := &caddyhttp.MatchExpression{ - Expr: `"example.com/app" in {tailscale.grants}`, - } - if err := expr.Provision(caddyCtx); err != nil { - t.Fatalf("Provision failed: %v", err) - } - matches, err := expr.MatchWithError(req) - if err != nil { - t.Fatalf("CEL evaluation failed: %v", err) - } - if !matches { - t.Error("expected 'example.com/app' in grants") - } - }) - - t.Run("map_index_with_list_size", func(t *testing.T) { - expr := &caddyhttp.MatchExpression{ - Expr: `{tailscale.grants}["example.com/app"].size() == 1`, - } - if err := expr.Provision(caddyCtx); err != nil { - t.Fatalf("Provision failed: %v", err) - } - matches, err := expr.MatchWithError(req) - if err != nil { - t.Fatalf("CEL evaluation failed: %v", err) - } - if !matches { - t.Error("expected grants map indexing to return list with 1 element") - } - }) + tests := []struct { + name string + capMap tailcfg.PeerCapMap + expr string + want bool + }{ + {"in_operator_key_exists", testCapMap, `"example.com/app" in {tailscale.grants}`, true}, + {"in_operator_missing_key", testCapMap, `"example.com/nonexistent" in {tailscale.grants}`, false}, + {"map_index_with_list_size", testCapMap, `{tailscale.grants}["example.com/app"].size() == 1`, true}, + {"deep_field_access", testCapMap, `{tailscale.grants}["example.com/app"][0].admin == true`, true}, + {"string_field_access", testCapMap, `{tailscale.grants}["example.com/cap/sql"][0].access == "read"`, true}, + // With no grants, the placeholder is an empty map rather than nil, so + // "in" returns false instead of failing with "no such overload". + {"in_operator_empty_grants", nil, `"example.com/app" in {tailscale.grants}`, false}, + {"null_check_empty_grants", nil, `{tailscale.grants} == null`, false}, + {"size_empty_grants", nil, `{tailscale.grants}.size() == 0`, true}, + } - t.Run("deep_field_access", func(t *testing.T) { - // Access a nested field: grants["example.com/app"][0].admin == true - expr := &caddyhttp.MatchExpression{ - Expr: `{tailscale.grants}["example.com/app"][0].admin == true`, - } - if err := expr.Provision(caddyCtx); err != nil { - t.Fatalf("Provision failed: %v", err) - } - matches, err := expr.MatchWithError(req) - if err != nil { - t.Fatalf("CEL evaluation failed: %v", err) - } - if !matches { - t.Error("expected admin to be true") - } - }) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, _ := newGrantsRequest(tt.capMap) + expr := &caddyhttp.MatchExpression{Expr: tt.expr} + if err := expr.Provision(caddyCtx); err != nil { + t.Fatalf("Provision failed: %v", err) + } + matches, err := expr.MatchWithError(req) + if err != nil { + t.Fatalf("CEL evaluation failed: %v", err) + } + if matches != tt.want { + t.Errorf("%s = %v, want %v", tt.expr, matches, tt.want) + } + }) + } +} - t.Run("in_operator_missing_key", func(t *testing.T) { - expr := &caddyhttp.MatchExpression{ - Expr: `"example.com/nonexistent" in {tailscale.grants}`, - } - if err := expr.Provision(caddyCtx); err != nil { - t.Fatalf("Provision failed: %v", err) - } - matches, err := expr.MatchWithError(req) - if err != nil { - t.Fatalf("CEL evaluation failed: %v", err) - } - if matches { - t.Error("expected nonexistent key not to be in grants") - } - }) +// TestTailscaleGrantsHeader verifies that the tailscale.grants placeholder +// renders as JSON when used in a header, matching the +// Tailscale-App-Capabilities header sent by tailscale serve. +func TestTailscaleGrantsHeader(t *testing.T) { + tests := []struct { + name string + capMap tailcfg.PeerCapMap + want string + }{ + { + name: "grants", + capMap: testCapMap, + want: `{"example.com/app":[{"admin":true,"role":"admin"}],"example.com/cap/sql":[{"access":"read"}]}`, + }, + { + name: "no_grants", + capMap: nil, + want: `{}`, + }, + { + name: "empty_capability", + capMap: tailcfg.PeerCapMap{"example.com/app": nil}, + want: `{"example.com/app":[]}`, + }, + { + name: "non_json_value", + capMap: tailcfg.PeerCapMap{"example.com/app": {`not json`}}, + want: `{"example.com/app":["not json"]}`, + }, + { + name: "non_ascii", + capMap: tailcfg.PeerCapMap{"example.com/app": {`{"name":"Zoë 🏠"}`}}, + want: `{"example.com/app":[{"name":"Zo\u00eb \ud83c\udfe0"}]}`, + }, + } - t.Run("grants_empty_when_not_set", func(t *testing.T) { - // Request without grants in context should get nil from replacer - emptyReq := httptest.NewRequest("GET", "http://example.com", nil) - emptyRepl := caddy.NewReplacer() - emptyCtx := context.WithValue(emptyReq.Context(), caddy.ReplacerCtxKey, emptyRepl) - emptyReq = emptyReq.WithContext(emptyCtx) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, repl := newGrantsRequest(tt.capMap) - emptyRepl.Map(func(key string) (any, bool) { - if key == "tailscale.grants" { - // Return empty map, as Auth.Authenticate now does - return map[string]any{}, true + // Apply the header the same way header_up does. + ops := &headers.HeaderOps{ + Set: http.Header{"Tailscale-App-Capabilities": []string{"{tailscale.grants}"}}, } - return nil, false - }) - - // Check that in operator returns false (not an error) when grants are nil - expr := &caddyhttp.MatchExpression{ - Expr: `"example.com/app" in {tailscale.grants}`, - } - if err := expr.Provision(caddyCtx); err != nil { - t.Fatalf("Provision failed: %v", err) - } - matches, err := expr.MatchWithError(emptyReq) - if err != nil { - t.Fatalf("CEL evaluation failed with 'no such overload': %v", err) - } - if matches { - t.Error("expected in operator to return false when grants are empty") - } - }) + if err := ops.Provision(caddy.Context{}); err != nil { + t.Fatalf("Provision failed: %v", err) + } + ops.ApplyToRequest(req) - t.Run("null_check_empty_grants", func(t *testing.T) { - // Same setup: empty grants - emptyReq := httptest.NewRequest("GET", "http://example.com", nil) - emptyRepl := caddy.NewReplacer() - emptyCtx := context.WithValue(emptyReq.Context(), caddy.ReplacerCtxKey, emptyRepl) - emptyReq = emptyReq.WithContext(emptyCtx) + got := req.Header.Get("Tailscale-App-Capabilities") + if got != tt.want { + t.Errorf("header = %s, want %s", got, tt.want) + } + if !json.Valid([]byte(got)) { + t.Errorf("header is not valid JSON: %s", got) + } + for i := 0; i < len(got); i++ { + if got[i] < 0x20 || got[i] > 0x7e { + t.Errorf("header contains non-printable-ASCII byte %#x: %s", got[i], got) + break + } + } - emptyRepl.Map(func(key string) (any, bool) { - if key == "tailscale.grants" { - return map[string]any{}, true + // The user metadata uses the same encoding. + if s := repl.ReplaceAll("{tailscale.grants}", ""); s != tt.want { + t.Errorf("ReplaceAll = %s, want %s", s, tt.want) } - return nil, false }) + } +} + +// TestTailscaleGrantsNonASCIIRoundTrip verifies that escaping non-ASCII +// characters does not change the decoded value. +func TestTailscaleGrantsNonASCIIRoundTrip(t *testing.T) { + grants := extractGrants(tailcfg.PeerCapMap{"example.com/app": {`{"name":"Zoë 🏠 日本"}`}}) - // Empty map is not null, so == null should be false - expr := &caddyhttp.MatchExpression{ - Expr: `{tailscale.grants} == null`, - } - if err := expr.Provision(caddyCtx); err != nil { - t.Fatalf("Provision failed: %v", err) - } - matches, err := expr.MatchWithError(emptyReq) - if err != nil { - t.Fatalf("CEL evaluation failed: %v", err) - } - if matches { - t.Error("expected tailscale.grants to not be null when grants are empty") - } - }) + var got map[string][]map[string]string + if err := json.Unmarshal([]byte(grants.String()), &got); err != nil { + t.Fatalf("Unmarshal failed: %v", err) + } + if name := got["example.com/app"][0]["name"]; name != "Zoë 🏠 日本" { + t.Errorf("name = %q, want %q", name, "Zoë 🏠 日本") + } } From accb17d43fad61c2ae428ced5f27916e5215d274 Mon Sep 17 00:00:00 2001 From: olistrik Date: Mon, 9 Nov 2026 15:36:10 +0100 Subject: [PATCH 3/3] README: restore Gitea example Signed-off-by: olistrik --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index 06e4e33..1f6237b 100644 --- a/README.md +++ b/README.md @@ -333,6 +333,19 @@ The following fields are set on the Caddy user object: These values can be mapped to HTTP headers that are then passed to an application that supports proxy authentication such as [Gitea] or [Grafana]. +You might have something like the following in your Caddyfile: + +```caddyfile +:80 { + bind tailscale/gitea + tailscale_auth + reverse_proxy http://localhost:3000 { + header_up X-Webauth-User {http.auth.user.tailscale_login} + header_up X-Webauth-Email {http.auth.user.tailscale_user} + header_up X-Webauth-Name {http.auth.user.tailscale_name} + } +} +``` When used with a Tailscale listener (described above), that Tailscale node is used to identify the remote user. Otherwise, the authentication provider will attempt to connect to the Tailscale daemon running on the local machine.