Skip to content

API token support #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 86 additions & 6 deletions oauthproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package main

import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -75,6 +78,10 @@ type OAuthProxy struct {
AuthOnlyPath string
UserInfoPath string

tokenKey string
tokenAuthData string
tokenRoutes []allowedRoute

allowedRoutes []allowedRoute
redirectURL *url.URL // the url to receive requests at
whitelistDomains []string
Expand Down Expand Up @@ -173,6 +180,11 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
return nil, err
}

tokenRoutes, err := buildTokenRoutesAllowlist(opts)
if err != nil {
return nil, err
}

preAuthChain, err := buildPreAuthChain(opts)
if err != nil {
return nil, fmt.Errorf("could not build pre-auth chain: %v", err)
Expand Down Expand Up @@ -204,11 +216,16 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
AuthOnlyPath: fmt.Sprintf("%s/auth", opts.ProxyPrefix),
UserInfoPath: fmt.Sprintf("%s/userinfo", opts.ProxyPrefix),

ProxyPrefix: opts.ProxyPrefix,
provider: opts.GetProvider(),
sessionStore: sessionStore,
serveMux: upstreamProxy,
redirectURL: redirectURL,
ProxyPrefix: opts.ProxyPrefix,
provider: opts.GetProvider(),
sessionStore: sessionStore,
serveMux: upstreamProxy,
redirectURL: redirectURL,

tokenKey: opts.TokenValidationKey,
tokenAuthData: opts.TokenValidationAuthData,
tokenRoutes: tokenRoutes,

allowedRoutes: allowedRoutes,
whitelistDomains: opts.WhitelistDomains,
skipAuthPreflight: opts.SkipAuthPreflight,
Expand Down Expand Up @@ -328,6 +345,25 @@ func buildProviderName(p providers.Provider, override string) string {
return p.Data().ProviderName
}

// buildTokenRoutesAllowlist builds an []allowedRoute list from either the legacy
func buildTokenRoutesAllowlist(opts *options.Options) ([]allowedRoute, error) {
routes := make([]allowedRoute, 0, len(opts.TokenValidationRegex))

for _, path := range opts.TokenValidationRegex {
compiledRegex, err := regexp.Compile(path)
if err != nil {
return nil, err
}
logger.Printf("Setting Token validation - Method: ALL | Path: %s", path)
routes = append(routes, allowedRoute{
method: "",
pathRegex: compiledRegex,
})
}

return routes, nil
}

// buildRoutesAllowlist builds an []allowedRoute list from either the legacy
// SkipAuthRegex option (paths only support) or newer SkipAuthRoutes option
// (method=path support)
Expand Down Expand Up @@ -536,7 +572,7 @@ func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code i
// IsAllowedRequest is used to check if auth should be skipped for this request
func (p *OAuthProxy) IsAllowedRequest(req *http.Request) bool {
isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == "OPTIONS"
return isPreflightRequestAllowed || p.isAllowedRoute(req) || p.isTrustedIP(req)
return isPreflightRequestAllowed || p.isAllowedRoute(req) || p.isTrustedIP(req) || p.isValidAPIToken(req)
}

// IsAllowedRoute is used to check if the request method & path is allowed without auth
Expand All @@ -549,6 +585,50 @@ func (p *OAuthProxy) isAllowedRoute(req *http.Request) bool {
return false
}

// IsAllowedRoute is used to check if the request method & path is allowed without auth
func (p *OAuthProxy) isValidAPIToken(req *http.Request) bool {
for _, route := range p.tokenRoutes {
if (route.method == "" || req.Method == route.method) && route.pathRegex.MatchString(req.URL.Path) {
authHeader := req.Header.Get("Authorization")
if len(authHeader) < 10 {
return false
}

hexToken := authHeader[5:]
token, err := hex.DecodeString(hexToken)

c, err := aes.NewCipher([]byte(p.tokenKey))
if err != nil {
return false
}

gcm, err := cipher.NewGCM(c)
if err != nil {
return false
}

nonceSize := gcm.NonceSize()
if len(token) < nonceSize {
return false
}

nonce, cipherText := token[:nonceSize], token[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, cipherText, []byte(p.tokenAuthData))
if err != nil {
return false
}

capiPayload := strings.Split(string(plaintext), ":")

req.Header.Add("X_CAPI_EMAIL", capiPayload[0])
req.Header.Add("X_CAPI_SIGNATURE", capiPayload[1])

return true
}
}
return false
}

// isTrustedIP is used to check if a request comes from a trusted client IP address.
func (p *OAuthProxy) isTrustedIP(req *http.Request) bool {
if p.trustedIPs == nil {
Expand Down
9 changes: 9 additions & 0 deletions pkg/apis/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ type Options struct {
SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify"`
SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight"`

TokenValidationKey string `flag:"token-validation-key" cfg:"token_validation_key"`
TokenValidationAuthData string `flag:"token-validation-auth-data" cfg:"token_validation_auth_data"`
TokenValidationRegex []string `flag:"token-validation-regex" cfg:"token_validation_regex"`

// These options allow for other providers besides Google, with
// potential overrides.
ProviderType string `flag:"provider" cfg:"provider"`
Expand Down Expand Up @@ -170,6 +174,11 @@ func NewFlagSet() *pflag.FlagSet {
flagSet.String("tls-cert-file", "", "path to certificate file")
flagSet.String("tls-key-file", "", "path to private key file")
flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"")

flagSet.String("token-validation-key", "", "Secret key to be used to decode api token requests")
flagSet.String("token-validation-auth-data", "", "Secret signature that will be used to verify token payload")
flagSet.StringSlice("token-validation-regex", []string{}, "Bypass regular authentication in favor of API token for requests that match the method & path.")

flagSet.StringSlice("skip-auth-regex", []string{}, "(DEPRECATED for --skip-auth-route) bypass authentication for requests path's that match (may be given multiple times)")
flagSet.StringSlice("skip-auth-route", []string{}, "bypass authentication for requests that match the method & path. Format: method=path_regex OR path_regex alone for all methods")
flagSet.Bool("skip-provider-button", false, "will skip sign-in-page to directly reach the next step: oauth/start")
Expand Down