zrok/endpoints/publicProxy/google.go

155 lines
4.6 KiB
Go
Raw Normal View History

2023-09-05 16:55:55 +02:00
package publicProxy
import (
"crypto/md5"
2023-09-05 16:55:55 +02:00
"encoding/json"
"errors"
2023-09-05 16:55:55 +02:00
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/zitadel/oidc/v2/pkg/client/rp"
zhttp "github.com/zitadel/oidc/v2/pkg/http"
"github.com/zitadel/oidc/v2/pkg/oidc"
"golang.org/x/oauth2"
googleOauth "golang.org/x/oauth2/google"
2023-10-05 19:34:27 +02:00
"io"
"net/http"
"net/url"
"time"
2023-09-05 16:55:55 +02:00
)
func configureGoogleOauth(cfg *OauthConfig, tls bool) error {
scheme := "http"
if tls {
scheme = "https"
}
providerCfg := cfg.GetProvider("google")
if providerCfg == nil {
logrus.Info("unable to find provider config for google. Skipping.")
return nil
}
clientID := providerCfg.ClientId
rpConfig := &oauth2.Config{
ClientID: clientID,
ClientSecret: providerCfg.ClientSecret,
RedirectURL: fmt.Sprintf("%v/google/oauth", cfg.RedirectUrl),
2023-09-05 16:55:55 +02:00
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
Endpoint: googleOauth.Endpoint,
}
hash := md5.New()
2023-10-05 19:34:27 +02:00
n, err := hash.Write([]byte(cfg.HashKey))
if err != nil {
return err
}
2023-10-05 19:34:27 +02:00
if n != len(cfg.HashKey) {
return errors.New("short hash")
}
key := hash.Sum(nil)
2023-09-05 16:55:55 +02:00
cookieHandler := zhttp.NewCookieHandler(key, key, zhttp.WithUnsecure(), zhttp.WithDomain(cfg.CookieDomain))
2023-09-05 16:55:55 +02:00
options := []rp.Option{
rp.WithCookieHandler(cookieHandler),
rp.WithVerifierOpts(rp.WithIssuedAtOffset(5 * time.Second)),
rp.WithPKCE(cookieHandler),
}
relyingParty, err := rp.NewRelyingPartyOAuth(rpConfig, options...)
if err != nil {
return err
}
type IntermediateJWT struct {
2023-09-05 18:50:41 +02:00
State string `json:"state"`
Host string `json:"host"`
2023-09-05 18:50:41 +02:00
AuthorizationCheckInterval string `json:"authorizationCheckInterval"`
2023-09-05 16:55:55 +02:00
jwt.RegisteredClaims
}
type googleOauthEmailResp struct {
Email string
}
authHandlerWithQueryState := func(party rp.RelyingParty) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
host, err := url.QueryUnescape(r.URL.Query().Get("targethost"))
if err != nil {
2023-12-15 18:15:40 +01:00
logrus.Errorf("unable to unescape target host: %v", err)
}
2023-09-05 16:55:55 +02:00
rp.AuthURLHandler(func() string {
id := uuid.New().String()
t := jwt.NewWithClaims(jwt.SigningMethodHS256, IntermediateJWT{
id,
host,
2023-09-05 18:50:41 +02:00
r.URL.Query().Get("checkInterval"),
2023-09-05 16:55:55 +02:00
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "zrok",
Subject: "intermediate_token",
ID: id,
},
})
s, err := t.SignedString(key)
if err != nil {
2023-12-15 18:15:40 +01:00
logrus.Errorf("unable to sign intermediate JWT: %v", err)
2023-09-05 16:55:55 +02:00
}
return s
}, party, rp.WithURLParam("access_type", "offline"))(w, r)
}
}
http.Handle("/google/login", authHandlerWithQueryState(relyingParty))
getEmail := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[*oidc.IDTokenClaims], state string, rp rp.RelyingParty) {
resp, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + url.QueryEscape(tokens.AccessToken))
if err != nil {
2023-12-15 18:15:40 +01:00
logrus.Errorf("error getting user info from google: %v", err)
2023-09-05 16:55:55 +02:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-10-05 19:34:27 +02:00
defer func() {
_ = resp.Body.Close()
}()
2023-09-05 16:55:55 +02:00
response, err := io.ReadAll(resp.Body)
if err != nil {
2023-12-15 18:15:40 +01:00
logrus.Errorf("error reading response body: %v", err)
2023-09-05 16:55:55 +02:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-12-15 18:15:40 +01:00
logrus.Infof("response from google userinfo endpoint: %s", string(response))
2023-09-05 16:55:55 +02:00
rDat := googleOauthEmailResp{}
err = json.Unmarshal(response, &rDat)
if err != nil {
2023-12-15 18:15:40 +01:00
logrus.Errorf("error unmarshalling google oauth response: %v", err)
2023-09-05 16:55:55 +02:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
token, err := jwt.ParseWithClaims(state, &IntermediateJWT{}, func(t *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
http.Error(w, fmt.Sprintf("After intermediate token parse: %v", err.Error()), http.StatusInternalServerError)
return
}
2023-09-05 18:50:41 +02:00
authCheckInterval := 3 * time.Hour
i, err := time.ParseDuration(token.Claims.(*IntermediateJWT).AuthorizationCheckInterval)
if err != nil {
logrus.Errorf("unable to parse authorization check interval: %v. Defaulting to 3 hours", err)
} else {
authCheckInterval = i
}
SetZrokCookie(w, cfg.CookieDomain, rDat.Email, tokens.AccessToken, "google", authCheckInterval, key, token.Claims.(*IntermediateJWT).Host)
http.Redirect(w, r, fmt.Sprintf("%s://%s", scheme, token.Claims.(*IntermediateJWT).Host), http.StatusFound)
2023-09-05 16:55:55 +02:00
}
http.Handle("/google/oauth", rp.CodeExchangeHandler(getEmail, relyingParty))
2023-09-05 16:55:55 +02:00
return nil
}