1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-04-21 12:17:22 +02:00

Merge remote-tracking branch 'origin2/master'

This commit is contained in:
Kevin Kreitner 2020-12-01 15:28:20 +01:00
commit 65901254d7
117 changed files with 18989 additions and 1906 deletions

67
.github/workflows/docs.yaml vendored Normal file
View File

@ -0,0 +1,67 @@
name: documentation
on:
pull_request:
branches: [master]
paths: ['docs/**']
push:
branches: [master]
paths: ['docs/**']
jobs:
checks:
if: github.event_name != 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Test Build
working-directory: ./docs
run: |
if [ -e yarn.lock ]; then
yarn install --frozen-lockfile
elif [ -e package-lock.json ]; then
npm ci
else
npm i
fi
npm run build
gh-release:
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Add key to allow access to repository
env:
SSH_AUTH_SOCK: /tmp/ssh_agent.sock
run: |
mkdir -p ~/.ssh
ssh-keyscan github.com >> ~/.ssh/known_hosts
echo "${{ secrets.GH_PAGES_DEPLOY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
cat <<EOT >> ~/.ssh/config
Host github.com
HostName github.com
IdentityFile ~/.ssh/id_rsa
EOT
- name: Release to GitHub Pages
working-directory: ./docs
env:
USE_SSH: true
GIT_USER: git
run: |
git config --global user.email "actions@gihub.com"
git config --global user.name "gh-actions"
if [ -e yarn.lock ]; then
yarn install --frozen-lockfile
elif [ -e package-lock.json ]; then
npm ci
else
npm i
fi
npx docusaurus deploy

View File

@ -17,7 +17,7 @@ if [ -z $CC_TEST_REPORTER_ID ]; then
echo "3. CC_TEST_REPORTER_ID is unset, skipping"
else
echo "3. Running after-build"
./cc-test-reporter after-build --exit-code $TEST_STATUS -t gocov --prefix $(basename $(go list -m))
./cc-test-reporter after-build --exit-code $TEST_STATUS -t gocov --prefix $(go list -m)
fi
if [ "$TEST_STATUS" -ne 0 ]; then

View File

@ -1,20 +0,0 @@
language: go
go:
- 1.15.x
env:
- COVER=true
install:
# Fetch dependencies
- curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $GOPATH/bin v1.24.0
- GO111MODULE=on go mod download
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
before_script:
- ./cc-test-reporter before-build
script:
- make test
after_script:
- ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT -t gocov
sudo: false
notifications:
email: false

View File

