Add JWT plugin

This commit is contained in:
Jeff Mitchell 2018-07-09 16:21:47 -04:00
parent bda3d3e92a
commit 1011f61bf2
11 changed files with 1868 additions and 0 deletions

View File

@ -38,6 +38,7 @@ import (
credAzure "github.com/hashicorp/vault-plugin-auth-azure"
credCentrify "github.com/hashicorp/vault-plugin-auth-centrify"
credGcp "github.com/hashicorp/vault-plugin-auth-gcp/plugin"
credJWT "github.com/hashicorp/vault-plugin-auth-jwt"
credKube "github.com/hashicorp/vault-plugin-auth-kubernetes"
credAppId "github.com/hashicorp/vault/builtin/credential/app-id"
credAppRole "github.com/hashicorp/vault/builtin/credential/approle"
@ -102,6 +103,7 @@ var (
"cert": credCert.Factory,
"gcp": credGcp.Factory,
"github": credGitHub.Factory,
"jwt": credJWT.Factory,
"kubernetes": credKube.Factory,
"ldap": credLdap.Factory,
"okta": credOkta.Factory,

View File

@ -0,0 +1,355 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "github.com/SermoDigital/jose"
packages = [
".",
"crypto",
"jws",
"jwt"
]
revision = "f6df55f235c24f236d11dbcf665249a59ac2021f"
version = "1.1"
[[projects]]
branch = "master"
name = "github.com/armon/go-radix"
packages = ["."]
revision = "1fca145dffbcaa8fe914309b1ec0cfc67500fe61"
[[projects]]
name = "github.com/coreos/go-oidc"
packages = ["."]
revision = "1180514eaf4d9f38d0d19eef639a1d695e066e72"
version = "v2.0.0"
[[projects]]
name = "github.com/go-test/deep"
packages = ["."]
revision = "6592d9cc0a499ad2d5f574fde80a2b5c5cc3b4f5"
version = "v1.0.1"
[[projects]]
name = "github.com/golang/protobuf"
packages = [
"proto",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/timestamp"
]
revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265"
version = "v1.1.0"
[[projects]]
branch = "master"
name = "github.com/golang/snappy"
packages = ["."]
revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a"
[[projects]]
branch = "master"
name = "github.com/hashicorp/errwrap"
packages = ["."]
revision = "7554cd9344cec97297fa6649b055a8c98c2a1e55"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-cleanhttp"
packages = ["."]
revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-hclog"
packages = ["."]
revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-immutable-radix"
packages = ["."]
revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-multierror"
packages = ["."]
revision = "b7773ae218740a7be65057fc60b366a49b538a44"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-plugin"
packages = ["."]
revision = "e8d22c780116115ae5624720c9af0c97afe4f551"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-retryablehttp"
packages = ["."]
revision = "3b087ef2d313afe6c55b2f511d20db04ca767075"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-rootcerts"
packages = ["."]
revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-sockaddr"
packages = ["."]
revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-uuid"
packages = ["."]
revision = "27454136f0364f2d44b1276c552d69105cf8c498"
[[projects]]
branch = "master"
name = "github.com/hashicorp/go-version"
packages = ["."]
revision = "23480c0665776210b5fbbac6eaaee40e3e6a96b7"
[[projects]]
branch = "master"
name = "github.com/hashicorp/golang-lru"
packages = [
".",
"simplelru"
]
revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3"
[[projects]]
branch = "master"
name = "github.com/hashicorp/hcl"
packages = [
".",
"hcl/ast",
"hcl/parser",
"hcl/scanner",
"hcl/strconv",
"hcl/token",
"json/parser",
"json/scanner",
"json/token"
]
revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168"
[[projects]]
branch = "master"
name = "github.com/hashicorp/vault"
packages = [
"api",
"helper/certutil",
"helper/cidrutil",
"helper/compressutil",
"helper/consts",
"helper/errutil",
"helper/hclutil",
"helper/jsonutil",
"helper/locksutil",
"helper/logging",
"helper/mlock",
"helper/parseutil",
"helper/pathmanager",
"helper/pluginutil",
"helper/policyutil",
"helper/salt",
"helper/strutil",
"helper/wrapping",
"logical",
"logical/framework",
"logical/plugin",
"logical/plugin/pb",
"physical",
"physical/inmem",
"version"
]
revision = "8ac73469a380d78cd690d4ce137a8820c2b49a41"
[[projects]]
branch = "master"
name = "github.com/hashicorp/yamux"
packages = ["."]
revision = "3520598351bb3500a49ae9563f5539666ae0a27c"
[[projects]]
branch = "master"
name = "github.com/mitchellh/go-homedir"
packages = ["."]
revision = "3864e76763d94a6df2f9960b16a20a33da9f9a66"
[[projects]]
branch = "master"
name = "github.com/mitchellh/go-testing-interface"
packages = ["."]
revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28"
[[projects]]
branch = "master"
name = "github.com/mitchellh/mapstructure"
packages = ["."]
revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b"
[[projects]]
name = "github.com/oklog/run"
packages = ["."]
revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39"
version = "v1.0.0"
[[projects]]
branch = "master"
name = "github.com/pquerna/cachecontrol"
packages = [
".",
"cacheobject"
]
revision = "1555304b9b35fdd2b425bccf1a5613677705e7d0"
[[projects]]
name = "github.com/ryanuber/go-glob"
packages = ["."]
revision = "572520ed46dbddaed19ea3d9541bdd0494163693"
version = "v0.1"
[[projects]]
branch = "master"
name = "golang.org/x/crypto"
packages = [
"ed25519",
"ed25519/internal/edwards25519"
]
revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602"
[[projects]]
branch = "master"
name = "golang.org/x/net"
packages = [
"context",
"context/ctxhttp",
"http/httpguts",
"http2",
"http2/hpack",
"idna",
"internal/timeseries",
"trace"
]
revision = "c21de06aaf072cea07f3a65d6970e5c7d8b6cd6d"
[[projects]]
branch = "master"
name = "golang.org/x/oauth2"
packages = [
".",
"internal"
]
revision = "ef147856a6ddbb60760db74283d2424e98c87bff"
[[projects]]
branch = "master"
name = "golang.org/x/sys"
packages = ["unix"]
revision = "1b2967e3c290b7c545b3db0deeda16e9be4f98a2"
[[projects]]
name = "golang.org/x/text"
packages = [
"collate",
"collate/build",
"internal/colltab",
"internal/gen",
"internal/tag",
"internal/triegen",
"internal/ucd",
"language",
"secure/bidirule",
"transform",
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable"
]
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
branch = "master"
name = "golang.org/x/time"
packages = ["rate"]
revision = "fbb02b2291d28baffd63558aa44b4b56f178d650"
[[projects]]
name = "google.golang.org/appengine"
packages = [
"internal",
"internal/base",
"internal/datastore",
"internal/log",
"internal/remote_api",
"internal/urlfetch",
"urlfetch"
]
revision = "b1f26356af11148e710935ed1ac8a7f5702c7612"
version = "v1.1.0"
[[projects]]
branch = "master"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
revision = "8b2cc369ab52e0003a878865c9372afdd6ca5c5a"
[[projects]]
name = "google.golang.org/grpc"
packages = [
".",
"balancer",
"balancer/base",
"balancer/roundrobin",
"codes",
"connectivity",
"credentials",
"encoding",
"encoding/proto",
"grpclog",
"health",
"health/grpc_health_v1",
"internal",
"internal/backoff",
"internal/channelz",
"internal/grpcrand",
"keepalive",
"metadata",
"naming",
"peer",
"resolver",
"resolver/dns",
"resolver/passthrough",
"stats",
"status",
"tap",
"transport"
]
revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8"
version = "v1.13.0"
[[projects]]
name = "gopkg.in/square/go-jose.v2"
packages = [
".",
"cipher",
"json",
"jwt"
]
revision = "76dd09796242edb5b897103a75df2645c028c960"
version = "v2.1.6"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "1df54eedb307685c78614117603a3cf7a9dffaf2ce9cdbbd49a4398761eb2cc3"
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -0,0 +1,58 @@
# Gopkg.toml example
#
# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[[constraint]]
name = "github.com/coreos/go-oidc"
version = "2.0.0"
[[constraint]]
branch = "master"
name = "github.com/hashicorp/errwrap"
[[constraint]]
branch = "master"
name = "github.com/hashicorp/go-cleanhttp"
[[constraint]]
branch = "master"
name = "github.com/hashicorp/go-sockaddr"
[[constraint]]
branch = "master"
name = "github.com/hashicorp/vault"
[[constraint]]
branch = "master"
name = "golang.org/x/oauth2"
[[constraint]]
name = "gopkg.in/square/go-jose.v2"
version = "2.1.6"
[prune]
go-tests = true
unused-packages = true

View File

@ -0,0 +1,363 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.

View File

@ -0,0 +1,55 @@
TOOL?=vault-plugin-auth-jwt
TEST?=$$(go list ./... | grep -v /vendor/)
EXTERNAL_TOOLS=\
github.com/mitchellh/gox
BUILD_TAGS?=${TOOL}
GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor)
# bin generates the releaseable binaries for this plugin
bin: generate
@CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'"
default: dev
# dev creates binaries for testing Vault locally. These are put
# into ./bin/ as well as $GOPATH/bin, except for quickdev which
# is only put into /bin/
quickdev: generate
@CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/${TOOL}
dev: generate
@CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'"
testcompile: generate
@for pkg in $(TEST) ; do \
go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \
done
# test runs all tests
test: generate
@if [ "$(TEST)" = "./..." ]; then \
echo "ERROR: Set TEST to a specific package"; \
exit 1; \
fi
VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 10m
# generate runs `go generate` to build the dynamically generated
# source files.
generate:
@go generate $(go list ./... | grep -v /vendor/)
# bootstrap the build by downloading additional tools
bootstrap:
@for tool in $(EXTERNAL_TOOLS) ; do \
echo "Installing/Updating $$tool" ; \
go get -u $$tool; \
done
fmt:
gofmt -w $(GOFMT_FILES)
# deps updates all dependencies for this project.
deps:
@echo "==> Updating deps for ${TOOL}"
@dep ensure -update
.PHONY: bin default generate test bootstrap fmt deps

View File

@ -0,0 +1,127 @@
# Vault Plugin: JWT Auth Backend [![Build Status](https://travis-ci.org/hashicorp/vault-plugin-auth-jwt.svg?branch=master)](https://travis-ci.org/hashicorp/vault-plugin-auth-jwt)
This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault).
This plugin allows for JWTs (including OIDC tokens) to authenticate with Vault.
**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com).
## IMPORTANT
This plugin is in pre-release state. It is not well tested (in fact, not tested at all) and there is no documentation currently available.
## Quick Links
- Vault Website: https://www.vaultproject.io
- JWT Auth Docs: https://www.vaultproject.io/docs/auth/jwt.html
- Main Project Github: https://www.github.com/hashicorp/vault
## Getting Started
This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html)
and is meant to work with Vault. This guide assumes you have already installed Vault
and have a basic understanding of how Vault works.
Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html).
To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html).
## Usage
Please see [documentation for the plugin](https://www.vaultproject.io/docs/auth/jwt.html)
on the Vault website.
This plugin is currently built into Vault and by default is accessed
at `auth/jwt`. To enable this in a running Vault server:
```sh
$ vault auth enable jwt
Successfully enabled 'jwt' at 'jwt'!
```
To see all the supported paths, see the [JWT auth backend docs](https://www.vaultproject.io/docs/auth/jwt.html).
## Developing
If you wish to work on this plugin, you'll first need
[Go](https://www.golang.org) installed on your machine.
For local dev first make sure Go is properly installed, including
setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH).
Next, clone this repository into
`$GOPATH/src/github.com/hashicorp/vault-plugin-auth-jwt`.
You can then download any required build tools by bootstrapping your
environment:
```sh
$ make bootstrap
```
To compile a development version of this plugin, run `make` or `make dev`.
This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev`
mode will only generate the binary for your platform and is faster:
```sh
$ make
$ make dev
```
Put the plugin binary into a location of your choice. This directory
will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory)
in the Vault config used to start the server.
```json
...
plugin_directory = "path/to/plugin/directory"
...
```
Start a Vault server with this config file:
```sh
$ vault server -config=path/to/config.json ...
...
```
Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog):
```sh
$ vault write sys/plugins/catalog/jwt \
sha_256=<expected SHA256 Hex value of the plugin binary> \
command="vault-plugin-auth-jwt"
...
Success! Data written to: sys/plugins/catalog/jwt
```
Note you should generate a new sha256 checksum if you have made changes
to the plugin. Example using openssl:
```sh
openssl dgst -sha256 $GOPATH/vault-plugin-auth-jwt
...
SHA256(.../go/bin/vault-plugin-auth-jwt)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1
```
Enable the auth plugin backend using the JWT auth plugin:
```sh
$ vault auth enable -plugin-name='jwt' plugin
...
Successfully enabled 'plugin' at 'jwt'!
```
#### Tests
If you are developing this plugin and want to verify it is still
functioning (and you haven't broken anything else), we recommend
running the tests.
To run the tests, invoke `make test`:
```sh
$ make test
```
You can also specify a `TESTARGS` variable to filter tests like so:
```sh
$ make test TESTARGS='--run=TestConfig'
```

View File

@ -0,0 +1,107 @@
package jwtauth
import (
"context"
"sync"
oidc "github.com/coreos/go-oidc"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
const (
configPath string = "config"
rolePrefix string = "role/"
)
// Factory is used by framework
func Factory(ctx context.Context, c *logical.BackendConfig) (logical.Backend, error) {
b := backend(c)
if err := b.Setup(ctx, c); err != nil {
return nil, err
}
return b, nil
}
type jwtAuthBackend struct {
*framework.Backend
l sync.RWMutex
provider *oidc.Provider
cachedConfig *jwtConfig
}
func backend(c *logical.BackendConfig) *jwtAuthBackend {
b := new(jwtAuthBackend)
b.Backend = &framework.Backend{
AuthRenew: b.pathLoginRenew,
BackendType: logical.TypeCredential,
Invalidate: b.invalidate,
Help: backendHelp,
PathsSpecial: &logical.Paths{
Unauthenticated: []string{
"login",
},
SealWrapStorage: []string{
"config",
},
},
Paths: framework.PathAppend(
[]*framework.Path{
pathLogin(b),
pathRoleList(b),
pathRole(b),
pathConfig(b),
},
),
}
return b
}
func (b *jwtAuthBackend) invalidate(ctx context.Context, key string) {
switch key {
case "config":
b.reset()
}
}
func (b *jwtAuthBackend) reset() {
b.l.Lock()
b.provider = nil
b.cachedConfig = nil
b.l.Unlock()
}
func (b *jwtAuthBackend) getProvider(ctx context.Context, config *jwtConfig) (*oidc.Provider, error) {
b.l.RLock()
unlockFunc := b.l.RUnlock
defer func() { unlockFunc() }()
if b.provider != nil {
return b.provider, nil
}
b.l.RUnlock()
b.l.Lock()
unlockFunc = b.l.Unlock
if b.provider != nil {
return b.provider, nil
}
provider, err := b.createProvider(ctx, config)
if err != nil {
return nil, err
}
b.provider = provider
return provider, nil
}
const (
backendHelp = `
The JWT backend plugin allows authentication using JWTs (including OIDC).
`
)

View File

@ -0,0 +1,200 @@
package jwtauth
import (
"crypto/tls"
"crypto/x509"
"errors"
"net/http"
"context"
oidc "github.com/coreos/go-oidc"
"github.com/hashicorp/errwrap"
cleanhttp "github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/vault/helper/certutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"golang.org/x/oauth2"
)
func pathConfig(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: `config`,
Fields: map[string]*framework.FieldSchema{
"oidc_issuer_url": &framework.FieldSchema{
Type: framework.TypeString,
Description: `OIDC issuer URL, without any .well-known component (base path). Cannot be used with "jwt_validation_pubkeys".`,
},
"oidc_issuer_ca_pem": &framework.FieldSchema{
Type: framework.TypeString,
Description: "The CA certificate or chain of certificates, in PEM format, to use to validate conections to the OIDC issuer URL. If not set, system certificates are used.",
},
"jwt_validation_pubkeys": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `When performing local validation on a JWT, a list of PEM-encoded public keys to use to authenticate the JWT's signature. Cannot be used with "oidc_issuer_url".`,
},
"bound_issuer": &framework.FieldSchema{
Type: framework.TypeString,
Description: "The value against which to match the 'iss' claim in a JWT. Optional.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathConfigRead,
logical.UpdateOperation: b.pathConfigWrite,
},
HelpSynopsis: confHelpSyn,
HelpDescription: confHelpDesc,
}
}
func (b *jwtAuthBackend) config(ctx context.Context, s logical.Storage) (*jwtConfig, error) {
b.l.RLock()
defer b.l.RUnlock()
if b.cachedConfig != nil {
return b.cachedConfig, nil
}
entry, err := s.Get(ctx, configPath)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
result := &jwtConfig{}
if entry != nil {
if err := entry.DecodeJSON(result); err != nil {
return nil, err
}
}
for _, v := range result.JWTValidationPubKeys {
key, err := certutil.ParsePublicKeyPEM([]byte(v))
if err != nil {
return nil, errwrap.Wrapf("error parsing public key: {{err}}", err)
}
result.ParsedJWTPubKeys = append(result.ParsedJWTPubKeys, key)
}
b.cachedConfig = result
return result, nil
}
func (b *jwtAuthBackend) pathConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return nil, nil
}
resp := &logical.Response{
Data: map[string]interface{}{
"oidc_issuer_url": config.OIDCIssuerURL,
"oidc_issuer_ca_pem": config.OIDCIssuerCAPEM,
"jwt_validation_pubkeys": config.JWTValidationPubKeys,
"bound_issuer": config.BoundIssuer,
},
}
return resp, nil
}
func (b *jwtAuthBackend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
config := &jwtConfig{
OIDCIssuerURL: d.Get("oidc_issuer_url").(string),
OIDCIssuerCAPEM: d.Get("oidc_issuer_ca_pem").(string),
JWTValidationPubKeys: d.Get("jwt_validation_pubkeys").([]string),
BoundIssuer: d.Get("bound_issuer").(string),
}
// Run checks on values
switch {
case config.OIDCIssuerURL == "" && len(config.JWTValidationPubKeys) == 0,
config.OIDCIssuerURL != "" && len(config.JWTValidationPubKeys) != 0:
return logical.ErrorResponse("exactly one of 'oidc_issuer_url' and 'jwt_validation_pubkeys' must be set"), nil
case config.OIDCIssuerURL != "":
_, err := b.createProvider(ctx, config)
if err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error checking issuer URL: {{err}}", err).Error()), nil
}
case len(config.JWTValidationPubKeys) != 0:
for _, v := range config.JWTValidationPubKeys {
if _, err := certutil.ParsePublicKeyPEM([]byte(v)); err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error parsing public key: {{err}}", err).Error()), nil
}
}
default:
return nil, errors.New("unknown condition")
}
entry, err := logical.StorageEntryJSON(configPath, config)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
b.reset()
return nil, nil
}
func (b *jwtAuthBackend) createProvider(ctx context.Context, config *jwtConfig) (*oidc.Provider, error) {
var certPool *x509.CertPool
if config.OIDCIssuerCAPEM != "" {
certPool = x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM([]byte(config.OIDCIssuerCAPEM)); !ok {
return nil, errors.New("could not parse 'oidc_issuer_ca_pem' value successfully")
}
}
tr := cleanhttp.DefaultPooledTransport()
if certPool != nil {
tr.TLSClientConfig = &tls.Config{
RootCAs: certPool,
}
}
tc := &http.Client{
Transport: tr,
}
oidcCtx := context.WithValue(ctx, oauth2.HTTPClient, tc)
provider, err := oidc.NewProvider(oidcCtx, config.OIDCIssuerURL)
if err != nil {
return nil, errwrap.Wrapf("error creating provider with given values: {{err}}", err)
}
return provider, nil
}
type jwtConfig struct {
OIDCIssuerURL string `json:"oidc_issuer_url"`
OIDCIssuerCAPEM string `json:"oidc_issuer_ca_pem"`
JWTValidationPubKeys []string `json:"jwt_validation_pubkeys"`
BoundIssuer string `json:"bound_issuer"`
ParsedJWTPubKeys []interface{} `json:"-"`
}
const (
confHelpSyn = `
Configures the JWT authentication backend.
`
confHelpDesc = `
The JWT authentication backend validates JWTs (or OIDC) using the configured
credentials. If using OIDC issuer discovery, the URL must be provided, along
with (optionally) the CA cert to use for the connection. If performing JWT
validation locally, a set of public keys must be provided.
`
)

