summaryrefslogtreecommitdiff
path: root/cmd/gtwy/main.go
blob: 8d1baa6fa205e343714292e7dea2c10a69fc2540 (plain)
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
package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"strings"

	"github.com/casbin/casbin/v2"
	"github.com/xlgmokha/x/pkg/env"
	"github.com/xlgmokha/x/pkg/x"
	"gitlab.com/mokhax/spike/pkg/srv"
)

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()
	mux.Handle("/", NewRouter(map[string]string{
		"idp.example.com": "localhost:8282",
		"ui.example.com":  "localhost:8283",
		"api.example.com": "localhost:8284",
	}))

	log.Fatal(srv.Run(srv.NewConfig(
		env.Fetch("BIND_ADDR", ":8080"),
		srv.WithMux(mux),
	)))
}