@ -4,6 +4,13 @@
## Important Notes
- [#905](https://github.com/oauth2-proxy/oauth2-proxy/pull/905) Existing sessions from v6.0.0 or earlier are no longer valid. They will trigger a reauthentication.
- [#826](https://github.com/oauth2-proxy/oauth2-proxy/pull/826) `skip-auth-strip-headers` now applies to all requests, not just those where authentication would be skipped.
- [#797](https://github.com/oauth2-proxy/oauth2-proxy/pull/797) The behavior of the Google provider Groups restriction changes with this
- Either `--google-group` or the new `--allowed-group` will work for Google now (`--google-group` will be used if both are set)
- Group membership lists will be passed to the backend with the `X-Forwarded-Groups` header
- If you change the list of allowed groups, existing sessions that now don't have a valid group will be logged out immediately.
- Previously, group membership was only checked on session creation and refresh.
- [#789](https://github.com/oauth2-proxy/oauth2-proxy/pull/789) `--skip-auth-route` is (almost) backwards compatible with `--skip-auth-regex`
- We are marking `--skip-auth-regex` as DEPRECATED and will remove it in the next major version.
- If your regex contains an `=` and you want it for all methods, you will need to add a leading `=` (this is the area where `--skip-auth-regex` doesn't port perfectly)
@ -15,6 +22,10 @@
## Breaking Changes
- [#911](https://github.com/oauth2-proxy/oauth2-proxy/pull/911) Specifying a non-existent provider will cause OAuth2-Proxy to fail on startup instead of defaulting to "google".
- [#797](https://github.com/oauth2-proxy/oauth2-proxy/pull/797) Security changes to Google provider group authorization flow
- If you change the list of allowed groups, existing sessions that now don't have a valid group will be logged out immediately.
- Previously, group membership was only checked on session creation and refresh.
- [#722](https://github.com/oauth2-proxy/oauth2-proxy/pull/722) When a Redis session store is configured, OAuth2-Proxy will fail to start up unless connection and health checks to Redis pass
- [#800](https://github.com/oauth2-proxy/oauth2-proxy/pull/800) Fix import path for v7. The import path has changed to support the go get installation.
- You can now `go get github.com/oauth2-proxy/oauth2-proxy/v7` to get the latest `v7` version of OAuth2 Proxy
@ -23,9 +34,31 @@
via the login url. If this option was used in the past, behavior will change with this release as it will
affect the tokens returned by Azure. In the past, the tokens were always for `https://graph.microsoft.com` (the default)
and will now be for the configured resource (if it exists, otherwise it will run into errors)
- [#754](https://github.com/oauth2-proxy/oauth2-proxy/pull/754) The Azure provider now has token refresh functionality implemented. This means that there won't
be any redirects in the browser anymore when tokens expire, but instead a token refresh is initiated
in the background, which leads to new tokens being returned in the cookies.
- Please note that `--cookie-refresh` must be 0 (the default) or equal to the token lifespan configured in Azure AD to make
Azure token refresh reliable. Setting this value to 0 means that it relies on the provider implementation
to decide if a refresh is required.
## Changes since v6.1.1
- [#907](https://github.com/oauth2-proxy/oauth2-proxy/pull/907) Introduce alpha configuration option to enable testing of structured configuration (@JoelSpeed)
- [#938](https://github.com/oauth2-proxy/oauth2-proxy/pull/938) Cleanup missed provider renaming refactor methods (@NickMeves)
- [#925](https://github.com/oauth2-proxy/oauth2-proxy/pull/925) Fix basic auth legacy header conversion (@JoelSpeed)
- [#916](https://github.com/oauth2-proxy/oauth2-proxy/pull/916) Add AlphaOptions struct to prepare for alpha config loading (@JoelSpeed)
- [#923](https://github.com/oauth2-proxy/oauth2-proxy/pull/923) Support TLS 1.3 (@aajisaka)
- [#918](https://github.com/oauth2-proxy/oauth2-proxy/pull/918) Fix log header output (@JoelSpeed)
- [#911](https://github.com/oauth2-proxy/oauth2-proxy/pull/911) Validate provider type on startup.
- [#869](https://github.com/oauth2-proxy/oauth2-proxy/pull/869) Streamline provider interface method names and signatures (@NickMeves)
- [#906](https://github.com/oauth2-proxy/oauth2-proxy/pull/906) Set up v6.1.x versioned documentation as default documentation (@JoelSpeed)
- [#905](https://github.com/oauth2-proxy/oauth2-proxy/pull/905) Remove v5 legacy sessions support (@NickMeves)
- [#904](https://github.com/oauth2-proxy/oauth2-proxy/pull/904) Set `skip-auth-strip-headers` to `true` by default (@NickMeves)
- [#826](https://github.com/oauth2-proxy/oauth2-proxy/pull/826) Integrate new header injectors into project (@JoelSpeed)
- [#797](https://github.com/oauth2-proxy/oauth2-proxy/pull/797) Create universal Authorization behavior across providers (@NickMeves)
- [#898](https://github.com/oauth2-proxy/oauth2-proxy/pull/898) Migrate documentation to Docusaurus (@JoelSpeed)
- [#754](https://github.com/oauth2-proxy/oauth2-proxy/pull/754) Azure token refresh (@codablock)
- [#850](https://github.com/oauth2-proxy/oauth2-proxy/pull/850) Increase session fields in `/oauth2/userinfo` endpoint (@NickMeves)
- [#825](https://github.com/oauth2-proxy/oauth2-proxy/pull/825) Fix code coverage reporting on GitHub actions(@JoelSpeed)
- [#796](https://github.com/oauth2-proxy/oauth2-proxy/pull/796) Deprecate GetUserName & GetEmailAdress for EnrichSessionState (@NickMeves)
- [#705](https://github.com/oauth2-proxy/oauth2-proxy/pull/705) Add generic Header injectors for upstream request and response headers (@JoelSpeed)
@ -35,6 +68,7 @@
- [#722](https://github.com/oauth2-proxy/oauth2-proxy/pull/722) Validate Redis configuration options at startup (@NickMeves)
- [#791](https://github.com/oauth2-proxy/oauth2-proxy/pull/791) Remove GetPreferredUsername method from provider interface (@NickMeves)
- [#764](https://github.com/oauth2-proxy/oauth2-proxy/pull/764) Document bcrypt encryption for htpasswd (and hide SHA) (@lentzi90)
- [#778](https://github.com/oauth2-proxy/oauth2-proxy/pull/778) Use display-htpasswd-form flag
- [#616](https://github.com/oauth2-proxy/oauth2-proxy/pull/616) Add support to ensure user belongs in required groups when using the OIDC provider (@stefansedich)
- [#800](https://github.com/oauth2-proxy/oauth2-proxy/pull/800) Fix import path for v7 (@johejo)
- [#783](https://github.com/oauth2-proxy/oauth2-proxy/pull/783) Update Go to 1.15 (@johejo)
@ -44,6 +78,7 @@
- [#829](https://github.com/oauth2-proxy/oauth2-proxy/pull/820) Rename test directory to testdata (@johejo)
- [#819](https://github.com/oauth2-proxy/oauth2-proxy/pull/819) Improve CI (@johejo)
# v6.1.1
## Release Highlights

View File

@ -1,4 +1,4 @@
![OAuth2 Proxy](/docs/logos/OAuth2_Proxy_horizontal.svg)
![OAuth2 Proxy](/docs/static/img/logos/OAuth2_Proxy_horizontal.svg)
[![Build Status](https://secure.travis-ci.org/oauth2-proxy/oauth2-proxy.svg?branch=master)](http://travis-ci.org/oauth2-proxy/oauth2-proxy)
[![Go Report Card](https://goreportcard.com/badge/github.com/oauth2-proxy/oauth2-proxy)](https://goreportcard.com/report/github.com/oauth2-proxy/oauth2-proxy)
@ -36,9 +36,9 @@ sha256sum -c sha256sum.txt 2>&1 | grep OK
oauth2-proxy-x.y.z.linux-amd64: OK
```
2. [Select a Provider and Register an OAuth Application with a Provider](https://oauth2-proxy.github.io/oauth2-proxy/auth-configuration)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](https://oauth2-proxy.github.io/oauth2-proxy/configuration)
4. [Configure SSL or Deploy behind a SSL endpoint](https://oauth2-proxy.github.io/oauth2-proxy/tls-configuration) (example provided for Nginx)
2. [Select a Provider and Register an OAuth Application with a Provider](https://oauth2-proxy.github.io/oauth2-proxy/docs/configuration/oauth_provider)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](https://oauth2-proxy.github.io/oauth2-proxy/docs/configuration/overview)
4. [Configure SSL or Deploy behind a SSL endpoint](https://oauth2-proxy.github.io/oauth2-proxy/docs/configuration/tls) (example provided for Nginx)
## Security
@ -48,7 +48,7 @@ See [open redirect vulnverability](https://github.com/oauth2-proxy/oauth2-proxy/
## Docs
Read the docs on our [Docs site](https://oauth2-proxy.github.io/oauth2-proxy).
Read the docs on our [Docs site](https://oauth2-proxy.github.io/oauth2-proxy/docs/).
![OAuth2 Proxy Architecture](https://cloud.githubusercontent.com/assets/45028/8027702/bd040b7a-0d6a-11e5-85b9-f8d953d04f39.png)

View File

@ -6,6 +6,14 @@ up:
%:
docker-compose $*
.PHONY: alpha-config-up
alpha-config-up:
docker-compose -f docker-compose.yaml -f docker-compose-alpha-config.yaml up -d
.PHONY: alpha-config-%
alpha-config-%:
docker-compose -f docker-compose.yaml -f docker-compose-nginx.yaml $*
.PHONY: nginx-up
nginx-up:
docker-compose -f docker-compose.yaml -f docker-compose-nginx.yaml up -d

View File

@ -0,0 +1,19 @@
# This docker-compose file can be used to bring up an example instance of oauth2-proxy
# for manual testing and exploration of features.
# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
# etcd for storage for Dex and HTTPBin as an example upstream.
# This file also uses alpha configuration when configuring OAuth2 Proxy.
#
# This file is an extension of the main compose file and must be used with it
# docker-compose -f docker-compose.yaml -f docker-compose-alpha-config.yaml <command>
# Alternatively:
# make alpha-config-<command> (eg make nginx-up, make nginx-down)
#
# Access http://localhost:4180 to initiate a login cycle
version: '3.0'
services:
oauth2-proxy:
command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml
volumes:
- "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg"
- "./oauth2-proxy-alpha-config.yaml:/oauth2-proxy-alpha-config.yaml"

View File

@ -1,9 +1,9 @@
dependencies:
- name: dex
repository: https://kubernetes-charts.storage.googleapis.com
repository: https://charts.helm.sh/stable
version: 2.11.0
- name: oauth2-proxy
repository: https://kubernetes-charts.storage.googleapis.com
repository: https://charts.helm.sh/stable
version: 3.1.0
- name: httpbin
repository: https://conservis.github.io/helm-charts
@ -11,5 +11,5 @@ dependencies:
- name: hello-world
repository: https://conservis.github.io/helm-charts
version: 1.0.1
digest: sha256:ce64f06102abb551ee23b6de7b4cec3537f4900de89412458e53760781005aac
generated: "2020-06-16T16:59:19.126187-05:00"
digest: sha256:e325948ece1706bd9d9e439568985db41e9a0d57623d0f9638249cb0d23821b8
generated: "2020-11-23T11:45:07.908898-08:00"

View File

@ -6,10 +6,10 @@ appVersion: 5.1.1
dependencies:
- name: dex
version: 2.11.0
repository: https://kubernetes-charts.storage.googleapis.com
repository: https://charts.helm.sh/stable
- name: oauth2-proxy
version: 3.1.0
repository: https://kubernetes-charts.storage.googleapis.com
repository: https://charts.helm.sh/stable
# https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart
- name: httpbin
version: 1.0.1

View File

@ -0,0 +1,10 @@
http_address="0.0.0.0:4180"
cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
provider="oidc"
email_domains="example.com"
oidc_issuer_url="http://dex.localhost:4190/dex"
client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
client_id="oauth2-proxy"
cookie_secure="false"
redirect_url="http://localhost:4180/oauth2/callback"

View File

@ -0,0 +1,17 @@
upstreams:
- id: httpbin
path: /
uri: http://httpbin
injectRequestHeaders:
- name: X-Forwarded-Groups
values:
- claim: groups
- name: X-Forwarded-User
values:
- claim: user
- name: X-Forwarded-Email
values:
- claim: email
- name: X-Forwarded-Preferred-Username
values:
- claim: preferred_username

23
docs/.gitignore vendored
View File

@ -1,3 +1,20 @@
_site
.sass-cache
.jekyll-metadata
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1,32 +0,0 @@
---
layout: default
title: Home
permalink: /
nav_order: 0
---
![OAuth2 Proxy](/logos/OAuth2_Proxy_horizontal.svg)
A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others)
to validate accounts by email, domain or group.
**Note:** This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018.
Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork.
A list of changes can be seen in the [CHANGELOG]({{ site.gitweb }}/CHANGELOG.md).
[![Build Status](https://secure.travis-ci.org/oauth2-proxy/oauth2-proxy.svg?branch=master)](http://travis-ci.org/oauth2-proxy/oauth2-proxy)
![Sign In Page](https://cloud.githubusercontent.com/assets/45028/4970624/7feb7dd8-6886-11e4-93e0-c9904af44ea8.png)
## Architecture
![OAuth2 Proxy Architecture](https://cloud.githubusercontent.com/assets/45028/8027702/bd040b7a-0d6a-11e5-85b9-f8d953d04f39.png)
## Behavior
1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`).
2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned)
3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set
4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration)
Notice that the proxy also provides a number of useful [endpoints](/oauth2-proxy/endpoints).

View File

@ -1,24 +0,0 @@
---
layout: default
---
<style type="text/css" media="screen">
.container {
margin: 10px auto;
max-width: 600px;
text-align: center;
}
h1 {
margin: 30px 0;
font-size: 4em;
line-height: 1;
letter-spacing: -1px;
}
</style>
<div class="container">
<h1>404</h1>
<p><strong>Page not found :(</strong></p>
<p>The requested page could not be found.</p>
</div>

View File

@ -1,11 +0,0 @@
source "https://rubygems.org"
gem "github-pages", group: :jekyll_plugins
# just-the-docs Jekyll theme
gem "just-the-docs"
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby]
# Performance-booster for watching directories on Windows
gem "wdm", "~> 0.1.0" if Gem.win_platform?

View File

@ -1,255 +0,0 @@
GEM
remote: https://rubygems.org/
specs:
activesupport (6.0.3.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
zeitwerk (~> 2.2, >= 2.2.2)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
coffee-script (2.4.1)
coffee-script-source
execjs
coffee-script-source (1.11.1)
colorator (1.1.0)
commonmarker (0.17.13)
ruby-enum (~> 0.5)
concurrent-ruby (1.1.6)
dnsruby (1.61.3)
addressable (~> 2.5)
em-websocket (0.5.1)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0.6.0)
ethon (0.12.0)
ffi (>= 1.3.0)
eventmachine (1.2.7)
execjs (2.7.0)
faraday (1.0.0)
multipart-post (>= 1.2, < 3)
ffi (1.12.2)
forwardable-extended (2.6.0)
gemoji (3.0.1)
github-pages (204)
github-pages-health-check (= 1.16.1)
jekyll (= 3.8.5)
jekyll-avatar (= 0.7.0)
jekyll-coffeescript (= 1.1.1)
jekyll-commonmark-ghpages (= 0.1.6)
jekyll-default-layout (= 0.1.4)
jekyll-feed (= 0.13.0)
jekyll-gist (= 1.5.0)
jekyll-github-metadata (= 2.13.0)
jekyll-mentions (= 1.5.1)
jekyll-optional-front-matter (= 0.3.2)
jekyll-paginate (= 1.1.0)
jekyll-readme-index (= 0.3.0)
jekyll-redirect-from (= 0.15.0)
jekyll-relative-links (= 0.6.1)
jekyll-remote-theme (= 0.4.1)
jekyll-sass-converter (= 1.5.2)
jekyll-seo-tag (= 2.6.1)
jekyll-sitemap (= 1.4.0)
jekyll-swiss (= 1.0.0)
jekyll-theme-architect (= 0.1.1)
jekyll-theme-cayman (= 0.1.1)
jekyll-theme-dinky (= 0.1.1)
jekyll-theme-hacker (= 0.1.1)
jekyll-theme-leap-day (= 0.1.1)
jekyll-theme-merlot (= 0.1.1)
jekyll-theme-midnight (= 0.1.1)
jekyll-theme-minimal (= 0.1.1)
jekyll-theme-modernist (= 0.1.1)
jekyll-theme-primer (= 0.5.4)
jekyll-theme-slate (= 0.1.1)
jekyll-theme-tactile (= 0.1.1)
jekyll-theme-time-machine (= 0.1.1)
jekyll-titles-from-headings (= 0.5.3)
jemoji (= 0.11.1)
kramdown (= 1.17.0)
liquid (= 4.0.3)
mercenary (~> 0.3)
minima (= 2.5.1)
nokogiri (>= 1.10.4, < 2.0)
rouge (= 3.13.0)
terminal-table (~> 1.4)
github-pages-health-check (1.16.1)
addressable (~> 2.3)
dnsruby (~> 1.60)
octokit (~> 4.0)
public_suffix (~> 3.0)
typhoeus (~> 1.3)
html-pipeline (2.12.3)
activesupport (>= 2)
nokogiri (>= 1.4)
http_parser.rb (0.6.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
jekyll (3.8.5)
addressable (~> 2.4)
colorator (~> 1.0)
em-websocket (~> 0.5)
i18n (~> 0.7)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 2.0)
kramdown (~> 1.14)
liquid (~> 4.0)
mercenary (~> 0.3.3)
pathutil (~> 0.9)
rouge (>= 1.7, < 4)
safe_yaml (~> 1.0)
jekyll-avatar (0.7.0)
jekyll (>= 3.0, < 5.0)
jekyll-coffeescript (1.1.1)
coffee-script (~> 2.2)
coffee-script-source (~> 1.11.1)
jekyll-commonmark (1.3.1)
commonmarker (~> 0.14)
jekyll (>= 3.7, < 5.0)
jekyll-commonmark-ghpages (0.1.6)
commonmarker (~> 0.17.6)
jekyll-commonmark (~> 1.2)
rouge (>= 2.0, < 4.0)
jekyll-default-layout (0.1.4)
jekyll (~> 3.0)
jekyll-feed (0.13.0)
jekyll (>= 3.7, < 5.0)
jekyll-gist (1.5.0)
octokit (~> 4.2)
jekyll-github-metadata (2.13.0)
jekyll (>= 3.4, < 5.0)
octokit (~> 4.0, != 4.4.0)
jekyll-mentions (1.5.1)
html-pipeline (~> 2.3)
jekyll (>= 3.7, < 5.0)
jekyll-optional-front-matter (0.3.2)
jekyll (>= 3.0, < 5.0)
jekyll-paginate (1.1.0)
jekyll-readme-index (0.3.0)
jekyll (>= 3.0, < 5.0)
jekyll-redirect-from (0.15.0)
jekyll (>= 3.3, < 5.0)
jekyll-relative-links (0.6.1)
jekyll (>= 3.3, < 5.0)
jekyll-remote-theme (0.4.1)
addressable (~> 2.0)
jekyll (>= 3.5, < 5.0)
rubyzip (>= 1.3.0)
jekyll-sass-converter (1.5.2)
sass (~> 3.4)
jekyll-seo-tag (2.6.1)
jekyll (>= 3.3, < 5.0)
jekyll-sitemap (1.4.0)
jekyll (>= 3.7, < 5.0)
jekyll-swiss (1.0.0)
jekyll-theme-architect (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-cayman (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-dinky (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-hacker (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-leap-day (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-merlot (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-midnight (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-minimal (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-modernist (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-primer (0.5.4)
jekyll (> 3.5, < 5.0)
jekyll-github-metadata (~> 2.9)
jekyll-seo-tag (~> 2.0)
jekyll-theme-slate (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-tactile (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-time-machine (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-titles-from-headings (0.5.3)
jekyll (>= 3.3, < 5.0)
jekyll-watch (2.2.1)
listen (~> 3.0)
jemoji (0.11.1)
gemoji (~> 3.0)
html-pipeline (~> 2.2)
jekyll (>= 3.0, < 5.0)
just-the-docs (0.2.7)
jekyll (~> 3.8.5)
jekyll-seo-tag (~> 2.0)
rake (~> 12.3.1)
kramdown (1.17.0)
liquid (4.0.3)
listen (3.2.1)
rb-fsevent (~> 0.10, >= 0.10.3)
rb-inotify (~> 0.9, >= 0.9.10)
mercenary (0.3.6)
mini_portile2 (2.4.0)
minima (2.5.1)
jekyll (>= 3.5, < 5.0)
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
minitest (5.14.1)
multipart-post (2.1.1)
nokogiri (1.10.9)
mini_portile2 (~> 2.4.0)
octokit (4.16.0)
faraday (>= 0.9)
sawyer (~> 0.8.0, >= 0.5.3)
pathutil (0.16.2)
forwardable-extended (~> 2.6)
public_suffix (3.1.1)
rake (12.3.3)
rb-fsevent (0.10.3)
rb-inotify (0.10.1)
ffi (~> 1.0)
rouge (3.13.0)
ruby-enum (0.7.2)
i18n
rubyzip (2.2.0)
safe_yaml (1.0.5)
sass (3.7.4)
sass-listen (~> 4.0.0)
sass-listen (4.0.0)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
sawyer (0.8.2)
addressable (>= 2.3.5)
faraday (> 0.8, < 2.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
thread_safe (0.3.6)
typhoeus (1.3.1)
ethon (>= 0.9.0)
tzinfo (1.2.7)
thread_safe (~> 0.1)
unicode-display_width (1.6.1)
zeitwerk (2.3.0)
PLATFORMS
ruby
DEPENDENCIES
github-pages
just-the-docs
tzinfo-data
BUNDLED WITH
2.1.2

View File

@ -1,19 +0,0 @@
.PHONY: ruby
ruby:
@ if [ ! $$(which ruby) ]; then \
echo "Please install ruby version 2.5.0 or higher"; \
fi
.PHONY: bundle
bundle: ruby
@ if [ ! $$(which bundle) ]; then \
echo "Please install bundle: `gem install bundler`"; \
fi
vendor/bundle: bundle
bundle config set --local path 'vendor/bundle'
bundle install
.PHONY: serve
serve: vendor/bundle
bundle exec jekyll serve

View File

@ -1,13 +1,33 @@
# Docs
# Website
This folder contains our Jekyll based docs site which is hosted at
https://oauth2-proxy.github.io/oauth2-proxy.
This website is built using [Docusaurus 2](https://v2.docusaurus.io/), a modern static website generator.
When making changes to this docs site, please test your changes locally:
## Installation
```bash
docs$ make serve
```console
yarn install
```
To run the docs site locally you will need Ruby at version 2.5.0 or
higher and `bundle` (`gem install bundler` if you already have Ruby).
## Local Development
```console
yarn start
```
This command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server.
## Build
```console
yarn build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
## Deployment
```console
GIT_USER=<Your GitHub username> USE_SSH=true yarn deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.

View File

@ -1,44 +0,0 @@
# Welcome to Jekyll!
#
# This config file is meant for settings that affect your whole blog, values
# which you are expected to set up once and rarely edit after that. If you find
# yourself editing this file very often, consider using Jekyll's data files
# feature for the data you need to update frequently.
#
# For technical reasons, this file is *NOT* reloaded automatically when you use
# 'bundle exec jekyll serve'. If you change this file, please restart the server process.
# Site settings
# These are used to personalize your new site. If you look in the HTML files,
# you will see them accessed via {{ site.title }}, {{ site.email }}, and so on.
# You can create any custom variable you would like, and they will be accessible
# in the templates via {{ site.myvariable }}.
title: OAuth2 Proxy
logo: /logos/OAuth2_Proxy_horizontal.svg
description: >- # this means to ignore newlines until "baseurl:"
OAuth2-Proxy documentation site
baseurl: "/oauth2-proxy" # the subpath of your site, e.g. /blog
url: "https://oauth2-proxy.github.io" # the base hostname & protocol for your site, e.g. http://example.com
gitweb: "https://github.com/oauth2-proxy/oauth2-proxy/blob/master"
# Build settings
markdown: kramdown
remote_theme: pmarsceill/just-the-docs
search_enabled: true
# Aux links for the upper right navigation
aux_links:
"OAuth2 Proxy on GitHub":
- "https://github.com/oauth2-proxy/oauth2-proxy"
# Exclude from processing.
# The following items will not be processed, by default. Create a custom list
# to override the default setting.
# exclude:
# - Gemfile
# - Gemfile.lock
# - node_modules
# - vendor/bundle/
# - vendor/cache/
# - vendor/gems/
# - vendor/ruby/

View File

@ -1,12 +0,0 @@
---
---
{
{% for page in site.html_pages %}"{{ forloop.index0 }}": {
"id": "{{ forloop.index0 }}",
"title": "{{ page.title | xml_escape }}",
"content": "{{ page.content | markdownify | strip_html | xml_escape | remove: 'Table of contents' | strip_newlines | replace: '\', ' ' }}",
"url": "{{ page.url | absolute_url | xml_escape }}",
"relUrl": "{{ page.url | xml_escape }}"
}{% if forloop.last %}{% else %},
{% endif %}{% endfor %}
}

3
docs/babel.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
};

11
docs/docs/behaviour.md Normal file
View File

@ -0,0 +1,11 @@
---
id: behaviour
title: Behaviour
---
1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`).
2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned)
3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set
4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration)
Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md).

View File

@ -1,12 +1,8 @@
---
layout: default
title: Auth Configuration
permalink: /auth-configuration
nav_order: 2
id: oauth_provider
title: OAuth Provider Configuration
---
## OAuth Provider Configuration
You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on.
Valid providers are :
@ -89,7 +85,7 @@ Note: The user is checked against the group members list on initial authenticati
--client-secret=<value from step 6>
```
Note: When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the [redis session storage](configuration/sessions#redis-storage) should resolve this.
Note: When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the [redis session storage](sessions.md#redis-storage) should resolve this.
### Facebook Auth Provider
@ -454,7 +450,7 @@ To authorize by email domain use `--email-domain=yourcompany.com`. To authorize
## Adding a new Provider
Follow the examples in the [`providers` package]({{ site.gitweb }}/providers/) to define a new
Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new
`Provider` instance. Add a new `case` to
[`providers.New()`]({{ site.gitweb }}/providers/providers.go) to allow `oauth2-proxy` to use the
[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the
new `Provider`.

View File

@ -1,13 +1,8 @@
---
layout: default
title: Configuration
permalink: /configuration
has_children: true
nav_order: 3
id: overview
title: Overview
---
## Configuration
`oauth2-proxy` can be configured via [config file](#config-file), [command line options](#command-line-options) or [environment variables](#environment-variables).
To generate a strong cookie secret use `python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(16)).decode())'`
@ -16,7 +11,7 @@ To generate a strong cookie secret use `python -c 'import os,base64; print(base6
Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s).
An example [oauth2-proxy.cfg]({{ site.gitweb }}/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg`
An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg`
### Command Line Options
@ -112,7 +107,7 @@ An example [oauth2-proxy.cfg]({{ site.gitweb }}/contrib/oauth2-proxy.cfg.example
| `--reverse-proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted | false |
| `--scope` | string | OAuth scope specification | |
| `--session-cookie-minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false |
| `--session-store-type` | string | [Session data storage backend](configuration/sessions); redis or cookie | cookie |
| `--session-store-type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
| `--set-xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false |
| `--set-authorization-header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false |
| `--set-basic-auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false |
@ -121,7 +116,7 @@ An example [oauth2-proxy.cfg]({{ site.gitweb }}/contrib/oauth2-proxy.cfg.example
| `--skip-auth-preflight` | bool | will skip authentication for OPTIONS requests | false |
| `--skip-auth-regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | |
| `--skip-auth-route` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR path_regex alone for all methods | |
| `--skip-auth-strip-headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy for allowlisted requests (`--skip-auth-route`, `--skip-auth-regex`, `--skip-auth-preflight`, `--trusted-ip`) | false |
| `--skip-auth-strip-headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true |
| `--skip-jwt-bearer-tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false |
| `--skip-oidc-discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false |
| `--skip-provider-button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
@ -195,7 +190,7 @@ If you require a different format than that, you can configure it with the `--au
The default format is configured as follows:
```
{% raw %}{{.Client}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}{% endraw %}
{{.Client}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}
```
Available variables for auth logging:
@ -223,7 +218,7 @@ If you require a different format than that, you can configure it with the `--re
The default format is configured as follows:
```
{% raw %}{{.Client}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}{% endraw %}
{{.Client}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}
```
Available variables for request logging:
@ -253,7 +248,7 @@ All other logging that is not covered by the above two types of logging will be
If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows:
```
{% raw %}[{{.Timestamp}}] [{{.File}}] {{.Message}}{% endraw %}
[{{.Timestamp}}] [{{.File}}] {{.Message}}
```
Available variables for standard logging:
@ -264,7 +259,7 @@ Available variables for standard logging:
| File | main.go:40 | The file and line number of the logging statement. |
| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. |
## <a name="nginx-auth-request"></a>Configuring for use with the Nginx `auth_request` directive
## Configuring for use with the Nginx `auth_request` directive
The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example:
@ -358,5 +353,6 @@ It is recommended to use `--session-store-type=redis` when expecting large sessi
You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=".
### Note on rotated Client Secret
:::note
If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated.
:::

View File

@ -1,13 +1,8 @@
---
layout: default
title: Sessions
permalink: /configuration/sessions
parent: Configuration
nav_order: 3
id: session_storage
title: Session Storage
---
## Sessions
Sessions allow a user's authentication to be tracked between multiple HTTP
requests to a service.
@ -38,7 +33,7 @@ users to re-authenticate
### Redis Storage
The Redis Storage backend stores sessions, encrypted, in redis. Instead sending all the information
back the the client for storage, as in the [Cookie storage](cookie-storage), a ticket is sent back
back the the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back
to the user as the cookie value instead.
A ticket is composed as the following:

View File

@ -1,12 +1,8 @@
---
layout: default
id: tls
title: TLS Configuration
permalink: /tls-configuration
nav_order: 4
---
## SSL Configuration
There are two recommended configurations.
1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`.

View File

@ -1,12 +1,8 @@
---
layout: default
id: endpoints
title: Endpoints
permalink: /endpoints
nav_order: 5
---
## Endpoint Documentation
OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable.
- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info
@ -16,7 +12,7 @@ OAuth2 Proxy responds directly to the following endpoints. All other endpoints w
- /oauth2/start - a URL that will redirect to start the OAuth cycle
- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url.
- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format.
- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](#nginx-auth-request)
- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/overview.md#configuring-for-use-with-the-nginx-auth_request-directive)
### Sign out
@ -36,4 +32,4 @@ X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page
(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.)
BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](configuration) configuration option otherwise the redirect will be ignored.
BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored.

View File

@ -1,17 +1,13 @@
---
layout: default
id: request_signatures
title: Request Signatures
permalink: /request-signatures
nav_order: 6
---
## Request signatures
If `signature_key` is defined, proxied requests will be signed with the
`GAP-Signature` header, which is a [Hash-based Message Authentication Code
(HMAC)](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)
of selected request information and the request body [see `SIGNATURE_HEADERS`
in `oauthproxy.go`]({{ site.gitweb }}/oauthproxy.go).
in `oauthproxy.go`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/oauthproxy.go).
`signature_key` must be of the form `algorithm:secretkey`, (ie: `signature_key = "sha1:secret0"`)

View File

@ -1,12 +1,9 @@
---
layout: default
id: installation
title: Installation
permalink: /installation
nav_order: 1
slug: /
---
## Installation
1. Choose how to deploy:
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v6.1.1`)
@ -22,6 +19,6 @@ $ sha256sum -c sha256sum.txt 2>&1 | grep OK
oauth2-proxy-x.y.z.linux-amd64: OK
```
2. [Select a Provider and Register an OAuth Application with a Provider](auth-configuration)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration)
4. [Configure SSL or Deploy behind a SSL endpoint](tls-configuration) (example provided for Nginx)
2. [Select a Provider and Register an OAuth Application with a Provider](configuration/auth.md)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md)
4. [Configure SSL or Deploy behind a SSL endpoint](configuration/tls.md) (example provided for Nginx)

57
docs/docusaurus.config.js Normal file
View File

@ -0,0 +1,57 @@
module.exports = {
title: 'OAuth2 Proxy',
tagline: 'A lightweight authentication proxy written in Go',
url: 'https://oauth2-proxy.github.io',
baseUrl: '/oauth2-proxy/',
onBrokenLinks: 'throw',
favicon: 'img/logos/OAuth2_Proxy_icon.svg',
organizationName: 'oauth2-proxy', // Usually your GitHub org/user name.
projectName: 'oauth2-proxy', // Usually your repo name.
themeConfig: {
navbar: {
title: 'OAuth2 Proxy',
logo: {
alt: 'OAuth2 Proxy',
src: 'img/logos/OAuth2_Proxy_icon.svg',
},
items: [
{
to: 'docs/',
activeBasePath: 'docs',
label: 'Docs',
position: 'left',
},
{
type: 'docsVersionDropdown',
position: 'right',
dropdownActiveClassDisabled: true,
},
{
href: 'https://github.com/oauth2-proxy/oauth2-proxy',
label: 'GitHub',
position: 'right',
},
],
},
footer: {
style: 'dark',
copyright: `Copyright © ${new Date().getFullYear()} OAuth2 Proxy.`,
},
},
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
// Please change this to your repo.
editUrl:
'https://github.com/oauth2-proxy/oauth2-proxy/edit/master/docs/',
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
};

14114
docs/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

33
docs/package.json Normal file
View File

@ -0,0 +1,33 @@
{
"name": "docusaurus",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"serve": "docusaurus serve"
},
"dependencies": {
"@docusaurus/core": "2.0.0-alpha.66",
"@docusaurus/preset-classic": "2.0.0-alpha.66",
"@mdx-js/react": "^1.5.8",
"clsx": "^1.1.1",
"react": "^16.8.4",
"react-dom": "^16.8.4"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

24
docs/sidebars.js Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
docs: [
{
type: 'doc',
id: 'installation',
},
{
type: 'doc',
id: 'behaviour',
},
{
type: 'category',
label: 'Configuration',
collapsed: false,
items: ['configuration/overview', 'configuration/oauth_provider', 'configuration/session_storage', 'configuration/tls'],
},
{
type: 'category',
label: 'Features',
collapsed: false,
items: ['features/endpoints', 'features/request_signatures'],
},
],
};

25
docs/src/css/custom.css Normal file
View File

@ -0,0 +1,25 @@
/* stylelint-disable docusaurus/copyright-header */
/**
* Any CSS included here will be global. The classic template
* bundles Infima by default. Infima is a CSS framework designed to
* work well for content-centric websites.
*/
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: rgb(33, 175, 144);
--ifm-color-primary-darker: rgb(31, 165, 136);
--ifm-color-primary-darkest: rgb(26, 136, 112);
--ifm-color-primary-light: rgb(70, 203, 174);
--ifm-color-primary-lighter: rgb(102, 212, 189);
--ifm-color-primary-lightest: rgb(146, 224, 208);
--ifm-code-font-size: 95%;
}
.docusaurus-highlight-code-line {
background-color: rgb(72, 77, 91);
display: block;
margin: 0 calc(-1 * var(--ifm-pre-padding));
padding: 0 var(--ifm-pre-padding);
}

21
docs/src/pages/index.md Normal file
View File

@ -0,0 +1,21 @@
---
title: Welcome to OAuth2 Proxy
hide_table_of_contents: true
---
![OAuth2 Proxy](../../static/img/logos/OAuth2_Proxy_horizontal.svg)
A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others)
to validate accounts by email, domain or group.
:::note
This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018.
Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork.
A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md).
:::
![Sign In Page](../../static/img/sign-in-page.png)
## Architecture
![OAuth2 Proxy Architecture](../../static/img/architecture.png)

View File

@ -0,0 +1,37 @@
/* stylelint-disable docusaurus/copyright-header */
/**
* CSS files with the .module.css suffix will be treated as CSS modules
* and scoped locally.
*/
.heroBanner {
padding: 4rem 0;
text-align: center;
position: relative;
overflow: hidden;
}
@media screen and (max-width: 966px) {
.heroBanner {
padding: 2rem;
}
}
.buttons {
display: flex;
align-items: center;
justify-content: center;
}
.features {
display: flex;
align-items: center;
padding: 2rem 0;
width: 100%;
}
.featureImage {
height: 200px;
width: 200px;
}

0
docs/static/.nojekyll vendored Normal file
View File

BIN
docs/static/img/architecture.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 108 KiB

View File

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

View File

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 55 KiB

View File

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

BIN
docs/static/img/sign-in-page.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File

@ -0,0 +1,11 @@
---
id: behaviour
title: Behaviour
---
1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`).
2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned)
3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set
4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration)
Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md).

View File

@ -0,0 +1,456 @@
---
id: oauth_provider
title: OAuth Provider Configuration
---
You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on.
Valid providers are :
- [Google](#google-auth-provider) _default_
- [Azure](#azure-auth-provider)
- [Facebook](#facebook-auth-provider)
- [GitHub](#github-auth-provider)
- [Keycloak](#keycloak-auth-provider)
- [GitLab](#gitlab-auth-provider)
- [LinkedIn](#linkedin-auth-provider)
- [Microsoft Azure AD](#microsoft-azure-ad-provider)
- [OpenID Connect](#openid-connect-provider)
- [login.gov](#logingov-provider)
- [Nextcloud](#nextcloud-provider)
- [DigitalOcean](#digitalocean-auth-provider)
- [Bitbucket](#bitbucket-auth-provider)
- [Gitea](#gitea-auth-provider)
The provider can be selected using the `provider` configuration value.
Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the OpenID Connect provider.
### Google Auth Provider
For Google, the registration steps are:
1. Create a new project: https://console.developers.google.com/project
2. Choose the new project from the top right project dropdown (only if another project is selected)
3. In the project Dashboard center pane, choose **"API Manager"**
4. In the left Nav pane, choose **"Credentials"**
5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save.
6. In the center pane, choose **"Credentials"** tab.
- Open the **"New credentials"** drop down
- Choose **"OAuth client ID"**
- Choose **"Web application"**
- Application name is freeform, choose something appropriate
- Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com`
- Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback`
- Choose **"Create"**
7. Take note of the **Client ID** and **Client Secret**
It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the account is still authorized.
#### Restrict auth to specific Google groups on your domain. (optional)
1. Create a service account: https://developers.google.com/identity/protocols/OAuth2ServiceAccount and make sure to download the json file.
2. Make note of the Client ID for a future step.
3. Under "APIs & Auth", choose APIs.
4. Click on Admin SDK and then Enable API.
5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account and give the client id from step 2 the following oauth scopes:
```
https://www.googleapis.com/auth/admin.directory.group.readonly
https://www.googleapis.com/auth/admin.directory.user.readonly
```
6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access.
7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from step 5 for the reason why.
8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances of this flag with different groups
and the user will be checked against all the provided groups.
9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and set the path to the file in the `google-service-account-json` flag.
10. Restart oauth2-proxy.
Note: The user is checked against the group members list on initial authentication and every time the token is refreshed ( about once an hour ).
### Azure Auth Provider
1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **"Azure Active Directory"** in the left menu, select **"App registrations"** and then click on **"New app registration"**.
2. Pick a name and choose **"Webapp / API"** as application type. Use `https://internal.yourcompany.com` as Sign-on URL. Click **"Create"**.
3. On the **"Settings"** / **"Properties"** page of the app, pick a logo and select **"Multi-tenanted"** if you want to allow users from multiple organizations to access your app. Note down the application ID. Click **"Save"**.
4. On the **"Settings"** / **"Required Permissions"** page of the app, click on **"Windows Azure Active Directory"** and then on **"Access the directory as the signed in user"**. Hit **"Save"** and then then on **"Grant permissions"** (you might need another admin to do this).
5. On the **"Settings"** / **"Reply URLs"** page of the app, add `https://internal.yourcompanycom/oauth2/callback` for each host that you want to protect by the oauth2 proxy. Click **"Save"**.
6. On the **"Settings"** / **"Keys"** page of the app, add a new key and note down the value after hitting **"Save"**.
7. Configure the proxy with
```
--provider=azure
--client-id=<application ID from step 3>
--client-secret=<value from step 6>
```
Note: When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the [redis session storage](sessions.md#redis-storage) should resolve this.
### Facebook Auth Provider
1. Create a new FB App from <https://developers.facebook.com/>
2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback`
### GitHub Auth Provider
1. Create a new project: https://github.com/settings/developers
2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback`
The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`
NOTE: When `--github-user` is set, the specified users are allowed to login even if they do not belong to the specified org and team or collaborators.
To restrict by organization only, include the following flag:
-github-org="": restrict logins to members of this organisation
To restrict within an organization to specific teams, include the following flag in addition to `-github-org`:
-github-team="": restrict logins to members of any of these teams (slug), separated by a comma
If you would rather restrict access to collaborators of a repository, those users must either have push access to a public repository or any access to a private repository:
-github-repo="": restrict logins to collaborators of this repository formatted as orgname/repo
If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a [token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be created with at least the `public_repo` scope:
-github-token="": the token to use when verifying repository collaborators
To allow a user to login with their username even if they do not belong to the specified org and team or collaborators, separated by a comma
-github-user="": allow logins by username, separated by a comma
If you are using GitHub enterprise, make sure you set the following to the appropriate url:
-login-url="http(s)://<enterprise github host>/login/oauth/authorize"
-redeem-url="http(s)://<enterprise github host>/login/oauth/access_token"
-validate-url="http(s)://<enterprise github host>/api/v3"
### Keycloak Auth Provider
1. Create new client in your Keycloak with **Access Type** 'confidental' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback'
2. Take note of the Secret in the credential tab of the client
3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'.
Make sure you set the following to the appropriate url:
-provider=keycloak
-client-id=<client you have created>
-client-secret=<your client's secret>
-login-url="http(s)://<keycloak host>/realms/<your realm>/protocol/openid-connect/auth"
-redeem-url="http(s)://<keycloak host>/realms/<your realm>/protocol/openid-connect/token"
-validate-url="http(s)://<keycloak host>/realms/<your realm>/protocol/openid-connect/userinfo"
-keycloak-group=<user_group>
The group management in keycloak is using a tree. If you create a group named admin in keycloak you should define the 'keycloak-group' value to /admin.
### GitLab Auth Provider
Whether you are using GitLab.com or self-hosting GitLab, follow [these steps to add an application](https://docs.gitlab.com/ce/integration/oauth_provider.html). Make sure to enable at least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. https://myapp.com/oauth2/callback.
The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow [these steps](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/docs/configuration/configuration.md#configuration)
```
--provider="gitlab"
--redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab
--client-id=GITLAB_CLIENT_ID
--client-secret=GITLAB_CLIENT_SECRET
--cookie-secret=COOKIE_SECRET
```
Restricting by group membership is possible with the following option:
--gitlab-group="mygroup,myothergroup": restrict logins to members of any of these groups (slug), separated by a comma
If you are using self-hosted GitLab, make sure you set the following to the appropriate URL:
--oidc-issuer-url="<your gitlab url>"
### LinkedIn Auth Provider
For LinkedIn, the registration steps are:
1. Create a new project: https://www.linkedin.com/secure/developer
2. In the OAuth User Agreement section:
- In default scope, select r_basicprofile and r_emailaddress.
- In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback`
3. Fill in the remaining required fields and Save.
4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key**
### Microsoft Azure AD Provider
For adding an application to the Microsoft Azure AD follow [these steps to add an application](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app).
Take note of your `TenantId` if applicable for your situation. The `TenantId` can be used to override the default `common` authorization server with a tenant specific server.
### OpenID Connect Provider
OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. This provider was originally built against CoreOS Dex and we will use it as an example.
1. Launch a Dex instance using the [getting started guide](https://github.com/coreos/dex/blob/master/Documentation/getting-started.md).
2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks.
3. Login with the fixture use in the dex guide and run the oauth2-proxy with the following args:
```
-provider oidc
-provider-display-name "My OIDC Provider"
-client-id oauth2-proxy
-client-secret proxy
-redirect-url http://127.0.0.1:4180/oauth2/callback
-oidc-issuer-url http://127.0.0.1:5556
-cookie-secure=false
-email-domain example.com
```
The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta. To configure the OIDC provider for Okta, perform
the following steps:
#### Configuring the OIDC Provider with Okta
1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com`
2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications,
you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work.
* Navigate to **Security** then select **API**
* Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom authorization server.
* Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'.
* For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com
* Fill out a **Description**
* Add any **Access Policies** you wish to configure to limit application access.
* The default settings will work for other options.
[See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/)
3. Navigate to **Applications** then select **Add Application**.
* Select **Web** for the **Platform** setting.
* Select **OpenID Connect** and click **Create**
* Pick an **Application Name** such as `Example App`.
* Set the **Login redirect URI** to `https://example.corp.com`.
* Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`.
* Leave the rest as default, taking note of the `Client ID` and `Client Secret`.
* Under **Assignments** select the users or groups you wish to access your application.
4. Create a configuration file like the following:
```
provider = "oidc"
redirect_url = "https://example.corp.com/oauth2/callback"
oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234"
upstreams = [
"https://example.corp.com"
]
email_domains = [
"corp.com"
]
client_id = "XXXXX"
client_secret = "YYYYY"
pass_access_token = true
cookie_secret = "ZZZZZ"
skip_provider_button = true
```
The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply https://corp.okta.com
The `client_id` and `client_secret` are configured in the application settings.
Generate a unique `client_secret` to encrypt the cookie.
Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg`
#### Configuring the OIDC Provider with Okta - localhost
1. Signup for developer account: https://developer.okta.com/signup/
2. Create New `Web` Application: https://${your-okta-domain}/dev/console/apps/new
3. Example Application Settings for localhost:
* **Name:** My Web App
* **Base URIs:** http://localhost:4180/
* **Login redirect URIs:** http://localhost:4180/oauth2/callback
* **Logout redirect URIs:** http://localhost:4180/
* **Group assignments:** `Everyone`
* **Grant type allowed:** `Authorization Code` and `Refresh Token`
4. Make note of the `Client ID` and `Client secret`, they are needed in a future step
5. Make note of the **default** Authorization Server Issuer URI from: https://${your-okta-domain}/admin/oauth2/as
6. Example config file `/etc/localhost.cfg`
```
provider = "oidc"
redirect_url = "http://localhost:4180/oauth2/callback"
oidc_issuer_url = "https://${your-okta-domain}/oauth2/default"
upstreams = [
"http://0.0.0.0:8080"
]
email_domains = [
"*"
]
client_id = "XXX"
client_secret = "YYY"
pass_access_token = true
cookie_secret = "ZZZ"
cookie_secure = false
skip_provider_button = true
# Note: use the following for testing within a container
# http_address = "0.0.0.0:4180"
```
7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg`
### login.gov Provider
login.gov is an OIDC provider for the US Government.
If you are a US Government agency, you can contact the login.gov team through the contact information
that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov
accounts for integration/test and production access.
A developer guide is available here: https://developers.login.gov/, though this proxy handles everything
but the data you need to create to register your application in the login.gov dashboard.
As a demo, we will assume that you are running your application that you want to secure locally on
http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that
you have an agency integration account for testing.
First, register your application in the dashboard. The important bits are:
* Identity protocol: make this `Openid connect`
* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`.
* Public key: This is a self-signed certificate in .pem format generated from a 2048 bit RSA private key.
A quick way to do this is `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`,
The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`.
* Return to App URL: Make this be `http://localhost:4180/`
* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`.
* Attribute Bundle: Make sure that email is selected.
Now start the proxy up with the following options:
```
./oauth2-proxy -provider login.gov \
-client-id=${LOGINGOV_ISSUER} \
-redirect-url=http://localhost:4180/oauth2/callback \
-oidc-issuer-url=https://idp.int.identitysandbox.gov/ \
-cookie-secure=false \
-email-domain=gsa.gov \
-upstream=http://localhost:3000/ \
-cookie-secret=somerandomstring12341234567890AB \
-cookie-domain=localhost \
-skip-provider-button=true \
-pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \
-profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \
-jwt-key="${OAUTH2_PROXY_JWT_KEY}"
```
You can also set all these options with environment variables, for use in cloud/docker environments.
One tricky thing that you may encounter is that some cloud environments will pass in environment
variables in a docker env-file, which does not allow multiline variables like a PEM file.
If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level
directory of the repo which contains the key in PEM format and then do your docker build.
The docker build process will copy that file into your image which you can then access by
setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem`
environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline.
Once it is running, you should be able to go to `http://localhost:4180/` in your browser,
get authenticated by the login.gov integration server, and then get proxied on to your
application running on `http://localhost:3000/`. In a real deployment, you would secure
your application with a firewall or something so that it was only accessible from the
proxy, and you would use real hostnames everywhere.
#### Skip OIDC discovery
Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, token and jwks URI endpoints from the provider's metadata.
In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually:
```
-provider oidc
-client-id oauth2-proxy
-client-secret proxy
-redirect-url http://127.0.0.1:4180/oauth2/callback
-oidc-issuer-url http://127.0.0.1:5556
-skip-oidc-discovery
-login-url http://127.0.0.1:5556/authorize
-redeem-url http://127.0.0.1:5556/token
-oidc-jwks-url http://127.0.0.1:5556/keys
-cookie-secure=false
-email-domain example.com
```
### Nextcloud Provider
The Nextcloud provider allows you to authenticate against users in your
Nextcloud instance.
When you are using the Nextcloud provider, you must specify the urls via
configuration, environment variable, or command line argument. Depending
on whether your Nextcloud instance is using pretty urls your urls may be of the
form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`.
Refer to the [OAuth2
documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html)
to setup the client id and client secret. Your "Redirection URI" will be
`https://internalapp.yourcompany.com/oauth2/callback`.
```
-provider nextcloud
-client-id <from nextcloud admin>
-client-secret <from nextcloud admin>
-login-url="<your nextcloud url>/index.php/apps/oauth2/authorize"
-redeem-url="<your nextcloud url>/index.php/apps/oauth2/api/v1/token"
-validate-url="<your nextcloud url>/ocs/v2.php/cloud/user?format=json"
```
Note: in *all* cases the validate-url will *not* have the `index.php`.
### DigitalOcean Auth Provider
1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications)
* You can fill in the name, homepage, and description however you wish.
* In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL.
2. Note the Client ID and Client Secret.
To use the provider, pass the following options:
```
--provider=digitalocean
--client-id=<Client ID>
--client-secret=<Client Secret>
```
Alternatively, set the equivalent options in the config file. The redirect URL defaults to `https://<requested host header>/oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option.
### Bitbucket Auth Provider
1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html)
* In "Callback URL" use `https://<oauth2-proxy>/oauth2/callback`, substituting `<oauth2-proxy>` with the actual hostname that oauth2-proxy is running on.
* In Permissions section select:
* Account -> Email
* Team membership -> Read
* Repositories -> Read
2. Note the Client ID and Client Secret.
To use the provider, pass the following options:
```
--provider=bitbucket
--client-id=<Client ID>
--client-secret=<Client Secret>
```
The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team members use additional configuration option: `--bitbucket-team=<Team name>`. To restrict the access to only these users who has access to one selected repository use `--bitbucket-repository=<Repository name>`.
### Gitea Auth Provider
1. Create a new application: `https://< your gitea host >/user/settings/applications`
2. Under `Redirect URI` enter the correct URL i.e. `https://<proxied host>/oauth2/callback`
3. Note the Client ID and Client Secret.
4. Pass the following options to the proxy:
```
--provider="github"
--redirect-url="https://<proxied host>/oauth2/callback"
--provider-display-name="Gitea"
--client-id="< client_id as generated by Gitea >"
--client-secret="< client_secret as generated by Gitea >"
--login-url="https://< your gitea host >/login/oauth/authorize"
--redeem-url="https://< your gitea host >/login/oauth/access_token"
--validate-url="https://< your gitea host >/api/v1"
```
## Email Authentication
To authorize by email domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use `--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`.
## Adding a new Provider
Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new
`Provider` instance. Add a new `case` to
[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the
new `Provider`.

View File

@ -0,0 +1,355 @@
---
id: overview
title: Overview
---
`oauth2-proxy` can be configured via [config file](#config-file), [command line options](#command-line-options) or [environment variables](#environment-variables).
To generate a strong cookie secret use `python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(16)).decode())'`
### Config File
Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s).
An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg`
### Command Line Options
| Option | Type | Description | Default |
| ------ | ---- | ----------- | ------- |
| `--acr-values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` |
| `--approval-prompt` | string | OAuth approval_prompt | `"force"` |
| `--auth-logging` | bool | Log authentication attempts | true |
| `--auth-logging-format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) |
| `--authenticated-emails-file` | string | authenticate against emails via file (one per line) | |
| `--azure-tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` |
| `--basic-auth-password` | string | the password to set when passing the HTTP Basic Auth header | |
| `--client-id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | |
| `--client-secret` | string | the OAuth Client Secret | |
| `--client-secret-file` | string | the file with OAuth Client Secret | |
| `--config` | string | path to config file | |
| `--cookie-domain` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | |
| `--cookie-expire` | duration | expire timeframe for cookie | 168h0m0s |
| `--cookie-httponly` | bool | set HttpOnly cookie flag | true |
| `--cookie-name` | string | the name of the cookie that the oauth_proxy creates | `"_oauth2_proxy"` |
| `--cookie-path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` |
| `--cookie-refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;\[[1](#footnote1)\] | |
| `--cookie-secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
| `--cookie-secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
| `--cookie-samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
| `--custom-templates-dir` | string | path to custom html templates | |
| `--display-htpasswd-form` | bool | display username / password login form if an htpasswd file is provided | true |
| `--email-domain` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | |
| `--errors-to-info-log` | bool | redirects error-level logging to default log channel instead of stderr | |
| `--extra-jwt-issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | |
| `--exclude-logging-paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` |`""` (no paths excluded) |
| `--flush-interval` | duration | period between flushing response buffers when streaming responses | `"1s"` |
| `--force-https` | bool | enforce https redirect | `false` |
| `--banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
| `--footer` | string | custom (html) footer string. Use `"-"` to disable default footer. | |
| `--gcp-healthchecks` | bool | will enable `/liveness_check`, `/readiness_check`, and `/` (with the proper user-agent) endpoints that will make it work well with GCP App Engine and GKE Ingresses | false |
| `--github-org` | string | restrict logins to members of this organisation | |
| `--github-team` | string | restrict logins to members of any of these teams (slug), separated by a comma | |
| `--github-repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | |
| `--github-token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | |
| `--github-user` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | |
| `--gitlab-group` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
| `--google-admin-email` | string | the google admin to impersonate for api calls | |
| `--google-group` | string | restrict logins to members of this google group (may be given multiple times). | |
| `--google-service-account-json` | string | the path to the service account json credentials | |
| `--htpasswd-file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -s` for SHA encryption | |
| `--http-address` | string | `[http://]<addr>:<port>` or `unix://<path>` to listen on for HTTP clients | `"127.0.0.1:4180"` |
| `--https-address` | string | `<addr>:<port>` to listen on for HTTPS clients | `":443"` |
| `--logging-compress` | bool | Should rotated log files be compressed using gzip | false |
| `--logging-filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) |
| `--logging-local-time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) |
| `--logging-max-age` | int | Maximum number of days to retain old log files | 7 |
| `--logging-max-backups` | int | Maximum number of old log files to retain; 0 to disable | 0 |
| `--logging-max-size` | int | Maximum size in megabytes of the log file before rotation | 100 |
| `--jwt-key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | |
| `--jwt-key-file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | |
| `--login-url` | string | Authentication endpoint | |
| `--insecure-oidc-allow-unverified-email` | bool | don't fail if an email address in an id_token is not verified | false |
| `--insecure-oidc-skip-issuer-verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false |
| `--oidc-issuer-url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | |
| `--oidc-jwks-url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled | |
| `--pass-access-token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false |
| `--pass-authorization-header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false |
| `--pass-basic-auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
| `--prefer-email-to-user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false |
| `--pass-host-header` | bool | pass the request Host Header to upstream | true |
| `--pass-user-headers` | bool | pass X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
| `--profile-url` | string | Profile access endpoint | |
| `--prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
| `--provider` | string | OAuth provider | google |
| `--provider-ca-file` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. |
| `--provider-display-name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) |
| `--ping-path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` |
| `--ping-user-agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) |
| `--proxy-prefix` | string | the url root path that this proxy should be nested under (e.g. /`<oauth2>/sign_in`) | `"/oauth2"` |
| `--proxy-websockets` | bool | enables WebSocket proxying | true |
| `--pubjwk-url` | string | JWK pubkey access endpoint: required by login.gov | |
| `--real-client-ip-header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, or X-ProxyUser-IP) | X-Real-IP |
| `--redeem-url` | string | Token redemption endpoint | |
| `--redirect-url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
| `--redis-cluster-connection-urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | |
| `--redis-connection-url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
| `--redis-password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
| `--redis-sentinel-password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
| `--redis-sentinel-master-name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | |
| `--redis-sentinel-connection-urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | |
| `--redis-use-cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false |
| `--redis-use-sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false |
| `--request-logging` | bool | Log requests | true |
| `--request-logging-format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) |
| `--resource` | string | The resource that is protected (Azure AD only) | |
| `--reverse-proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted | false |
| `--scope` | string | OAuth scope specification | |
| `--session-cookie-minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false |
| `--session-store-type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
| `--set-xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false |
| `--set-authorization-header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false |
| `--set-basic-auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false |
| `--signature-key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
| `--silence-ping-logging` | bool | disable logging of requests to ping endpoint | false |
| `--skip-auth-preflight` | bool | will skip authentication for OPTIONS requests | false |
| `--skip-auth-regex` | string | bypass authentication for requests paths that match (may be given multiple times) | |
| `--skip-auth-strip-headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy for request paths in `--skip-auth-regex` | false |
| `--skip-jwt-bearer-tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false |
| `--skip-oidc-discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false |
| `--skip-provider-button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
| `--ssl-insecure-skip-verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
| `--ssl-upstream-insecure-skip-verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false |
| `--standard-logging` | bool | Log standard runtime information | true |
| `--standard-logging-format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) |
| `--tls-cert-file` | string | path to certificate file | |
| `--tls-key-file` | string | path to private key file | |
| `--upstream` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://<status_code>` for static response. Routing is based on the path | |
| `--user-id-claim` | string | which claim contains the user ID | \["email"\] |
| `--validate-url` | string | Access token validation endpoint | |
| `--version` | n/a | print version string | |
| `--whitelist-domain` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` to allow subdomains (e.g. `.example.com`)&nbsp;\[[2](#footnote2)\] | |
| `--trusted-ip` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | |
\[<a name="footnote1">1</a>\]: Only these providers support `--cookie-refresh`: GitLab, Google and OIDC
\[<a name="footnote2">2</a>\]: When using the `whitelist-domain` option, any domain prefixed with a `.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`.
See below for provider specific options
### Upstreams Configuration
`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers or serve static files from the file system. HTTP and HTTPS upstreams are configured by providing a URL such as `http://127.0.0.1:8080/` for the upstream parameter. This will forward all authenticated requests to the upstream server. If you instead provide `http://127.0.0.1:8080/some/path/` then it will only be requests that start with `/some/path/` which are forwarded to the upstream.
Static file paths are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`.
Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with.
### Environment variables
Every command line argument can be specified as an environment variable by
prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`)
with underscores (`_`). If the argument can be specified multiple times, the
environment variable should be plural (trailing `S`).
This is particularly useful for storing secrets outside of a configuration file
or the command line.
For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`,
and the `--email-domain` flag becomes `OAUTH2_PROXY_EMAIL_DOMAINS`.
## Logging Configuration
By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command.
If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`).
There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`.
Each type of logging has its own configurable format and variables. By default these formats are similar to the Apache Combined Log.
Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) can be disabled with `--silence-ping-logging` reducing log volume. This flag appends the `--ping-path` to `--exclude-logging-paths`.
### Auth Log Format
Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format:
```
<REMOTE_ADDRESS> - <user@domain.com> [19/Mar/2015:17:20:19 -0400] [<STATUS>] <MESSAGE>
```
The status block will contain one of the below strings:
- `AuthSuccess` If a user has authenticated successfully by any method
- `AuthFailure` If the user failed to authenticate explicitly
- `AuthError` If there was an unexpected error during authentication
If you require a different format than that, you can configure it with the `--auth-logging-format` flag.
The default format is configured as follows:
```
{{.Client}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}
```
Available variables for auth logging:
| Variable | Example | Description |
| --- | --- | --- |
| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. |
| Host | domain.com | The value of the Host header. |
| Protocol | HTTP/1.0 | The request protocol. |
| RequestMethod | GET | The request method. |
| Timestamp | 19/Mar/2015:17:20:19 -0400 | The date and time of the logging event. |
| UserAgent | - | The full user agent as reported by the requesting client. |
| Username | username@email.com | The email or username of the auth request. |
| Status | AuthSuccess | The status of the auth request. See above for details. |
| Message | Authenticated via OAuth2 | The details of the auth attempt. |
### Request Log Format
HTTP request logs will output by default in the below format:
```
<REMOTE_ADDRESS> - <user@domain.com> [19/Mar/2015:17:20:19 -0400] <HOST_HEADER> GET <UPSTREAM_HOST> "/path/" HTTP/1.1 "<USER_AGENT>" <RESPONSE_CODE> <RESPONSE_BYTES> <REQUEST_DURATION>
```
If you require a different format than that, you can configure it with the `--request-logging-format` flag.
The default format is configured as follows:
```
{{.Client}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}
```
Available variables for request logging:
| Variable | Example | Description |
| --- | --- | --- |
| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. |
| Host | domain.com | The value of the Host header. |
| Protocol | HTTP/1.0 | The request protocol. |
| RequestDuration | 0.001 | The time in seconds that a request took to process. |
| RequestMethod | GET | The request method. |
| RequestURI | "/oauth2/auth" | The URI path of the request. |
| ResponseSize | 12 | The size in bytes of the response. |
| StatusCode | 200 | The HTTP status code of the response. |
| Timestamp | 19/Mar/2015:17:20:19 -0400 | The date and time of the logging event. |
| Upstream | - | The upstream data of the HTTP request. |
| UserAgent | - | The full user agent as reported by the requesting client. |
| Username | username@email.com | The email or username of the auth request. |
### Standard Log Format
All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below:
```
[19/Mar/2015:17:20:19 -0400] [main.go:40] <MESSAGE>
```
If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows:
```
[{{.Timestamp}}] [{{.File}}] {{.Message}}
```
Available variables for standard logging:
| Variable | Example | Description |
| --- | --- | --- |
| Timestamp | 19/Mar/2015:17:20:19 -0400 | The date and time of the logging event. |
| File | main.go:40 | The file and line number of the logging statement. |
| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. |
## Configuring for use with the Nginx `auth_request` directive
The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example:
```nginx
server {
listen 443 ssl;
server_name ...;
include ssl/ssl.conf;
location /oauth2/ {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Auth-Request-Redirect $request_uri;
# or, if you are handling multiple domains:
# proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
}
location = /oauth2/auth {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
# nginx auth_request includes headers but not body
proxy_set_header Content-Length "";
proxy_pass_request_body off;
}
location / {
auth_request /oauth2/auth;
error_page 401 = /oauth2/sign_in;
# pass information via X-User and X-Email headers to backend,
# requires running with --set-xauthrequest flag
auth_request_set $user $upstream_http_x_auth_request_user;
auth_request_set $email $upstream_http_x_auth_request_email;
proxy_set_header X-User $user;
proxy_set_header X-Email $email;
# if you enabled --pass-access-token, this will pass the token to the backend
auth_request_set $token $upstream_http_x_auth_request_access_token;
proxy_set_header X-Access-Token $token;
# if you enabled --cookie-refresh, this is needed for it to work with auth_request
auth_request_set $auth_cookie $upstream_http_set_cookie;
add_header Set-Cookie $auth_cookie;
# When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb
# limit and so the OAuth2 Proxy splits these into multiple parts.
# Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response,
# so if your cookies are larger than 4kb, you will need to extract additional cookies manually.
auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;
# Extract the Cookie attributes from the first Set-Cookie header and append them
# to the second part ($upstream_cookie_* variables only contain the raw cookie content)
if ($auth_cookie ~* "(; .*)") {
set $auth_cookie_name_0 $auth_cookie;
set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
}
# Send both Set-Cookie headers now if there was a second part
if ($auth_cookie_name_upstream_1) {
add_header Set-Cookie $auth_cookie_name_0;
add_header Set-Cookie $auth_cookie_name_1;
}
proxy_pass http://backend/;
# or "root /path/to/site;" or "fastcgi_pass ..." etc
}
}
```
When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`.
Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua.
Note that `nginxinc/kubernetes-ingress` does not include the Lua module.
```yaml
nginx.ingress.kubernetes.io/auth-response-headers: Authorization
nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri
nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth
nginx.ingress.kubernetes.io/configuration-snippet: |
auth_request_set $name_upstream_1 $upstream_cookie_name_1;
access_by_lua_block {
if ngx.var.name_upstream_1 ~= "" then
ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)")
end
}
```
It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure).
You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=".
:::note
If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated.
:::

View File

@ -0,0 +1,67 @@
---
id: session_storage
title: Session Storage
---
Sessions allow a user's authentication to be tracked between multiple HTTP
requests to a service.
The OAuth2 Proxy uses a Cookie to track user sessions and will store the session
data in one of the available session storage backends.
At present the available backends are (as passed to `--session-store-type`):
- [cookie](#cookie-storage) (default)
- [redis](#redis-storage)
### Cookie Storage
The Cookie storage backend is the default backend implementation and has
been used in the OAuth2 Proxy historically.
With the Cookie storage backend, all session information is stored in client
side cookies and transferred with each and every request.
The following should be known when using this implementation:
- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless
- Cookies are signed server side to prevent modification client-side
- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data.
- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation
cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force
users to re-authenticate
### Redis Storage
The Redis Storage backend stores sessions, encrypted, in redis. Instead sending all the information
back the the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back
to the user as the cookie value instead.
A ticket is composed as the following:
`{CookieName}-{ticketID}.{secret}`
Where:
- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default)
- The `ticketID` is a 128 bit random number, hex-encoded
- The `secret` is a 128 bit random number, base64url encoded (no padding). The secret is unique for every session.
- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key
to which the session is stored. The encoded session is encrypted with the secret and stored
in redis via the `SETEX` command.
Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from
disclosure.
#### Usage
When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via
`--redis-connection-url=redis://host[:port][/db-number]`.
You may also configure the store for Redis Sentinel. In this case, you will want to use the
`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name`
and `--redis-sentinel-connection-urls` appropriately.
Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the
`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately.
Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive.

View File

@ -0,0 +1,70 @@
---
id: tls
title: TLS Configuration
---
There are two recommended configurations.
1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`.
The command line to run `oauth2-proxy` in this configuration would look like this:
```bash
./oauth2-proxy \
--email-domain="yourcompany.com" \
--upstream=http://127.0.0.1:8080/ \
--tls-cert-file=/path/to/cert.pem \
--tls-key-file=/path/to/cert.key \
--cookie-secret=... \
--cookie-secure=true \
--provider=... \
--client-id=... \
--client-secret=...
```
2. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ....
Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an
external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or
`--http-address="http://:4180"`.
Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`.
`oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example
would be `https://internal.yourcompany.com/`.
An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL
via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security):
```
server {
listen 443 default ssl;
server_name internal.yourcompany.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/cert.key;
add_header Strict-Transport-Security max-age=2592000;
location / {
proxy_pass http://127.0.0.1:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 1;
proxy_send_timeout 30;
proxy_read_timeout 30;
}
}
```
The command line to run `oauth2-proxy` in this configuration would look like this:
```bash
./oauth2-proxy \
--email-domain="yourcompany.com" \
--upstream=http://127.0.0.1:8080/ \
--cookie-secret=... \
--cookie-secure=true \
--provider=... \
--reverse-proxy=true \
--client-id=... \
--client-secret=...
```

View File

@ -0,0 +1,35 @@
---
id: endpoints
title: Endpoints
---
OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable.
- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info
- /ping - returns a 200 OK response, which is intended for use with health checks
- /oauth2/sign_in - the login page, which also doubles as a sign out page (it clears cookies)
- /oauth2/sign_out - this URL is used to clear the session cookie
- /oauth2/start - a URL that will redirect to start the OAuth cycle
- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url.
- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format.
- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/overview.md#configuring-for-use-with-the-nginx-auth_request-directive)
### Sign out
To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign out page afterwards using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!):
```
/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page
```
Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header:
```
GET /oauth2/sign_out HTTP/1.1
X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page
...
```
(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.)
BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored.

View File

@ -0,0 +1,20 @@
---
id: request_signatures
title: Request Signatures
---
If `signature_key` is defined, proxied requests will be signed with the
`GAP-Signature` header, which is a [Hash-based Message Authentication Code
(HMAC)](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)
of selected request information and the request body [see `SIGNATURE_HEADERS`
in `oauthproxy.go`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/oauthproxy.go).
`signature_key` must be of the form `algorithm:secretkey`, (ie: `signature_key = "sha1:secret0"`)
For more information about HMAC request signature validation, read the
following:
- [Amazon Web Services: Signing and Authenticating REST
Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html)
- [rc3.org: Using HMAC to authenticate Web service
requests](http://rc3.org/2011/12/02/using-hmac-to-authenticate-web-service-requests/)

View File

@ -0,0 +1,24 @@
---
id: installation
title: Installation
slug: /
---
1. Choose how to deploy:
a. Download [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v6.1.1`)
b. Build with `$ go get github.com/oauth2-proxy/oauth2-proxy` which will put the binary in `$GOPATH/bin`
c. Using the prebuilt docker image [quay.io/oauth2-proxy/oauth2-proxy](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, ARMv6 and ARM64 tags available)
Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`.
```
$ sha256sum -c sha256sum.txt 2>&1 | grep OK
oauth2-proxy-x.y.z.linux-amd64: OK
```
2. [Select a Provider and Register an OAuth Application with a Provider](configuration/auth.md)
3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md)
4. [Configure SSL or Deploy behind a SSL endpoint](configuration/tls.md) (example provided for Nginx)

View File

@ -0,0 +1,50 @@
{
"version-6.1.x/docs": [
{
"type": "doc",
"id": "version-6.1.x/installation"
},
{
"type": "doc",
"id": "version-6.1.x/behaviour"
},
{
"collapsed": false,
"type": "category",
"label": "Configuration",
"items": [
{
"type": "doc",
"id": "version-6.1.x/configuration/overview"
},
{
"type": "doc",
"id": "version-6.1.x/configuration/oauth_provider"
},
{
"type": "doc",
"id": "version-6.1.x/configuration/session_storage"
},
{
"type": "doc",
"id": "version-6.1.x/configuration/tls"
}
]
},
{
"collapsed": false,
"type": "category",
"label": "Features",
"items": [
{
"type": "doc",
"id": "version-6.1.x/features/endpoints"
},
{
"type": "doc",
"id": "version-6.1.x/features/request_signatures"
}
]
}
]
}

3
docs/versions.json Normal file
View File

@ -0,0 +1,3 @@
[
"6.1.x"
]

8
go.mod
View File

@ -11,6 +11,7 @@ require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/frankban/quicktest v1.10.0 // indirect
github.com/fsnotify/fsnotify v1.4.9
github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32
github.com/go-redis/redis/v8 v8.2.3
github.com/justinas/alice v1.2.0
github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa
@ -19,15 +20,16 @@ require (
github.com/onsi/gomega v1.10.2
github.com/pierrec/lz4 v2.5.2+incompatible
github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect
github.com/spf13/pflag v1.0.3
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.6.3
github.com/stretchr/testify v1.6.1
github.com/vmihailenco/msgpack/v4 v4.3.11
github.com/yhat/wsutil v0.0.0-20170731153501-1d66fa95c997
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/net v0.0.0-20200707034311-ab3426394381
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
google.golang.org/api v0.20.0
gopkg.in/natefinch/lumberjack.v2 v2.0.0
gopkg.in/square/go-jose.v2 v2.4.1
k8s.io/apimachinery v0.19.3
)

72
go.sum
View File

@ -8,7 +8,10 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc=
github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
@ -48,36 +51,55 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM=
github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE=
github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc=
github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/frankban/quicktest v1.10.0 h1:Gfh+GAJZOAoKZsIZeZbdn2JF10kN1XHNvjsvQK8gVkE=
github.com/frankban/quicktest v1.10.0/go.mod h1:ui7WezCLWMWxVWr1GETZY3smRy0G4KWq9vcPtJmFl7Y=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32 h1:Mn26/9ZMNWSw9C9ERFA1PUxfmGpolnw2v0bKOREu5ew=
github.com/ghodss/yaml v1.0.1-0.20190212211648-25d852aebe32/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas=
github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU=
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/go-redis/redis/v8 v8.2.3 h1:eNesND+DWt/sjQOtPFxAbQkTIXaXX00qNLxjVWkZ70k=
github.com/go-redis/redis/v8 v8.2.3/go.mod h1:ysgGY09J/QeDYbu3HikWEIPCwaeOkuNoTgKayTEaEOw=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
@ -92,6 +114,7 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k=
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
@ -99,6 +122,7 @@ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
@ -112,7 +136,9 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
@ -120,6 +146,7 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V
github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
@ -131,6 +158,7 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A=
github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
@ -139,16 +167,23 @@ github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa/go.mod h1:8vxFeeg+
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.14.1 h1:jMU0WaQrP0a/YAEq8eJmJKjBoMs+pClEr1vDMlM/Do4=
github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.10.2 h1:aY/nuoWlKJud2J6U0E3NWsjlg+0GtwXxgEqthRdzlcs=
@ -158,6 +193,7 @@ github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/9
github.com/pierrec/lz4 v2.5.2+incompatible h1:WCjObylUIOlKy/+7Abdn34TLIkXiA4UWUMhxq9m9ZXI=
github.com/pierrec/lz4 v2.5.2+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 h1:J9b7z+QKAmPf4YLrFg6oQUotqHQeUNWwkvo7jZp1GLU=
@ -186,14 +222,18 @@ github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.6.3 h1:pDDu1OyEDTKzpJwdq4TiuLyMsUgRa/BT5cn5O62NoHs=
github.com/spf13/viper v1.6.3/go.mod h1:jUMtyi0/lB5yZH/FjyGAoH7IMNrIhlBf6pXZmbMDvzw=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
@ -223,6 +263,8 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
@ -237,12 +279,16 @@ golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7 h1:AeiKBIuRw3UomYXSbLy0Mc2dDLfdtbT/IVn4keq83P0=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200707034311-ab3426394381 h1:VXak5I6aEWmAXeQjA+QSZzlgNrpq9mjcfDemuexIKsU=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@ -260,6 +306,7 @@ golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@ -267,14 +314,20 @@ golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 h1:DYfZAGf2WMFjMxbgTjaC+2HC7NkNAQs+6Q8b9WEB/F4=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4 h1:5/PjkGUjvEU5Gl6BxmvKRPpqo2uNMv4rcHBMwzk/st8=
golang.org/x/sys v0.0.0-20200622214017-ed371f2e16b4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
@ -296,6 +349,8 @@ google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRn
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
@ -306,13 +361,20 @@ google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.24.0 h1:UhZDfRO8JRQru4/+LlLE0BRKGF8L+PICnvYZmx/fEGA=
google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
@ -326,6 +388,7 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
@ -333,3 +396,12 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
k8s.io/apimachinery v0.19.3 h1:bpIQXlKjB4cB/oNpnNnV+BybGPR7iP5oYpsOTEJ4hgc=
k8s.io/apimachinery v0.19.3/go.mod h1:DnPGDnARWFvYa3pMHgSxtbZb7gpzzAZ1pTfaUNDVlmA=
k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0=
k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE=
k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y=
k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o=
sigs.k8s.io/structured-merge-diff/v4 v4.0.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc=

View File

@ -64,7 +64,7 @@ func (s *Server) ServeHTTPS() {
addr := s.Opts.HTTPSAddress
config := &tls.Config{
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS13,
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}

153
main.go
View File

@ -3,49 +3,49 @@ package main
import (
"fmt"
"math/rand"
"net"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/justinas/alice"
"github.com/ghodss/yaml"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/middleware"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation"
"github.com/spf13/pflag"
)
func main() {
logger.SetFlags(logger.Lshortfile)
flagSet := options.NewFlagSet()
config := flagSet.String("config", "", "path to config file")
showVersion := flagSet.Bool("version", false, "print version string")
err := flagSet.Parse(os.Args[1:])
if err != nil {
logger.Printf("ERROR: Failed to parse flags: %v", err)
os.Exit(1)
}
configFlagSet := pflag.NewFlagSet("oauth2-proxy", pflag.ContinueOnError)
config := configFlagSet.String("config", "", "path to config file")
alphaConfig := configFlagSet.String("alpha-config", "", "path to alpha config file (use at your own risk - the structure in this config file may change between minor releases)")
convertConfig := configFlagSet.Bool("convert-config-to-alpha", false, "if true, the proxy will load configuration as normal and convert existing configuration to the alpha config structure, and print it to stdout")
showVersion := configFlagSet.Bool("version", false, "print version string")
configFlagSet.Parse(os.Args[1:])
if *showVersion {
fmt.Printf("oauth2-proxy %s (built with %s)\n", VERSION, runtime.Version())
return
}
legacyOpts := options.NewLegacyOptions()
err = options.Load(*config, flagSet, legacyOpts)
if *convertConfig && *alphaConfig != "" {
logger.Fatal("cannot use alpha-config and conver-config-to-alpha together")
}
opts, err := loadConfiguration(*config, *alphaConfig, configFlagSet, os.Args[1:])
if err != nil {
logger.Errorf("ERROR: Failed to load config: %v", err)
logger.Printf("ERROR: %v", err)
os.Exit(1)
}
opts, err := legacyOpts.ToOptions()
if err != nil {
logger.Errorf("ERROR: Failed to convert config: %v", err)
os.Exit(1)
if *convertConfig {
if err := printConvertedConfig(opts); err != nil {
logger.Fatalf("ERROR: could not convert config: %v", err)
}
return
}
err = validation.Validate(opts)
@ -63,33 +63,8 @@ func main() {
rand.Seed(time.Now().UnixNano())
chain := alice.New()
if opts.ForceHTTPS {
_, httpsPort, err := net.SplitHostPort(opts.HTTPSAddress)
if err != nil {
logger.Fatalf("FATAL: invalid HTTPS address %q: %v", opts.HTTPAddress, err)
}
chain = chain.Append(middleware.NewRedirectToHTTPS(httpsPort))
}
healthCheckPaths := []string{opts.PingPath}
healthCheckUserAgents := []string{opts.PingUserAgent}
if opts.GCPHealthChecks {
healthCheckPaths = append(healthCheckPaths, "/liveness_check", "/readiness_check")
healthCheckUserAgents = append(healthCheckUserAgents, "GoogleHC/1.0")
}
// To silence logging of health checks, register the health check handler before
// the logging handler
if opts.Logging.SilencePing {
chain = chain.Append(middleware.NewHealthCheck(healthCheckPaths, healthCheckUserAgents), LoggingHandler)
} else {
chain = chain.Append(LoggingHandler, middleware.NewHealthCheck(healthCheckPaths, healthCheckUserAgents))
}
s := &Server{
Handler: chain.Then(oauthproxy),
Handler: oauthproxy,
Opts: opts,
stop: make(chan struct{}, 1),
}
@ -102,3 +77,91 @@ func main() {
}()
s.ListenAndServe()
}
// loadConfiguration will load in the user's configuration.
// It will either load the alpha configuration (if alphaConfig is given)
// or the legacy configuration.
func loadConfiguration(config, alphaConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) {
if alphaConfig != "" {
logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.")
return loadAlphaOptions(config, alphaConfig, extraFlags, args)
}
return loadLegacyOptions(config, extraFlags, args)
}
// loadLegacyOptions loads the old toml options using the legacy flagset
// and legacy options struct.
func loadLegacyOptions(config string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) {
optionsFlagSet := options.NewLegacyFlagSet()
optionsFlagSet.AddFlagSet(extraFlags)
if err := optionsFlagSet.Parse(args); err != nil {
return nil, fmt.Errorf("failed to parse flags: %v", err)
}
legacyOpts := options.NewLegacyOptions()
if err := options.Load(config, optionsFlagSet, legacyOpts); err != nil {
return nil, fmt.Errorf("failed to load config: %v", err)
}
opts, err := legacyOpts.ToOptions()
if err != nil {
return nil, fmt.Errorf("failed to convert config: %v", err)
}
return opts, nil
}
// loadAlphaOptions loads the old style config excluding options converted to
// the new alpha format, then merges the alpha options, loaded from YAML,
// into the core configuration.
func loadAlphaOptions(config, alphaConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) {
opts, err := loadOptions(config, extraFlags, args)
if err != nil {
return nil, fmt.Errorf("failed to load core options: %v", err)
}
alphaOpts := &options.AlphaOptions{}
if err := options.LoadYAML(alphaConfig, alphaOpts); err != nil {
return nil, fmt.Errorf("failed to load alpha options: %v", err)
}
alphaOpts.MergeInto(opts)
return opts, nil
}
// loadOptions loads the configuration using the old style format into the
// core options.Options struct.
// This means that none of the options that have been converted to alpha config
// will be loaded using this method.
func loadOptions(config string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) {
optionsFlagSet := options.NewFlagSet()
optionsFlagSet.AddFlagSet(extraFlags)
if err := optionsFlagSet.Parse(args); err != nil {
return nil, fmt.Errorf("failed to parse flags: %v", err)
}
opts := options.NewOptions()
if err := options.Load(config, optionsFlagSet, opts); err != nil {
return nil, fmt.Errorf("failed to load config: %v", err)
}
return opts, nil
}
// printConvertedConfig extracts alpha options from the loaded configuration
// and renders these to stdout in YAML format.
func printConvertedConfig(opts *options.Options) error {
alphaConfig := &options.AlphaOptions{}
alphaConfig.ExtractFrom(opts)
data, err := yaml.Marshal(alphaConfig)
if err != nil {
return fmt.Errorf("unable to marshal config: %v", err)
}
if _, err := os.Stdout.Write(data); err != nil {
return fmt.Errorf("unable to write output: %v", err)
}
return nil
}

16
main_suite_test.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"testing"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestMainSuite(t *testing.T) {
logger.SetOutput(GinkgoWriter)
RegisterFailHandler(Fail)
RunSpecs(t, "Main Suite")
}

215
main_test.go Normal file
View File

@ -0,0 +1,215 @@
package main
import (
"errors"
"io/ioutil"
"os"
"time"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
"github.com/spf13/pflag"
)
var _ = Describe("Configuration Loading Suite", func() {
const testLegacyConfig = `
upstreams="http://httpbin"
set_basic_auth="true"
basic_auth_password="super-secret-password"
`
const testAlphaConfig = `
upstreams:
- id: /
path: /
uri: http://httpbin
flushInterval: 1s
passHostHeader: true
proxyWebSockets: true
injectRequestHeaders:
- name: Authorization
values:
- claim: user
prefix: "Basic "
basicAuthPassword:
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk
- name: X-Forwarded-Groups
values:
- claim: groups
- name: X-Forwarded-User
values:
- claim: user
- name: X-Forwarded-Email
values:
- claim: email
- name: X-Forwarded-Preferred-Username
values:
- claim: preferred_username
injectResponseHeaders:
- name: Authorization
values:
- claim: user
prefix: "Basic "
basicAuthPassword:
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk
`
const testCoreConfig = `
http_address="0.0.0.0:4180"
cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
provider="oidc"
email_domains="example.com"
oidc_issuer_url="http://dex.localhost:4190/dex"
client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
client_id="oauth2-proxy"
cookie_secure="false"
redirect_url="http://localhost:4180/oauth2/callback"
`
boolPtr := func(b bool) *bool {
return &b
}
durationPtr := func(d time.Duration) *options.Duration {
du := options.Duration(d)
return &du
}
testExpectedOptions := func() *options.Options {
opts, err := options.NewLegacyOptions().ToOptions()
Expect(err).ToNot(HaveOccurred())
opts.HTTPAddress = "0.0.0.0:4180"
opts.Cookie.Secret = "OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
opts.ProviderType = "oidc"
opts.EmailDomains = []string{"example.com"}
opts.OIDCIssuerURL = "http://dex.localhost:4190/dex"
opts.ClientSecret = "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
opts.ClientID = "oauth2-proxy"
opts.Cookie.Secure = false
opts.RawRedirectURL = "http://localhost:4180/oauth2/callback"
opts.UpstreamServers = options.Upstreams{
{
ID: "/",
Path: "/",
URI: "http://httpbin",
FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval),
PassHostHeader: boolPtr(true),
ProxyWebSockets: boolPtr(true),
},
}
authHeader := options.Header{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
Prefix: "Basic ",
BasicAuthPassword: &options.SecretSource{
Value: []byte("super-secret-password"),
},
},
},
},
}
opts.InjectRequestHeaders = append([]options.Header{authHeader}, opts.InjectRequestHeaders...)
opts.InjectResponseHeaders = append(opts.InjectResponseHeaders, authHeader)
return opts
}
type loadConfigurationTableInput struct {
configContent string
alphaConfigContent string
args []string
extraFlags func() *pflag.FlagSet
expectedOptions func() *options.Options
expectedErr error
}
DescribeTable("LoadConfiguration",
func(in loadConfigurationTableInput) {
var configFileName, alphaConfigFileName string
defer func() {
if configFileName != "" {
Expect(os.Remove(configFileName)).To(Succeed())
}
if alphaConfigFileName != "" {
Expect(os.Remove(alphaConfigFileName)).To(Succeed())
}
}()
if in.configContent != "" {
By("Writing the config to a temporary file", func() {
file, err := ioutil.TempFile("", "oauth2-proxy-test-config-XXXX.cfg")
Expect(err).ToNot(HaveOccurred())
defer file.Close()
configFileName = file.Name()
_, err = file.WriteString(in.configContent)
Expect(err).ToNot(HaveOccurred())
})
}
if in.alphaConfigContent != "" {
By("Writing the config to a temporary file", func() {
file, err := ioutil.TempFile("", "oauth2-proxy-test-alpha-config-XXXX.yaml")
Expect(err).ToNot(HaveOccurred())
defer file.Close()
alphaConfigFileName = file.Name()
_, err = file.WriteString(in.alphaConfigContent)
Expect(err).ToNot(HaveOccurred())
})
}
extraFlags := pflag.NewFlagSet("test-flagset", pflag.ExitOnError)
if in.extraFlags != nil {
extraFlags = in.extraFlags()
}
opts, err := loadConfiguration(configFileName, alphaConfigFileName, extraFlags, in.args)
if in.expectedErr != nil {
Expect(err).To(MatchError(in.expectedErr.Error()))
} else {
Expect(err).ToNot(HaveOccurred())
}
Expect(in.expectedOptions).ToNot(BeNil())
Expect(opts).To(Equal(in.expectedOptions()))
},
Entry("with legacy configuration", loadConfigurationTableInput{
configContent: testCoreConfig + testLegacyConfig,
expectedOptions: testExpectedOptions,
}),
Entry("with alpha configuration", loadConfigurationTableInput{
configContent: testCoreConfig,
alphaConfigContent: testAlphaConfig,
expectedOptions: testExpectedOptions,
}),
Entry("with bad legacy configuration", loadConfigurationTableInput{
configContent: testCoreConfig + "unknown_field=\"something\"",
expectedOptions: func() *options.Options { return nil },
expectedErr: errors.New("failed to load config: error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_field"),
}),
Entry("with bad alpha configuration", loadConfigurationTableInput{
configContent: testCoreConfig,
alphaConfigContent: testAlphaConfig + ":",
expectedOptions: func() *options.Options { return nil },
expectedErr: errors.New("failed to load alpha options: error unmarshalling config: error converting YAML to JSON: yaml: line 34: did not find expected key"),
}),
Entry("with alpha configuration and bad core configuration", loadConfigurationTableInput{
configContent: testCoreConfig + "unknown_field=\"something\"",
alphaConfigContent: testAlphaConfig,
expectedOptions: func() *options.Options { return nil },
expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_field"),
}),
)
})

View File

@ -2,7 +2,6 @@ package main
import (
"context"
b64 "encoding/base64"
"encoding/json"
"errors"
"fmt"
@ -14,7 +13,6 @@ import (
"strings"
"time"
"github.com/coreos/go-oidc"
"github.com/justinas/alice"
ipapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/ip"
middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
@ -43,6 +41,9 @@ var (
// ErrNeedsLogin means the user should be redirected to the login page
ErrNeedsLogin = errors.New("redirect to login page")
// ErrAccessDenied means the user should receive a 401 Unauthorized response
ErrAccessDenied = errors.New("access denied")
// Used to check final redirects are not susceptible to open redirects.
// Matches //, /\ and both of these with whitespace in between (eg / / or / \).
invalidRedirectRegex = regexp.MustCompile(`[/\\](?:[\s\v]*|\.{1,2})[/\\]`)
@ -98,18 +99,16 @@ type OAuthProxy struct {
PassAuthorization bool
PreferEmailToUser bool
skipAuthPreflight bool
skipAuthStripHeaders bool
skipJwtBearerTokens bool
mainJwtBearerVerifier *oidc.IDTokenVerifier
extraJwtBearerVerifiers []*oidc.IDTokenVerifier
templates *template.Template
realClientIPParser ipapi.RealClientIPParser
trustedIPs *ip.NetSet
Banner string
Footer string
AllowedGroups []string
sessionChain alice.Chain
headersChain alice.Chain
preAuthChain alice.Chain
}
// NewOAuthProxy creates a new instance of OAuthProxy from the options provided
@ -169,7 +168,15 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
return nil, err
}
preAuthChain, err := buildPreAuthChain(opts)
if err != nil {
return nil, fmt.Errorf("could not build pre-auth chain: %v", err)
}
sessionChain := buildSessionChain(opts, sessionStore, basicAuthValidator)
headersChain, err := buildHeadersChain(opts)
if err != nil {
return nil, fmt.Errorf("could not build headers chain: %v", err)
}
return &OAuthProxy{
CookieName: opts.Cookie.Name,
@ -201,50 +208,66 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
allowedRoutes: allowedRoutes,
whitelistDomains: opts.WhitelistDomains,
skipAuthPreflight: opts.SkipAuthPreflight,
skipAuthStripHeaders: opts.SkipAuthStripHeaders,
skipJwtBearerTokens: opts.SkipJwtBearerTokens,
mainJwtBearerVerifier: opts.GetOIDCVerifier(),
extraJwtBearerVerifiers: opts.GetJWTBearerVerifiers(),
realClientIPParser: opts.GetRealClientIPParser(),
SetXAuthRequest: opts.SetXAuthRequest,
PassBasicAuth: opts.PassBasicAuth,
SetBasicAuth: opts.SetBasicAuth,
PassUserHeaders: opts.PassUserHeaders,
BasicAuthPassword: opts.BasicAuthPassword,
PassAccessToken: opts.PassAccessToken,
SetAuthorization: opts.SetAuthorization,
PassAuthorization: opts.PassAuthorization,
PreferEmailToUser: opts.PreferEmailToUser,
SkipProviderButton: opts.SkipProviderButton,
templates: templates,
trustedIPs: trustedIPs,
Banner: opts.Banner,
Footer: opts.Footer,
SignInMessage: buildSignInMessage(opts),
AllowedGroups: opts.AllowedGroups,
basicAuthValidator: basicAuthValidator,
displayHtpasswdForm: basicAuthValidator != nil,
displayHtpasswdForm: basicAuthValidator != nil && opts.DisplayHtpasswdForm,
sessionChain: sessionChain,
headersChain: headersChain,
preAuthChain: preAuthChain,
}, nil
}
func buildSessionChain(opts *options.Options, sessionStore sessionsapi.SessionStore, validator basic.Validator) alice.Chain {
// buildPreAuthChain constructs a chain that should process every request before
// the OAuth2 Proxy authentication logic kicks in.
// For example forcing HTTPS or health checks.
func buildPreAuthChain(opts *options.Options) (alice.Chain, error) {
chain := alice.New(middleware.NewScope())
if opts.ForceHTTPS {
_, httpsPort, err := net.SplitHostPort(opts.HTTPSAddress)
if err != nil {
return alice.Chain{}, fmt.Errorf("invalid HTTPS address %q: %v", opts.HTTPAddress, err)
}
chain = chain.Append(middleware.NewRedirectToHTTPS(httpsPort))
}
healthCheckPaths := []string{opts.PingPath}
healthCheckUserAgents := []string{opts.PingUserAgent}
if opts.GCPHealthChecks {
healthCheckPaths = append(healthCheckPaths, "/liveness_check", "/readiness_check")
healthCheckUserAgents = append(healthCheckUserAgents, "GoogleHC/1.0")
}
// To silence logging of health checks, register the health check handler before
// the logging handler
if opts.Logging.SilencePing {
chain = chain.Append(middleware.NewHealthCheck(healthCheckPaths, healthCheckUserAgents), LoggingHandler)
} else {
chain = chain.Append(LoggingHandler, middleware.NewHealthCheck(healthCheckPaths, healthCheckUserAgents))
}
return chain, nil
}
func buildSessionChain(opts *options.Options, sessionStore sessionsapi.SessionStore, validator basic.Validator) alice.Chain {
chain := alice.New()
if opts.SkipJwtBearerTokens {
sessionLoaders := []middlewareapi.TokenToSessionLoader{}
if opts.GetOIDCVerifier() != nil {
sessionLoaders = append(sessionLoaders, middlewareapi.TokenToSessionLoader{
Verifier: opts.GetOIDCVerifier(),
TokenToSession: opts.GetProvider().CreateSessionStateFromBearerToken,
})
sessionLoaders := []middlewareapi.TokenToSessionFunc{
opts.GetProvider().CreateSessionFromToken,
}
for _, verifier := range opts.GetJWTBearerVerifiers() {
sessionLoaders = append(sessionLoaders, middlewareapi.TokenToSessionLoader{
Verifier: verifier,
})
sessionLoaders = append(sessionLoaders,
middlewareapi.CreateTokenToSessionFunc(verifier.Verify))
}
chain = chain.Append(middleware.NewJwtSessionLoader(sessionLoaders))
@ -258,12 +281,26 @@ func buildSessionChain(opts *options.Options, sessionStore sessionsapi.SessionSt
SessionStore: sessionStore,
RefreshPeriod: opts.Cookie.Refresh,
RefreshSessionIfNeeded: opts.GetProvider().RefreshSessionIfNeeded,
ValidateSessionState: opts.GetProvider().ValidateSessionState,
ValidateSessionState: opts.GetProvider().ValidateSession,
}))
return chain
}
func buildHeadersChain(opts *options.Options) (alice.Chain, error) {
requestInjector, err := middleware.NewRequestHeaderInjector(opts.InjectRequestHeaders)
if err != nil {
return alice.Chain{}, fmt.Errorf("error constructing request header injector: %v", err)
}
responseInjector, err := middleware.NewResponseHeaderInjector(opts.InjectResponseHeaders)
if err != nil {
return alice.Chain{}, fmt.Errorf("error constructing request header injector: %v", err)
}
return alice.New(requestInjector, responseInjector), nil
}
func buildSignInMessage(opts *options.Options) string {
var msg string
if len(opts.Banner) >= 1 {
@ -350,7 +387,7 @@ func (p *OAuthProxy) GetRedirectURI(host string) string {
func (p *OAuthProxy) redeemCode(ctx context.Context, host, code string) (*sessionsapi.SessionState, error) {
if code == "" {
return nil, errors.New("missing code")
return nil, providers.ErrMissingCode
}
redirectURI := p.GetRedirectURI(host)
s, err := p.provider.Redeem(ctx, redirectURI, code)
@ -369,7 +406,7 @@ func (p *OAuthProxy) enrichSessionState(ctx context.Context, s *sessionsapi.Sess
}
}
return p.provider.EnrichSessionState(ctx, s)
return p.provider.EnrichSession(ctx, s)
}
// MakeCSRFCookie creates a cookie for CSRF
@ -685,6 +722,10 @@ func (p *OAuthProxy) IsTrustedIP(req *http.Request) bool {
}
func (p *OAuthProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
p.preAuthChain.Then(http.HandlerFunc(p.serveHTTP)).ServeHTTP(rw, req)
}
func (p *OAuthProxy) serveHTTP(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path != p.AuthOnlyPath && strings.HasPrefix(req.URL.Path, p.ProxyPrefix) {
prepareNoCache(rw)
}
@ -747,13 +788,19 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
userInfo := struct {
User string `json:"user"`
Email string `json:"email"`
Groups []string `json:"groups,omitempty"`
PreferredUsername string `json:"preferredUsername,omitempty"`
}{
User: session.User,
Email: session.Email,
Groups: session.Groups,
PreferredUsername: session.PreferredUsername,
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
err = json.NewEncoder(rw).Encode(userInfo)
@ -859,11 +906,15 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
}
// set cookie, or deny
if p.Validator(session.Email) && p.provider.ValidateGroup(session.Email) {
authorized, err := p.provider.Authorize(req.Context(), session)
if err != nil {
logger.Errorf("Error with authorization: %v", err)
}
if p.Validator(session.Email) && authorized {
logger.PrintAuthf(session.Email, req, logger.AuthSuccess, "Authenticated via OAuth2: %s", session)
err := p.SaveSession(rw, req, session)
if err != nil {
logger.Printf("Error saving session state for %s: %v", remoteAddr, err)
logger.Errorf("Error saving session state for %s: %v", remoteAddr, err)
p.ErrorPage(rw, http.StatusInternalServerError, "Internal Server Error", err.Error())
return
}
@ -884,15 +935,14 @@ func (p *OAuthProxy) AuthenticateOnly(rw http.ResponseWriter, req *http.Request)
// we are authenticated
p.addHeadersForProxying(rw, req, session)
p.headersChain.Then(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusAccepted)
})).ServeHTTP(rw, req)
}
// SkipAuthProxy proxies allowlisted requests and skips authentication
func (p *OAuthProxy) SkipAuthProxy(rw http.ResponseWriter, req *http.Request) {
if p.skipAuthStripHeaders {
p.stripAuthHeaders(req)
}
p.serveMux.ServeHTTP(rw, req)
p.headersChain.Then(p.serveMux).ServeHTTP(rw, req)
}
// Proxy proxies the user request if the user is authenticated else it prompts
@ -903,8 +953,7 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
case nil:
// we are authenticated
p.addHeadersForProxying(rw, req, session)
p.serveMux.ServeHTTP(rw, req)
p.headersChain.Then(p.serveMux).ServeHTTP(rw, req)
case ErrNeedsLogin:
// we need to send the user to a login screen
if isAjax(req) {
@ -919,6 +968,9 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
p.SignInPage(rw, req, http.StatusForbidden)
}
case ErrAccessDenied:
p.ErrorPage(rw, http.StatusUnauthorized, "Permission Denied", "Unauthorized")
default:
// unknown error
logger.Errorf("Unexpected internal error: %v", err)
@ -929,7 +981,9 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
}
// getAuthenticatedSession checks whether a user is authenticated and returns a session object and nil error if so
// Returns nil, ErrNeedsLogin if user needs to login.
// Returns:
// - `nil, ErrNeedsLogin` if user needs to login.
// - `nil, ErrAccessDenied` if the authenticated user is not authorized
// Set-Cookie headers may be set on the response as a side-effect of calling this method.
func (p *OAuthProxy) getAuthenticatedSession(rw http.ResponseWriter, req *http.Request) (*sessionsapi.SessionState, error) {
var session *sessionsapi.SessionState
@ -943,17 +997,20 @@ func (p *OAuthProxy) getAuthenticatedSession(rw http.ResponseWriter, req *http.R
return nil, ErrNeedsLogin
}
invalidEmail := session != nil && session.Email != "" && !p.Validator(session.Email)
invalidGroups := session != nil && !p.validateGroups(session.Groups)
invalidEmail := session.Email != "" && !p.Validator(session.Email)
authorized, err := p.provider.Authorize(req.Context(), session)
if err != nil {
logger.Errorf("Error with authorization: %v", err)
}
if invalidEmail || invalidGroups {
logger.Printf(session.Email, req, logger.AuthFailure, "Invalid authentication via session: removing session %s", session)
if invalidEmail || !authorized {
logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authorization via session: removing session %s", session)
// Invalid session, clear it
err := p.ClearSessionCookie(rw, req)
if err != nil {
logger.Printf("Error clearing session cookie: %v", err)
logger.Errorf("Error clearing session cookie: %v", err)
}
return nil, ErrNeedsLogin
return nil, ErrAccessDenied
}
return session, nil
@ -961,120 +1018,6 @@ func (p *OAuthProxy) getAuthenticatedSession(rw http.ResponseWriter, req *http.R
// addHeadersForProxying adds the appropriate headers the request / response for proxying
func (p *OAuthProxy) addHeadersForProxying(rw http.ResponseWriter, req *http.Request, session *sessionsapi.SessionState) {
if p.PassBasicAuth {
if p.PreferEmailToUser && session.Email != "" {
req.SetBasicAuth(session.Email, p.BasicAuthPassword)
req.Header["X-Forwarded-User"] = []string{session.Email}
req.Header.Del("X-Forwarded-Email")
} else {
req.SetBasicAuth(session.User, p.BasicAuthPassword)
req.Header["X-Forwarded-User"] = []string{session.User}
if session.Email != "" {
req.Header["X-Forwarded-Email"] = []string{session.Email}
} else {
req.Header.Del("X-Forwarded-Email")
}
}
if session.PreferredUsername != "" {
req.Header["X-Forwarded-Preferred-Username"] = []string{session.PreferredUsername}
} else {
req.Header.Del("X-Forwarded-Preferred-Username")
}
}
if p.PassUserHeaders {
if p.PreferEmailToUser && session.Email != "" {
req.Header["X-Forwarded-User"] = []string{session.Email}
req.Header.Del("X-Forwarded-Email")
} else {
req.Header["X-Forwarded-User"] = []string{session.User}
if session.Email != "" {
req.Header["X-Forwarded-Email"] = []string{session.Email}
} else {
req.Header.Del("X-Forwarded-Email")
}
}
if session.PreferredUsername != "" {
req.Header["X-Forwarded-Preferred-Username"] = []string{session.PreferredUsername}
} else {
req.Header.Del("X-Forwarded-Preferred-Username")
}
if len(session.Groups) > 0 {
for _, group := range session.Groups {
req.Header.Add("X-Forwarded-Groups", group)
}
} else {
req.Header.Del("X-Forwarded-Groups")
}
}
if p.SetXAuthRequest {
rw.Header().Set("X-Auth-Request-User", session.User)
if session.Email != "" {
rw.Header().Set("X-Auth-Request-Email", session.Email)
} else {
rw.Header().Del("X-Auth-Request-Email")
}
if session.PreferredUsername != "" {
rw.Header().Set("X-Auth-Request-Preferred-Username", session.PreferredUsername)
} else {
rw.Header().Del("X-Auth-Request-Preferred-Username")
}
if p.PassAccessToken {
if session.AccessToken != "" {
rw.Header().Set("X-Auth-Request-Access-Token", session.AccessToken)
} else {
rw.Header().Del("X-Auth-Request-Access-Token")
}
}
if len(session.Groups) > 0 {
for _, group := range session.Groups {
rw.Header().Add("X-Auth-Request-Groups", group)
}
} else {
rw.Header().Del("X-Auth-Request-Groups")
}
}
if p.PassAccessToken {
if session.AccessToken != "" {
req.Header["X-Forwarded-Access-Token"] = []string{session.AccessToken}
} else {
req.Header.Del("X-Forwarded-Access-Token")
}
}
if p.PassAuthorization {
if session.IDToken != "" {
req.Header["Authorization"] = []string{fmt.Sprintf("Bearer %s", session.IDToken)}
} else {
req.Header.Del("Authorization")
}
}
if p.SetBasicAuth {
switch {
case p.PreferEmailToUser && session.Email != "":
authVal := b64.StdEncoding.EncodeToString([]byte(session.Email + ":" + p.BasicAuthPassword))
rw.Header().Set("Authorization", "Basic "+authVal)
case session.User != "":
authVal := b64.StdEncoding.EncodeToString([]byte(session.User + ":" + p.BasicAuthPassword))
rw.Header().Set("Authorization", "Basic "+authVal)
default:
rw.Header().Del("Authorization")
}
}
if p.SetAuthorization {
if session.IDToken != "" {
rw.Header().Set("Authorization", fmt.Sprintf("Bearer %s", session.IDToken))
} else {
rw.Header().Del("Authorization")
}
}
if session.Email == "" {
rw.Header().Set("GAP-Auth", session.User)
} else {
@ -1082,32 +1025,6 @@ func (p *OAuthProxy) addHeadersForProxying(rw http.ResponseWriter, req *http.Req
}
}
// stripAuthHeaders removes Auth headers for allowlisted routes from skipAuthRegex
func (p *OAuthProxy) stripAuthHeaders(req *http.Request) {
if p.PassBasicAuth {
req.Header.Del("X-Forwarded-User")
req.Header.Del("X-Forwarded-Groups")
req.Header.Del("X-Forwarded-Email")
req.Header.Del("X-Forwarded-Preferred-Username")
req.Header.Del("Authorization")
}
if p.PassUserHeaders {
req.Header.Del("X-Forwarded-User")
req.Header.Del("X-Forwarded-Groups")
req.Header.Del("X-Forwarded-Email")
req.Header.Del("X-Forwarded-Preferred-Username")
}
if p.PassAccessToken {
req.Header.Del("X-Forwarded-Access-Token")
}
if p.PassAuthorization {
req.Header.Del("Authorization")
}
}
// isAjax checks if a request is an ajax request
func isAjax(req *http.Request) bool {
acceptValues := req.Header.Values("Accept")
@ -1125,23 +1042,3 @@ func (p *OAuthProxy) ErrorJSON(rw http.ResponseWriter, code int) {
rw.Header().Set("Content-Type", applicationJSON)
rw.WriteHeader(code)
}
func (p *OAuthProxy) validateGroups(groups []string) bool {
if len(p.AllowedGroups) == 0 {
return true
}
allowedGroups := map[string]struct{}{}
for _, group := range p.AllowedGroups {
allowedGroups[group] = struct{}{}
}
for _, group := range groups {
if _, ok := allowedGroups[group]; ok {
return true
}
}
return false
}

View File

@ -400,7 +400,7 @@ func (tp *TestProvider) GetEmailAddress(_ context.Context, _ *sessions.SessionSt
return tp.EmailAddress, nil
}
func (tp *TestProvider) ValidateSessionState(_ context.Context, _ *sessions.SessionState) bool {
func (tp *TestProvider) ValidateSession(_ context.Context, _ *sessions.SessionState) bool {
return tp.ValidToken
}
@ -495,6 +495,8 @@ func TestBasicAuthPassword(t *testing.T) {
t.Fatal(err)
}
}))
basicAuthPassword := "This is a secure password"
opts := baseTestOptions()
opts.UpstreamServers = options.Upstreams{
{
@ -505,11 +507,22 @@ func TestBasicAuthPassword(t *testing.T) {
}
opts.Cookie.Secure = false
opts.PassBasicAuth = true
opts.SetBasicAuth = true
opts.PassUserHeaders = true
opts.PreferEmailToUser = true
opts.BasicAuthPassword = "This is a secure password"
opts.InjectRequestHeaders = []options.Header{
{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
BasicAuthPassword: &options.SecretSource{
Value: []byte(basicAuthPassword),
},
},
},
},
},
}
err := validation.Validate(opts)
assert.NoError(t, err)
@ -524,148 +537,44 @@ func TestBasicAuthPassword(t *testing.T) {
t.Fatal(err)
}
// Save the required session
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/oauth2/callback?code=callback_code&state=nonce:", strings.NewReader(""))
req.AddCookie(proxy.MakeCSRFCookie(req, "nonce", proxy.CookieExpire, time.Now()))
proxy.ServeHTTP(rw, req)
if rw.Code >= 400 {
t.Fatalf("expected 3xx got %d", rw.Code)
}
cookie := rw.Header().Values("Set-Cookie")[1]
cookieName := proxy.CookieName
var value string
keyPrefix := cookieName + "="
for _, field := range strings.Split(cookie, "; ") {
value = strings.TrimPrefix(field, keyPrefix)
if value != field {
break
} else {
value = ""
}
}
req, _ = http.NewRequest("GET", "/", strings.NewReader(""))
req.AddCookie(&http.Cookie{
Name: cookieName,
Value: value,
Path: "/",
Expires: time.Now().Add(time.Duration(24)),
HttpOnly: true,
req, _ := http.NewRequest("GET", "/", nil)
err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{
Email: emailAddress,
})
req.AddCookie(proxy.MakeCSRFCookie(req, "nonce", proxy.CookieExpire, time.Now()))
assert.NoError(t, err)
// Extract the cookie value to inject into the test request
cookie := rw.Header().Values("Set-Cookie")[0]
req, _ = http.NewRequest("GET", "/", nil)
req.Header.Set("Cookie", cookie)
rw = httptest.NewRecorder()
proxy.ServeHTTP(rw, req)
// The username in the basic auth credentials is expected to be equal to the email address from the
// auth response, so we use the same variable here.
expectedHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(emailAddress+":"+opts.BasicAuthPassword))
expectedHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(emailAddress+":"+basicAuthPassword))
assert.Equal(t, expectedHeader, rw.Body.String())
providerServer.Close()
}
func TestBasicAuthWithEmail(t *testing.T) {
opts := baseTestOptions()
opts.PassBasicAuth = true
opts.PassUserHeaders = false
opts.PreferEmailToUser = false
opts.BasicAuthPassword = "This is a secure password"
err := validation.Validate(opts)
assert.NoError(t, err)
const emailAddress = "john.doe@example.com"
const userName = "9fcab5c9b889a557"
// The username in the basic auth credentials is expected to be equal to the email address from the
expectedEmailHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(emailAddress+":"+opts.BasicAuthPassword))
expectedUserHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(userName+":"+opts.BasicAuthPassword))
created := time.Now()
session := &sessions.SessionState{
User: userName,
Email: emailAddress,
AccessToken: "oauth_token",
CreatedAt: &created,
}
{
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", opts.ProxyPrefix+"/testCase0", nil)
proxy, err := NewOAuthProxy(opts, func(email string) bool {
return email == emailAddress
})
if err != nil {
t.Fatal(err)
}
proxy.addHeadersForProxying(rw, req, session)
assert.Equal(t, expectedUserHeader, req.Header["Authorization"][0])
assert.Equal(t, userName, req.Header["X-Forwarded-User"][0])
}
opts.PreferEmailToUser = true
{
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", opts.ProxyPrefix+"/testCase1", nil)
proxy, err := NewOAuthProxy(opts, func(email string) bool {
return email == emailAddress
})
if err != nil {
t.Fatal(err)
}
proxy.addHeadersForProxying(rw, req, session)
assert.Equal(t, expectedEmailHeader, req.Header["Authorization"][0])
assert.Equal(t, emailAddress, req.Header["X-Forwarded-User"][0])
}
}
func TestPassUserHeadersWithEmail(t *testing.T) {
opts := baseTestOptions()
err := validation.Validate(opts)
assert.NoError(t, err)
const emailAddress = "john.doe@example.com"
const userName = "9fcab5c9b889a557"
created := time.Now()
session := &sessions.SessionState{
User: userName,
Email: emailAddress,
AccessToken: "oauth_token",
CreatedAt: &created,
}
{
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", opts.ProxyPrefix+"/testCase0", nil)
proxy, err := NewOAuthProxy(opts, func(email string) bool {
return email == emailAddress
})
if err != nil {
t.Fatal(err)
}
proxy.addHeadersForProxying(rw, req, session)
assert.Equal(t, userName, req.Header["X-Forwarded-User"][0])
}
opts.PreferEmailToUser = true
{
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", opts.ProxyPrefix+"/testCase1", nil)
proxy, err := NewOAuthProxy(opts, func(email string) bool {
return email == emailAddress
})
if err != nil {
t.Fatal(err)
}
proxy.addHeadersForProxying(rw, req, session)
assert.Equal(t, emailAddress, req.Header["X-Forwarded-User"][0])
}
}
func TestPassGroupsHeadersWithGroups(t *testing.T) {
opts := baseTestOptions()
opts.InjectRequestHeaders = []options.Header{
{
Name: "X-Forwarded-Groups",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "groups",
},
},
},
},
}
err := validation.Validate(opts)
assert.NoError(t, err)
@ -681,162 +590,28 @@ func TestPassGroupsHeadersWithGroups(t *testing.T) {
AccessToken: "oauth_token",
CreatedAt: &created,
}
{
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", opts.ProxyPrefix+"/testCase0", nil)
proxy, err := NewOAuthProxy(opts, func(email string) bool {
return email == emailAddress
})
if err != nil {
t.Fatal(err)
}
proxy.addHeadersForProxying(rw, req, session)
assert.NoError(t, err)
// Save the required session
rw := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
err = proxy.sessionStore.Save(rw, req, session)
assert.NoError(t, err)
// Extract the cookie value to inject into the test request
cookie := rw.Header().Values("Set-Cookie")[0]
req, _ = http.NewRequest("GET", "/", nil)
req.Header.Set("Cookie", cookie)
rw = httptest.NewRecorder()
proxy.ServeHTTP(rw, req)
assert.Equal(t, groups, req.Header["X-Forwarded-Groups"])
}
}
func TestStripAuthHeaders(t *testing.T) {
testCases := map[string]struct {
SkipAuthStripHeaders bool
PassBasicAuth bool
PassUserHeaders bool
PassAccessToken bool
PassAuthorization bool
StrippedHeaders map[string]bool
}{
"Default options": {
SkipAuthStripHeaders: true,
PassBasicAuth: true,
PassUserHeaders: true,
PassAccessToken: false,
PassAuthorization: false,
StrippedHeaders: map[string]bool{
"X-Forwarded-User": true,
"X-Forwared-Groups": true,
"X-Forwarded-Email": true,
"X-Forwarded-Preferred-Username": true,
"X-Forwarded-Access-Token": false,
"Authorization": true,
},
},
"Pass access token": {
SkipAuthStripHeaders: true,
PassBasicAuth: true,
PassUserHeaders: true,
PassAccessToken: true,
PassAuthorization: false,
StrippedHeaders: map[string]bool{
"X-Forwarded-User": true,
"X-Forwared-Groups": true,
"X-Forwarded-Email": true,
"X-Forwarded-Preferred-Username": true,
"X-Forwarded-Access-Token": true,
"Authorization": true,
},
},
"Nothing setting Authorization": {
SkipAuthStripHeaders: true,
PassBasicAuth: false,
PassUserHeaders: true,
PassAccessToken: true,
PassAuthorization: false,
StrippedHeaders: map[string]bool{
"X-Forwarded-User": true,
"X-Forwared-Groups": true,
"X-Forwarded-Email": true,
"X-Forwarded-Preferred-Username": true,
"X-Forwarded-Access-Token": true,
"Authorization": false,
},
},
"Only Authorization header modified": {
SkipAuthStripHeaders: true,
PassBasicAuth: false,
PassUserHeaders: false,
PassAccessToken: false,
PassAuthorization: true,
StrippedHeaders: map[string]bool{
"X-Forwarded-User": false,
"X-Forwared-Groups": false,
"X-Forwarded-Email": false,
"X-Forwarded-Preferred-Username": false,
"X-Forwarded-Access-Token": false,
"Authorization": true,
},
},
"Don't strip any headers (default options)": {
SkipAuthStripHeaders: false,
PassBasicAuth: true,
PassUserHeaders: true,
PassAccessToken: false,
PassAuthorization: false,
StrippedHeaders: map[string]bool{
"X-Forwarded-User": false,
"X-Forwared-Groups": false,
"X-Forwarded-Email": false,
"X-Forwarded-Preferred-Username": false,
"X-Forwarded-Access-Token": false,
"Authorization": false,
},
},
"Don't strip any headers (custom options)": {
SkipAuthStripHeaders: false,
PassBasicAuth: true,
PassUserHeaders: true,
PassAccessToken: true,
PassAuthorization: false,
StrippedHeaders: map[string]bool{
"X-Forwarded-User": false,
"X-Forwared-Groups": false,
"X-Forwarded-Email": false,
"X-Forwarded-Preferred-Username": false,
"X-Forwarded-Access-Token": false,
"Authorization": false,
},
},
}
initialHeaders := map[string]string{
"X-Forwarded-User": "9fcab5c9b889a557",
"X-Forwarded-Email": "john.doe@example.com",
"X-Forwarded-Groups": "a,b,c",
"X-Forwarded-Preferred-Username": "john.doe",
"X-Forwarded-Access-Token": "AccessToken",
"Authorization": "bearer IDToken",
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
opts := baseTestOptions()
opts.SkipAuthStripHeaders = tc.SkipAuthStripHeaders
opts.PassBasicAuth = tc.PassBasicAuth
opts.PassUserHeaders = tc.PassUserHeaders
opts.PassAccessToken = tc.PassAccessToken
opts.PassAuthorization = tc.PassAuthorization
err := validation.Validate(opts)
assert.NoError(t, err)
req, _ := http.NewRequest("GET", fmt.Sprintf("%s/testCase", opts.ProxyPrefix), nil)
for header, val := range initialHeaders {
req.Header.Set(header, val)
}
proxy, err := NewOAuthProxy(opts, func(_ string) bool { return true })
assert.NoError(t, err)
if proxy.skipAuthStripHeaders {
proxy.stripAuthHeaders(req)
}
for header, stripped := range tc.StrippedHeaders {
if stripped {
assert.Equal(t, req.Header.Get(header), "")
} else {
assert.Equal(t, req.Header.Get(header), initialHeaders[header])
}
}
})
}
}
type PassAccessTokenTest struct {
providerServer *httptest.Server
@ -884,7 +659,21 @@ func NewPassAccessTokenTest(opts PassAccessTokenTestOptions) (*PassAccessTokenTe
}
patt.opts.Cookie.Secure = false
patt.opts.PassAccessToken = opts.PassAccessToken
if opts.PassAccessToken {
patt.opts.InjectRequestHeaders = []options.Header{
{
Name: "X-Forwarded-Access-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "access_token",
},
},
},
},
}
}
err := validation.Validate(patt.opts)
if err != nil {
return nil, err
@ -1187,8 +976,10 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
return nil, err
}
pcTest.proxy.provider = &TestProvider{
ProviderData: &providers.ProviderData{},
ValidToken: opts.providerValidateCookieResponse,
}
pcTest.proxy.provider.(*TestProvider).SetAllowedGroups(pcTest.opts.AllowedGroups)
// Now, zero-out proxy.CookieRefresh for the cases that don't involve
// access_token validation.
@ -1333,20 +1124,67 @@ func NewUserInfoEndpointTest() (*ProcessCookieTest, error) {
}
func TestUserInfoEndpointAccepted(t *testing.T) {
testCases := []struct {
name string
session *sessions.SessionState
expectedResponse string
}{
{
name: "Full session",
session: &sessions.SessionState{
User: "john.doe",
Email: "john.doe@example.com",
Groups: []string{"example", "groups"},
AccessToken: "my_access_token",
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"]}\n",
},
{
name: "Minimal session",
session: &sessions.SessionState{
User: "john.doe",
Email: "john.doe@example.com",
Groups: []string{"example", "groups"},
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"]}\n",
},
{
name: "No groups",
session: &sessions.SessionState{
User: "john.doe",
Email: "john.doe@example.com",
AccessToken: "my_access_token",
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\"}\n",
},
{
name: "With Preferred Username",
session: &sessions.SessionState{
User: "john.doe",
PreferredUsername: "john",
Email: "john.doe@example.com",
Groups: []string{"example", "groups"},
AccessToken: "my_access_token",
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\"}\n",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
test, err := NewUserInfoEndpointTest()
if err != nil {
t.Fatal(err)
}
startSession := &sessions.SessionState{
Email: "john.doe@example.com", AccessToken: "my_access_token"}
err = test.SaveSession(startSession)
err = test.SaveSession(tc.session)
assert.NoError(t, err)
test.proxy.ServeHTTP(test.rw, test.req)
assert.Equal(t, http.StatusOK, test.rw.Code)
bodyBytes, _ := ioutil.ReadAll(test.rw.Body)
assert.Equal(t, "{\"email\":\"john.doe@example.com\"}\n", string(bodyBytes))
assert.Equal(t, tc.expectedResponse, string(bodyBytes))
})
}
}
func TestUserInfoEndpointUnauthorizedOnNoCookieSetError(t *testing.T) {
@ -1442,7 +1280,48 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) {
var pcTest ProcessCookieTest
pcTest.opts = baseTestOptions()
pcTest.opts.SetXAuthRequest = true
pcTest.opts.InjectResponseHeaders = []options.Header{
{
Name: "X-Auth-Request-User",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Auth-Request-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
},
{
Name: "X-Auth-Request-Groups",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "groups",
},
},
},
},
{
Name: "X-Forwarded-Preferred-Username",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "preferred_username",
},
},
},
},
}
pcTest.opts.AllowedGroups = []string{"oauth_groups"}
err := validation.Validate(pcTest.opts)
assert.NoError(t, err)
@ -1454,6 +1333,7 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) {
t.Fatal(err)
}
pcTest.proxy.provider = &TestProvider{
ProviderData: &providers.ProviderData{},
ValidToken: true,
}
@ -1480,8 +1360,62 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
var pcTest ProcessCookieTest
pcTest.opts = baseTestOptions()
pcTest.opts.SetXAuthRequest = true
pcTest.opts.SetBasicAuth = true
pcTest.opts.InjectResponseHeaders = []options.Header{
{
Name: "X-Auth-Request-User",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Auth-Request-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
},
{
Name: "X-Auth-Request-Groups",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "groups",
},
},
},
},
{
Name: "X-Forwarded-Preferred-Username",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "preferred_username",
},
},
},
},
{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
BasicAuthPassword: &options.SecretSource{
Value: []byte("This is a secure password"),
},
},
},
},
},
}
err := validation.Validate(pcTest.opts)
assert.NoError(t, err)
@ -1492,6 +1426,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
t.Fatal(err)
}
pcTest.proxy.provider = &TestProvider{
ProviderData: &providers.ProviderData{},
ValidToken: true,
}
@ -1511,7 +1446,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
assert.Equal(t, http.StatusAccepted, pcTest.rw.Code)
assert.Equal(t, "oauth_user", pcTest.rw.Header().Values("X-Auth-Request-User")[0])
assert.Equal(t, "oauth_user@example.com", pcTest.rw.Header().Values("X-Auth-Request-Email")[0])
expectedHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte("oauth_user:"+pcTest.opts.BasicAuthPassword))
expectedHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte("oauth_user:This is a secure password"))
assert.Equal(t, expectedHeader, pcTest.rw.Header().Values("Authorization")[0])
}
@ -1519,8 +1454,48 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
var pcTest ProcessCookieTest
pcTest.opts = baseTestOptions()
pcTest.opts.SetXAuthRequest = true
pcTest.opts.SetBasicAuth = false
pcTest.opts.InjectResponseHeaders = []options.Header{
{
Name: "X-Auth-Request-User",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Auth-Request-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
},
{
Name: "X-Auth-Request-Groups",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "groups",
},
},
},
},
{
Name: "X-Forwarded-Preferred-Username",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "preferred_username",
},
},
},
},
}
err := validation.Validate(pcTest.opts)
assert.NoError(t, err)
@ -1531,6 +1506,7 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
t.Fatal(err)
}
pcTest.proxy.provider = &TestProvider{
ProviderData: &providers.ProviderData{},
ValidToken: true,
}
@ -1985,9 +1961,74 @@ func TestGetJwtSession(t *testing.T) {
&oidc.Config{ClientID: "https://test.myapp.com", SkipExpiryCheck: true})
test, err := NewAuthOnlyEndpointTest(func(opts *options.Options) {
opts.PassAuthorization = true
opts.SetAuthorization = true
opts.SetXAuthRequest = true
opts.InjectRequestHeaders = []options.Header{
{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "id_token",
Prefix: "Bearer ",
},
},
},
},
{
Name: "X-Forwarded-User",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Forwarded-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
},
}
opts.InjectResponseHeaders = []options.Header{
{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "id_token",
Prefix: "Bearer ",
},
},
},
},
{
Name: "X-Auth-Request-User",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Auth-Request-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
},
}
opts.SkipJwtBearerTokens = true
opts.SetJWTBearerVerifiers(append(opts.GetJWTBearerVerifiers(), verifier))
})
@ -2004,15 +2045,6 @@ func TestGetJwtSession(t *testing.T) {
"Authorization": {authHeader},
}
// Bearer
expires := time.Unix(1912151821, 0)
session, err := test.proxy.getAuthenticatedSession(test.rw, test.req)
assert.NoError(t, err)
assert.Equal(t, session.User, "1234567890")
assert.Equal(t, session.Email, "john@example.com")
assert.Equal(t, session.ExpiresOn, &expires)
assert.Equal(t, session.IDToken, goodJwt)
test.proxy.ServeHTTP(test.rw, test.req)
if test.rw.Code >= 400 {
t.Fatalf("expected 3xx got %d", test.rw.Code)
@ -2140,6 +2172,43 @@ func baseTestOptions() *options.Options {
opts.ClientID = clientID
opts.ClientSecret = clientSecret
opts.EmailDomains = []string{"*"}
// Default injected headers for legacy configuration
opts.InjectRequestHeaders = []options.Header{
{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
BasicAuthPassword: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("This is a secure password"))),
},
},
},
},
},
{
Name: "X-Forwarded-User",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Forwarded-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
},
}
return opts
}

