typedef.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package dynamicproxy
  2. /*
  3. typdef.go
  4. This script handle the type definition for dynamic proxy and endpoints
  5. If you are looking for the default object initailization, please refer to default.go
  6. */
  7. import (
  8. _ "embed"
  9. "net"
  10. "net/http"
  11. "sync"
  12. "imuslab.com/zoraxy/mod/access"
  13. "imuslab.com/zoraxy/mod/auth/sso/authelia"
  14. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  15. "imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
  16. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  17. "imuslab.com/zoraxy/mod/dynamicproxy/redirection"
  18. "imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
  19. "imuslab.com/zoraxy/mod/geodb"
  20. "imuslab.com/zoraxy/mod/info/logger"
  21. "imuslab.com/zoraxy/mod/statistic"
  22. "imuslab.com/zoraxy/mod/tlscert"
  23. )
  24. type ProxyType int
  25. const PassiveLoadBalanceNotifyTimeout = 60 //Time to assume a passive load balance is unreachable, in seconds
  26. const (
  27. ProxyTypeRoot ProxyType = iota //Root Proxy, everything not matching will be routed here
  28. ProxyTypeHost //Host Proxy, match by host (domain) name
  29. ProxyTypeVdir //Virtual Directory Proxy, match by path prefix
  30. )
  31. type ProxyHandler struct {
  32. Parent *Router
  33. }
  34. /* Router Object Options */
  35. type RouterOption struct {
  36. /* Basic Settings */
  37. HostUUID string //The UUID of Zoraxy, use for heading mod
  38. HostVersion string //The version of Zoraxy, use for heading mod
  39. Port int //Incoming port
  40. UseTls bool //Use TLS to serve incoming requsts
  41. ForceTLSLatest bool //Force TLS1.2 or above
  42. NoCache bool //Force set Cache-Control: no-store
  43. ListenOnPort80 bool //Enable port 80 http listener
  44. ForceHttpsRedirect bool //Force redirection of http to https endpoint
  45. /* Routing Service Managers */
  46. TlsManager *tlscert.Manager //TLS manager for serving SAN certificates
  47. RedirectRuleTable *redirection.RuleTable //Redirection rules handler and table
  48. GeodbStore *geodb.Store //GeoIP resolver
  49. AccessController *access.Controller //Blacklist / whitelist controller
  50. StatisticCollector *statistic.Collector //Statistic collector for storing stats on incoming visitors
  51. WebDirectory string //The static web server directory containing the templates folder
  52. LoadBalancer *loadbalance.RouteManager //Load balancer that handle load balancing of proxy target
  53. /* Authentication Providers */
  54. AutheliaRouter *authelia.AutheliaRouter //Authelia router for Authelia authentication
  55. /* Utilities */
  56. Logger *logger.Logger //Logger for reverse proxy requets
  57. }
  58. /* Router Object */
  59. type Router struct {
  60. Option *RouterOption
  61. ProxyEndpoints *sync.Map //Map of ProxyEndpoint objects, each ProxyEndpoint object is a routing rule that handle incoming requests
  62. Running bool //If the router is running
  63. Root *ProxyEndpoint //Root proxy endpoint, default site
  64. mux http.Handler //HTTP handler
  65. server *http.Server //HTTP server
  66. tlsListener net.Listener //TLS listener, handle SNI routing
  67. loadBalancer *loadbalance.RouteManager //Load balancer routing manager
  68. routingRules []*RoutingRule //Special routing rules, handle high priority routing like ACME request handling
  69. tlsRedirectStop chan bool //Stop channel for tls redirection server
  70. rateLimterStop chan bool //Stop channel for rate limiter
  71. rateLimitCounter RequestCountPerIpTable //Request counter for rate limter
  72. }
  73. /* Basic Auth Related Data structure*/
  74. // Auth credential for basic auth on certain endpoints
  75. type BasicAuthCredentials struct {
  76. Username string
  77. PasswordHash string
  78. }
  79. // Auth credential for basic auth on certain endpoints
  80. type BasicAuthUnhashedCredentials struct {
  81. Username string
  82. Password string
  83. }
  84. // Paths to exclude in basic auth enabled proxy handler
  85. type BasicAuthExceptionRule struct {
  86. PathPrefix string
  87. }
  88. /* Routing Rule Data Structures */
  89. // A Virtual Directory endpoint, provide a subset of ProxyEndpoint for better
  90. // program structure than directly using ProxyEndpoint
  91. type VirtualDirectoryEndpoint struct {
  92. MatchingPath string //Matching prefix of the request path, also act as key
  93. Domain string //Domain or IP to proxy to
  94. RequireTLS bool //Target domain require TLS
  95. SkipCertValidations bool //Set to true to accept self signed certs
  96. Disabled bool //If the rule is enabled
  97. proxy *dpcore.ReverseProxy `json:"-"`
  98. parent *ProxyEndpoint `json:"-"`
  99. }
  100. // Rules and settings for header rewriting
  101. type HeaderRewriteRules struct {
  102. UserDefinedHeaders []*rewrite.UserDefinedHeader //Custom headers to append when proxying requests from this endpoint
  103. RequestHostOverwrite string //If not empty, this domain will be used to overwrite the Host field in request header
  104. HSTSMaxAge int64 //HSTS max age, set to 0 for disable HSTS headers
  105. EnablePermissionPolicyHeader bool //Enable injection of permission policy header
  106. PermissionPolicy *permissionpolicy.PermissionsPolicy //Permission policy header
  107. DisableHopByHopHeaderRemoval bool //Do not remove hop-by-hop headers
  108. }
  109. /*
  110. Authentication Provider
  111. TODO: Move these into a dedicated module
  112. */
  113. type AuthMethod int
  114. const (
  115. AuthMethodNone AuthMethod = iota //No authentication required
  116. AuthMethodBasic //Basic Auth
  117. AuthMethodAuthelia //Authelia
  118. AuthMethodOauth2 //Oauth2
  119. )
  120. type AuthenticationProvider struct {
  121. AuthMethod AuthMethod //The authentication method to use
  122. /* Basic Auth Settings */
  123. BasicAuthCredentials []*BasicAuthCredentials //Basic auth credentials
  124. BasicAuthExceptionRules []*BasicAuthExceptionRule //Path to exclude in a basic auth enabled proxy target
  125. BasicAuthGroupIDs []string //Group IDs that are allowed to access this endpoint
  126. /* Authelia Settings */
  127. AutheliaURL string //URL of the Authelia server, leave empty to use global settings e.g. authelia.example.com
  128. UseHTTPS bool //Whether to use HTTPS for the Authelia server
  129. }
  130. // A proxy endpoint record, a general interface for handling inbound routing
  131. type ProxyEndpoint struct {
  132. ProxyType ProxyType //The type of this proxy, see const def
  133. RootOrMatchingDomain string //Matching domain for host, also act as key
  134. MatchingDomainAlias []string //A list of domains that alias to this rule
  135. ActiveOrigins []*loadbalance.Upstream //Activated Upstream or origin servers IP or domain to proxy to
  136. InactiveOrigins []*loadbalance.Upstream //Disabled Upstream or origin servers IP or domain to proxy to
  137. UseStickySession bool //Use stick session for load balancing
  138. UseActiveLoadBalance bool //Use active loadbalancing, default passive
  139. Disabled bool //If the rule is disabled
  140. //Inbound TLS/SSL Related
  141. BypassGlobalTLS bool //Bypass global TLS setting options if TLS Listener enabled (parent.tlsListener != nil)
  142. //Virtual Directories
  143. VirtualDirectories []*VirtualDirectoryEndpoint
  144. //Custom Headers
  145. HeaderRewriteRules *HeaderRewriteRules
  146. EnableWebsocketCustomHeaders bool //Enable custom headers for websocket connections as well (default only http reqiests)
  147. //Authentication
  148. AuthenticationProvider *AuthenticationProvider
  149. // Rate Limiting
  150. RequireRateLimit bool
  151. RateLimit int64 // Rate limit in requests per second
  152. //Uptime Monitor
  153. DisableUptimeMonitor bool //Disable uptime monitor for this endpoint
  154. //Access Control
  155. AccessFilterUUID string //Access filter ID
  156. //Fallback routing logic (Special Rule Sets Only)
  157. DefaultSiteOption int //Fallback routing logic options
  158. DefaultSiteValue string //Fallback routing target, optional
  159. //Internal Logic Elements
  160. parent *Router `json:"-"`
  161. Tags []string // Tags for the proxy endpoint
  162. }
  163. /*
  164. Routing type specific interface
  165. These are options that only avaible for a specific interface
  166. when running, these are converted into "ProxyEndpoint" objects
  167. for more generic routing logic
  168. */
  169. // Root options are those that are required for reverse proxy handler to work
  170. const (
  171. DefaultSite_InternalStaticWebServer = 0
  172. DefaultSite_ReverseProxy = 1
  173. DefaultSite_Redirect = 2
  174. DefaultSite_NotFoundPage = 3
  175. DefaultSite_NoResponse = 4
  176. DefaultSite_TeaPot = 418 //I'm a teapot
  177. )
  178. /*
  179. Web Templates
  180. */
  181. var (
  182. //go:embed templates/forbidden.html
  183. page_forbidden []byte
  184. //go:embed templates/hosterror.html
  185. page_hosterror []byte
  186. )