1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"strings"
"time"
"github.com/casbin/casbin/v2"
"github.com/xlgmokha/x/pkg/env"
"github.com/xlgmokha/x/pkg/x"
)
func NewRouter(routes map[string]string) http.Handler {
authz := x.Must(casbin.NewEnforcer("model.conf", "policy.csv"))
return &httputil.ReverseProxy{
Director: func(r *http.Request) {
segments := strings.SplitN(r.Host, ":", 2)
host := segments[0]
destinationHost := routes[host]
log.Printf("%v (from: %v to: %v)\n", r.URL, host, destinationHost)
subject := "71cbc18e-bd41-4229-9ad2-749546a2a4a7" // TODO:: unpack sub claim in JWT
if x.Must(authz.Enforce(subject, host, r.Method, r.URL.Path)) {
r.URL.Scheme = "http" // TODO:: use TLS
r.Host = destinationHost
r.URL.Host = destinationHost
} else {
log.Println("UNAUTHORIZED") // TODO:: Return forbidden, unauthorized or not found status code
}
},
Transport: http.DefaultTransport,
FlushInterval: -1,
ErrorLog: nil,
ModifyResponse: func(r *http.Response) error {
r.Header.Add("Via", fmt.Sprintf("%v gtwy", r.Proto))
return nil
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Println(err)
},
}
}
func main() {
mux := http.NewServeMux()
routes := map[string]string{
"idp.example.com": "localhost:8282",
"ui.example.com": "localhost:8283",
"api.example.com": "localhost:8284",
}
mux.Handle("/", NewRouter(routes))
bindAddress := env.Fetch("BIND_ADDR", ":8080")
log.Fatal((&http.Server{
Addr: bindAddress,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 2 * time.Minute,
IdleTimeout: 5 * time.Minute,
ErrorLog: log.Default(),
}).ListenAndServe())
}
|