View File

@ -2,23 +2,57 @@ package middleware
import (
"context"
"fmt"
"github.com/coreos/go-oidc"
sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
)
// TokenToSessionFunc takes a rawIDToken and an idToken and converts it into a
// SessionState.
type TokenToSessionFunc func(ctx context.Context, rawIDToken string, idToken *oidc.IDToken) (*sessionsapi.SessionState, error)
// TokenToSessionFunc takes a raw ID Token and converts it into a SessionState.
type TokenToSessionFunc func(ctx context.Context, token string) (*sessionsapi.SessionState, error)
// TokenToSessionLoader pairs a token verifier with the correct converter function
// to convert the ID Token to a SessionState.
type TokenToSessionLoader struct {
// Verfier is used to verify that the ID Token was signed by the claimed issuer
// and that the token has not been tampered with.
Verifier *oidc.IDTokenVerifier
// VerifyFunc takes a raw bearer token and verifies it returning the converted
// oidc.IDToken representation of the token.
type VerifyFunc func(ctx context.Context, token string) (*oidc.IDToken, error)
// TokenToSession converts a rawIDToken and an idToken to a SessionState.
// (Optional) If not set a default basic implementation is used.
TokenToSession TokenToSessionFunc
// CreateTokenToSessionFunc provides a handler that is a default implementation
// for converting a JWT into a session.
func CreateTokenToSessionFunc(verify VerifyFunc) TokenToSessionFunc {
return func(ctx context.Context, token string) (*sessionsapi.SessionState, error) {
var claims struct {
Subject string `json:"sub"`
Email string `json:"email"`
Verified *bool `json:"email_verified"`
PreferredUsername string `json:"preferred_username"`
}
idToken, err := verify(ctx, token)
if err != nil {
return nil, err
}
if err := idToken.Claims(&claims); err != nil {
return nil, fmt.Errorf("failed to parse bearer token claims: %v", err)
}
if claims.Email == "" {
claims.Email = claims.Subject
}
if claims.Verified != nil && !*claims.Verified {
return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email)
}
newSession := &sessionsapi.SessionState{
Email: claims.Email,
User: claims.Subject,
PreferredUsername: claims.PreferredUsername,
AccessToken: token,
IDToken: token,
RefreshToken: "",
ExpiresOn: &idToken.Expiry,
}
return newSession, nil
}
}

