web.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package web provides the Tailscale client for web.
  4. package web
  5. import (
  6. "context"
  7. "crypto/rand"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "log"
  13. "net/http"
  14. "net/netip"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "slices"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/gorilla/csrf"
  23. "tailscale.com/client/tailscale"
  24. "tailscale.com/client/tailscale/apitype"
  25. "tailscale.com/clientupdate"
  26. "tailscale.com/envknob"
  27. "tailscale.com/hostinfo"
  28. "tailscale.com/ipn"
  29. "tailscale.com/ipn/ipnstate"
  30. "tailscale.com/licenses"
  31. "tailscale.com/net/netutil"
  32. "tailscale.com/net/tsaddr"
  33. "tailscale.com/tailcfg"
  34. "tailscale.com/types/logger"
  35. "tailscale.com/util/httpm"
  36. "tailscale.com/version"
  37. "tailscale.com/version/distro"
  38. )
  39. // ListenPort is the static port used for the web client when run inside tailscaled.
  40. // (5252 are the numbers above the letters "TSTS" on a qwerty keyboard.)
  41. const ListenPort = 5252
  42. // Server is the backend server for a Tailscale web client.
  43. type Server struct {
  44. mode ServerMode
  45. logf logger.Logf
  46. lc *tailscale.LocalClient
  47. timeNow func() time.Time
  48. // devMode indicates that the server run with frontend assets
  49. // served by a Vite dev server, allowing for local development
  50. // on the web client frontend.
  51. devMode bool
  52. cgiMode bool
  53. pathPrefix string
  54. apiHandler http.Handler // serves api endpoints; csrf-protected
  55. assetsHandler http.Handler // serves frontend assets
  56. assetsCleanup func() // called from Server.Shutdown
  57. // browserSessions is an in-memory cache of browser sessions for the
  58. // full management web client, which is only accessible over Tailscale.
  59. //
  60. // Users obtain a valid browser session by connecting to the web client
  61. // over Tailscale and verifying their identity by authenticating on the
  62. // control server.
  63. //
  64. // browserSessions get reset on every Server restart.
  65. //
  66. // The map provides a lookup of the session by cookie value
  67. // (browserSession.ID => browserSession).
  68. browserSessions sync.Map
  69. // newAuthURL creates a new auth URL that can be used to validate
  70. // a browser session to manage this web client.
  71. newAuthURL func(ctx context.Context, src tailcfg.NodeID) (*tailcfg.WebClientAuthResponse, error)
  72. // waitWebClientAuthURL blocks until the associated auth URL has
  73. // been completed by its user, or until ctx is canceled.
  74. waitAuthURL func(ctx context.Context, id string, src tailcfg.NodeID) (*tailcfg.WebClientAuthResponse, error)
  75. }
  76. // ServerMode specifies the mode of a running web.Server.
  77. type ServerMode string
  78. const (
  79. // LoginServerMode serves a readonly login client for logging a
  80. // node into a tailnet, and viewing a readonly interface of the
  81. // node's current Tailscale settings.
  82. //
  83. // In this mode, API calls are authenticated via platform auth.
  84. LoginServerMode ServerMode = "login"
  85. // ManageServerMode serves a management client for editing tailscale
  86. // settings of a node.
  87. //
  88. // This mode restricts the app to only being assessible over Tailscale,
  89. // and API calls are authenticated via browser sessions associated with
  90. // the source's Tailscale identity. If the source browser does not have
  91. // a valid session, a readonly version of the app is displayed.
  92. ManageServerMode ServerMode = "manage"
  93. )
  94. var (
  95. exitNodeRouteV4 = netip.MustParsePrefix("0.0.0.0/0")
  96. exitNodeRouteV6 = netip.MustParsePrefix("::/0")
  97. )
  98. // ServerOpts contains options for constructing a new Server.
  99. type ServerOpts struct {
  100. // Mode specifies the mode of web client being constructed.
  101. Mode ServerMode
  102. // CGIMode indicates if the server is running as a CGI script.
  103. CGIMode bool
  104. // PathPrefix is the URL prefix added to requests by CGI or reverse proxy.
  105. PathPrefix string
  106. // LocalClient is the tailscale.LocalClient to use for this web server.
  107. // If nil, a new one will be created.
  108. LocalClient *tailscale.LocalClient
  109. // TimeNow optionally provides a time function.
  110. // time.Now is used as default.
  111. TimeNow func() time.Time
  112. // Logf optionally provides a logger function.
  113. // log.Printf is used as default.
  114. Logf logger.Logf
  115. // The following two fields are required and used exclusively
  116. // in ManageServerMode to facilitate the control server login
  117. // check step for authorizing browser sessions.
  118. // NewAuthURL should be provided as a function that generates
  119. // a new tailcfg.WebClientAuthResponse.
  120. // This field is required for ManageServerMode mode.
  121. NewAuthURL func(ctx context.Context, src tailcfg.NodeID) (*tailcfg.WebClientAuthResponse, error)
  122. // WaitAuthURL should be provided as a function that blocks until
  123. // the associated tailcfg.WebClientAuthResponse has been marked
  124. // as completed.
  125. // This field is required for ManageServerMode mode.
  126. WaitAuthURL func(ctx context.Context, id string, src tailcfg.NodeID) (*tailcfg.WebClientAuthResponse, error)
  127. }
  128. // NewServer constructs a new Tailscale web client server.
  129. // If err is empty, s is always non-nil.
  130. // ctx is only required to live the duration of the NewServer call,
  131. // and not the lifespan of the web server.
  132. func NewServer(opts ServerOpts) (s *Server, err error) {
  133. switch opts.Mode {
  134. case LoginServerMode, ManageServerMode:
  135. // valid types
  136. case "":
  137. return nil, fmt.Errorf("must specify a Mode")
  138. default:
  139. return nil, fmt.Errorf("invalid Mode provided")
  140. }
  141. if opts.LocalClient == nil {
  142. opts.LocalClient = &tailscale.LocalClient{}
  143. }
  144. s = &Server{
  145. mode: opts.Mode,
  146. logf: opts.Logf,
  147. devMode: envknob.Bool("TS_DEBUG_WEB_CLIENT_DEV"),
  148. lc: opts.LocalClient,
  149. cgiMode: opts.CGIMode,
  150. pathPrefix: opts.PathPrefix,
  151. timeNow: opts.TimeNow,
  152. newAuthURL: opts.NewAuthURL,
  153. waitAuthURL: opts.WaitAuthURL,
  154. }
  155. if opts.PathPrefix != "" {
  156. // Enforce that path prefix always has a single leading '/'
  157. // so that it is treated as a relative URL path.
  158. // We strip multiple leading '/' to prevent schema-less offsite URLs like "//example.com".
  159. //
  160. // See https://github.com/tailscale/corp/issues/16268.
  161. s.pathPrefix = "/" + strings.TrimLeft(path.Clean(opts.PathPrefix), "/\\")
  162. }
  163. if s.mode == ManageServerMode {
  164. if opts.NewAuthURL == nil {
  165. return nil, fmt.Errorf("must provide a NewAuthURL implementation")
  166. }
  167. if opts.WaitAuthURL == nil {
  168. return nil, fmt.Errorf("must provide WaitAuthURL implementation")
  169. }
  170. }
  171. if s.timeNow == nil {
  172. s.timeNow = time.Now
  173. }
  174. if s.logf == nil {
  175. s.logf = log.Printf
  176. }
  177. s.assetsHandler, s.assetsCleanup = assetsHandler(s.devMode)
  178. var metric string // clientmetric to report on startup
  179. // Create handler for "/api" requests with CSRF protection.
  180. // We don't require secure cookies, since the web client is regularly used
  181. // on network appliances that are served on local non-https URLs.
  182. // The client is secured by limiting the interface it listens on,
  183. // or by authenticating requests before they reach the web client.
  184. csrfProtect := csrf.Protect(s.csrfKey(), csrf.Secure(false))
  185. if s.mode == LoginServerMode {
  186. s.apiHandler = csrfProtect(http.HandlerFunc(s.serveLoginAPI))
  187. metric = "web_login_client_initialization"
  188. } else {
  189. s.apiHandler = csrfProtect(http.HandlerFunc(s.serveAPI))
  190. metric = "web_client_initialization"
  191. }
  192. // Don't block startup on reporting metric.
  193. // Report in separate go routine with 5 second timeout.
  194. go func() {
  195. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  196. defer cancel()
  197. s.lc.IncrementCounter(ctx, metric, 1)
  198. }()
  199. return s, nil
  200. }
  201. func (s *Server) Shutdown() {
  202. s.logf("web.Server: shutting down")
  203. if s.assetsCleanup != nil {
  204. s.assetsCleanup()
  205. }
  206. }
  207. // ServeHTTP processes all requests for the Tailscale web client.
  208. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  209. handler := s.serve
  210. // if path prefix is defined, strip it from requests.
  211. if s.cgiMode && s.pathPrefix != "" {
  212. handler = enforcePrefix(s.pathPrefix, handler)
  213. }
  214. handler(w, r)
  215. }
  216. func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
  217. if s.mode == ManageServerMode {
  218. // In manage mode, requests must be sent directly to the bare Tailscale IP address.
  219. // If a request comes in on any other hostname, redirect.
  220. if s.requireTailscaleIP(w, r) {
  221. return // user was redirected
  222. }
  223. // serve HTTP 204 on /ok requests as connectivity check
  224. if r.Method == httpm.GET && r.URL.Path == "/ok" {
  225. w.WriteHeader(http.StatusNoContent)
  226. return
  227. }
  228. if !s.devMode {
  229. // This hash corresponds to the inline script in index.html that runs when the react app is unavailable.
  230. // It was generated from https://csplite.com/csp/sha/.
  231. // If the contents of the script are changed, this hash must be updated.
  232. const indexScriptHash = "sha384-CW2AYVfS14P7QHZN27thEkMLKiCj3YNURPoLc1elwiEkMVHeuYTWkJOEki1F3nZc"
  233. w.Header().Set("X-Frame-Options", "DENY")
  234. w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src * data:; script-src 'self' '"+indexScriptHash+"'")
  235. w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
  236. }
  237. }
  238. if strings.HasPrefix(r.URL.Path, "/api/") {
  239. switch {
  240. case r.URL.Path == "/api/auth" && r.Method == httpm.GET:
  241. s.serveAPIAuth(w, r) // serve auth status
  242. return
  243. case r.URL.Path == "/api/auth/session/new" && r.Method == httpm.GET:
  244. s.serveAPIAuthSessionNew(w, r) // create new session
  245. return
  246. case r.URL.Path == "/api/auth/session/wait" && r.Method == httpm.GET:
  247. s.serveAPIAuthSessionWait(w, r) // wait for session to be authorized
  248. return
  249. }
  250. if ok := s.authorizeRequest(w, r); !ok {
  251. http.Error(w, "not authorized", http.StatusUnauthorized)
  252. return
  253. }
  254. // Pass API requests through to the API handler.
  255. s.apiHandler.ServeHTTP(w, r)
  256. return
  257. }
  258. s.assetsHandler.ServeHTTP(w, r)
  259. }
  260. // requireTailscaleIP redirects an incoming request if the HTTP request was not made to a bare Tailscale IP address.
  261. // The request will be redirected to the Tailscale IP, port 5252, with the original request path.
  262. // This allows any custom hostname to be used to access the device, but protects against DNS rebinding attacks.
  263. // Returns true if the request has been fully handled, either be returning a redirect or an HTTP error.
  264. func (s *Server) requireTailscaleIP(w http.ResponseWriter, r *http.Request) (handled bool) {
  265. const (
  266. ipv4ServiceHost = tsaddr.TailscaleServiceIPString
  267. ipv6ServiceHost = "[" + tsaddr.TailscaleServiceIPv6String + "]"
  268. )
  269. // allow requests on quad-100 (or ipv6 equivalent)
  270. if r.Host == ipv4ServiceHost || r.Host == ipv6ServiceHost {
  271. return false
  272. }
  273. st, err := s.lc.StatusWithoutPeers(r.Context())
  274. if err != nil {
  275. s.logf("error getting status: %v", err)
  276. http.Error(w, "internal error", http.StatusInternalServerError)
  277. return true
  278. }
  279. ipv4, ipv6 := s.selfNodeAddresses(r, st)
  280. if r.Host == fmt.Sprintf("%s:%d", ipv4.String(), ListenPort) {
  281. return false // already accessing over Tailscale IP
  282. }
  283. if r.Host == fmt.Sprintf("[%s]:%d", ipv6.String(), ListenPort) {
  284. return false // already accessing over Tailscale IP
  285. }
  286. // Not currently accessing via Tailscale IP,
  287. // redirect them.
  288. var preferV6 bool
  289. if ap, err := netip.ParseAddrPort(r.Host); err == nil {
  290. // If Host was already ipv6, keep them on same protocol.
  291. preferV6 = ap.Addr().Is6()
  292. }
  293. newURL := *r.URL
  294. if (preferV6 && ipv6.IsValid()) || !ipv4.IsValid() {
  295. newURL.Host = fmt.Sprintf("[%s]:%d", ipv6.String(), ListenPort)
  296. } else {
  297. newURL.Host = fmt.Sprintf("%s:%d", ipv4.String(), ListenPort)
  298. }
  299. http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently)
  300. return true
  301. }
  302. // selfNodeAddresses return the Tailscale IPv4 and IPv6 addresses for the self node.
  303. // st is expected to be a status with peers included.
  304. func (s *Server) selfNodeAddresses(r *http.Request, st *ipnstate.Status) (ipv4, ipv6 netip.Addr) {
  305. for _, ip := range st.Self.TailscaleIPs {
  306. if ip.Is4() {
  307. ipv4 = ip
  308. } else if ip.Is6() {
  309. ipv6 = ip
  310. }
  311. if ipv4.IsValid() && ipv6.IsValid() {
  312. break // found both IPs
  313. }
  314. }
  315. if whois, err := s.lc.WhoIs(r.Context(), r.RemoteAddr); err == nil {
  316. // The source peer connecting to this node may know it by a different
  317. // IP than the node knows itself as. Specifically, this may be the case
  318. // if the peer is coming from a different tailnet (sharee node), as IPs
  319. // are specific to each tailnet.
  320. // Here, we check if the source peer knows the node by a different IP,
  321. // and return the peer's version if so.
  322. if knownIPv4 := whois.Node.SelfNodeV4MasqAddrForThisPeer; knownIPv4 != nil {
  323. ipv4 = *knownIPv4
  324. }
  325. if knownIPv6 := whois.Node.SelfNodeV6MasqAddrForThisPeer; knownIPv6 != nil {
  326. ipv6 = *knownIPv6
  327. }
  328. }
  329. return ipv4, ipv6
  330. }
  331. // authorizeRequest reports whether the request from the web client
  332. // is authorized to be completed.
  333. // It reports true if the request is authorized, and false otherwise.
  334. // authorizeRequest manages writing out any relevant authorization
  335. // errors to the ResponseWriter itself.
  336. func (s *Server) authorizeRequest(w http.ResponseWriter, r *http.Request) (ok bool) {
  337. if s.mode == ManageServerMode { // client using tailscale auth
  338. session, _, _, err := s.getSession(r)
  339. switch {
  340. case errors.Is(err, errNotUsingTailscale):
  341. // All requests must be made over tailscale.
  342. http.Error(w, "must access over tailscale", http.StatusUnauthorized)
  343. return false
  344. case r.URL.Path == "/api/data" && r.Method == httpm.GET:
  345. // Readonly endpoint allowed without valid browser session.
  346. return true
  347. case r.URL.Path == "/api/device-details-click" && r.Method == httpm.POST:
  348. // Special case metric endpoint that is allowed without a browser session.
  349. return true
  350. case strings.HasPrefix(r.URL.Path, "/api/"):
  351. // All other /api/ endpoints require a valid browser session.
  352. if err != nil || !session.isAuthorized(s.timeNow()) {
  353. http.Error(w, "no valid session", http.StatusUnauthorized)
  354. return false
  355. }
  356. return true
  357. default:
  358. // No additional auth on non-api (assets, index.html, etc).
  359. return true
  360. }
  361. }
  362. // Client using system-specific auth.
  363. switch distro.Get() {
  364. case distro.Synology:
  365. authorized, _ := authorizeSynology(r)
  366. return authorized
  367. case distro.QNAP:
  368. authorized, _ := authorizeQNAP(r)
  369. return authorized
  370. default:
  371. return true // no additional auth for this distro
  372. }
  373. }
  374. // serveLoginAPI serves requests for the web login client.
  375. // It should only be called by Server.ServeHTTP, via Server.apiHandler,
  376. // which protects the handler using gorilla csrf.
  377. func (s *Server) serveLoginAPI(w http.ResponseWriter, r *http.Request) {
  378. w.Header().Set("X-CSRF-Token", csrf.Token(r))
  379. switch {
  380. case r.URL.Path == "/api/data" && r.Method == httpm.GET:
  381. s.serveGetNodeData(w, r)
  382. case r.URL.Path == "/api/up" && r.Method == httpm.POST:
  383. s.serveTailscaleUp(w, r)
  384. case r.URL.Path == "/api/device-details-click" && r.Method == httpm.POST:
  385. s.serveDeviceDetailsClick(w, r)
  386. default:
  387. http.Error(w, "invalid endpoint or method", http.StatusNotFound)
  388. }
  389. }
  390. type authType string
  391. var (
  392. synoAuth authType = "synology" // user needs a SynoToken for subsequent API calls
  393. tailscaleAuth authType = "tailscale" // user needs to complete Tailscale check mode
  394. )
  395. type authResponse struct {
  396. AuthNeeded authType `json:"authNeeded,omitempty"` // filled when user needs to complete a specific type of auth
  397. CanManageNode bool `json:"canManageNode"`
  398. ViewerIdentity *viewerIdentity `json:"viewerIdentity,omitempty"`
  399. ServerMode ServerMode `json:"serverMode"`
  400. }
  401. // viewerIdentity is the Tailscale identity of the source node
  402. // connected to this web client.
  403. type viewerIdentity struct {
  404. LoginName string `json:"loginName"`
  405. NodeName string `json:"nodeName"`
  406. NodeIP string `json:"nodeIP"`
  407. ProfilePicURL string `json:"profilePicUrl,omitempty"`
  408. Capabilities peerCapabilities `json:"capabilities"` // features peer is allowed to edit
  409. }
  410. // serverAPIAuth handles requests to the /api/auth endpoint
  411. // and returns an authResponse indicating the current auth state and any steps the user needs to take.
  412. func (s *Server) serveAPIAuth(w http.ResponseWriter, r *http.Request) {
  413. var resp authResponse
  414. resp.ServerMode = s.mode
  415. session, whois, status, sErr := s.getSession(r)
  416. if whois != nil {
  417. caps, err := toPeerCapabilities(whois)
  418. if err != nil {
  419. http.Error(w, sErr.Error(), http.StatusInternalServerError)
  420. return
  421. }
  422. resp.ViewerIdentity = &viewerIdentity{
  423. LoginName: whois.UserProfile.LoginName,
  424. NodeName: whois.Node.Name,
  425. ProfilePicURL: whois.UserProfile.ProfilePicURL,
  426. Capabilities: caps,
  427. }
  428. if addrs := whois.Node.Addresses; len(addrs) > 0 {
  429. resp.ViewerIdentity.NodeIP = addrs[0].Addr().String()
  430. }
  431. }
  432. // First verify platform auth.
  433. // If platform auth is needed, this should happen first.
  434. if s.mode == LoginServerMode {
  435. switch distro.Get() {
  436. case distro.Synology:
  437. authorized, err := authorizeSynology(r)
  438. if err != nil {
  439. http.Error(w, err.Error(), http.StatusUnauthorized)
  440. return
  441. }
  442. if !authorized {
  443. resp.AuthNeeded = synoAuth
  444. writeJSON(w, resp)
  445. return
  446. }
  447. case distro.QNAP:
  448. if _, err := authorizeQNAP(r); err != nil {
  449. http.Error(w, err.Error(), http.StatusUnauthorized)
  450. return
  451. }
  452. default:
  453. // no additional auth for this distro
  454. }
  455. }
  456. switch {
  457. case sErr != nil && errors.Is(sErr, errNotUsingTailscale):
  458. // Restricted to the readonly view, no auth action to take.
  459. s.lc.IncrementCounter(r.Context(), "web_client_viewing_local", 1)
  460. resp.AuthNeeded = ""
  461. case sErr != nil && errors.Is(sErr, errNotOwner):
  462. // Restricted to the readonly view, no auth action to take.
  463. s.lc.IncrementCounter(r.Context(), "web_client_viewing_not_owner", 1)
  464. resp.AuthNeeded = ""
  465. case sErr != nil && errors.Is(sErr, errTaggedLocalSource):
  466. // Restricted to the readonly view, no auth action to take.
  467. s.lc.IncrementCounter(r.Context(), "web_client_viewing_local_tag", 1)
  468. resp.AuthNeeded = ""
  469. case sErr != nil && errors.Is(sErr, errTaggedRemoteSource):
  470. // Restricted to the readonly view, no auth action to take.
  471. s.lc.IncrementCounter(r.Context(), "web_client_viewing_remote_tag", 1)
  472. resp.AuthNeeded = ""
  473. case sErr != nil && !errors.Is(sErr, errNoSession):
  474. // Any other error.
  475. http.Error(w, sErr.Error(), http.StatusInternalServerError)
  476. return
  477. case session.isAuthorized(s.timeNow()):
  478. if whois.Node.StableID == status.Self.ID {
  479. s.lc.IncrementCounter(r.Context(), "web_client_managing_local", 1)
  480. } else {
  481. s.lc.IncrementCounter(r.Context(), "web_client_managing_remote", 1)
  482. }
  483. resp.CanManageNode = true
  484. resp.AuthNeeded = ""
  485. default:
  486. // whois being nil implies local as the request did not come over Tailscale
  487. if whois == nil || (whois.Node.StableID == status.Self.ID) {
  488. s.lc.IncrementCounter(r.Context(), "web_client_viewing_local", 1)
  489. } else {
  490. s.lc.IncrementCounter(r.Context(), "web_client_viewing_remote", 1)
  491. }
  492. resp.AuthNeeded = tailscaleAuth
  493. }
  494. writeJSON(w, resp)
  495. }
  496. type newSessionAuthResponse struct {
  497. AuthURL string `json:"authUrl,omitempty"`
  498. }
  499. // serveAPIAuthSessionNew handles requests to the /api/auth/session/new endpoint.
  500. func (s *Server) serveAPIAuthSessionNew(w http.ResponseWriter, r *http.Request) {
  501. session, whois, _, err := s.getSession(r)
  502. if err != nil && !errors.Is(err, errNoSession) {
  503. // Source associated with request not allowed to create
  504. // a session for this web client.
  505. http.Error(w, err.Error(), http.StatusUnauthorized)
  506. return
  507. }
  508. if session == nil {
  509. // Create a new session.
  510. // If one already existed, we return that authURL rather than creating a new one.
  511. session, err = s.newSession(r.Context(), whois)
  512. if err != nil {
  513. http.Error(w, err.Error(), http.StatusInternalServerError)
  514. return
  515. }
  516. // Set the cookie on browser.
  517. http.SetCookie(w, &http.Cookie{
  518. Name: sessionCookieName,
  519. Value: session.ID,
  520. Raw: session.ID,
  521. Path: "/",
  522. HttpOnly: true,
  523. SameSite: http.SameSiteStrictMode,
  524. Expires: session.expires(),
  525. // We can't set Secure to true because we serve over HTTP
  526. // (but only on Tailscale IPs, hence over encrypted
  527. // connections that a LAN-local attacker cannot sniff).
  528. // In the future, we could support HTTPS requests using
  529. // the full MagicDNS hostname, and could set this.
  530. // Secure: true,
  531. })
  532. }
  533. writeJSON(w, newSessionAuthResponse{AuthURL: session.AuthURL})
  534. }
  535. // serveAPIAuthSessionWait handles requests to the /api/auth/session/wait endpoint.
  536. func (s *Server) serveAPIAuthSessionWait(w http.ResponseWriter, r *http.Request) {
  537. session, _, _, err := s.getSession(r)
  538. if err != nil {
  539. http.Error(w, err.Error(), http.StatusUnauthorized)
  540. return
  541. }
  542. if session.isAuthorized(s.timeNow()) {
  543. return // already authorized
  544. }
  545. if err := s.awaitUserAuth(r.Context(), session); err != nil {
  546. http.Error(w, err.Error(), http.StatusUnauthorized)
  547. return
  548. }
  549. }
  550. // serveAPI serves requests for the web client api.
  551. // It should only be called by Server.ServeHTTP, via Server.apiHandler,
  552. // which protects the handler using gorilla csrf.
  553. func (s *Server) serveAPI(w http.ResponseWriter, r *http.Request) {
  554. w.Header().Set("X-CSRF-Token", csrf.Token(r))
  555. path := strings.TrimPrefix(r.URL.Path, "/api")
  556. switch {
  557. case path == "/data" && r.Method == httpm.GET:
  558. s.serveGetNodeData(w, r)
  559. return
  560. case path == "/exit-nodes" && r.Method == httpm.GET:
  561. s.serveGetExitNodes(w, r)
  562. return
  563. case path == "/routes" && r.Method == httpm.POST:
  564. s.servePostRoutes(w, r)
  565. return
  566. case path == "/device-details-click" && r.Method == httpm.POST:
  567. s.serveDeviceDetailsClick(w, r)
  568. return
  569. case strings.HasPrefix(path, "/local/"):
  570. s.proxyRequestToLocalAPI(w, r)
  571. return
  572. }
  573. http.Error(w, "invalid endpoint", http.StatusNotFound)
  574. }
  575. type nodeData struct {
  576. ID tailcfg.StableNodeID
  577. Status string
  578. DeviceName string
  579. TailnetName string // TLS cert name
  580. DomainName string
  581. IPv4 string
  582. IPv6 string
  583. OS string
  584. IPNVersion string
  585. Profile tailcfg.UserProfile
  586. IsTagged bool
  587. Tags []string
  588. KeyExpiry string // time.RFC3339
  589. KeyExpired bool
  590. TUNMode bool
  591. IsSynology bool
  592. DSMVersion int // 6 or 7, if IsSynology=true
  593. IsUnraid bool
  594. UnraidToken string
  595. URLPrefix string // if set, the URL prefix the client is served behind
  596. UsingExitNode *exitNode
  597. AdvertisingExitNode bool
  598. AdvertisingExitNodeApproved bool // whether running this node as an exit node has been approved by an admin
  599. AdvertisedRoutes []subnetRoute // excludes exit node routes
  600. RunningSSHServer bool
  601. ClientVersion *tailcfg.ClientVersion
  602. // whether tailnet ACLs allow access to port 5252 on this device
  603. ACLAllowsAnyIncomingTraffic bool
  604. ControlAdminURL string
  605. LicensesURL string
  606. // Features is the set of available features for use on the
  607. // current platform. e.g. "ssh", "advertise-exit-node", etc.
  608. // Map value is true if the given feature key is available.
  609. //
  610. // See web.availableFeatures func for population of this field.
  611. // Contents are expected to match values defined in node-data.ts
  612. // on the frontend.
  613. Features map[string]bool
  614. }
  615. type subnetRoute struct {
  616. Route string
  617. Approved bool // approved by control server
  618. }
  619. func (s *Server) serveGetNodeData(w http.ResponseWriter, r *http.Request) {
  620. st, err := s.lc.Status(r.Context())
  621. if err != nil {
  622. http.Error(w, err.Error(), http.StatusInternalServerError)
  623. return
  624. }
  625. prefs, err := s.lc.GetPrefs(r.Context())
  626. if err != nil {
  627. http.Error(w, err.Error(), http.StatusInternalServerError)
  628. return
  629. }
  630. filterRules, _ := s.lc.DebugPacketFilterRules(r.Context())
  631. data := &nodeData{
  632. ID: st.Self.ID,
  633. Status: st.BackendState,
  634. DeviceName: strings.Split(st.Self.DNSName, ".")[0],
  635. OS: st.Self.OS,
  636. IPNVersion: strings.Split(st.Version, "-")[0],
  637. Profile: st.User[st.Self.UserID],
  638. IsTagged: st.Self.IsTagged(),
  639. KeyExpired: st.Self.Expired,
  640. TUNMode: st.TUN,
  641. IsSynology: distro.Get() == distro.Synology || envknob.Bool("TS_FAKE_SYNOLOGY"),
  642. DSMVersion: distro.DSMVersion(),
  643. IsUnraid: distro.Get() == distro.Unraid,
  644. UnraidToken: os.Getenv("UNRAID_CSRF_TOKEN"),
  645. RunningSSHServer: prefs.RunSSH,
  646. URLPrefix: strings.TrimSuffix(s.pathPrefix, "/"),
  647. ControlAdminURL: prefs.AdminPageURL(),
  648. LicensesURL: licenses.LicensesURL(),
  649. Features: availableFeatures(),
  650. ACLAllowsAnyIncomingTraffic: s.aclsAllowAccess(filterRules),
  651. }
  652. ipv4, ipv6 := s.selfNodeAddresses(r, st)
  653. data.IPv4 = ipv4.String()
  654. data.IPv6 = ipv6.String()
  655. if hostinfo.GetEnvType() == hostinfo.HomeAssistantAddOn && data.URLPrefix == "" {
  656. // X-Ingress-Path is the path prefix in use for Home Assistant
  657. // https://developers.home-assistant.io/docs/add-ons/presentation#ingress
  658. data.URLPrefix = r.Header.Get("X-Ingress-Path")
  659. }
  660. cv, err := s.lc.CheckUpdate(r.Context())
  661. if err != nil {
  662. s.logf("could not check for updates: %v", err)
  663. } else {
  664. data.ClientVersion = cv
  665. }
  666. if st.CurrentTailnet != nil {
  667. data.TailnetName = st.CurrentTailnet.MagicDNSSuffix
  668. data.DomainName = st.CurrentTailnet.Name
  669. }
  670. if st.Self.Tags != nil {
  671. data.Tags = st.Self.Tags.AsSlice()
  672. }
  673. if st.Self.KeyExpiry != nil {
  674. data.KeyExpiry = st.Self.KeyExpiry.Format(time.RFC3339)
  675. }
  676. routeApproved := func(route netip.Prefix) bool {
  677. if st.Self == nil || st.Self.AllowedIPs == nil {
  678. return false
  679. }
  680. return st.Self.AllowedIPs.ContainsFunc(func(p netip.Prefix) bool {
  681. return p == route
  682. })
  683. }
  684. data.AdvertisingExitNodeApproved = routeApproved(exitNodeRouteV4) || routeApproved(exitNodeRouteV6)
  685. for _, r := range prefs.AdvertiseRoutes {
  686. if r == exitNodeRouteV4 || r == exitNodeRouteV6 {
  687. data.AdvertisingExitNode = true
  688. } else {
  689. data.AdvertisedRoutes = append(data.AdvertisedRoutes, subnetRoute{
  690. Route: r.String(),
  691. Approved: routeApproved(r),
  692. })
  693. }
  694. }
  695. if e := st.ExitNodeStatus; e != nil {
  696. data.UsingExitNode = &exitNode{
  697. ID: e.ID,
  698. Online: e.Online,
  699. }
  700. for _, ps := range st.Peer {
  701. if ps.ID == e.ID {
  702. data.UsingExitNode.Name = ps.DNSName
  703. data.UsingExitNode.Location = ps.Location
  704. break
  705. }
  706. }
  707. if data.UsingExitNode.Name == "" {
  708. // Falling back to TailscaleIP/StableNodeID when the peer
  709. // is no longer included in status.
  710. if len(e.TailscaleIPs) > 0 {
  711. data.UsingExitNode.Name = e.TailscaleIPs[0].Addr().String()
  712. } else {
  713. data.UsingExitNode.Name = string(e.ID)
  714. }
  715. }
  716. }
  717. writeJSON(w, *data)
  718. }
  719. func availableFeatures() map[string]bool {
  720. env := hostinfo.GetEnvType()
  721. features := map[string]bool{
  722. "advertise-exit-node": true, // available on all platforms
  723. "advertise-routes": true, // available on all platforms
  724. "use-exit-node": canUseExitNode(env) == nil,
  725. "ssh": envknob.CanRunTailscaleSSH() == nil,
  726. "auto-update": version.IsUnstableBuild() && clientupdate.CanAutoUpdate(),
  727. }
  728. if env == hostinfo.HomeAssistantAddOn {
  729. // Setting SSH on Home Assistant causes trouble on startup
  730. // (since the flag is not being passed to `tailscale up`).
  731. // Although Tailscale SSH does work here,
  732. // it's not terribly useful since it's running in a separate container.
  733. features["ssh"] = false
  734. }
  735. return features
  736. }
  737. func canUseExitNode(env hostinfo.EnvType) error {
  738. switch dist := distro.Get(); dist {
  739. case distro.Synology, // see https://github.com/tailscale/tailscale/issues/1995
  740. distro.QNAP,
  741. distro.Unraid:
  742. return fmt.Errorf("Tailscale exit nodes cannot be used on %s.", dist)
  743. }
  744. if env == hostinfo.HomeAssistantAddOn {
  745. return errors.New("Tailscale exit nodes cannot be used on Home Assistant.")
  746. }
  747. return nil
  748. }
  749. // aclsAllowAccess returns whether tailnet ACLs (as expressed in the provided filter rules)
  750. // permit any devices to access the local web client.
  751. // This does not currently check whether a specific device can connect, just any device.
  752. func (s *Server) aclsAllowAccess(rules []tailcfg.FilterRule) bool {
  753. for _, rule := range rules {
  754. for _, dp := range rule.DstPorts {
  755. if dp.Ports.Contains(ListenPort) {
  756. return true
  757. }
  758. }
  759. }
  760. return false
  761. }
  762. type exitNode struct {
  763. ID tailcfg.StableNodeID
  764. Name string
  765. Location *tailcfg.Location
  766. Online bool
  767. }
  768. func (s *Server) serveGetExitNodes(w http.ResponseWriter, r *http.Request) {
  769. st, err := s.lc.Status(r.Context())
  770. if err != nil {
  771. http.Error(w, err.Error(), http.StatusInternalServerError)
  772. return
  773. }
  774. var exitNodes []*exitNode
  775. for _, ps := range st.Peer {
  776. if !ps.ExitNodeOption {
  777. continue
  778. }
  779. exitNodes = append(exitNodes, &exitNode{
  780. ID: ps.ID,
  781. Name: ps.DNSName,
  782. Location: ps.Location,
  783. Online: ps.Online,
  784. })
  785. }
  786. writeJSON(w, exitNodes)
  787. }
  788. type postRoutesRequest struct {
  789. SetExitNode bool // when set, UseExitNode and AdvertiseExitNode values are applied
  790. SetRoutes bool // when set, AdvertiseRoutes value is applied
  791. UseExitNode tailcfg.StableNodeID
  792. AdvertiseExitNode bool
  793. AdvertiseRoutes []string
  794. }
  795. func (s *Server) servePostRoutes(w http.ResponseWriter, r *http.Request) {
  796. defer r.Body.Close()
  797. var data postRoutesRequest
  798. if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
  799. http.Error(w, err.Error(), http.StatusInternalServerError)
  800. return
  801. }
  802. prefs, err := s.lc.GetPrefs(r.Context())
  803. if err != nil {
  804. http.Error(w, err.Error(), http.StatusInternalServerError)
  805. return
  806. }
  807. var currNonExitRoutes []string
  808. var currAdvertisingExitNode bool
  809. for _, r := range prefs.AdvertiseRoutes {
  810. if r == exitNodeRouteV4 || r == exitNodeRouteV6 {
  811. currAdvertisingExitNode = true
  812. continue
  813. }
  814. currNonExitRoutes = append(currNonExitRoutes, r.String())
  815. }
  816. // Set non-edited fields to their current values.
  817. if data.SetExitNode {
  818. data.AdvertiseRoutes = currNonExitRoutes
  819. } else if data.SetRoutes {
  820. data.AdvertiseExitNode = currAdvertisingExitNode
  821. data.UseExitNode = prefs.ExitNodeID
  822. }
  823. // Calculate routes.
  824. routesStr := strings.Join(data.AdvertiseRoutes, ",")
  825. routes, err := netutil.CalcAdvertiseRoutes(routesStr, data.AdvertiseExitNode)
  826. if err != nil {
  827. http.Error(w, err.Error(), http.StatusInternalServerError)
  828. return
  829. }
  830. hasExitNodeRoute := func(all []netip.Prefix) bool {
  831. return slices.Contains(all, exitNodeRouteV4) ||
  832. slices.Contains(all, exitNodeRouteV6)
  833. }
  834. if !data.UseExitNode.IsZero() && hasExitNodeRoute(routes) {
  835. http.Error(w, "cannot use and advertise exit node at same time", http.StatusBadRequest)
  836. return
  837. }
  838. // Make prefs update.
  839. p := &ipn.MaskedPrefs{
  840. AdvertiseRoutesSet: true,
  841. ExitNodeIDSet: true,
  842. Prefs: ipn.Prefs{
  843. ExitNodeID: data.UseExitNode,
  844. AdvertiseRoutes: routes,
  845. },
  846. }
  847. if _, err := s.lc.EditPrefs(r.Context(), p); err != nil {
  848. http.Error(w, err.Error(), http.StatusInternalServerError)
  849. return
  850. }
  851. w.WriteHeader(http.StatusOK)
  852. }
  853. // tailscaleUp starts the daemon with the provided options.
  854. // If reauthentication has been requested, an authURL is returned to complete device registration.
  855. func (s *Server) tailscaleUp(ctx context.Context, st *ipnstate.Status, opt tailscaleUpOptions) (authURL string, retErr error) {
  856. origAuthURL := st.AuthURL
  857. isRunning := st.BackendState == ipn.Running.String()
  858. if !opt.Reauthenticate {
  859. switch {
  860. case origAuthURL != "":
  861. return origAuthURL, nil
  862. case isRunning:
  863. return "", nil
  864. case st.BackendState == ipn.Stopped.String():
  865. // stopped and not reauthenticating, so just start running
  866. _, err := s.lc.EditPrefs(ctx, &ipn.MaskedPrefs{
  867. Prefs: ipn.Prefs{
  868. WantRunning: true,
  869. },
  870. WantRunningSet: true,
  871. })
  872. return "", err
  873. }
  874. }
  875. // printAuthURL reports whether we should print out the
  876. // provided auth URL from an IPN notify.
  877. printAuthURL := func(url string) bool {
  878. return url != origAuthURL
  879. }
  880. watchCtx, cancelWatch := context.WithCancel(ctx)
  881. defer cancelWatch()
  882. watcher, err := s.lc.WatchIPNBus(watchCtx, 0)
  883. if err != nil {
  884. return "", err
  885. }
  886. defer watcher.Close()
  887. go func() {
  888. if !isRunning {
  889. ipnOptions := ipn.Options{AuthKey: opt.AuthKey}
  890. if opt.ControlURL != "" {
  891. ipnOptions.UpdatePrefs = &ipn.Prefs{ControlURL: opt.ControlURL}
  892. }
  893. if err := s.lc.Start(ctx, ipnOptions); err != nil {
  894. s.logf("start: %v", err)
  895. }
  896. }
  897. if opt.Reauthenticate {
  898. if err := s.lc.StartLoginInteractive(ctx); err != nil {
  899. s.logf("startLogin: %v", err)
  900. }
  901. }
  902. }()
  903. for {
  904. n, err := watcher.Next()
  905. if err != nil {
  906. return "", err
  907. }
  908. if n.State != nil && *n.State == ipn.Running {
  909. return "", nil
  910. }
  911. if n.ErrMessage != nil {
  912. msg := *n.ErrMessage
  913. return "", fmt.Errorf("backend error: %v", msg)
  914. }
  915. if url := n.BrowseToURL; url != nil && printAuthURL(*url) {
  916. return *url, nil
  917. }
  918. }
  919. }
  920. type tailscaleUpOptions struct {
  921. // If true, force reauthentication of the client.
  922. // Otherwise simply reconnect, the same as running `tailscale up`.
  923. Reauthenticate bool
  924. ControlURL string
  925. AuthKey string
  926. }
  927. // serveTailscaleUp serves requests to /api/up.
  928. // If the user needs to authenticate, an authURL is provided in the response.
  929. func (s *Server) serveTailscaleUp(w http.ResponseWriter, r *http.Request) {
  930. defer r.Body.Close()
  931. st, err := s.lc.Status(r.Context())
  932. if err != nil {
  933. http.Error(w, err.Error(), http.StatusInternalServerError)
  934. return
  935. }
  936. var opt tailscaleUpOptions
  937. type mi map[string]any
  938. if err := json.NewDecoder(r.Body).Decode(&opt); err != nil {
  939. w.WriteHeader(400)
  940. json.NewEncoder(w).Encode(mi{"error": err.Error()})
  941. return
  942. }
  943. w.Header().Set("Content-Type", "application/json")
  944. s.logf("tailscaleUp(reauth=%v) ...", opt.Reauthenticate)
  945. url, err := s.tailscaleUp(r.Context(), st, opt)
  946. s.logf("tailscaleUp = (URL %v, %v)", url != "", err)
  947. if err != nil {
  948. w.WriteHeader(http.StatusInternalServerError)
  949. json.NewEncoder(w).Encode(mi{"error": err.Error()})
  950. return
  951. }
  952. if url != "" {
  953. json.NewEncoder(w).Encode(mi{"url": url})
  954. } else {
  955. io.WriteString(w, "{}")
  956. }
  957. }
  958. // serveDeviceDetailsClick increments the web_client_device_details_click metric
  959. // by one.
  960. //
  961. // Metric logging from the frontend typically is proxied to the localapi. This event
  962. // has been special cased as access to the localapi is gated upon having a valid
  963. // session which is not always the case when we want to be logging this metric (e.g.,
  964. // when in readonly mode).
  965. //
  966. // Other metrics should not be logged in this way without a good reason.
  967. func (s *Server) serveDeviceDetailsClick(w http.ResponseWriter, r *http.Request) {
  968. s.lc.IncrementCounter(r.Context(), "web_client_device_details_click", 1)
  969. io.WriteString(w, "{}")
  970. }
  971. // proxyRequestToLocalAPI proxies the web API request to the localapi.
  972. //
  973. // The web API request path is expected to exactly match a localapi path,
  974. // with prefix /api/local/ rather than /localapi/.
  975. //
  976. // If the localapi path is not included in localapiAllowlist,
  977. // the request is rejected.
  978. func (s *Server) proxyRequestToLocalAPI(w http.ResponseWriter, r *http.Request) {
  979. path := strings.TrimPrefix(r.URL.Path, "/api/local")
  980. if r.URL.Path == path { // missing prefix
  981. http.Error(w, "invalid request", http.StatusBadRequest)
  982. return
  983. }
  984. if r.Method == httpm.PATCH {
  985. // enforce that PATCH requests are always application/json
  986. if ct := r.Header.Get("Content-Type"); ct != "application/json" {
  987. http.Error(w, "invalid request", http.StatusBadRequest)
  988. return
  989. }
  990. }
  991. if !slices.Contains(localapiAllowlist, path) {
  992. http.Error(w, fmt.Sprintf("%s not allowed from localapi proxy", path), http.StatusForbidden)
  993. return
  994. }
  995. localAPIURL := "http://" + apitype.LocalAPIHost + "/localapi" + path
  996. req, err := http.NewRequestWithContext(r.Context(), r.Method, localAPIURL, r.Body)
  997. if err != nil {
  998. http.Error(w, "failed to construct request", http.StatusInternalServerError)
  999. return
  1000. }
  1001. // Make request to tailscaled localapi.
  1002. resp, err := s.lc.DoLocalRequest(req)
  1003. if err != nil {
  1004. http.Error(w, err.Error(), resp.StatusCode)
  1005. return
  1006. }
  1007. defer resp.Body.Close()
  1008. // Send response back to web frontend.
  1009. w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
  1010. w.WriteHeader(resp.StatusCode)
  1011. if _, err := io.Copy(w, resp.Body); err != nil {
  1012. http.Error(w, err.Error(), http.StatusInternalServerError)
  1013. }
  1014. }
  1015. // localapiAllowlist is an allowlist of localapi endpoints the
  1016. // web client is allowed to proxy to the client's localapi.
  1017. //
  1018. // Rather than exposing all localapi endpoints over the proxy,
  1019. // this limits to just the ones actually used from the web
  1020. // client frontend.
  1021. var localapiAllowlist = []string{
  1022. "/v0/logout",
  1023. "/v0/prefs",
  1024. "/v0/update/check",
  1025. "/v0/update/install",
  1026. "/v0/update/progress",
  1027. "/v0/upload-client-metrics",
  1028. }
  1029. // csrfKey returns a key that can be used for CSRF protection.
  1030. // If an error occurs during key creation, the error is logged and the active process terminated.
  1031. // If the server is running in CGI mode, the key is cached to disk and reused between requests.
  1032. // If an error occurs during key storage, the error is logged and the active process terminated.
  1033. func (s *Server) csrfKey() []byte {
  1034. csrfFile := filepath.Join(os.TempDir(), "tailscale-web-csrf.key")
  1035. // if running in CGI mode, try to read from disk, but ignore errors
  1036. if s.cgiMode {
  1037. key, _ := os.ReadFile(csrfFile)
  1038. if len(key) == 32 {
  1039. return key
  1040. }
  1041. }
  1042. // create a new key
  1043. key := make([]byte, 32)
  1044. if _, err := rand.Read(key); err != nil {
  1045. log.Fatalf("error generating CSRF key: %v", err)
  1046. }
  1047. // if running in CGI mode, try to write the newly created key to disk, and exit if it fails.
  1048. if s.cgiMode {
  1049. if err := os.WriteFile(csrfFile, key, 0600); err != nil {
  1050. log.Fatalf("unable to store CSRF key: %v", err)
  1051. }
  1052. }
  1053. return key
  1054. }
  1055. // enforcePrefix returns a HandlerFunc that enforces a given path prefix is used in requests,
  1056. // then strips it before invoking h.
  1057. // Unlike http.StripPrefix, it does not return a 404 if the prefix is not present.
  1058. // Instead, it returns a redirect to the prefix path.
  1059. func enforcePrefix(prefix string, h http.HandlerFunc) http.HandlerFunc {
  1060. if prefix == "" {
  1061. return h
  1062. }
  1063. // ensure that prefix always has both a leading and trailing slash so
  1064. // that relative links for JS and CSS assets work correctly.
  1065. if !strings.HasPrefix(prefix, "/") {
  1066. prefix = "/" + prefix
  1067. }
  1068. if !strings.HasSuffix(prefix, "/") {
  1069. prefix += "/"
  1070. }
  1071. return func(w http.ResponseWriter, r *http.Request) {
  1072. if !strings.HasPrefix(r.URL.Path, prefix) {
  1073. http.Redirect(w, r, prefix, http.StatusFound)
  1074. return
  1075. }
  1076. prefix = strings.TrimSuffix(prefix, "/")
  1077. http.StripPrefix(prefix, h).ServeHTTP(w, r)
  1078. }
  1079. }
  1080. func writeJSON(w http.ResponseWriter, data any) {
  1081. w.Header().Set("Content-Type", "application/json")
  1082. if err := json.NewEncoder(w).Encode(data); err != nil {
  1083. w.Header().Set("Content-Type", "text/plain")
  1084. http.Error(w, err.Error(), http.StatusInternalServerError)
  1085. return
  1086. }
  1087. }