View File

@ -0,0 +1,257 @@
package jwtauth
import (
"context"
"errors"
"fmt"
"time"
oidc "github.com/coreos/go-oidc"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/helper/cidrutil"
"github.com/hashicorp/vault/helper/strutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"gopkg.in/square/go-jose.v2/jwt"
)
func pathLogin(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: `login$`,
Fields: map[string]*framework.FieldSchema{
"role": &framework.FieldSchema{
Type: framework.TypeLowerCaseString,
Description: "The role to log in against.",
},
"token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "The signed JWT to validate.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathLogin,
logical.AliasLookaheadOperation: b.pathLogin,
},
HelpSynopsis: pathLoginHelpSyn,
HelpDescription: pathLoginHelpDesc,
}
}
func (b *jwtAuthBackend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
token := d.Get("token").(string)
if len(token) == 0 {
return logical.ErrorResponse("missing token"), nil
}
roleName := d.Get("role").(string)
if len(roleName) == 0 {
return logical.ErrorResponse("missing role"), nil
}
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse("role could not be found"), nil
}
if req.Connection != nil && !cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, role.BoundCIDRs) {
return logical.ErrorResponse("request originated from invalid CIDR"), nil
}
config, err := b.config(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return logical.ErrorResponse("could not load configuration"), nil
}
// Here is where things diverge. If it is using OIDC discovery, validate
// that way; otherwise validate against the locally configured keys. Once
// things are validated, we re-unify the request path when evaluating the
// claims.
allClaims := map[string]interface{}{}
switch {
case len(config.ParsedJWTPubKeys) != 0:
parsedJWT, err := jwt.ParseSigned(token)
if err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error parsing token: {{err}}", err).Error()), nil
}
claims := jwt.Claims{}
var valid bool
for _, key := range config.ParsedJWTPubKeys {
if err := parsedJWT.Claims(key, &claims, &allClaims); err == nil {
valid = true
break
}
}
if !valid {
return logical.ErrorResponse("no known key successfully validated the token signature"), nil
}
// We require notbefore or expiry; if only one is provided, we allow 5 minutes of leeway.
if claims.IssuedAt == 0 && claims.Expiry == 0 && claims.NotBefore == 0 {
return logical.ErrorResponse("no issue time, notbefore, or expiration time encoded in token"), nil
}
if claims.Expiry == 0 {
latestStart := claims.IssuedAt
if claims.NotBefore > claims.IssuedAt {
latestStart = claims.NotBefore
}
claims.Expiry = latestStart + 300
}
if claims.NotBefore == 0 {
if claims.IssuedAt != 0 {
claims.NotBefore = claims.IssuedAt
} else {
claims.NotBefore = claims.Expiry - 300
}
}
expected := jwt.Expected{
Issuer: config.BoundIssuer,
Subject: role.BoundSubject,
Audience: jwt.Audience(role.BoundAudiences),
Time: time.Now(),
}
if err := claims.Validate(expected); err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error validating claims: {{err}}", err).Error()), nil
}
case config.OIDCIssuerURL != "":
provider, err := b.getProvider(ctx, config)
if err != nil {
return nil, errwrap.Wrapf("error getting provider for login operation: {{err}}", err)
}
verifier := provider.Verifier(&oidc.Config{
SkipClientIDCheck: true,
})
idToken, err := verifier.Verify(ctx, token)
if err != nil {
return logical.ErrorResponse(errwrap.Wrapf("error validating signature: {{err}}", err).Error()), nil
}
if err := idToken.Claims(&allClaims); err != nil {
return logical.ErrorResponse(errwrap.Wrapf("unable to successfully parse all claims from token: {{err}}", err).Error()), nil
}
if role.BoundSubject != "" && role.BoundSubject != idToken.Subject {
return logical.ErrorResponse("sub claim does not match bound subject"), nil
}
if len(role.BoundAudiences) != 0 {
var found bool
for _, v := range role.BoundAudiences {
if strutil.StrListContains(idToken.Audience, v) {
found = true
break
}
}
if !found {
return logical.ErrorResponse("aud claim does not match any bound audience"), nil
}
}
default:
return nil, errors.New("unhandled case during login")
}
userClaimRaw, ok := allClaims[role.UserClaim]
if !ok {
return logical.ErrorResponse(fmt.Sprintf("%q claim not found in token", role.UserClaim)), nil
}
userName, ok := userClaimRaw.(string)
if !ok {
return logical.ErrorResponse(fmt.Sprintf("%q claim could not be converted to string", role.UserClaim)), nil
}
var groupAliases []*logical.Alias
if role.GroupsClaim != "" {
groupsClaimRaw, ok := allClaims[role.GroupsClaim]
if !ok {
return logical.ErrorResponse(fmt.Sprintf("%q claim not found in token", role.GroupsClaim)), nil
}
groups, ok := groupsClaimRaw.([]interface{})
if !ok {
return logical.ErrorResponse(fmt.Sprintf("%q claim could not be converted to string list", role.GroupsClaim)), nil
}
for _, groupRaw := range groups {
group, ok := groupRaw.(string)
if !ok {
return logical.ErrorResponse(fmt.Sprintf("value %v in groups claim could not be parsed as string", groupRaw)), nil
}
if group == "" {
continue
}
groupAliases = append(groupAliases, &logical.Alias{
Name: group,
})
}
}
resp := &logical.Response{
Auth: &logical.Auth{
Policies: role.Policies,
DisplayName: userName,
Period: role.Period,
NumUses: role.NumUses,
Alias: &logical.Alias{
Name: userName,
},
GroupAliases: groupAliases,
InternalData: map[string]interface{}{
"role": roleName,
},
Metadata: map[string]string{
"role": roleName,
},
LeaseOptions: logical.LeaseOptions{
Renewable: true,
TTL: role.TTL,
MaxTTL: role.MaxTTL,
},
BoundCIDRs: role.BoundCIDRs,
},
}
return resp, nil
}
func (b *jwtAuthBackend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := req.Auth.InternalData["role"].(string)
if roleName == "" {
return nil, errors.New("failed to fetch role_name during renewal")
}
// Ensure that the Role still exists.
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, errwrap.Wrapf(fmt.Sprintf("failed to validate role %s during renewal: {{err}}", roleName), err)
}
if role == nil {
return nil, fmt.Errorf("role %s does not exist during renewal", roleName)
}
resp := &logical.Response{Auth: req.Auth}
resp.Auth.TTL = role.TTL
resp.Auth.MaxTTL = role.MaxTTL
resp.Auth.Period = role.Period
return resp, nil
}
const (
pathLoginHelpSyn = `
Authenticates to Vault using a JWT (or OIDC) token.
`
pathLoginHelpDesc = `
Authenticates JWTs.
`
)

