handler.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "math"
  6. "net/http"
  7. "net/http/httputil"
  8. )
  9. func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
  10. return func(w http.ResponseWriter, r *http.Request) {
  11. //put the request inside our structure
  12. ProxyFlow.request = r
  13. probs := Classifier.Posterior(formatRequest(r))
  14. log.Printf("Posterior Probabilities: %+v\n", probs)
  15. action := quadrant(probs)
  16. ControPlane.StatsTokens <- action
  17. switch action {
  18. case "BLOCK":
  19. w.Header().Set("Probabilities", fmt.Sprintf("%v", probs))
  20. w.WriteHeader(403)
  21. w.Header().Set("Content-Encoding", "none")
  22. fmt.Fprintf(w, fmt.Sprintf("%s", BlockMessage))
  23. log.Println("Request Blocked")
  24. case "BLOCKLEARN":
  25. p.ModifyResponse = classifierDecide
  26. w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
  27. w.WriteHeader(403)
  28. log.Println("Still Ingesting prediction")
  29. p.ServeHTTP(w, r)
  30. case "PASS":
  31. w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
  32. p.ServeHTTP(w, r)
  33. log.Println("Passing Request")
  34. case "PASSLEARN":
  35. p.ModifyResponse = classifierDecide
  36. w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
  37. p.ServeHTTP(w, r)
  38. log.Println("Passing Request and ingesting")
  39. default:
  40. log.Println("No Decision: PASS and LEARN")
  41. p.ModifyResponse = classifierDecide
  42. w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
  43. p.ServeHTTP(w, r)
  44. }
  45. }
  46. }
  47. func quadrant(p map[string]float64) string {
  48. sure := math.Abs(p["BAD"]-p["GOOD"]) >= ProxyFlow.sensitivity
  49. badish := p["BAD"] > p["GOOD"]
  50. goodish := p["GOOD"] > p["BAD"]
  51. if ProxyFlow.seniority < Maturity {
  52. log.Println("Seniority too low. Waiting.")
  53. return "MEH"
  54. }
  55. if sure {
  56. if goodish {
  57. return "PASS"
  58. }
  59. if badish {
  60. return "BLOCK"
  61. }
  62. } else {
  63. if goodish {
  64. return "PASSLEARN"
  65. }
  66. if badish {
  67. return "BLOCKLEARN"
  68. }
  69. }
  70. return "MEH"
  71. }