summaryrefslogtreecommitdiff
path: root/pkg
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-04-17 14:43:01 -0600
committermo khan <mo@mokhan.ca>2025-04-17 14:43:01 -0600
commit1a1da99c2bde90bfd0cb78ddca5276deed10bdc5 (patch)
tree6da1e0eaa16e8e2d89ef29d6654bb953a2309e81 /pkg
parente3eeba19f090f38712b4720e2f928d503f0d92d2 (diff)
refactor: introduce api to parse id token from multiple locations
Diffstat (limited to 'pkg')
-rw-r--r--pkg/web/middleware/unpack_token.go64
1 files changed, 38 insertions, 26 deletions
diff --git a/pkg/web/middleware/unpack_token.go b/pkg/web/middleware/unpack_token.go
index db04e0e..d31f9cc 100644
--- a/pkg/web/middleware/unpack_token.go
+++ b/pkg/web/middleware/unpack_token.go
@@ -4,41 +4,53 @@ import (
"net/http"
"github.com/xlgmokha/x/pkg/log"
+ "github.com/xlgmokha/x/pkg/x"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/key"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/oidc"
)
-func UnpackToken(cfg *oidc.OpenID) func(http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- cookies := r.CookiesNamed("session")
+type TokenParser func(*http.Request) string
- if len(cookies) != 1 {
- next.ServeHTTP(w, r)
- return
- }
+func fromSessionCookie(r *http.Request) string {
+ cookies := r.CookiesNamed("session")
- tokens, err := oidc.TokensFromBase64String(cookies[0].Value)
- if err != nil {
- log.WithFields(ctx, log.Fields{"error": err})
- next.ServeHTTP(w, r)
- return
- }
+ if len(cookies) != 1 {
+ return ""
+ }
+
+ tokens, err := oidc.TokensFromBase64String(cookies[0].Value)
+ if err != nil {
+ log.WithFields(r.Context(), log.Fields{"error": err})
+ return ""
+ }
+
+ return tokens.IDToken
+}
- verifier := cfg.Provider.VerifierContext(ctx, cfg.OIDCConfig)
- idToken, err := verifier.Verify(ctx, tokens.IDToken)
- if err != nil {
- log.WithFields(ctx, log.Fields{"error": err})
- next.ServeHTTP(w, r)
- return
+func UnpackToken(cfg *oidc.OpenID) func(http.Handler) http.Handler {
+ parsers := []TokenParser{fromSessionCookie}
+
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ for _, parser := range parsers {
+ rawIDToken := parser(r)
+ if !x.IsZero(rawIDToken) {
+ verifier := cfg.Provider.VerifierContext(r.Context(), cfg.OIDCConfig)
+ idToken, err := verifier.Verify(r.Context(), rawIDToken)
+ if err != nil {
+ log.WithFields(r.Context(), log.Fields{"error": err})
+ } else {
+ log.WithFields(r.Context(), log.Fields{"id_token": idToken})
+ next.ServeHTTP(
+ w,
+ r.WithContext(key.IDToken.With(r.Context(), idToken)),
+ )
+ return
+ }
+ }
}
- log.WithFields(r.Context(), log.Fields{"id_token": idToken})
- next.ServeHTTP(
- w,
- r.WithContext(key.IDToken.With(r.Context(), idToken)),
- )
+ next.ServeHTTP(w, r)
})
}
}