From af4d091663ddc5a33652c3947dbee108505fa2df Mon Sep 17 00:00:00 2001 From: Pavol Ipoth Date: Wed, 18 Dec 2024 00:05:05 +0100 Subject: [PATCH] Fix dot linter --- .golangci.yml | 1 - pkg/apperrors/apperrors.go | 2 +- pkg/authorization/resource.go | 10 ++++---- pkg/constant/constant.go | 4 ++-- pkg/encryption/rotation.go | 8 +++---- pkg/encryption/self_signed.go | 14 +++++------ pkg/encryption/text_encryption.go | 8 +++---- pkg/google/config/config.go | 8 ++----- pkg/keycloak/config/config.go | 8 ++----- pkg/keycloak/proxy/forwarding.go | 2 +- pkg/keycloak/proxy/misc.go | 2 +- pkg/keycloak/proxy/server.go | 20 ++++++++-------- pkg/proxy/cookie/cookies.go | 40 +++++++++++++++---------------- pkg/proxy/core/core.go | 2 -- pkg/proxy/core/helpers.go | 4 ++-- pkg/proxy/core/template.go | 3 +-- pkg/proxy/handlers/handlers.go | 16 ++++++------- pkg/proxy/middleware/base.go | 14 ++++------- pkg/proxy/middleware/security.go | 4 ++-- pkg/proxy/models/models.go | 2 +- pkg/proxy/models/rest.go | 2 +- pkg/proxy/models/user.go | 8 +++---- pkg/proxy/session/token.go | 18 +++++++------- pkg/storage/storage.go | 4 ++-- pkg/storage/store_redis.go | 14 +++++------ pkg/testsuite/fake_authserver.go | 8 +------ pkg/testsuite/fake_upstream.go | 4 ++-- pkg/testsuite/middleware_test.go | 2 +- pkg/utils/token.go | 2 -- pkg/utils/utils.go | 32 +++++++++---------------- 30 files changed, 116 insertions(+), 150 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 3d535eb0..669530af 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -42,5 +42,4 @@ linters: # TODO: Revisit after the refactor - gocognit - testpackage - - godot - nestif diff --git a/pkg/apperrors/apperrors.go b/pkg/apperrors/apperrors.go index b3bdf186..d7e5628b 100644 --- a/pkg/apperrors/apperrors.go +++ b/pkg/apperrors/apperrors.go @@ -83,7 +83,7 @@ var ( ErrStartRedirectHTTP = errors.New("failed to start http redirect service") ErrStartAdminHTTP = errors.New("failed to start admin service") - // config errors + // config errors. ErrNoRedirectsWithEnableRefreshTokensInvalid = errors.New("no-redirects true cannot be enabled with refresh tokens") ErrInvalidPostLoginRedirectPath = errors.New("post login redirect path invalid, should be only path not absolute url (no hostname, scheme)") diff --git a/pkg/authorization/resource.go b/pkg/authorization/resource.go index 0e74f24d..40f21be5 100644 --- a/pkg/authorization/resource.go +++ b/pkg/authorization/resource.go @@ -25,7 +25,7 @@ import ( "github.com/gogatekeeper/gatekeeper/pkg/utils" ) -// Resource represents a url resource to protect +// Resource represents a url resource to protect. type Resource struct { // URL the url for the resource URL string `json:"uri" yaml:"uri"` @@ -171,22 +171,22 @@ func (r *Resource) Valid() error { return nil } -// GetRoles returns a list of roles for this resource +// GetRoles returns a list of roles for this resource. func (r Resource) GetRoles() string { return strings.Join(r.Roles, ",") } -// GetAcr returns a list of authentication levels for this resource +// GetAcr returns a list of authentication levels for this resource. func (r Resource) GetAcr() string { return strings.Join(r.Acr, ",") } -// GetHeaders returns a list of headers for this resource +// GetHeaders returns a list of headers for this resource. func (r Resource) GetHeaders() string { return strings.Join(r.Headers, ",") } -// String returns a string representation of the resource +// String returns a string representation of the resource. func (r Resource) String() string { if r.WhiteListed { return fmt.Sprintf("uri: %s, white-listed", r.URL) diff --git a/pkg/constant/constant.go b/pkg/constant/constant.go index 6110014e..d5752116 100644 --- a/pkg/constant/constant.go +++ b/pkg/constant/constant.go @@ -42,7 +42,7 @@ const ( IDTokenCookie = "id_token" UMACookie = "uma_token" // case is like this because go net package canonicalizes it - // to this form, see net package + // to this form, see net package. UMAHeader = "X-Uma-Token" UnsecureScheme = "http" SecureScheme = "https" @@ -62,7 +62,7 @@ const ( DurationType = "time.Duration" - // SameSite cookie config options + // SameSite cookie config options. SameSiteStrict = "Strict" SameSiteLax = "Lax" SameSiteNone = "None" diff --git a/pkg/encryption/rotation.go b/pkg/encryption/rotation.go index b77c4b9b..65b27db0 100644 --- a/pkg/encryption/rotation.go +++ b/pkg/encryption/rotation.go @@ -40,7 +40,7 @@ type CertificationRotation struct { rotationMetric *prometheus.Counter } -// newCertificateRotator creates a new certificate +// newCertificateRotator creates a new certificate. func NewCertificateRotator(cert, key string, log *zap.Logger, metric *prometheus.Counter) (*CertificationRotation, error) { // step: attempt to load the certificate certificate, err := tls.LoadX509KeyPair(cert, key) @@ -59,7 +59,7 @@ func NewCertificateRotator(cert, key string, log *zap.Logger, metric *prometheus }, nil } -// watch is responsible for adding a file notification and watch on the files for changes +// watch is responsible for adding a file notification and watch on the files for changes. func (c *CertificationRotation) Watch() error { c.log.Info( "adding a file watch on the certificates, certificate", @@ -115,7 +115,7 @@ func (c *CertificationRotation) Watch() error { return nil } -// storeCertificate provides entrypoint to update the certificate +// storeCertificate provides entrypoint to update the certificate. func (c *CertificationRotation) storeCertificate(certifacte tls.Certificate) error { c.Lock() defer c.Unlock() @@ -124,7 +124,7 @@ func (c *CertificationRotation) storeCertificate(certifacte tls.Certificate) err return nil } -// GetCertificate is responsible for retrieving +// GetCertificate is responsible for retrieving. func (c *CertificationRotation) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { c.RLock() defer c.RUnlock() diff --git a/pkg/encryption/self_signed.go b/pkg/encryption/self_signed.go index 4f568f31..e84c97cd 100644 --- a/pkg/encryption/self_signed.go +++ b/pkg/encryption/self_signed.go @@ -51,7 +51,7 @@ type SelfSignedCertificate struct { cancel context.CancelFunc } -// newSelfSignedCertificate creates and returns a self signed certificate manager +// newSelfSignedCertificate creates and returns a self signed certificate manager. func NewSelfSignedCertificate(hostnames []string, expiry time.Duration, log *zap.Logger) (*SelfSignedCertificate, error) { if len(hostnames) == 0 { return nil, apperrors.ErrCertSelfNoHostname @@ -99,7 +99,7 @@ func NewSelfSignedCertificate(hostnames []string, expiry time.Duration, log *zap return svc, nil } -// rotate is responsible for rotation the certificate +// rotate is responsible for rotation the certificate. func (c *SelfSignedCertificate) rotate(ctx context.Context) error { go func() { c.log.Info("starting the self-signed certificate rotation", @@ -136,12 +136,12 @@ func (c *SelfSignedCertificate) rotate(ctx context.Context) error { } // Deprecated:unused -// close is used to shutdown resources +// close is used to shutdown resources. func (c *SelfSignedCertificate) close() { c.cancel() } -// updateCertificate is responsible for update the certificate +// updateCertificate is responsible for update the certificate. func (c *SelfSignedCertificate) updateCertificate(cert tls.Certificate) { c.Lock() defer c.Unlock() @@ -149,7 +149,7 @@ func (c *SelfSignedCertificate) updateCertificate(cert tls.Certificate) { c.certificate = cert } -// GetCertificate is responsible for retrieving +// GetCertificate is responsible for retrieving. func (c *SelfSignedCertificate) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { c.RLock() defer c.RUnlock() @@ -157,7 +157,7 @@ func (c *SelfSignedCertificate) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Cer return &c.certificate, nil } -// createCertificate is responsible for creating a certificate +// createCertificate is responsible for creating a certificate. func CreateCertificate(key *ed25519.PrivateKey, hostnames []string, expire time.Duration) (tls.Certificate, error) { // @step: create a serial for the certificate serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), constant.SelfSignedMaxSerialBits)) @@ -208,7 +208,7 @@ func CreateCertificate(key *ed25519.PrivateKey, hostnames []string, expire time. return tls.X509KeyPair(certPEM, keyPEM) } -// loadCA loads the certificate authority +// loadCA loads the certificate authority. func LoadCA(cert, key string) (*tls.Certificate, error) { caCert, err := os.ReadFile(cert) diff --git a/pkg/encryption/text_encryption.go b/pkg/encryption/text_encryption.go index 4c94e53e..2fa18e32 100644 --- a/pkg/encryption/text_encryption.go +++ b/pkg/encryption/text_encryption.go @@ -11,7 +11,7 @@ import ( "github.com/gogatekeeper/gatekeeper/pkg/apperrors" ) -// encryptDataBlock encrypts the plaintext string with the key +// encryptDataBlock encrypts the plaintext string with the key. func EncryptDataBlock(plaintext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) @@ -34,7 +34,7 @@ func EncryptDataBlock(plaintext, key []byte) ([]byte, error) { return gcm.Seal(nonce, nonce, plaintext, nil), nil } -// decryptDataBlock decrypts some cipher text +// decryptDataBlock decrypts some cipher text. func DecryptDataBlock(cipherText, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) @@ -59,7 +59,7 @@ func DecryptDataBlock(cipherText, key []byte) ([]byte, error) { return gcm.Open(nil, nonce, input, nil) } -// encodeText encodes the session state information into a value for a cookie to consume +// encodeText encodes the session state information into a value for a cookie to consume. func EncodeText(plaintext string, key string) (string, error) { cipherText, err := EncryptDataBlock([]byte(plaintext), []byte(key)) @@ -70,7 +70,7 @@ func EncodeText(plaintext string, key string) (string, error) { return base64.RawStdEncoding.EncodeToString(cipherText), nil } -// decodeText decodes the session state cookie value +// decodeText decodes the session state cookie value. func DecodeText(state, key string) (string, error) { cipherText, err := base64.RawStdEncoding.DecodeString(state) diff --git a/pkg/google/config/config.go b/pkg/google/config/config.go index e14847c0..449e0666 100644 --- a/pkg/google/config/config.go +++ b/pkg/google/config/config.go @@ -173,7 +173,6 @@ type Config struct { IsDiscoverURILegacy bool } -// NewDefaultConfig returns a initialized config func NewDefaultConfig() *Config { var hostnames []string if name, err := os.Hostname(); err == nil { @@ -265,7 +264,7 @@ func (r *Config) GetDefaultAllowedQueryParams() map[string]string { return r.DefaultAllowedQueryParams } -// readConfigFile reads and parses the configuration file +// readConfigFile reads and parses the configuration file. func (r *Config) ReadConfigFile(filename string) error { content, err := os.ReadFile(filename) @@ -299,7 +298,7 @@ func (r *Config) Update() error { return nil } -// IsValid validates if the config is valid +// IsValid validates if the config is valid. func (r *Config) IsValid() error { if r.ListenAdmin == r.Listen { r.ListenAdmin = "" @@ -332,17 +331,14 @@ func (r *Config) IsValid() error { return nil } -// HasCustomSignInPage checks if there is a custom sign in page func (r *Config) HasCustomSignInPage() bool { return r.SignInPage != "" } -// HasForbiddenPage checks if there is a custom forbidden page func (r *Config) HasCustomForbiddenPage() bool { return r.ForbiddenPage != "" } -// HasCustomErrorPage checks if there is a custom error page func (r *Config) HasCustomErrorPage() bool { return r.ErrorPage != "" } diff --git a/pkg/keycloak/config/config.go b/pkg/keycloak/config/config.go index 35c82ab9..8180ef01 100644 --- a/pkg/keycloak/config/config.go +++ b/pkg/keycloak/config/config.go @@ -183,7 +183,6 @@ type Config struct { IsDiscoverURILegacy bool } -// NewDefaultConfig returns a initialized config func NewDefaultConfig() *Config { var hostnames []string if name, err := os.Hostname(); err == nil { @@ -278,7 +277,7 @@ func (r *Config) GetDefaultAllowedQueryParams() map[string]string { return r.DefaultAllowedQueryParams } -// readConfigFile reads and parses the configuration file +// readConfigFile reads and parses the configuration file. func (r *Config) ReadConfigFile(filename string) error { content, err := os.ReadFile(filename) @@ -312,7 +311,7 @@ func (r *Config) Update() error { return nil } -// IsValid validates if the config is valid +// IsValid validates if the config is valid. func (r *Config) IsValid() error { if r.ListenAdmin == r.Listen { r.ListenAdmin = "" @@ -347,17 +346,14 @@ func (r *Config) IsValid() error { return nil } -// HasCustomSignInPage checks if there is a custom sign in page func (r *Config) HasCustomSignInPage() bool { return r.SignInPage != "" } -// HasForbiddenPage checks if there is a custom forbidden page func (r *Config) HasCustomForbiddenPage() bool { return r.ForbiddenPage != "" } -// HasCustomErrorPage checks if there is a custom error page func (r *Config) HasCustomErrorPage() bool { return r.ErrorPage != "" } diff --git a/pkg/keycloak/proxy/forwarding.go b/pkg/keycloak/proxy/forwarding.go index 2244ea7d..6780e71b 100644 --- a/pkg/keycloak/proxy/forwarding.go +++ b/pkg/keycloak/proxy/forwarding.go @@ -23,7 +23,7 @@ import ( "go.uber.org/zap" ) -// forwardProxyHandler is responsible for signing outbound requests +// forwardProxyHandler is responsible for signing outbound requests. func forwardProxyHandler( logger *zap.Logger, pat *PAT, diff --git a/pkg/keycloak/proxy/misc.go b/pkg/keycloak/proxy/misc.go index 1a219282..15ed9865 100644 --- a/pkg/keycloak/proxy/misc.go +++ b/pkg/keycloak/proxy/misc.go @@ -230,7 +230,7 @@ func WithUMAIdentity( return authzFunc(targetPath, umaUser.Permissions) } -// getRPT retrieves relaying party token +// getRPT retrieves relaying party token. func getRPT( ctx context.Context, pat *PAT, diff --git a/pkg/keycloak/proxy/server.go b/pkg/keycloak/proxy/server.go index 305a53de..ecc3eda2 100644 --- a/pkg/keycloak/proxy/server.go +++ b/pkg/keycloak/proxy/server.go @@ -171,7 +171,7 @@ func NewProxy(config *config.Config, log *zap.Logger, upstream core.ReverseProxy return svc, nil } -// createLogger is responsible for creating the service logger +// createLogger is responsible for creating the service logger. func createLogger(config *config.Config) (*zap.Logger, error) { httplog.SetOutput(io.Discard) // disable the http logger @@ -202,7 +202,7 @@ func createLogger(config *config.Config) (*zap.Logger, error) { return cfg.Build() } -// useDefaultStack sets the default middleware stack for router +// useDefaultStack sets the default middleware stack for router. func (r *OauthProxy) useDefaultStack(engine chi.Router, accessForbidden func(wrt http.ResponseWriter, req *http.Request) context.Context) { engine.NotFound(handlers.EmptyHandler) @@ -1065,7 +1065,7 @@ func (r *OauthProxy) Run() (context.Context, error) { return ctx, nil } -// Shutdown finishes the proxy service with gracefully period +// Shutdown finishes the proxy service with gracefully period. func (r *OauthProxy) Shutdown() error { ctx, cancel := context.WithTimeout( context.Background(), @@ -1100,7 +1100,7 @@ func (r *OauthProxy) Shutdown() error { return err } -// listenerConfig encapsulate listener options +// listenerConfig encapsulate listener options. type listenerConfig struct { hostnames []string // list of hostnames the service will respond to ca string // the path to a certificate authority @@ -1117,7 +1117,7 @@ type listenerConfig struct { useSelfSignedTLS bool // indicates we are using the self-signed tls } -// makeListenerConfig extracts a listener configuration from a proxy Config +// makeListenerConfig extracts a listener configuration from a proxy Config. func makeListenerConfig(config *config.Config) listenerConfig { var minTLSVersion uint16 switch strings.ToLower(config.TLSMinVersion) { @@ -1148,10 +1148,10 @@ func makeListenerConfig(config *config.Config) listenerConfig { } } -// ErrHostNotConfigured indicates the hostname was not configured +// ErrHostNotConfigured indicates the hostname was not configured. var ErrHostNotConfigured = errors.New("acme/autocert: host not configured") -// createHTTPListener is responsible for creating a listening socket +// createHTTPListener is responsible for creating a listening socket. // //nolint:cyclop func (r *OauthProxy) createHTTPListener(config listenerConfig) (net.Listener, error) { @@ -1304,7 +1304,7 @@ func (r *OauthProxy) createHTTPListener(config listenerConfig) (net.Listener, er return listener, nil } -// createUpstreamProxy create a reverse http proxy from the upstream +// createUpstreamProxy create a reverse http proxy from the upstream. func (r *OauthProxy) createUpstreamProxy(upstream *url.URL) error { dialer := (&net.Dialer{ KeepAlive: r.Config.UpstreamKeepaliveTimeout, @@ -1417,7 +1417,7 @@ func (r *OauthProxy) createUpstreamProxy(upstream *url.URL) error { return nil } -// createTemplates loads the custom template +// createTemplates loads the custom template. func createTemplates( logger *zap.Logger, signInPage string, @@ -1489,7 +1489,7 @@ func (r OpenIDRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) } // newOpenIDProvider initializes the openID configuration, note: the redirection url is deliberately left blank -// in order to retrieve it from the host header on request +// in order to retrieve it from the host header on request. func (r *OauthProxy) NewOpenIDProvider() (*oidc3.Provider, *gocloak.GoCloak, error) { host := fmt.Sprintf( "%s://%s", diff --git a/pkg/proxy/cookie/cookies.go b/pkg/proxy/cookie/cookies.go index 11dec2c8..ca7cba1a 100644 --- a/pkg/proxy/cookie/cookies.go +++ b/pkg/proxy/cookie/cookies.go @@ -44,7 +44,7 @@ type Manager struct { NoRedirects bool } -// DropCookie drops a cookie into the response +// DropCookie drops a cookie into the response. func (cm *Manager) DropCookie( wrt http.ResponseWriter, name, @@ -88,7 +88,7 @@ func (cm *Manager) DropCookie( } // maxCookieChunkSize calculates max cookie chunk size, which can be used for cookie value -// this seems to be not useful as many browsers have limits of all cookies per domain = 4096 bytes +// this seems to be not useful as many browsers have limits of all cookies per domain = 4096 bytes. func (cm *Manager) GetMaxCookieChunkLength( req *http.Request, cookieName string, @@ -125,7 +125,7 @@ func (cm *Manager) GetMaxCookieChunkLength( return maxCookieChunkLength } -// dropCookieWithChunks drops a cookie from the response, taking into account possible chunks +// dropCookieWithChunks drops a cookie from the response, taking into account possible chunks. func (cm *Manager) dropCookieWithChunks( req *http.Request, wrt http.ResponseWriter, @@ -138,7 +138,7 @@ func (cm *Manager) dropCookieWithChunks( if len(value) <= maxCookieChunkLength { cm.DropCookie(wrt, name, value, duration) } else { - // write divided cookies because payload is too long for single cookie + // write divided cookies because payload is too long for single cookie. cm.DropCookie(wrt, name, value[0:maxCookieChunkLength], duration) for idx := maxCookieChunkLength; idx < len(value); idx += maxCookieChunkLength { @@ -157,27 +157,27 @@ func (cm *Manager) dropCookieWithChunks( } } -// dropAccessTokenCookie drops a access token cookie +// dropAccessTokenCookie drops a access token cookie. func (cm *Manager) DropAccessTokenCookie(req *http.Request, w http.ResponseWriter, value string, duration time.Duration) { cm.dropCookieWithChunks(req, w, cm.CookieAccessName, value, duration) } -// DropRefreshTokenCookie drops a refresh token cookie +// DropRefreshTokenCookie drops a refresh token cookie. func (cm *Manager) DropRefreshTokenCookie(req *http.Request, w http.ResponseWriter, value string, duration time.Duration) { cm.dropCookieWithChunks(req, w, cm.CookieRefreshName, value, duration) } -// dropIdTokenCookie drops a id token cookie +// dropIdTokenCookie drops a id token cookie. func (cm *Manager) DropIDTokenCookie(req *http.Request, w http.ResponseWriter, value string, duration time.Duration) { cm.dropCookieWithChunks(req, w, cm.CookieIDTokenName, value, duration) } -// dropUMATokenCookie drops a uma token cookie +// dropUMATokenCookie drops a uma token cookie. func (cm *Manager) DropUMATokenCookie(req *http.Request, w http.ResponseWriter, value string, duration time.Duration) { cm.dropCookieWithChunks(req, w, cm.CookieUMAName, value, duration) } -// DropStateParameterCookie sets a state parameter cookie into the response +// DropStateParameterCookie sets a state parameter cookie into the response. func (cm *Manager) DropStateParameterCookie(req *http.Request, wrt http.ResponseWriter) string { uuid, err := uuid.NewV4() @@ -200,12 +200,12 @@ func (cm *Manager) DropStateParameterCookie(req *http.Request, wrt http.Response return uuid.String() } -// DropPKCECookie sets a code verifier cookie into the response +// DropPKCECookie sets a code verifier cookie into the response. func (cm *Manager) DropPKCECookie(wrt http.ResponseWriter, codeVerifier string) { cm.DropCookie(wrt, cm.CookiePKCEName, codeVerifier, 0) } -// ClearAllCookies is just a helper function for the below +// ClearAllCookies is just a helper function for the below. func (cm *Manager) ClearAllCookies(req *http.Request, w http.ResponseWriter) { cm.ClearAccessTokenCookie(req, w) cm.ClearRefreshTokenCookie(req, w) @@ -217,7 +217,7 @@ func (cm *Manager) ClearAllCookies(req *http.Request, w http.ResponseWriter) { func (cm *Manager) ClearCookie(req *http.Request, wrt http.ResponseWriter, name string) { cm.DropCookie(wrt, name, "", constant.InvalidCookieDuration) - // clear divided cookies + // clear divided cookies. for idx := 1; idx < 600; idx++ { var _, err = req.Cookie(name + "-" + strconv.Itoa(idx)) @@ -234,38 +234,38 @@ func (cm *Manager) ClearCookie(req *http.Request, wrt http.ResponseWriter, name } } -// clearRefreshSessionCookie clears the session cookie +// clearRefreshSessionCookie clears the session cookie. func (cm *Manager) ClearRefreshTokenCookie(req *http.Request, wrt http.ResponseWriter) { cm.ClearCookie(req, wrt, cm.CookieRefreshName) } -// ClearAccessTokenCookie clears the session cookie +// ClearAccessTokenCookie clears the session cookie. func (cm *Manager) ClearAccessTokenCookie(req *http.Request, wrt http.ResponseWriter) { cm.ClearCookie(req, wrt, cm.CookieAccessName) } -// ClearIDTokenCookie clears the session cookie +// ClearIDTokenCookie clears the session cookie. func (cm *Manager) ClearIDTokenCookie(req *http.Request, wrt http.ResponseWriter) { cm.ClearCookie(req, wrt, cm.CookieIDTokenName) } -// ClearUMATokenCookie clears the session cookie +// ClearUMATokenCookie clears the session cookie. func (cm *Manager) ClearUMATokenCookie(req *http.Request, wrt http.ResponseWriter) { cm.ClearCookie(req, wrt, cm.CookieUMAName) } -// ClearPKCECookie clears the session cookie +// ClearPKCECookie clears the session cookie. func (cm *Manager) ClearPKCECookie(req *http.Request, wrt http.ResponseWriter) { cm.ClearCookie(req, wrt, cm.CookiePKCEName) } -// ClearStateParameterCookie clears the session cookie +// ClearStateParameterCookie clears the session cookie. func (cm *Manager) ClearStateParameterCookie(req *http.Request, wrt http.ResponseWriter) { cm.ClearCookie(req, wrt, cm.CookieRequestURIName) cm.ClearCookie(req, wrt, cm.CookieOAuthStateName) } -// findCookie looks for a cookie in a list of cookies +// findCookie looks for a cookie in a list of cookies. func FindCookie(name string, cookies []*http.Cookie) *http.Cookie { for _, cookie := range cookies { if cookie.Name == name { @@ -276,7 +276,7 @@ func FindCookie(name string, cookies []*http.Cookie) *http.Cookie { return nil } -// filterCookies is responsible for censoring any cookies we don't want sent +// filterCookies is responsible for censoring any cookies we don't want sent. func FilterCookies(req *http.Request, filter []string) error { // @NOTE: there doesn't appear to be a way of removing a cookie from the http.Request as // AddCookie() just append diff --git a/pkg/proxy/core/core.go b/pkg/proxy/core/core.go index bbef36e1..a2b68c67 100644 --- a/pkg/proxy/core/core.go +++ b/pkg/proxy/core/core.go @@ -18,7 +18,6 @@ var ( Version = "" ) -// GetVersion returns the proxy version func GetVersion() string { if Version == "" { tm, err := strconv.ParseInt(compiled, 10, 64) @@ -37,7 +36,6 @@ type OauthProxies interface { Shutdown() error } -// ReverseProxy is a wrapper type ReverseProxy interface { ServeHTTP(rw http.ResponseWriter, req *http.Request) } diff --git a/pkg/proxy/core/helpers.go b/pkg/proxy/core/helpers.go index dbe2b408..bbef5dac 100644 --- a/pkg/proxy/core/helpers.go +++ b/pkg/proxy/core/helpers.go @@ -14,7 +14,7 @@ import ( "go.uber.org/zap" ) -// RedirectToURL redirects the user and aborts the context +// RedirectToURL redirects the user and aborts the context. func RedirectToURL( logger *zap.Logger, url string, @@ -142,7 +142,7 @@ func EncryptToken( return encrypted, nil } -// revokeProxy is responsible for stopping middleware from proxying the request +// revokeProxy is responsible for stopping middleware from proxying the request. func revokeProxy(logger *zap.Logger, req *http.Request) context.Context { var scope *models.RequestScope ctxVal := req.Context().Value(constant.ContextScopeName) diff --git a/pkg/proxy/core/template.go b/pkg/proxy/core/template.go index 2cc3801a..034d32a4 100644 --- a/pkg/proxy/core/template.go +++ b/pkg/proxy/core/template.go @@ -10,7 +10,7 @@ import ( "go.uber.org/zap" ) -// AccessForbidden redirects the user to the forbidden page +// AccessForbidden redirects the user to the forbidden page. func AccessForbidden( logger *zap.Logger, httpStatus int, @@ -37,7 +37,6 @@ func AccessForbidden( } } -// renders CustomSignInPage func CustomSignInPage( logger *zap.Logger, page string, diff --git a/pkg/proxy/handlers/handlers.go b/pkg/proxy/handlers/handlers.go index db05960c..c307079d 100644 --- a/pkg/proxy/handlers/handlers.go +++ b/pkg/proxy/handlers/handlers.go @@ -35,10 +35,10 @@ import ( "go.uber.org/zap" ) -// EmptyHandler is responsible for doing nothing +// EmptyHandler is responsible for doing nothing. func EmptyHandler(_ http.ResponseWriter, _ *http.Request) {} -// HealthHandler is a health check handler for the service +// HealthHandler is a health check handler for the service. func HealthHandler(w http.ResponseWriter, _ *http.Request) { w.Header().Set(constant.VersionHeader, proxycore.GetVersion()) w.WriteHeader(http.StatusOK) @@ -90,7 +90,7 @@ func MethodNotAllowHandlder(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(nil) } -// ProxyMetricsHandler forwards the request into the prometheus handler +// ProxyMetricsHandler forwards the request into the prometheus handler. func ProxyMetricsHandler( localhostMetrics bool, accessForbidden func(wrt http.ResponseWriter, req *http.Request) context.Context, @@ -107,7 +107,7 @@ func ProxyMetricsHandler( } } -// RetrieveIDToken retrieves the id token from cookie +// RetrieveIDToken retrieves the id token from cookie. func RetrieveIDToken( cookieIDTokenName string, enableEncryptedToken bool, @@ -133,7 +133,7 @@ func RetrieveIDToken( return token, encrypted, err } -// discoveryHandler provides endpoint info +// discoveryHandler provides endpoint info. func DiscoveryHandler( logger *zap.Logger, withOAuthURI func(string) string, @@ -171,7 +171,7 @@ func DiscoveryHandler( } } -// getRedirectionURL returns the redirectionURL for the oauth flow +// getRedirectionURL returns the redirectionURL for the oauth flow. func GetRedirectionURL( logger *zap.Logger, redirectionURL string, @@ -225,7 +225,7 @@ func GetRedirectionURL( } } -// ExpirationHandler checks if the token has expired +// ExpirationHandler checks if the token has expired. func ExpirationHandler( getIdentity func(req *http.Request, tokenCookie string, tokenHeader string) (*models.UserContext, error), cookieAccessName string, @@ -246,7 +246,7 @@ func ExpirationHandler( } } -// TokenHandler display access token to screen +// TokenHandler display access token to screen. func TokenHandler( getIdentity func(req *http.Request, tokenCookie string, tokenHeader string) (*models.UserContext, error), cookieAccessName string, diff --git a/pkg/proxy/middleware/base.go b/pkg/proxy/middleware/base.go index 842f6e81..0ce23c4f 100644 --- a/pkg/proxy/middleware/base.go +++ b/pkg/proxy/middleware/base.go @@ -24,11 +24,10 @@ import ( ) const ( - // normalizeFlags is the options to purell normalizeFlags purell.NormalizationFlags = purell.FlagRemoveDotSegments | purell.FlagRemoveDuplicateSlashes ) -// entrypointMiddleware is custom filtering for incoming requests +// entrypointMiddleware is custom filtering for incoming requests. func EntrypointMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(wrt http.ResponseWriter, req *http.Request) { @@ -66,7 +65,7 @@ func EntrypointMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { } } -// requestIDMiddleware is responsible for adding a request id if none found +// requestIDMiddleware is responsible for adding a request id if none found. func RequestIDMiddleware(header string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(wrt http.ResponseWriter, req *http.Request) { @@ -83,7 +82,7 @@ func RequestIDMiddleware(header string) func(http.Handler) http.Handler { } } -// loggingMiddleware is a custom http logger +// loggingMiddleware is a custom http logger. func LoggingMiddleware( logger *zap.Logger, verbose bool, @@ -138,7 +137,7 @@ func LoggingMiddleware( } } -// ResponseHeaderMiddleware is responsible for adding response headers +// ResponseHeaderMiddleware is responsible for adding response headers. func ResponseHeaderMiddleware(headers map[string]string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(wrt http.ResponseWriter, req *http.Request) { @@ -152,7 +151,6 @@ func ResponseHeaderMiddleware(headers map[string]string) func(http.Handler) http } } -// DenyMiddleware func DenyMiddleware( logger *zap.Logger, accessForbidden func(wrt http.ResponseWriter, req *http.Request) context.Context, @@ -165,7 +163,7 @@ func DenyMiddleware( } } -// ProxyDenyMiddleware just block everything +// ProxyDenyMiddleware just block everything. func ProxyDenyMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(wrt http.ResponseWriter, req *http.Request) { @@ -192,7 +190,6 @@ func ProxyDenyMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { } } -// MethodCheck middleware func MethodCheckMiddleware(logger *zap.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { logger.Info("enabling the method check middleware") @@ -372,7 +369,6 @@ func ProxyMiddleware( } } -// ForwardAuthMiddleware func ForwardAuthMiddleware(logger *zap.Logger, oAuthURI string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { logger.Info("enabling the forward-auth middleware") diff --git a/pkg/proxy/middleware/security.go b/pkg/proxy/middleware/security.go index 7c703787..c00c7a3e 100644 --- a/pkg/proxy/middleware/security.go +++ b/pkg/proxy/middleware/security.go @@ -17,7 +17,7 @@ import ( "go.uber.org/zap" ) -// SecurityMiddleware performs numerous security checks on the request +// SecurityMiddleware performs numerous security checks on the request. func SecurityMiddleware( logger *zap.Logger, allowedHosts []string, @@ -59,7 +59,7 @@ func SecurityMiddleware( } } -// HmacMiddleware verifies hmac +// HmacMiddleware verifies hmac. func HmacMiddleware(logger *zap.Logger, encKey string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(wrt http.ResponseWriter, req *http.Request) { diff --git a/pkg/proxy/models/models.go b/pkg/proxy/models/models.go index 346aae6a..c6be8ede 100644 --- a/pkg/proxy/models/models.go +++ b/pkg/proxy/models/models.go @@ -2,7 +2,7 @@ package models import "go.uber.org/zap" -// RequestScope is a request level context scope passed between middleware +// RequestScope is a request level context scope passed between middleware. type RequestScope struct { // AccessDenied indicates the request should not be proxied on AccessDenied bool diff --git a/pkg/proxy/models/rest.go b/pkg/proxy/models/rest.go index 34de9778..bbe04183 100644 --- a/pkg/proxy/models/rest.go +++ b/pkg/proxy/models/rest.go @@ -1,6 +1,6 @@ package models -// models.TokenResponse +// models.TokenResponse. type TokenResponse struct { TokenType string `json:"token_type"` AccessToken string `json:"access_token"` diff --git a/pkg/proxy/models/user.go b/pkg/proxy/models/user.go index bce7d31a..ebbbafce 100644 --- a/pkg/proxy/models/user.go +++ b/pkg/proxy/models/user.go @@ -20,7 +20,7 @@ type RealmRoles struct { Roles []string `json:"roles"` } -// Extract custom claims +// Extract custom claims. type CustClaims struct { Email string `json:"email"` Acr string `json:"acr"` @@ -34,12 +34,12 @@ type CustClaims struct { Authorization Permissions `json:"authorization"` } -// isExpired checks if the token has expired +// isExpired checks if the token has expired. func (r *UserContext) IsExpired() bool { return r.ExpiresAt.Before(time.Now()) } -// String returns a string representation of the user context +// String returns a string representation of the user context. func (r *UserContext) String() string { return fmt.Sprintf( "user: %s, expires: %s, roles: %s", @@ -49,7 +49,7 @@ func (r *UserContext) String() string { ) } -// userContext holds the information extracted the token +// userContext holds the information extracted the token. type UserContext struct { // the id of the user ID string diff --git a/pkg/proxy/session/token.go b/pkg/proxy/session/token.go index 81066f2c..4d0860f4 100644 --- a/pkg/proxy/session/token.go +++ b/pkg/proxy/session/token.go @@ -25,7 +25,7 @@ import ( "golang.org/x/oauth2" ) -// GetRefreshTokenFromCookie returns the refresh token from the cookie if any +// GetRefreshTokenFromCookie returns the refresh token from the cookie if any. func GetRefreshTokenFromCookie(req *http.Request, cookieName string) (string, error) { token, err := GetTokenInCookie(req, cookieName) if err != nil { @@ -73,7 +73,7 @@ func GetTokenInRequest( return token, bearer, nil } -// getTokenInBearer retrieves a access token from the authorization header +// getTokenInBearer retrieves a access token from the authorization header. func GetTokenInBearer(req *http.Request) (string, error) { token := req.Header.Get(constant.AuthorizationHeader) if token == "" { @@ -92,7 +92,7 @@ func GetTokenInBearer(req *http.Request) (string, error) { return items[1], nil } -// getTokenInHeader retrieves a token from the header +// getTokenInHeader retrieves a token from the header. func GetTokenInHeader(req *http.Request, headerName string) (string, error) { token := req.Header.Get(headerName) if token == "" { @@ -101,7 +101,7 @@ func GetTokenInHeader(req *http.Request, headerName string) (string, error) { return token, nil } -// getTokenInCookie retrieves the access token from the request cookies +// getTokenInCookie retrieves the access token from the request cookies. func GetTokenInCookie(req *http.Request, name string) (string, error) { var token bytes.Buffer @@ -125,7 +125,7 @@ func GetTokenInCookie(req *http.Request, name string) (string, error) { return token.String(), nil } -// GetIdentity retrieves the user identity from a request, either from a session cookie or a bearer token +// GetIdentity retrieves the user identity from a request, either from a session cookie or a bearer token. func GetIdentity( logger *zap.Logger, skipAuthorizationHeaderIdentity bool, @@ -177,7 +177,7 @@ func GetIdentity( } } -// ExtractIdentity parse the jwt token and extracts the various elements is order to construct +// ExtractIdentity parse the jwt token and extracts the various elements is order to construct. func ExtractIdentity(token *jwt.JSONWebToken) (*models.UserContext, error) { stdClaims := &jwt.Claims{} customClaims := models.CustClaims{} @@ -243,7 +243,7 @@ func ExtractIdentity(token *jwt.JSONWebToken) (*models.UserContext, error) { }, nil } -// retrieveRefreshToken retrieves the refresh token from store or cookie +// retrieveRefreshToken retrieves the refresh token from store or cookie. func RetrieveRefreshToken( store storage.Storage, cookieRefreshName string, @@ -270,7 +270,7 @@ func RetrieveRefreshToken( return token, encrypted, err } -// GetAccessCookieExpiration calculates the expiration of the access token cookie +// GetAccessCookieExpiration calculates the expiration of the access token cookie. func GetAccessCookieExpiration( logger *zap.Logger, accessTokenDuration time.Duration, @@ -361,7 +361,7 @@ func GetCodeFlowTokens( return resp.AccessToken, idToken, resp.RefreshToken, nil } -// exchangeAuthenticationCode exchanges the authentication code with the oauth server for a access token +// exchangeAuthenticationCode exchanges the authentication code with the oauth server for a access token. func exchangeAuthenticationCode( ctx context.Context, oConfig *oauth2.Config, diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index 641f8348..22680570 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -8,7 +8,7 @@ import ( ) // storage is used to hold the offline refresh token, assuming you don't want to use -// the default practice of a encrypted cookie +// the default practice of a encrypted cookie. type Storage interface { // Set the token to the store Set(ctx context.Context, key string, value string, expiration time.Duration) error @@ -23,7 +23,7 @@ type Storage interface { GetRefreshTokenFromStore(ctx context.Context, token string) (string, error) } -// createStorage creates the store client for use +// createStorage creates the store client for use. func CreateStorage(location string) (Storage, error) { var store Storage var err error diff --git a/pkg/storage/store_redis.go b/pkg/storage/store_redis.go index fa384b10..47bb56aa 100644 --- a/pkg/storage/store_redis.go +++ b/pkg/storage/store_redis.go @@ -30,7 +30,7 @@ type RedisStore struct { Client *redis.Client } -// newRedisStore creates a new redis store +// newRedisStore creates a new redis store. func newRedisStore(url string) (Storage, error) { opts, err := redis.ParseURL(url) if err != nil { @@ -40,7 +40,7 @@ func newRedisStore(url string) (Storage, error) { return RedisStore{Client: client}, nil } -// Set adds a token to the store +// Set adds a token to the store. func (r RedisStore) Set(ctx context.Context, key, value string, expiration time.Duration) error { if err := r.Client.Set(ctx, key, value, expiration); err.Err() != nil { return err.Err() @@ -49,7 +49,7 @@ func (r RedisStore) Set(ctx context.Context, key, value string, expiration time. return nil } -// Checks if key exists in store +// Checks if key exists in store. func (r RedisStore) Exists(ctx context.Context, key string) (bool, error) { val, err := r.Client.Exists(ctx, key).Result() if err != nil { @@ -59,7 +59,7 @@ func (r RedisStore) Exists(ctx context.Context, key string) (bool, error) { return val > 0, nil } -// Get retrieves a token from the store +// Get retrieves a token from the store. func (r RedisStore) Get(ctx context.Context, key string) (string, error) { result := r.Client.Get(ctx, key) if result.Err() != nil { @@ -69,12 +69,12 @@ func (r RedisStore) Get(ctx context.Context, key string) (string, error) { return result.Val(), nil } -// Delete remove the key +// Delete remove the key. func (r RedisStore) Delete(ctx context.Context, key string) error { return r.Client.Del(ctx, key).Err() } -// Close closes of any open resources +// Close closes of any open resources. func (r RedisStore) Close() error { if r.Client != nil { return r.Client.Close() @@ -83,7 +83,7 @@ func (r RedisStore) Close() error { return nil } -// Get retrieves a token from the store, the key we are using here is the access token +// Get retrieves a token from the store, the key we are using here is the access token. func (r RedisStore) GetRefreshTokenFromStore( ctx context.Context, token string, diff --git a/pkg/testsuite/fake_authserver.go b/pkg/testsuite/fake_authserver.go index 1a238f53..184a8473 100644 --- a/pkg/testsuite/fake_authserver.go +++ b/pkg/testsuite/fake_authserver.go @@ -103,7 +103,6 @@ func NewTestToken(issuer string) *FakeToken { return &FakeToken{Claims: claims} } -// getToken returns a JWT token from the clains func (t *FakeToken) GetToken() (string, error) { input := []byte("") block, _ := pem.Decode([]byte(fakePrivateKey)) @@ -133,7 +132,6 @@ func (t *FakeToken) GetToken() (string, error) { return jwt, nil } -// getUnsignedToken returns a unsigned JWT token from the claims func (t *FakeToken) GetUnsignedToken() (string, error) { input := []byte("") block, _ := pem.Decode([]byte(fakePrivateKey)) @@ -169,22 +167,18 @@ func (t *FakeToken) GetUnsignedToken() (string, error) { return jwt, nil } -// setExpiration sets the expiration of the token func (t *FakeToken) SetExpiration(tm time.Time) { t.Claims.Exp = tm.Unix() } -// addGroups adds groups to then token func (t *FakeToken) addGroups(groups []string) { t.Claims.Groups = groups } -// addRealmRoles adds realms roles to token func (t *FakeToken) addRealmRoles(roles []string) { t.Claims.RealmAccess.Roles = roles } -// addClientRoles adds client roles to the token func (t *FakeToken) addClientRoles(client string, roles []string) { t.Claims.ResourceAccess = make(map[string]RoleClaim) t.Claims.ResourceAccess[client] = RoleClaim{Roles: roles} @@ -300,7 +294,7 @@ type fakeAuthConfig struct { ResourceSetHandlerFailure bool } -// newFakeAuthServer simulates a oauth service +// newFakeAuthServer simulates a oauth service. func newFakeAuthServer(config *fakeAuthConfig) *fakeAuthServer { certBlock, _ := pem.Decode([]byte(fakeCert)) diff --git a/pkg/testsuite/fake_upstream.go b/pkg/testsuite/fake_upstream.go index bb73a04d..9277f492 100644 --- a/pkg/testsuite/fake_upstream.go +++ b/pkg/testsuite/fake_upstream.go @@ -12,7 +12,7 @@ import ( "golang.org/x/net/websocket" ) -// fakeUpstreamResponse is the response from fake upstream +// fakeUpstreamResponse is the response from fake upstream. type fakeUpstreamResponse struct { URI string `json:"uri"` Method string `json:"method"` @@ -21,7 +21,7 @@ type fakeUpstreamResponse struct { Body string `json:"body"` } -// FakeUpstreamService acts as a fake upstream service, returns the headers and request +// FakeUpstreamService acts as a fake upstream service, returns the headers and request. type FakeUpstreamService struct{} func (f *FakeUpstreamService) ServeHTTP(wrt http.ResponseWriter, req *http.Request) { diff --git a/pkg/testsuite/middleware_test.go b/pkg/testsuite/middleware_test.go index a1c5f66d..60e413b3 100644 --- a/pkg/testsuite/middleware_test.go +++ b/pkg/testsuite/middleware_test.go @@ -1997,7 +1997,7 @@ func TestAdmissionHandlerRoles(t *testing.T) { newFakeProxy(cfg, &fakeAuthConfig{}).RunTests(t, requests) } -// check to see if custom headers are hitting the upstream +// check to see if custom headers are hitting the upstream. func TestCustomHeaders(t *testing.T) { requests := []struct { Headers map[string]string diff --git a/pkg/utils/token.go b/pkg/utils/token.go index 69ed9450..3a38ca45 100644 --- a/pkg/utils/token.go +++ b/pkg/utils/token.go @@ -243,7 +243,6 @@ func CheckClaim( return false } -// VerifyOIDCTokens func VerifyOIDCTokens( ctx context.Context, provider *oidc3.Provider, @@ -287,7 +286,6 @@ func VerifyOIDCTokens( return oAccToken, oIDToken, nil } -// NewOAuth2Config returns a oauth2 config func NewOAuth2Config( clientID string, clientSecret string, diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 86b2f1be..0cbc8af1 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -58,7 +58,6 @@ var ( symbolsFilter = regexp.MustCompilePOSIX("[_$><\\[\\].,\\+-/'%^&*()!\\\\]+") ) -// getRequestHostURL returns the hostname from the request func GetRequestHostURL(req *http.Request) string { scheme := constant.UnsecureScheme @@ -73,7 +72,6 @@ func GetRequestHostURL(req *http.Request) string { return redirect } -// decodeKeyPairs converts a list of strings (key=pair) to a map func DecodeKeyPairs(list []string) (map[string]string, error) { keyPairs := make(map[string]string) @@ -90,7 +88,6 @@ func DecodeKeyPairs(list []string) (map[string]string, error) { return keyPairs, nil } -// IsValidHTTPMethod ensure this is a valid http method type func IsValidHTTPMethod(method string) bool { for _, x := range AllHTTPMethods { if method == x { @@ -101,7 +98,6 @@ func IsValidHTTPMethod(method string) bool { return false } -// defaultTo returns the value of the default func DefaultTo(v, d string) string { if v != "" { return v @@ -110,7 +106,6 @@ func DefaultTo(v, d string) string { return d } -// fileExists check if a file exists func FileExists(filename string) bool { if _, err := os.Stat(filename); err != nil { if os.IsNotExist(err) { @@ -121,7 +116,6 @@ func FileExists(filename string) bool { return true } -// hasAccess checks we have all or any of the needed items in the list func HasAccess(need, have []string, all bool) bool { if len(need) == 0 { return true @@ -148,7 +142,6 @@ func HasAccess(need, have []string, all bool) bool { return matched > 0 } -// containedIn checks if a value in a list of a strings func ContainedIn(value string, list []string) bool { for _, x := range list { if x == value { @@ -159,7 +152,6 @@ func ContainedIn(value string, list []string) bool { return false } -// containsSubString checks if substring exists func ContainsSubString(value string, list []string) bool { for _, x := range list { if strings.Contains(value, x) { @@ -170,7 +162,7 @@ func ContainsSubString(value string, list []string) bool { return false } -// tryDialEndpoint dials the upstream endpoint via plain HTTP +// tryDialEndpoint dials the upstream endpoint via plain HTTP. func TryDialEndpoint(location *url.URL) (net.Conn, error) { switch dialAddress := DialAddress(location); location.Scheme { case constant.UnsecureScheme: @@ -184,18 +176,17 @@ func TryDialEndpoint(location *url.URL) (net.Conn, error) { } } -// isUpgradedConnection checks to see if the request is requesting func IsUpgradedConnection(req *http.Request) bool { return req.Header.Get(constant.HeaderUpgrade) != "" } -// transferBytes transfers bytes between the sink and source +// transferBytes transfers bytes between the sink and source. func TransferBytes(src io.Reader, dest io.Writer, wg *sync.WaitGroup) (int64, error) { defer wg.Done() return io.Copy(dest, src) } -// tryUpdateConnection attempt to upgrade the connection to a http pdy stream +// tryUpdateConnection attempt to upgrade the connection to a http pdy stream. func TryUpdateConnection(req *http.Request, writer http.ResponseWriter, endpoint *url.URL) error { // step: dial the endpoint server, err := TryDialEndpoint(endpoint) @@ -238,7 +229,7 @@ func TryUpdateConnection(req *http.Request, writer http.ResponseWriter, endpoint return nil } -// dialAddress extracts the dial address from the url +// dialAddress extracts the dial address from the url. func DialAddress(location *url.URL) string { items := strings.Split(location.Host, ":") @@ -255,7 +246,6 @@ func DialAddress(location *url.URL) string { return location.Host } -// toHeader is a helper method to play nice in the headers func ToHeader(v string) string { symbols := symbolsFilter.Split(v, -1) list := make([]string, 0, len(symbols)) @@ -268,7 +258,7 @@ func ToHeader(v string) string { return strings.Join(list, "-") } -// capitalize capitalizes the first letter of a word +// capitalize capitalizes the first letter of a word. func Capitalize(word string) string { if word == "" { return "" @@ -278,7 +268,7 @@ func Capitalize(word string) string { return string(unicode.ToUpper(r)) + word[n:] } -// mergeMaps simples copies the keys from source to destination +// mergeMaps simples copies the keys from source to destination. func MergeMaps(dest, source map[string]string) map[string]string { for k, v := range source { dest[k] = v @@ -288,7 +278,7 @@ func MergeMaps(dest, source map[string]string) map[string]string { } // getWithin calculates a duration of x percent of the time period, i.e. something -// expires in 1 hours, get me a duration within 80% +// expires in 1 hours, get me a duration within 80%. func GetWithin(expires time.Time, within float64) time.Duration { left := expires.UTC().Sub(time.Now().UTC()).Seconds() @@ -301,18 +291,18 @@ func GetWithin(expires time.Time, within float64) time.Duration { return time.Duration(seconds) * time.Second } -// getHashKey returns a hash of the encodes jwt token +// getHashKey returns a hash of the encoded jwt token. func GetHashKey(token string) string { hash := sha.Sum512([]byte(token)) return base64.RawStdEncoding.EncodeToString(hash[:]) } -// printError display the command line usage and error +// printError display the command line usage and error. func PrintError(message string, args ...interface{}) cli.ExitCoder { return cli.Exit(fmt.Sprintf("[error] "+message, args...), 1) } -// realIP retrieves the client ip address from a http request +// realIP retrieves the client ip address from a http request. func RealIP(req *http.Request) string { rAddr := req.RemoteAddr @@ -351,7 +341,7 @@ func GenerateHmac(req *http.Request, encKey string) (string, error) { return hexHmac, nil } -// WithOAuthURI returns the oauth uri +// WithOAuthURI returns the oauth uri. func WithOAuthURI(baseURI string, oauthURI string) func(uri string) string { return func(uri string) string { uri = strings.TrimPrefix(uri, "/")