endpoint.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package appproxy
  2. import (
  3. "errors"
  4. "net"
  5. "net/url"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. )
  10. /*
  11. endpoint.go
  12. The Endpoint record an administrator publishes, and its validation.
  13. An endpoint maps a slug to a web server reachable from this host (usually
  14. a Docker container's published port) and is served in one of two modes:
  15. - path mode: https://<arozos host>/app/<slug>/ (same origin as the
  16. desktop, so it requires the "trusted" flag)
  17. - subdomain mode: https://<hostname>/ (its own origin)
  18. The canonical entry point is always /app/<slug>/ on the ArozOS host; in
  19. subdomain mode it hands the login over and redirects to the hostname, so a
  20. desktop shortcut keeps working when an admin switches the mode.
  21. */
  22. const (
  23. ModePath = "path"
  24. ModeSubdomain = "subdomain"
  25. OpenInFloat = "float"
  26. OpenInTab = "tab"
  27. minWindowSize = 100
  28. maxWindowSize = 10000
  29. )
  30. // Endpoint is one published container web app
  31. type Endpoint struct {
  32. Slug string //URL-safe id, used in /app/<slug>/ and never changed after creation
  33. Name string //Display name
  34. Icon string //Icon web path or URL
  35. Container string //Docker container name it was published from, informational
  36. Image string //Docker image, used by the probe for known-app hints
  37. Target string //host:port of the upstream web server
  38. TargetTLS bool //Upstream speaks https
  39. SkipTLSVerify bool //Accept self-signed upstream certificates
  40. Mode string //ModePath or ModeSubdomain
  41. Hostname string //Subdomain mode: the host name this app answers on
  42. PortalOrigin string //Subdomain mode: origin of the ArozOS desktop, for the login hand-off
  43. Trusted bool //Admin trusts this container to share the desktop's origin (required for path mode)
  44. RootRedirect bool //Path mode: redirect root requests made from the app back under /app/<slug>/
  45. RewriteRoot bool //Path mode: rewrite root paths in HTML / CSS and inject the rewrite script
  46. AllowFraming bool //Strip X-Frame-Options / frame-ancestors so it opens in a desktop window
  47. RequireLogin bool //Only logged in ArozOS users may open it
  48. AllowedGroups []string //Permission groups allowed to open it, empty = every user
  49. OpenIn string //OpenInFloat or OpenInTab
  50. Width int //Initial float window width, 0 = default
  51. Height int //Initial float window height, 0 = default
  52. CreatedBy string
  53. CreatedAt int64
  54. UpdatedAt int64
  55. }
  56. var (
  57. slugRegex = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
  58. hostnameRegex = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$`)
  59. )
  60. // NormalizeSlug turns a free text name (e.g. a container name) into a valid slug
  61. func NormalizeSlug(name string) string {
  62. name = strings.ToLower(strings.TrimSpace(name))
  63. var b strings.Builder
  64. lastDash := true
  65. for _, c := range name {
  66. if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') {
  67. b.WriteRune(c)
  68. lastDash = false
  69. } else if !lastDash {
  70. b.WriteRune('-')
  71. lastDash = true
  72. }
  73. }
  74. slug := strings.Trim(b.String(), "-")
  75. if len(slug) > 63 {
  76. slug = strings.Trim(slug[:63], "-")
  77. }
  78. return slug
  79. }
  80. // ValidSlug reports whether s can be used as an endpoint slug
  81. func ValidSlug(s string) bool {
  82. return slugRegex.MatchString(s)
  83. }
  84. // NormalizeHostname lower-cases a host name and drops any port
  85. func NormalizeHostname(host string) string {
  86. host = strings.ToLower(strings.TrimSpace(host))
  87. if h, _, err := net.SplitHostPort(host); err == nil {
  88. host = h
  89. }
  90. return strings.TrimSuffix(host, ".")
  91. }
  92. // normalizeWindowSize clamps a float window dimension, 0 means default
  93. func normalizeWindowSize(v int) int {
  94. if v <= 0 {
  95. return 0
  96. }
  97. if v < minWindowSize {
  98. return minWindowSize
  99. }
  100. if v > maxWindowSize {
  101. return maxWindowSize
  102. }
  103. return v
  104. }
  105. // validateTarget checks a host:port upstream address
  106. func validateTarget(target string) error {
  107. host, port, err := net.SplitHostPort(target)
  108. if err != nil {
  109. return errors.New("Target must be host:port, e.g. 127.0.0.1:8081")
  110. }
  111. if host == "" || strings.ContainsAny(host, "/?#@ ") {
  112. return errors.New("Invalid target host")
  113. }
  114. p, err := strconv.Atoi(port)
  115. if err != nil || p < 1 || p > 65535 {
  116. return errors.New("Invalid target port")
  117. }
  118. return nil
  119. }
  120. // isLoopbackHost reports whether host points back at this machine
  121. func isLoopbackHost(host string) bool {
  122. host = strings.ToLower(host)
  123. if host == "localhost" || host == "0.0.0.0" || host == "::" {
  124. return true
  125. }
  126. ip := net.ParseIP(host)
  127. return ip != nil && ip.IsLoopback()
  128. }
  129. // validateOrigin checks a scheme://host[:port] origin without a path
  130. func validateOrigin(origin string) error {
  131. u, err := url.Parse(origin)
  132. if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
  133. return errors.New("Portal origin must look like https://nas.example.com")
  134. }
  135. if (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
  136. return errors.New("Portal origin must not contain a path")
  137. }
  138. return nil
  139. }
  140. // Normalize fills defaults and validates the endpoint. selfPort is the port
  141. // ArozOS itself listens on (a loopback target on it would proxy into itself)
  142. func (e *Endpoint) Normalize(selfPort int) error {
  143. e.Slug = strings.TrimSpace(e.Slug)
  144. if !ValidSlug(e.Slug) {
  145. return errors.New("Slug may only contain a-z, 0-9 and - (max 63 characters)")
  146. }
  147. e.Name = strings.TrimSpace(e.Name)
  148. if e.Name == "" {
  149. e.Name = e.Slug
  150. }
  151. if len(e.Name) > 64 {
  152. return errors.New("Name is too long")
  153. }
  154. e.Icon = strings.TrimSpace(e.Icon)
  155. if strings.ContainsAny(e.Icon, "\"'<>`\r\n") {
  156. return errors.New("Invalid icon path")
  157. }
  158. e.Container = strings.TrimSpace(e.Container)
  159. e.Image = strings.TrimSpace(e.Image)
  160. e.Target = strings.TrimSpace(e.Target)
  161. e.Target = strings.TrimPrefix(strings.TrimPrefix(e.Target, "http://"), "https://")
  162. e.Target = strings.TrimSuffix(e.Target, "/")
  163. if err := validateTarget(e.Target); err != nil {
  164. return err
  165. }
  166. if selfPort > 0 {
  167. host, port, _ := net.SplitHostPort(e.Target)
  168. if isLoopbackHost(host) && port == strconv.Itoa(selfPort) {
  169. return errors.New("Target cannot be ArozOS itself")
  170. }
  171. }
  172. switch e.Mode {
  173. case ModePath:
  174. if !e.Trusted {
  175. return errors.New("Path mode shares the desktop's origin and requires trusting this container. Use subdomain mode for untrusted containers")
  176. }
  177. e.Hostname = ""
  178. case ModeSubdomain:
  179. e.Hostname = NormalizeHostname(e.Hostname)
  180. if !hostnameRegex.MatchString(e.Hostname) {
  181. return errors.New("Invalid hostname for subdomain mode")
  182. }
  183. e.PortalOrigin = strings.TrimSuffix(strings.TrimSpace(e.PortalOrigin), "/")
  184. if err := validateOrigin(e.PortalOrigin); err != nil {
  185. return err
  186. }
  187. portal, _ := url.Parse(e.PortalOrigin)
  188. if NormalizeHostname(portal.Host) == e.Hostname {
  189. return errors.New("The app hostname must differ from the ArozOS hostname")
  190. }
  191. //Root path rewriting is a path mode feature
  192. e.RootRedirect = false
  193. e.RewriteRoot = false
  194. default:
  195. return errors.New("Mode must be path or subdomain")
  196. }
  197. if e.OpenIn != OpenInTab {
  198. e.OpenIn = OpenInFloat
  199. }
  200. e.Width = normalizeWindowSize(e.Width)
  201. e.Height = normalizeWindowSize(e.Height)
  202. groups := []string{}
  203. seen := map[string]bool{}
  204. for _, g := range e.AllowedGroups {
  205. g = strings.TrimSpace(g)
  206. if g == "" || seen[g] {
  207. continue
  208. }
  209. seen[g] = true
  210. groups = append(groups, g)
  211. }
  212. e.AllowedGroups = groups
  213. return nil
  214. }
  215. // PathPrefix is the path mode URL prefix of this endpoint, without a trailing slash
  216. func (e *Endpoint) PathPrefix() string {
  217. return "/app/" + e.Slug
  218. }
  219. // UpstreamURL is the base URL requests are forwarded to
  220. func (e *Endpoint) UpstreamURL() *url.URL {
  221. scheme := "http"
  222. if e.TargetTLS {
  223. scheme = "https"
  224. }
  225. return &url.URL{Scheme: scheme, Host: e.Target}
  226. }
  227. // CanAccess reports whether a user may open the endpoint. A nil identity is
  228. // an anonymous visitor
  229. func (e *Endpoint) CanAccess(id *Identity) bool {
  230. if !e.RequireLogin {
  231. return true
  232. }
  233. if id == nil {
  234. return false
  235. }
  236. if id.IsAdmin || len(e.AllowedGroups) == 0 {
  237. return true
  238. }
  239. for _, want := range e.AllowedGroups {
  240. for _, have := range id.Groups {
  241. if want == have {
  242. return true
  243. }
  244. }
  245. }
  246. return false
  247. }