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
|
package sessions
import (
"context"
"errors"
"fmt"
"net/http"
"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() (string, string) {
nonce := pls.GenerateRandomHex(32)
url := svc.cfg.Config.AuthCodeURL(
nonce,
oauth2.SetAuthURLParam("audience", svc.cfg.Config.ClientID),
)
return url, nonce
}
func (svc *Service) Exchange(r *http.Request) (*oidc.Tokens, error) {
cookies := r.CookiesNamed("oauth_state")
if len(cookies) != 1 {
return nil, errors.New(fmt.Sprintf("Missing CSRF token: %v, cookies: %v", len(cookies), r.Cookies()))
}
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
}
|