forked from crawshaw/httpts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpts.go
More file actions
317 lines (279 loc) · 8.34 KB
/
httpts.go
File metadata and controls
317 lines (279 loc) · 8.34 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Package httpts provides an HTTP server that runs on a Tailscale tailnet.
//
// Every http.Request context served by this package has httpts.Who attached
// to it, telling you who is calling.
package httpts
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/crawshaw/httpts/internal/tsnet"
"golang.org/x/oauth2/clientcredentials"
"tailscale.com/client/tailscale"
"tailscale.com/ipn"
"tailscale.com/tailcfg"
)
// Server is a drop-in for http.Server that serves a Handler on a tailnet.
type Server struct {
// Handler answers requests from the tailnet.
Handler http.Handler
// FunnelHandler, if non-nil, answers requsts from the internet via Tailscale Funnel.
// Unused if InsecureLocalPortOnly is true.
FunnelHandler http.Handler
// InsecureLocalPortOnly, if non-zero, means that no tsnet server is started
// and instead the server listens over http:// on the specified 127.0.0.1 port.
// It is insecure because all localhost handling is passed to Handler.
InsecureLocalPortOnly int
// StateStore, if non-nil, is used to store state for the tailscale client.
StateStore ipn.StateStore
AdvertiseTags []string
// OauthClientSecret is used to authenticate the node if it is not already.
// Create one at https://login.tailscale.com/admin/settings/oauth.
// The client must be created with a tag that matches AdvertiseTags.
// Note that the client secret must start with `tskey-client-`.
//
// Ignored if AuthKey is non-empty.
//
// Do not pass an OauthClientSecret to a server that you do not trust
// to add nodes to your tailnet.
OauthClientSecret string
// AuthKey, if non-empty, is the auth key to create the node.
AuthKey string
ts *tsnet.Server
httpsrv *http.Server
lc *tailscale.LocalClient
ctx context.Context
ctxCancel func()
started struct {
mu sync.Mutex
ch chan struct{} // closed when tsnet is serving, access via startedCh
}
}
func (s *Server) startedCh() chan struct{} {
s.started.mu.Lock()
defer s.started.mu.Unlock()
if s.started.ch == nil {
s.started.ch = make(chan struct{})
}
return s.started.ch
}
// Who is attached to every http.Request context naming the HTTP client.
type Who struct {
LoginName string
PeerCap tailcfg.PeerCapMap
}
type whoCtxKeyType struct{}
var whoCtxKey = whoCtxKeyType{}
func WhoFromCtx(ctx context.Context) *Who {
who, ok := ctx.Value(whoCtxKey).(*Who)
if !ok {
return nil
}
return who
}
func (s *Server) mkhttpsrv() {
if s.httpsrv != nil {
return
}
s.ctx, s.ctxCancel = context.WithCancel(context.Background())
s.httpsrv = &http.Server{
Handler: http.HandlerFunc(s.whoHandler),
}
}
func (s *Server) whoHandler(w http.ResponseWriter, r *http.Request) {
var who Who
if s.InsecureLocalPortOnly != 0 {
who = Who{LoginName: "insecure-localhost"}
} else {
whoResp, err := s.lc.WhoIs(r.Context(), r.RemoteAddr)
if s.FunnelHandler != nil && errors.Is(err, tailscale.ErrPeerNotFound) {
// TODO: pass an empty Who?
s.FunnelHandler.ServeHTTP(w, r)
return
} else if err != nil {
http.Error(w, "httpts: "+err.Error(), http.StatusUnauthorized)
return
}
who = Who{
LoginName: whoResp.UserProfile.LoginName,
PeerCap: whoResp.CapMap,
}
}
r = r.WithContext(context.WithValue(r.Context(), whoCtxKey, &who))
s.Handler.ServeHTTP(w, r)
}
// Dial dials the address on the tailnet.
func (s *Server) Dial(ctx context.Context, network, address string) (net.Conn, error) {
select {
case <-s.startedCh():
return s.ts.Dial(ctx, network, address)
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Serve serves :443 and a :80 redirect on a tailnet.
func (s *Server) Serve(tsHostname string) error {
s.mkhttpsrv()
confDir, err := os.UserConfigDir()
if err != nil {
return fmt.Errorf("httpts: %w", err)
}
s.ts = &tsnet.Server{
Dir: filepath.Join(confDir, "httpts-"+tsHostname),
Store: s.StateStore,
Hostname: tsHostname,
AdvertiseTags: s.AdvertiseTags,
AuthKey: s.AuthKey,
}
defer s.ts.Close()
if s.InsecureLocalPortOnly != 0 {
s.httpsrv.Addr = fmt.Sprintf("127.0.0.1:%d", s.InsecureLocalPortOnly)
log.Printf("Serving: http://%s", s.httpsrv.Addr)
// Return before calling Up, so local-port-only mode
// does not necessarily invoke Tailscale, unless you call Dial.
close(s.startedCh())
return s.httpsrv.ListenAndServe()
}
if s.AuthKey == "" && s.OauthClientSecret != "" {
var err error
s.ts.AuthKey, err = s.createAuthKey(s.ctx)
if err != nil {
return fmt.Errorf("create auth key: %w", err)
}
}
// Call Up explicitly with a context that is canceled on Shutdown
// so we don't get stuck in ListenTLS on Shutdown.
if _, err := s.ts.Up(s.ctx); err != nil {
return fmt.Errorf("httpts.up: %w", err)
}
close(s.startedCh())
var ln net.Listener
if s.FunnelHandler != nil {
ln, err = s.ts.ListenFunnel("tcp", ":443")
} else {
ln, err = s.ts.ListenTLS("tcp", ":443")
}
if err != nil {
return fmt.Errorf("httpts: %w", err)
}
lc, err := s.ts.LocalClient()
if err != nil {
return fmt.Errorf("httpts: %w", err)
}
s.lc = lc
if status, err := lc.Status(context.Background()); err != nil {
return fmt.Errorf("httpts: %w", err)
} else {
log.Printf("Serving: https://%s/\n", strings.TrimSuffix(status.Self.DNSName, "."))
}
ln80, err := s.ts.Listen("tcp", ":80")
if err != nil {
return fmt.Errorf("httpts: %w", err)
}
srv80 := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
target := "https://" + r.Host + r.URL.Path
if len(r.URL.RawQuery) > 0 {
target += "?" + r.URL.RawQuery
}
http.Redirect(w, r, target, http.StatusMovedPermanently)
})}
go func() {
err := srv80.Serve(ln80)
if errors.Is(err, http.ErrServerClosed) {
return
}
panic(err)
}()
s.httpsrv.RegisterOnShutdown(func() {
ctx, cancel := context.WithCancel(context.Background())
cancel() // shut down immediately
srv80.Shutdown(ctx)
})
err = s.httpsrv.Serve(ln)
s.lc = nil
return err
}
// Shutdown shuts down the HTTP server and Tailscale client.
func (s *Server) Shutdown(ctx context.Context) error {
s.ctxCancel()
var err, err2 error
err = s.httpsrv.Shutdown(ctx)
if s.ts != nil {
err2 = s.ts.Close()
}
s.ts = nil
if err == nil {
err = err2
}
return err
}
func tsClientConfig(clientSecret string) (*clientcredentials.Config, error) {
oauthConfig := &clientcredentials.Config{
ClientSecret: clientSecret,
TokenURL: "https://api.tailscale.com/api/v2/oauth/token",
}
if s := strings.TrimPrefix(oauthConfig.ClientSecret, "tskey-client-"); s == oauthConfig.ClientSecret {
return nil, fmt.Errorf("OauthClientSecret must start with `tskey-client-`")
} else {
oauthConfig.ClientID, _, _ = strings.Cut(s, "-")
}
return oauthConfig, nil
}
func checkTSClientConfig(ctx context.Context, oauthConfig *clientcredentials.Config) error {
tsClient := oauthConfig.Client(ctx)
resp, err := tsClient.Get("https://api.tailscale.com/api/v2/tailnet/-/devices")
if err != nil {
return fmt.Errorf("oauth client failure: %w", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("oauth client failure: %w", err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("basic device list failed: %s", body)
}
return nil
}
func (s *Server) createAuthKey(ctx context.Context) (string, error) {
return CreateAuthKey(ctx, s.OauthClientSecret, tailscale.KeyDeviceCreateCapabilities{
Reusable: false,
Ephemeral: false, // TODO export
Preauthorized: true, // false, // TODO export
Tags: s.AdvertiseTags,
})
}
func CreateAuthKey(ctx context.Context, clientSecret string, deviceCaps tailscale.KeyDeviceCreateCapabilities) (string, error) {
oauthCfg, err := tsClientConfig(clientSecret)
if err != nil {
return "", err
}
if err := checkTSClientConfig(ctx, oauthCfg); err != nil {
return "", err
}
tailscale.I_Acknowledge_This_API_Is_Unstable = true
tsClient := tailscale.NewClient("-", nil)
tsClient.HTTPClient = oauthCfg.Client(ctx)
caps := tailscale.KeyCapabilities{
Devices: tailscale.KeyDeviceCapabilities{
Create: deviceCaps,
},
}
authkey, _, err := tsClient.CreateKey(ctx, caps)
if err != nil {
return "", err
}
return authkey, nil
}
// TestWhoRequest sets up a Who object on a http.Request for use in testing.
func TestWhoRequest(r *http.Request) *http.Request {
who := Who{LoginName: "insecure-test"}
return r.WithContext(context.WithValue(r.Context(), whoCtxKey, &who))
}