mirror of
https://github.com/thomseddon/traefik-forward-auth.git
synced 2026-02-06 22:22:15 +00:00
Compare commits
43 Commits
fix/callba
...
v2.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26e7995ea1 | ||
|
|
20cef15e7b | ||
|
|
c4317b7503 | ||
|
|
4ffb6593d5 | ||
|
|
6c6f75e80d | ||
|
|
8be8244b13 | ||
|
|
f96a3fb332 | ||
|
|
c19f622fbd | ||
|
|
04f5499f0b | ||
|
|
41560feaa7 | ||
|
|
1743537438 | ||
|
|
9e5994b959 | ||
|
|
870724c994 | ||
|
|
be2b4ba9f4 | ||
|
|
529e28d83b | ||
|
|
2937b04fdb | ||
|
|
fb8b216481 | ||
|
|
8b3a950162 | ||
|
|
655eddeaf9 | ||
|
|
c63fd738d6 | ||
|
|
00b5d9e031 | ||
|
|
8902cf8735 | ||
|
|
3345f8ec69 | ||
|
|
60604ad3db | ||
|
|
a668454a11 | ||
|
|
eec62eb03a | ||
|
|
7381450015 | ||
|
|
f7a94e7db9 | ||
|
|
f802a366de | ||
|
|
07f9587bc1 | ||
|
|
1ac0ca9732 | ||
|
|
9abf5645b7 | ||
|
|
3a66191314 | ||
|
|
c3b4ba8244 | ||
|
|
b413c60d42 | ||
|
|
e678a33016 | ||
|
|
3652a0b244 | ||
|
|
68c329901a | ||
|
|
ffa5afbf22 | ||
|
|
5a9c6adedf | ||
|
|
5dfd4f2878 | ||
|
|
a99330e6b2 | ||
|
|
5a676f3068 |
@@ -1,2 +1,3 @@
|
||||
example
|
||||
.travis.yml
|
||||
.git
|
||||
|
||||
2
.github/FUNDING.yml
vendored
Normal file
2
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
github: thomseddon
|
||||
|
||||
36
.github/workflows/ci.yml
vendored
Normal file
36
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ^1.13
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
go get -v -t -d ./...
|
||||
if [ -f Gopkg.toml ]; then
|
||||
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
|
||||
dep ensure
|
||||
fi
|
||||
|
||||
- name: Build
|
||||
run: go build -v ./...
|
||||
|
||||
- name: Test
|
||||
run: go test -v ./...
|
||||
71
.github/workflows/codeql-analysis.yml
vendored
Normal file
71
.github/workflows/codeql-analysis.yml
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [master]
|
||||
schedule:
|
||||
- cron: '0 10 * * 2'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Override automatic language detection by changing the below list
|
||||
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
|
||||
language: ['go']
|
||||
# Learn more...
|
||||
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
# We must fetch at least the immediate parents so that if this is
|
||||
# a pull request then we can checkout the head.
|
||||
fetch-depth: 2
|
||||
|
||||
# If this run was triggered by a pull request event, then checkout
|
||||
# the head of the pull request instead of the merge commit.
|
||||
- run: git checkout HEAD^2
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
||||
57
.github/workflows/release.yml
vendored
Normal file
57
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build release binaries
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ^1.13
|
||||
id: go
|
||||
|
||||
- name: Build AMD64
|
||||
run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build -a -installsuffix nocgo -v -o traefik-forward-auth_amd64 ./cmd
|
||||
|
||||
- name: Build ARM
|
||||
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm GO111MODULE=on go build -a -installsuffix nocgo -v -o traefik-forward-auth_arm ./cmd
|
||||
|
||||
- name: Get tag name
|
||||
run: echo "TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
|
||||
|
||||
- name: Get artifact details
|
||||
uses: octokit/request-action@v2.x
|
||||
id: get_release_details
|
||||
with:
|
||||
route: get /repos/${{ github.repository }}/releases/tags/${{ env.TAG }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload AMD64 release asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ fromJson(steps.get_release_details.outputs.data).upload_url }}
|
||||
asset_path: traefik-forward-auth_amd64
|
||||
asset_name: traefik-forward-auth_amd64
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Upload ARM release asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ fromJson(steps.get_release_details.outputs.data).upload_url }}
|
||||
asset_path: traefik-forward-auth_arm
|
||||
asset_name: traefik-forward-auth_arm
|
||||
asset_content_type: application/octet-stream
|
||||
@@ -1,5 +0,0 @@
|
||||
language: go
|
||||
sudo: false
|
||||
go:
|
||||
- "1.12"
|
||||
script: env GO111MODULE=on go test -v ./...
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.12-alpine as builder
|
||||
FROM golang:1.20-alpine as builder
|
||||
|
||||
# Setup
|
||||
RUN mkdir -p /go/src/github.com/thomseddon/traefik-forward-auth
|
||||
@@ -9,7 +9,7 @@ RUN apk add --no-cache git
|
||||
|
||||
# Copy & build
|
||||
ADD . /go/src/github.com/thomseddon/traefik-forward-auth/
|
||||
RUN CGO_ENABLED=0 GOOS=linux GO111MODULE=on go build -a -installsuffix nocgo -o /traefik-forward-auth github.com/thomseddon/traefik-forward-auth/cmd
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build -a -installsuffix nocgo -o /traefik-forward-auth github.com/thomseddon/traefik-forward-auth/cmd
|
||||
|
||||
# Copy into scratch container
|
||||
FROM scratch
|
||||
|
||||
18
Dockerfile.arm
Normal file
18
Dockerfile.arm
Normal file
@@ -0,0 +1,18 @@
|
||||
FROM golang:1.13-alpine as builder
|
||||
|
||||
# Setup
|
||||
RUN mkdir -p /go/src/github.com/thomseddon/traefik-forward-auth
|
||||
WORKDIR /go/src/github.com/thomseddon/traefik-forward-auth
|
||||
|
||||
# Add libraries
|
||||
RUN apk add --no-cache git
|
||||
|
||||
# Copy & build
|
||||
ADD . /go/src/github.com/thomseddon/traefik-forward-auth/
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm GO111MODULE=on go build -a -installsuffix nocgo -o /traefik-forward-auth github.com/thomseddon/traefik-forward-auth/cmd
|
||||
|
||||
# Copy into scratch container
|
||||
FROM scratch
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
COPY --from=builder /traefik-forward-auth ./
|
||||
ENTRYPOINT ["./traefik-forward-auth"]
|
||||
18
Dockerfile.arm64
Normal file
18
Dockerfile.arm64
Normal file
@@ -0,0 +1,18 @@
|
||||
FROM golang:1.13-alpine as builder
|
||||
|
||||
# Setup
|
||||
RUN mkdir -p /go/src/github.com/thomseddon/traefik-forward-auth
|
||||
WORKDIR /go/src/github.com/thomseddon/traefik-forward-auth
|
||||
|
||||
# Add libraries
|
||||
RUN apk add --no-cache git
|
||||
|
||||
# Copy & build
|
||||
ADD . /go/src/github.com/thomseddon/traefik-forward-auth/
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GO111MODULE=on go build -a -installsuffix nocgo -o /traefik-forward-auth github.com/thomseddon/traefik-forward-auth/cmd
|
||||
|
||||
# Copy into scratch container
|
||||
FROM scratch
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
COPY --from=builder /traefik-forward-auth ./
|
||||
ENTRYPOINT ["./traefik-forward-auth"]
|
||||
7
Makefile
7
Makefile
@@ -1,5 +1,8 @@
|
||||
|
||||
format:
|
||||
gofmt -w -s internal/*.go cmd/*.go
|
||||
gofmt -w -s internal/*.go internal/provider/*.go cmd/*.go
|
||||
|
||||
.PHONY: format
|
||||
test:
|
||||
go test -v ./...
|
||||
|
||||
.PHONY: format test
|
||||
|
||||
255
README.md
255
README.md
@@ -1,15 +1,16 @@
|
||||
|
||||
# Traefik Forward Auth [](https://travis-ci.org/thomseddon/traefik-forward-auth) [](https://goreportcard.com/report/github.com/thomseddon/traefik-forward-auth)  [](https://GitHub.com/thomseddon/traefik-forward-auth/releases/)
|
||||
# Traefik Forward Auth  [](https://goreportcard.com/report/github.com/thomseddon/traefik-forward-auth)  [](https://GitHub.com/thomseddon/traefik-forward-auth/releases/)
|
||||
|
||||
|
||||
A minimal forward authentication service that provides Google oauth based login and authentication for the [traefik](https://github.com/containous/traefik) reverse proxy/load balancer.
|
||||
A minimal forward authentication service that provides OAuth/SSO login and authentication for the [traefik](https://github.com/containous/traefik) reverse proxy/load balancer.
|
||||
|
||||
## Why?
|
||||
|
||||
- Seamlessly overlays any http service with a single endpoint (see: `url-path` in [Configuration](#configuration))
|
||||
- Supports multiple providers including Google and OpenID Connect (supported by Azure, Github, Salesforce etc.)
|
||||
- Supports multiple domains/subdomains by dynamically generating redirect_uri's
|
||||
- Allows authentication to be selectively applied/bypassed based on request parameters (see `rules` in [Configuration](#configuration)))
|
||||
- Supports use of centralised authentication host/redirect_uri (see `auth-host` in [Configuration](#configuration)))
|
||||
- Allows authentication to be selectively applied/bypassed based on request parameters (see `rules` in [Configuration](#configuration))
|
||||
- Supports use of centralised authentication host/redirect_uri (see `auth-host` in [Configuration](#configuration))
|
||||
- Allows authentication to persist across multiple domains (see [Cookie Domains](#cookie-domains))
|
||||
- Supports extended authentication beyond Google token lifetime (see: `lifetime` in [Configuration](#configuration))
|
||||
|
||||
@@ -19,25 +20,35 @@ A minimal forward authentication service that provides Google oauth based login
|
||||
- [Usage](#usage)
|
||||
- [Simple](#simple)
|
||||
- [Advanced](#advanced)
|
||||
- [OAuth Configuration](#oauth-configuration)
|
||||
- [Provider Setup](#provider-setup)
|
||||
- [Configuration](#configuration)
|
||||
- [Overview](#overview)
|
||||
- [Option Details](#option-details)
|
||||
- [Concepts](#concepts)
|
||||
- [Forwarded Headers](#forwarded-headers)
|
||||
- [User Restriction](#user-restriction)
|
||||
- [Applying Authentication](#applying-authentication)
|
||||
- [Global Authentication](#global-authentication)
|
||||
- [Selective Ingress Authentication in Kubernetes](#selective-ingress-authentication-in-kubernetes)
|
||||
- [Selective Container Authentication in Swarm](#selective-container-authentication-in-swarm)
|
||||
- [Rules Based Authentication](#rules-based-authentication)
|
||||
- [Operation Modes](#operation-modes)
|
||||
- [Overlay Mode](#overlay-mode)
|
||||
- [Auth Host Mode](#auth-host-mode)
|
||||
- [Logging Out](#logging-out)
|
||||
- [Copyright](#copyright)
|
||||
- [License](#license)
|
||||
|
||||
## Releases
|
||||
|
||||
We recommend using the `2` tag on docker hub.
|
||||
We recommend using the `2` tag on docker hub (`thomseddon/traefik-forward-auth:2`).
|
||||
|
||||
You can also use the latest incremental releases found on [docker hub](https://hub.docker.com/r/thomseddon/traefik-forward-auth/tags) and [github](https://github.com/thomseddon/traefik-forward-auth/releases).
|
||||
|
||||
ARM releases are also available on docker hub, just append `-arm` or `-arm64` to your desired released (e.g. `2-arm` or `2.1-arm64`).
|
||||
|
||||
We also build binary files for usage without docker starting with releases after 2.2.0 You can find these as assets of the specific GitHub release.
|
||||
|
||||
#### Upgrade Guide
|
||||
|
||||
v2 was released in June 2019, whilst this is fully backwards compatible, a number of configuration options were modified, please see the [upgrade guide](https://github.com/thomseddon/traefik-forward-auth/wiki/v2-Upgrade-Guide) to prevent warnings on startup and ensure you are using the current configuration.
|
||||
@@ -46,7 +57,7 @@ v2 was released in June 2019, whilst this is fully backwards compatible, a numbe
|
||||
|
||||
#### Simple:
|
||||
|
||||
See below for instructions on how to setup your [OAuth Configuration](#oauth-configuration).
|
||||
See below for instructions on how to setup your [Provider Setup](#provider-setup).
|
||||
|
||||
docker-compose.yml:
|
||||
|
||||
@@ -55,50 +66,43 @@ version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik:1.7
|
||||
image: traefik:v2.2
|
||||
command: --providers.docker
|
||||
ports:
|
||||
- "8085:80"
|
||||
volumes:
|
||||
- ./traefik.toml:/traefik.toml
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth:2
|
||||
environment:
|
||||
- CLIENT_ID=your-client-id
|
||||
- CLIENT_SECRET=your-client-secret
|
||||
- PROVIDERS_GOOGLE_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_GOOGLE_CLIENT_SECRET=your-client-secret
|
||||
- SECRET=something-random
|
||||
- INSECURE_COOKIE=true # Example assumes no https, do not use in production
|
||||
labels:
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.address=http://traefik-forward-auth:4181"
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.authResponseHeaders=X-Forwarded-User"
|
||||
- "traefik.http.services.traefik-forward-auth.loadbalancer.server.port=4181"
|
||||
|
||||
whoami:
|
||||
image: emilevauge/whoami:latest
|
||||
image: containous/whoami
|
||||
labels:
|
||||
- "traefik.frontend.rule=Host:whoami.mycompany.com"
|
||||
```
|
||||
|
||||
traefik.toml:
|
||||
|
||||
```toml
|
||||
[entryPoints]
|
||||
[entryPoints.http]
|
||||
address = ":80"
|
||||
|
||||
[entryPoints.http.auth.forward]
|
||||
address = "http://traefik-forward-auth:4181"
|
||||
authResponseHeaders = ["X-Forwarded-User"]
|
||||
|
||||
[docker]
|
||||
endpoint = "unix:///var/run/docker.sock"
|
||||
network = "traefik"
|
||||
- "traefik.http.routers.whoami.rule=Host(`whoami.mycompany.com`)"
|
||||
- "traefik.http.routers.whoami.middlewares=traefik-forward-auth"
|
||||
```
|
||||
|
||||
#### Advanced:
|
||||
|
||||
Please see the examples directory for a more complete [docker-compose.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/docker-compose.yml) and full [traefik.toml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik.toml).
|
||||
Please see the examples directory for a more complete [docker-compose.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik-v2/swarm/docker-compose.yml) or [kubernetes/simple-separate-pod](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik-v2/kubernetes/simple-separate-pod/).
|
||||
|
||||
Also in the examples directory is [docker-compose-auth-host.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/docker-compose-auth-host.yml) which shows how to configure a central auth host, along with some other options.
|
||||
Also in the examples directory is [docker-compose-auth-host.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik-v2/swarm/docker-compose-auth-host.yml) and [kubernetes/advanced-separate-pod](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik-v2/kubernetes/advanced-separate-pod/) which shows how to configure a central auth host, along with some other options.
|
||||
|
||||
#### OAuth Configuration
|
||||
#### Provider Setup
|
||||
|
||||
Below are some general notes on provider setup, specific instructions and examples for a number of providers can be found on the [Provider Setup](https://github.com/thomseddon/traefik-forward-auth/wiki/Provider-Setup) wiki page.
|
||||
|
||||
##### Google
|
||||
|
||||
Head to https://console.developers.google.com and make sure you've switched to the correct email account.
|
||||
|
||||
@@ -106,6 +110,33 @@ 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)
|
||||
|
||||
You must set the `providers.google.client-id` and `providers.google.client-secret` config options.
|
||||
|
||||
##### OpenID Connect
|
||||
|
||||
Any provider that supports OpenID Connect 1.0 can be configured via the OIDC config options below.
|
||||
|
||||
You must set the `providers.oidc.issuer-url`, `providers.oidc.client-id` and `providers.oidc.client-secret` config options.
|
||||
|
||||
Please see the [Provider Setup](https://github.com/thomseddon/traefik-forward-auth/wiki/Provider-Setup) wiki page for examples.
|
||||
|
||||
##### Generic OAuth2
|
||||
|
||||
For providers that don't support OpenID Connect, we also have the Generic OAuth2 provider where you can statically configure the OAuth2 and "user" endpoints.
|
||||
|
||||
You must set:
|
||||
- `providers.generic-oauth.auth-url` - URL the client should be sent to authenticate the authenticate
|
||||
- `providers.generic-oauth.token-url` - URL the service should call to exchange an auth code for an access token
|
||||
- `providers.generic-oauth.user-url` - URL used to retrieve user info (service makes a GET request)
|
||||
- `providers.generic-oauth.client-id` - Client ID
|
||||
- `providers.generic-oauth.client-secret` - Client Secret
|
||||
|
||||
You can also set:
|
||||
- `providers.generic-oauth.scope`- Any scopes that should be included in the request (default: profile, email)
|
||||
- `providers.generic-oauth.token-style` - How token is presented when querying the User URL. Can be `header` or `query`, defaults to `header`. With `header` the token is provided in an Authorization header, with query the token is provided in the `access_token` query string value.
|
||||
|
||||
Please see the [Provider Setup](https://github.com/thomseddon/traefik-forward-auth/wiki/Provider-Setup) wiki page for examples.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Overview
|
||||
@@ -126,18 +157,38 @@ Application Options:
|
||||
--cookie-name= Cookie Name (default: _forward_auth) [$COOKIE_NAME]
|
||||
--csrf-cookie-name= CSRF Cookie Name (default: _forward_auth_csrf) [$CSRF_COOKIE_NAME]
|
||||
--default-action=[auth|allow] Default action (default: auth) [$DEFAULT_ACTION]
|
||||
--default-provider=[google|oidc|generic-oauth] Default provider (default: google) [$DEFAULT_PROVIDER]
|
||||
--domain= Only allow given email domains, can be set multiple times [$DOMAIN]
|
||||
--lifetime= Lifetime in seconds (default: 43200) [$LIFETIME]
|
||||
--logout-redirect= URL to redirect to following logout [$LOGOUT_REDIRECT]
|
||||
--url-path= Callback URL Path (default: /_oauth) [$URL_PATH]
|
||||
--secret= Secret used for signing (required) [$SECRET]
|
||||
--whitelist= Only allow given email addresses, can be set multiple times [$WHITELIST]
|
||||
--rules.<name>.<param>= Rule definitions, param can be: "action" or "rule"
|
||||
--port= Port to listen on (default: 4181) [$PORT]
|
||||
--rule.<name>.<param>= Rule definitions, param can be: "action", "rule" or "provider"
|
||||
|
||||
Google Provider:
|
||||
--providers.google.client-id= Client ID [$PROVIDERS_GOOGLE_CLIENT_ID]
|
||||
--providers.google.client-secret= Client Secret [$PROVIDERS_GOOGLE_CLIENT_SECRET]
|
||||
--providers.google.prompt= Space separated list of OpenID prompt options [$PROVIDERS_GOOGLE_PROMPT]
|
||||
|
||||
OIDC Provider:
|
||||
--providers.oidc.issuer-url= Issuer URL [$PROVIDERS_OIDC_ISSUER_URL]
|
||||
--providers.oidc.client-id= Client ID [$PROVIDERS_OIDC_CLIENT_ID]
|
||||
--providers.oidc.client-secret= Client Secret [$PROVIDERS_OIDC_CLIENT_SECRET]
|
||||
--providers.oidc.resource= Optional resource indicator [$PROVIDERS_OIDC_RESOURCE]
|
||||
|
||||
Generic OAuth2 Provider:
|
||||
--providers.generic-oauth.auth-url= Auth/Login URL [$PROVIDERS_GENERIC_OAUTH_AUTH_URL]
|
||||
--providers.generic-oauth.token-url= Token URL [$PROVIDERS_GENERIC_OAUTH_TOKEN_URL]
|
||||
--providers.generic-oauth.user-url= URL used to retrieve user info [$PROVIDERS_GENERIC_OAUTH_USER_URL]
|
||||
--providers.generic-oauth.client-id= Client ID [$PROVIDERS_GENERIC_OAUTH_CLIENT_ID]
|
||||
--providers.generic-oauth.client-secret= Client Secret [$PROVIDERS_GENERIC_OAUTH_CLIENT_SECRET]
|
||||
--providers.generic-oauth.scope= Scopes (default: profile, email) [$PROVIDERS_GENERIC_OAUTH_SCOPE]
|
||||
--providers.generic-oauth.token-style=[header|query] How token is presented when querying the User URL (default: header)
|
||||
[$PROVIDERS_GENERIC_OAUTH_TOKEN_STYLE]
|
||||
--providers.generic-oauth.resource= Optional resource indicator [$PROVIDERS_GENERIC_OAUTH_RESOURCE]
|
||||
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
```
|
||||
@@ -210,6 +261,12 @@ All options can be supplied in any of the following ways, in the following prece
|
||||
|
||||
Default: `auth` (i.e. all requests require authentication)
|
||||
|
||||
- `default-provider`
|
||||
|
||||
Set the default provider to use for authentication, this can be overridden within [rules](#rules). Valid options are currently `google` or `oidc`.
|
||||
|
||||
Default: `google`
|
||||
|
||||
- `domain`
|
||||
|
||||
When set, only users matching a given domain will be permitted to access.
|
||||
@@ -224,6 +281,20 @@ All options can be supplied in any of the following ways, in the following prece
|
||||
|
||||
Default: `43200` (12 hours)
|
||||
|
||||
- `logout-redirect`
|
||||
|
||||
When set, users will be redirected to this URL following logout.
|
||||
|
||||
- `match-whitelist-or-domain`
|
||||
|
||||
When enabled, users will be permitted if they match *either* the `whitelist` or `domain` parameters.
|
||||
|
||||
This will be enabled by default in v3, but is disabled by default in v2 to maintain backwards compatibility.
|
||||
|
||||
Default: `false`
|
||||
|
||||
For more details, please also read [User Restriction](#user-restriction) in the concepts section.
|
||||
|
||||
- `url-path`
|
||||
|
||||
Customise the path that this service uses to handle the callback following authentication.
|
||||
@@ -244,7 +315,7 @@ All options can be supplied in any of the following ways, in the following prece
|
||||
|
||||
For more details, please also read [User Restriction](#user-restriction) in the concepts section.
|
||||
|
||||
- `rules`
|
||||
- `rule`
|
||||
|
||||
Specify selective authentication rules. Rules are specified in the following format: `rule.<name>.<param>=<value>`
|
||||
|
||||
@@ -253,6 +324,10 @@ All options can be supplied in any of the following ways, in the following prece
|
||||
- `action` - same usage as [`default-action`](#default-action), supported values:
|
||||
- `auth` (default)
|
||||
- `allow`
|
||||
- `domains` - optional, same usage as [`domain`](#domain)
|
||||
- `provider` - same usage as [`default-provider`](#default-provider), supported values:
|
||||
- `google`
|
||||
- `oidc`
|
||||
- `rule` - a rule to match a request, this uses traefik's v2 rule parser for which you can find the documentation here: https://docs.traefik.io/v2.0/routing/routers/#rule, supported values are summarised here:
|
||||
- ``Headers(`key`, `value`)``
|
||||
- ``HeadersRegexp(`key`, `regexp`)``
|
||||
@@ -262,17 +337,30 @@ All options can be supplied in any of the following ways, in the following prece
|
||||
- ``Path(`path`, `/articles/{category}/{id:[0-9]+}`, ...)``
|
||||
- ``PathPrefix(`/products/`, `/articles/{category}/{id:[0-9]+}`)``
|
||||
- ``Query(`foo=bar`, `bar=baz`)``
|
||||
- `whitelist` - optional, same usage as whitelist`](#whitelist)
|
||||
|
||||
For example:
|
||||
```
|
||||
# Allow requests that being with `/api/public` and contain the `Content-Type` header with a value of `application/json`
|
||||
rule.1.action = allow
|
||||
rule.1.rule = PathPrefix(`/api/public`) && Headers(`Content-Type`, `application/json`)
|
||||
|
||||
# Allow requests that have the exact path `/public`
|
||||
rule.two.action = allow
|
||||
rule.two.rule = Path(`/public`)
|
||||
|
||||
# Use OpenID Connect provider (must be configured) for requests that begin with `/github`
|
||||
rule.oidc.action = auth
|
||||
rule.oidc.provider = oidc
|
||||
rule.oidc.rule = PathPrefix(`/github`)
|
||||
|
||||
# Allow jane@example.com to `/janes-eyes-only`
|
||||
rule.two.action = allow
|
||||
rule.two.rule = Path(`/janes-eyes-only`)
|
||||
rule.two.whitelist = jane@example.com
|
||||
```
|
||||
|
||||
In the above example, the first rule would allow requests that begin with `/api/public` and contain the `Content-Type` header with a value of `application/json`. It would also allow requests that had the exact path `/public`.
|
||||
Note: It is possible to break your redirect flow with rules, please be careful not to create an `allow` rule that matches your redirect_uri unless you know what you're doing. This limitation is being tracked in in #101 and the behaviour will change in future releases.
|
||||
|
||||
## Concepts
|
||||
|
||||
@@ -283,17 +371,96 @@ 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.
|
||||
Note, if you pass both `whitelist` and `domain`, then the default behaviour is for only `whitelist` to be used and `domain` will be effectively ignored. You can allow users matching *either* `whitelist` or `domain` by passing the `match-whitelist-or-domain` parameter (this will be the default behaviour in v3). If you set `domains` or `whitelist` on a rule, the global configuration is ignored.
|
||||
|
||||
### Forwarded Headers
|
||||
|
||||
The authenticated user is set in the `X-Forwarded-User` header, to pass this on add this to the `authResponseHeaders` config option in traefik, as shown [here](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/docker-compose-dev.yml).
|
||||
The authenticated user is set in the `X-Forwarded-User` header, to pass this on add this to the `authResponseHeaders` config option in traefik, as shown below in the [Applying Authentication](#applying-authentication) section.
|
||||
|
||||
### Applying Authentication
|
||||
|
||||
Authentication can be applied in a variety of ways, either globally across all requests, or selectively to specific containers/ingresses.
|
||||
|
||||
#### Global Authentication
|
||||
|
||||
This can be achieved by enabling forward authentication for an entire entrypoint, for example, with http only:
|
||||
|
||||
```ini
|
||||
--entryPoints.http.address=:80
|
||||
--entrypoints.http.http.middlewares=traefik-forward-auth # "default-traefik-forward-auth" on kubernetes
|
||||
```
|
||||
|
||||
Or https:
|
||||
|
||||
```ini
|
||||
--entryPoints.http.address=:80
|
||||
--entryPoints.http.http.redirections.entryPoint.to=https
|
||||
--entryPoints.http.http.redirections.entryPoint.scheme=https
|
||||
--entryPoints.https.address=:443
|
||||
--entrypoints.https.http.middlewares=traefik-forward-auth # "default-traefik-forward-auth" on kubernetes
|
||||
```
|
||||
|
||||
Note: Traefik prepends the namespace to the name of middleware defined via a kubernetes resource. This is handled automatically when referencing the middleware from another resource in the same namespace (so the namespace does not need to be prepended when referenced). However the full name, including the namespace, must be used when referenced from static configuration (e.g. command arguments or config file), hence you must prepend the namespace to your traefik-forward-auth middleware reference, as shown in the comments above (e.g. `default-traefik-forward-auth` if your middleware is named `traefik-forward-auth` and is defined in the `default` namespace).
|
||||
|
||||
#### Selective Ingress Authentication in Kubernetes
|
||||
|
||||
If you choose not to enable forward authentication for a specific entrypoint, you can apply the middleware to selected ingressroutes:
|
||||
|
||||
```yaml
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
entryPoints:
|
||||
- http
|
||||
routes:
|
||||
- match: Host(`whoami.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: whoami
|
||||
port: 80
|
||||
middlewares:
|
||||
- name: traefik-forward-auth
|
||||
```
|
||||
|
||||
See the examples directory for more examples.
|
||||
|
||||
#### Selective Container Authentication in Swarm
|
||||
|
||||
You can apply labels to selected containers:
|
||||
|
||||
```yaml
|
||||
whoami:
|
||||
image: containous/whoami
|
||||
labels:
|
||||
- "traefik.http.routers.whoami.rule=Host(`whoami.example.com`)"
|
||||
- "traefik.http.routers.whoami.middlewares=traefik-forward-auth"
|
||||
```
|
||||
|
||||
See the examples directory for more examples.
|
||||
|
||||
#### Rules Based Authentication
|
||||
|
||||
You can also leverage the `rules` config to selectively apply authentication via traefik-forward-auth. For example if you enabled global authentication by enabling forward authentication for an entire entrypoint, you can still exclude some patterns from requiring authentication:
|
||||
|
||||
```ini
|
||||
# Allow requests to 'dash.example.com'
|
||||
rule.1.action = allow
|
||||
rule.1.rule = Host(`dash.example.com`)
|
||||
|
||||
# Allow requests to `app.example.com/public`
|
||||
rule.two.action = allow
|
||||
rule.two.rule = Host(`app.example.com`) && Path(`/public`)
|
||||
```
|
||||
|
||||
### Operation Modes
|
||||
|
||||
#### Overlay Mode
|
||||
|
||||
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.
|
||||
Overlay is the default operation mode, in this mode the authorisation endpoint is overlaid onto any domain. By default the `/_oauth` path is used, this can be customised using the `url-path` option.
|
||||
|
||||
The user flow will be:
|
||||
|
||||
@@ -308,7 +475,7 @@ As the hostname in the `redirect_uri` is dynamically generated based on the orig
|
||||
|
||||
#### Auth Host Mode
|
||||
|
||||
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/examples/docker-compose-auth-host.yml)).
|
||||
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/examples/traefik-v2/swarm/docker-compose-auth-host.yml) or [this kubernetes example](https://github.com/thomseddon/traefik-forward-auth/tree/master/examples/traefik-v2/kubernetes/advanced-separate-pod)).
|
||||
|
||||
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`.
|
||||
@@ -329,7 +496,15 @@ 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`
|
||||
|
||||
Please note: For Auth Host mode to work, you must ensure that requests to your auth-host are routed to the traefik-forward-auth container, as demonstrated with the service labels in the [docker-compose-auth.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/docker-compose-auth-host.yml) example.
|
||||
Please note: For Auth Host mode to work, you must ensure that requests to your auth-host are routed to the traefik-forward-auth container, as demonstrated with the service labels in the [docker-compose-auth.yml](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik-v2/swarm/docker-compose-auth-host.yml) example and the [ingressroute resource](https://github.com/thomseddon/traefik-forward-auth/blob/master/examples/traefik-v2/kubernetes/advanced-separate-pod/traefik-forward-auth/ingress.yaml) in a kubernetes example.
|
||||
|
||||
### Logging Out
|
||||
|
||||
The service provides an endpoint to clear a users session and "log them out". The path is created by appending `/logout` to your configured `path` and so with the default settings it will be: `/_oauth/logout`.
|
||||
|
||||
You can use the `logout-redirect` config option to redirect users to another URL following logout (note: the user will not have a valid auth cookie after being logged out).
|
||||
|
||||
Note: This only clears the auth cookie from the users browser and as this service is stateless, it does not invalidate the cookie against future use. So if the cookie was recorded, for example, it could continue to be used for the duration of the cookie lifetime.
|
||||
|
||||
## Copyright
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
internal "github.com/thomseddon/traefik-forward-auth/internal"
|
||||
@@ -24,7 +25,7 @@ func main() {
|
||||
http.HandleFunc("/", server.RootHandler)
|
||||
|
||||
// Start
|
||||
log.Debugf("Starting with options: %s", config)
|
||||
log.Info("Listening on :4181")
|
||||
log.Info(http.ListenAndServe(":4181", nil))
|
||||
log.WithField("config", config).Debug("Starting with config")
|
||||
log.Infof("Listening on :%d", config.Port)
|
||||
log.Info(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil))
|
||||
}
|
||||
|
||||
10
examples/traefik-v1.7/kubernetes/README.md
Normal file
10
examples/traefik-v1.7/kubernetes/README.md
Normal file
@@ -0,0 +1,10 @@
|
||||
|
||||
# Kubernetes
|
||||
|
||||
These examples show how to deploy traefik-forward-auth alongside traefik v1.7.
|
||||
|
||||
The "seperate pod" examples show traefik-forward-auth in it's own pod and leave the deployment of traefik as an exercise for the user (e.g. if using helm).
|
||||
|
||||
The "single pod" examples show traefik and traefik-forward-auth in a single pod.
|
||||
|
||||
Please see the README's in each example for more details.
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
# Kubernetes - Advanced Separate Pod Example
|
||||
|
||||
This is an advanced example of how to deploy traefik-forward-auth in it's own pod. This example is a good starting point for those who already have traefik deployed (e.g. using helm).
|
||||
|
||||
This example uses [Selective Authentication](https://github.com/thomseddon/traefik-forward-auth/blob/master/README.md#selective-ingress-authentication-in-kubernetes) to selectively apply forward authentication to each selective ingress, a simple example "whoami" application (deployment, service and ingress) is included for completeness.
|
||||
|
||||
This example leverages kustomise to define Secrets and ConfigMaps, example deployment:
|
||||
|
||||
```
|
||||
# Deploy traefik-forward-auth
|
||||
kubectl apply -k traefik-forward-auth
|
||||
|
||||
# Deploy example whoami app
|
||||
kubectl apply -k whoami
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
bases:
|
||||
- traefik-forward-auth
|
||||
- whoami
|
||||
@@ -0,0 +1,68 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: traefik-forward-auth
|
||||
strategy:
|
||||
type: Recreate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 60
|
||||
containers:
|
||||
- image: thomseddon/traefik-forward-auth:2
|
||||
name: traefik-forward-auth
|
||||
ports:
|
||||
- containerPort: 4181
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: CONFIG
|
||||
value: "/config"
|
||||
- name: DOMAIN
|
||||
value: "example.com"
|
||||
# INSECURE_COOKIE is required unless using https entrypoint
|
||||
- name: INSECURE_COOKIE
|
||||
value: "true"
|
||||
# Remove COOKIE_DOMAIN if not using auth host mode
|
||||
- name: COOKIE_DOMAIN
|
||||
value: "example.com"
|
||||
# Remove AUTH_HOST if not using auth host mode
|
||||
- name: AUTH_HOST
|
||||
value: "auth.example.com"
|
||||
- name: LOG_LEVEL
|
||||
value: "info"
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-id
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-secret
|
||||
- name: SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: secret
|
||||
volumeMounts:
|
||||
- name: configs
|
||||
mountPath: /config
|
||||
subPath: traefik-forward-auth.ini
|
||||
|
||||
volumes:
|
||||
- name: configs
|
||||
configMap:
|
||||
name: configs
|
||||
- name: traefik-forward-auth-secrets
|
||||
secret:
|
||||
secretName: secrets
|
||||
@@ -0,0 +1,22 @@
|
||||
#
|
||||
# NOTE: This is only needed if you are using auth-host mode
|
||||
#
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: traefik
|
||||
ingress.kubernetes.io/auth-type: forward
|
||||
ingress.kubernetes.io/auth-url: http://traefik-forward-auth:4181
|
||||
ingress.kubernetes.io/auth-response-headers: X-Forwarded-User
|
||||
spec:
|
||||
rules:
|
||||
- host: auth.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: traefik-forward-auth
|
||||
servicePort: auth-http
|
||||
@@ -0,0 +1,22 @@
|
||||
commonLabels:
|
||||
app: traefik-forward-auth
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml # Only needed for auth-host mode
|
||||
|
||||
#
|
||||
# Configs
|
||||
#
|
||||
configMapGenerator:
|
||||
- name: configs
|
||||
files:
|
||||
- traefik-forward-auth.ini
|
||||
|
||||
#
|
||||
# Secrets
|
||||
#
|
||||
secretGenerator:
|
||||
- name: traefik-forward-auth-secrets
|
||||
env: traefik-forward-auth.env
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik-forward-auth
|
||||
ports:
|
||||
- name: auth-http
|
||||
port: 4181
|
||||
targetPort: 4181
|
||||
@@ -0,0 +1,3 @@
|
||||
google-client-id=client-id
|
||||
google-client-secret=client-secret
|
||||
secret=something-random
|
||||
@@ -0,0 +1,8 @@
|
||||
rule.example_public.action=allow
|
||||
rule.example_public.rule=Host("stats.example.com") && PathPrefix("/api/public")
|
||||
|
||||
rule.example_api.action=allow
|
||||
rule.example_api.rule=Host("api.example.com") && Headers("X-API-Authorization", "a-long-api-key")
|
||||
|
||||
rule.example_api_query.action=allow
|
||||
rule.example_api_query.rule=Host("api.example.com") && && Query("api_key=a-long-api-key")
|
||||
@@ -0,0 +1,19 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: whoami
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
containers:
|
||||
- image: containous/whoami
|
||||
name: whoami
|
||||
@@ -0,0 +1,19 @@
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: traefik
|
||||
ingress.kubernetes.io/auth-type: forward
|
||||
ingress.kubernetes.io/auth-url: http://traefik-forward-auth:4181
|
||||
ingress.kubernetes.io/auth-response-headers: X-Forwarded-User
|
||||
spec:
|
||||
rules:
|
||||
- host: whoami.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: whoami
|
||||
servicePort: http
|
||||
@@ -0,0 +1,7 @@
|
||||
commonLabels:
|
||||
app: whoami
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
selector:
|
||||
app: whoami
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
|
||||
# Kubernetes - Advanced Single Pod Example
|
||||
|
||||
This is an advanced example of how to deploy traefik and traefik-forward-auth in a single pod. This example is a good starting point for those who already have a manually defined traefik config (e.g. not using helm).
|
||||
|
||||
This example uses [Global Authentication](https://github.com/thomseddon/traefik-forward-auth/blob/master/README.md#global-authentication) to apply authentication for the entire `https` entrypoint.
|
||||
|
||||
This example also includes SSL via traefik acme/lesencrypt, auth host mode, exposes the traefik dashboard and leverages kustomise. No special config if required for your applications, but a simple example "whoami" application (deployment, service and ingress) is included for completeness.
|
||||
|
||||
Example deployment:
|
||||
|
||||
```
|
||||
# Deploy traefik+traefik-forward-auth
|
||||
kubectl apply -k traefik
|
||||
|
||||
# Deploy whoami app
|
||||
kubectl apply -k whoami
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
bases:
|
||||
- traefik
|
||||
- whoami
|
||||
@@ -0,0 +1,8 @@
|
||||
rule.example_public.action=allow
|
||||
rule.example_public.rule=Host("stats.example.com") && PathPrefix("/api/public")
|
||||
|
||||
rule.example_api.action=allow
|
||||
rule.example_api.rule=Host("api.example.com") && Headers("X-API-Authorization", "a-long-api-key")
|
||||
|
||||
rule.example_api_query.action=allow
|
||||
rule.example_api_query.rule=Host("api.example.com") && && Query("api_key=a-long-api-key")
|
||||
@@ -0,0 +1,169 @@
|
||||
################################################################
|
||||
# Global configuration
|
||||
################################################################
|
||||
|
||||
# Enable debug mode
|
||||
#
|
||||
# Optional
|
||||
# Default: false
|
||||
#
|
||||
# debug = true
|
||||
|
||||
# Log level
|
||||
#
|
||||
# Optional
|
||||
# Default: "ERROR"
|
||||
#
|
||||
logLevel = "INFO"
|
||||
|
||||
# Entrypoints to be used by frontends that do not specify any entrypoint.
|
||||
# Each frontend can specify its own entrypoints.
|
||||
#
|
||||
# Optional
|
||||
# Default: ["http"]
|
||||
#
|
||||
defaultEntryPoints = ["http", "https"]
|
||||
|
||||
# If set to true invalid SSL certificates are accepted for backends.
|
||||
# This disables detection of man-in-the-middle attacks so should only be used on secure backend networks.
|
||||
#
|
||||
# Optional
|
||||
# Default: false
|
||||
#
|
||||
insecureSkipVerify = true
|
||||
|
||||
################################################################
|
||||
# Entrypoints configuration
|
||||
################################################################
|
||||
|
||||
# Entrypoints definition
|
||||
#
|
||||
# Optional
|
||||
# Default:
|
||||
[entryPoints]
|
||||
[entryPoints.http]
|
||||
address = ":80"
|
||||
compress = true
|
||||
|
||||
[entryPoints.http.redirect]
|
||||
entryPoint = "https"
|
||||
|
||||
[entryPoints.https]
|
||||
address = ":443"
|
||||
compress = true
|
||||
|
||||
[entryPoints.https.tls]
|
||||
|
||||
[entryPoints.https.auth.forward]
|
||||
address = "http://127.0.0.1:4181"
|
||||
authResponseHeaders = ["X-Forwarded-User"]
|
||||
|
||||
[entryPoints.traefik]
|
||||
address = ":8080"
|
||||
|
||||
################################################################
|
||||
# Traefik logs configuration
|
||||
################################################################
|
||||
|
||||
# Traefik logs
|
||||
# Enabled by default and log to stdout
|
||||
#
|
||||
# Optional
|
||||
#
|
||||
[traefikLog]
|
||||
format = "json"
|
||||
|
||||
# Sets the filepath for the traefik log. If not specified, stdout will be used.
|
||||
# Intermediate directories are created if necessary.
|
||||
#
|
||||
# Optional
|
||||
# Default: os.Stdout
|
||||
#
|
||||
# filePath = "log/traefik.log"
|
||||
|
||||
# Format is either "json" or "common".
|
||||
#
|
||||
# Optional
|
||||
# Default: "common"
|
||||
#
|
||||
# format = "common"
|
||||
|
||||
################################################################
|
||||
# Access logs configuration
|
||||
################################################################
|
||||
|
||||
# Enable access logs
|
||||
# By default it will write to stdout and produce logs in the textual
|
||||
# Common Log Format (CLF), extended with additional fields.
|
||||
#
|
||||
# Optional
|
||||
#
|
||||
# [accessLog]
|
||||
|
||||
# Sets the file path for the access log. If not specified, stdout will be used.
|
||||
# Intermediate directories are created if necessary.
|
||||
#
|
||||
# Optional
|
||||
# Default: os.Stdout
|
||||
#
|
||||
# filePath = "/path/to/log/log.txt"
|
||||
|
||||
# Format is either "json" or "common".
|
||||
#
|
||||
# Optional
|
||||
# Default: "common"
|
||||
#
|
||||
# format = "common"
|
||||
|
||||
################################################################
|
||||
# API and dashboard configuration
|
||||
################################################################
|
||||
|
||||
# Enable API and dashboard
|
||||
[api]
|
||||
|
||||
# Name of the related entry point
|
||||
#
|
||||
# Optional
|
||||
# Default: "traefik"
|
||||
#
|
||||
# entryPoint = "traefik"
|
||||
|
||||
# Enabled Dashboard
|
||||
#
|
||||
# Optional
|
||||
# Default: true
|
||||
#
|
||||
# dashboard = false
|
||||
|
||||
################################################################
|
||||
# Ping configuration
|
||||
################################################################
|
||||
|
||||
# Enable ping
|
||||
[ping]
|
||||
|
||||
# Name of the related entry point
|
||||
#
|
||||
# Optional
|
||||
# Default: "traefik"
|
||||
#
|
||||
# entryPoint = "traefik"
|
||||
|
||||
################################################################
|
||||
# Docker configuration backend
|
||||
################################################################
|
||||
|
||||
# Enable Kubernetes configuration backend
|
||||
[kubernetes]
|
||||
|
||||
[acme]
|
||||
KeyType = "RSA4096"
|
||||
email = "you@example.com"
|
||||
storage = "/acme/acme.json"
|
||||
entryPoint = "https"
|
||||
onHostRule = true
|
||||
acmeLogging = true
|
||||
|
||||
[acme.httpChallenge]
|
||||
entryPoint = "http"
|
||||
@@ -0,0 +1,94 @@
|
||||
#
|
||||
# Traefik + Traefik Forward Auth Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: traefik
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: traefik
|
||||
strategy:
|
||||
type: Recreate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
serviceAccountName: traefik
|
||||
terminationGracePeriodSeconds: 60
|
||||
containers:
|
||||
- image: traefik:1.7.12
|
||||
name: traefik
|
||||
args:
|
||||
- --configfile=/config/traefik.toml
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 80
|
||||
protocol: TCP
|
||||
- name: https
|
||||
containerPort: 443
|
||||
protocol: TCP
|
||||
- name: dash
|
||||
containerPort: 8080
|
||||
protocol: TCP
|
||||
volumeMounts:
|
||||
- mountPath: /config
|
||||
name: configs
|
||||
- mountPath: /acme
|
||||
name: acme
|
||||
|
||||
- image: thomseddon/traefik-forward-auth:2
|
||||
name: traefik-forward-auth
|
||||
ports:
|
||||
- containerPort: 4181
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: CONFIG
|
||||
value: "/config"
|
||||
- name: DOMAIN
|
||||
value: "example.com"
|
||||
# INSECURE_COOKIE is required if not using a https entrypoint
|
||||
# - name: INSECURE_COOKIE
|
||||
# value: "true"
|
||||
# Remove COOKIE_DOMAIN if not using auth host mode
|
||||
- name: COOKIE_DOMAIN
|
||||
value: "example.com"
|
||||
- name: AUTH_HOST
|
||||
value: "auth.example.com"
|
||||
- name: LOG_LEVEL
|
||||
value: "info"
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-id
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-secret
|
||||
- name: SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: secret
|
||||
volumeMounts:
|
||||
- name: configs
|
||||
mountPath: /config
|
||||
subPath: traefik-forward-auth.ini
|
||||
|
||||
volumes:
|
||||
- name: configs
|
||||
configMap:
|
||||
name: configs
|
||||
- name: traefik-forward-auth-secrets
|
||||
secret:
|
||||
secretName: secrets
|
||||
- name: acme
|
||||
persistentVolumeClaim:
|
||||
claimName: traefik-acme
|
||||
@@ -0,0 +1,36 @@
|
||||
#
|
||||
# Auth Ingress
|
||||
#
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
rules:
|
||||
- host: auth.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: traefik-forward-auth
|
||||
servicePort: auth-http
|
||||
|
||||
---
|
||||
#
|
||||
# Dash Ingress
|
||||
#
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: traefik-dashboard
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
rules:
|
||||
- host: traefik.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: traefik-dashboard
|
||||
servicePort: dashboard-http
|
||||
@@ -0,0 +1,28 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: default
|
||||
commonLabels:
|
||||
app: traefik
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
- pvc.yaml
|
||||
- rbac.yaml
|
||||
|
||||
#
|
||||
# Configs
|
||||
#
|
||||
configMapGenerator:
|
||||
- name: configs
|
||||
files:
|
||||
- configs/traefik.toml
|
||||
- configs/traefik-forward-auth.ini
|
||||
|
||||
#
|
||||
# Secrets
|
||||
#
|
||||
secretGenerator:
|
||||
- name: traefik-forward-auth-secrets
|
||||
env: secrets/traefik-forward-auth.env
|
||||
@@ -0,0 +1,17 @@
|
||||
# Source: traefik/templates/acme-pvc.yaml
|
||||
#
|
||||
# PVC
|
||||
#
|
||||
kind: PersistentVolumeClaim
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
name: traefik-acme
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
accessModes:
|
||||
- "ReadWriteOnce"
|
||||
resources:
|
||||
requests:
|
||||
storage: "1Gi"
|
||||
storageClassName: "local-traefik-acme"
|
||||
@@ -0,0 +1,52 @@
|
||||
#
|
||||
# RBAC
|
||||
# Source: traefik/templates/rbac.yaml
|
||||
#
|
||||
kind: ServiceAccount
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
name: traefik
|
||||
---
|
||||
kind: ClusterRole
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
metadata:
|
||||
name: traefik
|
||||
rules:
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- pods
|
||||
- services
|
||||
- endpoints
|
||||
- secrets
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- extensions
|
||||
resources:
|
||||
- ingresses
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- extensions
|
||||
resources:
|
||||
- ingresses/status
|
||||
verbs:
|
||||
- update
|
||||
---
|
||||
kind: ClusterRoleBinding
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
metadata:
|
||||
name: traefik
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: traefik
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: traefik
|
||||
namespace: kube-system
|
||||
@@ -0,0 +1,3 @@
|
||||
google-client-id=client-id
|
||||
google-client-secret=client-secret
|
||||
secret=something-random
|
||||
@@ -0,0 +1,58 @@
|
||||
#
|
||||
# Traefik Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
# Use NodePort if required
|
||||
type: LoadBalancer
|
||||
selector:
|
||||
app: traefik
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: 80
|
||||
- name: https
|
||||
port: 443
|
||||
targetPort: 443
|
||||
---
|
||||
#
|
||||
# Auth Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik
|
||||
ports:
|
||||
- name: auth-http
|
||||
port: 4181
|
||||
targetPort: 4181
|
||||
|
||||
---
|
||||
#
|
||||
# Dash Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-dashboard
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik
|
||||
ports:
|
||||
- name: dashboard-http
|
||||
port: 8080
|
||||
targetPort: 8080
|
||||
@@ -0,0 +1,19 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: whoami
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
containers:
|
||||
- image: containous/whoami
|
||||
name: whoami
|
||||
@@ -0,0 +1,16 @@
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: traefik
|
||||
spec:
|
||||
rules:
|
||||
- host: whoami.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: whoami
|
||||
servicePort: http
|
||||
@@ -0,0 +1,7 @@
|
||||
commonLabels:
|
||||
app: whoami
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
selector:
|
||||
app: whoami
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
|
||||
# Kubernetes - Simple Separate Pod Example
|
||||
|
||||
This is a simple example of how to deploy traefik-forward-auth in it's own pod with minimal configuration. This example is a good starting point for those who already have traefik deployed (e.g. using helm).
|
||||
|
||||
This example uses annotations to apply authentication to selected ingresses (see `k8s-app.yml`). This means ingresses will not be protected by default, only those with these annotations will require forward authentication. For example:
|
||||
|
||||
```
|
||||
#
|
||||
# Ingress
|
||||
#
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: traefik
|
||||
ingress.kubernetes.io/auth-type: forward
|
||||
ingress.kubernetes.io/auth-url: http://traefik-forward-auth:4181
|
||||
ingress.kubernetes.io/auth-response-headers: X-Forwarded-User
|
||||
spec:
|
||||
rules:
|
||||
- host: whoami.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: whoami
|
||||
servicePort: http
|
||||
```
|
||||
|
||||
|
||||
Example deployment:
|
||||
```
|
||||
# Deploy traefik-forward-auth
|
||||
kubectl apply -f k8s-traefik-forward-auth.yml
|
||||
|
||||
# Deploy example whoami app
|
||||
kubectl apply -f k8s-app.yml
|
||||
```
|
||||
|
||||
Please see the advanced examples for more details.
|
||||
@@ -0,0 +1,62 @@
|
||||
#
|
||||
# Example Application Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: whoami
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
containers:
|
||||
- name: whoami
|
||||
image: containous/whoami
|
||||
---
|
||||
#
|
||||
# Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
selector:
|
||||
app: whoami
|
||||
|
||||
---
|
||||
#
|
||||
# Ingress
|
||||
#
|
||||
apiVersion: extensions/v1beta1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: traefik
|
||||
ingress.kubernetes.io/auth-type: forward
|
||||
ingress.kubernetes.io/auth-url: http://traefik-forward-auth:4181
|
||||
ingress.kubernetes.io/auth-response-headers: X-Forwarded-User
|
||||
spec:
|
||||
rules:
|
||||
- host: whoami.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
serviceName: whoami
|
||||
servicePort: http
|
||||
@@ -0,0 +1,90 @@
|
||||
#
|
||||
# Traefik Forward Auth Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: traefik-forward-auth
|
||||
strategy:
|
||||
type: Recreate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 60
|
||||
containers:
|
||||
- image: thomseddon/traefik-forward-auth:2
|
||||
name: traefik-forward-auth
|
||||
ports:
|
||||
- containerPort: 4181
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: DOMAIN
|
||||
value: "example.com"
|
||||
# INSECURE_COOKIE is required unless using https entrypoint
|
||||
- name: INSECURE_COOKIE
|
||||
value: "true"
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: traefik-forward-auth-google-client-id
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: traefik-forward-auth-google-client-secret
|
||||
- name: SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: traefik-forward-auth-secret
|
||||
|
||||
---
|
||||
#
|
||||
# Auth Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik-forward-auth
|
||||
ports:
|
||||
- name: auth-http
|
||||
port: 4181
|
||||
targetPort: 4181
|
||||
|
||||
---
|
||||
#
|
||||
# Secrets
|
||||
#
|
||||
# Kubernetes requires secret values to be converted to base64 when defined
|
||||
# explicitly like this. (use `echo -n 'secret-value' | base64`)
|
||||
#
|
||||
# These are here for completeness, in reality you may define these elsewhere,
|
||||
# for example using kustomize (shown in advanced examples)
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: traefik-forward-auth-secrets
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
type: Opaque
|
||||
data:
|
||||
traefik-forward-auth-google-client-id: base64-client-id
|
||||
traefik-forward-auth-google-client-secret: base64-client-secret
|
||||
traefik-forward-auth-secret: base64-something-random
|
||||
@@ -14,7 +14,7 @@ services:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami1:
|
||||
image: emilevauge/whoami
|
||||
image: containous/whoami
|
||||
networks:
|
||||
- traefik
|
||||
labels:
|
||||
@@ -23,7 +23,7 @@ services:
|
||||
- "traefik.frontend.rule=Host:whoami.yourdomain.com"
|
||||
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth
|
||||
image: thomseddon/traefik-forward-auth:2
|
||||
environment:
|
||||
- PROVIDERS_GOOGLE_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_GOOGLE_CLIENT_SECRET=your-client-secret
|
||||
@@ -2,9 +2,8 @@ version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik
|
||||
image: traefik:1.7
|
||||
command: -c /traefik.toml
|
||||
# command: -c /traefik.toml --logLevel=DEBUG
|
||||
ports:
|
||||
- "8085:80"
|
||||
- "8086:8080"
|
||||
@@ -15,32 +14,25 @@ services:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami1:
|
||||
image: emilevauge/whoami
|
||||
image: containous/whoami
|
||||
networks:
|
||||
- traefik
|
||||
labels:
|
||||
- "traefik.backend=whoami1"
|
||||
- "traefik.backend=whoami"
|
||||
- "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: ../
|
||||
build: thomseddon/traefik-forward-auth:2
|
||||
environment:
|
||||
- PROVIDERS_GOOGLE_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_GOOGLE_CLIENT_SECRET=your-client-secret
|
||||
- DEFAULT_PROVIDER=oidc
|
||||
- PROVIDERS_OIDC_ISSUER_URL=https://login.microsoftonline.com/{tenant}
|
||||
- PROVIDERS_OIDC_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_OIDC_CLIENT_SECRET=your-client-secret
|
||||
- SECRET=something-random
|
||||
- INSECURE_COOKIE=true
|
||||
- COOKIE_DOMAIN=localhost.com
|
||||
- AUTH_HOST=auth.localhost.com
|
||||
- DOMAIN=yourcompany.com
|
||||
- LOG_LEVEL=debug
|
||||
networks:
|
||||
- traefik
|
||||
|
||||
@@ -2,7 +2,7 @@ version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik
|
||||
image: traefik:1.7
|
||||
command: -c /traefik.toml --logLevel=DEBUG
|
||||
ports:
|
||||
- "8085:80"
|
||||
@@ -14,7 +14,7 @@ services:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami1:
|
||||
image: emilevauge/whoami
|
||||
image: containous/whoami
|
||||
networks:
|
||||
- traefik
|
||||
labels:
|
||||
@@ -23,8 +23,8 @@ services:
|
||||
- "traefik.frontend.rule=Host:whoami.localhost.com"
|
||||
|
||||
traefik-forward-auth:
|
||||
build: ../
|
||||
command: ./traefik-forward-auth --rule.1.action=allow --rule.1.rule="Path(`/`)"
|
||||
build: thomseddon/traefik-forward-auth:2
|
||||
command: ./traefik-forward-auth --rule.1.action=allow --rule.1.rule="Path(`/public`)"
|
||||
environment:
|
||||
- PROVIDERS_GOOGLE_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_GOOGLE_CLIENT_SECRET=your-client-secret
|
||||
@@ -135,3 +135,4 @@
|
||||
# Enable Docker configuration backend
|
||||
[docker]
|
||||
exposedByDefault = false
|
||||
network = "traefik"
|
||||
@@ -0,0 +1,39 @@
|
||||
# Kubernetes - Advanced Separate Pod Example
|
||||
|
||||
This is an advanced example of how to deploy traefik-forward-auth in it's own pod. This example is a good starting point for those who already have traefik deployed (e.g. using helm).
|
||||
|
||||
This example uses [Selective Authentication](https://github.com/thomseddon/traefik-forward-auth/blob/master/README.md#selective-ingress-authentication-in-kubernetes) to selectively apply forward authentication to each selective ingresses, for example:
|
||||
|
||||
```
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
entryPoints:
|
||||
- https
|
||||
routes:
|
||||
- match: Host(`whoami.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: whoami
|
||||
port: 80
|
||||
middlewares:
|
||||
- name: traefik-forward-auth
|
||||
tls:
|
||||
certresolver: default
|
||||
```
|
||||
|
||||
This example also includes SSL via traefik acme/lesencrypt, auth host mode, and leverages kustomise. A simple example "whoami" application (deployment, service and ingress) is included for completeness.
|
||||
|
||||
Example deployment:
|
||||
|
||||
```
|
||||
# Deploy traefik-forward-auth
|
||||
kubectl apply -k traefik-forward-auth
|
||||
|
||||
# Deploy example whoami app
|
||||
kubectl apply -k whoami
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
bases:
|
||||
- traefik-forward-auth
|
||||
- whoami
|
||||
@@ -0,0 +1,8 @@
|
||||
rule.example_public.action=allow
|
||||
rule.example_public.rule=Host("stats.example.com") && PathPrefix("/api/public")
|
||||
|
||||
rule.example_api.action=allow
|
||||
rule.example_api.rule=Host("api.example.com") && Headers("X-API-Authorization", "a-long-api-key")
|
||||
|
||||
rule.example_api_query.action=allow
|
||||
rule.example_api_query.rule=Host("api.example.com") && && Query("api_key=a-long-api-key")
|
||||
@@ -0,0 +1,71 @@
|
||||
#
|
||||
# Traefik Forward Auth Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: traefik-forward-auth
|
||||
strategy:
|
||||
type: Recreate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
serviceAccountName: traefik-ingress-controller
|
||||
terminationGracePeriodSeconds: 60
|
||||
containers:
|
||||
- image: thomseddon/traefik-forward-auth:2
|
||||
name: traefik-forward-auth
|
||||
ports:
|
||||
- containerPort: 4181
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: CONFIG
|
||||
value: "/config"
|
||||
- name: DOMAIN
|
||||
value: "example.com"
|
||||
# INSECURE_COOKIE is required if not using a https entrypoint
|
||||
# - name: INSECURE_COOKIE
|
||||
# value: "true"
|
||||
# Remove COOKIE_DOMAIN if not using auth host mode
|
||||
- name: COOKIE_DOMAIN
|
||||
value: "example.com"
|
||||
- name: AUTH_HOST
|
||||
value: "auth.example.com"
|
||||
- name: LOG_LEVEL
|
||||
value: "info"
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-id
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-secret
|
||||
- name: SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: secret
|
||||
volumeMounts:
|
||||
- name: configs
|
||||
mountPath: /config
|
||||
subPath: traefik-forward-auth.ini
|
||||
|
||||
volumes:
|
||||
- name: configs
|
||||
configMap:
|
||||
name: configs
|
||||
- name: traefik-forward-auth-secrets
|
||||
secret:
|
||||
secretName: traefik-forward-auth-secrets
|
||||
@@ -0,0 +1,20 @@
|
||||
#
|
||||
# Auth Ingress
|
||||
#
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
entryPoints:
|
||||
- https
|
||||
routes:
|
||||
- match: Host(`auth.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: traefik-forward-auth
|
||||
port: 4181
|
||||
tls:
|
||||
certresolver: default
|
||||
@@ -0,0 +1,26 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: default
|
||||
commonLabels:
|
||||
app: traefik-forward-auth
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
- middleware.yaml
|
||||
|
||||
#
|
||||
# Configs
|
||||
#
|
||||
configMapGenerator:
|
||||
- name: configs
|
||||
files:
|
||||
- configs/traefik-forward-auth.ini
|
||||
|
||||
#
|
||||
# Secrets
|
||||
#
|
||||
secretGenerator:
|
||||
- name: traefik-forward-auth-secrets
|
||||
env: secrets/traefik-forward-auth.env
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: Middleware
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
spec:
|
||||
forwardAuth:
|
||||
address: http://traefik-forward-auth:4181
|
||||
authResponseHeaders:
|
||||
- X-Forwarded-User
|
||||
@@ -0,0 +1,3 @@
|
||||
google-client-id=client-id
|
||||
google-client-secret=client-secret
|
||||
secret=something-random
|
||||
@@ -0,0 +1,17 @@
|
||||
#
|
||||
# Auth Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik
|
||||
ports:
|
||||
- name: auth-http
|
||||
port: 4181
|
||||
targetPort: 4181
|
||||
@@ -0,0 +1,19 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: whoami
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
containers:
|
||||
- image: containous/whoami
|
||||
name: whoami
|
||||
@@ -0,0 +1,19 @@
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
entryPoints:
|
||||
- https
|
||||
routes:
|
||||
- match: Host(`whoami.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: whoami
|
||||
port: 80
|
||||
middlewares:
|
||||
- name: traefik-forward-auth
|
||||
tls:
|
||||
certresolver: default
|
||||
@@ -0,0 +1,7 @@
|
||||
commonLabels:
|
||||
app: whoami
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
selector:
|
||||
app: whoami
|
||||
|
||||
18
examples/traefik-v2/kubernetes/advanced-single-pod/README.md
Normal file
18
examples/traefik-v2/kubernetes/advanced-single-pod/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
|
||||
# Kubernetes - Advanced Single Pod Example
|
||||
|
||||
This is an advanced example of how to deploy traefik and traefik-forward-auth in a single pod. This example is a good starting point for those who already have a manually defined traefik config (e.g. not using helm).
|
||||
|
||||
This example uses [Global Authentication](https://github.com/thomseddon/traefik-forward-auth/blob/master/README.md#global-authentication) to apply authentication for the entire `https` entrypoint.
|
||||
|
||||
This example also includes SSL via traefik acme/lesencrypt, auth host mode, exposes the traefik dashboard and leverages kustomise. No special config if required for your applications, but a simple example "whoami" application (deployment, service and ingress) is included for completeness.
|
||||
|
||||
Example deployment:
|
||||
|
||||
```
|
||||
# Deploy traefik+traefik-forward-auth
|
||||
kubectl apply -k traefik
|
||||
|
||||
# Deploy whoami app
|
||||
kubectl apply -k whoami
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
bases:
|
||||
- traefik
|
||||
- whoami
|
||||
@@ -0,0 +1,8 @@
|
||||
rule.example_public.action=allow
|
||||
rule.example_public.rule=Host("stats.example.com") && PathPrefix("/api/public")
|
||||
|
||||
rule.example_api.action=allow
|
||||
rule.example_api.rule=Host("api.example.com") && Headers("X-API-Authorization", "a-long-api-key")
|
||||
|
||||
rule.example_api_query.action=allow
|
||||
rule.example_api_query.rule=Host("api.example.com") && && Query("api_key=a-long-api-key")
|
||||
@@ -0,0 +1,103 @@
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: ingressroutes.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: IngressRoute
|
||||
plural: ingressroutes
|
||||
singular: ingressroute
|
||||
scope: Namespaced
|
||||
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: middlewares.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: Middleware
|
||||
plural: middlewares
|
||||
singular: middleware
|
||||
scope: Namespaced
|
||||
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: ingressroutetcps.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: IngressRouteTCP
|
||||
plural: ingressroutetcps
|
||||
singular: ingressroutetcp
|
||||
scope: Namespaced
|
||||
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: ingressrouteudps.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: IngressRouteUDP
|
||||
plural: ingressrouteudps
|
||||
singular: ingressrouteudp
|
||||
scope: Namespaced
|
||||
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: tlsoptions.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: TLSOption
|
||||
plural: tlsoptions
|
||||
singular: tlsoption
|
||||
scope: Namespaced
|
||||
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: tlsstores.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: TLSStore
|
||||
plural: tlsstores
|
||||
singular: tlsstore
|
||||
scope: Namespaced
|
||||
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1beta1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: traefikservices.traefik.containo.us
|
||||
|
||||
spec:
|
||||
group: traefik.containo.us
|
||||
version: v1alpha1
|
||||
names:
|
||||
kind: TraefikService
|
||||
plural: traefikservices
|
||||
singular: traefikservice
|
||||
scope: Namespaced
|
||||
@@ -0,0 +1,110 @@
|
||||
#
|
||||
# Traefik + Traefik Forward Auth Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: traefik
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: traefik
|
||||
strategy:
|
||||
type: Recreate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
serviceAccountName: traefik-ingress-controller
|
||||
terminationGracePeriodSeconds: 60
|
||||
containers:
|
||||
- image: traefik:2.2
|
||||
name: traefik
|
||||
args:
|
||||
- --api.dashboard
|
||||
- --accesslog
|
||||
- --entryPoints.http.address=:80
|
||||
- --entryPoints.http.http.redirections.entryPoint.to=https
|
||||
- --entryPoints.http.http.redirections.entryPoint.scheme=https
|
||||
- --entryPoints.https.address=:443
|
||||
# We're using "global authentication", so the middleware is defined here on the entrypoint
|
||||
# When a kubernetescrd middleware is applied globally it should take the form <kubernetes-namespace>-<middleware>
|
||||
- --entrypoints.https.http.middlewares=default-traefik-forward-auth
|
||||
- --providers.kubernetescrd
|
||||
- --log.level=info
|
||||
- --log.format=json
|
||||
- --certificatesresolvers.default.acme.email=foo@you.com
|
||||
- --certificatesresolvers.default.acme.storage=/acme/acme.json
|
||||
- --certificatesresolvers.default.acme.storage=/acme/acme.json
|
||||
- --certificatesresolvers.default.acme.httpchallenge.entrypoint=http
|
||||
# Please note that this is the staging Let's Encrypt server.
|
||||
# Once you get things working, you should remove that whole line altogether.
|
||||
- --certificatesresolvers.default.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 80
|
||||
protocol: TCP
|
||||
- name: https
|
||||
containerPort: 443
|
||||
protocol: TCP
|
||||
- name: dash
|
||||
containerPort: 8080
|
||||
protocol: TCP
|
||||
volumeMounts:
|
||||
- mountPath: /acme
|
||||
name: acme
|
||||
|
||||
- image: thomseddon/traefik-forward-auth:2
|
||||
name: traefik-forward-auth
|
||||
ports:
|
||||
- containerPort: 4181
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: CONFIG
|
||||
value: "/config"
|
||||
- name: DOMAIN
|
||||
value: "example.com"
|
||||
# INSECURE_COOKIE is required if not using a https entrypoint
|
||||
# - name: INSECURE_COOKIE
|
||||
# value: "true"
|
||||
# Remove COOKIE_DOMAIN if not using auth host mode
|
||||
- name: COOKIE_DOMAIN
|
||||
value: "example.com"
|
||||
- name: AUTH_HOST
|
||||
value: "auth.example.com"
|
||||
- name: LOG_LEVEL
|
||||
value: "info"
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-id
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: google-client-secret
|
||||
- name: SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: secret
|
||||
volumeMounts:
|
||||
- name: configs
|
||||
mountPath: /config
|
||||
subPath: traefik-forward-auth.ini
|
||||
|
||||
volumes:
|
||||
- name: configs
|
||||
configMap:
|
||||
name: configs
|
||||
- name: traefik-forward-auth-secrets
|
||||
secret:
|
||||
secretName: traefik-forward-auth-secrets
|
||||
- name: acme
|
||||
persistentVolumeClaim:
|
||||
claimName: traefik-acme
|
||||
@@ -0,0 +1,42 @@
|
||||
#
|
||||
# Auth Ingress
|
||||
#
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
entryPoints:
|
||||
- https
|
||||
routes:
|
||||
- match: Host(`auth.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: traefik-forward-auth
|
||||
port: 4181
|
||||
tls:
|
||||
certresolver: default
|
||||
|
||||
---
|
||||
#
|
||||
# Dash Ingress
|
||||
#
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: traefik-dashboard
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
entryPoints:
|
||||
- https
|
||||
routes:
|
||||
- match: Host(`traefik.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: api@internal
|
||||
kind: TraefikService
|
||||
tls:
|
||||
certresolver: default
|
||||
@@ -0,0 +1,29 @@
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: default
|
||||
commonLabels:
|
||||
app: traefik
|
||||
|
||||
resources:
|
||||
- crds.yaml
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
- middleware.yaml
|
||||
- pvc.yaml
|
||||
- rbac.yaml
|
||||
|
||||
#
|
||||
# Configs
|
||||
#
|
||||
configMapGenerator:
|
||||
- name: configs
|
||||
files:
|
||||
- configs/traefik-forward-auth.ini
|
||||
|
||||
#
|
||||
# Secrets
|
||||
#
|
||||
secretGenerator:
|
||||
- name: traefik-forward-auth-secrets
|
||||
env: secrets/traefik-forward-auth.env
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: Middleware
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
spec:
|
||||
forwardAuth:
|
||||
address: http://127.0.0.1:4181
|
||||
authResponseHeaders:
|
||||
- X-Forwarded-User
|
||||
@@ -0,0 +1,17 @@
|
||||
# Source: traefik/templates/acme-pvc.yaml
|
||||
#
|
||||
# PVC
|
||||
#
|
||||
kind: PersistentVolumeClaim
|
||||
apiVersion: v1
|
||||
metadata:
|
||||
name: traefik-acme
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
accessModes:
|
||||
- "ReadWriteOnce"
|
||||
resources:
|
||||
requests:
|
||||
storage: "1Gi"
|
||||
storageClassName: "local-traefik-acme"
|
||||
@@ -0,0 +1,66 @@
|
||||
#
|
||||
# RBAC
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
namespace: default
|
||||
name: traefik-ingress-controller
|
||||
---
|
||||
kind: ClusterRole
|
||||
apiVersion: rbac.authorization.k8s.io/v1beta1
|
||||
metadata:
|
||||
name: traefik-ingress-controller
|
||||
rules:
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- services
|
||||
- endpoints
|
||||
- secrets
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- extensions
|
||||
resources:
|
||||
- ingresses
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
- apiGroups:
|
||||
- extensions
|
||||
resources:
|
||||
- ingresses/status
|
||||
verbs:
|
||||
- update
|
||||
- apiGroups:
|
||||
- traefik.containo.us
|
||||
resources:
|
||||
- middlewares
|
||||
- ingressroutes
|
||||
- traefikservices
|
||||
- ingressroutetcps
|
||||
- ingressrouteudps
|
||||
- tlsoptions
|
||||
- tlsstores
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- watch
|
||||
|
||||
---
|
||||
kind: ClusterRoleBinding
|
||||
apiVersion: rbac.authorization.k8s.io/v1beta1
|
||||
metadata:
|
||||
name: traefik-ingress-controller
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: traefik-ingress-controller
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: traefik-ingress-controller
|
||||
namespace: default
|
||||
@@ -0,0 +1,3 @@
|
||||
google-client-id=client-id
|
||||
google-client-secret=client-secret
|
||||
secret=something-random
|
||||
@@ -0,0 +1,39 @@
|
||||
#
|
||||
# Traefik Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
# Use NodePort if required
|
||||
type: LoadBalancer
|
||||
selector:
|
||||
app: traefik
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: 80
|
||||
- name: https
|
||||
port: 443
|
||||
targetPort: 443
|
||||
---
|
||||
#
|
||||
# Auth Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik
|
||||
ports:
|
||||
- name: auth-http
|
||||
port: 4181
|
||||
targetPort: 4181
|
||||
@@ -0,0 +1,19 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: whoami
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
containers:
|
||||
- image: containous/whoami
|
||||
name: whoami
|
||||
@@ -0,0 +1,17 @@
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
entryPoints:
|
||||
- https
|
||||
routes:
|
||||
- match: Host(`whoami.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: whoami
|
||||
port: 80
|
||||
tls:
|
||||
certresolver: default
|
||||
@@ -0,0 +1,7 @@
|
||||
commonLabels:
|
||||
app: whoami
|
||||
|
||||
resources:
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
- ingress.yaml
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
selector:
|
||||
app: whoami
|
||||
|
||||
39
examples/traefik-v2/kubernetes/simple-separate-pod/README.md
Normal file
39
examples/traefik-v2/kubernetes/simple-separate-pod/README.md
Normal file
@@ -0,0 +1,39 @@
|
||||
|
||||
# Kubernetes - Simple Separate Pod Example
|
||||
|
||||
This is a simple example of how to deploy traefik-forward-auth in it's own pod with minimal configuration. This example is a good starting point for those who already have traefik deployed (e.g. using helm).
|
||||
|
||||
This example uses [Selective Authentication](https://github.com/thomseddon/traefik-forward-auth/blob/master/README.md#selective-ingress-authentication-in-kubernetes) to apply forward authentication to selected ingresses. This means ingresses will not be protected by default. Authentication can be applied by adding the `traefik-forward-auth` middleware, for example:
|
||||
|
||||
```
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
entryPoints:
|
||||
- http
|
||||
routes:
|
||||
- match: Host(`whoami.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: whoami
|
||||
port: 80
|
||||
middlewares:
|
||||
- name: traefik-forward-auth
|
||||
```
|
||||
|
||||
A minimal application example is provided in `k8s-app.yml`.
|
||||
|
||||
Example deployment:
|
||||
```
|
||||
# Deploy traefik-forward-auth
|
||||
kubectl apply -f k8s-traefik-forward-auth.yml
|
||||
|
||||
# Deploy example whoami app
|
||||
kubectl apply -f k8s-app.yml
|
||||
```
|
||||
|
||||
Please see the advanced examples for more details.
|
||||
@@ -0,0 +1,60 @@
|
||||
#
|
||||
# Example Application Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: whoami
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
containers:
|
||||
- name: whoami
|
||||
image: containous/whoami
|
||||
---
|
||||
#
|
||||
# Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
selector:
|
||||
app: whoami
|
||||
|
||||
---
|
||||
#
|
||||
# IngressRoute
|
||||
#
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whoami
|
||||
labels:
|
||||
app: whoami
|
||||
spec:
|
||||
entryPoints:
|
||||
- http
|
||||
routes:
|
||||
- match: Host(`whoami.example.com`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: whoami
|
||||
port: 80
|
||||
middlewares:
|
||||
- name: traefik-forward-auth
|
||||
@@ -0,0 +1,104 @@
|
||||
#
|
||||
# Traefik Forward Auth Deployment
|
||||
#
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: traefik-forward-auth
|
||||
strategy:
|
||||
type: Recreate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 60
|
||||
containers:
|
||||
- image: thomseddon/traefik-forward-auth:2
|
||||
name: traefik-forward-auth
|
||||
ports:
|
||||
- containerPort: 4181
|
||||
protocol: TCP
|
||||
env:
|
||||
- name: DOMAIN
|
||||
value: "example.com"
|
||||
# INSECURE_COOKIE is required unless using https entrypoint
|
||||
- name: INSECURE_COOKIE
|
||||
value: "true"
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_ID
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: traefik-forward-auth-google-client-id
|
||||
- name: PROVIDERS_GOOGLE_CLIENT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: traefik-forward-auth-google-client-secret
|
||||
- name: SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: traefik-forward-auth-secrets
|
||||
key: traefik-forward-auth-secret
|
||||
|
||||
---
|
||||
#
|
||||
# Auth Service
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: traefik-forward-auth
|
||||
ports:
|
||||
- name: auth-http
|
||||
port: 4181
|
||||
targetPort: 4181
|
||||
|
||||
---
|
||||
#
|
||||
# Auth Middleware
|
||||
#
|
||||
apiVersion: traefik.containo.us/v1alpha1
|
||||
kind: Middleware
|
||||
metadata:
|
||||
name: traefik-forward-auth
|
||||
spec:
|
||||
forwardAuth:
|
||||
address: http://traefik-forward-auth:4181
|
||||
authResponseHeaders:
|
||||
- X-Forwarded-User
|
||||
|
||||
---
|
||||
#
|
||||
# Secrets
|
||||
#
|
||||
# Kubernetes requires secret values to be converted to base64 when defined
|
||||
# explicitly like this. (use `echo -n 'secret-value' | base64`)
|
||||
#
|
||||
# These are here for completeness, in reality you may define these elsewhere,
|
||||
# for example using kustomize (shown in advanced examples)
|
||||
#
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: traefik-forward-auth-secrets
|
||||
labels:
|
||||
app: traefik-forward-auth
|
||||
type: Opaque
|
||||
data:
|
||||
traefik-forward-auth-google-client-id: base64-client-id
|
||||
traefik-forward-auth-google-client-secret: base64-client-secret
|
||||
traefik-forward-auth-secret: base64-something-random
|
||||
37
examples/traefik-v2/swarm/docker-compose-auth-host.yml
Normal file
37
examples/traefik-v2/swarm/docker-compose-auth-host.yml
Normal file
@@ -0,0 +1,37 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik:v2.2
|
||||
command:
|
||||
- --providers.docker
|
||||
# This example uses "global authentication"
|
||||
- --entryPoints.http.address=:80
|
||||
- --entrypoints.http.http.middlewares=traefik-forward-auth
|
||||
ports:
|
||||
- "8085:80"
|
||||
- "8086:8080"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami:
|
||||
image: containous/whoami
|
||||
labels:
|
||||
- "traefik.http.routers.whoami.rule=Host(`whoami.localhost.com`)"
|
||||
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth:2
|
||||
environment:
|
||||
- PROVIDERS_GOOGLE_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_GOOGLE_CLIENT_SECRET=your-client-secret
|
||||
- SECRET=something-random
|
||||
# INSECURE_COOKIE is required if not using a https entrypoint
|
||||
- INSECURE_COOKIE=true
|
||||
- COOKIE_DOMAIN=localhost.com
|
||||
- AUTH_HOST=auth.localhost.com:8085
|
||||
- LOG_LEVEL=debug
|
||||
labels:
|
||||
- "traefik.http.routers.traefik-forward-auth.rule=Host(`auth.localhost.com`)"
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.address=http://traefik-forward-auth:4181"
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.authResponseHeaders=X-Forwarded-User"
|
||||
- "traefik.http.services.traefik-forward-auth.loadbalancer.server.port=4181"
|
||||
34
examples/traefik-v2/swarm/docker-compose-oidc.yml
Normal file
34
examples/traefik-v2/swarm/docker-compose-oidc.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik:v2.2
|
||||
command: --providers.docker
|
||||
ports:
|
||||
- "8085:80"
|
||||
- "8086:8080"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami:
|
||||
image: containous/whoami
|
||||
labels:
|
||||
- "traefik.http.routers.whoami.rule=Host(`whoami.localhost.com`)"
|
||||
- "traefik.http.routers.whoami.middlewares=traefik-forward-auth"
|
||||
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth:2
|
||||
environment:
|
||||
- DEFAULT_PROVIDER=oidc
|
||||
- PROVIDERS_OIDC_ISSUER_URL=https://login.microsoftonline.com/{tenant}
|
||||
- PROVIDERS_OIDC_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_OIDC_CLIENT_SECRET=your-client-secret
|
||||
- SECRET=something-random
|
||||
# INSECURE_COOKIE is required if not using a https entrypoint
|
||||
- INSECURE_COOKIE=true
|
||||
- LOG_LEVEL=debug
|
||||
labels:
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.address=http://traefik-forward-auth:4181"
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.authResponseHeaders=X-Forwarded-User"
|
||||
- "traefik.http.services.traefik-forward-auth.loadbalancer.server.port=4181"
|
||||
|
||||
32
examples/traefik-v2/swarm/docker-compose.yml
Normal file
32
examples/traefik-v2/swarm/docker-compose.yml
Normal file
@@ -0,0 +1,32 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
traefik:
|
||||
image: traefik:v2.2
|
||||
command: --providers.docker
|
||||
ports:
|
||||
- "8085:80"
|
||||
- "8086:8080"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami:
|
||||
image: containous/whoami
|
||||
labels:
|
||||
- "traefik.http.routers.whoami.rule=Host(`whoami.localhost.com`)"
|
||||
# This example uses "Selective Authentication"
|
||||
- "traefik.http.routers.whoami.middlewares=traefik-forward-auth"
|
||||
|
||||
traefik-forward-auth:
|
||||
image: thomseddon/traefik-forward-auth:2
|
||||
environment:
|
||||
- PROVIDERS_GOOGLE_CLIENT_ID=your-client-id
|
||||
- PROVIDERS_GOOGLE_CLIENT_SECRET=your-client-secret
|
||||
- SECRET=something-random
|
||||
# INSECURE_COOKIE is required if not using a https entrypoint
|
||||
- INSECURE_COOKIE=true
|
||||
- LOG_LEVEL=debug
|
||||
labels:
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.address=http://traefik-forward-auth:4181"
|
||||
- "traefik.http.middlewares.traefik-forward-auth.forwardauth.authResponseHeaders=X-Forwarded-User"
|
||||
- "traefik.http.services.traefik-forward-auth.loadbalancer.server.port=4181"
|
||||
73
go.mod
73
go.mod
@@ -1,36 +1,49 @@
|
||||
module github.com/thomseddon/traefik-forward-auth
|
||||
|
||||
go 1.12
|
||||
go 1.22
|
||||
|
||||
toolchain go1.22.2
|
||||
|
||||
require (
|
||||
github.com/VividCortex/gohistogram v1.0.0 // indirect
|
||||
github.com/cenkalti/backoff v2.1.1+incompatible // indirect
|
||||
github.com/containous/alice v0.0.0-20181107144136-d83ebdd94cbd // indirect
|
||||
github.com/containous/flaeg v1.4.1 // indirect
|
||||
github.com/containous/mux v0.0.0-20181024131434-c33f32e26898 // indirect
|
||||
github.com/containous/traefik v2.0.0-alpha2+incompatible
|
||||
github.com/go-acme/lego v2.5.0+incompatible // indirect
|
||||
github.com/go-kit/kit v0.8.0 // indirect
|
||||
github.com/gorilla/context v1.1.1 // indirect
|
||||
github.com/gravitational/trace v0.0.0-20190409171327-f30095ced5ff // indirect
|
||||
github.com/jessevdk/go-flags v1.4.1-0.20181221193153-c0795c8afcf4
|
||||
github.com/jonboulle/clockwork v0.1.0 // indirect
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
|
||||
github.com/kr/pretty v0.1.0 // indirect
|
||||
github.com/kr/pty v1.1.4 // indirect
|
||||
github.com/miekg/dns v1.1.8 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pkg/errors v0.8.1 // indirect
|
||||
github.com/ryanuber/go-glob v1.0.0 // indirect
|
||||
github.com/sirupsen/logrus v1.4.1
|
||||
github.com/stretchr/objx v0.2.0 // indirect
|
||||
github.com/stretchr/testify v1.3.0
|
||||
github.com/coreos/go-oidc v2.2.1+incompatible
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.8.4
|
||||
github.com/thomseddon/go-flags v1.4.1-0.20190507184247-a3629c504486
|
||||
github.com/vulcand/predicate v1.1.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20190422183909-d864b10871cd // indirect
|
||||
golang.org/x/net v0.0.0-20190420063019-afa5a82059c6 // indirect
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
|
||||
gopkg.in/square/go-jose.v2 v2.3.1 // indirect
|
||||
github.com/traefik/traefik/v2 v2.11.2
|
||||
golang.org/x/oauth2 v0.20.0
|
||||
gopkg.in/square/go-jose.v2 v2.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/containous/alice v0.0.0-20181107144136-d83ebdd94cbd // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/gravitational/trace v1.4.0 // indirect
|
||||
github.com/jonboulle/clockwork v0.4.0 // indirect
|
||||
github.com/miekg/dns v1.1.59 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/pquerna/cachecontrol v0.2.0 // indirect
|
||||
github.com/traefik/paerser v0.2.0 // indirect
|
||||
github.com/vulcand/predicate v1.2.0 // indirect
|
||||
golang.org/x/crypto v0.23.0 // indirect
|
||||
golang.org/x/mod v0.17.0 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
golang.org/x/term v0.20.0 // indirect
|
||||
golang.org/x/text v0.15.0 // indirect
|
||||
golang.org/x/tools v0.21.0 // indirect
|
||||
google.golang.org/appengine v1.6.8 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
// Containous forks
|
||||
replace (
|
||||
github.com/abbot/go-http-auth => github.com/containous/go-http-auth v0.4.1-0.20200324110947-a37a7636d23e
|
||||
github.com/go-check/check => github.com/containous/check v0.0.0-20170915194414-ca0bf163426a
|
||||
github.com/gorilla/mux => github.com/containous/mux v0.0.0-20220627093034-b2dd784e613f
|
||||
github.com/mailgun/minheap => github.com/containous/minheap v0.0.0-20190809180810-6e71eb837595
|
||||
)
|
||||
|
||||
224
internal/auth.go
224
internal/auth.go
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
// Request Validation
|
||||
|
||||
// ValidateCookie verifies that a cookie matches the expected format of:
|
||||
// Cookie = hash(secret, cookie domain, email, expires)|expires|email
|
||||
func ValidateCookie(r *http.Request, c *http.Cookie) (string, error) {
|
||||
parts := strings.Split(c.Value, "|")
|
||||
@@ -55,80 +56,88 @@ func ValidateCookie(r *http.Request, c *http.Cookie) (string, error) {
|
||||
return parts[2], nil
|
||||
}
|
||||
|
||||
// Validate email
|
||||
func ValidateEmail(email string) bool {
|
||||
found := false
|
||||
if len(config.Whitelist) > 0 {
|
||||
for _, whitelist := range config.Whitelist {
|
||||
if email == whitelist {
|
||||
found = true
|
||||
}
|
||||
// ValidateEmail checks if the given email address matches either a whitelisted
|
||||
// email address, as defined by the "whitelist" config parameter. Or is part of
|
||||
// a permitted domain, as defined by the "domains" config parameter
|
||||
func ValidateEmail(email, ruleName string) bool {
|
||||
// Use global config by default
|
||||
whitelist := config.Whitelist
|
||||
domains := config.Domains
|
||||
|
||||
if rule, ok := config.Rules[ruleName]; ok {
|
||||
// Override with rule config if found
|
||||
if len(rule.Whitelist) > 0 || len(rule.Domains) > 0 {
|
||||
whitelist = rule.Whitelist
|
||||
domains = rule.Domains
|
||||
}
|
||||
} else if len(config.Domains) > 0 {
|
||||
parts := strings.Split(email, "@")
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
for _, domain := range config.Domains {
|
||||
if domain == parts[1] {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
}
|
||||
|
||||
// Do we have any validation to perform?
|
||||
if len(whitelist) == 0 && len(domains) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
return found
|
||||
// Email whitelist validation
|
||||
if len(whitelist) > 0 {
|
||||
if ValidateWhitelist(email, whitelist) {
|
||||
return true
|
||||
}
|
||||
|
||||
// If we're not matching *either*, stop here
|
||||
if !config.MatchWhitelistOrDomain {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Domain validation
|
||||
if len(domains) > 0 && ValidateDomains(email, domains) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// OAuth Methods
|
||||
|
||||
// Get login url
|
||||
func GetLoginURL(r *http.Request, nonce string) string {
|
||||
state := fmt.Sprintf("%s:%s", nonce, returnUrl(r))
|
||||
|
||||
// TODO: Support multiple providers
|
||||
return config.Providers.Google.GetLoginURL(redirectUri(r), state)
|
||||
// ValidateWhitelist checks if the email is in whitelist
|
||||
func ValidateWhitelist(email string, whitelist CommaSeparatedList) bool {
|
||||
for _, whitelist := range whitelist {
|
||||
if email == whitelist {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Exchange code for token
|
||||
|
||||
func ExchangeCode(r *http.Request) (string, error) {
|
||||
code := r.URL.Query().Get("code")
|
||||
|
||||
// TODO: Support multiple providers
|
||||
return config.Providers.Google.ExchangeCode(redirectUri(r), code)
|
||||
}
|
||||
|
||||
// Get user with token
|
||||
|
||||
func GetUser(token string) (provider.User, error) {
|
||||
// TODO: Support multiple providers
|
||||
return config.Providers.Google.GetUser(token)
|
||||
// ValidateDomains checks if the email matches a whitelisted domain
|
||||
func ValidateDomains(email string, domains CommaSeparatedList) bool {
|
||||
parts := strings.Split(email, "@")
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
for _, domain := range domains {
|
||||
if domain == parts[1] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Utility methods
|
||||
|
||||
// Get the redirect base
|
||||
func redirectBase(r *http.Request) string {
|
||||
proto := r.Header.Get("X-Forwarded-Proto")
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
|
||||
return fmt.Sprintf("%s://%s", proto, host)
|
||||
return fmt.Sprintf("%s://%s", r.Header.Get("X-Forwarded-Proto"), r.Host)
|
||||
}
|
||||
|
||||
// // Return url
|
||||
// Return url
|
||||
func returnUrl(r *http.Request) string {
|
||||
path := r.Header.Get("X-Forwarded-Uri")
|
||||
|
||||
return fmt.Sprintf("%s%s", redirectBase(r), path)
|
||||
return fmt.Sprintf("%s%s", redirectBase(r), r.URL.Path)
|
||||
}
|
||||
|
||||
// Get oauth redirect uri
|
||||
func redirectUri(r *http.Request) string {
|
||||
if use, _ := useAuthDomain(r); use {
|
||||
proto := r.Header.Get("X-Forwarded-Proto")
|
||||
return fmt.Sprintf("%s://%s%s", proto, config.AuthHost, config.Path)
|
||||
p := r.Header.Get("X-Forwarded-Proto")
|
||||
return fmt.Sprintf("%s://%s%s", p, config.AuthHost, config.Path)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s%s", redirectBase(r), config.Path)
|
||||
@@ -141,7 +150,7 @@ func useAuthDomain(r *http.Request) (bool, string) {
|
||||
}
|
||||
|
||||
// Does the request match a given cookie domain?
|
||||
reqMatch, reqHost := matchCookieDomains(r.Header.Get("X-Forwarded-Host"))
|
||||
reqMatch, reqHost := matchCookieDomains(r.Host)
|
||||
|
||||
// Do any of the auth hosts match a cookie domain?
|
||||
authMatch, authHost := matchCookieDomains(config.AuthHost)
|
||||
@@ -152,7 +161,7 @@ func useAuthDomain(r *http.Request) (bool, string) {
|
||||
|
||||
// Cookie methods
|
||||
|
||||
// Create an auth cookie
|
||||
// MakeCookie creates an auth cookie
|
||||
func MakeCookie(r *http.Request, email string) *http.Cookie {
|
||||
expires := cookieExpiry()
|
||||
mac := cookieSignature(r, email, fmt.Sprintf("%d", expires.Unix()))
|
||||
@@ -169,23 +178,44 @@ func MakeCookie(r *http.Request, email string) *http.Cookie {
|
||||
}
|
||||
}
|
||||
|
||||
// Make a CSRF cookie (used during login only)
|
||||
// ClearCookie clears the auth cookie
|
||||
func ClearCookie(r *http.Request) *http.Cookie {
|
||||
return &http.Cookie{
|
||||
Name: config.CookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Domain: cookieDomain(r),
|
||||
HttpOnly: true,
|
||||
Secure: !config.InsecureCookie,
|
||||
Expires: time.Now().Local().Add(time.Hour * -1),
|
||||
}
|
||||
}
|
||||
|
||||
func buildCSRFCookieName(nonce string) string {
|
||||
return config.CSRFCookieName + "_" + nonce[:6]
|
||||
}
|
||||
|
||||
// MakeCSRFCookie makes a csrf cookie (used during login only)
|
||||
//
|
||||
// Note, CSRF cookies live shorter than auth cookies, a fixed 1h.
|
||||
// That's because some CSRF cookies may belong to auth flows that don't complete
|
||||
// and thus may not get cleared by ClearCookie.
|
||||
func MakeCSRFCookie(r *http.Request, nonce string) *http.Cookie {
|
||||
return &http.Cookie{
|
||||
Name: config.CSRFCookieName,
|
||||
Name: buildCSRFCookieName(nonce),
|
||||
Value: nonce,
|
||||
Path: "/",
|
||||
Domain: csrfCookieDomain(r),
|
||||
HttpOnly: true,
|
||||
Secure: !config.InsecureCookie,
|
||||
Expires: cookieExpiry(),
|
||||
Expires: time.Now().Local().Add(time.Hour * 1),
|
||||
}
|
||||
}
|
||||
|
||||
// Create a cookie to clear csrf cookie
|
||||
func ClearCSRFCookie(r *http.Request) *http.Cookie {
|
||||
// ClearCSRFCookie makes an expired csrf cookie to clear csrf cookie
|
||||
func ClearCSRFCookie(r *http.Request, c *http.Cookie) *http.Cookie {
|
||||
return &http.Cookie{
|
||||
Name: config.CSRFCookieName,
|
||||
Name: c.Name,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Domain: csrfCookieDomain(r),
|
||||
@@ -195,29 +225,49 @@ func ClearCSRFCookie(r *http.Request) *http.Cookie {
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the csrf cookie against state
|
||||
func ValidateCSRFCookie(r *http.Request, c *http.Cookie) (bool, string, error) {
|
||||
state := r.URL.Query().Get("state")
|
||||
// FindCSRFCookie extracts the CSRF cookie from the request based on state.
|
||||
func FindCSRFCookie(r *http.Request, state string) (c *http.Cookie, err error) {
|
||||
// Check for CSRF cookie
|
||||
return r.Cookie(buildCSRFCookieName(state))
|
||||
}
|
||||
|
||||
// ValidateCSRFCookie validates the csrf cookie against state
|
||||
func ValidateCSRFCookie(c *http.Cookie, state string) (valid bool, provider string, redirect string, err error) {
|
||||
if len(c.Value) != 32 {
|
||||
return false, "", errors.New("Invalid CSRF cookie value")
|
||||
}
|
||||
|
||||
if len(state) < 34 {
|
||||
return false, "", errors.New("Invalid CSRF state value")
|
||||
return false, "", "", errors.New("Invalid CSRF cookie value")
|
||||
}
|
||||
|
||||
// Check nonce match
|
||||
if c.Value != state[:32] {
|
||||
return false, "", errors.New("CSRF cookie does not match state")
|
||||
return false, "", "", errors.New("CSRF cookie does not match state")
|
||||
}
|
||||
|
||||
// Valid, return redirect
|
||||
return true, state[33:], nil
|
||||
// Extract provider
|
||||
params := state[33:]
|
||||
split := strings.Index(params, ":")
|
||||
if split == -1 {
|
||||
return false, "", "", errors.New("Invalid CSRF state format")
|
||||
}
|
||||
|
||||
// Valid, return provider and redirect
|
||||
return true, params[:split], params[split+1:], nil
|
||||
}
|
||||
|
||||
// MakeState generates a state value
|
||||
func MakeState(r *http.Request, p provider.Provider, nonce string) string {
|
||||
return fmt.Sprintf("%s:%s:%s", nonce, p.Name(), returnUrl(r))
|
||||
}
|
||||
|
||||
// ValidateState checks whether the state is of right length.
|
||||
func ValidateState(state string) error {
|
||||
if len(state) < 34 {
|
||||
return errors.New("Invalid CSRF state value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Nonce generates a random nonce
|
||||
func Nonce() (error, string) {
|
||||
// Make nonce
|
||||
nonce := make([]byte, 16)
|
||||
_, err := rand.Read(nonce)
|
||||
if err != nil {
|
||||
@@ -229,10 +279,8 @@ func Nonce() (error, string) {
|
||||
|
||||
// Cookie domain
|
||||
func cookieDomain(r *http.Request) string {
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
|
||||
// Check if any of the given cookie domains matches
|
||||
_, domain := matchCookieDomains(host)
|
||||
_, domain := matchCookieDomains(r.Host)
|
||||
return domain
|
||||
}
|
||||
|
||||
@@ -242,7 +290,7 @@ func csrfCookieDomain(r *http.Request) string {
|
||||
if use, domain := useAuthDomain(r); use {
|
||||
host = domain
|
||||
} else {
|
||||
host = r.Header.Get("X-Forwarded-Host")
|
||||
host = r.Host
|
||||
}
|
||||
|
||||
// Remove port
|
||||
@@ -273,21 +321,20 @@ func cookieSignature(r *http.Request, email, expires string) string {
|
||||
return base64.URLEncoding.EncodeToString(hash.Sum(nil))
|
||||
}
|
||||
|
||||
// Get cookie expirary
|
||||
// Get cookie expiry
|
||||
func cookieExpiry() time.Time {
|
||||
return time.Now().Local().Add(config.Lifetime)
|
||||
}
|
||||
|
||||
// Cookie Domain
|
||||
|
||||
// Cookie Domain
|
||||
// CookieDomain holds cookie domain info
|
||||
type CookieDomain struct {
|
||||
Domain string `description:"TEST1"`
|
||||
DomainLen int `description:"TEST2"`
|
||||
SubDomain string `description:"TEST3"`
|
||||
SubDomainLen int `description:"TEST4"`
|
||||
Domain string
|
||||
DomainLen int
|
||||
SubDomain string
|
||||
SubDomainLen int
|
||||
}
|
||||
|
||||
// NewCookieDomain creates a new CookieDomain from the given domain string
|
||||
func NewCookieDomain(domain string) *CookieDomain {
|
||||
return &CookieDomain{
|
||||
Domain: domain,
|
||||
@@ -297,6 +344,7 @@ func NewCookieDomain(domain string) *CookieDomain {
|
||||
}
|
||||
}
|
||||
|
||||
// Match checks if the given host matches this CookieDomain
|
||||
func (c *CookieDomain) Match(host string) bool {
|
||||
// Exact domain match?
|
||||
if host == c.Domain {
|
||||
@@ -311,19 +359,22 @@ func (c *CookieDomain) Match(host string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// UnmarshalFlag converts a string to a CookieDomain
|
||||
func (c *CookieDomain) UnmarshalFlag(value string) error {
|
||||
*c = *NewCookieDomain(value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalFlag converts a CookieDomain to a string
|
||||
func (c *CookieDomain) MarshalFlag() (string, error) {
|
||||
return c.Domain, nil
|
||||
}
|
||||
|
||||
// Legacy support for comma separated list of cookie domains
|
||||
|
||||
// CookieDomains provides legacy sypport for comma separated list of cookie domains
|
||||
type CookieDomains []CookieDomain
|
||||
|
||||
// UnmarshalFlag converts a comma separated list of cookie domains to an array
|
||||
// of CookieDomains
|
||||
func (c *CookieDomains) UnmarshalFlag(value string) error {
|
||||
if len(value) > 0 {
|
||||
for _, d := range strings.Split(value, ",") {
|
||||
@@ -334,6 +385,7 @@ func (c *CookieDomains) UnmarshalFlag(value string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalFlag converts an array of CookieDomain to a comma seperated list
|
||||
func (c *CookieDomains) MarshalFlag() (string, error) {
|
||||
var domains []string
|
||||
for _, d := range *c {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tfa
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -66,168 +66,194 @@ func TestAuthValidateEmail(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
|
||||
// Should allow any
|
||||
v := ValidateEmail("test@test.com")
|
||||
// Should allow any with no whitelist/domain is specified
|
||||
v := ValidateEmail("test@test.com", "default")
|
||||
assert.True(v, "should allow any domain if email domain is not defined")
|
||||
v = ValidateEmail("one@two.com")
|
||||
v = ValidateEmail("one@two.com", "default")
|
||||
assert.True(v, "should allow any domain if email domain is not defined")
|
||||
|
||||
// Should block non matching domain
|
||||
config.Domains = []string{"test.com"}
|
||||
v = ValidateEmail("one@two.com")
|
||||
assert.False(v, "should not allow user from another domain")
|
||||
|
||||
// Should allow matching domain
|
||||
config.Domains = []string{"test.com"}
|
||||
v = ValidateEmail("test@test.com")
|
||||
v = ValidateEmail("one@two.com", "default")
|
||||
assert.False(v, "should not allow user from another domain")
|
||||
v = ValidateEmail("test@test.com", "default")
|
||||
assert.True(v, "should allow user from allowed domain")
|
||||
|
||||
// Should block non whitelisted email address
|
||||
config.Domains = []string{}
|
||||
config.Whitelist = []string{"test@test.com"}
|
||||
v = ValidateEmail("one@two.com")
|
||||
assert.False(v, "should not allow user not in whitelist")
|
||||
|
||||
// Should allow matching whitelisted email address
|
||||
config.Domains = []string{}
|
||||
config.Whitelist = []string{"test@test.com"}
|
||||
v = ValidateEmail("test@test.com")
|
||||
v = ValidateEmail("one@two.com", "default")
|
||||
assert.False(v, "should not allow user not in whitelist")
|
||||
v = ValidateEmail("test@test.com", "default")
|
||||
assert.True(v, "should allow user in whitelist")
|
||||
|
||||
// Should allow only matching email address when
|
||||
// MatchWhitelistOrDomain is disabled
|
||||
config.Domains = []string{"example.com"}
|
||||
config.Whitelist = []string{"test@test.com"}
|
||||
config.MatchWhitelistOrDomain = false
|
||||
v = ValidateEmail("one@two.com", "default")
|
||||
assert.False(v, "should not allow user not in either")
|
||||
v = ValidateEmail("test@example.com", "default")
|
||||
assert.False(v, "should not allow user from allowed domain")
|
||||
v = ValidateEmail("test@test.com", "default")
|
||||
assert.True(v, "should allow user in whitelist")
|
||||
|
||||
// Should allow either matching domain or email address when
|
||||
// MatchWhitelistOrDomain is enabled
|
||||
config.Domains = []string{"example.com"}
|
||||
config.Whitelist = []string{"test@test.com"}
|
||||
config.MatchWhitelistOrDomain = true
|
||||
v = ValidateEmail("one@two.com", "default")
|
||||
assert.False(v, "should not allow user not in either")
|
||||
v = ValidateEmail("test@example.com", "default")
|
||||
assert.True(v, "should allow user from allowed domain")
|
||||
v = ValidateEmail("test@test.com", "default")
|
||||
assert.True(v, "should allow user in whitelist")
|
||||
|
||||
// Rule testing
|
||||
|
||||
// Should use global whitelist/domain when not specified on rule
|
||||
config.Domains = []string{"example.com"}
|
||||
config.Whitelist = []string{"test@test.com"}
|
||||
config.Rules = map[string]*Rule{"test": NewRule()}
|
||||
config.MatchWhitelistOrDomain = true
|
||||
v = ValidateEmail("one@two.com", "test")
|
||||
assert.False(v, "should not allow user not in either")
|
||||
v = ValidateEmail("test@example.com", "test")
|
||||
assert.True(v, "should allow user from allowed global domain")
|
||||
v = ValidateEmail("test@test.com", "test")
|
||||
assert.True(v, "should allow user in global whitelist")
|
||||
|
||||
// Should allow matching domain in rule
|
||||
config.Domains = []string{"testglobal.com"}
|
||||
config.Whitelist = []string{}
|
||||
rule := NewRule()
|
||||
config.Rules = map[string]*Rule{"test": rule}
|
||||
rule.Domains = []string{"testrule.com"}
|
||||
config.MatchWhitelistOrDomain = false
|
||||
v = ValidateEmail("one@two.com", "test")
|
||||
assert.False(v, "should not allow user from another domain")
|
||||
v = ValidateEmail("one@testglobal.com", "test")
|
||||
assert.False(v, "should not allow user from global domain")
|
||||
v = ValidateEmail("test@testrule.com", "test")
|
||||
assert.True(v, "should allow user from allowed domain")
|
||||
|
||||
// Should allow matching whitelist in rule
|
||||
config.Domains = []string{}
|
||||
config.Whitelist = []string{"test@testglobal.com"}
|
||||
rule = NewRule()
|
||||
config.Rules = map[string]*Rule{"test": rule}
|
||||
rule.Whitelist = []string{"test@testrule.com"}
|
||||
config.MatchWhitelistOrDomain = false
|
||||
v = ValidateEmail("one@two.com", "test")
|
||||
assert.False(v, "should not allow user from another domain")
|
||||
v = ValidateEmail("test@testglobal.com", "test")
|
||||
assert.False(v, "should not allow user from global domain")
|
||||
v = ValidateEmail("test@testrule.com", "test")
|
||||
assert.True(v, "should allow user from allowed domain")
|
||||
|
||||
// Should allow only matching email address when
|
||||
// MatchWhitelistOrDomain is disabled
|
||||
config.Domains = []string{"exampleglobal.com"}
|
||||
config.Whitelist = []string{"test@testglobal.com"}
|
||||
rule = NewRule()
|
||||
config.Rules = map[string]*Rule{"test": rule}
|
||||
rule.Domains = []string{"examplerule.com"}
|
||||
rule.Whitelist = []string{"test@testrule.com"}
|
||||
config.MatchWhitelistOrDomain = false
|
||||
v = ValidateEmail("one@two.com", "test")
|
||||
assert.False(v, "should not allow user not in either")
|
||||
v = ValidateEmail("test@testglobal.com", "test")
|
||||
assert.False(v, "should not allow user in global whitelist")
|
||||
v = ValidateEmail("test@exampleglobal.com", "test")
|
||||
assert.False(v, "should not allow user from global domain")
|
||||
v = ValidateEmail("test@examplerule.com", "test")
|
||||
assert.False(v, "should not allow user from allowed domain")
|
||||
v = ValidateEmail("test@testrule.com", "test")
|
||||
assert.True(v, "should allow user in whitelist")
|
||||
|
||||
// Should allow either matching domain or email address when
|
||||
// MatchWhitelistOrDomain is enabled
|
||||
config.Domains = []string{"exampleglobal.com"}
|
||||
config.Whitelist = []string{"test@testglobal.com"}
|
||||
rule = NewRule()
|
||||
config.Rules = map[string]*Rule{"test": rule}
|
||||
rule.Domains = []string{"examplerule.com"}
|
||||
rule.Whitelist = []string{"test@testrule.com"}
|
||||
config.MatchWhitelistOrDomain = true
|
||||
v = ValidateEmail("one@two.com", "test")
|
||||
assert.False(v, "should not allow user not in either")
|
||||
v = ValidateEmail("test@testglobal.com", "test")
|
||||
assert.False(v, "should not allow user in global whitelist")
|
||||
v = ValidateEmail("test@exampleglobal.com", "test")
|
||||
assert.False(v, "should not allow user from global domain")
|
||||
v = ValidateEmail("test@examplerule.com", "test")
|
||||
assert.True(v, "should allow user from allowed domain")
|
||||
v = ValidateEmail("test@testrule.com", "test")
|
||||
assert.True(v, "should allow user in whitelist")
|
||||
}
|
||||
|
||||
// TODO: Split google tests out
|
||||
func TestAuthGetLoginURL(t *testing.T) {
|
||||
func TestRedirectUri(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
google := provider.Google{
|
||||
ClientId: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
Scope: "scopetest",
|
||||
Prompt: "consent select_account",
|
||||
LoginURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "test.com",
|
||||
Path: "/auth",
|
||||
},
|
||||
}
|
||||
|
||||
config, _ = NewConfig([]string{})
|
||||
config.Providers.Google = google
|
||||
|
||||
r, _ := http.NewRequest("GET", "http://example.com", nil)
|
||||
r := httptest.NewRequest("GET", "http://app.example.com/hello", 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(GetLoginURL(r, "nonce"))
|
||||
//
|
||||
// No Auth Host
|
||||
//
|
||||
config, _ = NewConfig([]string{})
|
||||
|
||||
uri, err := url.Parse(redirectUri(r))
|
||||
assert.Nil(err)
|
||||
assert.Equal("https", uri.Scheme)
|
||||
assert.Equal("test.com", uri.Host)
|
||||
assert.Equal("/auth", 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"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
assert.Equal("http", uri.Scheme)
|
||||
assert.Equal("app.example.com", uri.Host)
|
||||
assert.Equal("/_oauth", uri.Path)
|
||||
|
||||
//
|
||||
// With Auth URL but no matching cookie domain
|
||||
// - will not use auth host
|
||||
//
|
||||
config, _ = NewConfig([]string{})
|
||||
config.AuthHost = "auth.example.com"
|
||||
config.Providers.Google = google
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(GetLoginURL(r, "nonce"))
|
||||
uri, err = url.Parse(redirectUri(r))
|
||||
assert.Nil(err)
|
||||
assert.Equal("https", uri.Scheme)
|
||||
assert.Equal("test.com", uri.Host)
|
||||
assert.Equal("/auth", 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"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
assert.Equal("http", uri.Scheme)
|
||||
assert.Equal("app.example.com", uri.Host)
|
||||
assert.Equal("/_oauth", uri.Path)
|
||||
|
||||
//
|
||||
// With correct Auth URL + cookie domain
|
||||
//
|
||||
config, _ = NewConfig([]string{})
|
||||
config.AuthHost = "auth.example.com"
|
||||
config.CookieDomains = []CookieDomain{*NewCookieDomain("example.com")}
|
||||
config.Providers.Google = google
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(GetLoginURL(r, "nonce"))
|
||||
uri, err = url.Parse(redirectUri(r))
|
||||
assert.Nil(err)
|
||||
assert.Equal("https", uri.Scheme)
|
||||
assert.Equal("test.com", uri.Host)
|
||||
assert.Equal("/auth", 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"},
|
||||
"prompt": []string{"consent select_account"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
assert.Equal("http", uri.Scheme)
|
||||
assert.Equal("auth.example.com", uri.Host)
|
||||
assert.Equal("/_oauth", uri.Path)
|
||||
|
||||
//
|
||||
// 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")
|
||||
r = httptest.NewRequest("GET", "https://another.com/hello", nil)
|
||||
r.Header.Add("X-Forwarded-Proto", "https")
|
||||
|
||||
config.AuthHost = "auth.example.com"
|
||||
config.CookieDomains = []CookieDomain{*NewCookieDomain("example.com")}
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(GetLoginURL(r, "nonce"))
|
||||
uri, err = url.Parse(redirectUri(r))
|
||||
assert.Nil(err)
|
||||
assert.Equal("https", uri.Scheme)
|
||||
assert.Equal("test.com", uri.Host)
|
||||
assert.Equal("/auth", 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"},
|
||||
"prompt": []string{"consent select_account"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
assert.Equal("another.com", uri.Host)
|
||||
assert.Equal("/_oauth", uri.Path)
|
||||
}
|
||||
|
||||
// TODO
|
||||
// func TestAuthExchangeCode(t *testing.T) {
|
||||
// }
|
||||
|
||||
// TODO
|
||||
// func TestAuthGetUser(t *testing.T) {
|
||||
// }
|
||||
|
||||
func TestAuthMakeCookie(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
@@ -262,29 +288,30 @@ func TestAuthMakeCSRFCookie(t *testing.T) {
|
||||
|
||||
// No cookie domain or auth url
|
||||
c := MakeCSRFCookie(r, "12345678901234567890123456789012")
|
||||
assert.Equal("_forward_auth_csrf_123456", c.Name)
|
||||
assert.Equal("app.example.com", c.Domain)
|
||||
|
||||
// With cookie domain but no auth url
|
||||
config = Config{
|
||||
CookieDomains: []CookieDomain{*NewCookieDomain("example.com")},
|
||||
}
|
||||
c = MakeCSRFCookie(r, "12345678901234567890123456789012")
|
||||
config.CookieDomains = []CookieDomain{*NewCookieDomain("example.com")}
|
||||
c = MakeCSRFCookie(r, "12222278901234567890123456789012")
|
||||
assert.Equal("_forward_auth_csrf_122222", c.Name)
|
||||
assert.Equal("app.example.com", c.Domain)
|
||||
|
||||
// With cookie domain and auth url
|
||||
config = Config{
|
||||
AuthHost: "auth.example.com",
|
||||
CookieDomains: []CookieDomain{*NewCookieDomain("example.com")},
|
||||
}
|
||||
c = MakeCSRFCookie(r, "12345678901234567890123456789012")
|
||||
config.AuthHost = "auth.example.com"
|
||||
config.CookieDomains = []CookieDomain{*NewCookieDomain("example.com")}
|
||||
c = MakeCSRFCookie(r, "12333378901234567890123456789012")
|
||||
assert.Equal("_forward_auth_csrf_123333", c.Name)
|
||||
assert.Equal("example.com", c.Domain)
|
||||
}
|
||||
|
||||
func TestAuthClearCSRFCookie(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
r, _ := http.NewRequest("GET", "http://example.com", nil)
|
||||
|
||||
c := ClearCSRFCookie(r)
|
||||
c := ClearCSRFCookie(r, &http.Cookie{Name: "someCsrfCookie"})
|
||||
assert.Equal("someCsrfCookie", c.Name)
|
||||
if c.Value != "" {
|
||||
t.Error("ClearCSRFCookie should create cookie with empty value")
|
||||
}
|
||||
@@ -294,44 +321,77 @@ func TestAuthValidateCSRFCookie(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
c := &http.Cookie{}
|
||||
|
||||
newCsrfRequest := func(state string) *http.Request {
|
||||
u := fmt.Sprintf("http://example.com?state=%s", state)
|
||||
r, _ := http.NewRequest("GET", u, nil)
|
||||
return r
|
||||
}
|
||||
state := ""
|
||||
|
||||
// Should require 32 char string
|
||||
r := newCsrfRequest("")
|
||||
state = ""
|
||||
c.Value = ""
|
||||
valid, _, err := ValidateCSRFCookie(r, c)
|
||||
valid, _, _, err := ValidateCSRFCookie(c, state)
|
||||
assert.False(valid)
|
||||
if assert.Error(err) {
|
||||
assert.Equal("Invalid CSRF cookie value", err.Error())
|
||||
}
|
||||
c.Value = "123456789012345678901234567890123"
|
||||
valid, _, err = ValidateCSRFCookie(r, c)
|
||||
valid, _, _, err = ValidateCSRFCookie(c, state)
|
||||
assert.False(valid)
|
||||
if assert.Error(err) {
|
||||
assert.Equal("Invalid CSRF cookie value", err.Error())
|
||||
}
|
||||
|
||||
// Should require valid state
|
||||
r = newCsrfRequest("12345678901234567890123456789012:")
|
||||
// Should require provider
|
||||
state = "12345678901234567890123456789012:99"
|
||||
c.Value = "12345678901234567890123456789012"
|
||||
valid, _, err = ValidateCSRFCookie(r, c)
|
||||
valid, _, _, err = ValidateCSRFCookie(c, state)
|
||||
assert.False(valid)
|
||||
if assert.Error(err) {
|
||||
assert.Equal("Invalid CSRF state value", err.Error())
|
||||
assert.Equal("Invalid CSRF state format", err.Error())
|
||||
}
|
||||
|
||||
// Should allow valid state
|
||||
r = newCsrfRequest("12345678901234567890123456789012:99")
|
||||
state = "12345678901234567890123456789012:p99:url123"
|
||||
c.Value = "12345678901234567890123456789012"
|
||||
valid, state, err := ValidateCSRFCookie(r, c)
|
||||
valid, provider, redirect, err := ValidateCSRFCookie(c, state)
|
||||
assert.True(valid, "valid request should return valid")
|
||||
assert.Nil(err, "valid request should not return an error")
|
||||
assert.Equal("99", state, "valid request should return correct state")
|
||||
assert.Equal("p99", provider, "valid request should return correct provider")
|
||||
assert.Equal("url123", redirect, "valid request should return correct redirect")
|
||||
}
|
||||
|
||||
func TestValidateState(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Should require valid state
|
||||
state := "12345678901234567890123456789012:"
|
||||
err := ValidateState(state)
|
||||
if assert.Error(err) {
|
||||
assert.Equal("Invalid CSRF state value", err.Error())
|
||||
}
|
||||
// Should pass this state
|
||||
state = "12345678901234567890123456789012:p99:url123"
|
||||
err = ValidateState(state)
|
||||
assert.Nil(err, "valid request should not return an error")
|
||||
}
|
||||
|
||||
func TestMakeState(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
r := httptest.NewRequest("GET", "http://example.com/hello", nil)
|
||||
r.Header.Add("X-Forwarded-Proto", "http")
|
||||
|
||||
// Test with google
|
||||
p := provider.Google{}
|
||||
state := MakeState(r, &p, "nonce")
|
||||
assert.Equal("nonce:google:http://example.com/hello", state)
|
||||
|
||||
// Test with OIDC
|
||||
p2 := provider.OIDC{}
|
||||
state = MakeState(r, &p2, "nonce")
|
||||
assert.Equal("nonce:oidc:http://example.com/hello", state)
|
||||
|
||||
// Test with Generic OAuth
|
||||
p3 := provider.GenericOAuth{}
|
||||
state = MakeState(r, &p3, "nonce")
|
||||
assert.Equal("nonce:generic-oauth:http://example.com/hello", state)
|
||||
}
|
||||
|
||||
func TestAuthNonce(t *testing.T) {
|
||||
@@ -356,6 +416,8 @@ func TestAuthCookieDomainMatch(t *testing.T) {
|
||||
|
||||
// Subdomain should match
|
||||
assert.True(cd.Match("test.example.com"), "subdomain should match")
|
||||
assert.True(cd.Match("twolevels.test.example.com"), "subdomain should match")
|
||||
assert.True(cd.Match("many.many.levels.test.example.com"), "subdomain should match")
|
||||
|
||||
// Derived domain should not match
|
||||
assert.False(cd.Match("testexample.com"), "derived domain should not match")
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -18,27 +17,32 @@ import (
|
||||
"github.com/thomseddon/traefik-forward-auth/internal/provider"
|
||||
)
|
||||
|
||||
var config Config
|
||||
var config *Config
|
||||
|
||||
// Config holds the runtime application config
|
||||
type Config struct {
|
||||
LogLevel string `long:"log-level" env:"LOG_LEVEL" default:"warn" choice:"trace" choice:"debug" choice:"info" choice:"warn" choice:"error" choice:"fatal" choice:"panic" description:"Log level"`
|
||||
LogFormat string `long:"log-format" env:"LOG_FORMAT" default:"text" choice:"text" choice:"json" choice:"pretty" description:"Log format"`
|
||||
|
||||
AuthHost string `long:"auth-host" env:"AUTH_HOST" description:"Single host to use when returning from 3rd party auth"`
|
||||
Config func(s string) error `long:"config" env:"CONFIG" description:"Path to config file" json:"-"`
|
||||
CookieDomains []CookieDomain `long:"cookie-domain" env:"COOKIE_DOMAIN" description:"Domain to set auth cookie on, can be set multiple times"`
|
||||
InsecureCookie bool `long:"insecure-cookie" env:"INSECURE_COOKIE" description:"Use insecure cookies"`
|
||||
CookieName string `long:"cookie-name" env:"COOKIE_NAME" default:"_forward_auth" description:"Cookie Name"`
|
||||
CSRFCookieName string `long:"csrf-cookie-name" env:"CSRF_COOKIE_NAME" default:"_forward_auth_csrf" description:"CSRF Cookie Name"`
|
||||
DefaultAction string `long:"default-action" env:"DEFAULT_ACTION" default:"auth" choice:"auth" choice:"allow" description:"Default action"`
|
||||
Domains CommaSeparatedList `long:"domain" env:"DOMAIN" description:"Only allow given email domains, can be set multiple times"`
|
||||
LifetimeString int `long:"lifetime" env:"LIFETIME" default:"43200" description:"Lifetime in seconds"`
|
||||
Path string `long:"url-path" env:"URL_PATH" default:"/_oauth" description:"Callback URL Path"`
|
||||
SecretString string `long:"secret" env:"SECRET" description:"Secret used for signing (required)" json:"-"`
|
||||
Whitelist CommaSeparatedList `long:"whitelist" env:"WHITELIST" description:"Only allow given email addresses, can be set multiple times"`
|
||||
AuthHost string `long:"auth-host" env:"AUTH_HOST" description:"Single host to use when returning from 3rd party auth"`
|
||||
Config func(s string) error `long:"config" env:"CONFIG" description:"Path to config file" json:"-"`
|
||||
CookieDomains []CookieDomain `long:"cookie-domain" env:"COOKIE_DOMAIN" env-delim:"," description:"Domain to set auth cookie on, can be set multiple times"`
|
||||
InsecureCookie bool `long:"insecure-cookie" env:"INSECURE_COOKIE" description:"Use insecure cookies"`
|
||||
CookieName string `long:"cookie-name" env:"COOKIE_NAME" default:"_forward_auth" description:"Cookie Name"`
|
||||
CSRFCookieName string `long:"csrf-cookie-name" env:"CSRF_COOKIE_NAME" default:"_forward_auth_csrf" description:"CSRF Cookie Name"`
|
||||
DefaultAction string `long:"default-action" env:"DEFAULT_ACTION" default:"auth" choice:"auth" choice:"allow" description:"Default action"`
|
||||
DefaultProvider string `long:"default-provider" env:"DEFAULT_PROVIDER" default:"google" choice:"google" choice:"oidc" choice:"generic-oauth" description:"Default provider"`
|
||||
Domains CommaSeparatedList `long:"domain" env:"DOMAIN" env-delim:"," description:"Only allow given email domains, can be set multiple times"`
|
||||
LifetimeString int `long:"lifetime" env:"LIFETIME" default:"43200" description:"Lifetime in seconds"`
|
||||
LogoutRedirect string `long:"logout-redirect" env:"LOGOUT_REDIRECT" description:"URL to redirect to following logout"`
|
||||
MatchWhitelistOrDomain bool `long:"match-whitelist-or-domain" env:"MATCH_WHITELIST_OR_DOMAIN" description:"Allow users that match *either* whitelist or domain (enabled by default in v3)"`
|
||||
Path string `long:"url-path" env:"URL_PATH" default:"/_oauth" description:"Callback URL Path"`
|
||||
SecretString string `long:"secret" env:"SECRET" description:"Secret used for signing (required)" json:"-"`
|
||||
Whitelist CommaSeparatedList `long:"whitelist" env:"WHITELIST" env-delim:"," description:"Only allow given email addresses, can be set multiple times"`
|
||||
Port int `long:"port" env:"PORT" default:"4181" description:"Port to listen on"`
|
||||
|
||||
Providers provider.Providers `group:"providers" namespace:"providers" env-namespace:"PROVIDERS"`
|
||||
Rules map[string]*Rule `long:"rules.<name>.<param>" description:"Rule definitions, param can be: \"action\" or \"rule\""`
|
||||
Rules map[string]*Rule `long:"rule.<name>.<param>" description:"Rule definitions, param can be: \"action\", \"rule\" or \"provider\""`
|
||||
|
||||
// Filled during transformations
|
||||
Secret []byte `json:"-"`
|
||||
@@ -48,12 +52,13 @@ type Config struct {
|
||||
CookieDomainsLegacy CookieDomains `long:"cookie-domains" env:"COOKIE_DOMAINS" description:"DEPRECATED - Use \"cookie-domain\""`
|
||||
CookieSecretLegacy string `long:"cookie-secret" env:"COOKIE_SECRET" description:"DEPRECATED - Use \"secret\"" json:"-"`
|
||||
CookieSecureLegacy string `long:"cookie-secure" env:"COOKIE_SECURE" description:"DEPRECATED - Use \"insecure-cookie\""`
|
||||
ClientIdLegacy string `long:"client-id" env:"CLIENT_ID" group:"DEPs" description:"DEPRECATED - Use \"providers.google.client-id\""`
|
||||
ClientIdLegacy string `long:"client-id" env:"CLIENT_ID" description:"DEPRECATED - Use \"providers.google.client-id\""`
|
||||
ClientSecretLegacy string `long:"client-secret" env:"CLIENT_SECRET" description:"DEPRECATED - Use \"providers.google.client-id\"" json:"-"`
|
||||
PromptLegacy string `long:"prompt" env:"PROMPT" description:"DEPRECATED - Use \"providers.google.prompt\""`
|
||||
}
|
||||
|
||||
func NewGlobalConfig() Config {
|
||||
// NewGlobalConfig creates a new global config, parsed from command arguments
|
||||
func NewGlobalConfig() *Config {
|
||||
var err error
|
||||
config, err = NewConfig(os.Args[1:])
|
||||
if err != nil {
|
||||
@@ -64,29 +69,12 @@ func NewGlobalConfig() Config {
|
||||
return config
|
||||
}
|
||||
|
||||
func NewConfig(args []string) (Config, error) {
|
||||
c := Config{
|
||||
// TODO: move config parsing into new func "NewParsedConfig"
|
||||
|
||||
// NewConfig parses and validates provided configuration into a config object
|
||||
func NewConfig(args []string) (*Config, error) {
|
||||
c := &Config{
|
||||
Rules: map[string]*Rule{},
|
||||
Providers: provider.Providers{
|
||||
Google: provider.Google{
|
||||
Scope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
|
||||
LoginURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "accounts.google.com",
|
||||
Path: "/o/oauth2/auth",
|
||||
},
|
||||
TokenURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v3/token",
|
||||
},
|
||||
UserURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v2/userinfo",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := c.parseFlags(args)
|
||||
@@ -97,13 +85,23 @@ func NewConfig(args []string) (Config, error) {
|
||||
// TODO: as log flags have now been parsed maybe we should return here so
|
||||
// any further errors can be logged via logrus instead of printed?
|
||||
|
||||
// TODO: Rename "Validate" method to "Setup" and move all below logic
|
||||
|
||||
// Setup
|
||||
// Set default provider on any rules where it's not specified
|
||||
for _, rule := range c.Rules {
|
||||
if rule.Provider == "" {
|
||||
rule.Provider = c.DefaultProvider
|
||||
}
|
||||
}
|
||||
|
||||
// Backwards compatability
|
||||
if c.CookieSecretLegacy != "" && c.SecretString == "" {
|
||||
fmt.Println("cookie-secret config option is deprecated, please use secret")
|
||||
c.SecretString = c.CookieSecretLegacy
|
||||
}
|
||||
if c.ClientIdLegacy != "" {
|
||||
c.Providers.Google.ClientId = c.ClientIdLegacy
|
||||
c.Providers.Google.ClientID = c.ClientIdLegacy
|
||||
}
|
||||
if c.ClientSecretLegacy != "" {
|
||||
c.Providers.Google.ClientSecret = c.ClientSecretLegacy
|
||||
@@ -161,7 +159,7 @@ func (c *Config) parseFlags(args []string) error {
|
||||
|
||||
_, err := p.ParseArgs(args)
|
||||
if err != nil {
|
||||
return handlFlagError(err)
|
||||
return handleFlagError(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -213,8 +211,16 @@ func (c *Config) parseUnknownFlag(option string, arg flags.SplitArgument, args [
|
||||
rule.Rule = val
|
||||
case "provider":
|
||||
rule.Provider = val
|
||||
case "whitelist":
|
||||
list := CommaSeparatedList{}
|
||||
list.UnmarshalFlag(val)
|
||||
rule.Whitelist = list
|
||||
case "domains":
|
||||
list := CommaSeparatedList{}
|
||||
list.UnmarshalFlag(val)
|
||||
rule.Domains = list
|
||||
default:
|
||||
return args, fmt.Errorf("inavlid route param: %v", option)
|
||||
return args, fmt.Errorf("invalid route param: %v", option)
|
||||
}
|
||||
} else {
|
||||
return args, fmt.Errorf("unknown flag: %v", option)
|
||||
@@ -223,7 +229,7 @@ func (c *Config) parseUnknownFlag(option string, arg flags.SplitArgument, args [
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func handlFlagError(err error) error {
|
||||
func handleFlagError(err error) error {
|
||||
flagsErr, ok := err.(*flags.Error)
|
||||
if ok && flagsErr.Type == flags.ErrHelp {
|
||||
// Library has just printed cli help
|
||||
@@ -244,19 +250,25 @@ func convertLegacyToIni(name string) (io.Reader, error) {
|
||||
return bytes.NewReader(legacyFileFormat.ReplaceAll(b, []byte("$1=$2"))), nil
|
||||
}
|
||||
|
||||
// Validate validates a config object
|
||||
func (c *Config) Validate() {
|
||||
// Check for show stopper errors
|
||||
if len(c.Secret) == 0 {
|
||||
log.Fatal("\"secret\" option must be set.")
|
||||
log.Fatal("\"secret\" option must be set")
|
||||
}
|
||||
|
||||
if c.Providers.Google.ClientId == "" || c.Providers.Google.ClientSecret == "" {
|
||||
log.Fatal("providers.google.client-id, providers.google.client-secret must be set")
|
||||
// Setup default provider
|
||||
err := c.setupProvider(c.DefaultProvider)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Check rules
|
||||
// Check rules (validates the rule and the rule provider)
|
||||
for _, rule := range c.Rules {
|
||||
rule.Validate()
|
||||
err = rule.Validate(c)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,16 +277,76 @@ func (c Config) String() string {
|
||||
return string(jsonConf)
|
||||
}
|
||||
|
||||
type Rule struct {
|
||||
Action string
|
||||
Rule string
|
||||
Provider string
|
||||
// GetProvider returns the provider of the given name
|
||||
func (c *Config) GetProvider(name string) (provider.Provider, error) {
|
||||
switch name {
|
||||
case "google":
|
||||
return &c.Providers.Google, nil
|
||||
case "oidc":
|
||||
return &c.Providers.OIDC, nil
|
||||
case "generic-oauth":
|
||||
return &c.Providers.GenericOAuth, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("Unknown provider: %s", name)
|
||||
}
|
||||
|
||||
// GetConfiguredProvider returns the provider of the given name, if it has been
|
||||
// configured. Returns an error if the provider is unknown, or hasn't been configured
|
||||
func (c *Config) GetConfiguredProvider(name string) (provider.Provider, error) {
|
||||
// Check the provider has been configured
|
||||
if !c.providerConfigured(name) {
|
||||
return nil, fmt.Errorf("Unconfigured provider: %s", name)
|
||||
}
|
||||
|
||||
return c.GetProvider(name)
|
||||
}
|
||||
|
||||
func (c *Config) providerConfigured(name string) bool {
|
||||
// Check default provider
|
||||
if name == c.DefaultProvider {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check rule providers
|
||||
for _, rule := range c.Rules {
|
||||
if name == rule.Provider {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Config) setupProvider(name string) error {
|
||||
// Check provider exists
|
||||
p, err := c.GetProvider(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Setup
|
||||
err = p.Setup()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rule holds defined rules
|
||||
type Rule struct {
|
||||
Action string
|
||||
Rule string
|
||||
Provider string
|
||||
Whitelist CommaSeparatedList
|
||||
Domains CommaSeparatedList
|
||||
}
|
||||
|
||||
// NewRule creates a new rule object
|
||||
func NewRule() *Rule {
|
||||
return &Rule{
|
||||
Action: "auth",
|
||||
Provider: "google", // TODO: Use default provider
|
||||
Action: "auth",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,26 +356,27 @@ func (r *Rule) formattedRule() string {
|
||||
return strings.ReplaceAll(r.Rule, "Host(", "HostRegexp(")
|
||||
}
|
||||
|
||||
func (r *Rule) Validate() {
|
||||
// Validate validates a rule
|
||||
func (r *Rule) Validate(c *Config) error {
|
||||
if r.Action != "auth" && r.Action != "allow" {
|
||||
log.Fatal("invalid rule action, must be \"auth\" or \"allow\"")
|
||||
return errors.New("invalid rule action, must be \"auth\" or \"allow\"")
|
||||
}
|
||||
|
||||
// TODO: Update with more provider support
|
||||
if r.Provider != "google" {
|
||||
log.Fatal("invalid rule provider, must be \"google\"")
|
||||
}
|
||||
return c.setupProvider(r.Provider)
|
||||
}
|
||||
|
||||
// Legacy support for comma separated lists
|
||||
|
||||
// CommaSeparatedList provides legacy support for config values provided as csv
|
||||
type CommaSeparatedList []string
|
||||
|
||||
// UnmarshalFlag converts a comma separated list to an array
|
||||
func (c *CommaSeparatedList) UnmarshalFlag(value string) error {
|
||||
*c = append(*c, strings.Split(value, ",")...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalFlag converts an array back to a comma separated list
|
||||
func (c *CommaSeparatedList) MarshalFlag() (string, error) {
|
||||
return strings.Join(*c, ","), nil
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package tfa
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
// "fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus/hooks/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -28,34 +30,16 @@ func TestConfigDefaults(t *testing.T) {
|
||||
assert.Equal("_forward_auth", c.CookieName)
|
||||
assert.Equal("_forward_auth_csrf", c.CSRFCookieName)
|
||||
assert.Equal("auth", c.DefaultAction)
|
||||
assert.Equal("google", c.DefaultProvider)
|
||||
assert.Len(c.Domains, 0)
|
||||
assert.Equal(time.Second*time.Duration(43200), c.Lifetime)
|
||||
assert.Equal("", c.LogoutRedirect)
|
||||
assert.False(c.MatchWhitelistOrDomain)
|
||||
assert.Equal("/_oauth", c.Path)
|
||||
assert.Len(c.Whitelist, 0)
|
||||
assert.Equal(c.Port, 4181)
|
||||
|
||||
assert.Equal("https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email", c.Providers.Google.Scope)
|
||||
assert.Equal("", c.Providers.Google.Prompt)
|
||||
|
||||
loginURL := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "accounts.google.com",
|
||||
Path: "/o/oauth2/auth",
|
||||
}
|
||||
assert.Equal(loginURL, c.Providers.Google.LoginURL)
|
||||
|
||||
tokenURL := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v3/token",
|
||||
}
|
||||
assert.Equal(tokenURL, c.Providers.Google.TokenURL)
|
||||
|
||||
userURL := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v2/userinfo",
|
||||
}
|
||||
assert.Equal(userURL, c.Providers.Google.UserURL)
|
||||
assert.Equal("select_account", c.Providers.Google.Prompt)
|
||||
}
|
||||
|
||||
func TestConfigParseArgs(t *testing.T) {
|
||||
@@ -63,28 +47,32 @@ func TestConfigParseArgs(t *testing.T) {
|
||||
c, err := NewConfig([]string{
|
||||
"--cookie-name=cookiename",
|
||||
"--csrf-cookie-name", "\"csrfcookiename\"",
|
||||
"--default-provider", "\"oidc\"",
|
||||
"--rule.1.action=allow",
|
||||
"--rule.1.rule=PathPrefix(`/one`)",
|
||||
"--rule.two.action=auth",
|
||||
"--rule.two.rule=\"Host(`two.com`) && Path(`/two`)\"",
|
||||
"--port=8000",
|
||||
})
|
||||
require.Nil(t, err)
|
||||
|
||||
// Check normal flags
|
||||
assert.Equal("cookiename", c.CookieName)
|
||||
assert.Equal("csrfcookiename", c.CSRFCookieName)
|
||||
assert.Equal("oidc", c.DefaultProvider)
|
||||
assert.Equal(8000, c.Port)
|
||||
|
||||
// Check rules
|
||||
assert.Equal(map[string]*Rule{
|
||||
"1": {
|
||||
Action: "allow",
|
||||
Rule: "PathPrefix(`/one`)",
|
||||
Provider: "google",
|
||||
Provider: "oidc",
|
||||
},
|
||||
"two": {
|
||||
Action: "auth",
|
||||
Rule: "Host(`two.com`) && Path(`/two`)",
|
||||
Provider: "google",
|
||||
Provider: "oidc",
|
||||
},
|
||||
}, c.Rules)
|
||||
}
|
||||
@@ -157,7 +145,7 @@ func TestConfigFlagBackwardsCompatability(t *testing.T) {
|
||||
|
||||
// Google provider params used to be top level
|
||||
assert.Equal("clientid", c.ClientIdLegacy)
|
||||
assert.Equal("clientid", c.Providers.Google.ClientId, "--client-id should set providers.google.client-id")
|
||||
assert.Equal("clientid", c.Providers.Google.ClientID, "--client-id should set providers.google.client-id")
|
||||
assert.Equal("verysecret", c.ClientSecretLegacy)
|
||||
assert.Equal("verysecret", c.Providers.Google.ClientSecret, "--client-secret should set providers.google.client-secret")
|
||||
assert.Equal("prompt", c.PromptLegacy)
|
||||
@@ -216,14 +204,27 @@ func TestConfigParseEnvironment(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
os.Setenv("COOKIE_NAME", "env_cookie_name")
|
||||
os.Setenv("PROVIDERS_GOOGLE_CLIENT_ID", "env_client_id")
|
||||
os.Setenv("COOKIE_DOMAIN", "test1.com,example.org")
|
||||
os.Setenv("DOMAIN", "test2.com,example.org")
|
||||
os.Setenv("WHITELIST", "test3.com,example.org")
|
||||
|
||||
c, err := NewConfig([]string{})
|
||||
assert.Nil(err)
|
||||
|
||||
assert.Equal("env_cookie_name", c.CookieName, "variable should be read from environment")
|
||||
assert.Equal("env_client_id", c.Providers.Google.ClientId, "namespace variable should be read from environment")
|
||||
assert.Equal("env_client_id", c.Providers.Google.ClientID, "namespace variable should be read from environment")
|
||||
assert.Equal([]CookieDomain{
|
||||
*NewCookieDomain("test1.com"),
|
||||
*NewCookieDomain("example.org"),
|
||||
}, c.CookieDomains, "array variable should be read from environment COOKIE_DOMAIN")
|
||||
assert.Equal(CommaSeparatedList{"test2.com", "example.org"}, c.Domains, "array variable should be read from environment DOMAIN")
|
||||
assert.Equal(CommaSeparatedList{"test3.com", "example.org"}, c.Whitelist, "array variable should be read from environment WHITELIST")
|
||||
|
||||
os.Unsetenv("COOKIE_NAME")
|
||||
os.Unsetenv("PROVIDERS_GOOGLE_CLIENT_ID")
|
||||
os.Unsetenv("COOKIE_DOMAIN")
|
||||
os.Unsetenv("DOMAIN")
|
||||
os.Unsetenv("WHITELIST")
|
||||
}
|
||||
|
||||
func TestConfigParseEnvironmentBackwardsCompatability(t *testing.T) {
|
||||
@@ -265,7 +266,7 @@ func TestConfigParseEnvironmentBackwardsCompatability(t *testing.T) {
|
||||
|
||||
// Google provider params used to be top level
|
||||
assert.Equal("clientid", c.ClientIdLegacy)
|
||||
assert.Equal("clientid", c.Providers.Google.ClientId, "--client-id should set providers.google.client-id")
|
||||
assert.Equal("clientid", c.Providers.Google.ClientID, "--client-id should set providers.google.client-id")
|
||||
assert.Equal("verysecret", c.ClientSecretLegacy)
|
||||
assert.Equal("verysecret", c.Providers.Google.ClientSecret, "--client-secret should set providers.google.client-secret")
|
||||
assert.Equal("prompt", c.PromptLegacy)
|
||||
@@ -273,7 +274,7 @@ func TestConfigParseEnvironmentBackwardsCompatability(t *testing.T) {
|
||||
|
||||
// "cookie-secure" used to be a standard go bool flag that could take
|
||||
// true, TRUE, 1, false, FALSE, 0 etc. values.
|
||||
// Here we're checking that format is still suppoted
|
||||
// Here we're checking that format is still supported
|
||||
assert.Equal("false", c.CookieSecureLegacy)
|
||||
assert.True(c.InsecureCookie, "--cookie-secure=false should set insecure-cookie true")
|
||||
|
||||
@@ -305,6 +306,97 @@ func TestConfigTransformation(t *testing.T) {
|
||||
assert.Equal(time.Second*time.Duration(200), c.Lifetime, "lifetime should be read and converted to duration")
|
||||
}
|
||||
|
||||
func TestConfigValidate(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Install new logger + hook
|
||||
var hook *test.Hook
|
||||
log, hook = test.NewNullLogger()
|
||||
log.ExitFunc = func(code int) {}
|
||||
|
||||
// Validate defualt config + rule error
|
||||
c, _ := NewConfig([]string{
|
||||
"--rule.1.action=bad",
|
||||
})
|
||||
c.Validate()
|
||||
|
||||
logs := hook.AllEntries()
|
||||
assert.Len(logs, 3)
|
||||
|
||||
// Should have fatal error requiring secret
|
||||
assert.Equal("\"secret\" option must be set", logs[0].Message)
|
||||
assert.Equal(logrus.FatalLevel, logs[0].Level)
|
||||
|
||||
// Should also have default provider (google) error
|
||||
assert.Equal("providers.google.client-id, providers.google.client-secret must be set", logs[1].Message)
|
||||
assert.Equal(logrus.FatalLevel, logs[1].Level)
|
||||
|
||||
// Should validate rule
|
||||
assert.Equal("invalid rule action, must be \"auth\" or \"allow\"", logs[2].Message)
|
||||
assert.Equal(logrus.FatalLevel, logs[2].Level)
|
||||
|
||||
hook.Reset()
|
||||
|
||||
// Validate with invalid providers
|
||||
c, _ = NewConfig([]string{
|
||||
"--secret=veryverysecret",
|
||||
"--providers.google.client-id=id",
|
||||
"--providers.google.client-secret=secret",
|
||||
"--rule.1.action=auth",
|
||||
"--rule.1.provider=bad2",
|
||||
})
|
||||
c.Validate()
|
||||
|
||||
logs = hook.AllEntries()
|
||||
assert.Len(logs, 1)
|
||||
|
||||
// Should have error for rule provider
|
||||
assert.Equal("Unknown provider: bad2", logs[0].Message)
|
||||
assert.Equal(logrus.FatalLevel, logs[0].Level)
|
||||
}
|
||||
|
||||
func TestConfigGetProvider(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
c, _ := NewConfig([]string{})
|
||||
|
||||
// Should be able to get "google" provider
|
||||
p, err := c.GetProvider("google")
|
||||
assert.Nil(err)
|
||||
assert.Equal(&c.Providers.Google, p)
|
||||
|
||||
// Should be able to get "oidc" provider
|
||||
p, err = c.GetProvider("oidc")
|
||||
assert.Nil(err)
|
||||
assert.Equal(&c.Providers.OIDC, p)
|
||||
|
||||
// Should be able to get "generic-oauth" provider
|
||||
p, err = c.GetProvider("generic-oauth")
|
||||
assert.Nil(err)
|
||||
assert.Equal(&c.Providers.GenericOAuth, p)
|
||||
|
||||
// Should catch unknown provider
|
||||
p, err = c.GetProvider("bad")
|
||||
if assert.Error(err) {
|
||||
assert.Equal("Unknown provider: bad", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigGetConfiguredProvider(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
c, _ := NewConfig([]string{})
|
||||
|
||||
// Should be able to get "google" default provider
|
||||
p, err := c.GetConfiguredProvider("google")
|
||||
assert.Nil(err)
|
||||
assert.Equal(&c.Providers.Google, p)
|
||||
|
||||
// Should fail to get valid "oidc" provider as it's not configured
|
||||
p, err = c.GetConfiguredProvider("oidc")
|
||||
if assert.Error(err) {
|
||||
assert.Equal("Unconfigured provider: oidc", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigCommaSeparatedList(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
list := CommaSeparatedList{}
|
||||
|
||||
@@ -6,9 +6,10 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var log logrus.FieldLogger
|
||||
var log *logrus.Logger
|
||||
|
||||
func NewDefaultLogger() logrus.FieldLogger {
|
||||
// NewDefaultLogger creates a new logger based on the current configuration
|
||||
func NewDefaultLogger() *logrus.Logger {
|
||||
// Setup logger
|
||||
log = logrus.StandardLogger()
|
||||
logrus.SetOutput(os.Stdout)
|
||||
|
||||
96
internal/provider/generic_oauth.go
Normal file
96
internal/provider/generic_oauth.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// GenericOAuth provider
|
||||
type GenericOAuth struct {
|
||||
AuthURL string `long:"auth-url" env:"AUTH_URL" description:"Auth/Login URL"`
|
||||
TokenURL string `long:"token-url" env:"TOKEN_URL" description:"Token URL"`
|
||||
UserURL string `long:"user-url" env:"USER_URL" description:"URL used to retrieve user info"`
|
||||
ClientID string `long:"client-id" env:"CLIENT_ID" description:"Client ID"`
|
||||
ClientSecret string `long:"client-secret" env:"CLIENT_SECRET" description:"Client Secret" json:"-"`
|
||||
Scopes []string `long:"scope" env:"SCOPE" env-delim:"," default:"profile" default:"email" description:"Scopes"`
|
||||
TokenStyle string `long:"token-style" env:"TOKEN_STYLE" default:"header" choice:"header" choice:"query" description:"How token is presented when querying the User URL"`
|
||||
|
||||
OAuthProvider
|
||||
}
|
||||
|
||||
// Name returns the name of the provider
|
||||
func (o *GenericOAuth) Name() string {
|
||||
return "generic-oauth"
|
||||
}
|
||||
|
||||
// Setup performs validation and setup
|
||||
func (o *GenericOAuth) Setup() error {
|
||||
// Check parmas
|
||||
if o.AuthURL == "" || o.TokenURL == "" || o.UserURL == "" || o.ClientID == "" || o.ClientSecret == "" {
|
||||
return errors.New("providers.generic-oauth.auth-url, providers.generic-oauth.token-url, providers.generic-oauth.user-url, providers.generic-oauth.client-id, providers.generic-oauth.client-secret must be set")
|
||||
}
|
||||
|
||||
// Create oauth2 config
|
||||
o.Config = &oauth2.Config{
|
||||
ClientID: o.ClientID,
|
||||
ClientSecret: o.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: o.AuthURL,
|
||||
TokenURL: o.TokenURL,
|
||||
},
|
||||
Scopes: o.Scopes,
|
||||
}
|
||||
|
||||
o.ctx = context.Background()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLoginURL provides the login url for the given redirect uri and state
|
||||
func (o *GenericOAuth) GetLoginURL(redirectURI, state string) string {
|
||||
return o.OAuthGetLoginURL(redirectURI, state)
|
||||
}
|
||||
|
||||
// ExchangeCode exchanges the given redirect uri and code for a token
|
||||
func (o *GenericOAuth) ExchangeCode(redirectURI, code string) (string, error) {
|
||||
token, err := o.OAuthExchangeCode(redirectURI, code)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return token.AccessToken, nil
|
||||
}
|
||||
|
||||
// GetUser uses the given token and returns a complete provider.User object
|
||||
func (o *GenericOAuth) GetUser(token string) (User, error) {
|
||||
var user User
|
||||
|
||||
req, err := http.NewRequest("GET", o.UserURL, nil)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
if o.TokenStyle == "header" {
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||
} else if o.TokenStyle == "query" {
|
||||
q := req.URL.Query()
|
||||
q.Add("access_token", token)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
defer res.Body.Close()
|
||||
err = json.NewDecoder(res.Body).Decode(&user)
|
||||
|
||||
return user, err
|
||||
}
|
||||
140
internal/provider/generic_oauth_test.go
Normal file
140
internal/provider/generic_oauth_test.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Tests
|
||||
|
||||
func TestGenericOAuthName(t *testing.T) {
|
||||
p := GenericOAuth{}
|
||||
assert.Equal(t, "generic-oauth", p.Name())
|
||||
}
|
||||
|
||||
func TestGenericOAuthSetup(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
p := GenericOAuth{}
|
||||
|
||||
// Check validation
|
||||
err := p.Setup()
|
||||
if assert.Error(err) {
|
||||
assert.Equal("providers.generic-oauth.auth-url, providers.generic-oauth.token-url, providers.generic-oauth.user-url, providers.generic-oauth.client-id, providers.generic-oauth.client-secret must be set", err.Error())
|
||||
}
|
||||
|
||||
// Check setup
|
||||
p = GenericOAuth{
|
||||
AuthURL: "https://provider.com/oauth2/auth",
|
||||
TokenURL: "https://provider.com/oauth2/token",
|
||||
UserURL: "https://provider.com/oauth2/user",
|
||||
ClientID: "id",
|
||||
ClientSecret: "secret",
|
||||
}
|
||||
err = p.Setup()
|
||||
assert.Nil(err)
|
||||
}
|
||||
|
||||
func TestGenericOAuthGetLoginURL(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
p := GenericOAuth{
|
||||
AuthURL: "https://provider.com/oauth2/auth",
|
||||
TokenURL: "https://provider.com/oauth2/token",
|
||||
UserURL: "https://provider.com/oauth2/user",
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "secret",
|
||||
Scopes: []string{"scopetest"},
|
||||
}
|
||||
err := p.Setup()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Check url
|
||||
uri, err := url.Parse(p.GetLoginURL("http://example.com/_oauth", "state"))
|
||||
assert.Nil(err)
|
||||
assert.Equal("https", uri.Scheme)
|
||||
assert.Equal("provider.com", uri.Host)
|
||||
assert.Equal("/oauth2/auth", 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"},
|
||||
"state": []string{"state"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
}
|
||||
|
||||
func TestGenericOAuthExchangeCode(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Setup server
|
||||
expected := url.Values{
|
||||
"client_id": []string{"idtest"},
|
||||
"client_secret": []string{"sectest"},
|
||||
"code": []string{"code"},
|
||||
"grant_type": []string{"authorization_code"},
|
||||
"redirect_uri": []string{"http://example.com/_oauth"},
|
||||
}
|
||||
server, serverURL := NewOAuthServer(t, map[string]string{
|
||||
"token": expected.Encode(),
|
||||
})
|
||||
defer server.Close()
|
||||
|
||||
// Setup provider
|
||||
p := GenericOAuth{
|
||||
AuthURL: "https://provider.com/oauth2/auth",
|
||||
TokenURL: serverURL.String() + "/token",
|
||||
UserURL: "https://provider.com/oauth2/user",
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
}
|
||||
err := p.Setup()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// We force AuthStyleInParams to prevent the test failure when the
|
||||
// AuthStyleInHeader is attempted
|
||||
p.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams
|
||||
|
||||
token, err := p.ExchangeCode("http://example.com/_oauth", "code")
|
||||
assert.Nil(err)
|
||||
assert.Equal("123456789", token)
|
||||
}
|
||||
|
||||
func TestGenericOAuthGetUser(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Setup server
|
||||
server, serverURL := NewOAuthServer(t, nil)
|
||||
defer server.Close()
|
||||
|
||||
// Setup provider
|
||||
p := GenericOAuth{
|
||||
AuthURL: "https://provider.com/oauth2/auth",
|
||||
TokenURL: "https://provider.com/oauth2/token",
|
||||
UserURL: serverURL.String() + "/userinfo",
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
}
|
||||
err := p.Setup()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// We force AuthStyleInParams to prevent the test failure when the
|
||||
// AuthStyleInHeader is attempted
|
||||
p.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams
|
||||
|
||||
user, err := p.GetUser("123456789")
|
||||
assert.Nil(err)
|
||||
|
||||
assert.Equal("example@example.com", user.Email)
|
||||
}
|
||||
@@ -2,31 +2,66 @@ package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Google provider
|
||||
type Google struct {
|
||||
ClientId string `long:"client-id" env:"CLIENT_ID" description:"Client ID"`
|
||||
ClientID string `long:"client-id" env:"CLIENT_ID" description:"Client ID"`
|
||||
ClientSecret string `long:"client-secret" env:"CLIENT_SECRET" description:"Client Secret" json:"-"`
|
||||
Scope string
|
||||
Prompt string `long:"prompt" env:"PROMPT" description:"Space separated list of OpenID prompt options"`
|
||||
Prompt string `long:"prompt" env:"PROMPT" default:"select_account" description:"Space separated list of OpenID prompt options"`
|
||||
|
||||
LoginURL *url.URL
|
||||
TokenURL *url.URL
|
||||
UserURL *url.URL
|
||||
}
|
||||
|
||||
func (g *Google) GetLoginURL(redirectUri, state string) string {
|
||||
// Name returns the name of the provider
|
||||
func (g *Google) Name() string {
|
||||
return "google"
|
||||
}
|
||||
|
||||
// Setup performs validation and setup
|
||||
func (g *Google) Setup() error {
|
||||
if g.ClientID == "" || g.ClientSecret == "" {
|
||||
return errors.New("providers.google.client-id, providers.google.client-secret must be set")
|
||||
}
|
||||
|
||||
// Set static values
|
||||
g.Scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
|
||||
g.LoginURL = &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "accounts.google.com",
|
||||
Path: "/o/oauth2/auth",
|
||||
}
|
||||
g.TokenURL = &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v3/token",
|
||||
}
|
||||
g.UserURL = &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v2/userinfo",
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLoginURL provides the login url for the given redirect uri and state
|
||||
func (g *Google) GetLoginURL(redirectURI, state string) string {
|
||||
q := url.Values{}
|
||||
q.Set("client_id", g.ClientId)
|
||||
q.Set("client_id", g.ClientID)
|
||||
q.Set("response_type", "code")
|
||||
q.Set("scope", g.Scope)
|
||||
if g.Prompt != "" {
|
||||
q.Set("prompt", g.Prompt)
|
||||
}
|
||||
q.Set("redirect_uri", redirectUri)
|
||||
q.Set("redirect_uri", redirectURI)
|
||||
q.Set("state", state)
|
||||
|
||||
var u url.URL
|
||||
@@ -36,12 +71,13 @@ func (g *Google) GetLoginURL(redirectUri, state string) string {
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (g *Google) ExchangeCode(redirectUri, code string) (string, error) {
|
||||
// ExchangeCode exchanges the given redirect uri and code for a token
|
||||
func (g *Google) ExchangeCode(redirectURI, code string) (string, error) {
|
||||
form := url.Values{}
|
||||
form.Set("client_id", g.ClientId)
|
||||
form.Set("client_id", g.ClientID)
|
||||
form.Set("client_secret", g.ClientSecret)
|
||||
form.Set("grant_type", "authorization_code")
|
||||
form.Set("redirect_uri", redirectUri)
|
||||
form.Set("redirect_uri", redirectURI)
|
||||
form.Set("code", code)
|
||||
|
||||
res, err := http.PostForm(g.TokenURL.String(), form)
|
||||
@@ -49,13 +85,14 @@ func (g *Google) ExchangeCode(redirectUri, code string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var token Token
|
||||
var token token
|
||||
defer res.Body.Close()
|
||||
err = json.NewDecoder(res.Body).Decode(&token)
|
||||
|
||||
return token.Token, err
|
||||
}
|
||||
|
||||
// GetUser uses the given token and returns a complete provider.User object
|
||||
func (g *Google) GetUser(token string) (User, error) {
|
||||
var user User
|
||||
|
||||
|
||||
148
internal/provider/google_test.go
Normal file
148
internal/provider/google_test.go
Normal file
@@ -0,0 +1,148 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Tests
|
||||
|
||||
func TestGoogleName(t *testing.T) {
|
||||
p := Google{}
|
||||
assert.Equal(t, "google", p.Name())
|
||||
}
|
||||
|
||||
func TestGoogleSetup(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
p := Google{}
|
||||
|
||||
// Check validation
|
||||
err := p.Setup()
|
||||
if assert.Error(err) {
|
||||
assert.Equal("providers.google.client-id, providers.google.client-secret must be set", err.Error())
|
||||
}
|
||||
|
||||
// Check setup
|
||||
p = Google{
|
||||
ClientID: "id",
|
||||
ClientSecret: "secret",
|
||||
}
|
||||
err = p.Setup()
|
||||
assert.Nil(err)
|
||||
assert.Equal("https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email", p.Scope)
|
||||
assert.Equal("", p.Prompt)
|
||||
|
||||
assert.Equal(&url.URL{
|
||||
Scheme: "https",
|
||||
Host: "accounts.google.com",
|
||||
Path: "/o/oauth2/auth",
|
||||
}, p.LoginURL)
|
||||
|
||||
assert.Equal(&url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v3/token",
|
||||
}, p.TokenURL)
|
||||
|
||||
assert.Equal(&url.URL{
|
||||
Scheme: "https",
|
||||
Host: "www.googleapis.com",
|
||||
Path: "/oauth2/v2/userinfo",
|
||||
}, p.UserURL)
|
||||
}
|
||||
|
||||
func TestGoogleGetLoginURL(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
p := Google{
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
Scope: "scopetest",
|
||||
Prompt: "consent select_account",
|
||||
LoginURL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "google.com",
|
||||
Path: "/auth",
|
||||
},
|
||||
}
|
||||
|
||||
// Check url
|
||||
uri, err := url.Parse(p.GetLoginURL("http://example.com/_oauth", "state"))
|
||||
assert.Nil(err)
|
||||
assert.Equal("https", uri.Scheme)
|
||||
assert.Equal("google.com", uri.Host)
|
||||
assert.Equal("/auth", 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{"state"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
}
|
||||
|
||||
func TestGoogleExchangeCode(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Setup server
|
||||
expected := url.Values{
|
||||
"client_id": []string{"idtest"},
|
||||
"client_secret": []string{"sectest"},
|
||||
"code": []string{"code"},
|
||||
"grant_type": []string{"authorization_code"},
|
||||
"redirect_uri": []string{"http://example.com/_oauth"},
|
||||
}
|
||||
server, serverURL := NewOAuthServer(t, map[string]string{
|
||||
"token": expected.Encode(),
|
||||
})
|
||||
defer server.Close()
|
||||
|
||||
// Setup provider
|
||||
p := Google{
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
Scope: "scopetest",
|
||||
Prompt: "consent select_account",
|
||||
TokenURL: &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/token",
|
||||
},
|
||||
}
|
||||
|
||||
token, err := p.ExchangeCode("http://example.com/_oauth", "code")
|
||||
assert.Nil(err)
|
||||
assert.Equal("123456789", token)
|
||||
}
|
||||
|
||||
func TestGoogleGetUser(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Setup server
|
||||
server, serverURL := NewOAuthServer(t, nil)
|
||||
defer server.Close()
|
||||
|
||||
// Setup provider
|
||||
p := Google{
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
Scope: "scopetest",
|
||||
Prompt: "consent select_account",
|
||||
UserURL: &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/userinfo",
|
||||
},
|
||||
}
|
||||
|
||||
user, err := p.GetUser("123456789")
|
||||
assert.Nil(err)
|
||||
|
||||
assert.Equal("example@example.com", user.Email)
|
||||
}
|
||||
99
internal/provider/oidc.go
Normal file
99
internal/provider/oidc.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/coreos/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// OIDC provider
|
||||
type OIDC struct {
|
||||
IssuerURL string `long:"issuer-url" env:"ISSUER_URL" description:"Issuer URL"`
|
||||
ClientID string `long:"client-id" env:"CLIENT_ID" description:"Client ID"`
|
||||
ClientSecret string `long:"client-secret" env:"CLIENT_SECRET" description:"Client Secret" json:"-"`
|
||||
|
||||
OAuthProvider
|
||||
|
||||
provider *oidc.Provider
|
||||
verifier *oidc.IDTokenVerifier
|
||||
}
|
||||
|
||||
// Name returns the name of the provider
|
||||
func (o *OIDC) Name() string {
|
||||
return "oidc"
|
||||
}
|
||||
|
||||
// Setup performs validation and setup
|
||||
func (o *OIDC) Setup() error {
|
||||
// Check parms
|
||||
if o.IssuerURL == "" || o.ClientID == "" || o.ClientSecret == "" {
|
||||
return errors.New("providers.oidc.issuer-url, providers.oidc.client-id, providers.oidc.client-secret must be set")
|
||||
}
|
||||
|
||||
var err error
|
||||
o.ctx = context.Background()
|
||||
|
||||
// Try to initiate provider
|
||||
o.provider, err = oidc.NewProvider(o.ctx, o.IssuerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create oauth2 config
|
||||
o.Config = &oauth2.Config{
|
||||
ClientID: o.ClientID,
|
||||
ClientSecret: o.ClientSecret,
|
||||
Endpoint: o.provider.Endpoint(),
|
||||
|
||||
// "openid" is a required scope for OpenID Connect flows.
|
||||
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
||||
}
|
||||
|
||||
// Create OIDC verifier
|
||||
o.verifier = o.provider.Verifier(&oidc.Config{
|
||||
ClientID: o.ClientID,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLoginURL provides the login url for the given redirect uri and state
|
||||
func (o *OIDC) GetLoginURL(redirectURI, state string) string {
|
||||
return o.OAuthGetLoginURL(redirectURI, state)
|
||||
}
|
||||
|
||||
// ExchangeCode exchanges the given redirect uri and code for a token
|
||||
func (o *OIDC) ExchangeCode(redirectURI, code string) (string, error) {
|
||||
token, err := o.OAuthExchangeCode(redirectURI, code)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Extract ID token
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return "", errors.New("Missing id_token")
|
||||
}
|
||||
|
||||
return rawIDToken, nil
|
||||
}
|
||||
|
||||
// GetUser uses the given token and returns a complete provider.User object
|
||||
func (o *OIDC) GetUser(token string) (User, error) {
|
||||
var user User
|
||||
|
||||
// Parse & Verify ID Token
|
||||
idToken, err := o.verifier.Verify(o.ctx, token)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
// Extract custom claims
|
||||
if err := idToken.Claims(&user); err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
277
internal/provider/oidc_test.go
Normal file
277
internal/provider/oidc_test.go
Normal file
@@ -0,0 +1,277 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
jose "gopkg.in/square/go-jose.v2"
|
||||
)
|
||||
|
||||
// Tests
|
||||
|
||||
func TestOIDCName(t *testing.T) {
|
||||
p := OIDC{}
|
||||
assert.Equal(t, "oidc", p.Name())
|
||||
}
|
||||
|
||||
func TestOIDCSetup(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
p := OIDC{}
|
||||
|
||||
err := p.Setup()
|
||||
if assert.Error(err) {
|
||||
assert.Equal("providers.oidc.issuer-url, providers.oidc.client-id, providers.oidc.client-secret must be set", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCGetLoginURL(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
provider, server, serverURL, _ := setupOIDCTest(t, nil)
|
||||
defer server.Close()
|
||||
|
||||
// Check url
|
||||
uri, err := url.Parse(provider.GetLoginURL("http://example.com/_oauth", "state"))
|
||||
assert.Nil(err)
|
||||
assert.Equal(serverURL.Scheme, uri.Scheme)
|
||||
assert.Equal(serverURL.Host, uri.Host)
|
||||
assert.Equal("/auth", 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{"openid profile email"},
|
||||
"state": []string{"state"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
|
||||
// Calling the method should not modify the underlying config
|
||||
assert.Equal("", provider.Config.RedirectURL)
|
||||
|
||||
//
|
||||
// Test with resource config option
|
||||
//
|
||||
provider.Resource = "resourcetest"
|
||||
|
||||
// Check url
|
||||
uri, err = url.Parse(provider.GetLoginURL("http://example.com/_oauth", "state"))
|
||||
assert.Nil(err)
|
||||
assert.Equal(serverURL.Scheme, uri.Scheme)
|
||||
assert.Equal(serverURL.Host, uri.Host)
|
||||
assert.Equal("/auth", 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{"openid profile email"},
|
||||
"state": []string{"state"},
|
||||
"resource": []string{"resourcetest"},
|
||||
}
|
||||
assert.Equal(expectedQs, qs)
|
||||
|
||||
// Calling the method should not modify the underlying config
|
||||
assert.Equal("", provider.Config.RedirectURL)
|
||||
}
|
||||
|
||||
func TestOIDCExchangeCode(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
provider, server, _, _ := setupOIDCTest(t, map[string]map[string]string{
|
||||
"token": {
|
||||
"code": "code",
|
||||
"grant_type": "authorization_code",
|
||||
"redirect_uri": "http://example.com/_oauth",
|
||||
},
|
||||
})
|
||||
defer server.Close()
|
||||
|
||||
token, err := provider.ExchangeCode("http://example.com/_oauth", "code")
|
||||
assert.Nil(err)
|
||||
assert.Equal("id_123456789", token)
|
||||
}
|
||||
|
||||
func TestOIDCGetUser(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
provider, server, serverURL, key := setupOIDCTest(t, nil)
|
||||
defer server.Close()
|
||||
|
||||
// Generate JWT
|
||||
token := key.sign(t, []byte(`{
|
||||
"iss": "`+serverURL.String()+`",
|
||||
"exp":`+strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)+`,
|
||||
"aud": "idtest",
|
||||
"sub": "1",
|
||||
"email": "example@example.com",
|
||||
"email_verified": true
|
||||
}`))
|
||||
|
||||
// Get user
|
||||
user, err := provider.GetUser(token)
|
||||
assert.Nil(err)
|
||||
assert.Equal("example@example.com", user.Email)
|
||||
}
|
||||
|
||||
// Utils
|
||||
|
||||
// setOIDCTest creates a key, OIDCServer and initilises an OIDC provider
|
||||
func setupOIDCTest(t *testing.T, bodyValues map[string]map[string]string) (*OIDC, *httptest.Server, *url.URL, *rsaKey) {
|
||||
// Generate key
|
||||
key, err := newRSAKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
body := make(map[string]string)
|
||||
if bodyValues != nil {
|
||||
// URL encode bodyValues into body
|
||||
for method, values := range bodyValues {
|
||||
q := url.Values{}
|
||||
for k, v := range values {
|
||||
q.Set(k, v)
|
||||
}
|
||||
body[method] = q.Encode()
|
||||
}
|
||||
}
|
||||
|
||||
// Set up oidc server
|
||||
server, serverURL := NewOIDCServer(t, key, body)
|
||||
|
||||
// Setup provider
|
||||
p := OIDC{
|
||||
ClientID: "idtest",
|
||||
ClientSecret: "sectest",
|
||||
IssuerURL: serverURL.String(),
|
||||
}
|
||||
|
||||
// Initialise config/verifier
|
||||
err = p.Setup()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return &p, server, serverURL, key
|
||||
}
|
||||
|
||||
// OIDCServer is used in the OIDC Tests to mock an OIDC server
|
||||
type OIDCServer struct {
|
||||
t *testing.T
|
||||
url *url.URL
|
||||
body map[string]string // method -> body
|
||||
key *rsaKey
|
||||
}
|
||||
|
||||
func NewOIDCServer(t *testing.T, key *rsaKey, body map[string]string) (*httptest.Server, *url.URL) {
|
||||
handler := &OIDCServer{t: t, key: key, body: body}
|
||||
server := httptest.NewServer(handler)
|
||||
handler.url, _ = url.Parse(server.URL)
|
||||
return server, handler.url
|
||||
}
|
||||
|
||||
func (s *OIDCServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := ioutil.ReadAll(r.Body)
|
||||
|
||||
if r.URL.Path == "/.well-known/openid-configuration" {
|
||||
// Open id config
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{
|
||||
"issuer":"`+s.url.String()+`",
|
||||
"authorization_endpoint":"`+s.url.String()+`/auth",
|
||||
"token_endpoint":"`+s.url.String()+`/token",
|
||||
"jwks_uri":"`+s.url.String()+`/jwks"
|
||||
}`)
|
||||
} else if r.URL.Path == "/token" {
|
||||
// Token request
|
||||
// Check body
|
||||
if b, ok := s.body["token"]; ok {
|
||||
if b != string(body) {
|
||||
s.t.Fatal("Unexpected request body, expected", b, "got", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{
|
||||
"access_token":"123456789",
|
||||
"id_token":"id_123456789"
|
||||
}`)
|
||||
} else if r.URL.Path == "/jwks" {
|
||||
// Key request
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"keys":[`+s.key.publicJWK(s.t)+`]}`)
|
||||
} else {
|
||||
s.t.Fatal("Unrecognised request: ", r.URL, string(body))
|
||||
}
|
||||
}
|
||||
|
||||
// rsaKey is used in the OIDCServer tests to sign and verify requests
|
||||
type rsaKey struct {
|
||||
key *rsa.PrivateKey
|
||||
alg jose.SignatureAlgorithm
|
||||
jwkPub *jose.JSONWebKey
|
||||
jwkPriv *jose.JSONWebKey
|
||||
}
|
||||
|
||||
func newRSAKey() (*rsaKey, error) {
|
||||
key, err := rsa.GenerateKey(rand.Reader, 1028)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &rsaKey{
|
||||
key: key,
|
||||
alg: jose.RS256,
|
||||
jwkPub: &jose.JSONWebKey{
|
||||
Key: key.Public(),
|
||||
Algorithm: string(jose.RS256),
|
||||
},
|
||||
jwkPriv: &jose.JSONWebKey{
|
||||
Key: key,
|
||||
Algorithm: string(jose.RS256),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (k *rsaKey) publicJWK(t *testing.T) string {
|
||||
b, err := k.jwkPub.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// sign creates a JWS using the private key from the provided payload.
|
||||
func (k *rsaKey) sign(t *testing.T, payload []byte) string {
|
||||
signer, err := jose.NewSigner(jose.SigningKey{
|
||||
Algorithm: k.alg,
|
||||
Key: k.key,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
jws, err := signer.Sign(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := jws.CompactSerialize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -1,16 +1,66 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
// "net/url"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Providers contains all the implemented providers
|
||||
type Providers struct {
|
||||
Google Google `group:"Google Provider" namespace:"google" env-namespace:"GOOGLE"`
|
||||
Google Google `group:"Google Provider" namespace:"google" env-namespace:"GOOGLE"`
|
||||
OIDC OIDC `group:"OIDC Provider" namespace:"oidc" env-namespace:"OIDC"`
|
||||
GenericOAuth GenericOAuth `group:"Generic OAuth2 Provider" namespace:"generic-oauth" env-namespace:"GENERIC_OAUTH"`
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
// Provider is used to authenticate users
|
||||
type Provider interface {
|
||||
Name() string
|
||||
GetLoginURL(redirectURI, state string) string
|
||||
ExchangeCode(redirectURI, code string) (string, error)
|
||||
GetUser(token string) (User, error)
|
||||
Setup() error
|
||||
}
|
||||
|
||||
type token struct {
|
||||
Token string `json:"access_token"`
|
||||
}
|
||||
|
||||
// User is the authenticated user
|
||||
type User struct {
|
||||
Id string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Verified bool `json:"verified_email"`
|
||||
Hd string `json:"hd"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// OAuthProvider is a provider using the oauth2 library
|
||||
type OAuthProvider struct {
|
||||
Resource string `long:"resource" env:"RESOURCE" description:"Optional resource indicator"`
|
||||
|
||||
Config *oauth2.Config
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
// ConfigCopy returns a copy of the oauth2 config with the given redirectURI
|
||||
// which ensures the underlying config is not modified
|
||||
func (p *OAuthProvider) ConfigCopy(redirectURI string) oauth2.Config {
|
||||
config := *p.Config
|
||||
config.RedirectURL = redirectURI
|
||||
return config
|
||||
}
|
||||
|
||||
// OAuthGetLoginURL provides a base "GetLoginURL" for proiders using OAauth2
|
||||
func (p *OAuthProvider) OAuthGetLoginURL(redirectURI, state string) string {
|
||||
config := p.ConfigCopy(redirectURI)
|
||||
|
||||
if p.Resource != "" {
|
||||
return config.AuthCodeURL(state, oauth2.SetAuthURLParam("resource", p.Resource))
|
||||
}
|
||||
|
||||
return config.AuthCodeURL(state)
|
||||
}
|
||||
|
||||
// OAuthExchangeCode provides a base "ExchangeCode" for proiders using OAauth2
|
||||
func (p *OAuthProvider) OAuthExchangeCode(redirectURI, code string) (*oauth2.Token, error) {
|
||||
config := p.ConfigCopy(redirectURI)
|
||||
return config.Exchange(p.ctx, code)
|
||||
}
|
||||
|
||||
48
internal/provider/providers_test.go
Normal file
48
internal/provider/providers_test.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Utilities
|
||||
|
||||
type OAuthServer struct {
|
||||
t *testing.T
|
||||
url *url.URL
|
||||
body map[string]string // method -> body
|
||||
}
|
||||
|
||||
func NewOAuthServer(t *testing.T, body map[string]string) (*httptest.Server, *url.URL) {
|
||||
handler := &OAuthServer{t: t, body: body}
|
||||
server := httptest.NewServer(handler)
|
||||
handler.url, _ = url.Parse(server.URL)
|
||||
return server, handler.url
|
||||
}
|
||||
|
||||
func (s *OAuthServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := ioutil.ReadAll(r.Body)
|
||||
// fmt.Println("Got request:", r.URL, r.Method, string(body))
|
||||
|
||||
if r.Method == "POST" && r.URL.Path == "/token" {
|
||||
if s.body["token"] != string(body) {
|
||||
s.t.Fatal("Unexpected request body, expected", s.body["token"], "got", string(body))
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"access_token":"123456789"}`)
|
||||
} else if r.Method == "GET" && r.URL.Path == "/userinfo" {
|
||||
fmt.Fprint(w, `{
|
||||
"id":"1",
|
||||
"email":"example@example.com",
|
||||
"verified_email":true,
|
||||
"hd":"example.com"
|
||||
}`)
|
||||
} else {
|
||||
s.t.Fatal("Unrecognised request: ", r.Method, r.URL, string(body))
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,17 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/containous/traefik/pkg/rules"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/thomseddon/traefik-forward-auth/internal/provider"
|
||||
muxhttp "github.com/traefik/traefik/v2/pkg/muxer/http"
|
||||
)
|
||||
|
||||
// Server contains muxer and handler methods
|
||||
type Server struct {
|
||||
router *rules.Router
|
||||
muxer *muxhttp.Muxer
|
||||
}
|
||||
|
||||
// NewServer creates a new server object and builds muxer
|
||||
func NewServer() *Server {
|
||||
s := &Server{}
|
||||
s.buildRoutes()
|
||||
@@ -20,59 +23,71 @@ func NewServer() *Server {
|
||||
|
||||
func (s *Server) buildRoutes() {
|
||||
var err error
|
||||
s.router, err = rules.NewRouter()
|
||||
s.muxer, err = muxhttp.NewMuxer()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Let's build a router
|
||||
// Let's build a muxer
|
||||
for name, rule := range config.Rules {
|
||||
matchRule := rule.formattedRule()
|
||||
if rule.Action == "allow" {
|
||||
s.router.AddRoute(rule.formattedRule(), 1, s.AllowHandler(name))
|
||||
_ = s.muxer.AddRoute(matchRule, 1, s.AllowHandler(name))
|
||||
} else {
|
||||
s.router.AddRoute(rule.formattedRule(), 1, s.AuthHandler(name))
|
||||
_ = s.muxer.AddRoute(matchRule, 1, s.AuthHandler(rule.Provider, name))
|
||||
}
|
||||
}
|
||||
|
||||
// Add callback handler
|
||||
s.router.Handle(config.Path, s.AuthCallbackHandler())
|
||||
s.muxer.Handle(config.Path, s.AuthCallbackHandler())
|
||||
|
||||
// Add logout handler
|
||||
s.muxer.Handle(config.Path+"/logout", s.LogoutHandler())
|
||||
|
||||
// Add a default handler
|
||||
if config.DefaultAction == "allow" {
|
||||
s.router.NewRoute().Handler(s.AllowHandler("default"))
|
||||
s.muxer.NewRoute().Handler(s.AllowHandler("default"))
|
||||
} else {
|
||||
s.router.NewRoute().Handler(s.AuthHandler("default"))
|
||||
s.muxer.NewRoute().Handler(s.AuthHandler(config.DefaultProvider, "default"))
|
||||
}
|
||||
}
|
||||
|
||||
// RootHandler Overwrites the request method, host and URL with those from the
|
||||
// forwarded request so it's correctly routed by mux
|
||||
func (s *Server) RootHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// Modify request
|
||||
r.Method = r.Header.Get("X-Forwarded-Method")
|
||||
r.Host = r.Header.Get("X-Forwarded-Host")
|
||||
r.URL, _ = url.Parse(r.Header.Get("X-Forwarded-Uri"))
|
||||
|
||||
// Read URI from header if we're acting as forward auth middleware
|
||||
if _, ok := r.Header["X-Forwarded-Uri"]; ok {
|
||||
r.URL, _ = url.Parse(r.Header.Get("X-Forwarded-Uri"))
|
||||
}
|
||||
|
||||
// Pass to mux
|
||||
s.router.ServeHTTP(w, r)
|
||||
s.muxer.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// Handler that allows requests
|
||||
// AllowHandler Allows requests
|
||||
func (s *Server) AllowHandler(rule string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
s.logger(r, rule, "Allowing request")
|
||||
s.logger(r, "Allow", rule, "Allowing request")
|
||||
w.WriteHeader(200)
|
||||
}
|
||||
}
|
||||
|
||||
// Authenticate requests
|
||||
func (s *Server) AuthHandler(rule string) http.HandlerFunc {
|
||||
// AuthHandler Authenticates requests
|
||||
func (s *Server) AuthHandler(providerName, rule string) http.HandlerFunc {
|
||||
p, _ := config.GetConfiguredProvider(providerName)
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Logging setup
|
||||
logger := s.logger(r, rule, "Authenticating request")
|
||||
logger := s.logger(r, "Auth", rule, "Authenticating request")
|
||||
|
||||
// Get auth cookie
|
||||
c, err := r.Cookie(config.CookieName)
|
||||
if err != nil {
|
||||
s.authRedirect(logger, w, r)
|
||||
s.authRedirect(logger, w, r, p)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -81,112 +96,169 @@ func (s *Server) AuthHandler(rule string) http.HandlerFunc {
|
||||
if err != nil {
|
||||
if err.Error() == "Cookie has expired" {
|
||||
logger.Info("Cookie has expired")
|
||||
s.authRedirect(logger, w, r)
|
||||
s.authRedirect(logger, w, r, p)
|
||||
} else {
|
||||
logger.Errorf("Invalid cookie: %v", err)
|
||||
logger.WithField("error", err).Warn("Invalid cookie")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Validate user
|
||||
valid := ValidateEmail(email)
|
||||
valid := ValidateEmail(email, rule)
|
||||
if !valid {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"email": email,
|
||||
}).Errorf("Invalid email")
|
||||
logger.WithField("email", email).Warn("Invalid email")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
|
||||
// Valid request
|
||||
logger.Debugf("Allowing valid request ")
|
||||
logger.Debug("Allowing valid request")
|
||||
w.Header().Set("X-Forwarded-User", email)
|
||||
w.WriteHeader(200)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle auth callback
|
||||
// AuthCallbackHandler Handles auth callback request
|
||||
func (s *Server) AuthCallbackHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Logging setup
|
||||
logger := s.logger(r, "default", "Handling callback")
|
||||
logger := s.logger(r, "AuthCallback", "default", "Handling callback")
|
||||
|
||||
// Check for CSRF cookie
|
||||
c, err := r.Cookie(config.CSRFCookieName)
|
||||
if err != nil {
|
||||
logger.Warn("Missing csrf cookie")
|
||||
// Check state
|
||||
state := r.URL.Query().Get("state")
|
||||
if err := ValidateState(state); err != nil {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"error": err,
|
||||
}).Warn("Error validating state")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate state
|
||||
valid, redirect, err := ValidateCSRFCookie(r, c)
|
||||
// Check for CSRF cookie
|
||||
c, err := FindCSRFCookie(r, state)
|
||||
if err != nil {
|
||||
logger.Info("Missing csrf cookie")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate CSRF cookie against state
|
||||
valid, providerName, redirect, err := ValidateCSRFCookie(c, state)
|
||||
if !valid {
|
||||
logger.Warnf("Error validating csrf cookie: %v", err)
|
||||
logger.WithFields(logrus.Fields{
|
||||
"error": err,
|
||||
"csrf_cookie": c,
|
||||
}).Warn("Error validating csrf cookie")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
|
||||
// Get provider
|
||||
p, err := config.GetConfiguredProvider(providerName)
|
||||
if err != nil {
|
||||
logger.WithFields(logrus.Fields{
|
||||
"error": err,
|
||||
"csrf_cookie": c,
|
||||
"provider": providerName,
|
||||
}).Warn("Invalid provider in csrf cookie")
|
||||
http.Error(w, "Not authorized", 401)
|
||||
return
|
||||
}
|
||||
|
||||
// Clear CSRF cookie
|
||||
http.SetCookie(w, ClearCSRFCookie(r))
|
||||
http.SetCookie(w, ClearCSRFCookie(r, c))
|
||||
|
||||
// Exchange code for token
|
||||
token, err := ExchangeCode(r)
|
||||
token, err := p.ExchangeCode(redirectUri(r), r.URL.Query().Get("code"))
|
||||
if err != nil {
|
||||
logger.Errorf("Code exchange failed with: %v", err)
|
||||
logger.WithField("error", err).Error("Code exchange failed with provider")
|
||||
http.Error(w, "Service unavailable", 503)
|
||||
return
|
||||
}
|
||||
|
||||
// Get user
|
||||
user, err := GetUser(token)
|
||||
user, err := p.GetUser(token)
|
||||
if err != nil {
|
||||
logger.Errorf("Error getting user: %s", err)
|
||||
logger.WithField("error", err).Error("Error getting user")
|
||||
http.Error(w, "Service unavailable", 503)
|
||||
return
|
||||
}
|
||||
|
||||
// Generate cookie
|
||||
http.SetCookie(w, MakeCookie(r, user.Email))
|
||||
logger.WithFields(logrus.Fields{
|
||||
"user": user.Email,
|
||||
}).Infof("Generated auth cookie")
|
||||
"provider": providerName,
|
||||
"redirect": redirect,
|
||||
"user": user.Email,
|
||||
}).Info("Successfully generated auth cookie, redirecting user.")
|
||||
|
||||
// Redirect
|
||||
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) authRedirect(logger *logrus.Entry, w http.ResponseWriter, r *http.Request) {
|
||||
// LogoutHandler logs a user out
|
||||
func (s *Server) LogoutHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Clear cookie
|
||||
http.SetCookie(w, ClearCookie(r))
|
||||
|
||||
logger := s.logger(r, "Logout", "default", "Handling logout")
|
||||
logger.Info("Logged out user")
|
||||
|
||||
if config.LogoutRedirect != "" {
|
||||
http.Redirect(w, r, config.LogoutRedirect, http.StatusTemporaryRedirect)
|
||||
} else {
|
||||
http.Error(w, "You have been logged out", 401)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) authRedirect(logger *logrus.Entry, w http.ResponseWriter, r *http.Request, p provider.Provider) {
|
||||
// Error indicates no cookie, generate nonce
|
||||
err, nonce := Nonce()
|
||||
if err != nil {
|
||||
logger.Errorf("Error generating nonce, %v", err)
|
||||
logger.WithField("error", err).Error("Error generating nonce")
|
||||
http.Error(w, "Service unavailable", 503)
|
||||
return
|
||||
}
|
||||
|
||||
// Set the CSRF cookie
|
||||
http.SetCookie(w, MakeCSRFCookie(r, nonce))
|
||||
logger.Debug("Set CSRF cookie and redirecting to google login")
|
||||
csrf := MakeCSRFCookie(r, nonce)
|
||||
http.SetCookie(w, csrf)
|
||||
|
||||
if !config.InsecureCookie && r.Header.Get("X-Forwarded-Proto") != "https" {
|
||||
logger.Warn("You are using \"secure\" cookies for a request that was not " +
|
||||
"received via https. You should either redirect to https or pass the " +
|
||||
"\"insecure-cookie\" config option to permit cookies via http.")
|
||||
}
|
||||
|
||||
// Forward them on
|
||||
http.Redirect(w, r, GetLoginURL(r, nonce), http.StatusTemporaryRedirect)
|
||||
loginURL := p.GetLoginURL(redirectUri(r), MakeState(r, p, nonce))
|
||||
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
|
||||
|
||||
logger.Debug("Done")
|
||||
return
|
||||
logger.WithFields(logrus.Fields{
|
||||
"csrf_cookie": csrf,
|
||||
"login_url": loginURL,
|
||||
}).Debug("Set CSRF cookie and redirected to provider login url")
|
||||
}
|
||||
|
||||
func (s *Server) logger(r *http.Request, rule, msg string) *logrus.Entry {
|
||||
func (s *Server) logger(r *http.Request, handler, rule, msg string) *logrus.Entry {
|
||||
// Create logger
|
||||
logger := log.WithFields(logrus.Fields{
|
||||
"handler": handler,
|
||||
"rule": rule,
|
||||
"method": r.Header.Get("X-Forwarded-Method"),
|
||||
"proto": r.Header.Get("X-Forwarded-Proto"),
|
||||
"host": r.Header.Get("X-Forwarded-Host"),
|
||||
"uri": r.Header.Get("X-Forwarded-Uri"),
|
||||
"source_ip": r.Header.Get("X-Forwarded-For"),
|
||||
})
|
||||
|
||||
// Log request
|
||||
logger.WithFields(logrus.Fields{
|
||||
"rule": rule,
|
||||
"headers": r.Header,
|
||||
"cookies": r.Cookies(),
|
||||
}).Debug(msg)
|
||||
|
||||
return logger
|
||||
|
||||
@@ -10,16 +10,19 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus/hooks/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// TODO:
|
||||
|
||||
/**
|
||||
* Setup
|
||||
*/
|
||||
|
||||
func init() {
|
||||
config = newDefaultConfig()
|
||||
config.LogLevel = "panic"
|
||||
log = NewDefaultLogger()
|
||||
}
|
||||
@@ -28,9 +31,42 @@ func init() {
|
||||
* Tests
|
||||
*/
|
||||
|
||||
func TestServerRootHandler(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config = newDefaultConfig()
|
||||
|
||||
// X-Forwarded headers should be read into request
|
||||
req := httptest.NewRequest("POST", "http://should-use-x-forwarded.com/should?ignore=me", nil)
|
||||
req.Header.Add("X-Forwarded-Method", "GET")
|
||||
req.Header.Add("X-Forwarded-Proto", "https")
|
||||
req.Header.Add("X-Forwarded-Host", "example.com")
|
||||
req.Header.Add("X-Forwarded-Uri", "/foo?q=bar")
|
||||
NewServer().RootHandler(httptest.NewRecorder(), req)
|
||||
|
||||
assert.Equal("GET", req.Method, "x-forwarded-method should be read into request")
|
||||
assert.Equal("example.com", req.Host, "x-forwarded-host should be read into request")
|
||||
assert.Equal("/foo", req.URL.Path, "x-forwarded-uri should be read into request")
|
||||
assert.Equal("/foo?q=bar", req.URL.RequestURI(), "x-forwarded-uri should be read into request")
|
||||
|
||||
// Other X-Forwarded headers should be read in into request and original URL
|
||||
// should be preserved if X-Forwarded-Uri not present
|
||||
req = httptest.NewRequest("POST", "http://should-use-x-forwarded.com/should-not?ignore=me", nil)
|
||||
req.Header.Add("X-Forwarded-Method", "GET")
|
||||
req.Header.Add("X-Forwarded-Proto", "https")
|
||||
req.Header.Add("X-Forwarded-Host", "example.com")
|
||||
NewServer().RootHandler(httptest.NewRecorder(), req)
|
||||
|
||||
assert.Equal("GET", req.Method, "x-forwarded-method should be read into request")
|
||||
assert.Equal("example.com", req.Host, "x-forwarded-host should be read into request")
|
||||
assert.Equal("/should-not", req.URL.Path, "request url should be preserved if x-forwarded-uri not present")
|
||||
assert.Equal("/should-not?ignore=me", req.URL.RequestURI(), "request url should be preserved if x-forwarded-uri not present")
|
||||
}
|
||||
|
||||
func TestServerAuthHandlerInvalid(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
var hook *test.Hook
|
||||
log, hook = test.NewNullLogger()
|
||||
|
||||
// Should redirect vanilla request to login url
|
||||
req := newDefaultHttpRequest("/foo")
|
||||
@@ -42,10 +78,28 @@ func TestServerAuthHandlerInvalid(t *testing.T) {
|
||||
assert.Equal("accounts.google.com", fwd.Host, "vanilla request should be redirected to google")
|
||||
assert.Equal("/o/oauth2/auth", fwd.Path, "vanilla request should be redirected to google")
|
||||
|
||||
// Check state string
|
||||
qs := fwd.Query()
|
||||
state, exists := qs["state"]
|
||||
require.True(t, exists)
|
||||
require.Len(t, state, 1)
|
||||
parts := strings.SplitN(state[0], ":", 3)
|
||||
require.Len(t, parts, 3)
|
||||
assert.Equal("google", parts[1])
|
||||
assert.Equal("http://example.com/foo", parts[2])
|
||||
|
||||
// Should warn as using http without insecure cookie
|
||||
logs := hook.AllEntries()
|
||||
assert.Len(logs, 1)
|
||||
assert.Equal("You are using \"secure\" cookies for a request that was not "+
|
||||
"received via https. You should either redirect to https or pass the "+
|
||||
"\"insecure-cookie\" config option to permit cookies via http.", logs[0].Message)
|
||||
assert.Equal(logrus.WarnLevel, logs[0].Level)
|
||||
|
||||
// Should catch invalid cookie
|
||||
req = newDefaultHttpRequest("/foo")
|
||||
c := MakeCookie(req, "test@example.com")
|
||||
parts := strings.Split(c.Value, "|")
|
||||
parts = strings.Split(c.Value, "|")
|
||||
c.Value = fmt.Sprintf("bad|%s|%s", parts[1], parts[2])
|
||||
|
||||
res, _ = doHttpRequest(req, c)
|
||||
@@ -62,20 +116,20 @@ func TestServerAuthHandlerInvalid(t *testing.T) {
|
||||
|
||||
func TestServerAuthHandlerExpired(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
config.Lifetime = time.Second * time.Duration(-1)
|
||||
config.Domains = []string{"test.com"}
|
||||
|
||||
// Should redirect expired cookie
|
||||
req := newDefaultHttpRequest("/foo")
|
||||
req := newHTTPRequest("GET", "http://example.com/foo")
|
||||
c := MakeCookie(req, "test@example.com")
|
||||
res, _ := doHttpRequest(req, c)
|
||||
assert.Equal(307, res.StatusCode, "request with expired cookie should be redirected")
|
||||
require.Equal(t, 307, res.StatusCode, "request with expired cookie should be redirected")
|
||||
|
||||
// Check for CSRF cookie
|
||||
var cookie *http.Cookie
|
||||
for _, c := range res.Cookies() {
|
||||
if c.Name == config.CSRFCookieName {
|
||||
if strings.HasPrefix(c.Name, config.CSRFCookieName) {
|
||||
cookie = c
|
||||
}
|
||||
}
|
||||
@@ -90,10 +144,10 @@ func TestServerAuthHandlerExpired(t *testing.T) {
|
||||
|
||||
func TestServerAuthHandlerValid(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
|
||||
// Should allow valid request email
|
||||
req := newDefaultHttpRequest("/foo")
|
||||
req := newHTTPRequest("GET", "http://example.com/foo")
|
||||
c := MakeCookie(req, "test@example.com")
|
||||
config.Domains = []string{}
|
||||
|
||||
@@ -108,38 +162,46 @@ func TestServerAuthHandlerValid(t *testing.T) {
|
||||
|
||||
func TestServerAuthCallback(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
require := require.New(t)
|
||||
config = newDefaultConfig()
|
||||
|
||||
// Setup token server
|
||||
tokenServerHandler := &TokenServerHandler{}
|
||||
tokenServer := httptest.NewServer(tokenServerHandler)
|
||||
defer tokenServer.Close()
|
||||
tokenUrl, _ := url.Parse(tokenServer.URL)
|
||||
config.Providers.Google.TokenURL = tokenUrl
|
||||
|
||||
// Setup user server
|
||||
userServerHandler := &UserServerHandler{}
|
||||
userServer := httptest.NewServer(userServerHandler)
|
||||
defer userServer.Close()
|
||||
userUrl, _ := url.Parse(userServer.URL)
|
||||
config.Providers.Google.UserURL = userUrl
|
||||
// Setup OAuth server
|
||||
server, serverURL := NewOAuthServer(t)
|
||||
defer server.Close()
|
||||
config.Providers.Google.TokenURL = &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/token",
|
||||
}
|
||||
config.Providers.Google.UserURL = &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/userinfo",
|
||||
}
|
||||
|
||||
// Should pass auth response request to callback
|
||||
req := newDefaultHttpRequest("/_oauth")
|
||||
req := newHTTPRequest("GET", "http://example.com/_oauth")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
assert.Equal(401, res.StatusCode, "auth callback without cookie shouldn't be authorised")
|
||||
|
||||
// Should catch invalid csrf cookie
|
||||
req = newDefaultHttpRequest("/_oauth?state=12345678901234567890123456789012:http://redirect")
|
||||
nonce := "12345678901234567890123456789012"
|
||||
req = newHTTPRequest("GET", "http://example.com/_oauth?state="+nonce+":http://redirect")
|
||||
c := MakeCSRFCookie(req, "nononononononononononononononono")
|
||||
res, _ = doHttpRequest(req, c)
|
||||
assert.Equal(401, res.StatusCode, "auth callback with invalid cookie shouldn't be authorised")
|
||||
|
||||
// Should redirect valid request
|
||||
req = newDefaultHttpRequest("/_oauth?state=12345678901234567890123456789012:http://redirect")
|
||||
c = MakeCSRFCookie(req, "12345678901234567890123456789012")
|
||||
// Should catch invalid provider cookie
|
||||
req = newHTTPRequest("GET", "http://example.com/_oauth?state="+nonce+":invalid:http://redirect")
|
||||
c = MakeCSRFCookie(req, nonce)
|
||||
res, _ = doHttpRequest(req, c)
|
||||
assert.Equal(307, res.StatusCode, "valid auth callback should be allowed")
|
||||
assert.Equal(401, res.StatusCode, "auth callback with invalid provider shouldn't be authorised")
|
||||
|
||||
// Should redirect valid request
|
||||
req = newHTTPRequest("GET", "http://example.com/_oauth?state="+nonce+":google:http://redirect")
|
||||
c = MakeCSRFCookie(req, nonce)
|
||||
res, _ = doHttpRequest(req, c)
|
||||
require.Equal(307, res.StatusCode, "valid auth callback should be allowed")
|
||||
|
||||
fwd, _ := res.Location()
|
||||
assert.Equal("http", fwd.Scheme, "valid request should be redirected to return url")
|
||||
@@ -147,9 +209,104 @@ func TestServerAuthCallback(t *testing.T) {
|
||||
assert.Equal("", fwd.Path, "valid request should be redirected to return url")
|
||||
}
|
||||
|
||||
func TestServerAuthCallbackExchangeFailure(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config = newDefaultConfig()
|
||||
|
||||
// Setup OAuth server
|
||||
server, serverURL := NewFailingOAuthServer(t)
|
||||
defer server.Close()
|
||||
config.Providers.Google.TokenURL = &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/token",
|
||||
}
|
||||
config.Providers.Google.UserURL = &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/userinfo",
|
||||
}
|
||||
|
||||
// Should handle failed code exchange
|
||||
req := newDefaultHttpRequest("/_oauth?state=12345678901234567890123456789012:google:http://redirect")
|
||||
c := MakeCSRFCookie(req, "12345678901234567890123456789012")
|
||||
res, _ := doHttpRequest(req, c)
|
||||
assert.Equal(503, res.StatusCode, "auth callback should handle failed code exchange")
|
||||
}
|
||||
|
||||
func TestServerAuthCallbackUserFailure(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config = newDefaultConfig()
|
||||
|
||||
// Setup OAuth server
|
||||
server, serverURL := NewOAuthServer(t)
|
||||
defer server.Close()
|
||||
config.Providers.Google.TokenURL = &url.URL{
|
||||
Scheme: serverURL.Scheme,
|
||||
Host: serverURL.Host,
|
||||
Path: "/token",
|
||||
}
|
||||
serverFail, serverFailURL := NewFailingOAuthServer(t)
|
||||
defer serverFail.Close()
|
||||
config.Providers.Google.UserURL = &url.URL{
|
||||
Scheme: serverFailURL.Scheme,
|
||||
Host: serverFailURL.Host,
|
||||
Path: "/userinfo",
|
||||
}
|
||||
|
||||
// Should handle failed user request
|
||||
req := newDefaultHttpRequest("/_oauth?state=12345678901234567890123456789012:google:http://redirect")
|
||||
c := MakeCSRFCookie(req, "12345678901234567890123456789012")
|
||||
res, _ := doHttpRequest(req, c)
|
||||
assert.Equal(503, res.StatusCode, "auth callback should handle failed user request")
|
||||
}
|
||||
|
||||
func TestServerLogout(t *testing.T) {
|
||||
require := require.New(t)
|
||||
assert := assert.New(t)
|
||||
config = newDefaultConfig()
|
||||
|
||||
req := newDefaultHttpRequest("/_oauth/logout")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
require.Equal(401, res.StatusCode, "should return a 401")
|
||||
|
||||
// Check for cookie
|
||||
var cookie *http.Cookie
|
||||
for _, c := range res.Cookies() {
|
||||
if c.Name == config.CookieName {
|
||||
cookie = c
|
||||
}
|
||||
}
|
||||
require.NotNil(cookie)
|
||||
require.Less(cookie.Expires.Local().Unix(), time.Now().Local().Unix()-50, "cookie should have expired")
|
||||
|
||||
// Test with redirect
|
||||
config.LogoutRedirect = "http://redirect/path"
|
||||
req = newDefaultHttpRequest("/_oauth/logout")
|
||||
res, _ = doHttpRequest(req, nil)
|
||||
require.Equal(307, res.StatusCode, "should return a 307")
|
||||
|
||||
// Check for cookie
|
||||
cookie = nil
|
||||
for _, c := range res.Cookies() {
|
||||
if c.Name == config.CookieName {
|
||||
cookie = c
|
||||
}
|
||||
}
|
||||
require.NotNil(cookie)
|
||||
require.Less(cookie.Expires.Local().Unix(), time.Now().Local().Unix()-50, "cookie should have expired")
|
||||
|
||||
fwd, _ := res.Location()
|
||||
require.NotNil(fwd)
|
||||
assert.Equal("http", fwd.Scheme, "valid request should be redirected to return url")
|
||||
assert.Equal("redirect", fwd.Host, "valid request should be redirected to return url")
|
||||
assert.Equal("/path", fwd.Path, "valid request should be redirected to return url")
|
||||
|
||||
}
|
||||
|
||||
func TestServerDefaultAction(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
|
||||
req := newDefaultHttpRequest("/random")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
@@ -161,9 +318,36 @@ func TestServerDefaultAction(t *testing.T) {
|
||||
assert.Equal(200, res.StatusCode, "request should be allowed with default handler")
|
||||
}
|
||||
|
||||
func TestServerDefaultProvider(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config = newDefaultConfig()
|
||||
|
||||
// Should use "google" as default provider when not specified
|
||||
req := newDefaultHttpRequest("/random")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
fwd, _ := res.Location()
|
||||
assert.Equal("https", fwd.Scheme, "request with expired cookie should be redirected to google")
|
||||
assert.Equal("accounts.google.com", fwd.Host, "request with expired cookie should be redirected to google")
|
||||
assert.Equal("/o/oauth2/auth", fwd.Path, "request with expired cookie should be redirected to google")
|
||||
|
||||
// Should use alternative default provider when set
|
||||
config.DefaultProvider = "oidc"
|
||||
config.Providers.OIDC.OAuthProvider.Config = &oauth2.Config{
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: "https://oidc.com/oidcauth",
|
||||
},
|
||||
}
|
||||
|
||||
res, _ = doHttpRequest(req, nil)
|
||||
fwd, _ = res.Location()
|
||||
assert.Equal("https", fwd.Scheme, "request with expired cookie should be redirected to oidc")
|
||||
assert.Equal("oidc.com", fwd.Host, "request with expired cookie should be redirected to oidc")
|
||||
assert.Equal("/oidcauth", fwd.Path, "request with expired cookie should be redirected to oidc")
|
||||
}
|
||||
|
||||
func TestServerRouteHeaders(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
config.Rules = map[string]*Rule{
|
||||
"1": {
|
||||
Action: "allow",
|
||||
@@ -196,7 +380,7 @@ func TestServerRouteHeaders(t *testing.T) {
|
||||
|
||||
func TestServerRouteHost(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
config.Rules = map[string]*Rule{
|
||||
"1": {
|
||||
Action: "allow",
|
||||
@@ -209,24 +393,24 @@ func TestServerRouteHost(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should block any request
|
||||
req := newHttpRequest("GET", "https://example.com/", "/")
|
||||
req := newHTTPRequest("GET", "https://example.com/")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
assert.Equal(307, res.StatusCode, "request not matching any rule should require auth")
|
||||
|
||||
// Should allow matching request
|
||||
req = newHttpRequest("GET", "https://api.example.com/", "/")
|
||||
req = newHTTPRequest("GET", "https://api.example.com/")
|
||||
res, _ = doHttpRequest(req, nil)
|
||||
assert.Equal(200, res.StatusCode, "request matching allow rule should be allowed")
|
||||
|
||||
// Should allow matching request
|
||||
req = newHttpRequest("GET", "https://sub8.example.com/", "/")
|
||||
req = newHTTPRequest("GET", "https://sub8.example.com/")
|
||||
res, _ = doHttpRequest(req, nil)
|
||||
assert.Equal(200, res.StatusCode, "request matching allow rule should be allowed")
|
||||
}
|
||||
|
||||
func TestServerRouteMethod(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
config.Rules = map[string]*Rule{
|
||||
"1": {
|
||||
Action: "allow",
|
||||
@@ -235,19 +419,19 @@ func TestServerRouteMethod(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should block any request
|
||||
req := newHttpRequest("GET", "https://example.com/", "/")
|
||||
req := newHTTPRequest("GET", "https://example.com/")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
assert.Equal(307, res.StatusCode, "request not matching any rule should require auth")
|
||||
|
||||
// Should allow matching request
|
||||
req = newHttpRequest("PUT", "https://example.com/", "/")
|
||||
req = newHTTPRequest("PUT", "https://example.com/")
|
||||
res, _ = doHttpRequest(req, nil)
|
||||
assert.Equal(200, res.StatusCode, "request matching allow rule should be allowed")
|
||||
}
|
||||
|
||||
func TestServerRoutePath(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
config.Rules = map[string]*Rule{
|
||||
"1": {
|
||||
Action: "allow",
|
||||
@@ -281,7 +465,7 @@ func TestServerRoutePath(t *testing.T) {
|
||||
|
||||
func TestServerRouteQuery(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
config, _ = NewConfig([]string{})
|
||||
config = newDefaultConfig()
|
||||
config.Rules = map[string]*Rule{
|
||||
"1": {
|
||||
Action: "allow",
|
||||
@@ -290,12 +474,12 @@ func TestServerRouteQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should block any request
|
||||
req := newHttpRequest("GET", "https://example.com/", "/?q=no")
|
||||
req := newHTTPRequest("GET", "https://example.com/?q=no")
|
||||
res, _ := doHttpRequest(req, nil)
|
||||
assert.Equal(307, res.StatusCode, "request not matching any rule should require auth")
|
||||
|
||||
// Should allow matching request
|
||||
req = newHttpRequest("GET", "https://api.example.com/", "/?q=test123")
|
||||
req = newHTTPRequest("GET", "https://api.example.com/?q=test123")
|
||||
res, _ = doHttpRequest(req, nil)
|
||||
assert.Equal(200, res.StatusCode, "request matching allow rule should be allowed")
|
||||
}
|
||||
@@ -304,21 +488,43 @@ func TestServerRouteQuery(t *testing.T) {
|
||||
* Utilities
|
||||
*/
|
||||
|
||||
type TokenServerHandler struct{}
|
||||
|
||||
func (t *TokenServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"access_token":"123456789"}`)
|
||||
type OAuthServer struct {
|
||||
t *testing.T
|
||||
fail bool
|
||||
}
|
||||
|
||||
type UserServerHandler struct{}
|
||||
func (s *OAuthServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if s.fail {
|
||||
http.Error(w, "Service unavailable", 500)
|
||||
return
|
||||
}
|
||||
|
||||
func (t *UserServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{
|
||||
"id":"1",
|
||||
"email":"example@example.com",
|
||||
"verified_email":true,
|
||||
"hd":"example.com"
|
||||
}`)
|
||||
if r.URL.Path == "/token" {
|
||||
fmt.Fprintf(w, `{"access_token":"123456789"}`)
|
||||
} else if r.URL.Path == "/userinfo" {
|
||||
fmt.Fprint(w, `{
|
||||
"id":"1",
|
||||
"email":"example@example.com",
|
||||
"verified_email":true,
|
||||
"hd":"example.com"
|
||||
}`)
|
||||
} else {
|
||||
s.t.Fatal("Unrecognised request: ", r.Method, r.URL)
|
||||
}
|
||||
}
|
||||
|
||||
func NewOAuthServer(t *testing.T) (*httptest.Server, *url.URL) {
|
||||
handler := &OAuthServer{}
|
||||
server := httptest.NewServer(handler)
|
||||
serverURL, _ := url.Parse(server.URL)
|
||||
return server, serverURL
|
||||
}
|
||||
|
||||
func NewFailingOAuthServer(t *testing.T) (*httptest.Server, *url.URL) {
|
||||
handler := &OAuthServer{fail: true}
|
||||
server := httptest.NewServer(handler)
|
||||
serverURL, _ := url.Parse(server.URL)
|
||||
return server, serverURL
|
||||
}
|
||||
|
||||
func doHttpRequest(r *http.Request, c *http.Cookie) (*http.Response, string) {
|
||||
@@ -346,33 +552,29 @@ func doHttpRequest(r *http.Request, c *http.Cookie) (*http.Response, string) {
|
||||
return res, string(body)
|
||||
}
|
||||
|
||||
func newDefaultHttpRequest(uri string) *http.Request {
|
||||
return newHttpRequest("", "http://example.com/", uri)
|
||||
func newDefaultConfig() *Config {
|
||||
config, _ = NewConfig([]string{
|
||||
"--providers.google.client-id=id",
|
||||
"--providers.google.client-secret=secret",
|
||||
})
|
||||
|
||||
// Setup the google providers without running all the config validation
|
||||
config.Providers.Google.Setup()
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
func newHttpRequest(method, dest, uri string) *http.Request {
|
||||
r := httptest.NewRequest("", "http://should-use-x-forwarded.com", nil)
|
||||
p, _ := url.Parse(dest)
|
||||
// TODO: replace with newHTTPRequest("GET", "http://example.com/"+uri)
|
||||
func newDefaultHttpRequest(uri string) *http.Request {
|
||||
return newHTTPRequest("GET", "http://example.com"+uri)
|
||||
}
|
||||
|
||||
func newHTTPRequest(method, target string) *http.Request {
|
||||
u, _ := url.Parse(target)
|
||||
r := httptest.NewRequest(method, target, nil)
|
||||
r.Header.Add("X-Forwarded-Method", method)
|
||||
r.Header.Add("X-Forwarded-Host", p.Host)
|
||||
r.Header.Add("X-Forwarded-Uri", uri)
|
||||
r.Header.Add("X-Forwarded-Proto", u.Scheme)
|
||||
r.Header.Add("X-Forwarded-Host", u.Host)
|
||||
r.Header.Add("X-Forwarded-Uri", u.RequestURI())
|
||||
return r
|
||||
}
|
||||
|
||||
func qsDiff(t *testing.T, one, two url.Values) []string {
|
||||
errs := make([]string, 0)
|
||||
for k := range one {
|
||||
if two.Get(k) == "" {
|
||||
errs = append(errs, fmt.Sprintf("Key missing: %s", k))
|
||||
}
|
||||
if one.Get(k) != two.Get(k) {
|
||||
errs = append(errs, fmt.Sprintf("Value different for %s: expected: '%s' got: '%s'", k, one.Get(k), two.Get(k)))
|
||||
}
|
||||
}
|
||||
for k := range two {
|
||||
if one.Get(k) == "" {
|
||||
errs = append(errs, fmt.Sprintf("Extra key: %s", k))
|
||||
}
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user