server.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package lapitest provides utilities for black-box testing of LocalAPI ([ipnserver]).
  4. package lapitest
  5. import (
  6. "context"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "sync"
  12. "testing"
  13. "tailscale.com/client/local"
  14. "tailscale.com/client/tailscale/apitype"
  15. "tailscale.com/envknob"
  16. "tailscale.com/ipn"
  17. "tailscale.com/ipn/ipnauth"
  18. "tailscale.com/ipn/ipnlocal"
  19. "tailscale.com/ipn/ipnserver"
  20. "tailscale.com/types/logger"
  21. "tailscale.com/types/logid"
  22. "tailscale.com/types/ptr"
  23. "tailscale.com/util/mak"
  24. "tailscale.com/util/rands"
  25. )
  26. // A Server is an in-process LocalAPI server that can be used in end-to-end tests.
  27. type Server struct {
  28. tb testing.TB
  29. ctx context.Context
  30. cancelCtx context.CancelFunc
  31. lb *ipnlocal.LocalBackend
  32. ipnServer *ipnserver.Server
  33. // mu protects the following fields.
  34. mu sync.Mutex
  35. started bool
  36. httpServer *httptest.Server
  37. actorsByName map[string]*ipnauth.TestActor
  38. lastClientID int
  39. }
  40. // NewUnstartedServer returns a new [Server] with the specified options without starting it.
  41. func NewUnstartedServer(tb testing.TB, opts ...Option) *Server {
  42. tb.Helper()
  43. options, err := newOptions(tb, opts...)
  44. if err != nil {
  45. tb.Fatalf("invalid options: %v", err)
  46. }
  47. s := &Server{tb: tb, lb: options.Backend()}
  48. s.ctx, s.cancelCtx = context.WithCancel(options.Context())
  49. s.ipnServer = newUnstartedIPNServer(options)
  50. s.httpServer = httptest.NewUnstartedServer(http.HandlerFunc(s.serveHTTP))
  51. s.httpServer.Config.Addr = "http://" + apitype.LocalAPIHost
  52. s.httpServer.Config.BaseContext = func(_ net.Listener) context.Context { return s.ctx }
  53. s.httpServer.Config.ErrorLog = logger.StdLogger(logger.WithPrefix(options.Logf(), "lapitest: "))
  54. tb.Cleanup(s.Close)
  55. return s
  56. }
  57. // NewServer starts and returns a new [Server] with the specified options.
  58. func NewServer(tb testing.TB, opts ...Option) *Server {
  59. tb.Helper()
  60. server := NewUnstartedServer(tb, opts...)
  61. server.Start()
  62. return server
  63. }
  64. // Start starts the server from [NewUnstartedServer].
  65. func (s *Server) Start() {
  66. s.tb.Helper()
  67. s.mu.Lock()
  68. defer s.mu.Unlock()
  69. if !s.started && s.httpServer != nil {
  70. s.httpServer.Start()
  71. s.started = true
  72. }
  73. }
  74. // Backend returns the underlying [ipnlocal.LocalBackend].
  75. func (s *Server) Backend() *ipnlocal.LocalBackend {
  76. s.tb.Helper()
  77. return s.lb
  78. }
  79. // Client returns a new [Client] configured for making requests to the server
  80. // as a new [ipnauth.TestActor] with a unique username and [ipnauth.ClientID].
  81. func (s *Server) Client() *Client {
  82. s.tb.Helper()
  83. user := s.MakeTestActor("", "") // generate a unique username and client ID
  84. return s.ClientFor(user)
  85. }
  86. // ClientWithName returns a new [Client] configured for making requests to the server
  87. // as a new [ipnauth.TestActor] with the specified name and a unique [ipnauth.ClientID].
  88. func (s *Server) ClientWithName(name string) *Client {
  89. s.tb.Helper()
  90. user := s.MakeTestActor(name, "") // generate a unique client ID
  91. return s.ClientFor(user)
  92. }
  93. // ClientFor returns a new [Client] configured for making requests to the server
  94. // as the specified actor.
  95. func (s *Server) ClientFor(actor ipnauth.Actor) *Client {
  96. s.tb.Helper()
  97. client := &Client{
  98. tb: s.tb,
  99. Actor: actor,
  100. }
  101. client.Client = &local.Client{Transport: newRoundTripper(client, s.httpServer)}
  102. return client
  103. }
  104. // MakeTestActor returns a new [ipnauth.TestActor] with the specified name and client ID.
  105. // If the name is empty, a unique sequential name is generated. Likewise,
  106. // if clientID is empty, a unique sequential client ID is generated.
  107. func (s *Server) MakeTestActor(name string, clientID string) *ipnauth.TestActor {
  108. s.tb.Helper()
  109. s.mu.Lock()
  110. defer s.mu.Unlock()
  111. // Generate a unique sequential name if the provided name is empty.
  112. if name == "" {
  113. n := len(s.actorsByName)
  114. name = generateSequentialName("User", n)
  115. }
  116. if clientID == "" {
  117. s.lastClientID += 1
  118. clientID = fmt.Sprintf("Client-%d", s.lastClientID)
  119. }
  120. // Create a new base actor if one doesn't already exist for the given name.
  121. baseActor := s.actorsByName[name]
  122. if baseActor == nil {
  123. baseActor = &ipnauth.TestActor{Name: name}
  124. if envknob.GOOS() == "windows" {
  125. // Historically, as of 2025-04-15, IPN does not distinguish between
  126. // different users on non-Windows devices. Therefore, the UID, which is
  127. // an [ipn.WindowsUserID], should only be populated when the actual or
  128. // fake GOOS is Windows.
  129. baseActor.UID = ipn.WindowsUserID(fmt.Sprintf("S-1-5-21-1-0-0-%d", 1001+len(s.actorsByName)))
  130. }
  131. mak.Set(&s.actorsByName, name, baseActor)
  132. s.tb.Cleanup(func() { delete(s.actorsByName, name) })
  133. }
  134. // Create a shallow copy of the base actor and assign it the new client ID.
  135. actor := ptr.To(*baseActor)
  136. actor.CID = ipnauth.ClientIDFrom(clientID)
  137. return actor
  138. }
  139. // BlockWhileInUse blocks until the server becomes idle (no active requests),
  140. // or the context is done. It returns the context's error if it is done.
  141. // It is used in tests only.
  142. func (s *Server) BlockWhileInUse(ctx context.Context) error {
  143. s.tb.Helper()
  144. s.mu.Lock()
  145. defer s.mu.Unlock()
  146. if s.httpServer == nil {
  147. return nil
  148. }
  149. return s.ipnServer.BlockWhileInUseForTest(ctx)
  150. }
  151. // BlockWhileInUseByOther blocks while the specified actor can't connect to the server
  152. // due to another actor being connected.
  153. // It is used in tests only.
  154. func (s *Server) BlockWhileInUseByOther(ctx context.Context, actor ipnauth.Actor) error {
  155. s.tb.Helper()
  156. s.mu.Lock()
  157. defer s.mu.Unlock()
  158. if s.httpServer == nil {
  159. return nil
  160. }
  161. return s.ipnServer.BlockWhileInUseByOtherForTest(ctx, actor)
  162. }
  163. // CheckCurrentUser fails the test if the current user does not match the expected user.
  164. // It is only used on Windows and will be removed as we progress on tailscale/corp#18342.
  165. func (s *Server) CheckCurrentUser(want ipnauth.Actor) {
  166. s.tb.Helper()
  167. var wantUID ipn.WindowsUserID
  168. if want != nil {
  169. wantUID = want.UserID()
  170. }
  171. lb := s.Backend()
  172. if lb == nil {
  173. s.tb.Fatalf("Backend: nil")
  174. }
  175. gotUID, gotActor := lb.CurrentUserForTest()
  176. if gotUID != wantUID {
  177. s.tb.Errorf("CurrentUser: got UID %q; want %q", gotUID, wantUID)
  178. }
  179. if hasActor := gotActor != nil; hasActor != (want != nil) || (want != nil && gotActor != want) {
  180. s.tb.Errorf("CurrentUser: got %v; want %v", gotActor, want)
  181. }
  182. }
  183. func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) {
  184. actor, err := getActorForRequest(r)
  185. if err != nil {
  186. http.Error(w, err.Error(), http.StatusBadRequest)
  187. s.tb.Errorf("getActorForRequest: %v", err)
  188. return
  189. }
  190. ctx := ipnserver.NewContextWithActorForTest(r.Context(), actor)
  191. s.ipnServer.ServeHTTPForTest(w, r.Clone(ctx))
  192. }
  193. // Close shuts down the server and blocks until all outstanding requests on this server have completed.
  194. func (s *Server) Close() {
  195. s.tb.Helper()
  196. s.mu.Lock()
  197. server := s.httpServer
  198. s.httpServer = nil
  199. s.mu.Unlock()
  200. if server != nil {
  201. server.Close()
  202. }
  203. s.cancelCtx()
  204. }
  205. // newUnstartedIPNServer returns a new [ipnserver.Server] that exposes
  206. // the specified [ipnlocal.LocalBackend] via LocalAPI, but does not start it.
  207. // The opts carry additional configuration options.
  208. func newUnstartedIPNServer(opts *options) *ipnserver.Server {
  209. opts.TB().Helper()
  210. lb := opts.Backend()
  211. server := ipnserver.New(opts.Logf(), logid.PublicID{}, lb.EventBus(), lb.NetMon())
  212. server.SetLocalBackend(lb)
  213. return server
  214. }
  215. // roundTripper is a [http.RoundTripper] that sends requests to a [Server]
  216. // on behalf of the [Client] who owns it.
  217. type roundTripper struct {
  218. client *Client
  219. transport http.RoundTripper
  220. }
  221. // newRoundTripper returns a new [http.RoundTripper] that sends requests
  222. // to the specified server as the specified client.
  223. func newRoundTripper(client *Client, server *httptest.Server) http.RoundTripper {
  224. return &roundTripper{
  225. client: client,
  226. transport: &http.Transport{DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  227. var std net.Dialer
  228. return std.DialContext(ctx, network, server.Listener.Addr().(*net.TCPAddr).String())
  229. }},
  230. }
  231. }
  232. // requestIDHeaderName is the name of the header used to pass request IDs
  233. // between the client and server. It is used to associate requests with their actors.
  234. const requestIDHeaderName = "TS-Request-ID"
  235. // RoundTrip implements [http.RoundTripper] by sending the request to the [ipnserver.Server]
  236. // on behalf of the owning [Client]. It registers each request for the duration
  237. // of the call and associates it with the actor sending the request.
  238. func (rt *roundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
  239. reqID, unregister := registerRequest(rt.client.Actor)
  240. defer unregister()
  241. r = r.Clone(r.Context())
  242. r.Header.Set(requestIDHeaderName, reqID)
  243. return rt.transport.RoundTrip(r)
  244. }
  245. // getActorForRequest returns the actor for a given request.
  246. // It returns an error if the request is not associated with an actor,
  247. // such as when it wasn't sent by a [roundTripper].
  248. func getActorForRequest(r *http.Request) (ipnauth.Actor, error) {
  249. reqID := r.Header.Get(requestIDHeaderName)
  250. if reqID == "" {
  251. return nil, fmt.Errorf("missing %s header", requestIDHeaderName)
  252. }
  253. actor, ok := getActorByRequestID(reqID)
  254. if !ok {
  255. return nil, fmt.Errorf("unknown request: %s", reqID)
  256. }
  257. return actor, nil
  258. }
  259. var (
  260. inFlightRequestsMu sync.Mutex
  261. inFlightRequests map[string]ipnauth.Actor
  262. )
  263. // registerRequest associates a request with the specified actor and returns a unique request ID
  264. // which can be used to retrieve the actor later. The returned function unregisters the request.
  265. func registerRequest(actor ipnauth.Actor) (requestID string, unregister func()) {
  266. inFlightRequestsMu.Lock()
  267. defer inFlightRequestsMu.Unlock()
  268. for {
  269. requestID = rands.HexString(16)
  270. if _, ok := inFlightRequests[requestID]; !ok {
  271. break
  272. }
  273. }
  274. mak.Set(&inFlightRequests, requestID, actor)
  275. return requestID, func() {
  276. inFlightRequestsMu.Lock()
  277. defer inFlightRequestsMu.Unlock()
  278. delete(inFlightRequests, requestID)
  279. }
  280. }
  281. // getActorByRequestID returns the actor associated with the specified request ID.
  282. // It returns the actor and true if found, or nil and false if not.
  283. func getActorByRequestID(requestID string) (ipnauth.Actor, bool) {
  284. inFlightRequestsMu.Lock()
  285. defer inFlightRequestsMu.Unlock()
  286. actor, ok := inFlightRequests[requestID]
  287. return actor, ok
  288. }