mirror of
https://github.com/netbirdio/netbird.git
synced 2026-10-09 23:19:11 +02:00
* [client] Force interactive login when extending the auth session A session extend must be answered from the account the peer is registered under. With a silent PKCE flow (DisablePromptLogin or max_age=0) the IdP answers from whatever session it already holds, which need not be the peer's account when several are signed in; the token then fails the user match in ExtendAuthSession with no way to pick another account. Mark the PKCE flow request as a session extend so the management server can force prompt=login for it, overriding the configured silent flow. * [client] Reduce cognitive complexity of Server.Login Login sat at cognitive complexity 27, over the 25 the linter allows. Extract the interactive SSO branch into startSSOLogin, and split the nested in-flight-flow reuse check out of it into reuseOAuthFlow, which flattens the original if/else into early returns: it returns the cached auth info when the previous flow targets the same client and still has more than 90s left, otherwise cancels the stale wait and returns nil so the caller requests a fresh flow. The helpers take the contextState through a small statusSetter interface, since internal.contextState is unexported and re-deriving it with CtxGetState inside the helper would resolve against callerCtx rather than rootCtx. No behavior change: same ordering of state transitions, same mutex scope around the oauthAuthFlow write, same error paths. Login is now at 21. * [client] Respect DisablePromptLogin when extending the auth session Forcing prompt=login on a session extend overrode DisablePromptLogin, which is set for IdPs that break on it: Authentik triggers a double authentication and social logins fail outright. Overriding it there trades a recoverable extend for a login that cannot complete at all. Keep the LoginFlag override, which only replaces max_age=0 or none with prompt=login so the IdP honours login_hint, and leave DisablePromptLogin as configured. Those deployments keep the silent flow, and with several accounts signed in an extend answered from the wrong one still fails the user match. * [client] Guard the shared OAuth flow state with the server mutex reuseOAuthFlow read flow, expiresAt, waitCancel and info without holding s.mutex, while startSSOLogin and WaitSSOLogin write them under it. Reading the fields one at a time could also answer with auth info from a flow that was already replaced, or cancel a wait that no longer belongs to the flow just judged stale. Take one snapshot under the lock and decide from it. WaitSSOLogin read oauthAuthFlow.flow twice outside the lock; both now use a value snapshotted in the critical section that already installs actCancel. Its stale waitCancel was read and called in a separate section from the one installing the new one, so two racing calls could read the same predecessor and leave one wait uncancelled. Swap the two in a single critical section. Both cancels run after unlocking: the displaced wait takes s.mutex as it unwinds. * [client] Verify the SSO login came back for the hinted account login_hint is a suggestion the IdP may ignore: with a silent flow configured (DisablePromptLogin or max_age=0) and a live IdP session for another account, the login completes with that account's token. On a registered peer the management server rejects it as a user mismatch, but on a fresh profile the peer silently registers under the wrong account and the profile is then bound to it — every later login follows the stored hint straight back. After the token exchange, compare the ID token's email against the hint the flow was sent with. On a mismatch, do not log in to management with the token; run one more round asking the IdP to re-decide the account (prompt=login, via ForceAccountPrompt — DisablePromptLogin still wins there). If the prompted round also comes back different, proceed with a warning: the address may legitimately have changed, and refusing forever would lock the user out of the profile while the management server still rejects a token that does not own the peer. A token or profile with no email to compare is not judged. The retry differs per platform because of who opens the browser: - CLI (netbird login foreground) and Android run the whole flow in one process, so the mismatch retries automatically: the browser reopens with the account prompt within the same login attempt. - On desktop the login is split between the daemon and the GUI: Login hands the authorize URL to the GUI, WaitSSOLogin blocks for the token, and only the GUI can open a browser. A new URL cannot be handed out from inside WaitSSOLogin (its response has no field for one, kept that way to avoid a proto change), so the daemon arms forceAccountPrompt, fails the round with "connect again to choose the account", and builds the next Login's flow with the prompt — the user's next connect is the retry. The flag and the flow annotations live in daemon memory only; SwitchProfile drops them so the previous profile's hint cannot judge the next profile's token. The device code flow has no prompt parameter (RFC 8628), so a prompted round there runs as-is and a repeated mismatch is let through with the warning rather than looping. * [client] Address review comments on PKCE session extend flow Fail the PKCE authorization flow test on request error instead of continuing into a nil dereference, and make the godoc comments on the touched exported symbols identifier-leading full sentences. * [client] Match accounts only on the email claim of the ID token The name-claim fallback in the ID token parsing is kept for the login hint and display, but account matching now only considers a value that came from the email claim, so a token without one no longer produces a false account mismatch. * [client] Drop the pending session extend on a profile switch The profile-switch cleanup dropped the pending login flow and the account-prompt flag, but left extendAuthSessionFlow untouched. Its device code was issued by the previous profile's IdP client, so a WaitExtendAuthSession still parked on the browser leg would submit the resulting token against the new profile's engine. * [client] Judge the SSO account against the flow that produced the token WaitSSOLogin snapshotted the flow on entry but re-read the info, hint and accountPrompted from the live s.oauthAuthFlow afterwards, in separate critical sections. WaitToken blocks for the whole browser leg, so a concurrent Login or RequestJWTAuth could replace the flow meanwhile and the mismatch check would compare this wait's token against another flow's account: either arming the prompt spuriously or letting a wrong-account token through against an unrelated profile's hint. Take all of it in the entry snapshot. * [client] Keep the forced account prompt from being lost to flow reuse startSSOLogin consumed forceAccountPrompt and applied the prompt to the freshly built flow, but reuseOAuthFlow could then answer from a cached flow for the same client — one built without prompt=login, e.g. by RequestJWTAuth. The user got the same silent authorization URL that produced the mismatch, with the flag already spent, so no later round asked either. Rule reuse out when the prompt is forced, while still cancelling the predecessor's wait. RequestJWTAuth also wrote the flow fields one by one, leaving the previous login's hint and accountPrompted behind for WaitSSOLogin to judge a later token against. Both sites now replace the whole record. * [client] Consume the forced account prompt after the retry forceAccountPrompt was never cleared, so a flow that outlived the retry it was armed for kept sending prompt=login on every later authorization request and re-authenticated the user each time. RequestAuthInfo now takes the flag as it builds the request. * [client] Cancel the caller context in the SSO login tests WaitSSOLogin parks a goroutine on the caller's context for the whole browser leg. The tests passed context.Background(), which never cancels, so each left one goroutine behind for the lifetime of the test binary. * [client] Cancel the wait displaced by an OAuth flow replacement Replacing the shared record with a whole struct value dropped the previous flow's waitCancel, so an SSO browser wait still parked on it lost its cancel: nothing could preempt it, and it could go on to run attemptLogin or mutate the record behind the new flow. Both replacement sites now take the displaced cancel over in the same critical section, via a shared replaceOAuthFlow, and invoke it after the unlock. * [client] Guard OAuth flow mutations by the flow that owns the wait * [client] Arm the account prompt only from the wait that owns the flow * [client] Adopt the three-value parseEmailFromIDToken in the device flow The main merge brought in the device flow's email extraction from #7193, which still used the two-value signature this branch replaced when account matching was narrowed to the email claim. Git merged the files without a textual conflict, so the branch stopped compiling. Take the fromEmailClaim result and fill EmailClaim from it, the same way the PKCE path does, so device-flow clients get the same account matching. * [client] Populate the pending extend flow in the test server helper SwitchProfile cancels and clears the pending session extend flow unconditionally, the same way it clears the SSH JWT cache. New always populates the field, but the hand-assembled test server did not, so TestSwitchProfile_ClearsJWTCache panicked on a nil PendingFlow.
460 lines
14 KiB
Go
460 lines
14 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"crypto/tls"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"html/template"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
"golang.org/x/oauth2"
|
|
|
|
"github.com/netbirdio/netbird/client/internal/templates"
|
|
"github.com/netbirdio/netbird/shared/management/client/common"
|
|
)
|
|
|
|
var _ OAuthFlow = &PKCEAuthorizationFlow{}
|
|
|
|
const (
|
|
queryState = "state"
|
|
queryCode = "code"
|
|
queryError = "error"
|
|
queryErrorDesc = "error_description"
|
|
defaultPKCETimeoutSeconds = 300
|
|
)
|
|
|
|
// PKCEAuthProviderConfig has all attributes needed to initiate PKCE authorization flow
|
|
type PKCEAuthProviderConfig struct {
|
|
// ClientID An IDP application client id
|
|
ClientID string
|
|
// ClientSecret An IDP application client secret
|
|
ClientSecret string
|
|
// Audience An Audience for to authorization validation
|
|
Audience string
|
|
// TokenEndpoint is the endpoint of an IDP manager where clients can obtain access token
|
|
TokenEndpoint string
|
|
// AuthorizationEndpoint is the endpoint of an IDP manager where clients can obtain authorization code
|
|
AuthorizationEndpoint string
|
|
// Scopes provides the scopes to be included in the token request
|
|
Scope string
|
|
// RedirectURL handles authorization code from IDP manager
|
|
RedirectURLs []string
|
|
// UseIDToken indicates if the id token should be used for authentication
|
|
UseIDToken bool
|
|
// ClientCertPair is used for mTLS authentication to the IDP
|
|
ClientCertPair *tls.Certificate
|
|
// DisablePromptLogin makes the PKCE flow to not prompt the user for login
|
|
DisablePromptLogin bool
|
|
// LoginFlag is used to configure the PKCE flow login behavior
|
|
LoginFlag common.LoginFlag
|
|
// LoginHint is used to pre-fill the email/username field during authentication
|
|
LoginHint string
|
|
}
|
|
|
|
// validatePKCEConfig validates PKCE provider configuration
|
|
func validatePKCEConfig(config *PKCEAuthProviderConfig) error {
|
|
errorMsgFormat := "invalid provider configuration received from management: %s value is empty. Contact your NetBird administrator"
|
|
|
|
if config.ClientID == "" {
|
|
return fmt.Errorf(errorMsgFormat, "Client ID")
|
|
}
|
|
if config.TokenEndpoint == "" {
|
|
return fmt.Errorf(errorMsgFormat, "Token Endpoint")
|
|
}
|
|
if config.AuthorizationEndpoint == "" {
|
|
return fmt.Errorf(errorMsgFormat, "Authorization Auth Endpoint")
|
|
}
|
|
if config.Scope == "" {
|
|
return fmt.Errorf(errorMsgFormat, "PKCE Auth Scopes")
|
|
}
|
|
if config.RedirectURLs == nil {
|
|
return fmt.Errorf(errorMsgFormat, "PKCE Redirect URLs")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// PKCEAuthorizationFlow implements the OAuthFlow interface for
|
|
// the Authorization Code Flow with PKCE.
|
|
type PKCEAuthorizationFlow struct {
|
|
providerConfig PKCEAuthProviderConfig
|
|
state string
|
|
codeVerifier string
|
|
oAuthConfig *oauth2.Config
|
|
forceAccountPrompt bool
|
|
}
|
|
|
|
// NewPKCEAuthorizationFlow returns new PKCE authorization code flow.
|
|
func NewPKCEAuthorizationFlow(config PKCEAuthProviderConfig) (*PKCEAuthorizationFlow, error) {
|
|
var availableRedirectURL string
|
|
|
|
excludedRanges := getSystemExcludedPortRanges()
|
|
|
|
for _, redirectURL := range config.RedirectURLs {
|
|
if !isRedirectURLPortUsed(redirectURL, excludedRanges) {
|
|
availableRedirectURL = redirectURL
|
|
break
|
|
}
|
|
}
|
|
|
|
if availableRedirectURL == "" {
|
|
return nil, fmt.Errorf("no available port found from configured redirect URLs: %q", config.RedirectURLs)
|
|
}
|
|
|
|
cfg := &oauth2.Config{
|
|
ClientID: config.ClientID,
|
|
ClientSecret: config.ClientSecret,
|
|
Endpoint: oauth2.Endpoint{
|
|
AuthURL: config.AuthorizationEndpoint,
|
|
TokenURL: config.TokenEndpoint,
|
|
},
|
|
RedirectURL: availableRedirectURL,
|
|
Scopes: strings.Split(config.Scope, " "),
|
|
}
|
|
|
|
return &PKCEAuthorizationFlow{
|
|
providerConfig: config,
|
|
oAuthConfig: cfg,
|
|
}, nil
|
|
}
|
|
|
|
// GetClientID returns the provider client id
|
|
func (p *PKCEAuthorizationFlow) GetClientID(_ context.Context) string {
|
|
return p.providerConfig.ClientID
|
|
}
|
|
|
|
// RequestAuthInfo requests a authorization code login flow information.
|
|
func (p *PKCEAuthorizationFlow) RequestAuthInfo(ctx context.Context) (AuthFlowInfo, error) {
|
|
state, err := randomBytesInHex(24)
|
|
if err != nil {
|
|
return AuthFlowInfo{}, fmt.Errorf("could not generate random state: %v", err)
|
|
}
|
|
p.state = state
|
|
|
|
codeVerifier, err := randomBytesInHex(64)
|
|
if err != nil {
|
|
return AuthFlowInfo{}, fmt.Errorf("could not create a code verifier: %v", err)
|
|
}
|
|
p.codeVerifier = codeVerifier
|
|
|
|
codeChallenge := createCodeChallenge(codeVerifier)
|
|
|
|
params := []oauth2.AuthCodeOption{
|
|
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
|
|
oauth2.SetAuthURLParam("code_challenge", codeChallenge),
|
|
oauth2.SetAuthURLParam("audience", p.providerConfig.Audience),
|
|
}
|
|
forceAccountPrompt := p.forceAccountPrompt
|
|
p.forceAccountPrompt = false
|
|
|
|
if !p.providerConfig.DisablePromptLogin {
|
|
switch {
|
|
case forceAccountPrompt:
|
|
params = append(params, oauth2.SetAuthURLParam("prompt", "login"))
|
|
case p.providerConfig.LoginFlag == common.LoginFlagPromptLogin:
|
|
params = append(params, oauth2.SetAuthURLParam("prompt", "login"))
|
|
case p.providerConfig.LoginFlag == common.LoginFlagMaxAge0:
|
|
params = append(params, oauth2.SetAuthURLParam("max_age", "0"))
|
|
}
|
|
}
|
|
if p.providerConfig.LoginHint != "" {
|
|
params = append(params, oauth2.SetAuthURLParam("login_hint", p.providerConfig.LoginHint))
|
|
}
|
|
|
|
authURL := p.oAuthConfig.AuthCodeURL(state, params...)
|
|
|
|
return AuthFlowInfo{
|
|
VerificationURIComplete: authURL,
|
|
ExpiresIn: defaultPKCETimeoutSeconds,
|
|
}, nil
|
|
}
|
|
|
|
// SetLoginHint sets the login hint for the PKCE authorization flow
|
|
func (p *PKCEAuthorizationFlow) SetLoginHint(hint string) {
|
|
p.providerConfig.LoginHint = hint
|
|
}
|
|
|
|
// ForceAccountPrompt makes the next authorization request ask the IdP to
|
|
// re-authenticate instead of answering from the session it already holds. Used
|
|
// to retry a login that came back for an account other than the one hinted.
|
|
//
|
|
// The next RequestAuthInfo consumes the flag, so a flow that outlives its retry
|
|
// goes back to the configured behaviour instead of re-authenticating forever.
|
|
//
|
|
// DisablePromptLogin still wins: it is set for IdPs that break on prompt=login,
|
|
// where retrying with it would replace a wrong-account login with one that
|
|
// cannot complete at all.
|
|
func (p *PKCEAuthorizationFlow) ForceAccountPrompt() {
|
|
p.forceAccountPrompt = true
|
|
}
|
|
|
|
// WaitToken waits for the OAuth token in the PKCE Authorization Flow.
|
|
// It starts an HTTP server to receive the OAuth token callback and waits for the token or an error.
|
|
// Once the token is received, it is converted to TokenInfo and validated before returning.
|
|
// The method creates a timeout context internally based on info.ExpiresIn.
|
|
func (p *PKCEAuthorizationFlow) WaitToken(ctx context.Context, info AuthFlowInfo) (TokenInfo, error) {
|
|
// Create timeout context based on flow expiration
|
|
timeout := time.Duration(info.ExpiresIn) * time.Second
|
|
waitCtx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
log.Infof("pkce flow: waiting for authorization callback on %s, timeout %s", p.oAuthConfig.RedirectURL, timeout)
|
|
|
|
tokenChan := make(chan *oauth2.Token, 1)
|
|
errChan := make(chan error, 1)
|
|
|
|
parsedURL, err := url.Parse(p.oAuthConfig.RedirectURL)
|
|
if err != nil {
|
|
return TokenInfo{}, fmt.Errorf("failed to parse redirect URL: %v", err)
|
|
}
|
|
|
|
server := &http.Server{Addr: fmt.Sprintf(":%s", parsedURL.Port())}
|
|
defer func() {
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := server.Shutdown(shutdownCtx); err != nil {
|
|
log.Errorf("failed to close the server: %v", err)
|
|
}
|
|
}()
|
|
|
|
go p.startServer(server, tokenChan, errChan)
|
|
|
|
select {
|
|
case <-waitCtx.Done():
|
|
return TokenInfo{}, waitCtx.Err()
|
|
case token := <-tokenChan:
|
|
return p.parseOAuthToken(token)
|
|
case err := <-errChan:
|
|
return TokenInfo{}, err
|
|
}
|
|
}
|
|
|
|
func (p *PKCEAuthorizationFlow) startServer(server *http.Server, tokenChan chan<- *oauth2.Token, errChan chan<- error) {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
|
|
log.Infof("pkce flow: received authorization callback from IdP")
|
|
cert := p.providerConfig.ClientCertPair
|
|
if cert != nil {
|
|
tr := &http.Transport{
|
|
TLSClientConfig: &tls.Config{
|
|
Certificates: []tls.Certificate{*cert},
|
|
},
|
|
}
|
|
sslClient := &http.Client{Transport: tr}
|
|
ctx := context.WithValue(req.Context(), oauth2.HTTPClient, sslClient)
|
|
req = req.WithContext(ctx)
|
|
}
|
|
|
|
token, err := p.handleRequest(req)
|
|
if err != nil {
|
|
renderPKCEFlowTmpl(w, err)
|
|
errChan <- fmt.Errorf("PKCE authorization flow failed: %v", err)
|
|
return
|
|
}
|
|
|
|
renderPKCEFlowTmpl(w, nil)
|
|
tokenChan <- token
|
|
})
|
|
|
|
server.Handler = mux
|
|
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
errChan <- err
|
|
}
|
|
}
|
|
|
|
func (p *PKCEAuthorizationFlow) handleRequest(req *http.Request) (*oauth2.Token, error) {
|
|
query := req.URL.Query()
|
|
|
|
if authError := query.Get(queryError); authError != "" {
|
|
authErrorDesc := query.Get(queryErrorDesc)
|
|
if authErrorDesc != "" {
|
|
return nil, fmt.Errorf("authentication failed: %s", authErrorDesc)
|
|
}
|
|
return nil, fmt.Errorf("authentication failed: %s", authError)
|
|
}
|
|
|
|
// Prevent timing attacks on the state
|
|
if state := query.Get(queryState); subtle.ConstantTimeCompare([]byte(p.state), []byte(state)) == 0 {
|
|
return nil, fmt.Errorf("authentication failed: Invalid state")
|
|
}
|
|
|
|
code := query.Get(queryCode)
|
|
if code == "" {
|
|
return nil, fmt.Errorf("authentication failed: missing code")
|
|
}
|
|
|
|
exchangeStart := time.Now()
|
|
token, err := p.oAuthConfig.Exchange(
|
|
req.Context(),
|
|
code,
|
|
oauth2.SetAuthURLParam("code_verifier", p.codeVerifier),
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
log.Infof("pkce flow: authorization code exchanged for token in %s", time.Since(exchangeStart).Round(time.Millisecond))
|
|
return token, nil
|
|
}
|
|
|
|
func (p *PKCEAuthorizationFlow) parseOAuthToken(token *oauth2.Token) (TokenInfo, error) {
|
|
tokenInfo := TokenInfo{
|
|
AccessToken: token.AccessToken,
|
|
RefreshToken: token.RefreshToken,
|
|
TokenType: token.TokenType,
|
|
ExpiresIn: token.Expiry.Second(),
|
|
UseIDToken: p.providerConfig.UseIDToken,
|
|
}
|
|
if idToken, ok := token.Extra("id_token").(string); ok {
|
|
tokenInfo.IDToken = idToken
|
|
}
|
|
|
|
// if a provider doesn't support an audience, use the Client ID for token verification
|
|
audience := p.providerConfig.Audience
|
|
if audience == "" {
|
|
audience = p.providerConfig.ClientID
|
|
}
|
|
|
|
if err := validateTokenAudience(tokenInfo.GetTokenToUse(), audience); err != nil {
|
|
return TokenInfo{}, fmt.Errorf("authentication failed: invalid access token - %w", err)
|
|
}
|
|
|
|
email, fromEmailClaim, err := parseEmailFromIDToken(tokenInfo.IDToken)
|
|
if err != nil {
|
|
log.Warnf("failed to parse email from ID token: %v", err)
|
|
} else {
|
|
tokenInfo.Email = email
|
|
if fromEmailClaim {
|
|
tokenInfo.EmailClaim = email
|
|
}
|
|
}
|
|
|
|
return tokenInfo, nil
|
|
}
|
|
|
|
// parseEmailFromIDToken extracts the email (or name) claim from an ID token
|
|
// without verifying its signature. The value is best-effort: it prefills the
|
|
// login hint and is displayed. Account matching (see MatchesAccount) only uses
|
|
// it when it came from the email claim, which fromEmailClaim reports. It never
|
|
// grants anything — the authoritative identity is established server-side from
|
|
// the signature-verified token.
|
|
func parseEmailFromIDToken(token string) (value string, fromEmailClaim bool, err error) {
|
|
parts := strings.Split(token, ".")
|
|
if len(parts) < 2 {
|
|
return "", false, fmt.Errorf("invalid token format")
|
|
}
|
|
|
|
data, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil {
|
|
return "", false, fmt.Errorf("failed to decode payload: %w", err)
|
|
}
|
|
var claims map[string]interface{}
|
|
if err := json.Unmarshal(data, &claims); err != nil {
|
|
return "", false, fmt.Errorf("json unmarshal error: %w", err)
|
|
}
|
|
|
|
if email, ok := claims["email"].(string); ok {
|
|
return email, true, nil
|
|
}
|
|
if name, ok := claims["name"].(string); ok {
|
|
return name, false, nil
|
|
}
|
|
|
|
return "", false, fmt.Errorf("email or name field not found in token payload")
|
|
}
|
|
|
|
func createCodeChallenge(codeVerifier string) string {
|
|
sha2 := sha256.Sum256([]byte(codeVerifier))
|
|
return base64.RawURLEncoding.EncodeToString(sha2[:])
|
|
}
|
|
|
|
// isRedirectURLPortUsed checks if the port used in the redirect URL is in use or excluded on Windows.
|
|
func isRedirectURLPortUsed(redirectURL string, excludedRanges []excludedPortRange) bool {
|
|
parsedURL, err := url.Parse(redirectURL)
|
|
if err != nil {
|
|
log.Errorf("failed to parse redirect URL: %v", err)
|
|
return true
|
|
}
|
|
|
|
port := parsedURL.Port()
|
|
|
|
if isPortInExcludedRange(port, excludedRanges) {
|
|
log.Warnf("port %s is in Windows excluded port range, skipping", port)
|
|
return true
|
|
}
|
|
|
|
// FreeBSD 15 disables connecting to INADDR_ANY (0.0.0.0) as a localhost
|
|
// alias by default, ensure explicit ip for localhost.
|
|
host := parsedURL.Hostname()
|
|
if host == "" {
|
|
host = "127.0.0.1"
|
|
}
|
|
addr := net.JoinHostPort(host, port)
|
|
conn, err := net.DialTimeout("tcp", addr, 3*time.Second)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
defer func() {
|
|
if err := conn.Close(); err != nil {
|
|
log.Errorf("error while closing the connection: %v", err)
|
|
}
|
|
}()
|
|
|
|
return true
|
|
}
|
|
|
|
// excludedPortRange represents a range of excluded ports.
|
|
type excludedPortRange struct {
|
|
start int
|
|
end int
|
|
}
|
|
|
|
// isPortInExcludedRange checks if the given port is in any of the excluded ranges.
|
|
func isPortInExcludedRange(port string, excludedRanges []excludedPortRange) bool {
|
|
if len(excludedRanges) == 0 {
|
|
return false
|
|
}
|
|
|
|
portNum, err := strconv.Atoi(port)
|
|
if err != nil {
|
|
log.Debugf("invalid port number %s: %v", port, err)
|
|
return false
|
|
}
|
|
|
|
for _, r := range excludedRanges {
|
|
if portNum >= r.start && portNum <= r.end {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func renderPKCEFlowTmpl(w http.ResponseWriter, authError error) {
|
|
tmpl, err := template.New("pkce-auth-flow").Parse(templates.PKCEAuthMsgTmpl)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
data := make(map[string]string)
|
|
if authError != nil {
|
|
data["Error"] = authError.Error()
|
|
}
|
|
|
|
if err := tmpl.Execute(w, data); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
}
|