Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.test
*.test.exe
65 changes: 65 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +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), 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].
Expand All @@ -349,6 +350,70 @@ You might have something like the following in your Caddyfile:
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 }
]
}
}
```

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 in a header:

```caddyfile
reverse_proxy localhost:3000 {
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/
Expand Down
99 changes: 99 additions & 0 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@ package tscaddy
// auth.go contains the TailscaleAuth module and supporting logic.

import (
"encoding/json"
"fmt"
"net"
"net/http"
"reflect"
"strings"
"unicode/utf16"
"unicode/utf8"

"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"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"
)

Expand Down Expand Up @@ -132,6 +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 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{}

Expand All @@ -156,17 +161,111 @@ 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(grantsReplacer(grants))

user.ID = info.UserProfile.LoginName
user.Metadata = map[string]string{
"tailscale_login": strings.Split(info.UserProfile.LoginName, "@")[0],
"tailscale_user": info.UserProfile.LoginName,
"tailscale_name": info.UserProfile.DisplayName,
"tailscale_profile_picture": info.UserProfile.ProfilePicURL,
"tailscale_tailnet": tailnet,
"tailscale_grants": grants.String(),
}
return user, true, nil
}

// 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(Grants)

for cap, vals := range capMap {
parsed := make([]any, 0, len(vals))
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

Expand Down
163 changes: 163 additions & 0 deletions cel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: Apache-2.0

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"
)

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)
repl := caddy.NewReplacer()
repl.Map(grantsReplacer(extractGrants(capMap)))
ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
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()

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},
}

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)
}
})
}
}

// 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"}]}`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, repl := newGrantsRequest(tt.capMap)

// Apply the header the same way header_up does.
ops := &headers.HeaderOps{
Set: http.Header{"Tailscale-App-Capabilities": []string{"{tailscale.grants}"}},
}
if err := ops.Provision(caddy.Context{}); err != nil {
t.Fatalf("Provision failed: %v", err)
}
ops.ApplyToRequest(req)

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
}
}

// 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)
}
})
}
}

// 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ë 🏠 日本"}`}})

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ë 🏠 日本")
}
}