Skip to content

Commit

Permalink
feat: modify auth token url based on instance param
Browse files Browse the repository at this point in the history
If an instance parameter is provided in the redirect, use it to modify
the URL from where the oauth token is obtained.

The instance provided is the Snyk region domain, minus the api. host
prefix.
  • Loading branch information
cmars committed Oct 9, 2024
1 parent 5661185 commit 6788c04
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions pkg/auth/oauth2authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"math/big"
"net"
"net/http"
"net/url"
"regexp"
"sync"
"time"

Expand Down Expand Up @@ -287,6 +289,7 @@ func (o *oAuth2Authenticator) authenticateWithAuthorizationCode() error {
var responseCode string
var responseState string
var responseError string
var responseInstance string
verifier, err := createVerifier(128)
if err != nil {
return err
Expand Down Expand Up @@ -336,6 +339,7 @@ func (o *oAuth2Authenticator) authenticateWithAuthorizationCode() error {
appUrl := o.config.GetString(configuration.WEB_APP_URL)
responseCode = html.EscapeString(r.URL.Query().Get("code"))
responseState = html.EscapeString(r.URL.Query().Get("state"))
responseInstance = html.EscapeString(r.URL.Query().Get("instance"))
w.Header().Add("Location", appUrl+"/authenticated?type=oauth")
w.WriteHeader(http.StatusMovedPermanently)
}
Expand Down Expand Up @@ -388,6 +392,22 @@ func (o *oAuth2Authenticator) authenticateWithAuthorizationCode() error {
return fmt.Errorf("incorrect response state: %s != %s", responseState, state)
}

if responseInstance != "" {
authHost, err := redirectAuthHost(responseInstance)
if err != nil {
return fmt.Errorf("invalid instance: %q", responseInstance)
}
authURL, err := url.Parse(o.oauthConfig.Endpoint.AuthURL)
if err != nil {
return fmt.Errorf("failed to parse auth url: %w", err)
}
if !isValidAuthHost(authHost) {
return fmt.Errorf("invalid instance: %q", responseInstance)
}
authURL.Host = authHost
o.oauthConfig.Endpoint.AuthURL = authURL.String()
}

// Use the custom HTTP client when requesting a token.
if o.httpClient != nil {
ctx = context.WithValue(ctx, oauth2.HTTPClient, o.httpClient)
Expand All @@ -402,6 +422,17 @@ func (o *oAuth2Authenticator) authenticateWithAuthorizationCode() error {
return err
}

var redirectAuthHostRE = regexp.MustCompile(`^api\.(.+)\.snyk\.io$`)

func redirectAuthHost(instance string) (string, error) {
authHost := fmt.Sprintf("api.%s", instance)
return authHost, nil
}

func isValidAuthHost(authHost string) bool {
return redirectAuthHostRE.MatchString(authHost)
}

func (o *oAuth2Authenticator) AddAuthenticationHeader(request *http.Request) error {
if request == nil {
return fmt.Errorf("request must not be nil")
Expand Down

0 comments on commit 6788c04

Please sign in to comment.