Compare commits
25 Commits
Author | SHA1 | Date | |
---|---|---|---|
5c800a0170 | |||
b1fdcc7f56 | |||
db31b09a72 | |||
e1d518db11 | |||
67339ae79a | |||
0b2889935e | |||
b3b31e2193 | |||
1a3a099ac1 | |||
afd8878188 | |||
6ccd1c6dfc | |||
df81be1147 | |||
5dcf889efe | |||
92d72dcdd2 | |||
4c1874b786 | |||
dcf4f6574d | |||
91775ff0a8 | |||
1832672f5e | |||
eaad0a9054 | |||
36fffd2382 | |||
ccbda4ec8c | |||
b014c5638a | |||
c897bc8387 | |||
96f9469abd | |||
b54871391f | |||
d230572879 |
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@ -0,0 +1,2 @@
|
||||
example
|
||||
.travis.yml
|
@ -4,4 +4,5 @@ go:
|
||||
- "1.10"
|
||||
install:
|
||||
- go get github.com/namsral/flag
|
||||
- go get github.com/op/go-logging
|
||||
- go get github.com/sirupsen/logrus
|
||||
script: go test -v ./...
|
||||
|
@ -7,7 +7,7 @@ WORKDIR /app
|
||||
# Add libraries
|
||||
RUN apk add --no-cache git && \
|
||||
go get "github.com/namsral/flag" && \
|
||||
go get "github.com/op/go-logging" && \
|
||||
go get "github.com/sirupsen/logrus" && \
|
||||
apk del git
|
||||
|
||||
# Copy & build
|
||||
|
58
README.md
58
README.md
@ -1,5 +1,5 @@
|
||||
|
||||
# Traefik Forward Auth [](https://travis-ci.org/thomseddon/traefik-forward-auth)
|
||||
# Traefik Forward Auth [](https://travis-ci.org/thomseddon/traefik-forward-auth) [](https://goreportcard.com/badge/github.com/thomseddon/traefik-forward-auth)
|
||||
|
||||
A minimal forward authentication service that provides Google oauth based login and authentication for the traefik reverse proxy.
|
||||
|
||||
@ -24,16 +24,20 @@ The following configuration is supported:
|
||||
|-----------------------|------|-----------|
|
||||
|-client-id|string|*Google Client ID (required)|
|
||||
|-client-secret|string|*Google Client Secret (required)|
|
||||
|-secret|string|*Secret used for signing (required)|
|
||||
|-config|string|Path to config file|
|
||||
|-cookie-domains|string|Comma separated list of cookie domains|
|
||||
|-auth-host|string|Central auth login (see below)|
|
||||
|-cookie-domains|string|Comma separated list of cookie domains (see below)|
|
||||
|-cookie-name|string|Cookie Name (default "_forward_auth")|
|
||||
|-cookie-secret|string|*Cookie secret (required)|
|
||||
|-cookie-secure|bool|Use secure cookies (default true)|
|
||||
|-csrf-cookie-name|string|CSRF Cookie Name (default "_forward_auth_csrf")|
|
||||
|-direct|bool|Run in direct mode (use own hostname as oppose to <br>X-Forwarded-Host, used for testing/development)
|
||||
|-domain|string|Comma separated list of email domains to allow|
|
||||
|-whitelist|string|Comma separated list of email addresses to allow|
|
||||
|-lifetime|int|Session length in seconds (default 43200)|
|
||||
|-url-path|string|Callback URL (default "_oauth")|
|
||||
|-prompt|string|Space separated list of [OpenID prompt options](https://developers.google.com/identity/protocols/OpenIDConnect#prompt)|
|
||||
|-log-level|string|Log level: trace, debug, info, warn, error, fatal, panic (default "warn")|
|
||||
|-log-format|string|Log format: text, json, pretty (default "text")|
|
||||
|
||||
Configuration can also be supplied as environment variables (use upper case and swap `-`'s for `_`'s e.g. `-client-id` becomes `CLIENT_ID`)
|
||||
|
||||
@ -47,6 +51,19 @@ Create a new project then search for and select "Credentials" in the search bar.
|
||||
|
||||
Click, "Create Credentials" > "OAuth client ID". Select "Web Application", fill in the name of your app, skip "Authorized JavaScript origins" and fill "Authorized redirect URIs" with all the domains you will allow authentication from, appended with the `url-path` (e.g. https://app.test.com/_oauth)
|
||||
|
||||
## Usage
|
||||
|
||||
The authenticated user is set in the `X-Forwarded-User` header, to pass this on add this to the `authResponseHeaders` as shown [here](https://github.com/thomseddon/traefik-forward-auth/blob/master/example/docker-compose-dev.yml).
|
||||
|
||||
## User Restriction
|
||||
|
||||
You can restrict who can login with the following parameters:
|
||||
|
||||
* `-domain` - Use this to limit logins to a specific domain, e.g. test.com only
|
||||
* `-whitelist` - Use this to only allow specific users to login e.g. thom@test.com only
|
||||
|
||||
Note, if you pass `whitelist` then only this is checked and `domain` is effectively ignored.
|
||||
|
||||
## Cookie Domains
|
||||
|
||||
You can supply a comma separated list of cookie domains, if the host of the original request is a subdomain of any given cookie domain, the authentication cookie will set with the given domain.
|
||||
@ -55,6 +72,39 @@ For example, if cookie domain is `test.com` and a request comes in on `app1.test
|
||||
|
||||
Beware however, if using cookie domains whilst running multiple instances of traefik/traefik-forward-auth for the same domain, the cookies will clash. You can fix this by using the same `cookie-secret` in both instances, or using a different `cookie-name` on each.
|
||||
|
||||
## Operation Modes
|
||||
|
||||
#### Overlay
|
||||
|
||||
Overlay is the default operation mode, in this mode the authorisation endpoint is overlayed onto any domain. By default the `/_oauth` path is used, this can be customised using the `-url-path` option.
|
||||
|
||||
If a request comes in for `www.myapp.com/home` then the user will be redirected to the google login, following this they will be sent back to `www.myapp.com/_oauth`, where their token will be validated (this request will not be forwarded to your application). Following successful authoristion, the user will return to their originally requested url of `www.myapp.com/home`.
|
||||
|
||||
As the hostname in the `redirect_uri` is dynamically generated based on the orignal request, every hostname must be permitted in the Google OAuth console (e.g. `www.myappp.com` would need to be added in the above example)
|
||||
|
||||
#### Auth Host
|
||||
|
||||
This is an optional mode of operation that is useful when dealing with a large number of subdomains, it is activated by using the `-auth-host` config option (see [this example docker-compose.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/example/docker-compose-auth-host.yml)).
|
||||
|
||||
For example, if you have a few applications: `app1.test.com`, `app2.test.com`, `appN.test.com`, adding every domain to Google's console can become laborious.
|
||||
To utilise an auth host, permit domain level cookies by setting the cookie domain to `test.com` then set the `auth-host` to: `auth.test.com`.
|
||||
|
||||
The user flow will then be:
|
||||
|
||||
1. Request to `app10.test.com/home/page`
|
||||
2. User redirected to Google login
|
||||
3. After Google login, user is redirected to `auth.test.com/_oauth`
|
||||
4. Token, user and CSRF cookie is validated, auth cookie is set to `test.com`
|
||||
5. User is redirected to `app10.test.com/home/page`
|
||||
6. Request is allowed
|
||||
|
||||
With this setup, only `auth.test.com` must be permitted in the Google console.
|
||||
|
||||
Two criteria must be met for an `auth-host` to be used:
|
||||
|
||||
1. Request matches given `cookie-domain`
|
||||
2. `auth-host` is also subdomain of same `cookie-domain`
|
||||
|
||||
## Copyright
|
||||
|
||||
2018 Thom Seddon
|
||||
|
44
example/docker-compose-auth-host.yml
Normal file
44
example/docker-compose-auth-host.yml
Normal file
@ -0,0 +1,44 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik
|
||||
command: -c /traefik.toml --logLevel=DEBUG
|
||||
ports:
|
||||
- "8085:80"
|
||||
- "8086:8080"
|
||||
networks:
|
||||
- traefik
|
||||
volumes:
|
||||
- ./traefik.toml:/traefik.toml
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami1:
|
||||
image: emilevauge/whoami
|
||||
networks:
|
||||
- traefik
|
||||
labels:
|
||||
- "traefik.backend=whoami"
|
||||
- "traefik.enable=true"
|
||||
- "traefik.frontend.rule=Host:whoami.yourdomain.com"
|
||||
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth
|
||||
environment:
|
||||
- CLIENT_ID=your-client-id
|
||||
- CLIENT_SECRET=your-client-secret
|
||||
- SECRET=something-random
|
||||
- COOKIE_SECURE=false
|
||||
- DOMAIN=yourcompany.com
|
||||
- AUTH_HOST=auth.yourdomain.com
|
||||
networks:
|
||||
- traefik
|
||||
# When using an auth host, adding it here prompts traefik to generate certs
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.port=4181
|
||||
- traefik.backend=traefik-forward-auth
|
||||
- traefik.frontend.rule=Host:auth.yourdomain.com
|
||||
|
||||
networks:
|
||||
traefik:
|
48
example/docker-compose-dev.yml
Normal file
48
example/docker-compose-dev.yml
Normal file
@ -0,0 +1,48 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik
|
||||
command: -c /traefik.toml
|
||||
# command: -c /traefik.toml --logLevel=DEBUG
|
||||
ports:
|
||||
- "8085:80"
|
||||
- "8086:8080"
|
||||
networks:
|
||||
- traefik
|
||||
volumes:
|
||||
- ./traefik.toml:/traefik.toml
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami1:
|
||||
image: emilevauge/whoami
|
||||
networks:
|
||||
- traefik
|
||||
labels:
|
||||
- "traefik.backend=whoami1"
|
||||
- "traefik.enable=true"
|
||||
- "traefik.frontend.rule=Host:whoami.localhost.com"
|
||||
|
||||
whoami2:
|
||||
image: emilevauge/whoami
|
||||
networks:
|
||||
- traefik
|
||||
labels:
|
||||
- "traefik.backend=whoami2"
|
||||
- "traefik.enable=true"
|
||||
- "traefik.frontend.rule=Host:whoami.localhost.org"
|
||||
|
||||
traefik-forward-auth:
|
||||
build: ../
|
||||
environment:
|
||||
- CLIENT_ID=test
|
||||
- CLIENT_SECRET=test
|
||||
- COOKIE_SECRET=something-random
|
||||
- COOKIE_SECURE=false
|
||||
- COOKIE_DOMAINS=localhost.com
|
||||
- AUTH_URL=http://auth.localhost.com:8085/_oauth
|
||||
networks:
|
||||
- traefik
|
||||
|
||||
networks:
|
||||
traefik:
|
@ -22,12 +22,12 @@ services:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.frontend.rule=Host:whoami.localhost.com"
|
||||
|
||||
forward-oauth:
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth
|
||||
environment:
|
||||
- CLIENT_ID=your-client-id
|
||||
- CLIENT_SECRET=your-client-secret
|
||||
- COOKIE_SECRET=something-random
|
||||
- SECRET=something-random
|
||||
- COOKIE_SECURE=false
|
||||
- DOMAIN=yourcompany.com
|
||||
networks:
|
||||
|
@ -37,7 +37,8 @@
|
||||
address = ":80"
|
||||
|
||||
[entryPoints.http.auth.forward]
|
||||
address = "http://forward-oauth:4181"
|
||||
address = "http://traefik-forward-auth:4181"
|
||||
authResponseHeaders = ["X-Forwarded-User"]
|
||||
|
||||
################################################################
|
||||
# Traefik logs configuration
|
||||
|
130
forwardauth.go
130
forwardauth.go
@ -1,43 +1,45 @@
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"errors"
|
||||
"strings"
|
||||
"strconv"
|
||||
"net/url"
|
||||
"net/http"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Forward Auth
|
||||
type ForwardAuth struct {
|
||||
Path string
|
||||
Lifetime time.Duration
|
||||
Secret []byte
|
||||
|
||||
ClientId string
|
||||
ClientSecret string
|
||||
ClientSecret string `json:"-"`
|
||||
Scope string
|
||||
|
||||
LoginURL *url.URL
|
||||
TokenURL *url.URL
|
||||
UserURL *url.URL
|
||||
|
||||
AuthHost string
|
||||
|
||||
CookieName string
|
||||
CookieDomains []CookieDomain
|
||||
CSRFCookieName string
|
||||
CookieSecret []byte
|
||||
CookieSecure bool
|
||||
|
||||
Domain []string
|
||||
Whitelist []string
|
||||
|
||||
Direct bool
|
||||
Prompt string
|
||||
}
|
||||
|
||||
// Request Validation
|
||||
@ -82,25 +84,29 @@ func (f *ForwardAuth) ValidateCookie(r *http.Request, c *http.Cookie) (bool, str
|
||||
|
||||
// Validate email
|
||||
func (f *ForwardAuth) ValidateEmail(email string) bool {
|
||||
if len(f.Domain) > 0 {
|
||||
found := false
|
||||
if len(f.Whitelist) > 0 {
|
||||
for _, whitelist := range f.Whitelist {
|
||||
if email == whitelist {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
} else if len(f.Domain) > 0 {
|
||||
parts := strings.Split(email, "@")
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
found := false
|
||||
for _, domain := range f.Domain {
|
||||
if domain == parts[1] {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return found
|
||||
}
|
||||
|
||||
// OAuth Methods
|
||||
|
||||
@ -112,7 +118,9 @@ func (f *ForwardAuth) GetLoginURL(r *http.Request, nonce string) string {
|
||||
q.Set("client_id", fw.ClientId)
|
||||
q.Set("response_type", "code")
|
||||
q.Set("scope", fw.Scope)
|
||||
// q.Set("approval_prompt", fw.ClientId)
|
||||
if fw.Prompt != "" {
|
||||
q.Set("prompt", fw.Prompt)
|
||||
}
|
||||
q.Set("redirect_uri", f.redirectUri(r))
|
||||
q.Set("state", state)
|
||||
|
||||
@ -137,7 +145,6 @@ func (f *ForwardAuth) ExchangeCode(r *http.Request, code string) (string, error)
|
||||
form.Set("redirect_uri", f.redirectUri(r))
|
||||
form.Set("code", code)
|
||||
|
||||
|
||||
res, err := http.PostForm(fw.TokenURL.String(), form)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@ -187,12 +194,6 @@ func (f *ForwardAuth) redirectBase(r *http.Request) string {
|
||||
proto := r.Header.Get("X-Forwarded-Proto")
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
|
||||
// Direct mode
|
||||
if f.Direct {
|
||||
proto = "http"
|
||||
host = r.Host
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s://%s", proto, host)
|
||||
}
|
||||
|
||||
@ -200,19 +201,35 @@ func (f *ForwardAuth) redirectBase(r *http.Request) string {
|
||||
func (f *ForwardAuth) returnUrl(r *http.Request) string {
|
||||
path := r.Header.Get("X-Forwarded-Uri")
|
||||
|
||||
// Testing
|
||||
if f.Direct {
|
||||
path = r.URL.String()
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s%s", f.redirectBase(r), path)
|
||||
}
|
||||
|
||||
// Get oauth redirect uri
|
||||
func (f *ForwardAuth) redirectUri(r *http.Request) string {
|
||||
if use, _ := f.useAuthDomain(r); use {
|
||||
proto := r.Header.Get("X-Forwarded-Proto")
|
||||
return fmt.Sprintf("%s://%s%s", proto, f.AuthHost, f.Path)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s%s", f.redirectBase(r), f.Path)
|
||||
}
|
||||
|
||||
// Should we use auth host + what it is
|
||||
func (f *ForwardAuth) useAuthDomain(r *http.Request) (bool, string) {
|
||||
if f.AuthHost == "" {
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// Does the request match a given cookie domain?
|
||||
reqMatch, reqHost := f.matchCookieDomains(r.Header.Get("X-Forwarded-Host"))
|
||||
|
||||
// Do any of the auth hosts match a cookie domain?
|
||||
authMatch, authHost := f.matchCookieDomains(f.AuthHost)
|
||||
|
||||
// We need both to match the same domain
|
||||
return reqMatch && authMatch && reqHost == authHost, reqHost
|
||||
}
|
||||
|
||||
// Cookie methods
|
||||
|
||||
// Create an auth cookie
|
||||
@ -238,7 +255,7 @@ func (f *ForwardAuth) MakeCSRFCookie(r *http.Request, nonce string) *http.Cookie
|
||||
Name: f.CSRFCookieName,
|
||||
Value: nonce,
|
||||
Path: "/",
|
||||
Domain: f.cookieDomain(r),
|
||||
Domain: f.csrfCookieDomain(r),
|
||||
HttpOnly: true,
|
||||
Secure: f.CookieSecure,
|
||||
Expires: f.cookieExpiry(),
|
||||
@ -251,7 +268,7 @@ func (f *ForwardAuth) ClearCSRFCookie(r *http.Request) *http.Cookie {
|
||||
Name: f.CSRFCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Domain: f.cookieDomain(r),
|
||||
Domain: f.csrfCookieDomain(r),
|
||||
HttpOnly: true,
|
||||
Secure: f.CookieSecure,
|
||||
Expires: time.Now().Local().Add(time.Hour * -1),
|
||||
@ -292,27 +309,42 @@ func (f *ForwardAuth) Nonce() (error, string) {
|
||||
func (f *ForwardAuth) cookieDomain(r *http.Request) string {
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
|
||||
// Direct mode
|
||||
if f.Direct {
|
||||
host = r.Host
|
||||
}
|
||||
|
||||
// Remove port for matching
|
||||
p := strings.Split(host, ":")
|
||||
|
||||
// Check if any of the given cookie domains matches
|
||||
for _, domain := range f.CookieDomains {
|
||||
if domain.Match(p[0]) {
|
||||
return domain.Domain
|
||||
_, domain := f.matchCookieDomains(host)
|
||||
return domain
|
||||
}
|
||||
|
||||
// Cookie domain
|
||||
func (f *ForwardAuth) csrfCookieDomain(r *http.Request) string {
|
||||
var host string
|
||||
if use, domain := f.useAuthDomain(r); use {
|
||||
host = domain
|
||||
} else {
|
||||
host = r.Header.Get("X-Forwarded-Host")
|
||||
}
|
||||
|
||||
// Remove port
|
||||
p := strings.Split(host, ":")
|
||||
return p[0]
|
||||
}
|
||||
|
||||
// Return matching cookie domain if exists
|
||||
func (f *ForwardAuth) matchCookieDomains(domain string) (bool, string) {
|
||||
// Remove port
|
||||
p := strings.Split(domain, ":")
|
||||
|
||||
for _, d := range f.CookieDomains {
|
||||
if d.Match(p[0]) {
|
||||
return true, d.Domain
|
||||
}
|
||||
}
|
||||
|
||||
return p[0]
|
||||
return false, p[0]
|
||||
}
|
||||
|
||||
// Create cookie hmac
|
||||
func (f *ForwardAuth) cookieSignature(r *http.Request, email, expires string) string {
|
||||
hash := hmac.New(sha256.New, f.CookieSecret)
|
||||
hash := hmac.New(sha256.New, f.Secret)
|
||||
hash.Write([]byte(f.cookieDomain(r)))
|
||||
hash.Write([]byte(email))
|
||||
hash.Write([]byte(expires))
|
||||
@ -350,7 +382,7 @@ func (c *CookieDomain) Match(host string) bool {
|
||||
}
|
||||
|
||||
// Subdomain match?
|
||||
if len(host) >= c.SubDomainLen && host[len(host) - c.SubDomainLen:] == c.SubDomain {
|
||||
if len(host) >= c.SubDomainLen && host[len(host)-c.SubDomainLen:] == c.SubDomain {
|
||||
return true
|
||||
}
|
||||
|
||||
|
@ -1,13 +1,12 @@
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
// "fmt"
|
||||
"time"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
"net/url"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestValidateCookie(t *testing.T) {
|
||||
@ -81,9 +80,28 @@ func TestValidateEmail(t *testing.T) {
|
||||
if !fw.ValidateEmail("test@test.com") {
|
||||
t.Error("Should allow user from allowed domain")
|
||||
}
|
||||
|
||||
// Should block non whitelisted email address
|
||||
fw.Domain = []string{}
|
||||
fw.Whitelist = []string{"test@test.com"}
|
||||
if fw.ValidateEmail("one@two.com") {
|
||||
t.Error("Should not allow user not in whitelist.")
|
||||
}
|
||||
|
||||
// Should allow matching whitelisted email address
|
||||
fw.Domain = []string{}
|
||||
fw.Whitelist = []string{"test@test.com"}
|
||||
if !fw.ValidateEmail("test@test.com") {
|
||||
t.Error("Should allow user in whitelist.")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLoginURL(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "http://example.com", nil)
|
||||
r.Header.Add("X-Forwarded-Proto", "http")
|
||||
r.Header.Add("X-Forwarded-Host", "example.com")
|
||||
r.Header.Add("X-Forwarded-Uri", "/hello")
|
||||
|
||||
fw = &ForwardAuth{
|
||||
Path: "/_oauth",
|
||||
ClientId: "idtest",
|
||||
@ -95,10 +113,6 @@ func TestGetLoginURL(t *testing.T) {
|
||||
Path: "/auth",
|
||||
},
|
||||
}
|
||||
r, _ := http.NewRequest("GET", "http://example.com", nil)
|
||||
r.Header.Add("X-Forwarded-Proto", "http")
|
||||
r.Header.Add("X-Forwarded-Host", "example.com")
|
||||
r.Header.Add("X-Forwarded-Uri", "/hello")
|
||||
|
||||
// Check url
|
||||
uri, err := url.Parse(fw.GetLoginURL(r, "nonce"))
|
||||
@ -125,14 +139,146 @@ func TestGetLoginURL(t *testing.T) {
|
||||
"state": []string{"nonce:http://example.com/hello"},
|
||||
}
|
||||
if !reflect.DeepEqual(qs, expectedQs) {
|
||||
t.Error("Incorrect login query string, expected:")
|
||||
t.Error(expectedQs)
|
||||
t.Error("Got:")
|
||||
t.Error(qs)
|
||||
t.Error("Incorrect login query string:")
|
||||
qsDiff(expectedQs, qs)
|
||||
}
|
||||
|
||||
//
|
||||
// With Auth URL but no matching cookie domain
|
||||
// - will not use auth host
|
||||
//
|
||||
fw = &ForwardAuth{
|
||||
Path: "/_oauth",
|
||||
AuthHost: "auth.example.com",
|
||||
ClientId: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
Scope: "scopetest",
|
||||
LoginURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "test.com",
|
||||
Path: "/auth",
|
||||
},
|
||||
Prompt: "consent select_account",
|
||||
}
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(fw.GetLoginURL(r, "nonce"))
|
||||
if err != nil {
|
||||
t.Error("Error parsing login url:", err)
|
||||
}
|
||||
if uri.Scheme != "https" {
|
||||
t.Error("Expected login Scheme to be \"https\", got:", uri.Scheme)
|
||||
}
|
||||
if uri.Host != "test.com" {
|
||||
t.Error("Expected login Host to be \"test.com\", got:", uri.Host)
|
||||
}
|
||||
if uri.Path != "/auth" {
|
||||
t.Error("Expected login Path to be \"/auth\", got:", uri.Path)
|
||||
}
|
||||
|
||||
// Check query string
|
||||
qs = uri.Query()
|
||||
expectedQs = url.Values{
|
||||
"client_id": []string{"idtest"},
|
||||
"redirect_uri": []string{"http://example.com/_oauth"},
|
||||
"response_type": []string{"code"},
|
||||
"scope": []string{"scopetest"},
|
||||
"prompt": []string{"consent select_account"},
|
||||
"state": []string{"nonce:http://example.com/hello"},
|
||||
}
|
||||
if !reflect.DeepEqual(qs, expectedQs) {
|
||||
t.Error("Incorrect login query string:")
|
||||
qsDiff(expectedQs, qs)
|
||||
}
|
||||
|
||||
//
|
||||
// With correct Auth URL + cookie domain
|
||||
//
|
||||
cookieDomain := NewCookieDomain("example.com")
|
||||
fw = &ForwardAuth{
|
||||
Path: "/_oauth",
|
||||
AuthHost: "auth.example.com",
|
||||
ClientId: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
Scope: "scopetest",
|
||||
LoginURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "test.com",
|
||||
Path: "/auth",
|
||||
},
|
||||
CookieDomains: []CookieDomain{*cookieDomain},
|
||||
}
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(fw.GetLoginURL(r, "nonce"))
|
||||
if err != nil {
|
||||
t.Error("Error parsing login url:", err)
|
||||
}
|
||||
if uri.Scheme != "https" {
|
||||
t.Error("Expected login Scheme to be \"https\", got:", uri.Scheme)
|
||||
}
|
||||
if uri.Host != "test.com" {
|
||||
t.Error("Expected login Host to be \"test.com\", got:", uri.Host)
|
||||
}
|
||||
if uri.Path != "/auth" {
|
||||
t.Error("Expected login Path to be \"/auth\", got:", uri.Path)
|
||||
}
|
||||
|
||||
// Check query string
|
||||
qs = uri.Query()
|
||||
expectedQs = url.Values{
|
||||
"client_id": []string{"idtest"},
|
||||
"redirect_uri": []string{"http://auth.example.com/_oauth"},
|
||||
"response_type": []string{"code"},
|
||||
"scope": []string{"scopetest"},
|
||||
"state": []string{"nonce:http://example.com/hello"},
|
||||
}
|
||||
qsDiff(expectedQs, qs)
|
||||
if !reflect.DeepEqual(qs, expectedQs) {
|
||||
t.Error("Incorrect login query string:")
|
||||
qsDiff(expectedQs, qs)
|
||||
}
|
||||
|
||||
//
|
||||
// With Auth URL + cookie domain, but from different domain
|
||||
// - will not use auth host
|
||||
//
|
||||
r, _ = http.NewRequest("GET", "http://another.com", nil)
|
||||
r.Header.Add("X-Forwarded-Proto", "http")
|
||||
r.Header.Add("X-Forwarded-Host", "another.com")
|
||||
r.Header.Add("X-Forwarded-Uri", "/hello")
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(fw.GetLoginURL(r, "nonce"))
|
||||
if err != nil {
|
||||
t.Error("Error parsing login url:", err)
|
||||
}
|
||||
if uri.Scheme != "https" {
|
||||
t.Error("Expected login Scheme to be \"https\", got:", uri.Scheme)
|
||||
}
|
||||
if uri.Host != "test.com" {
|
||||
t.Error("Expected login Host to be \"test.com\", got:", uri.Host)
|
||||
}
|
||||
if uri.Path != "/auth" {
|
||||
t.Error("Expected login Path to be \"/auth\", got:", uri.Path)
|
||||
}
|
||||
|
||||
// Check query string
|
||||
qs = uri.Query()
|
||||
expectedQs = url.Values{
|
||||
"client_id": []string{"idtest"},
|
||||
"redirect_uri": []string{"http://another.com/_oauth"},
|
||||
"response_type": []string{"code"},
|
||||
"scope": []string{"scopetest"},
|
||||
"state": []string{"nonce:http://another.com/hello"},
|
||||
}
|
||||
qsDiff(expectedQs, qs)
|
||||
if !reflect.DeepEqual(qs, expectedQs) {
|
||||
t.Error("Incorrect login query string:")
|
||||
qsDiff(expectedQs, qs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// TODO
|
||||
// func TestExchangeCode(t *testing.T) {
|
||||
// }
|
||||
@ -145,9 +291,35 @@ func TestGetLoginURL(t *testing.T) {
|
||||
// func TestMakeCookie(t *testing.T) {
|
||||
// }
|
||||
|
||||
// func TestMakeCSRFCookie(t *testing.T) {
|
||||
// t.Log("TODO")
|
||||
// }
|
||||
func TestMakeCSRFCookie(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "http://app.example.com", nil)
|
||||
r.Header.Add("X-Forwarded-Host", "app.example.com")
|
||||
|
||||
// No cookie domain or auth url
|
||||
fw = &ForwardAuth{}
|
||||
c := fw.MakeCSRFCookie(r, "12345678901234567890123456789012")
|
||||
if c.Domain != "app.example.com" {
|
||||
t.Error("Cookie Domain should match request domain, got:", c.Domain)
|
||||
}
|
||||
|
||||
// With cookie domain but no auth url
|
||||
cookieDomain := NewCookieDomain("example.com")
|
||||
fw = &ForwardAuth{CookieDomains: []CookieDomain{*cookieDomain}}
|
||||
c = fw.MakeCSRFCookie(r, "12345678901234567890123456789012")
|
||||
if c.Domain != "app.example.com" {
|
||||
t.Error("Cookie Domain should match request domain, got:", c.Domain)
|
||||
}
|
||||
|
||||
// With cookie domain and auth url
|
||||
fw = &ForwardAuth{
|
||||
AuthHost: "auth.example.com",
|
||||
CookieDomains: []CookieDomain{*cookieDomain},
|
||||
}
|
||||
c = fw.MakeCSRFCookie(r, "12345678901234567890123456789012")
|
||||
if c.Domain != "example.com" {
|
||||
t.Error("Cookie Domain should match request domain, got:", c.Domain)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCSRFCookie(t *testing.T) {
|
||||
fw = &ForwardAuth{}
|
||||
|
48
log.go
Normal file
48
log.go
Normal file
@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func CreateLogger(logLevel, logFormat string) logrus.FieldLogger {
|
||||
// Setup logger
|
||||
log := logrus.StandardLogger()
|
||||
logrus.SetOutput(os.Stdout)
|
||||
|
||||
// Set logger format
|
||||
switch logFormat {
|
||||
case "pretty":
|
||||
break
|
||||
case "json":
|
||||
logrus.SetFormatter(&logrus.JSONFormatter{})
|
||||
// "text" is the default
|
||||
default:
|
||||
logrus.SetFormatter(&logrus.TextFormatter{
|
||||
DisableColors: true,
|
||||
FullTimestamp: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Set logger level
|
||||
switch logLevel {
|
||||
case "trace":
|
||||
logrus.SetLevel(logrus.TraceLevel)
|
||||
case "debug":
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
case "info":
|
||||
logrus.SetLevel(logrus.InfoLevel)
|
||||
case "error":
|
||||
logrus.SetLevel(logrus.ErrorLevel)
|
||||
case "fatal":
|
||||
logrus.SetLevel(logrus.FatalLevel)
|
||||
case "panic":
|
||||
logrus.SetLevel(logrus.PanicLevel)
|
||||
// warn is the default
|
||||
default:
|
||||
logrus.SetLevel(logrus.WarnLevel)
|
||||
}
|
||||
|
||||
return log
|
||||
}
|
116
main.go
116
main.go
@ -1,55 +1,60 @@
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
"strings"
|
||||
"net/url"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/namsral/flag"
|
||||
"github.com/op/go-logging"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Vars
|
||||
var fw *ForwardAuth;
|
||||
var log = logging.MustGetLogger("traefik-forward-auth")
|
||||
var fw *ForwardAuth
|
||||
var log logrus.FieldLogger
|
||||
|
||||
// Primary handler
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
// Logging setup
|
||||
logger := log.WithFields(logrus.Fields{
|
||||
"RemoteAddr": r.RemoteAddr,
|
||||
})
|
||||
logger.WithFields(logrus.Fields{
|
||||
"Headers": r.Header,
|
||||
}).Debugf("Handling request")
|
||||
|
||||
// Parse uri
|
||||
uri, err := url.Parse(r.Header.Get("X-Forwarded-Uri"))
|
||||
if err != nil {
|
||||
log.Error("Error parsing url")
|
||||
logger.Errorf("Error parsing X-Forwarded-Uri, %v", err)
|
||||
http.Error(w, "Service unavailable", 503)
|
||||
return
|
||||
}
|
||||
|
||||
// Direct mode
|
||||
if fw.Direct {
|
||||
uri = r.URL
|
||||
}
|
||||
|
||||
// Handle callback
|
||||
if uri.Path == fw.Path {
|
||||
handleCallback(w, r, uri.Query())
|
||||
logger.Debugf("Passing request to auth callback")
|
||||
handleCallback(w, r, uri.Query(), logger)
|
||||
return
|
||||
}
|
||||
|
||||
// Get auth cookie
|
||||
c, err := r.Cookie(fw.CookieName)
|
||||
if err != nil {
|
||||
// Error indicates no cookie, generate nonce
|
||||
err, nonce := fw.Nonce()
|
||||
if err != nil {
|
||||
log.Error("Error generating nonce")
|
||||
logger.Errorf("Error generating nonce, %v", err)
|
||||
http.Error(w, "Service unavailable", 503)
|
||||
return
|
||||
}
|
||||
|
||||
// Set the CSRF cookie
|
||||
http.SetCookie(w, fw.MakeCSRFCookie(r, nonce))
|
||||
log.Debug("Set CSRF cookie and redirecting to google login")
|
||||
logger.Debug("Set CSRF cookie and redirecting to google login")
|
||||
|
||||
// Forward them on
|
||||
http.Redirect(w, r, fw.GetLoginURL(r, nonce), http.StatusTemporaryRedirect)
|
||||
@ -60,7 +65,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
|
||||
// Validate cookie
|
||||
valid, email, err := fw.ValidateCookie(r, c)
|
||||
if !valid {
|
||||
log.Debugf("Invlaid cookie: %s", err)
|
||||
logger.Errorf("Invalid cookie: %v", err)
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
@ -68,22 +73,26 @@ func handler(w http.ResponseWriter, r *http.Request) {
|
||||
// Validate user
|
||||
valid = fw.ValidateEmail(email)
|
||||
if !valid {
|
||||
log.Debugf("Invalid email: %s", email)
|
||||
logger.WithFields(logrus.Fields{
|
||||
"email": email,
|
||||
}).Errorf("Invalid email")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
|
||||
// Valid request
|
||||
logger.Debugf("Allowing valid request ")
|
||||
w.Header().Set("X-Forwarded-User", email)
|
||||
w.WriteHeader(200)
|
||||
}
|
||||
|
||||
|
||||
// Authenticate user after they have come back from google
|
||||
func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values) {
|
||||
func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values,
|
||||
logger logrus.FieldLogger) {
|
||||
// Check for CSRF cookie
|
||||
csrfCookie, err := r.Cookie(fw.CSRFCookieName)
|
||||
if err != nil {
|
||||
log.Debug("Missing csrf cookie")
|
||||
logger.Warn("Missing csrf cookie")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
@ -92,7 +101,10 @@ func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values) {
|
||||
state := qs.Get("state")
|
||||
valid, redirect, err := fw.ValidateCSRFCookie(csrfCookie, state)
|
||||
if !valid {
|
||||
log.Debugf("Invalid oauth state, expected '%s', got '%s'\n", csrfCookie.Value, state)
|
||||
logger.WithFields(logrus.Fields{
|
||||
"csrf": csrfCookie.Value,
|
||||
"state": state,
|
||||
}).Warnf("Error validating csrf cookie: %v", err)
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
@ -103,7 +115,7 @@ func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values) {
|
||||
// Exchange code for token
|
||||
token, err := fw.ExchangeCode(r, qs.Get("code"))
|
||||
if err != nil {
|
||||
log.Debugf("Code exchange failed with: %s\n", err)
|
||||
logger.Errorf("Code exchange failed with: %v", err)
|
||||
http.Error(w, "Service unavailable", 503)
|
||||
return
|
||||
}
|
||||
@ -111,53 +123,54 @@ func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values) {
|
||||
// Get user
|
||||
user, err := fw.GetUser(token)
|
||||
if err != nil {
|
||||
log.Debugf("Error getting user: %s\n", err)
|
||||
logger.Errorf("Error getting user: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Generate cookie
|
||||
http.SetCookie(w, fw.MakeCookie(r, user.Email))
|
||||
log.Debugf("Generated auth cookie for %s\n", user.Email)
|
||||
logger.WithFields(logrus.Fields{
|
||||
"user": user.Email,
|
||||
}).Infof("Generated auth cookie")
|
||||
|
||||
// Redirect
|
||||
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
|
||||
// Main
|
||||
func main() {
|
||||
// Parse options
|
||||
flag.String(flag.DefaultConfigFlagname, "", "Path to config file")
|
||||
path := flag.String("url-path", "_oauth", "Callback URL")
|
||||
lifetime := flag.Int("lifetime", 43200, "Session length in seconds")
|
||||
secret := flag.String("secret", "", "*Secret used for signing (required)")
|
||||
authHost := flag.String("auth-host", "", "Central auth login")
|
||||
clientId := flag.String("client-id", "", "*Google Client ID (required)")
|
||||
clientSecret := flag.String("client-secret", "", "*Google Client Secret (required)")
|
||||
cookieName := flag.String("cookie-name", "_forward_auth", "Cookie Name")
|
||||
cSRFCookieName := flag.String("csrf-cookie-name", "_forward_auth_csrf", "CSRF Cookie Name")
|
||||
cookieDomainList := flag.String("cookie-domains", "", "Comma separated list of cookie domains") //todo
|
||||
cookieSecret := flag.String("cookie-secret", "", "*Cookie secret (required)")
|
||||
cookieSecret := flag.String("cookie-secret", "", "Deprecated")
|
||||
cookieSecure := flag.Bool("cookie-secure", true, "Use secure cookies")
|
||||
domainList := flag.String("domain", "", "Comma separated list of email domains to allow")
|
||||
direct := flag.Bool("direct", false, "Run in direct mode (use own hostname as oppose to X-Forwarded-Host, used for testing/development)")
|
||||
emailWhitelist := flag.String("whitelist", "", "Comma separated list of emails to allow")
|
||||
prompt := flag.String("prompt", "", "Space separated list of OpenID prompt options")
|
||||
logLevel := flag.String("log-level", "warn", "Log level: trace, debug, info, warn, error, fatal, panic")
|
||||
logFormat := flag.String("log-format", "text", "Log format: text, json, pretty")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
// Setup logger
|
||||
log = CreateLogger(*logLevel, *logFormat)
|
||||
|
||||
// Backwards compatibility
|
||||
if *secret == "" && *cookieSecret != "" {
|
||||
*secret = *cookieSecret
|
||||
}
|
||||
|
||||
// Check for show stopper errors
|
||||
err := false
|
||||
if *clientId == "" {
|
||||
err = true
|
||||
log.Critical("client-id must be set")
|
||||
}
|
||||
if *clientSecret == "" {
|
||||
err = true
|
||||
log.Critical("client-secret must be set")
|
||||
}
|
||||
if *cookieSecret == "" {
|
||||
err = true
|
||||
log.Critical("cookie-secret must be set")
|
||||
}
|
||||
if err {
|
||||
return
|
||||
if *clientId == "" || *clientSecret == "" || *secret == "" {
|
||||
log.Fatal("client-id, client-secret and secret must all be set")
|
||||
}
|
||||
|
||||
// Parse lists
|
||||
@ -173,11 +186,17 @@ func main() {
|
||||
if *domainList != "" {
|
||||
domain = strings.Split(*domainList, ",")
|
||||
}
|
||||
var whitelist []string
|
||||
if *emailWhitelist != "" {
|
||||
whitelist = strings.Split(*emailWhitelist, ",")
|
||||
}
|
||||
|
||||
// Setup
|
||||
fw = &ForwardAuth{
|
||||
Path: fmt.Sprintf("/%s", *path),
|
||||
Lifetime: time.Second * time.Duration(*lifetime),
|
||||
Secret: []byte(*secret),
|
||||
AuthHost: *authHost,
|
||||
|
||||
ClientId: *clientId,
|
||||
ClientSecret: *clientSecret,
|
||||
@ -201,17 +220,20 @@ func main() {
|
||||
CookieName: *cookieName,
|
||||
CSRFCookieName: *cSRFCookieName,
|
||||
CookieDomains: cookieDomains,
|
||||
CookieSecret: []byte(*cookieSecret),
|
||||
CookieSecure: *cookieSecure,
|
||||
|
||||
Domain: domain,
|
||||
Whitelist: whitelist,
|
||||
|
||||
Direct: *direct,
|
||||
Prompt: *prompt,
|
||||
}
|
||||
|
||||
// Attach handler
|
||||
http.HandleFunc("/", handler)
|
||||
|
||||
log.Notice("Litening on :4181")
|
||||
log.Notice(http.ListenAndServe(":4181", nil))
|
||||
// Start
|
||||
jsonConf, _ := json.Marshal(fw)
|
||||
log.Debugf("Starting with options: %s", string(jsonConf))
|
||||
log.Info("Listening on :4181")
|
||||
log.Info(http.ListenAndServe(":4181", nil))
|
||||
}
|
||||
|
51
main_test.go
51
main_test.go
@ -1,27 +1,29 @@
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
// "reflect"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"net/url"
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
/**
|
||||
* Utilities
|
||||
*/
|
||||
|
||||
type TokenServerHandler struct{}
|
||||
|
||||
type TokenServerHandler struct {}
|
||||
func (t *TokenServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"access_token":"123456789"}`)
|
||||
}
|
||||
|
||||
type UserServerHandler struct {}
|
||||
type UserServerHandler struct{}
|
||||
|
||||
func (t *UserServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{
|
||||
"id":"1",
|
||||
@ -32,8 +34,7 @@ func (t *UserServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Remove for debugging
|
||||
logging.SetLevel(logging.INFO, "traefik-forward-auth")
|
||||
log = CreateLogger("panic", "")
|
||||
}
|
||||
|
||||
func httpRequest(r *http.Request, c *http.Cookie) (*http.Response, string) {
|
||||
@ -63,6 +64,26 @@ func newHttpRequest(uri string) *http.Request {
|
||||
return r
|
||||
}
|
||||
|
||||
func qsDiff(one, two url.Values) {
|
||||
for k := range one {
|
||||
if two.Get(k) == "" {
|
||||
fmt.Printf("Key missing: %s\n", k)
|
||||
}
|
||||
if one.Get(k) != two.Get(k) {
|
||||
fmt.Printf("Value different for %s: expected: '%s' got: '%s'\n", k, one.Get(k), two.Get(k))
|
||||
}
|
||||
}
|
||||
for k := range two {
|
||||
if one.Get(k) == "" {
|
||||
fmt.Printf("Extra key: %s\n", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests
|
||||
*/
|
||||
|
||||
func TestHandler(t *testing.T) {
|
||||
fw = &ForwardAuth{
|
||||
Path: "_oauth",
|
||||
@ -122,6 +143,14 @@ func TestHandler(t *testing.T) {
|
||||
if res.StatusCode != 200 {
|
||||
t.Error("Valid request should be allowed, got:", res.StatusCode)
|
||||
}
|
||||
|
||||
// Should pass through user
|
||||
users := res.Header["X-Forwarded-User"]
|
||||
if len(users) != 1 {
|
||||
t.Error("Valid request missing X-Forwarded-User header")
|
||||
} else if users[0] != "test@example.com" {
|
||||
t.Error("X-Forwarded-User should match user, got: ", users)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallback(t *testing.T) {
|
||||
|
Reference in New Issue
Block a user