View File

@ -0,0 +1,47 @@
package options
// AlphaOptions contains alpha structured configuration options.
// Usage of these options allows users to access alpha features that are not
// available as part of the primary configuration structure for OAuth2 Proxy.
//
// :::warning
// The options within this structure are considered alpha.
// They may change between releases without notice.
// :::
type AlphaOptions struct {
// Upstreams is used to configure upstream servers.
// Once a user is authenticated, requests to the server will be proxied to
// these upstream servers based on the path mappings defined in this list.
Upstreams Upstreams `json:"upstreams,omitempty"`
// InjectRequestHeaders is used to configure headers that should be added
// to requests to upstream servers.
// Headers may source values from either the authenticated user's session
// or from a static secret value.
InjectRequestHeaders []Header `json:"injectRequestHeaders,omitempty"`
// InjectResponseHeaders is used to configure headers that should be added
// to responses from the proxy.
// This is typically used when using the proxy as an external authentication
// provider in conjunction with another proxy such as NGINX and its
// auth_request module.
// Headers may source values from either the authenticated user's session
// or from a static secret value.
InjectResponseHeaders []Header `json:"injectResponseHeaders,omitempty"`
}
// MergeInto replaces alpha options in the Options struct with the values
// from the AlphaOptions
func (a *AlphaOptions) MergeInto(opts *Options) {
opts.UpstreamServers = a.Upstreams
opts.InjectRequestHeaders = a.InjectRequestHeaders
opts.InjectResponseHeaders = a.InjectResponseHeaders
}
// ExtractFrom populates the fields in the AlphaOptions with the values from
// the Options
func (a *AlphaOptions) ExtractFrom(opts *Options) {
a.Upstreams = opts.UpstreamServers
a.InjectRequestHeaders = opts.InjectRequestHeaders
a.InjectResponseHeaders = opts.InjectResponseHeaders
}

