customHeader.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package dynamicproxy
  2. import (
  3. "strconv"
  4. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  5. )
  6. /*
  7. CustomHeader.go
  8. This script handle parsing and injecting custom headers
  9. into the dpcore routing logic
  10. */
  11. // SplitInboundOutboundHeaders split user defined headers into upstream and downstream headers
  12. // return upstream header and downstream header key-value pairs
  13. // if the header is expected to be deleted, the value will be set to empty string
  14. func (ept *ProxyEndpoint) SplitInboundOutboundHeaders() ([][]string, [][]string) {
  15. if len(ept.UserDefinedHeaders) == 0 && ept.HSTSMaxAge == 0 && !ept.EnablePermissionPolicyHeader {
  16. //Early return if there are no defined headers
  17. return [][]string{}, [][]string{}
  18. }
  19. //Use pre-allocation for faster performance
  20. //Downstream +2 for Permission Policy and HSTS
  21. upstreamHeaders := make([][]string, len(ept.UserDefinedHeaders))
  22. downstreamHeaders := make([][]string, len(ept.UserDefinedHeaders)+2)
  23. upstreamHeaderCounter := 0
  24. downstreamHeaderCounter := 0
  25. //Sort the headers into upstream or downstream
  26. for _, customHeader := range ept.UserDefinedHeaders {
  27. thisHeaderSet := make([]string, 2)
  28. thisHeaderSet[0] = customHeader.Key
  29. thisHeaderSet[1] = customHeader.Value
  30. if customHeader.IsRemove {
  31. //Prevent invalid config
  32. thisHeaderSet[1] = ""
  33. }
  34. //Assign to slice
  35. if customHeader.Direction == HeaderDirection_ZoraxyToUpstream {
  36. upstreamHeaders[upstreamHeaderCounter] = thisHeaderSet
  37. upstreamHeaderCounter++
  38. } else if customHeader.Direction == HeaderDirection_ZoraxyToDownstream {
  39. downstreamHeaders[downstreamHeaderCounter] = thisHeaderSet
  40. downstreamHeaderCounter++
  41. }
  42. }
  43. //Check if the endpoint require HSTS headers
  44. if ept.HSTSMaxAge > 0 {
  45. downstreamHeaders[downstreamHeaderCounter] = []string{"Strict-Transport-Security", "max-age=" + strconv.Itoa(int(ept.HSTSMaxAge))}
  46. downstreamHeaderCounter++
  47. }
  48. //Check if the endpoint require Permission Policy
  49. if ept.EnablePermissionPolicyHeader {
  50. var usingPermissionPolicy *permissionpolicy.PermissionsPolicy
  51. if ept.PermissionPolicy != nil {
  52. //Custom permission policy
  53. usingPermissionPolicy = ept.PermissionPolicy
  54. } else {
  55. //Permission policy is enabled but not customized. Use default
  56. usingPermissionPolicy = permissionpolicy.GetDefaultPermissionPolicy()
  57. }
  58. downstreamHeaders[downstreamHeaderCounter] = usingPermissionPolicy.ToKeyValueHeader()
  59. downstreamHeaderCounter++
  60. }
  61. return upstreamHeaders, downstreamHeaders
  62. }