summaryrefslogtreecommitdiff
path: root/app/middleware/id_token.go
blob: a32c77bdacdfe66dfd6a7ca955a7e12fe4648f0a (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
package middleware

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"
)

type TokenParser func(*http.Request) oidc.RawToken

func IDTokenFromSessionCookie(r *http.Request) oidc.RawToken {
	cookies := r.CookiesNamed("session")

	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
}

func IDToken(cfg *oidc.OpenID) func(http.Handler) http.Handler {
	parsers := []TokenParser{IDTokenFromSessionCookie}

	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.String())
					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
					}
				}
			}

			next.ServeHTTP(w, r)
		})
	}
}