View File

@ -1,14 +1,62 @@
package options
import (
"fmt"
"strconv"
"time"
)
// SecretSource references an individual secret value.
// Only one source within the struct should be defined at any time.
type SecretSource struct {
// Value expects a base64 encoded string value.
Value []byte
Value []byte `json:"value,omitempty"`
// FromEnv expects the name of an environment variable.
FromEnv string
FromEnv string `json:"fromEnv,omitempty"`
// FromFile expects a path to a file containing the secret value.
FromFile string
FromFile string `json:"fromFile,omitempty"`
}
// Duration is an alias for time.Duration so that we can ensure the marshalling
// and unmarshalling of string durations is done as users expect.
// Intentional blank line below to keep this first part of the comment out of
// any generated references.
// Duration is as string representation of a period of time.
// A duration string is a is a possibly signed sequence of decimal numbers,
// each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
type Duration time.Duration
// UnmarshalJSON parses the duration string and sets the value of duration
// to the value of the duration string.
func (d *Duration) UnmarshalJSON(data []byte) error {
input := string(data)
if unquoted, err := strconv.Unquote(input); err == nil {
input = unquoted
}
du, err := time.ParseDuration(input)
if err != nil {
return err
}
*d = Duration(du)
return nil
}
// MarshalJSON ensures that when the string is marshalled to JSON as a human
// readable string.
func (d *Duration) MarshalJSON() ([]byte, error) {
dStr := fmt.Sprintf("%q", d.Duration().String())
return []byte(dStr), nil
}
// Duration returns the time.Duration version of this Duration
func (d *Duration) Duration() time.Duration {
if d == nil {
return time.Duration(0)
}
return time.Duration(*d)
}

View File

