typedef.go 8.8 KB

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