-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
222 lines (188 loc) · 5.81 KB
/
module.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package tscaddy
import (
"context"
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"os"
"path"
"strings"
"sync"
"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/tailscale"
"tailscale.com/tsnet"
"tailscale.com/util/strs"
)
var (
// servers maps hostnames to tsnet servers. It is protected by mu.
servers = make(map[string]*tsnet.Server)
mu = sync.RWMutex{}
)
func init() {
caddy.RegisterModule(TailscaleAuth{})
httpcaddyfile.RegisterHandlerDirective("tailscale_auth", parseCaddyfile)
caddy.RegisterNetwork("tailscale", getPlainListener)
caddy.RegisterNetwork("tailscale+tls", getTLSListener)
}
func getPlainListener(_ context.Context, network string, addr string, _ net.ListenConfig) (any, error) {
s, err := getServer("", addr)
if err != nil {
return nil, err
}
_, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
return s.Listen("tcp", ":"+port)
}
func getTLSListener(_ context.Context, network string, addr string, _ net.ListenConfig) (any, error) {
s, err := getServer("", addr)
if err != nil {
return nil, err
}
_, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ln, err := s.Listen("tcp", ":"+port)
if err != nil {
return nil, err
}
localClient, _ := s.LocalClient()
ln = tls.NewListener(ln, &tls.Config{
GetCertificate: localClient.GetCertificate,
})
return ln, nil
}
// getServer returns a tailscale tsnet.Server for Caddy apps to listen on. The specified
// address will take the form of "tailscale/host:port" or "tailscale+tls/host:port" with
// host being optional. If specified, host will be provided to tsnet as the desired
// hostname for the tailscale node. Only one tsnet server is created per host, even if
// multiple ports are being listened on for the host.
//
// Auth keys can be provided in environment variables of the form TS_AUTHKEY_<HOST>. If
// no host is specified in the address, the environment variable TS_AUTHKEY will be used.
func getServer(_, addr string) (*tsnet.Server, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
mu.Lock()
s, ok := servers[host]
if !ok {
s = &tsnet.Server{
Hostname: host,
Logf: func(format string, args ...any) {
// TODO: parse out and always log authURL so you don't need
// to turn on debug logging to get it.
if os.Getenv("TS_VERBOSE") == "1" {
log.Printf(format, args...)
}
},
}
if host != "" {
// Set authkey to "TS_AUTHKEY_<HOST>". If empty,
// fall back to "TS_AUTHKEY".
s.AuthKey = os.Getenv("TS_AUTHKEY_" + strings.ToUpper(host))
if s.AuthKey == "" {
s.AuthKey = os.Getenv("TS_AUTHKEY")
}
// Set config directory for tsnet. By default, tsnet will use the name of the
// running program, but we include the hostname as well so that a single
// caddy instance can have multiple tsnet servers.
configDir, err := os.UserConfigDir()
if err != nil {
return nil, err
}
s.Dir = path.Join(configDir, "tsnet-caddy-"+host)
if err := os.MkdirAll(s.Dir, 0700); err != nil {
return nil, err
}
}
servers[host] = s
}
defer mu.Unlock()
return s, nil
}
type TailscaleAuth struct {
localclient *tailscale.LocalClient
}
func (TailscaleAuth) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.authentication.providers.tailscale",
New: func() caddy.Module { return new(TailscaleAuth) },
}
}
// client returns the tailscale LocalClient for the TailscaleAuth module. If the LocalClient
// has not already been configured, the provided request will be used to set it up for the
// appropriate tsnet server.
func (ta *TailscaleAuth) client(r *http.Request) (*tailscale.LocalClient, error) {
if ta.localclient != nil {
return ta.localclient, nil
}
// if request was made through a tsnet listener, set up the client for the associated tsnet
// server.
server := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
for _, listener := range server.Listeners() {
if tsl, ok := listener.(tsnetListener); ok {
var err error
ta.localclient, err = tsl.Server().LocalClient()
if err != nil {
return nil, err
}
}
}
if ta.localclient == nil {
// default to empty client that will talk to local tailscaled
ta.localclient = new(tailscale.LocalClient)
}
return ta.localclient, nil
}
type tsnetListener interface {
Server() *tsnet.Server
}
func (ta TailscaleAuth) Authenticate(w http.ResponseWriter, r *http.Request) (caddyauth.User, bool, error) {
user := caddyauth.User{}
client, err := ta.client(r)
if err != nil {
return user, false, err
}
info, err := client.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
return user, false, err
}
if len(info.Node.Tags) != 0 {
return user, false, fmt.Errorf("node %s has tags", info.Node.Hostinfo.Hostname())
}
var tailnet string
if !info.Node.Hostinfo.ShareeNode() {
if s, found := strs.CutPrefix(info.Node.Name, info.Node.ComputedName+"."); found {
if s, found := strs.CutSuffix(s, ".beta.tailscale.net."); found {
tailnet = s
}
}
}
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,
}
return user, true, nil
}
func parseCaddyfile(_ httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var ta TailscaleAuth
return caddyauth.Authentication{
ProvidersRaw: caddy.ModuleMap{
"tailscale": caddyconfig.JSON(ta, nil),
},
}, nil
}