@ -0,0 +1,88 @@
package options
import (
"encoding/json"
"errors"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
var _ = Describe("Common", func() {
Context("Duration", func() {
type marshalJSONTableInput struct {
duration Duration
expectedJSON string
}
DescribeTable("MarshalJSON",
func(in marshalJSONTableInput) {
data, err := in.duration.MarshalJSON()
Expect(err).ToNot(HaveOccurred())
Expect(string(data)).To(Equal(in.expectedJSON))
var d Duration
Expect(json.Unmarshal(data, &d)).To(Succeed())
Expect(d).To(Equal(in.duration))
},
Entry("30 seconds", marshalJSONTableInput{
duration: Duration(30 * time.Second),
expectedJSON: "\"30s\"",
}),
Entry("1 minute", marshalJSONTableInput{
duration: Duration(1 * time.Minute),
expectedJSON: "\"1m0s\"",
}),
Entry("1 hour 15 minutes", marshalJSONTableInput{
duration: Duration(75 * time.Minute),
expectedJSON: "\"1h15m0s\"",
}),
Entry("A zero Duration", marshalJSONTableInput{
duration: Duration(0),
expectedJSON: "\"0s\"",
}),
)
type unmarshalJSONTableInput struct {
json string
expectedErr error
expectedDuration Duration
}
DescribeTable("UnmarshalJSON",
func(in unmarshalJSONTableInput) {
// A duration must be initialised pointer before UnmarshalJSON will work.
zero := Duration(0)
d := &zero
err := d.UnmarshalJSON([]byte(in.json))
if in.expectedErr != nil {
Expect(err).To(MatchError(in.expectedErr.Error()))
} else {
Expect(err).ToNot(HaveOccurred())
}
Expect(d).ToNot(BeNil())
Expect(*d).To(Equal(in.expectedDuration))
},
Entry("1m", unmarshalJSONTableInput{
json: "\"1m\"",
expectedDuration: Duration(1 * time.Minute),
}),
Entry("30s", unmarshalJSONTableInput{
json: "\"30s\"",
expectedDuration: Duration(30 * time.Second),
}),
Entry("1h15m", unmarshalJSONTableInput{
json: "\"1h15m\"",
expectedDuration: Duration(75 * time.Minute),
}),
Entry("am", unmarshalJSONTableInput{
json: "\"am\"",
expectedErr: errors.New("time: invalid duration \"am\""),
expectedDuration: Duration(0),
}),
)
})
})

View File

@ -5,26 +5,26 @@ package options
type Header struct {
// Name is the header name to be used for this set of values.
// Names should be unique within a list of Headers.
Name string `json:"name"`
Name string `json:"name,omitempty"`
// PreserveRequestValue determines whether any values for this header
// should be preserved for the request to the upstream server.
// This option only takes effet on injected request headers.
// Defaults to false (headers that match this header will be stripped).
PreserveRequestValue bool `json:"preserveRequestValue"`
PreserveRequestValue bool `json:"preserveRequestValue,omitempty"`
// Values contains the desired values for this header
Values []HeaderValue `json:"values"`
Values []HeaderValue `json:"values,omitempty"`
}
// HeaderValue represents a single header value and the sources that can
// make up the header value
type HeaderValue struct {
// Allow users to load the value from a secret source
*SecretSource
*SecretSource `json:",omitempty"`
// Allow users to load the value from a session claim
*ClaimSource
*ClaimSource `json:",omitempty"`
}
// ClaimSource allows loading a header value from a claim within the session
@ -40,5 +40,5 @@ type ClaimSource struct {
// BasicAuthPassword converts this claim into a basic auth header.
// Note the value of claim will become the basic auth username and the
// basicAuthPassword will be used as the password value.
BasicAuthPassword *SecretSource
BasicAuthPassword *SecretSource `json:"basicAuthPassword,omitempty"`
}

View File

@ -15,6 +15,9 @@ type LegacyOptions struct {
// Legacy options related to upstream servers
LegacyUpstreams LegacyUpstreams `cfg:",squash"`
// Legacy options for injecting request/response headers
LegacyHeaders LegacyHeaders `cfg:",squash"`
Options Options `cfg:",squash"`
}
@ -23,13 +26,28 @@ func NewLegacyOptions() *LegacyOptions {
LegacyUpstreams: LegacyUpstreams{
PassHostHeader: true,
ProxyWebSockets: true,
FlushInterval: time.Duration(1) * time.Second,
FlushInterval: DefaultUpstreamFlushInterval,
},
LegacyHeaders: LegacyHeaders{
PassBasicAuth: true,
PassUserHeaders: true,
SkipAuthStripHeaders: true,
},
Options: *NewOptions(),
}
}
func NewLegacyFlagSet() *pflag.FlagSet {
flagSet := NewFlagSet()
flagSet.AddFlagSet(legacyUpstreamsFlagSet())
flagSet.AddFlagSet(legacyHeadersFlagSet())
return flagSet
}
func (l *LegacyOptions) ToOptions() (*Options, error) {
upstreams, err := l.LegacyUpstreams.convert()
if err != nil {
@ -37,6 +55,7 @@ func (l *LegacyOptions) ToOptions() (*Options, error) {
}
l.Options.UpstreamServers = upstreams
l.Options.InjectRequestHeaders, l.Options.InjectResponseHeaders = l.LegacyHeaders.convert()
return &l.Options, nil
}
@ -51,7 +70,7 @@ type LegacyUpstreams struct {
func legacyUpstreamsFlagSet() *pflag.FlagSet {
flagSet := pflag.NewFlagSet("upstreams", pflag.ExitOnError)
flagSet.Duration("flush-interval", time.Duration(1)*time.Second, "period between response flushing when streaming responses")
flagSet.Duration("flush-interval", DefaultUpstreamFlushInterval, "period between response flushing when streaming responses")
flagSet.Bool("pass-host-header", true, "pass the request Host Header to upstream")
flagSet.Bool("proxy-websockets", true, "enables WebSocket proxying")
flagSet.Bool("ssl-upstream-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS upstreams")
@ -73,6 +92,7 @@ func (l *LegacyUpstreams) convert() (Upstreams, error) {
u.Path = "/"
}
flushInterval := Duration(l.FlushInterval)
upstream := Upstream{
ID: u.Path,
Path: u.Path,
@ -80,7 +100,7 @@ func (l *LegacyUpstreams) convert() (Upstreams, error) {
InsecureSkipTLSVerify: l.SSLUpstreamInsecureSkipVerify,
PassHostHeader: &l.PassHostHeader,
ProxyWebSockets: &l.ProxyWebSockets,
FlushInterval: &l.FlushInterval,
FlushInterval: &flushInterval,
}
switch u.Scheme {
@ -119,3 +139,267 @@ func (l *LegacyUpstreams) convert() (Upstreams, error) {
return upstreams, nil
}
type LegacyHeaders struct {
PassBasicAuth bool `flag:"pass-basic-auth" cfg:"pass_basic_auth"`
PassAccessToken bool `flag:"pass-access-token" cfg:"pass_access_token"`
PassUserHeaders bool `flag:"pass-user-headers" cfg:"pass_user_headers"`
PassAuthorization bool `flag:"pass-authorization-header" cfg:"pass_authorization_header"`
SetBasicAuth bool `flag:"set-basic-auth" cfg:"set_basic_auth"`
SetXAuthRequest bool `flag:"set-xauthrequest" cfg:"set_xauthrequest"`
SetAuthorization bool `flag:"set-authorization-header" cfg:"set_authorization_header"`
PreferEmailToUser bool `flag:"prefer-email-to-user" cfg:"prefer_email_to_user"`
BasicAuthPassword string `flag:"basic-auth-password" cfg:"basic_auth_password"`
SkipAuthStripHeaders bool `flag:"skip-auth-strip-headers" cfg:"skip_auth_strip_headers"`
}
func legacyHeadersFlagSet() *pflag.FlagSet {
flagSet := pflag.NewFlagSet("headers", pflag.ExitOnError)
flagSet.Bool("pass-basic-auth", true, "pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream")
flagSet.Bool("pass-access-token", false, "pass OAuth access_token to upstream via X-Forwarded-Access-Token header")
flagSet.Bool("pass-user-headers", true, "pass X-Forwarded-User and X-Forwarded-Email information to upstream")
flagSet.Bool("pass-authorization-header", false, "pass the Authorization Header to upstream")
flagSet.Bool("set-basic-auth", false, "set HTTP Basic Auth information in response (useful in Nginx auth_request mode)")
flagSet.Bool("set-xauthrequest", false, "set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode)")
flagSet.Bool("set-authorization-header", false, "set Authorization response headers (useful in Nginx auth_request mode)")
flagSet.Bool("prefer-email-to-user", false, "Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, eg. htaccess authentication. Used in conjunction with -pass-basic-auth and -pass-user-headers")
flagSet.String("basic-auth-password", "", "the password to set when passing the HTTP Basic Auth header")
flagSet.Bool("skip-auth-strip-headers", true, "strips X-Forwarded-* style authentication headers & Authorization header if they would be set by oauth2-proxy")
return flagSet
}
// convert takes the legacy request/response headers and converts them to
// the new format for InjectRequestHeaders and InjectResponseHeaders
func (l *LegacyHeaders) convert() ([]Header, []Header) {
return l.getRequestHeaders(), l.getResponseHeaders()
}
func (l *LegacyHeaders) getRequestHeaders() []Header {
requestHeaders := []Header{}
if l.PassBasicAuth && l.BasicAuthPassword != "" {
requestHeaders = append(requestHeaders, getBasicAuthHeader(l.PreferEmailToUser, l.BasicAuthPassword))
}
// In the old implementation, PassUserHeaders is a subset of PassBasicAuth
if l.PassBasicAuth || l.PassUserHeaders {
requestHeaders = append(requestHeaders, getPassUserHeaders(l.PreferEmailToUser)...)
requestHeaders = append(requestHeaders, getPreferredUsernameHeader())
}
if l.PassAccessToken {
requestHeaders = append(requestHeaders, getPassAccessTokenHeader())
}
if l.PassAuthorization {
requestHeaders = append(requestHeaders, getAuthorizationHeader())
}
for i := range requestHeaders {
requestHeaders[i].PreserveRequestValue = !l.SkipAuthStripHeaders
}
return requestHeaders
}
func (l *LegacyHeaders) getResponseHeaders() []Header {
responseHeaders := []Header{}
if l.SetXAuthRequest {
responseHeaders = append(responseHeaders, getXAuthRequestHeaders()...)
if l.PassAccessToken {
responseHeaders = append(responseHeaders, getXAuthRequestAccessTokenHeader())
}
}
if l.SetBasicAuth {
responseHeaders = append(responseHeaders, getBasicAuthHeader(l.PreferEmailToUser, l.BasicAuthPassword))
}
if l.SetAuthorization {
responseHeaders = append(responseHeaders, getAuthorizationHeader())
}
return responseHeaders
}
func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header {
claim := "user"
if preferEmailToUser {
claim = "email"
}
return Header{
Name: "Authorization",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: claim,
Prefix: "Basic ",
BasicAuthPassword: &SecretSource{
Value: []byte(basicAuthPassword),
},
},
},
},
}
}
func getPassUserHeaders(preferEmailToUser bool) []Header {
headers := []Header{
{
Name: "X-Forwarded-Groups",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "groups",
},
},
},
},
}
if preferEmailToUser {
return append(headers,
Header{
Name: "X-Forwarded-User",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
},
)
}
return append(headers,
Header{
Name: "X-Forwarded-User",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
},
},
},
},
Header{
Name: "X-Forwarded-Email",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
},
)
}
func getPassAccessTokenHeader() Header {
return Header{
Name: "X-Forwarded-Access-Token",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "access_token",
},
},
},
}
}
func getAuthorizationHeader() Header {
return Header{
Name: "Authorization",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "id_token",
Prefix: "Bearer ",
},
},
},
}
}
func getPreferredUsernameHeader() Header {
return Header{
Name: "X-Forwarded-Preferred-Username",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "preferred_username",
},
},
},
}
}
func getXAuthRequestHeaders() []Header {
headers := []Header{
{
Name: "X-Auth-Request-User",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Auth-Request-Email",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
},
{
Name: "X-Auth-Request-Preferred-Username",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "preferred_username",
},
},
},
},
{
Name: "X-Auth-Request-Groups",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "groups",
},
},
},
},
}
return headers
}
func getXAuthRequestAccessTokenHeader() Header {
return Header{
Name: "X-Auth-Request-Access-Token",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "access_token",
},
},
},
}
}

View File

@ -16,8 +16,8 @@ var _ = Describe("Legacy Options", func() {
legacyOpts := NewLegacyOptions()
// Set upstreams and related options to test their conversion
flushInterval := 5 * time.Second
legacyOpts.LegacyUpstreams.FlushInterval = flushInterval
flushInterval := Duration(5 * time.Second)
legacyOpts.LegacyUpstreams.FlushInterval = time.Duration(flushInterval)
legacyOpts.LegacyUpstreams.PassHostHeader = true
legacyOpts.LegacyUpstreams.ProxyWebSockets = true
legacyOpts.LegacyUpstreams.SSLUpstreamInsecureSkipVerify = true
@ -57,6 +57,55 @@ var _ = Describe("Legacy Options", func() {
},
}
opts.InjectRequestHeaders = []Header{
{
Name: "X-Forwarded-Groups",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "groups",
},
},
},
},
{
Name: "X-Forwarded-User",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
},
},
},
},
{
Name: "X-Forwarded-Email",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
},
{
Name: "X-Forwarded-Preferred-Username",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "preferred_username",
},
},
},
},
}
opts.InjectResponseHeaders = []Header{}
converted, err := legacyOpts.ToOptions()
Expect(err).ToNot(HaveOccurred())
Expect(converted).To(Equal(opts))
@ -74,7 +123,7 @@ var _ = Describe("Legacy Options", func() {
skipVerify := true
passHostHeader := false
proxyWebSockets := true
flushInterval := 5 * time.Second
flushInterval := Duration(5 * time.Second)
// Test cases and expected outcomes
validHTTP := "http://foo.bar/baz"
@ -149,7 +198,7 @@ var _ = Describe("Legacy Options", func() {
SSLUpstreamInsecureSkipVerify: skipVerify,
PassHostHeader: passHostHeader,
ProxyWebSockets: proxyWebSockets,
FlushInterval: flushInterval,
FlushInterval: time.Duration(flushInterval),
}
upstreams, err := legacyUpstreams.convert()
@ -210,4 +259,504 @@ var _ = Describe("Legacy Options", func() {
}),
)
})
Context("Legacy Headers", func() {
const basicAuthSecret = "super-secret-password"
type legacyHeadersTableInput struct {
legacyHeaders *LegacyHeaders
expectedRequestHeaders []Header
expectedResponseHeaders []Header
}
withPreserveRequestValue := func(h Header, preserve bool) Header {
h.PreserveRequestValue = preserve
return h
}
xForwardedUser := Header{
Name: "X-Forwarded-User",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
},
},
},
}
xForwardedEmail := Header{
Name: "X-Forwarded-Email",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
}
xForwardedGroups := Header{
Name: "X-Forwarded-Groups",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "groups",
},
},
},
}
xForwardedPreferredUsername := Header{
Name: "X-Forwarded-Preferred-Username",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "preferred_username",
},
},
},
}
basicAuthHeader := Header{
Name: "Authorization",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
Prefix: "Basic ",
BasicAuthPassword: &SecretSource{
Value: []byte(basicAuthSecret),
},
},
},
},
}
xForwardedUserWithEmail := Header{
Name: "X-Forwarded-User",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
}
xForwardedAccessToken := Header{
Name: "X-Forwarded-Access-Token",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "access_token",
},
},
},
}
basicAuthHeaderWithEmail := Header{
Name: "Authorization",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
Prefix: "Basic ",
BasicAuthPassword: &SecretSource{
Value: []byte(basicAuthSecret),
},
},
},
},
}
xAuthRequestUser := Header{
Name: "X-Auth-Request-User",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
},
},
},
}
xAuthRequestEmail := Header{
Name: "X-Auth-Request-Email",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "email",
},
},
},
}
xAuthRequestGroups := Header{
Name: "X-Auth-Request-Groups",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "groups",
},
},
},
}
xAuthRequestPreferredUsername := Header{
Name: "X-Auth-Request-Preferred-Username",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "preferred_username",
},
},
},
}
xAuthRequestAccessToken := Header{
Name: "X-Auth-Request-Access-Token",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "access_token",
},
},
},
}
authorizationHeader := Header{
Name: "Authorization",
PreserveRequestValue: false,
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "id_token",
Prefix: "Bearer ",
},
},
},
}
DescribeTable("should convert to injectRequestHeaders",
func(in legacyHeadersTableInput) {
requestHeaders, responseHeaders := in.legacyHeaders.convert()
Expect(requestHeaders).To(ConsistOf(in.expectedRequestHeaders))
Expect(responseHeaders).To(ConsistOf(in.expectedResponseHeaders))
},
Entry("with all header options off", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{},
expectedResponseHeaders: []Header{},
}),
Entry("with basic auth enabled", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: true,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: true,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: basicAuthSecret,
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
xForwardedUser,
xForwardedEmail,
xForwardedGroups,
xForwardedPreferredUsername,
basicAuthHeader,
},
expectedResponseHeaders: []Header{
basicAuthHeader,
},
}),
Entry("with basic auth enabled and skipAuthStripHeaders disabled", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: true,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: true,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: basicAuthSecret,
SkipAuthStripHeaders: false,
},
expectedRequestHeaders: []Header{
withPreserveRequestValue(xForwardedUser, true),
withPreserveRequestValue(xForwardedEmail, true),
withPreserveRequestValue(xForwardedGroups, true),
withPreserveRequestValue(xForwardedPreferredUsername, true),
withPreserveRequestValue(basicAuthHeader, true),
},
expectedResponseHeaders: []Header{
basicAuthHeader,
},
}),
Entry("with basic auth enabled and preferEmailToUser", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: true,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: true,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: true,
BasicAuthPassword: basicAuthSecret,
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
xForwardedUserWithEmail,
xForwardedGroups,
xForwardedPreferredUsername,
basicAuthHeaderWithEmail,
},
expectedResponseHeaders: []Header{
basicAuthHeaderWithEmail,
},
}),
Entry("with basic auth enabled and passUserHeaders", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: true,
PassAccessToken: false,
PassUserHeaders: true,
PassAuthorization: false,
SetBasicAuth: true,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: basicAuthSecret,
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
xForwardedUser,
xForwardedEmail,
xForwardedGroups,
xForwardedPreferredUsername,
basicAuthHeader,
},
expectedResponseHeaders: []Header{
basicAuthHeader,
},
}),
Entry("with passUserHeaders", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: false,
PassUserHeaders: true,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
xForwardedUser,
xForwardedEmail,
xForwardedGroups,
xForwardedPreferredUsername,
},
expectedResponseHeaders: []Header{},
}),
Entry("with passUserHeaders and SkipAuthStripHeaders disabled", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: false,
PassUserHeaders: true,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: false,
},
expectedRequestHeaders: []Header{
withPreserveRequestValue(xForwardedUser, true),
withPreserveRequestValue(xForwardedEmail, true),
withPreserveRequestValue(xForwardedGroups, true),
withPreserveRequestValue(xForwardedPreferredUsername, true),
},
expectedResponseHeaders: []Header{},
}),
Entry("with setXAuthRequest", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: true,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{},
expectedResponseHeaders: []Header{
xAuthRequestUser,
xAuthRequestEmail,
xAuthRequestGroups,
xAuthRequestPreferredUsername,
},
}),
Entry("with passAccessToken", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: true,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
xForwardedAccessToken,
},
expectedResponseHeaders: []Header{},
}),
Entry("with passAcessToken and setXAuthRequest", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: true,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: true,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
xForwardedAccessToken,
},
expectedResponseHeaders: []Header{
xAuthRequestUser,
xAuthRequestEmail,
xAuthRequestGroups,
xAuthRequestPreferredUsername,
xAuthRequestAccessToken,
},
}),
Entry("with passAcessToken and SkipAuthStripHeaders disabled", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: true,
PassUserHeaders: false,
PassAuthorization: false,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: false,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: false,
},
expectedRequestHeaders: []Header{
withPreserveRequestValue(xForwardedAccessToken, true),
},
expectedResponseHeaders: []Header{},
}),
Entry("with authorization headers", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: true,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: true,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: true,
},
expectedRequestHeaders: []Header{
authorizationHeader,
},
expectedResponseHeaders: []Header{
authorizationHeader,
},
}),
Entry("with authorization headers and SkipAuthStripHeaders disabled", legacyHeadersTableInput{
legacyHeaders: &LegacyHeaders{
PassBasicAuth: false,
PassAccessToken: false,
PassUserHeaders: false,
PassAuthorization: true,
SetBasicAuth: false,
SetXAuthRequest: false,
SetAuthorization: true,
PreferEmailToUser: false,
BasicAuthPassword: "",
SkipAuthStripHeaders: false,
},
expectedRequestHeaders: []Header{
withPreserveRequestValue(authorizationHeader, true),
},
expectedResponseHeaders: []Header{
authorizationHeader,
},
}),
)
})
})

View File

@ -1,10 +1,13 @@
package options
import (
"errors"
"fmt"
"io/ioutil"
"reflect"
"strings"
"github.com/ghodss/yaml"
"github.com/mitchellh/mapstructure"
"github.com/spf13/pflag"
"github.com/spf13/viper"
@ -132,3 +135,28 @@ func isUnexported(name string) bool {
first := string(name[0])
return first == strings.ToLower(first)
}
// LoadYAML will load a YAML based configuration file into the options interface provided.
func LoadYAML(configFileName string, into interface{}) error {
v := viper.New()
v.SetConfigFile(configFileName)
v.SetConfigType("yaml")
v.SetTypeByDefaultValue(true)
if configFileName == "" {
return errors.New("no configuration file provided")
}
data, err := ioutil.ReadFile(configFileName)
if err != nil {
return fmt.Errorf("unable to load config file: %w", err)
}
// UnmarshalStrict will return an error if the config includes options that are
// not mapped to felds of the into struct
if err := yaml.UnmarshalStrict(data, into, yaml.DisallowUnknownFields); err != nil {
return fmt.Errorf("error unmarshalling config: %w", err)
}
return nil
}

View File

@ -1,9 +1,11 @@
package options
import (
"errors"
"fmt"
"io/ioutil"
"os"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
@ -295,10 +297,199 @@ var _ = Describe("Load", func() {
expectedOutput: NewOptions(),
}),
Entry("with an empty LegacyOptions struct, should return default values", &testOptionsTableInput{
flagSet: NewFlagSet,
flagSet: NewLegacyFlagSet,
input: &LegacyOptions{},
expectedOutput: NewLegacyOptions(),
}),
)
})
})
var _ = Describe("LoadYAML", func() {
Context("with a testOptions structure", func() {
type TestOptionSubStruct struct {
StringSliceOption []string `yaml:"stringSliceOption,omitempty"`
}
type TestOptions struct {
StringOption string `yaml:"stringOption,omitempty"`
Sub TestOptionSubStruct `yaml:"sub,omitempty"`
// Check that embedded fields can be unmarshalled
TestOptionSubStruct `yaml:",inline,squash"`
}
var testOptionsConfigBytesFull = []byte(`
stringOption: foo
stringSliceOption:
- a
- b
- c
sub:
stringSliceOption:
- d
- e
`)
type loadYAMLTableInput struct {
configFile []byte
input interface{}
expectedErr error
expectedOutput interface{}
}
DescribeTable("LoadYAML",
func(in loadYAMLTableInput) {
var configFileName string
if in.configFile != nil {
By("Creating a config file")
configFile, err := ioutil.TempFile("", "oauth2-proxy-test-config-file")
Expect(err).ToNot(HaveOccurred())
defer configFile.Close()
_, err = configFile.Write(in.configFile)
Expect(err).ToNot(HaveOccurred())
defer os.Remove(configFile.Name())
configFileName = configFile.Name()
}
var input interface{}
if in.input != nil {
input = in.input
} else {
input = &TestOptions{}
}
err := LoadYAML(configFileName, input)
if in.expectedErr != nil {
Expect(err).To(MatchError(in.expectedErr.Error()))
} else {
Expect(err).ToNot(HaveOccurred())
}
Expect(input).To(Equal(in.expectedOutput))
},
Entry("with a valid input", loadYAMLTableInput{
configFile: testOptionsConfigBytesFull,
input: &TestOptions{},
expectedOutput: &TestOptions{
StringOption: "foo",
Sub: TestOptionSubStruct{
StringSliceOption: []string{"d", "e"},
},
TestOptionSubStruct: TestOptionSubStruct{
StringSliceOption: []string{"a", "b", "c"},
},
},
}),
Entry("with no config file", loadYAMLTableInput{
configFile: nil,
input: &TestOptions{},
expectedOutput: &TestOptions{},
expectedErr: errors.New("no configuration file provided"),
}),
Entry("with invalid YAML", loadYAMLTableInput{
configFile: []byte("\tfoo: bar"),
input: &TestOptions{},
expectedOutput: &TestOptions{},
expectedErr: errors.New("error unmarshalling config: error converting YAML to JSON: yaml: found character that cannot start any token"),
}),
Entry("with extra fields in the YAML", loadYAMLTableInput{
configFile: append(testOptionsConfigBytesFull, []byte("foo: bar\n")...),
input: &TestOptions{},
expectedOutput: &TestOptions{
StringOption: "foo",
Sub: TestOptionSubStruct{
StringSliceOption: []string{"d", "e"},
},
TestOptionSubStruct: TestOptionSubStruct{
StringSliceOption: []string{"a", "b", "c"},
},
},
expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: unknown field \"foo\""),
}),
Entry("with an incorrect type for a string field", loadYAMLTableInput{
configFile: []byte(`stringOption: ["a", "b"]`),
input: &TestOptions{},
expectedOutput: &TestOptions{},
expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal array into Go struct field TestOptions.StringOption of type string"),
}),
Entry("with an incorrect type for an array field", loadYAMLTableInput{
configFile: []byte(`stringSliceOption: "a"`),
input: &TestOptions{},
expectedOutput: &TestOptions{},
expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.StringSliceOption of type []string"),
}),
)
})
It("should load a full example AlphaOptions", func() {
config := []byte(`
upstreams:
- id: httpbin
path: /
uri: http://httpbin
flushInterval: 500ms
injectRequestHeaders:
- name: X-Forwarded-User
values:
- claim: user
injectResponseHeaders:
- name: X-Secret
values:
- value: c2VjcmV0
`)
By("Creating a config file")
configFile, err := ioutil.TempFile("", "oauth2-proxy-test-alpha-config-file")
Expect(err).ToNot(HaveOccurred())
defer configFile.Close()
_, err = configFile.Write(config)
Expect(err).ToNot(HaveOccurred())
defer os.Remove(configFile.Name())
configFileName := configFile.Name()
By("Loading the example config")
into := &AlphaOptions{}
Expect(LoadYAML(configFileName, into)).To(Succeed())
flushInterval := Duration(500 * time.Millisecond)
Expect(into).To(Equal(&AlphaOptions{
Upstreams: []Upstream{
{
ID: "httpbin",
Path: "/",
URI: "http://httpbin",
FlushInterval: &flushInterval,
},
},
InjectRequestHeaders: []Header{
{
Name: "X-Forwarded-User",
Values: []HeaderValue{
{
ClaimSource: &ClaimSource{
Claim: "user",
},
},
},
},
},
InjectResponseHeaders: []Header{
{
Name: "X-Secret",
Values: []HeaderValue{
{
SecretSource: &SecretSource{
Value: []byte("secret"),
},
},
},
},
},
}))
})
})

View File

