summaryrefslogtreecommitdiff
path: root/pkg
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-03-15 15:20:53 -0600
committermo khan <mo@mokhan.ca>2025-03-15 15:20:53 -0600
commitb27894fcfee8a8422ca191ccd87f641eb8befcf0 (patch)
tree503b19478f05ca2433082a3c9838e0c6ae401772 /pkg
parent80f1b83544b3482cbcdab8cdf521a92f2afdfa16 (diff)
refactor: authorize unsigned JWT in requests
Diffstat (limited to 'pkg')
-rw-r--r--pkg/app/app.go44
-rw-r--r--pkg/app/routes.go17
-rw-r--r--pkg/authz/token.go30
3 files changed, 91 insertions, 0 deletions
diff --git a/pkg/app/app.go b/pkg/app/app.go
new file mode 100644
index 00000000..fd6a3f11
--- /dev/null
+++ b/pkg/app/app.go
@@ -0,0 +1,44 @@
+package app
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+
+ "github.com/casbin/casbin/v3"
+ "github.com/xlgmokha/x/pkg/x"
+ "gitlab.com/mokhax/spike/pkg/authz"
+ "gitlab.com/mokhax/spike/pkg/cfg"
+ "gitlab.com/mokhax/spike/pkg/srv"
+)
+
+func WithCasbin() authz.Authorizer {
+ enforcer := x.Must(casbin.NewEnforcer("model.conf", "policy.csv"))
+
+ return authz.AuthorizerFunc(func(r *http.Request) bool {
+ host, _, err := net.SplitHostPort(r.Host)
+ if err != nil {
+ return false
+ }
+
+ subject, found := authz.TokenFrom(r).Subject()
+ if !found {
+ subject = "*"
+ }
+ ok, err := enforcer.Enforce(subject, host, r.Method, r.URL.Path)
+ if err != nil {
+ fmt.Printf("%v\n", err)
+ return false
+ }
+
+ fmt.Printf("%v: %v -> %v %v%v\n", ok, subject, r.Method, host, r.URL.Path)
+ return ok
+ })
+}
+
+func Start(bindAddr string) error {
+ return srv.Run(cfg.New(
+ bindAddr,
+ cfg.WithMux(authz.HTTP(WithCasbin(), Routes())),
+ ))
+}
diff --git a/pkg/app/routes.go b/pkg/app/routes.go
new file mode 100644
index 00000000..9cfa979b
--- /dev/null
+++ b/pkg/app/routes.go
@@ -0,0 +1,17 @@
+package app
+
+import (
+ "net/http"
+
+ "gitlab.com/mokhax/spike/pkg/prxy"
+)
+
+func Routes() http.Handler {
+ mux := http.NewServeMux()
+ mux.Handle("/", prxy.New(map[string]string{
+ "idp.example.com": "http://localhost:8282",
+ "ui.example.com": "http://localhost:8283",
+ "api.example.com": "http://localhost:8284",
+ }))
+ return mux
+}
diff --git a/pkg/authz/token.go b/pkg/authz/token.go
new file mode 100644
index 00000000..1822a217
--- /dev/null
+++ b/pkg/authz/token.go
@@ -0,0 +1,30 @@
+package authz
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/lestrrat-go/jwx/v3/jwt"
+)
+
+func TokenFrom(r *http.Request) jwt.Token {
+ authorization := r.Header.Get("Authorization")
+ if authorization == "" || !strings.Contains(authorization, "Bearer") {
+ return jwt.New()
+ }
+
+ token, err := jwt.ParseRequest(r,
+ jwt.WithContext(r.Context()),
+ jwt.WithHeaderKey("Authorization"),
+ jwt.WithValidate(false), // TODO:: Connect this to a JSON Web Key Set
+ jwt.WithVerify(false), // TODO:: Connect this to a JSON Web Key Set
+ )
+
+ if err != nil {
+ fmt.Printf("error: %v\n", err)
+ return jwt.New()
+ }
+
+ return token
+}