From b27894fcfee8a8422ca191ccd87f641eb8befcf0 Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 15 Mar 2025 15:20:53 -0600 Subject: refactor: authorize unsigned JWT in requests --- pkg/app/app.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ pkg/app/routes.go | 17 +++++++++++++++++ pkg/authz/token.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 pkg/app/app.go create mode 100644 pkg/app/routes.go create mode 100644 pkg/authz/token.go (limited to 'pkg') 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 +} -- cgit v1.2.3