@ -65,22 +65,15 @@ type Options struct {
// TODO(JoelSpeed): Rename when legacy config is removed
UpstreamServers Upstreams `cfg:",internal"`
InjectRequestHeaders []Header `cfg:",internal"`
InjectResponseHeaders []Header `cfg:",internal"`
SkipAuthRegex []string `flag:"skip-auth-regex" cfg:"skip_auth_regex"`
SkipAuthRoutes []string `flag:"skip-auth-route" cfg:"skip_auth_routes"`
SkipAuthStripHeaders bool `flag:"skip-auth-strip-headers" cfg:"skip_auth_strip_headers"`
SkipJwtBearerTokens bool `flag:"skip-jwt-bearer-tokens" cfg:"skip_jwt_bearer_tokens"`
ExtraJwtIssuers []string `flag:"extra-jwt-issuers" cfg:"extra_jwt_issuers"`
PassBasicAuth bool `flag:"pass-basic-auth" cfg:"pass_basic_auth"`
SetBasicAuth bool `flag:"set-basic-auth" cfg:"set_basic_auth"`
PreferEmailToUser bool `flag:"prefer-email-to-user" cfg:"prefer_email_to_user"`
BasicAuthPassword string `flag:"basic-auth-password" cfg:"basic_auth_password"`
PassAccessToken bool `flag:"pass-access-token" cfg:"pass_access_token"`
SkipProviderButton bool `flag:"skip-provider-button" cfg:"skip_provider_button"`
PassUserHeaders bool `flag:"pass-user-headers" cfg:"pass_user_headers"`
SSLInsecureSkipVerify bool `flag:"ssl-insecure-skip-verify" cfg:"ssl_insecure_skip_verify"`
SetXAuthRequest bool `flag:"set-xauthrequest" cfg:"set_xauthrequest"`
SetAuthorization bool `flag:"set-authorization-header" cfg:"set_authorization_header"`
PassAuthorization bool `flag:"pass-authorization-header" cfg:"pass_authorization_header"`
SkipAuthPreflight bool `flag:"skip-auth-preflight" cfg:"skip_auth_preflight"`
// These options allow for other providers besides Google, with
@ -151,15 +144,7 @@ func NewOptions() *Options {
Cookie: cookieDefaults(),
Session: sessionOptionsDefaults(),
AzureTenant: "common",
SetXAuthRequest: false,
SkipAuthPreflight: false,
PassBasicAuth: true,
SetBasicAuth: false,
PassUserHeaders: true,
PassAccessToken: false,
SetAuthorization: false,
PassAuthorization: false,
PreferEmailToUser: false,
Prompt: "", // Change to "login" when ApprovalPrompt officially deprecated
ApprovalPrompt: "force",
UserIDClaim: "email",
@ -183,18 +168,8 @@ func NewFlagSet() *pflag.FlagSet {
flagSet.String("tls-cert-file", "", "path to certificate file")
flagSet.String("tls-key-file", "", "path to private key file")
flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"")
flagSet.Bool("set-xauthrequest", false, "set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode)")
flagSet.Bool("pass-basic-auth", true, "pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream")
flagSet.Bool("set-basic-auth", false, "set HTTP Basic Auth information in response (useful in Nginx auth_request mode)")
flagSet.Bool("prefer-email-to-user", false, "Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, eg. htaccess authentication. Used in conjunction with -pass-basic-auth and -pass-user-headers")
flagSet.Bool("pass-user-headers", true, "pass X-Forwarded-User and X-Forwarded-Email information to upstream")
flagSet.String("basic-auth-password", "", "the password to set when passing the HTTP Basic Auth header")
flagSet.Bool("pass-access-token", false, "pass OAuth access_token to upstream via X-Forwarded-Access-Token header")
flagSet.Bool("pass-authorization-header", false, "pass the Authorization Header to upstream")
flagSet.Bool("set-authorization-header", false, "set Authorization response headers (useful in Nginx auth_request mode)")
flagSet.StringSlice("skip-auth-regex", []string{}, "(DEPRECATED for --skip-auth-route) bypass authentication for requests path's that match (may be given multiple times)")
flagSet.StringSlice("skip-auth-route", []string{}, "bypass authentication for requests that match the method & path. Format: method=path_regex OR path_regex alone for all methods")
flagSet.Bool("skip-auth-strip-headers", false, "strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy for allowlisted requests (`--skip-auth-route`, `--skip-auth-regex`, `--skip-auth-preflight`, `--trusted-ip`)")
flagSet.Bool("skip-provider-button", false, "will skip sign-in-page to directly reach the next step: oauth/start")
flagSet.Bool("skip-auth-preflight", false, "will skip authentication for OPTIONS requests")
flagSet.Bool("ssl-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS providers")
@ -271,7 +246,6 @@ func NewFlagSet() *pflag.FlagSet {
flagSet.AddFlagSet(cookieFlagSet())
flagSet.AddFlagSet(loggingFlagSet())
flagSet.AddFlagSet(legacyUpstreamsFlagSet())
return flagSet
}

View File

@ -2,6 +2,11 @@ package options
import "time"
const (
// DefaultUpstreamFlushInterval is the default value for the Upstream FlushInterval.
DefaultUpstreamFlushInterval = 1 * time.Second
)
// Upstreams is a collection of definitions for upstream servers.
type Upstreams []Upstream
@ -10,11 +15,11 @@ type Upstreams []Upstream
type Upstream struct {
// ID should be a unique identifier for the upstream.
// This value is required for all upstreams.
ID string `json:"id"`
ID string `json:"id,omitempty"`
// Path is used to map requests to the upstream server.
// The closest match will take precedence and all Paths must be unique.
Path string `json:"path"`
Path string `json:"path,omitempty"`
// The URI of the upstream server. This may be an HTTP(S) server of a File
// based URL. It may include a path, in which case all requests will be served
@ -26,19 +31,19 @@ type Upstream struct {
// - file://host/path
// If the URI's path is "/base" and the incoming request was for "/dir",
// the upstream request will be for "/base/dir".
URI string `json:"uri"`
URI string `json:"uri,omitempty"`
// InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
// This option is insecure and will allow potential Man-In-The-Middle attacks
// betweem OAuth2 Proxy and the usptream server.
// Defaults to false.
InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify"`
InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"`
// Static will make all requests to this upstream have a static response.
// The response will have a body of "Authenticated" and a response code
// matching StaticCode.
// If StaticCode is not set, the response will return a 200 response.
Static bool `json:"static"`
Static bool `json:"static,omitempty"`
// StaticCode determines the response code for the Static response.
// This option can only be used with Static enabled.
@ -47,14 +52,14 @@ type Upstream struct {
// FlushInterval is the period between flushing the response buffer when
// streaming response from the upstream.
// Defaults to 1 second.
FlushInterval *time.Duration `json:"flushInterval,omitempty"`
FlushInterval *Duration `json:"flushInterval,omitempty"`
// PassHostHeader determines whether the request host header should be proxied
// to the upstream server.
// Defaults to true.
PassHostHeader *bool `json:"passHostHeader"`
PassHostHeader *bool `json:"passHostHeader,omitempty"`
// ProxyWebSockets enables proxying of websockets to upstream servers
// Defaults to true.
ProxyWebSockets *bool `json:"proxyWebSockets"`
ProxyWebSockets *bool `json:"proxyWebSockets,omitempty"`
}

View File

@ -1,7 +1,6 @@
package util
import (
"encoding/base64"
"errors"
"io/ioutil"
"os"
@ -13,9 +12,7 @@ import (
func GetSecretValue(source *options.SecretSource) ([]byte, error) {
switch {
case len(source.Value) > 0 && source.FromEnv == "" && source.FromFile == "":
value := make([]byte, base64.StdEncoding.DecodedLen(len(source.Value)))
decoded, err := base64.StdEncoding.Decode(value, source.Value)
return value[:decoded], err
return source.Value, nil
case len(source.Value) == 0 && source.FromEnv != "" && source.FromFile == "":
return []byte(os.Getenv(source.FromEnv)), nil
case len(source.Value) == 0 && source.FromEnv == "" && source.FromFile != "":

View File

@ -1,7 +1,6 @@
package util
import (
"encoding/base64"
"io/ioutil"
"os"
"path"
@ -31,20 +30,12 @@ var _ = Describe("GetSecretValue", func() {
os.RemoveAll(fileDir)
})
It("returns the correct value from base64", func() {
originalValue := []byte("secret-value-1")
b64Value := base64.StdEncoding.EncodeToString((originalValue))
// Once encoded, the originalValue could have a decoded length longer than
// its actual length, ensure we trim this.
// This assertion ensures we are testing the triming
Expect(len(originalValue)).To(BeNumerically("<", base64.StdEncoding.DecodedLen(len(b64Value))))
It("returns the correct value from the string value", func() {
value, err := GetSecretValue(&options.SecretSource{
Value: []byte(b64Value),
Value: []byte("secret-value-1"),
})
Expect(err).ToNot(HaveOccurred())
Expect(value).To(Equal(originalValue))
Expect(string(value)).To(Equal("secret-value-1"))
})
It("returns the correct value from the environment", func() {

View File

@ -1,87 +0,0 @@
package sessions
import (
"fmt"
"testing"
"time"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
"github.com/stretchr/testify/assert"
)
const LegacyV5TestSecret = "0123456789abcdefghijklmnopqrstuv"
// LegacyV5TestCase provides V5 JSON based test cases for legacy fallback code
type LegacyV5TestCase struct {
Input string
Error bool
Output *SessionState
}
// CreateLegacyV5TestCases makes various V5 JSON sessions as test cases
//
// Used for `apis/sessions/session_state_test.go` & `sessions/redis/redis_store_test.go`
//
// TODO: Remove when this is deprecated (likely V7)
func CreateLegacyV5TestCases(t *testing.T) (map[string]LegacyV5TestCase, encryption.Cipher, encryption.Cipher) {
created := time.Now()
createdJSON, err := created.MarshalJSON()
assert.NoError(t, err)
createdString := string(createdJSON)
e := time.Now().Add(time.Duration(1) * time.Hour)
eJSON, err := e.MarshalJSON()
assert.NoError(t, err)
eString := string(eJSON)
cfbCipher, err := encryption.NewCFBCipher([]byte(LegacyV5TestSecret))
assert.NoError(t, err)
legacyCipher := encryption.NewBase64Cipher(cfbCipher)
testCases := map[string]LegacyV5TestCase{
"User & email unencrypted": {
Input: `{"Email":"user@domain.com","User":"just-user"}`,
Error: true,
},
"Only email unencrypted": {
Input: `{"Email":"user@domain.com"}`,
Error: true,
},
"Just user unencrypted": {
Input: `{"User":"just-user"}`,
Error: true,
},
"User and Email unencrypted while rest is encrypted": {
Input: fmt.Sprintf(`{"Email":"user@domain.com","User":"just-user","AccessToken":"I6s+ml+/MldBMgHIiC35BTKTh57skGX24w==","IDToken":"xojNdyyjB1HgYWh6XMtXY/Ph5eCVxa1cNsklJw==","RefreshToken":"qEX0x6RmASxo4dhlBG6YuRs9Syn/e9sHu/+K","CreatedAt":%s,"ExpiresOn":%s}`, createdString, eString),
Error: true,
},
"Full session with cipher": {
Input: fmt.Sprintf(`{"Email":"FsKKYrTWZWrxSOAqA/fTNAUZS5QWCqOBjuAbBlbVOw==","User":"rT6JP3dxQhxUhkWrrd7yt6c1mDVyQCVVxw==","AccessToken":"I6s+ml+/MldBMgHIiC35BTKTh57skGX24w==","IDToken":"xojNdyyjB1HgYWh6XMtXY/Ph5eCVxa1cNsklJw==","RefreshToken":"qEX0x6RmASxo4dhlBG6YuRs9Syn/e9sHu/+K","CreatedAt":%s,"ExpiresOn":%s}`, createdString, eString),
Output: &SessionState{
Email: "user@domain.com",
User: "just-user",
AccessToken: "token1234",
IDToken: "rawtoken1234",
CreatedAt: &created,
ExpiresOn: &e,
RefreshToken: "refresh4321",
},
},
"Minimal session encrypted with cipher": {
Input: `{"Email":"EGTllJcOFC16b7LBYzLekaHAC5SMMSPdyUrg8hd25g==","User":"rT6JP3dxQhxUhkWrrd7yt6c1mDVyQCVVxw=="}`,
Output: &SessionState{
Email: "user@domain.com",
User: "just-user",
},
},
"Unencrypted User, Email and AccessToken": {
Input: `{"Email":"user@domain.com","User":"just-user","AccessToken":"X"}`,
Error: true,
},
"Unencrypted User, Email and IDToken": {
Input: `{"Email":"user@domain.com","User":"just-user","IDToken":"XXXX"}`,
Error: true,
},
}
return testCases, cfbCipher, legacyCipher
}

View File

@ -2,7 +2,6 @@ package sessions
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
@ -18,15 +17,17 @@ import (
// SessionState is used to store information about the currently authenticated user session
type SessionState struct {
AccessToken string `json:",omitempty" msgpack:"at,omitempty"`
IDToken string `json:",omitempty" msgpack:"it,omitempty"`
CreatedAt *time.Time `json:",omitempty" msgpack:"ca,omitempty"`
ExpiresOn *time.Time `json:",omitempty" msgpack:"eo,omitempty"`
RefreshToken string `json:",omitempty" msgpack:"rt,omitempty"`
Email string `json:",omitempty" msgpack:"e,omitempty"`
User string `json:",omitempty" msgpack:"u,omitempty"`
Groups []string `json:",omitempty" msgpack:"g,omitempty"`
PreferredUsername string `json:",omitempty" msgpack:"pu,omitempty"`
CreatedAt *time.Time `msgpack:"ca,omitempty"`
ExpiresOn *time.Time `msgpack:"eo,omitempty"`
AccessToken string `msgpack:"at,omitempty"`
IDToken string `msgpack:"it,omitempty"`
RefreshToken string `msgpack:"rt,omitempty"`
Email string `msgpack:"e,omitempty"`
User string `msgpack:"u,omitempty"`
Groups []string `msgpack:"g,omitempty"`
PreferredUsername string `msgpack:"pu,omitempty"`
}
// IsExpired checks whether the session has expired
@ -146,52 +147,6 @@ func DecodeSessionState(data []byte, c encryption.Cipher, compressed bool) (*Ses
return &ss, nil
}
// LegacyV5DecodeSessionState decodes a legacy JSON session cookie string into a SessionState
func LegacyV5DecodeSessionState(v string, c encryption.Cipher) (*SessionState, error) {
var ss SessionState
err := json.Unmarshal([]byte(v), &ss)
if err != nil {
return nil, fmt.Errorf("error unmarshalling session: %w", err)
}
for _, s := range []*string{
&ss.User,
&ss.Email,
&ss.PreferredUsername,
&ss.AccessToken,
&ss.IDToken,
&ss.RefreshToken,
} {
err := into(s, c.Decrypt)
if err != nil {
return nil, err
}
}
err = ss.validate()
if err != nil {
return nil, err
}
return &ss, nil
}
// codecFunc is a function that takes a []byte and encodes/decodes it
type codecFunc func([]byte) ([]byte, error)
func into(s *string, f codecFunc) error {
// Do not encrypt/decrypt nil or empty strings
if s == nil || *s == "" {
return nil
}
d, err := f([]byte(*s))
if err != nil {
return err
}
*s = string(d)
return nil
}
// lz4Compress compresses with LZ4
//
// The Compress:Decompress ratio is 1:Many. LZ4 gives fastest decompress speeds

View File

@ -4,7 +4,6 @@ import (
"crypto/rand"
"fmt"
"io"
mathrand "math/rand"
"testing"
"time"
@ -257,78 +256,6 @@ func TestEncodeAndDecodeSessionState(t *testing.T) {
}
}
// TestLegacyV5DecodeSessionState confirms V5 JSON sessions decode
//
// TODO: Remove when this is deprecated (likely V7)
func TestLegacyV5DecodeSessionState(t *testing.T) {
testCases, cipher, legacyCipher := CreateLegacyV5TestCases(t)
for testName, tc := range testCases {
t.Run(testName, func(t *testing.T) {
// Legacy sessions fail in DecodeSessionState which results in
// the fallback to LegacyV5DecodeSessionState
_, err := DecodeSessionState([]byte(tc.Input), cipher, false)
assert.Error(t, err)
_, err = DecodeSessionState([]byte(tc.Input), cipher, true)
assert.Error(t, err)
ss, err := LegacyV5DecodeSessionState(tc.Input, legacyCipher)
if tc.Error {
assert.Error(t, err)
assert.Nil(t, ss)
return
}
assert.NoError(t, err)
compareSessionStates(t, tc.Output, ss)
})
}
}
// Test_into tests the into helper function used in LegacyV5DecodeSessionState
//
// TODO: Remove when this is deprecated (likely V7)
func Test_into(t *testing.T) {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// Test all 3 valid AES sizes
for _, secretSize := range []int{16, 24, 32} {
t.Run(fmt.Sprintf("%d", secretSize), func(t *testing.T) {
secret := make([]byte, secretSize)
_, err := io.ReadFull(rand.Reader, secret)
assert.Equal(t, nil, err)
cfb, err := encryption.NewCFBCipher(secret)
assert.NoError(t, err)
c := encryption.NewBase64Cipher(cfb)
// Check no errors with empty or nil strings
empty := ""
assert.Equal(t, nil, into(&empty, c.Encrypt))
assert.Equal(t, nil, into(&empty, c.Decrypt))
assert.Equal(t, nil, into(nil, c.Encrypt))
assert.Equal(t, nil, into(nil, c.Decrypt))
// Test various sizes tokens might be
for _, dataSize := range []int{10, 100, 1000, 5000, 10000} {
t.Run(fmt.Sprintf("%d", dataSize), func(t *testing.T) {
b := make([]byte, dataSize)
for i := range b {
b[i] = charset[mathrand.Intn(len(charset))]
}
data := string(b)
originalData := data
assert.Equal(t, nil, into(&data, c.Encrypt))
assert.NotEqual(t, originalData, data)
assert.Equal(t, nil, into(&data, c.Decrypt))
assert.Equal(t, originalData, data)
})
}
})
}
}
func compareSessionStates(t *testing.T, expected *SessionState, actual *SessionState) {
if expected.CreatedAt != nil {
assert.NotNil(t, actual.CreatedAt)

View File

@ -49,14 +49,14 @@ var _ = Describe("Injector Suite", func() {
},
expectedErr: nil,
}),
Entry("with a static valued header from base64", newInjectorTableInput{
Entry("with a static valued header from string", newInjectorTableInput{
headers: []options.Header{
{
Name: "Secret",
Values: []options.HeaderValue{
{
SecretSource: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("super-secret"))),
Value: []byte("super-secret"),
},
},
},
@ -200,7 +200,7 @@ var _ = Describe("Injector Suite", func() {
ClaimSource: &options.ClaimSource{
Claim: "user",
BasicAuthPassword: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))),
Value: []byte("basic-password"),
},
},
},
@ -349,7 +349,7 @@ var _ = Describe("Injector Suite", func() {
ClaimSource: &options.ClaimSource{
Claim: "user",
BasicAuthPassword: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))),
Value: []byte("basic-password"),
},
},
},
@ -380,17 +380,17 @@ var _ = Describe("Injector Suite", func() {
Values: []options.HeaderValue{
{
SecretSource: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("major=1"))),
Value: []byte("major=1"),
},
},
{
SecretSource: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("minor=2"))),
Value: []byte("minor=2"),
},
},
{
SecretSource: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("patch=3"))),
Value: []byte("patch=3"),
},
},
},

View File

@ -162,7 +162,7 @@ func (l *Logger) Output(lvl Level, calldepth int, message string) {
if !l.stdEnabled {
return
}
msg := l.formatLogMessage(calldepth, message)
msg := l.formatLogMessage(calldepth+1, message)
var err error
switch lvl {

View File

@ -1,30 +1,21 @@
package middleware
import (
"context"
"errors"
"fmt"
"net/http"
"regexp"
"github.com/coreos/go-oidc"
"github.com/justinas/alice"
middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
k8serrors "k8s.io/apimachinery/pkg/util/errors"
)
const jwtRegexFormat = `^eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+$`
func NewJwtSessionLoader(sessionLoaders []middlewareapi.TokenToSessionLoader) alice.Constructor {
for i, loader := range sessionLoaders {
if loader.TokenToSession == nil {
sessionLoaders[i] = middlewareapi.TokenToSessionLoader{
Verifier: loader.Verifier,
TokenToSession: createSessionStateFromBearerToken,
}
}
}
const jwtRegexFormat = `^ey[IJ][a-zA-Z0-9_-]*\.ey[IJ][a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+$`
func NewJwtSessionLoader(sessionLoaders []middlewareapi.TokenToSessionFunc) alice.Constructor {
js := &jwtSessionLoader{
jwtRegex: regexp.MustCompile(jwtRegexFormat),
sessionLoaders: sessionLoaders,
@ -36,7 +27,7 @@ func NewJwtSessionLoader(sessionLoaders []middlewareapi.TokenToSessionLoader) al
// Authorization headers.
type jwtSessionLoader struct {
jwtRegex *regexp.Regexp
sessionLoaders []middlewareapi.TokenToSessionLoader
sessionLoaders []middlewareapi.TokenToSessionFunc
}
// loadSession attempts to load a session from a JWT stored in an Authorization
@ -75,24 +66,27 @@ func (j *jwtSessionLoader) getJwtSession(req *http.Request) (*sessionsapi.Sessio
return nil, nil
}
rawBearerToken, err := j.findBearerTokenFromHeader(auth)
token, err := j.findTokenFromHeader(auth)
if err != nil {
return nil, err
}
// This leading error message only occurs if all session loaders fail
errs := []error{errors.New("unable to verify bearer token")}
for _, loader := range j.sessionLoaders {
bearerToken, err := loader.Verifier.Verify(req.Context(), rawBearerToken)
if err == nil {
// The token was verified, convert it to a session
return loader.TokenToSession(req.Context(), rawBearerToken, bearerToken)
session, err := loader(req.Context(), token)
if err != nil {
errs = append(errs, err)
continue
}
return session, nil
}
return nil, fmt.Errorf("unable to verify jwt token: %q", req.Header.Get("Authorization"))
return nil, k8serrors.NewAggregate(errs)
}
// findBearerTokenFromHeader finds a valid JWT token from the Authorization header of a given request.
func (j *jwtSessionLoader) findBearerTokenFromHeader(header string) (string, error) {
// findTokenFromHeader finds a valid JWT token from the Authorization header of a given request.
func (j *jwtSessionLoader) findTokenFromHeader(header string) (string, error) {
tokenType, token, err := splitAuthHeader(header)
if err != nil {
return "", err
@ -132,38 +126,3 @@ func (j *jwtSessionLoader) getBasicToken(token string) (string, error) {
return "", fmt.Errorf("invalid basic auth token found in authorization header")
}
// createSessionStateFromBearerToken is a default implementation for converting
// a JWT into a session state.
func createSessionStateFromBearerToken(ctx context.Context, rawIDToken string, idToken *oidc.IDToken) (*sessionsapi.SessionState, error) {
var claims struct {
Subject string `json:"sub"`
Email string `json:"email"`
Verified *bool `json:"email_verified"`
PreferredUsername string `json:"preferred_username"`
}
if err := idToken.Claims(&claims); err != nil {
return nil, fmt.Errorf("failed to parse bearer token claims: %v", err)
}
if claims.Email == "" {
claims.Email = claims.Subject
}
if claims.Verified != nil && !*claims.Verified {
return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email)
}
newSession := &sessionsapi.SessionState{
Email: claims.Email,
User: claims.Subject,
PreferredUsername: claims.PreferredUsername,
AccessToken: rawIDToken,
IDToken: rawIDToken,
RefreshToken: "",
ExpiresOn: &idToken.Expiry,
}
return newSession, nil
}

View File

@ -20,12 +20,13 @@ import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
k8serrors "k8s.io/apimachinery/pkg/util/errors"
)
type noOpKeySet struct {
}
func (noOpKeySet) VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) {
func (noOpKeySet) VerifySignature(_ context.Context, jwt string) (payload []byte, err error) {
splitStrings := strings.Split(jwt, ".")
payloadString := splitStrings[1]
return base64.RawURLEncoding.DecodeString(payloadString)
@ -73,13 +74,18 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
const validToken = "eyJfoobar.eyJfoobar.12345asdf"
Context("JwtSessionLoader", func() {
var verifier *oidc.IDTokenVerifier
var verifier middlewareapi.VerifyFunc
const nonVerifiedToken = validToken
BeforeEach(func() {
keyset := noOpKeySet{}
verifier = oidc.NewVerifier("https://issuer.example.com", keyset,
&oidc.Config{ClientID: "https://test.myapp.com", SkipExpiryCheck: true})
verifier = oidc.NewVerifier(
"https://issuer.example.com",
noOpKeySet{},
&oidc.Config{
ClientID: "https://test.myapp.com",
SkipExpiryCheck: true,
},
).Verify
})
type jwtSessionLoaderTableInput struct {
@ -102,10 +108,8 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
rw := httptest.NewRecorder()
sessionLoaders := []middlewareapi.TokenToSessionLoader{
{
Verifier: verifier,
},
sessionLoaders := []middlewareapi.TokenToSessionFunc{
middlewareapi.CreateTokenToSessionFunc(verifier),
}
// Create the handler with a next handler that will capture the session
@ -167,17 +171,19 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
const nonVerifiedToken = validToken
BeforeEach(func() {
keyset := noOpKeySet{}
verifier := oidc.NewVerifier("https://issuer.example.com", keyset,
&oidc.Config{ClientID: "https://test.myapp.com", SkipExpiryCheck: true})
verifier := oidc.NewVerifier(
"https://issuer.example.com",
noOpKeySet{},
&oidc.Config{
ClientID: "https://test.myapp.com",
SkipExpiryCheck: true,
},
).Verify
j = &jwtSessionLoader{
jwtRegex: regexp.MustCompile(jwtRegexFormat),
sessionLoaders: []middlewareapi.TokenToSessionLoader{
{
Verifier: verifier,
TokenToSession: createSessionStateFromBearerToken,
},
sessionLoaders: []middlewareapi.TokenToSessionFunc{
middlewareapi.CreateTokenToSessionFunc(verifier),
},
}
})
@ -218,7 +224,10 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
}),
Entry("Bearer <nonVerifiedToken>", getJWTSessionTableInput{
authorizationHeader: fmt.Sprintf("Bearer %s", nonVerifiedToken),
expectedErr: errors.New("unable to verify jwt token: \"Bearer eyJfoobar.eyJfoobar.12345asdf\""),
expectedErr: k8serrors.NewAggregate([]error{
errors.New("unable to verify bearer token"),
errors.New("oidc: malformed jwt: illegal base64 data at input byte 8"),
}),
expectedSession: nil,
}),
Entry("Bearer <verifiedToken>", getJWTSessionTableInput{
@ -228,7 +237,10 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
}),
Entry("Basic Base64(<nonVerifiedToken>:) (No password)", getJWTSessionTableInput{
authorizationHeader: "Basic ZXlKZm9vYmFyLmV5SmZvb2Jhci4xMjM0NWFzZGY6",
expectedErr: errors.New("unable to verify jwt token: \"Basic ZXlKZm9vYmFyLmV5SmZvb2Jhci4xMjM0NWFzZGY6\""),
expectedErr: k8serrors.NewAggregate([]error{
errors.New("unable to verify bearer token"),
errors.New("oidc: malformed jwt: illegal base64 data at input byte 8"),
}),
expectedSession: nil,
}),
Entry("Basic Base64(<verifiedToken>:x-oauth-basic) (Sentinel password)", getJWTSessionTableInput{
@ -239,7 +251,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
)
})
Context("findBearerTokenFromHeader", func() {
Context("findTokenFromHeader", func() {
var j *jwtSessionLoader
BeforeEach(func() {
@ -256,7 +268,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
DescribeTable("with a header",
func(in findBearerTokenFromHeaderTableInput) {
token, err := j.findBearerTokenFromHeader(in.header)
token, err := j.findTokenFromHeader(in.header)
if in.expectedErr != nil {
Expect(err).To(MatchError(in.expectedErr))
} else {
@ -381,7 +393,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
)
})
Context("createSessionStateFromBearerToken", func() {
Context("CreateTokenToSessionFunc", func() {
ctx := context.Background()
expiresFuture := time.Now().Add(time.Duration(5) * time.Minute)
verified := true
@ -393,7 +405,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
jwt.StandardClaims
}
type createSessionStateTableInput struct {
type tokenToSessionTableInput struct {
idToken idTokenClaims
expectedErr error
expectedUser string
@ -402,24 +414,27 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
}
DescribeTable("when creating a session from an IDToken",
func(in createSessionStateTableInput) {
verifier := oidc.NewVerifier(
func(in tokenToSessionTableInput) {
verifier := func(ctx context.Context, token string) (*oidc.IDToken, error) {
oidcVerifier := oidc.NewVerifier(
"https://issuer.example.com",
noOpKeySet{},
&oidc.Config{ClientID: "asdf1234"},
)
idToken, err := oidcVerifier.Verify(ctx, token)
Expect(err).ToNot(HaveOccurred())
return idToken, nil
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
Expect(err).ToNot(HaveOccurred())
rawIDToken, err := jwt.NewWithClaims(jwt.SigningMethodRS256, in.idToken).SignedString(key)
Expect(err).ToNot(HaveOccurred())
// Pass to a dummy Verifier to get an oidc.IDToken from the rawIDToken for our actual test below
idToken, err := verifier.Verify(context.Background(), rawIDToken)
Expect(err).ToNot(HaveOccurred())
session, err := createSessionStateFromBearerToken(ctx, rawIDToken, idToken)
session, err := middlewareapi.CreateTokenToSessionFunc(verifier)(ctx, rawIDToken)
if in.expectedErr != nil {
Expect(err).To(MatchError(in.expectedErr))
Expect(session).To(BeNil())
@ -435,7 +450,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
Expect(session.RefreshToken).To(BeEmpty())
Expect(session.PreferredUsername).To(BeEmpty())
},
Entry("with no email", createSessionStateTableInput{
Entry("with no email", tokenToSessionTableInput{
idToken: idTokenClaims{
StandardClaims: jwt.StandardClaims{
Audience: "asdf1234",
@ -452,7 +467,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
expectedEmail: "123456789",
expectedExpires: &expiresFuture,
}),
Entry("with a verified email", createSessionStateTableInput{
Entry("with a verified email", tokenToSessionTableInput{
idToken: idTokenClaims{
StandardClaims: jwt.StandardClaims{
Audience: "asdf1234",
@ -471,7 +486,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=`
expectedEmail: "foo@example.com",
expectedExpires: &expiresFuture,
}),
Entry("with a non-verified email", createSessionStateTableInput{
Entry("with a non-verified email", tokenToSessionTableInput{
idToken: idTokenClaims{
StandardClaims: jwt.StandardClaims{
Audience: "asdf1234",

View File

@ -60,7 +60,7 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
return nil, errors.New("cookie signature not valid")
}
session, err := sessionFromCookie(val, s.CookieCipher)
session, err := sessions.DecodeSessionState(val, s.CookieCipher, true)
if err != nil {
return nil, err
}
@ -98,20 +98,6 @@ func (s *SessionStore) cookieForSession(ss *sessions.SessionState) ([]byte, erro
return ss.EncodeSessionState(s.CookieCipher, true)
}
// sessionFromCookie deserializes a session from a cookie value
func sessionFromCookie(v []byte, c encryption.Cipher) (s *sessions.SessionState, err error) {
ss, err := sessions.DecodeSessionState(v, c, true)
// If anything fails (Decrypt, LZ4, MessagePack), try legacy JSON decode
// LZ4 will likely fail for wrong header after AES-CFB spits out garbage
// data from trying to decrypt JSON it things is ciphertext
if err != nil {
// Legacy used Base64 + AES CFB
legacyCipher := encryption.NewBase64Cipher(c)
return sessions.LegacyV5DecodeSessionState(string(v), legacyCipher)
}
return ss, nil
}
// setSessionCookie adds the user's session cookie to the response
func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Request, val []byte, created time.Time) error {
cookies, err := s.makeSessionCookie(req, val, created)

View File

@ -2,7 +2,6 @@ package persistence
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
@ -123,8 +122,6 @@ func (t *ticket) saveSession(s *sessions.SessionState, saver saveFunc) error {
// loadSession loads a session from the disk store via the passed loadFunc
// using the ticket.id as the key. It then decodes the SessionState using
// ticket.secret to make the AES-GCM cipher.
//
// TODO (@NickMeves): Remove legacyV5LoadSession support in V7
func (t *ticket) loadSession(loader loadFunc) (*sessions.SessionState, error) {
ciphertext, err := loader(t.id)
if err != nil {
@ -134,11 +131,8 @@ func (t *ticket) loadSession(loader loadFunc) (*sessions.SessionState, error) {
if err != nil {
return nil, err
}
ss, err := sessions.DecodeSessionState(ciphertext, c, false)
if err != nil {
return t.legacyV5LoadSession(ciphertext)
}
return ss, nil
return sessions.DecodeSessionState(ciphertext, c, false)
}
// clearSession uses the passed clearFunc to delete a session stored with a
@ -203,28 +197,3 @@ func (t *ticket) makeCipher() (encryption.Cipher, error) {
}
return c, nil
}
// legacyV5LoadSession loads a Redis session created in V5 with historical logic
//
// TODO (@NickMeves): Remove in V7
func (t *ticket) legacyV5LoadSession(resultBytes []byte) (*sessions.SessionState, error) {
block, err := aes.NewCipher(t.secret)
if err != nil {
return nil, fmt.Errorf("failed to create a legacy AES-CFB cipher from the ticket secret: %v", err)
}
stream := cipher.NewCFBDecrypter(block, t.secret)
stream.XORKeyStream(resultBytes, resultBytes)
cfbCipher, err := encryption.NewCFBCipher(encryption.SecretBytes(t.options.Secret))
if err != nil {
return nil, err
}
legacyCipher := encryption.NewBase64Cipher(cfbCipher)
session, err := sessions.LegacyV5DecodeSessionState(string(resultBytes), legacyCipher)
if err != nil {
return nil, err
}
return session, nil
}

View File

@ -1,14 +1,9 @@
package persistence
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"testing"
"time"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
@ -153,64 +148,3 @@ var _ = Describe("Session Ticket Tests", func() {
})
})
})
// TestLegacyV5DecodeSession tests the fallback to LegacyV5DecodeSession
// when a V5 encoded session is in Redis
//
// TODO (@NickMeves): Remove when this is deprecated (likely V7)
func Test_legacyV5LoadSession(t *testing.T) {
testCases, _, _ := sessions.CreateLegacyV5TestCases(t)
for testName, tc := range testCases {
t.Run(testName, func(t *testing.T) {
g := NewWithT(t)
secret := make([]byte, aes.BlockSize)
_, err := io.ReadFull(rand.Reader, secret)
g.Expect(err).ToNot(HaveOccurred())
tckt := &ticket{
secret: secret,
options: &options.Cookie{
Secret: base64.RawURLEncoding.EncodeToString([]byte(sessions.LegacyV5TestSecret)),
},
}
encrypted, err := legacyStoreValue(tc.Input, tckt.secret)
g.Expect(err).ToNot(HaveOccurred())
ss, err := tckt.legacyV5LoadSession(encrypted)
if tc.Error {
g.Expect(err).To(HaveOccurred())
g.Expect(ss).To(BeNil())
return
}
g.Expect(err).ToNot(HaveOccurred())
// Compare sessions without *time.Time fields
exp := *tc.Output
exp.CreatedAt = nil
exp.ExpiresOn = nil
act := *ss
act.CreatedAt = nil
act.ExpiresOn = nil
g.Expect(exp).To(Equal(act))
})
}
}
// legacyStoreValue implements the legacy V5 Redis persistence AES-CFB value encryption
//
// TODO (@NickMeves): Remove when this is deprecated (likely V7)
func legacyStoreValue(value string, ticketSecret []byte) ([]byte, error) {
ciphertext := make([]byte, len(value))
block, err := aes.NewCipher(ticketSecret)
if err != nil {
return nil, fmt.Errorf("error initiating cipher block: %v", err)
}
// Use secret as the Initialization Vector too, because each entry has it's own key
stream := cipher.NewCFBEncrypter(block, ticketSecret)
stream.XORKeyStream(ciphertext, []byte(value))
return ciphertext, nil
}

View File

@ -6,7 +6,6 @@ import (
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/mbland/hmacauth"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
@ -98,9 +97,9 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr
// Configure options on the SingleHostReverseProxy
if upstream.FlushInterval != nil {
proxy.FlushInterval = *upstream.FlushInterval
proxy.FlushInterval = upstream.FlushInterval.Duration()
} else {
proxy.FlushInterval = 1 * time.Second
proxy.FlushInterval = options.DefaultUpstreamFlushInterval
}
// InsecureSkipVerify is a configurable option we allow

View File

@ -22,8 +22,8 @@ import (
var _ = Describe("HTTP Upstream Suite", func() {
const flushInterval5s = 5 * time.Second
const flushInterval1s = 1 * time.Second
const flushInterval5s = options.Duration(5 * time.Second)
const flushInterval1s = options.Duration(1 * time.Second)
truth := true
falsum := false
@ -52,7 +52,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
rw := httptest.NewRecorder()
flush := 1 * time.Second
flush := options.Duration(1 * time.Second)
upstream := options.Upstream{
ID: in.id,
@ -258,7 +258,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
req := httptest.NewRequest("", "http://example.localhost/foo", nil)
rw := httptest.NewRecorder()
flush := 1 * time.Second
flush := options.Duration(1 * time.Second)
upstream := options.Upstream{
ID: "noPassHost",
PassHostHeader: &falsum,
@ -290,7 +290,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
type newUpstreamTableInput struct {
proxyWebSockets bool
flushInterval time.Duration
flushInterval options.Duration
skipVerify bool
sigData *options.SignatureData
errorHandler func(http.ResponseWriter, *http.Request, error)
@ -319,7 +319,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy)
Expect(ok).To(BeTrue())
Expect(proxy.FlushInterval).To(Equal(in.flushInterval))
Expect(proxy.FlushInterval).To(Equal(in.flushInterval.Duration()))
Expect(proxy.ErrorHandler != nil).To(Equal(in.errorHandler != nil))
if in.skipVerify {
Expect(proxy.Transport).To(Equal(&http.Transport{
@ -370,7 +370,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
var proxyServer *httptest.Server
BeforeEach(func() {
flush := 1 * time.Second
flush := options.Duration(1 * time.Second)
upstream := options.Upstream{
ID: "websocketProxy",
PassHostHeader: &truth,

37
pkg/validation/common.go Normal file
View File

@ -0,0 +1,37 @@
package validation
import (
"fmt"
"os"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
)
const multipleValuesForSecretSource = "multiple values specified for secret source: specify either value, fromEnv of fromFile"
func validateSecretSource(source options.SecretSource) string {
switch {
case len(source.Value) > 0 && source.FromEnv == "" && source.FromFile == "":
return ""
case len(source.Value) == 0 && source.FromEnv != "" && source.FromFile == "":
return validateSecretSourceEnv(source.FromEnv)
case len(source.Value) == 0 && source.FromEnv == "" && source.FromFile != "":
return validateSecretSourceFile(source.FromFile)
default:
return multipleValuesForSecretSource
}
}
func validateSecretSourceEnv(key string) string {
if value := os.Getenv(key); value == "" {
return fmt.Sprintf("error loading secret from environent: no value for for key %q", key)
}
return ""
}
func validateSecretSourceFile(path string) string {
if _, err := os.Stat(path); err != nil {
return fmt.Sprintf("error loadig secret from file: %v", err)
}
return ""
}

View File

@ -0,0 +1,129 @@
package validation
import (
"io/ioutil"
"os"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
var _ = Describe("Common", func() {
var validSecretSourceValue []byte
const validSecretSourceEnv = "OAUTH2_PROXY_TEST_SECRET_SOURCE_ENV"
var validSecretSourceFile string
BeforeEach(func() {
validSecretSourceValue = []byte("This is a secret source value")
Expect(os.Setenv(validSecretSourceEnv, "This is a secret source env")).To(Succeed())
tmp, err := ioutil.TempFile("", "oauth2-proxy-secret-source-test")
Expect(err).ToNot(HaveOccurred())
defer tmp.Close()
_, err = tmp.Write([]byte("This is a secret source file"))
Expect(err).ToNot(HaveOccurred())
validSecretSourceFile = tmp.Name()
})
AfterEach(func() {
Expect(os.Unsetenv(validSecretSourceEnv)).To(Succeed())
Expect(os.Remove(validSecretSourceFile)).To(Succeed())
})
type validateSecretSourceTableInput struct {
source func() options.SecretSource
expectedMsg string
}
DescribeTable("validateSecretSource should",
func(in validateSecretSourceTableInput) {
Expect(validateSecretSource(in.source())).To(Equal(in.expectedMsg))
},
Entry("with no entries", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{}
},
expectedMsg: multipleValuesForSecretSource,
}),
Entry("with a Value and FromEnv", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
Value: validSecretSourceValue,
FromEnv: validSecretSourceEnv,
}
},
expectedMsg: multipleValuesForSecretSource,
}),
Entry("with a Value and FromFile", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
Value: validSecretSourceValue,
FromFile: validSecretSourceFile,
}
},
expectedMsg: multipleValuesForSecretSource,
}),
Entry("with FromEnv and FromFile", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
FromEnv: validSecretSourceEnv,
FromFile: validSecretSourceFile,
}
},
expectedMsg: multipleValuesForSecretSource,
}),
Entry("with a Value, FromEnv and FromFile", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
Value: validSecretSourceValue,
FromEnv: validSecretSourceEnv,
FromFile: validSecretSourceFile,
}
},
expectedMsg: multipleValuesForSecretSource,
}),
Entry("with a valid Value", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
Value: validSecretSourceValue,
}
},
expectedMsg: "",
}),
Entry("with a valid FromEnv", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
FromEnv: validSecretSourceEnv,
}
},
expectedMsg: "",
}),
Entry("with a valid FromFile", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
FromFile: validSecretSourceFile,
}
},
expectedMsg: "",
}),
Entry("with an invalid FromEnv", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
FromEnv: "INVALID_ENV",
}
},
expectedMsg: "error loading secret from environent: no value for for key \"INVALID_ENV\"",
}),
Entry("with an invalid FromFile", validateSecretSourceTableInput{
source: func() options.SecretSource {
return options.SecretSource{
FromFile: "invalidFile",
}
},
expectedMsg: "error loadig secret from file: stat invalidFile: no such file or directory",
}),
)
})

63
pkg/validation/header.go Normal file
View File

@ -0,0 +1,63 @@
package validation
import (
"fmt"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
)
func validateHeaders(headers []options.Header) []string {
msgs := []string{}
names := make(map[string]struct{})
for _, header := range headers {
msgs = append(msgs, validateHeader(header, names)...)
}
return msgs
}
func validateHeader(header options.Header, names map[string]struct{}) []string {
msgs := []string{}
if header.Name == "" {
msgs = append(msgs, "header has empty name: names are required for all headers")
}
if _, ok := names[header.Name]; ok {
msgs = append(msgs, fmt.Sprintf("multiple headers found with name %q: header names must be unique", header.Name))
}
names[header.Name] = struct{}{}
for _, value := range header.Values {
msgs = append(msgs,
prefixValues(fmt.Sprintf("invalid header %q: invalid values: ", header.Name),
validateHeaderValue(header.Name, value)...,
)...,
)
}
return msgs
}
func validateHeaderValue(name string, value options.HeaderValue) []string {
switch {
case value.SecretSource != nil && value.ClaimSource == nil:
return []string{validateSecretSource(*value.SecretSource)}
case value.SecretSource == nil && value.ClaimSource != nil:
return validateHeaderValueClaimSource(*value.ClaimSource)
default:
return []string{"header value has multiple entries: only one entry per value is allowed"}
}
}
func validateHeaderValueClaimSource(claim options.ClaimSource) []string {
msgs := []string{}
if claim.Claim == "" {
msgs = append(msgs, "claim should not be empty")
}
if claim.BasicAuthPassword != nil {
msgs = append(msgs, prefixValues("invalid basicAuthPassword: ", validateSecretSource(*claim.BasicAuthPassword))...)
}
return msgs
}

View File

@ -0,0 +1,164 @@
package validation
import (
"encoding/base64"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
)
var _ = Describe("Headers", func() {
type validateHeaderTableInput struct {
headers []options.Header
expectedMsgs []string
}
validHeader1 := options.Header{
Name: "X-Email",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
},
},
},
}
validHeader2 := options.Header{
Name: "X-Forwarded-Auth",
Values: []options.HeaderValue{
{
SecretSource: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))),
},
},
},
}
validHeader3 := options.Header{
Name: "Authorization",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "email",
BasicAuthPassword: &options.SecretSource{
Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))),
},
},
},
},
}
DescribeTable("validateHeaders",
func(in validateHeaderTableInput) {
Expect(validateHeaders(in.headers)).To(ConsistOf(in.expectedMsgs))
},
Entry("with no headers", validateHeaderTableInput{
headers: []options.Header{},
expectedMsgs: []string{},
}),
Entry("with valid headers", validateHeaderTableInput{
headers: []options.Header{
validHeader1,
validHeader2,
validHeader3,
},
expectedMsgs: []string{},
}),
Entry("with multiple headers with the same name", validateHeaderTableInput{
headers: []options.Header{
validHeader1,
validHeader1,
validHeader2,
validHeader2,
},
expectedMsgs: []string{
"multiple headers found with name \"X-Email\": header names must be unique",
"multiple headers found with name \"X-Forwarded-Auth\": header names must be unique",
},
}),
Entry("with an unamed header", validateHeaderTableInput{
headers: []options.Header{
{},
validHeader2,
},
expectedMsgs: []string{
"header has empty name: names are required for all headers",
},
}),
Entry("with a header which has a claim and secret source", validateHeaderTableInput{
headers: []options.Header{
{
Name: "With-Claim-And-Secret",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{},
SecretSource: &options.SecretSource{},
},
},
},
validHeader1,
},
expectedMsgs: []string{
"invalid header \"With-Claim-And-Secret\": invalid values: header value has multiple entries: only one entry per value is allowed",
},
}),
Entry("with a header which has a claim without a claim", validateHeaderTableInput{
headers: []options.Header{
{
Name: "Without-Claim",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Prefix: "prefix",
},
},
},
},
validHeader3,
},
expectedMsgs: []string{
"invalid header \"Without-Claim\": invalid values: claim should not be empty",
},
}),
Entry("with a header with invalid secret source", validateHeaderTableInput{
headers: []options.Header{
{
Name: "With-Invalid-Secret",
Values: []options.HeaderValue{
{
SecretSource: &options.SecretSource{},
},
},
},
validHeader1,
},
expectedMsgs: []string{
"invalid header \"With-Invalid-Secret\": invalid values: multiple values specified for secret source: specify either value, fromEnv of fromFile",
},
}),
Entry("with a header with invalid basicAuthPassword source", validateHeaderTableInput{
headers: []options.Header{
{
Name: "With-Invalid-Basic-Auth",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "user",
BasicAuthPassword: &options.SecretSource{
FromEnv: "UNKNOWN_ENV",
},
},
},
},
},
validHeader1,
},
expectedMsgs: []string{
"invalid header \"With-Invalid-Basic-Auth\": invalid values: invalid basicAuthPassword: error loading secret from environent: no value for for key \"UNKNOWN_ENV\"",
},
}),
)
})

View File

@ -28,6 +28,8 @@ func Validate(o *options.Options) error {
msgs := validateCookie(o.Cookie)
msgs = append(msgs, validateSessionCookieMinimal(o)...)
msgs = append(msgs, validateRedisSessionStore(o)...)
msgs = append(msgs, prefixValues("injectRequestHeaders: ", validateHeaders(o.InjectRequestHeaders)...)...)
msgs = append(msgs, prefixValues("injectRespeonseHeaders: ", validateHeaders(o.InjectRequestHeaders)...)...)
if o.SSLInsecureSkipVerify {
// InsecureSkipVerify is a configurable option we allow
@ -71,10 +73,6 @@ func Validate(o *options.Options) error {
"\n use email-domain=* to authorize all email addresses")
}
if o.SetBasicAuth && o.SetAuthorization {
msgs = append(msgs, "mutually exclusive: set-basic-auth and set-authorization-header can not both be true")
}
if o.OIDCIssuerURL != "" {
ctx := context.Background()
@ -159,10 +157,6 @@ func Validate(o *options.Options) error {
}
}
if o.PreferEmailToUser && !o.PassBasicAuth && !o.PassUserHeaders {
msgs = append(msgs, "PreferEmailToUser should only be used with PassBasicAuth or PassUserHeaders")
}
if o.SkipJwtBearerTokens {
// Configure extra issuers
if len(o.ExtraJwtIssuers) > 0 {
@ -239,7 +233,18 @@ func parseProviderInfo(o *options.Options, msgs []string) []string {
p.ValidateURL, msgs = parseURL(o.ValidateURL, "validate", msgs)
p.ProtectedResource, msgs = parseURL(o.ProtectedResource, "resource", msgs)
o.SetProvider(providers.New(o.ProviderType, p))
// Make the OIDC Verifier accessible to all providers that can support it
p.Verifier = o.GetOIDCVerifier()
p.SetAllowedGroups(o.AllowedGroups)
provider := providers.New(o.ProviderType, p)
if provider == nil {
msgs = append(msgs, fmt.Sprintf("invalid setting: provider '%s' is not available", o.ProviderType))
return msgs
}
o.SetProvider(provider)
switch p := o.GetProvider().(type) {
case *providers.AzureProvider:
p.Configure(o.AzureTenant)
@ -255,7 +260,13 @@ func parseProviderInfo(o *options.Options, msgs []string) []string {
if err != nil {
msgs = append(msgs, "invalid Google credentials file: "+o.GoogleServiceAccountJSON)
} else {
p.SetGroupRestriction(o.GoogleGroups, o.GoogleAdminEmail, file)
groups := o.AllowedGroups
// Backwards compatibility with `--google-group` option
if len(o.GoogleGroups) > 0 {
groups = o.GoogleGroups
p.SetAllowedGroups(groups)
}
p.SetGroupRestriction(groups, o.GoogleAdminEmail, file)
}
}
case *providers.BitbucketProvider:
@ -265,18 +276,14 @@ func parseProviderInfo(o *options.Options, msgs []string) []string {
p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
p.UserIDClaim = o.UserIDClaim
p.GroupsClaim = o.OIDCGroupsClaim
if o.GetOIDCVerifier() == nil {
if p.Verifier == nil {
msgs = append(msgs, "oidc provider requires an oidc issuer URL")
} else {
p.Verifier = o.GetOIDCVerifier()
}
case *providers.GitLabProvider:
p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
p.Groups = o.GitLabGroup
if o.GetOIDCVerifier() != nil {
p.Verifier = o.GetOIDCVerifier()
} else {
if p.Verifier == nil {
// Initialize with default verifier for gitlab.com
ctx := context.Background()

View File

@ -162,29 +162,6 @@ func TestDefaultProviderApiSettings(t *testing.T) {
assert.Equal(t, "profile email", p.Scope)
}
func TestPassAccessTokenRequiresSpecificCookieSecretLengths(t *testing.T) {
o := testOptions()
assert.Equal(t, nil, Validate(o))
assert.Equal(t, false, o.PassAccessToken)
o.PassAccessToken = true
o.Cookie.Secret = "cookie of invalid length-"
assert.NotEqual(t, nil, Validate(o))
o.PassAccessToken = false
o.Cookie.Refresh = time.Duration(24) * time.Hour
assert.NotEqual(t, nil, Validate(o))
o.Cookie.Secret = "16 bytes AES-128"
assert.Equal(t, nil, Validate(o))
o.Cookie.Secret = "24 byte secret AES-192--"
assert.Equal(t, nil, Validate(o))
o.Cookie.Secret = "32 byte secret for AES-256------"
assert.Equal(t, nil, Validate(o))
}
func TestCookieRefreshMustBeLessThanCookieExpire(t *testing.T) {
o := testOptions()
assert.Equal(t, nil, Validate(o))

View File

@ -16,18 +16,21 @@ func validateSessionCookieMinimal(o *options.Options) []string {
}
msgs := []string{}
if o.PassAuthorization {
for _, header := range append(o.InjectRequestHeaders, o.InjectResponseHeaders...) {
for _, value := range header.Values {
if value.ClaimSource != nil {
if value.ClaimSource.Claim == "access_token" {
msgs = append(msgs,
"pass_authorization_header requires oauth tokens in sessions. session_cookie_minimal cannot be set")
fmt.Sprintf("access_token claim for header %q requires oauth tokens in sessions. session_cookie_minimal cannot be set", header.Name))
}
if o.SetAuthorization {
if value.ClaimSource.Claim == "id_token" {
msgs = append(msgs,
"set_authorization_header requires oauth tokens in sessions. session_cookie_minimal cannot be set")
fmt.Sprintf("id_token claim for header %q requires oauth tokens in sessions. session_cookie_minimal cannot be set", header.Name))
}
if o.PassAccessToken {
msgs = append(msgs,
"pass_access_token requires oauth tokens in sessions. session_cookie_minimal cannot be set")
}
}
}
if o.Cookie.Refresh != time.Duration(0) {
msgs = append(msgs,
"cookie_refresh > 0 requires oauth tokens in sessions. session_cookie_minimal cannot be set")

View File

@ -13,9 +13,8 @@ import (
var _ = Describe("Sessions", func() {
const (
passAuthorizationMsg = "pass_authorization_header requires oauth tokens in sessions. session_cookie_minimal cannot be set"
setAuthorizationMsg = "set_authorization_header requires oauth tokens in sessions. session_cookie_minimal cannot be set"
passAccessTokenMsg = "pass_access_token requires oauth tokens in sessions. session_cookie_minimal cannot be set"
idTokenConflictMsg = "id_token claim for header \"X-ID-Token\" requires oauth tokens in sessions. session_cookie_minimal cannot be set"
accessTokenConflictMsg = "access_token claim for header \"X-Access-Token\" requires oauth tokens in sessions. session_cookie_minimal cannot be set"
cookieRefreshMsg = "cookie_refresh > 0 requires oauth tokens in sessions. session_cookie_minimal cannot be set"
)
@ -38,14 +37,25 @@ var _ = Describe("Sessions", func() {
},
errStrings: []string{},
}),
Entry("No minimal cookie session & passAuthorization", &cookieMinimalTableInput{
Entry("No minimal cookie session & request header has access_token claim", &cookieMinimalTableInput{
opts: &options.Options{
Session: options.SessionOptions{
Cookie: options.CookieStoreOptions{
Minimal: false,
},
},
PassAuthorization: true,
InjectRequestHeaders: []options.Header{
{
Name: "X-Access-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "access_token",
},
},
},
},
},
},
errStrings: []string{},
}),
@ -59,38 +69,71 @@ var _ = Describe("Sessions", func() {
},
errStrings: []string{},
}),
Entry("PassAuthorization conflict", &cookieMinimalTableInput{
Entry("Request Header id_token conflict", &cookieMinimalTableInput{
opts: &options.Options{
Session: options.SessionOptions{
Cookie: options.CookieStoreOptions{
Minimal: true,
},
},
PassAuthorization: true,
InjectRequestHeaders: []options.Header{
{
Name: "X-ID-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "id_token",
},
errStrings: []string{passAuthorizationMsg},
},
},
},
},
},
errStrings: []string{idTokenConflictMsg},
}),
Entry("SetAuthorization conflict", &cookieMinimalTableInput{
Entry("Response Header id_token conflict", &cookieMinimalTableInput{
opts: &options.Options{
Session: options.SessionOptions{
Cookie: options.CookieStoreOptions{
Minimal: true,
},
},
SetAuthorization: true,
InjectResponseHeaders: []options.Header{
{
Name: "X-ID-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "id_token",
},
errStrings: []string{setAuthorizationMsg},
},
},
},
},
},
errStrings: []string{idTokenConflictMsg},
}),
Entry("PassAccessToken conflict", &cookieMinimalTableInput{
Entry("Request Header access_token conflict", &cookieMinimalTableInput{
opts: &options.Options{
Session: options.SessionOptions{
Cookie: options.CookieStoreOptions{
Minimal: true,
},
},
PassAccessToken: true,
InjectRequestHeaders: []options.Header{
{
Name: "X-Access-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "access_token",
},
errStrings: []string{passAccessTokenMsg},
},
},
},
},
},
errStrings: []string{accessTokenConflictMsg},
}),
Entry("CookieRefresh conflict", &cookieMinimalTableInput{
opts: &options.Options{
@ -112,10 +155,32 @@ var _ = Describe("Sessions", func() {
Minimal: true,
},
},
PassAuthorization: true,
PassAccessToken: true,
InjectResponseHeaders: []options.Header{
{
Name: "X-ID-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "id_token",
},
errStrings: []string{passAuthorizationMsg, passAccessTokenMsg},
},
},
},
},
InjectRequestHeaders: []options.Header{
{
Name: "X-Access-Token",
Values: []options.HeaderValue{
{
ClaimSource: &options.ClaimSource{
Claim: "access_token",
},
},
},
},
},
},
errStrings: []string{idTokenConflictMsg, accessTokenConflictMsg},
}),
)

View File

@ -3,7 +3,6 @@ package validation
import (
"fmt"
"net/url"
"time"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
)
@ -70,7 +69,7 @@ func validateStaticUpstream(upstream options.Upstream) []string {
if upstream.InsecureSkipTLSVerify {
msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID))
}
if upstream.FlushInterval != nil && *upstream.FlushInterval != time.Second {
if upstream.FlushInterval != nil && upstream.FlushInterval.Duration() != options.DefaultUpstreamFlushInterval {
msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID))
}
if upstream.PassHostHeader != nil {

View File

@ -15,7 +15,7 @@ var _ = Describe("Upstreams", func() {
errStrings []string
}
flushInterval := 5 * time.Second
flushInterval := options.Duration(5 * time.Second)
staticCode200 := 200
truth := true

11
pkg/validation/utils.go Normal file
View File

@ -0,0 +1,11 @@
package validation
func prefixValues(prefix string, values ...string) []string {
msgs := []string{}
for _, value := range values {
if value != "" {
msgs = append(msgs, prefix+value)
}
}
return msgs
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"time"
@ -74,6 +75,9 @@ func NewAzureProvider(p *ProviderData) *AzureProvider {
if p.ProtectedResource == nil || p.ProtectedResource.String() == "" {
p.ProtectedResource = azureDefaultProtectResourceURL
}
if p.ValidateURL == nil || p.ValidateURL.String() == "" {
p.ValidateURL = p.ProfileURL
}
return &AzureProvider{
ProviderData: p,
@ -103,14 +107,14 @@ func overrideTenantURL(current, defaultURL *url.URL, tenant, path string) {
}
}
func (p *AzureProvider) Redeem(ctx context.Context, redirectURL, code string) (s *sessions.SessionState, err error) {
// Redeem exchanges the OAuth2 authentication token for an ID token
func (p *AzureProvider) Redeem(ctx context.Context, redirectURL, code string) (*sessions.SessionState, error) {
if code == "" {
err = errors.New("missing code")
return
return nil, ErrMissingCode
}
clientSecret, err := p.GetClientSecret()
if err != nil {
return
return nil, err
}
params := url.Values{}
@ -123,6 +127,7 @@ func (p *AzureProvider) Redeem(ctx context.Context, redirectURL, code string) (s
params.Add("resource", p.ProtectedResource.String())
}
// blindly try json and x-www-form-urlencoded
var jsonResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
@ -143,13 +148,67 @@ func (p *AzureProvider) Redeem(ctx context.Context, redirectURL, code string) (s
created := time.Now()
expires := time.Unix(jsonResponse.ExpiresOn, 0)
s = &sessions.SessionState{
return &sessions.SessionState{
AccessToken: jsonResponse.AccessToken,
IDToken: jsonResponse.IDToken,
CreatedAt: &created,
ExpiresOn: &expires,
RefreshToken: jsonResponse.RefreshToken,
}, nil
}
// RefreshSessionIfNeeded checks if the session has expired and uses the
// RefreshToken to fetch a new ID token if required
func (p *AzureProvider) RefreshSessionIfNeeded(ctx context.Context, s *sessions.SessionState) (bool, error) {
if s == nil || s.ExpiresOn.After(time.Now()) || s.RefreshToken == "" {
return false, nil
}
origExpiration := s.ExpiresOn
err := p.redeemRefreshToken(ctx, s)
if err != nil {
return false, fmt.Errorf("unable to redeem refresh token: %v", err)
}
fmt.Printf("refreshed id token %s (expired on %s)\n", s, origExpiration)
return true, nil
}
func (p *AzureProvider) redeemRefreshToken(ctx context.Context, s *sessions.SessionState) (err error) {
params := url.Values{}
params.Add("client_id", p.ClientID)
params.Add("client_secret", p.ClientSecret)
params.Add("refresh_token", s.RefreshToken)
params.Add("grant_type", "refresh_token")
var jsonResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresOn int64 `json:"expires_on,string"`
IDToken string `json:"id_token"`
}
err = requests.New(p.RedeemURL.String()).
WithContext(ctx).
WithMethod("POST").
WithBody(bytes.NewBufferString(params.Encode())).
SetHeader("Content-Type", "application/x-www-form-urlencoded").
Do().
UnmarshalInto(&jsonResponse)
if err != nil {
return
}
now := time.Now()
expires := time.Unix(jsonResponse.ExpiresOn, 0)
s.AccessToken = jsonResponse.AccessToken
s.IDToken = jsonResponse.IDToken
s.RefreshToken = jsonResponse.RefreshToken
s.CreatedAt = &now
s.ExpiresOn = &expires
return
}
@ -219,3 +278,8 @@ func (p *AzureProvider) GetLoginURL(redirectURI, state string) string {
a := makeLoginURL(p.ProviderData, redirectURI, state, extraParams)
return a.String()
}
// ValidateSession validates the AccessToken
func (p *AzureProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool {
return validateToken(ctx, p, s.AccessToken, makeAzureHeader(s.AccessToken))
}

Some files were not shown because too many files have changed in this diff Show More