tsweb_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package tsweb
  4. import (
  5. "bufio"
  6. "context"
  7. "errors"
  8. "fmt"
  9. "net"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/url"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/google/go-cmp/cmp"
  17. "tailscale.com/tstest"
  18. "tailscale.com/util/must"
  19. "tailscale.com/util/vizerror"
  20. )
  21. type noopHijacker struct {
  22. *httptest.ResponseRecorder
  23. hijacked bool
  24. }
  25. func (h *noopHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  26. // Hijack "successfully" but don't bother returning a conn.
  27. h.hijacked = true
  28. return nil, nil, nil
  29. }
  30. type handlerFunc func(http.ResponseWriter, *http.Request) error
  31. func (f handlerFunc) ServeHTTPReturn(w http.ResponseWriter, r *http.Request) error {
  32. return f(w, r)
  33. }
  34. func TestStdHandler(t *testing.T) {
  35. const exampleRequestID = "example-request-id"
  36. var (
  37. handlerCode = func(code int) ReturnHandler {
  38. return handlerFunc(func(w http.ResponseWriter, r *http.Request) error {
  39. w.WriteHeader(code)
  40. return nil
  41. })
  42. }
  43. handlerErr = func(code int, err error) ReturnHandler {
  44. return handlerFunc(func(w http.ResponseWriter, r *http.Request) error {
  45. if code != 0 {
  46. w.WriteHeader(code)
  47. }
  48. return err
  49. })
  50. }
  51. req = func(ctx context.Context, url string) *http.Request {
  52. ret, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  53. if err != nil {
  54. panic(err)
  55. }
  56. return ret
  57. }
  58. testErr = errors.New("test error")
  59. bgCtx = context.Background()
  60. // canceledCtx, cancel = context.WithCancel(bgCtx)
  61. startTime = time.Unix(1687870000, 1234)
  62. )
  63. // cancel()
  64. tests := []struct {
  65. name string
  66. rh ReturnHandler
  67. r *http.Request
  68. errHandler ErrorHandlerFunc
  69. wantCode int
  70. wantLog AccessLogRecord
  71. wantBody string
  72. }{
  73. {
  74. name: "handler returns 200",
  75. rh: handlerCode(200),
  76. r: req(bgCtx, "http://example.com/"),
  77. wantCode: 200,
  78. wantLog: AccessLogRecord{
  79. Time: startTime,
  80. Seconds: 1.0,
  81. Proto: "HTTP/1.1",
  82. TLS: false,
  83. Host: "example.com",
  84. Method: "GET",
  85. Code: 200,
  86. RequestURI: "/",
  87. },
  88. },
  89. {
  90. name: "handler returns 200 with request ID",
  91. rh: handlerCode(200),
  92. r: req(bgCtx, "http://example.com/"),
  93. wantCode: 200,
  94. wantLog: AccessLogRecord{
  95. Time: startTime,
  96. Seconds: 1.0,
  97. Proto: "HTTP/1.1",
  98. TLS: false,
  99. Host: "example.com",
  100. Method: "GET",
  101. Code: 200,
  102. RequestURI: "/",
  103. },
  104. },
  105. {
  106. name: "handler returns 404",
  107. rh: handlerCode(404),
  108. r: req(bgCtx, "http://example.com/foo"),
  109. wantCode: 404,
  110. wantLog: AccessLogRecord{
  111. Time: startTime,
  112. Seconds: 1.0,
  113. Proto: "HTTP/1.1",
  114. Host: "example.com",
  115. Method: "GET",
  116. RequestURI: "/foo",
  117. Code: 404,
  118. },
  119. },
  120. {
  121. name: "handler returns 404 with request ID",
  122. rh: handlerCode(404),
  123. r: req(bgCtx, "http://example.com/foo"),
  124. wantCode: 404,
  125. wantLog: AccessLogRecord{
  126. Time: startTime,
  127. Seconds: 1.0,
  128. Proto: "HTTP/1.1",
  129. Host: "example.com",
  130. Method: "GET",
  131. RequestURI: "/foo",
  132. Code: 404,
  133. },
  134. },
  135. {
  136. name: "handler returns 404 via HTTPError",
  137. rh: handlerErr(0, Error(404, "not found", testErr)),
  138. r: req(bgCtx, "http://example.com/foo"),
  139. wantCode: 404,
  140. wantLog: AccessLogRecord{
  141. Time: startTime,
  142. Seconds: 1.0,
  143. Proto: "HTTP/1.1",
  144. Host: "example.com",
  145. Method: "GET",
  146. RequestURI: "/foo",
  147. Err: "not found: " + testErr.Error(),
  148. Code: 404,
  149. },
  150. wantBody: "not found\n",
  151. },
  152. {
  153. name: "handler returns 404 via HTTPError with request ID",
  154. rh: handlerErr(0, Error(404, "not found", testErr)),
  155. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/foo"),
  156. wantCode: 404,
  157. wantLog: AccessLogRecord{
  158. Time: startTime,
  159. Seconds: 1.0,
  160. Proto: "HTTP/1.1",
  161. Host: "example.com",
  162. Method: "GET",
  163. RequestURI: "/foo",
  164. Err: "not found: " + testErr.Error(),
  165. Code: 404,
  166. RequestID: exampleRequestID,
  167. },
  168. wantBody: "not found\n" + exampleRequestID + "\n",
  169. },
  170. {
  171. name: "handler returns 404 with nil child error",
  172. rh: handlerErr(0, Error(404, "not found", nil)),
  173. r: req(bgCtx, "http://example.com/foo"),
  174. wantCode: 404,
  175. wantLog: AccessLogRecord{
  176. Time: startTime,
  177. Seconds: 1.0,
  178. Proto: "HTTP/1.1",
  179. Host: "example.com",
  180. Method: "GET",
  181. RequestURI: "/foo",
  182. Err: "not found",
  183. Code: 404,
  184. },
  185. wantBody: "not found\n",
  186. },
  187. {
  188. name: "handler returns 404 with request ID and nil child error",
  189. rh: handlerErr(0, Error(404, "not found", nil)),
  190. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/foo"),
  191. wantCode: 404,
  192. wantLog: AccessLogRecord{
  193. Time: startTime,
  194. Seconds: 1.0,
  195. Proto: "HTTP/1.1",
  196. Host: "example.com",
  197. Method: "GET",
  198. RequestURI: "/foo",
  199. Err: "not found",
  200. Code: 404,
  201. RequestID: exampleRequestID,
  202. },
  203. wantBody: "not found\n" + exampleRequestID + "\n",
  204. },
  205. {
  206. name: "handler returns user-visible error",
  207. rh: handlerErr(0, vizerror.New("visible error")),
  208. r: req(bgCtx, "http://example.com/foo"),
  209. wantCode: 500,
  210. wantLog: AccessLogRecord{
  211. Time: startTime,
  212. Seconds: 1.0,
  213. Proto: "HTTP/1.1",
  214. Host: "example.com",
  215. Method: "GET",
  216. RequestURI: "/foo",
  217. Err: "visible error",
  218. Code: 500,
  219. },
  220. wantBody: "visible error\n",
  221. },
  222. {
  223. name: "handler returns user-visible error with request ID",
  224. rh: handlerErr(0, vizerror.New("visible error")),
  225. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/foo"),
  226. wantCode: 500,
  227. wantLog: AccessLogRecord{
  228. Time: startTime,
  229. Seconds: 1.0,
  230. Proto: "HTTP/1.1",
  231. Host: "example.com",
  232. Method: "GET",
  233. RequestURI: "/foo",
  234. Err: "visible error",
  235. Code: 500,
  236. RequestID: exampleRequestID,
  237. },
  238. wantBody: "visible error\n" + exampleRequestID + "\n",
  239. },
  240. {
  241. name: "handler returns user-visible error wrapped by private error",
  242. rh: handlerErr(0, fmt.Errorf("private internal error: %w", vizerror.New("visible error"))),
  243. r: req(bgCtx, "http://example.com/foo"),
  244. wantCode: 500,
  245. wantLog: AccessLogRecord{
  246. Time: startTime,
  247. Seconds: 1.0,
  248. Proto: "HTTP/1.1",
  249. Host: "example.com",
  250. Method: "GET",
  251. RequestURI: "/foo",
  252. Err: "visible error",
  253. Code: 500,
  254. },
  255. wantBody: "visible error\n",
  256. },
  257. {
  258. name: "handler returns user-visible error wrapped by private error with request ID",
  259. rh: handlerErr(0, fmt.Errorf("private internal error: %w", vizerror.New("visible error"))),
  260. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/foo"),
  261. wantCode: 500,
  262. wantLog: AccessLogRecord{
  263. Time: startTime,
  264. Seconds: 1.0,
  265. Proto: "HTTP/1.1",
  266. Host: "example.com",
  267. Method: "GET",
  268. RequestURI: "/foo",
  269. Err: "visible error",
  270. Code: 500,
  271. RequestID: exampleRequestID,
  272. },
  273. wantBody: "visible error\n" + exampleRequestID + "\n",
  274. },
  275. {
  276. name: "handler returns generic error",
  277. rh: handlerErr(0, testErr),
  278. r: req(bgCtx, "http://example.com/foo"),
  279. wantCode: 500,
  280. wantLog: AccessLogRecord{
  281. Time: startTime,
  282. Seconds: 1.0,
  283. Proto: "HTTP/1.1",
  284. Host: "example.com",
  285. Method: "GET",
  286. RequestURI: "/foo",
  287. Err: testErr.Error(),
  288. Code: 500,
  289. },
  290. wantBody: "internal server error\n",
  291. },
  292. {
  293. name: "handler returns generic error with request ID",
  294. rh: handlerErr(0, testErr),
  295. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/foo"),
  296. wantCode: 500,
  297. wantLog: AccessLogRecord{
  298. Time: startTime,
  299. Seconds: 1.0,
  300. Proto: "HTTP/1.1",
  301. Host: "example.com",
  302. Method: "GET",
  303. RequestURI: "/foo",
  304. Err: testErr.Error(),
  305. Code: 500,
  306. RequestID: exampleRequestID,
  307. },
  308. wantBody: "internal server error\n" + exampleRequestID + "\n",
  309. },
  310. {
  311. name: "handler returns error after writing response",
  312. rh: handlerErr(200, testErr),
  313. r: req(bgCtx, "http://example.com/foo"),
  314. wantCode: 200,
  315. wantLog: AccessLogRecord{
  316. Time: startTime,
  317. Seconds: 1.0,
  318. Proto: "HTTP/1.1",
  319. Host: "example.com",
  320. Method: "GET",
  321. RequestURI: "/foo",
  322. Err: testErr.Error(),
  323. Code: 200,
  324. },
  325. },
  326. {
  327. name: "handler returns error after writing response with request ID",
  328. rh: handlerErr(200, testErr),
  329. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/foo"),
  330. wantCode: 200,
  331. wantLog: AccessLogRecord{
  332. Time: startTime,
  333. Seconds: 1.0,
  334. Proto: "HTTP/1.1",
  335. Host: "example.com",
  336. Method: "GET",
  337. RequestURI: "/foo",
  338. Err: testErr.Error(),
  339. Code: 200,
  340. RequestID: exampleRequestID,
  341. },
  342. },
  343. {
  344. name: "handler returns HTTPError after writing response",
  345. rh: handlerErr(200, Error(404, "not found", testErr)),
  346. r: req(bgCtx, "http://example.com/foo"),
  347. wantCode: 200,
  348. wantLog: AccessLogRecord{
  349. Time: startTime,
  350. Seconds: 1.0,
  351. Proto: "HTTP/1.1",
  352. Host: "example.com",
  353. Method: "GET",
  354. RequestURI: "/foo",
  355. Err: "not found: " + testErr.Error(),
  356. Code: 200,
  357. },
  358. },
  359. {
  360. name: "handler does nothing",
  361. rh: handlerFunc(func(http.ResponseWriter, *http.Request) error { return nil }),
  362. r: req(bgCtx, "http://example.com/foo"),
  363. wantCode: 200,
  364. wantLog: AccessLogRecord{
  365. Time: startTime,
  366. Seconds: 1.0,
  367. Proto: "HTTP/1.1",
  368. Host: "example.com",
  369. Method: "GET",
  370. RequestURI: "/foo",
  371. Code: 200,
  372. },
  373. },
  374. {
  375. name: "handler hijacks conn",
  376. rh: handlerFunc(func(w http.ResponseWriter, r *http.Request) error {
  377. _, _, err := w.(http.Hijacker).Hijack()
  378. if err != nil {
  379. t.Errorf("couldn't hijack: %v", err)
  380. }
  381. return err
  382. }),
  383. r: req(bgCtx, "http://example.com/foo"),
  384. wantCode: 200,
  385. wantLog: AccessLogRecord{
  386. Time: startTime,
  387. Seconds: 1.0,
  388. Proto: "HTTP/1.1",
  389. Host: "example.com",
  390. Method: "GET",
  391. RequestURI: "/foo",
  392. Code: 101,
  393. },
  394. },
  395. {
  396. name: "error handler gets run",
  397. rh: handlerErr(0, Error(404, "not found", nil)), // status code changed in errHandler
  398. r: req(bgCtx, "http://example.com/"),
  399. wantCode: 200,
  400. errHandler: func(w http.ResponseWriter, r *http.Request, e HTTPError) {
  401. http.Error(w, e.Msg, 200)
  402. },
  403. wantLog: AccessLogRecord{
  404. Time: startTime,
  405. Seconds: 1.0,
  406. Proto: "HTTP/1.1",
  407. TLS: false,
  408. Host: "example.com",
  409. Method: "GET",
  410. Code: 404,
  411. Err: "not found",
  412. RequestURI: "/",
  413. },
  414. wantBody: "not found\n",
  415. },
  416. {
  417. name: "error handler gets run with request ID",
  418. rh: handlerErr(0, Error(404, "not found", nil)), // status code changed in errHandler
  419. r: req(RequestIDKey.WithValue(bgCtx, exampleRequestID), "http://example.com/"),
  420. wantCode: 200,
  421. errHandler: func(w http.ResponseWriter, r *http.Request, e HTTPError) {
  422. requestID := RequestIDFromContext(r.Context())
  423. http.Error(w, fmt.Sprintf("%s with request ID %s", e.Msg, requestID), 200)
  424. },
  425. wantLog: AccessLogRecord{
  426. Time: startTime,
  427. Seconds: 1.0,
  428. Proto: "HTTP/1.1",
  429. TLS: false,
  430. Host: "example.com",
  431. Method: "GET",
  432. Code: 404,
  433. Err: "not found",
  434. RequestURI: "/",
  435. RequestID: exampleRequestID,
  436. },
  437. wantBody: "not found with request ID " + exampleRequestID + "\n",
  438. },
  439. }
  440. for _, test := range tests {
  441. t.Run(test.name, func(t *testing.T) {
  442. var logs []AccessLogRecord
  443. logf := func(fmt string, args ...any) {
  444. if fmt == "%s" {
  445. logs = append(logs, args[0].(AccessLogRecord))
  446. }
  447. t.Logf(fmt, args...)
  448. }
  449. clock := tstest.NewClock(tstest.ClockOpts{
  450. Start: startTime,
  451. Step: time.Second,
  452. })
  453. rec := noopHijacker{httptest.NewRecorder(), false}
  454. h := StdHandler(test.rh, HandlerOptions{Logf: logf, Now: clock.Now, OnError: test.errHandler})
  455. h.ServeHTTP(&rec, test.r)
  456. res := rec.Result()
  457. if res.StatusCode != test.wantCode {
  458. t.Errorf("HTTP code = %v, want %v", res.StatusCode, test.wantCode)
  459. }
  460. if len(logs) != 1 {
  461. t.Errorf("handler didn't write a request log")
  462. return
  463. }
  464. errTransform := cmp.Transformer("err", func(e error) string {
  465. if e == nil {
  466. return ""
  467. }
  468. return e.Error()
  469. })
  470. if diff := cmp.Diff(logs[0], test.wantLog, errTransform); diff != "" {
  471. t.Errorf("handler wrote incorrect request log (-got+want):\n%s", diff)
  472. }
  473. if diff := cmp.Diff(rec.Body.String(), test.wantBody); diff != "" {
  474. t.Errorf("handler wrote incorrect body (-got+want):\n%s", diff)
  475. }
  476. })
  477. }
  478. }
  479. func BenchmarkLogNot200(b *testing.B) {
  480. b.ReportAllocs()
  481. rh := handlerFunc(func(w http.ResponseWriter, r *http.Request) error {
  482. // Implicit 200 OK.
  483. return nil
  484. })
  485. h := StdHandler(rh, HandlerOptions{QuietLoggingIfSuccessful: true})
  486. req := httptest.NewRequest("GET", "/", nil)
  487. rw := new(httptest.ResponseRecorder)
  488. for range b.N {
  489. *rw = httptest.ResponseRecorder{}
  490. h.ServeHTTP(rw, req)
  491. }
  492. }
  493. func BenchmarkLog(b *testing.B) {
  494. b.ReportAllocs()
  495. rh := handlerFunc(func(w http.ResponseWriter, r *http.Request) error {
  496. // Implicit 200 OK.
  497. return nil
  498. })
  499. h := StdHandler(rh, HandlerOptions{})
  500. req := httptest.NewRequest("GET", "/", nil)
  501. rw := new(httptest.ResponseRecorder)
  502. for range b.N {
  503. *rw = httptest.ResponseRecorder{}
  504. h.ServeHTTP(rw, req)
  505. }
  506. }
  507. func TestHTTPError_Unwrap(t *testing.T) {
  508. wrappedErr := fmt.Errorf("wrapped")
  509. err := Error(404, "not found", wrappedErr)
  510. if got := errors.Unwrap(err); got != wrappedErr {
  511. t.Errorf("HTTPError.Unwrap() = %v, want %v", got, wrappedErr)
  512. }
  513. }
  514. func TestAcceptsEncoding(t *testing.T) {
  515. tests := []struct {
  516. in, enc string
  517. want bool
  518. }{
  519. {"", "gzip", false},
  520. {"gzip", "gzip", true},
  521. {"foo,gzip", "gzip", true},
  522. {"foo, gzip", "gzip", true},
  523. {"foo, gzip ", "gzip", true},
  524. {"gzip, foo ", "gzip", true},
  525. {"gzip, foo ", "br", false},
  526. {"gzip, foo ", "fo", false},
  527. {"gzip;q=1.2, foo ", "gzip", true},
  528. {" gzip;q=1.2, foo ", "gzip", true},
  529. }
  530. for i, tt := range tests {
  531. h := make(http.Header)
  532. if tt.in != "" {
  533. h.Set("Accept-Encoding", tt.in)
  534. }
  535. got := AcceptsEncoding(&http.Request{Header: h}, tt.enc)
  536. if got != tt.want {
  537. t.Errorf("%d. got %v; want %v", i, got, tt.want)
  538. }
  539. }
  540. }
  541. func TestPort80Handler(t *testing.T) {
  542. tests := []struct {
  543. name string
  544. h *Port80Handler
  545. req string
  546. wantLoc string
  547. }{
  548. {
  549. name: "no_fqdn",
  550. h: &Port80Handler{},
  551. req: "GET / HTTP/1.1\r\nHost: foo.com\r\n\r\n",
  552. wantLoc: "https://foo.com/",
  553. },
  554. {
  555. name: "fqdn_and_path",
  556. h: &Port80Handler{FQDN: "bar.com"},
  557. req: "GET /path HTTP/1.1\r\nHost: foo.com\r\n\r\n",
  558. wantLoc: "https://bar.com/path",
  559. },
  560. {
  561. name: "path_and_query_string",
  562. h: &Port80Handler{FQDN: "baz.com"},
  563. req: "GET /path?a=b HTTP/1.1\r\nHost: foo.com\r\n\r\n",
  564. wantLoc: "https://baz.com/path?a=b",
  565. },
  566. }
  567. for _, tt := range tests {
  568. t.Run(tt.name, func(t *testing.T) {
  569. r, _ := http.ReadRequest(bufio.NewReader(strings.NewReader(tt.req)))
  570. rec := httptest.NewRecorder()
  571. tt.h.ServeHTTP(rec, r)
  572. got := rec.Result()
  573. if got, want := got.StatusCode, 302; got != want {
  574. t.Errorf("got status code %v; want %v", got, want)
  575. }
  576. if got, want := got.Header.Get("Location"), "https://foo.com/"; got != tt.wantLoc {
  577. t.Errorf("Location = %q; want %q", got, want)
  578. }
  579. })
  580. }
  581. }
  582. func TestCleanRedirectURL(t *testing.T) {
  583. tailscaleHost := []string{"tailscale.com"}
  584. tailscaleAndOtherHost := []string{"microsoft.com", "tailscale.com"}
  585. localHost := []string{"127.0.0.1", "localhost"}
  586. myServer := []string{"myserver"}
  587. cases := []struct {
  588. url string
  589. hosts []string
  590. want string
  591. wantErr bool
  592. }{
  593. {"http://tailscale.com/foo", tailscaleHost, "http://tailscale.com/foo", false},
  594. {"http://tailscale.com/foo", tailscaleAndOtherHost, "http://tailscale.com/foo", false},
  595. {"http://microsoft.com/foo", tailscaleAndOtherHost, "http://microsoft.com/foo", false},
  596. {"https://tailscale.com/foo", tailscaleHost, "https://tailscale.com/foo", false},
  597. {"/foo", tailscaleHost, "/foo", false},
  598. {"//tailscale.com/foo", tailscaleHost, "//tailscale.com/foo", false},
  599. {"/a/foobar", tailscaleHost, "/a/foobar", false},
  600. {"http://127.0.0.1/a/foobar", localHost, "http://127.0.0.1/a/foobar", false},
  601. {"http://127.0.0.1:123/a/foobar", localHost, "http://127.0.0.1:123/a/foobar", false},
  602. {"http://127.0.0.1:31544/a/foobar", localHost, "http://127.0.0.1:31544/a/foobar", false},
  603. {"http://localhost/a/foobar", localHost, "http://localhost/a/foobar", false},
  604. {"http://localhost:123/a/foobar", localHost, "http://localhost:123/a/foobar", false},
  605. {"http://localhost:31544/a/foobar", localHost, "http://localhost:31544/a/foobar", false},
  606. {"http://myserver/a/foobar", myServer, "http://myserver/a/foobar", false},
  607. {"http://myserver:123/a/foobar", myServer, "http://myserver:123/a/foobar", false},
  608. {"http://myserver:31544/a/foobar", myServer, "http://myserver:31544/a/foobar", false},
  609. {"http://evil.com/foo", tailscaleHost, "", true},
  610. {"//evil.com", tailscaleHost, "", true},
  611. {"\\\\evil.com", tailscaleHost, "", true},
  612. {"javascript:alert(123)", tailscaleHost, "", true},
  613. {"file:///", tailscaleHost, "", true},
  614. {"file:////SERVER/directory/goats.txt", tailscaleHost, "", true},
  615. {"https://google.com", tailscaleHost, "", true},
  616. {"", tailscaleHost, "", false},
  617. {"\"\"", tailscaleHost, "", true},
  618. {"https://[email protected]:8443", tailscaleHost, "", true},
  619. {"https://tailscale.com:[email protected]:8443", tailscaleHost, "", true},
  620. {"HttP://tailscale.com", tailscaleHost, "http://tailscale.com", false},
  621. {"http://TaIlScAlE.CoM/spongebob", tailscaleHost, "http://TaIlScAlE.CoM/spongebob", false},
  622. {"ftp://tailscale.com", tailscaleHost, "", true},
  623. {"https:/evil.com", tailscaleHost, "", true}, // regression test for tailscale/corp#892
  624. {"%2Fa%2F44869c061701", tailscaleHost, "/a/44869c061701", false}, // regression test for tailscale/corp#13288
  625. {"https%3A%2Ftailscale.com", tailscaleHost, "", true}, // escaped colon-single-slash malformed URL
  626. {"", nil, "", false},
  627. }
  628. for _, tc := range cases {
  629. gotURL, err := CleanRedirectURL(tc.url, tc.hosts)
  630. if err != nil {
  631. if !tc.wantErr {
  632. t.Errorf("CleanRedirectURL(%q, %v) got error: %v", tc.url, tc.hosts, err)
  633. }
  634. } else {
  635. if tc.wantErr {
  636. t.Errorf("CleanRedirectURL(%q, %v) got %q, want an error", tc.url, tc.hosts, gotURL)
  637. }
  638. if got := gotURL.String(); got != tc.want {
  639. t.Errorf("CleanRedirectURL(%q, %v) = %q, want %q", tc.url, tc.hosts, got, tc.want)
  640. }
  641. }
  642. }
  643. }
  644. func TestBucket(t *testing.T) {
  645. tcs := []struct {
  646. path string
  647. want string
  648. }{
  649. {"/map", "/map"},
  650. {"/key?v=63", "/key"},
  651. {"/map/a87e865a9d1c7", "/map/…"},
  652. {"/machine/37fc1acb57f256b69b0d76749d814d91c68b241057c6b127fee3df37e4af111e", "/machine/…"},
  653. {"/machine/37fc1acb57f256b69b0d76749d814d91c68b241057c6b127fee3df37e4af111e/map", "/machine/…/map"},
  654. {"/api/v2/tailnet/[email protected]/devices", "/api/v2/tailnet/…/devices"},
  655. {"/machine/ssh/wait/5227109621243650/to/7111899293970143/a/a9e4e04cc01b", "/machine/ssh/wait/…/to/…/a/…"},
  656. {"/a/831a4bf39856?refreshed=true", "/a/…"},
  657. {"/c2n/nxaaa1CNTRL", "/c2n/…"},
  658. {"/api/v2/tailnet/blueberries.com/keys/kxaDK21CNTRL", "/api/v2/tailnet/…/keys/…"},
  659. {"/api/v2/tailnet/bloop@passkey/devices", "/api/v2/tailnet/…/devices"},
  660. }
  661. for _, tc := range tcs {
  662. t.Run(tc.path, func(t *testing.T) {
  663. o := BucketedStatsOptions{}
  664. bucket := (&o).bucketForRequest(&http.Request{
  665. URL: must.Get(url.Parse(tc.path)),
  666. })
  667. if bucket != tc.want {
  668. t.Errorf("bucket for %q was %q, want %q", tc.path, bucket, tc.want)
  669. }
  670. })
  671. }
  672. }