manager.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package appproxy
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "errors"
  6. "net"
  7. "net/http"
  8. "net/http/httputil"
  9. "sort"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. )
  14. /*
  15. manager.go
  16. The Manager owns the published endpoints (persisted in the system
  17. database), one reverse proxy per endpoint and the subdomain login sessions.
  18. It knows nothing about ArozOS users or Docker: the core wires those in
  19. through Options, which keeps the package testable on its own.
  20. */
  21. const tableName = "appproxy"
  22. // Identity is the ArozOS user behind a request
  23. type Identity struct {
  24. Username string
  25. Groups []string
  26. IsAdmin bool
  27. }
  28. // Store is the subset of the system database the manager needs
  29. type Store interface {
  30. NewTable(tableName string) error
  31. Write(tableName string, key string, value interface{}) error
  32. Delete(tableName string, key string) error
  33. ListTable(tableName string) ([][][]byte, error)
  34. }
  35. // Options wires the manager into the host application
  36. type Options struct {
  37. Store Store
  38. //SelfPort is the port ArozOS listens on, so an endpoint cannot target it
  39. SelfPort int
  40. //ResolveUser returns the logged in user of a request on the ArozOS host, or nil
  41. ResolveUser func(w http.ResponseWriter, r *http.Request) *Identity
  42. //LookupUser returns a user by name (used to revalidate subdomain sessions), or nil
  43. LookupUser func(username string) *Identity
  44. //LoginURL is where an anonymous visitor of a protected app is sent, with
  45. //the path to come back to
  46. LoginURL func(returnTo string) string
  47. //StripCookies are the ArozOS cookie names never forwarded to a container
  48. StripCookies []string
  49. //Log receives operational messages
  50. Log func(message string, err error)
  51. //ContainersAvailable reports whether the host can run containers (Docker
  52. //is usable), so the desktop only offers its Container Apps category there.
  53. //Nil means no container support.
  54. ContainersAvailable func() bool
  55. }
  56. // Stats are runtime counters of one endpoint
  57. type Stats struct {
  58. Requests uint64
  59. Leaks uint64 //Root requests redirected back under /app/<slug>/
  60. LastLeaks []string //Most recent leaked paths, newest first
  61. }
  62. type endpointRuntime struct {
  63. ep *Endpoint
  64. proxy *httputil.ReverseProxy
  65. requests atomic.Uint64
  66. leaks atomic.Uint64
  67. leakMu sync.Mutex
  68. lastLeak []string
  69. }
  70. const maxLastLeaks = 10
  71. func (rt *endpointRuntime) recordLeak(path string) {
  72. rt.leaks.Add(1)
  73. rt.leakMu.Lock()
  74. defer rt.leakMu.Unlock()
  75. rt.lastLeak = append([]string{path}, rt.lastLeak...)
  76. if len(rt.lastLeak) > maxLastLeaks {
  77. rt.lastLeak = rt.lastLeak[:maxLastLeaks]
  78. }
  79. }
  80. func (rt *endpointRuntime) stats() Stats {
  81. rt.leakMu.Lock()
  82. defer rt.leakMu.Unlock()
  83. return Stats{
  84. Requests: rt.requests.Load(),
  85. Leaks: rt.leaks.Load(),
  86. LastLeaks: append([]string{}, rt.lastLeak...),
  87. }
  88. }
  89. // Manager serves and manages the published container apps
  90. type Manager struct {
  91. opts Options
  92. mu sync.RWMutex
  93. bySlug map[string]*endpointRuntime
  94. byHost map[string]*endpointRuntime
  95. transport *http.Transport
  96. insecureTransport *http.Transport
  97. sessions *sessionStore
  98. }
  99. // NewManager loads the saved endpoints and returns a ready manager
  100. func NewManager(opts Options) (*Manager, error) {
  101. if opts.Store == nil {
  102. return nil, errors.New("appproxy: a store is required")
  103. }
  104. if opts.Log == nil {
  105. opts.Log = func(string, error) {}
  106. }
  107. if opts.ResolveUser == nil {
  108. opts.ResolveUser = func(http.ResponseWriter, *http.Request) *Identity { return nil }
  109. }
  110. if opts.LookupUser == nil {
  111. opts.LookupUser = func(string) *Identity { return nil }
  112. }
  113. if opts.LoginURL == nil {
  114. opts.LoginURL = func(string) string { return "/login.html" }
  115. }
  116. if err := opts.Store.NewTable(tableName); err != nil {
  117. return nil, err
  118. }
  119. m := &Manager{
  120. opts: opts,
  121. bySlug: map[string]*endpointRuntime{},
  122. byHost: map[string]*endpointRuntime{},
  123. transport: newTransport(false),
  124. insecureTransport: newTransport(true),
  125. sessions: newSessionStore(),
  126. }
  127. rows, err := opts.Store.ListTable(tableName)
  128. if err != nil {
  129. return nil, err
  130. }
  131. for _, row := range rows {
  132. if len(row) != 2 {
  133. continue
  134. }
  135. ep := Endpoint{}
  136. if err := json.Unmarshal(row[1], &ep); err != nil {
  137. opts.Log("Skipping unreadable endpoint "+string(row[0]), err)
  138. continue
  139. }
  140. m.install(&ep)
  141. }
  142. return m, nil
  143. }
  144. func newTransport(skipVerify bool) *http.Transport {
  145. t := &http.Transport{
  146. Proxy: nil,
  147. DialContext: (&net.Dialer{
  148. Timeout: 10 * time.Second,
  149. KeepAlive: 30 * time.Second,
  150. }).DialContext,
  151. MaxIdleConns: 100,
  152. MaxIdleConnsPerHost: 16,
  153. IdleConnTimeout: 90 * time.Second,
  154. TLSHandshakeTimeout: 10 * time.Second,
  155. ExpectContinueTimeout: 1 * time.Second,
  156. }
  157. if skipVerify {
  158. t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  159. }
  160. return t
  161. }
  162. // install builds the runtime of an endpoint and indexes it (replacing an older one)
  163. func (m *Manager) install(ep *Endpoint) {
  164. rt := &endpointRuntime{ep: ep}
  165. rt.proxy = m.newReverseProxy(rt)
  166. m.mu.Lock()
  167. defer m.mu.Unlock()
  168. if old, ok := m.bySlug[ep.Slug]; ok {
  169. if old.ep.Hostname != "" {
  170. delete(m.byHost, old.ep.Hostname)
  171. }
  172. //Keep the counters across edits
  173. rt.requests.Store(old.requests.Load())
  174. rt.leaks.Store(old.leaks.Load())
  175. rt.lastLeak = old.stats().LastLeaks
  176. }
  177. m.bySlug[ep.Slug] = rt
  178. if ep.Mode == ModeSubdomain && ep.Hostname != "" {
  179. m.byHost[ep.Hostname] = rt
  180. }
  181. }
  182. func (m *Manager) runtimeBySlug(slug string) *endpointRuntime {
  183. m.mu.RLock()
  184. defer m.mu.RUnlock()
  185. return m.bySlug[slug]
  186. }
  187. func (m *Manager) runtimeByHost(host string) *endpointRuntime {
  188. m.mu.RLock()
  189. defer m.mu.RUnlock()
  190. if len(m.byHost) == 0 {
  191. return nil
  192. }
  193. return m.byHost[NormalizeHostname(host)]
  194. }
  195. // List returns a copy of every endpoint, sorted by name
  196. func (m *Manager) List() []Endpoint {
  197. m.mu.RLock()
  198. results := make([]Endpoint, 0, len(m.bySlug))
  199. for _, rt := range m.bySlug {
  200. results = append(results, *rt.ep)
  201. }
  202. m.mu.RUnlock()
  203. sort.Slice(results, func(i, j int) bool {
  204. if results[i].Name == results[j].Name {
  205. return results[i].Slug < results[j].Slug
  206. }
  207. return results[i].Name < results[j].Name
  208. })
  209. return results
  210. }
  211. // Get returns a copy of one endpoint
  212. func (m *Manager) Get(slug string) (Endpoint, bool) {
  213. rt := m.runtimeBySlug(slug)
  214. if rt == nil {
  215. return Endpoint{}, false
  216. }
  217. return *rt.ep, true
  218. }
  219. // Stats returns the runtime counters of one endpoint
  220. func (m *Manager) Stats(slug string) Stats {
  221. rt := m.runtimeBySlug(slug)
  222. if rt == nil {
  223. return Stats{}
  224. }
  225. return rt.stats()
  226. }
  227. // Count returns the number of published endpoints
  228. func (m *Manager) Count() int {
  229. m.mu.RLock()
  230. defer m.mu.RUnlock()
  231. return len(m.bySlug)
  232. }
  233. // Save creates (create=true) or updates an endpoint after validating it.
  234. // currentHost is the ArozOS host the admin is using, which an app hostname
  235. // must never take over
  236. func (m *Manager) Save(ep Endpoint, create bool, username string, currentHost string) (Endpoint, error) {
  237. if err := ep.Normalize(m.opts.SelfPort); err != nil {
  238. return Endpoint{}, err
  239. }
  240. if ep.Mode == ModeSubdomain && currentHost != "" && NormalizeHostname(currentHost) == ep.Hostname {
  241. return Endpoint{}, errors.New("The app hostname must differ from the ArozOS hostname")
  242. }
  243. m.mu.RLock()
  244. existing, exists := m.bySlug[ep.Slug]
  245. var hostOwner *endpointRuntime
  246. if ep.Hostname != "" {
  247. hostOwner = m.byHost[ep.Hostname]
  248. }
  249. m.mu.RUnlock()
  250. if create && exists {
  251. return Endpoint{}, errors.New("Slug already in use")
  252. }
  253. if !create && !exists {
  254. return Endpoint{}, errors.New("App not found")
  255. }
  256. if hostOwner != nil && hostOwner.ep.Slug != ep.Slug {
  257. return Endpoint{}, errors.New("Hostname already used by " + hostOwner.ep.Name)
  258. }
  259. now := time.Now().Unix()
  260. if create {
  261. ep.CreatedBy = username
  262. ep.CreatedAt = now
  263. } else {
  264. ep.CreatedBy = existing.ep.CreatedBy
  265. ep.CreatedAt = existing.ep.CreatedAt
  266. }
  267. ep.UpdatedAt = now
  268. if err := m.opts.Store.Write(tableName, ep.Slug, ep); err != nil {
  269. return Endpoint{}, err
  270. }
  271. saved := ep
  272. m.install(&saved)
  273. if !create {
  274. //Access rules or the hostname may have changed
  275. m.sessions.dropEndpoint(ep.Slug)
  276. }
  277. return saved, nil
  278. }
  279. // Delete removes an endpoint
  280. func (m *Manager) Delete(slug string) error {
  281. m.mu.Lock()
  282. rt, ok := m.bySlug[slug]
  283. if ok {
  284. delete(m.bySlug, slug)
  285. if rt.ep.Hostname != "" {
  286. delete(m.byHost, rt.ep.Hostname)
  287. }
  288. }
  289. m.mu.Unlock()
  290. if !ok {
  291. return errors.New("App not found")
  292. }
  293. m.sessions.dropEndpoint(slug)
  294. return m.opts.Store.Delete(tableName, slug)
  295. }
  296. // AccessibleBy returns the endpoints a user may open
  297. func (m *Manager) AccessibleBy(id *Identity) []Endpoint {
  298. results := []Endpoint{}
  299. for _, ep := range m.List() {
  300. if ep.CanAccess(id) {
  301. results = append(results, ep)
  302. }
  303. }
  304. return results
  305. }