View File

@ -0,0 +1,338 @@
package jwtauth
import (
"context"
"errors"
"fmt"
"strings"
"time"
sockaddr "github.com/hashicorp/go-sockaddr"
"github.com/hashicorp/vault/helper/parseutil"
"github.com/hashicorp/vault/helper/policyutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func pathRoleList(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: "role/?",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]),
}
}
// pathRole returns the path configurations for the CRUD operations on roles
func pathRole(b *jwtAuthBackend) *framework.Path {
return &framework.Path{
Pattern: "role/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": &framework.FieldSchema{
Type: framework.TypeLowerCaseString,
Description: "Name of the role.",
},
"policies": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: "List of policies on the role.",
},
"num_uses": &framework.FieldSchema{
Type: framework.TypeInt,
Description: `Number of times issued tokens can be used`,
},
"ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued token should expire. Defaults
to 0, in which case the value will fall back to the system/mount defaults.`,
},
"max_ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Duration in seconds after which the issued token should not be allowed to
be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`,
},
"period": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `If set, indicates that the token generated using this role
should never expire. The token should be renewed within the
duration specified by this value. At each renewal, the token's
TTL will be set to the value of this parameter.`,
},
"bound_subject": &framework.FieldSchema{
Type: framework.TypeString,
Description: `The 'sub' claim that is valid for login. Optional.`,
},
"bound_audiences": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of 'aud' claims that are valid for login; any match is sufficient`,
},
"user_claim": &framework.FieldSchema{
Type: framework.TypeString,
Description: `The claim to use for the Identity entity alias name`,
},
"groups_claim": &framework.FieldSchema{
Type: framework.TypeString,
Description: `The claim to use for the Identity group alias names`,
},
"bound_cidrs": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of IP CIDRS that are allowed to
authenticate against this role`,
},
},
ExistenceCheck: b.pathRoleExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.CreateOperation: b.pathRoleCreateUpdate,
logical.UpdateOperation: b.pathRoleCreateUpdate,
logical.ReadOperation: b.pathRoleRead,
logical.DeleteOperation: b.pathRoleDelete,
},
HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]),
HelpDescription: strings.TrimSpace(roleHelp["role"][1]),
}
}
type jwtRole struct {
// Policies that are to be required by the token to access this role
Policies []string `json:"policies"`
// TokenNumUses defines the number of allowed uses of the token issued
NumUses int `json:"num_uses"`
// Duration before which an issued token must be renewed
TTL time.Duration `json:"ttl"`
// Duration after which an issued token should not be allowed to be renewed
MaxTTL time.Duration `json:"max_ttl"`
// Period, if set, indicates that the token generated using this role
// should never expire. The token should be renewed within the duration
// specified by this value. The renewal duration will be fixed if the
// value is not modified on the role. If the `Period` in the role is modified,
// a token will pick up the new value during its next renewal.
Period time.Duration `json:"period"`
// Role binding properties
BoundAudiences []string `json:"bound_audiences"`
BoundSubject string `json:"bound_subject"`
BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"`
UserClaim string `json:"user_claim"`
GroupsClaim string `json:"groups_claim"`
}
// role takes a storage backend and the name and returns the role's storage
// entry
func (b *jwtAuthBackend) role(ctx context.Context, s logical.Storage, name string) (*jwtRole, error) {
raw, err := s.Get(ctx, rolePrefix+name)
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
role := new(jwtRole)
if err := raw.DecodeJSON(role); err != nil {
return nil, err
}
return role, nil
}
// pathRoleExistenceCheck returns whether the role with the given name exists or not.
func (b *jwtAuthBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
role, err := b.role(ctx, req.Storage, data.Get("name").(string))
if err != nil {
return false, err
}
return role != nil, nil
}
// pathRoleList is used to list all the Roles registered with the backend.
func (b *jwtAuthBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roles, err := req.Storage.List(ctx, rolePrefix)
if err != nil {
return nil, err
}
return logical.ListResponse(roles), nil
}
// pathRoleRead grabs a read lock and reads the options set on the role from the storage
func (b *jwtAuthBackend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing name"), nil
}
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
// Create a map of data to be returned
resp := &logical.Response{
Data: map[string]interface{}{
"policies": role.Policies,
"num_uses": role.NumUses,
"period": int64(role.Period.Seconds()),
"ttl": int64(role.TTL.Seconds()),
"max_ttl": int64(role.MaxTTL.Seconds()),
"bound_audiences": role.BoundAudiences,
"bound_subject": role.BoundSubject,
"bound_cidrs": role.BoundCIDRs,
"user_claim": role.UserClaim,
"groups_claim": role.GroupsClaim,
},
}
return resp, nil
}
// pathRoleDelete removes the role from storage
func (b *jwtAuthBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("role name required"), nil
}
// Delete the role itself
if err := req.Storage.Delete(ctx, rolePrefix+roleName); err != nil {
return nil, err
}
return nil, nil
}
// pathRoleCreateUpdate registers a new role with the backend or updates the options
// of an existing role
func (b *jwtAuthBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role name"), nil
}
// Check if the role already exists
role, err := b.role(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
// Create a new entry object if this is a CreateOperation
if role == nil {
if req.Operation == logical.UpdateOperation {
return nil, errors.New("role entry not found during update operation")
}
role = new(jwtRole)
}
if policiesRaw, ok := data.GetOk("policies"); ok {
role.Policies = policyutil.ParsePolicies(policiesRaw)
}
periodRaw, ok := data.GetOk("period")
if ok {
role.Period = time.Duration(periodRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
role.Period = time.Duration(data.Get("period").(int)) * time.Second
}
if role.Period > b.System().MaxLeaseTTL() {
return logical.ErrorResponse(fmt.Sprintf("'period' of '%q' is greater than the backend's maximum lease TTL of '%q'", role.Period.String(), b.System().MaxLeaseTTL().String())), nil
}
if tokenNumUsesRaw, ok := data.GetOk("num_uses"); ok {
role.NumUses = tokenNumUsesRaw.(int)
} else if req.Operation == logical.CreateOperation {
role.NumUses = data.Get("num_uses").(int)
}
if role.NumUses < 0 {
return logical.ErrorResponse("num_uses cannot be negative"), nil
}
if tokenTTLRaw, ok := data.GetOk("ttl"); ok {
role.TTL = time.Duration(tokenTTLRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
role.TTL = time.Duration(data.Get("ttl").(int)) * time.Second
}
if tokenMaxTTLRaw, ok := data.GetOk("max_ttl"); ok {
role.MaxTTL = time.Duration(tokenMaxTTLRaw.(int)) * time.Second
} else if req.Operation == logical.CreateOperation {
role.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second
}
if boundAudiences, ok := data.GetOk("bound_audiences"); ok {
role.BoundAudiences = boundAudiences.([]string)
}
if boundSubject, ok := data.GetOk("bound_subject"); ok {
role.BoundSubject = boundSubject.(string)
}
if boundCIDRs, ok := data.GetOk("bound_cidrs"); ok {
parsedCIDRs, err := parseutil.ParseAddrs(boundCIDRs)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
role.BoundCIDRs = parsedCIDRs
}
if userClaim, ok := data.GetOk("user_claim"); ok {
role.UserClaim = userClaim.(string)
}
if role.UserClaim == "" {
return logical.ErrorResponse("a user claim must be defined on the role"), nil
}
if groupsClaim, ok := data.GetOk("groups_claim"); ok {
role.GroupsClaim = groupsClaim.(string)
}
if len(role.BoundAudiences) == 0 &&
len(role.BoundCIDRs) == 0 &&
role.BoundSubject == "" {
return logical.ErrorResponse("must have at least one bound constraint when creating/updating a role"), nil
}
// Check that the TTL value provided is less than the MaxTTL.
// Sanitizing the TTL and MaxTTL is not required now and can be performed
// at credential issue time.
if role.MaxTTL > 0 && role.TTL > role.MaxTTL {
return logical.ErrorResponse("ttl should not be greater than max_ttl"), nil
}
var resp *logical.Response
if role.MaxTTL > b.System().MaxLeaseTTL() {
resp = &logical.Response{}
resp.AddWarning("max_ttl is greater than the system or backend mount's maximum TTL value; issued tokens' max TTL value will be truncated")
}
// Store the entry.
entry, err := logical.StorageEntryJSON(rolePrefix+roleName, role)
if err != nil {
return nil, err
}
if err = req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
return resp, nil
}
// roleStorageEntry stores all the options that are set on an role
var roleHelp = map[string][2]string{
"role-list": {
"Lists all the roles registered with the backend.",
"The list will contain the names of the roles.",
},
"role": {
"Register an role with the backend.",
`A role is required to authenticate with this backend. The role binds
JWT token information with token policies and settings.
The bindings, token polices and token settings can all be configured
using this endpoint`,
},
}

6
vendor/vendor.json vendored
View File

@ -1268,6 +1268,12 @@
"revision": "00e5bbe1b7d82707a43ae69de55a240fc888275e",
"revisionTime": "2018-06-06T02:26:37Z"
},
{
"checksumSHA1": "W0xV5xs8CYxSSGp619gG2RemfMY=",
"path": "github.com/hashicorp/vault-plugin-auth-jwt",
"revision": "e579104468327c5aad46cbc92ae6a9ca3a692147",
"revisionTime": "2018-07-09T20:20:09Z"
},
{
"checksumSHA1": "L5pDwOw2/MLLUSykrwxXbXQI7zI=",
"path": "github.com/hashicorp/vault-plugin-auth-kubernetes",