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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package sessions
import (
"context"
"encoding/base64"
"errors"
"net/http"
"net/url"
"strings"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/oidc"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
"golang.org/x/oauth2"
)
type Service struct {
cfg *oidc.OpenID
http *http.Client
}
func NewService(cfg *oidc.OpenID, http *http.Client) *Service {
return &Service{
cfg: cfg,
http: http,
}
}
func (svc *Service) GenerateRedirectURL(r *http.Request) (string, string) {
nonce := pls.GenerateRandomHex(32)
url := svc.cfg.Config.AuthCodeURL(
nonce,
oauth2.SetAuthURLParam("audience", svc.cfg.Config.ClientID),
oauth2.SetAuthURLParam("redirect_uri", svc.redirectURIFor(r)),
)
return url, nonce
}
func (svc *Service) Exchange(r *http.Request) (*oidc.Tokens, error) {
cookies := r.CookiesNamed(cfg.CSRFCookie)
if len(cookies) != 1 {
return nil, errors.New("Missing CSRF token")
}
state := r.URL.Query().Get("state")
if state != cookies[0].Value {
return nil, errors.New("Invalid CSRF token")
}
ctx := context.WithValue(r.Context(), oauth2.HTTPClient, svc.http)
token, err := svc.cfg.Config.Exchange(ctx, r.URL.Query().Get("code"))
if err != nil {
return nil, err
}
tokens := &oidc.Tokens{Token: token}
if rawIDToken, ok := token.Extra("id_token").(string); ok {
tokens.IDToken = oidc.RawToken(rawIDToken)
}
return tokens, nil
}
func (svc *Service) JWTBody(ctx context.Context, raw oidc.RawToken) ([]byte, error) {
sections := strings.SplitN(raw.String(), ".", 3)
if len(sections) != 3 {
return nil, errors.New("Invalid JWT")
}
return base64.RawURLEncoding.DecodeString(sections[1])
}
func (svc *Service) redirectURIFor(r *http.Request) string {
if len(svc.cfg.Config.RedirectURL) > 0 {
return svc.cfg.Config.RedirectURL
}
redirectURL, _ := url.Parse(r.URL.String())
redirectURL.Path = "/session/callback"
return redirectURL.String()
}
|