From 0fdebaf8215e9480896f01ec7ab2ef7caa242da1 Mon Sep 17 00:00:00 2001 From: Rohith Date: Sat, 10 Jun 2017 22:51:45 +0100 Subject: [PATCH 1/4] - updating the coreos go-oidc dep to use the fork for now --- Godeps/Godeps.json | 49 +- doc.go | 2 +- forwarding.go | 4 +- handlers.go | 2 +- middleware.go | 2 +- middleware_test.go | 2 +- misc.go | 2 +- oauth.go | 6 +- oauth_test.go | 4 +- server.go | 2 +- server_test.go | 2 +- session.go | 2 +- stores.go | 2 +- user_context.go | 4 +- utils.go | 4 +- vendor/github.com/coreos/go-oidc/oidc/doc.go | 2 - vendor/github.com/gambol99/go-oidc/LICENSE | 202 +++++++ vendor/github.com/gambol99/go-oidc/NOTICE | 5 + .../gambol99/go-oidc/http/client.go | 7 + .../github.com/gambol99/go-oidc/http/doc.go | 2 + .../github.com/gambol99/go-oidc/http/http.go | 156 +++++ .../github.com/gambol99/go-oidc/http/url.go | 29 + .../gambol99/go-oidc/jose/claims.go | 126 ++++ .../github.com/gambol99/go-oidc/jose/doc.go | 2 + .../github.com/gambol99/go-oidc/jose/jose.go | 112 ++++ .../github.com/gambol99/go-oidc/jose/jwk.go | 135 +++++ .../github.com/gambol99/go-oidc/jose/jws.go | 51 ++ .../github.com/gambol99/go-oidc/jose/jwt.go | 82 +++ .../github.com/gambol99/go-oidc/jose/sig.go | 24 + .../gambol99/go-oidc/jose/sig_rsa.go | 67 +++ vendor/github.com/gambol99/go-oidc/key/doc.go | 2 + vendor/github.com/gambol99/go-oidc/key/key.go | 153 +++++ .../gambol99/go-oidc/key/manager.go | 99 ++++ .../github.com/gambol99/go-oidc/key/repo.go | 55 ++ .../github.com/gambol99/go-oidc/key/rotate.go | 159 ++++++ .../github.com/gambol99/go-oidc/key/sync.go | 91 +++ .../github.com/gambol99/go-oidc/oauth2/doc.go | 2 + .../gambol99/go-oidc/oauth2/error.go | 29 + .../gambol99/go-oidc/oauth2/oauth2.go | 416 ++++++++++++++ .../go-oidc/oidc/client.go | 52 +- .../github.com/gambol99/go-oidc/oidc/doc.go | 2 + .../go-oidc/oidc/identity.go | 2 +- .../go-oidc/oidc/interface.go | 0 .../{coreos => gambol99}/go-oidc/oidc/key.go | 6 +- .../go-oidc/oidc/provider.go | 9 +- .../go-oidc/oidc/transport.go | 4 +- .../{coreos => gambol99}/go-oidc/oidc/util.go | 2 +- .../go-oidc/oidc/verification.go | 59 +- .../testify/assert/assertion_format.go | 379 ++++++++++++ .../testify/assert/assertion_format.go.tmpl | 4 + .../testify/assert/assertion_forward.go | 450 ++++++++++++++- .../stretchr/testify/assert/assertions.go | 217 +++++-- .../testify/assert/forward_assertions.go | 2 +- .../testify/assert/http_assertions.go | 49 +- .../testify/require/forward_requirements.go | 2 +- .../stretchr/testify/require/require.go | 538 +++++++++++++++++- .../testify/require/require_forward.go | 450 ++++++++++++++- .../stretchr/testify/require/requirements.go | 2 +- 58 files changed, 4089 insertions(+), 237 deletions(-) delete mode 100644 vendor/github.com/coreos/go-oidc/oidc/doc.go create mode 100644 vendor/github.com/gambol99/go-oidc/LICENSE create mode 100644 vendor/github.com/gambol99/go-oidc/NOTICE create mode 100644 vendor/github.com/gambol99/go-oidc/http/client.go create mode 100644 vendor/github.com/gambol99/go-oidc/http/doc.go create mode 100644 vendor/github.com/gambol99/go-oidc/http/http.go create mode 100644 vendor/github.com/gambol99/go-oidc/http/url.go create mode 100644 vendor/github.com/gambol99/go-oidc/jose/claims.go create mode 100644 vendor/github.com/gambol99/go-oidc/jose/doc.go create mode 100644 vendor/github.com/gambol99/go-oidc/jose/jose.go create mode 100644 vendor/github.com/gambol99/go-oidc/jose/jwk.go create mode 100644 vendor/github.com/gambol99/go-oidc/jose/jws.go create mode 100644 vendor/github.com/gambol99/go-oidc/jose/jwt.go create mode 100755 vendor/github.com/gambol99/go-oidc/jose/sig.go create mode 100755 vendor/github.com/gambol99/go-oidc/jose/sig_rsa.go create mode 100644 vendor/github.com/gambol99/go-oidc/key/doc.go create mode 100644 vendor/github.com/gambol99/go-oidc/key/key.go create mode 100644 vendor/github.com/gambol99/go-oidc/key/manager.go create mode 100644 vendor/github.com/gambol99/go-oidc/key/repo.go create mode 100644 vendor/github.com/gambol99/go-oidc/key/rotate.go create mode 100644 vendor/github.com/gambol99/go-oidc/key/sync.go create mode 100644 vendor/github.com/gambol99/go-oidc/oauth2/doc.go create mode 100644 vendor/github.com/gambol99/go-oidc/oauth2/error.go create mode 100644 vendor/github.com/gambol99/go-oidc/oauth2/oauth2.go rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/client.go (96%) create mode 100644 vendor/github.com/gambol99/go-oidc/oidc/doc.go rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/identity.go (95%) rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/interface.go (100%) rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/key.go (93%) rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/provider.go (98%) rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/transport.go (95%) rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/util.go (98%) rename vendor/github.com/{coreos => gambol99}/go-oidc/oidc/verification.go (75%) create mode 100644 vendor/github.com/stretchr/testify/assert/assertion_format.go create mode 100644 vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 52f21f61..e42e79ac 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -32,23 +32,19 @@ }, { "ImportPath": "github.com/coreos/go-oidc/http", - "Rev": "dedb650fb29c39c2f21aa88c1e4cec66da8754d1" + "Rev": "c797a55f1c1001ec3169f1d0fbb4c5523563bec6" }, { "ImportPath": "github.com/coreos/go-oidc/jose", - "Rev": "dedb650fb29c39c2f21aa88c1e4cec66da8754d1" + "Rev": "c797a55f1c1001ec3169f1d0fbb4c5523563bec6" }, { "ImportPath": "github.com/coreos/go-oidc/key", - "Rev": "dedb650fb29c39c2f21aa88c1e4cec66da8754d1" + "Rev": "c797a55f1c1001ec3169f1d0fbb4c5523563bec6" }, { "ImportPath": "github.com/coreos/go-oidc/oauth2", - "Rev": "dedb650fb29c39c2f21aa88c1e4cec66da8754d1" - }, - { - "ImportPath": "github.com/coreos/go-oidc/oidc", - "Rev": "dedb650fb29c39c2f21aa88c1e4cec66da8754d1" + "Rev": "c797a55f1c1001ec3169f1d0fbb4c5523563bec6" }, { "ImportPath": "github.com/coreos/pkg/health", @@ -79,6 +75,18 @@ "Comment": "v1.4.2-2-gfd9ec7d", "Rev": "fd9ec7deca8bf46ecd2a795baaacf2b3a9be1197" }, + { + "ImportPath": "github.com/gambol99/go-oidc/jose", + "Rev": "2111f98a1397a35f1800f4c3c354a7abebbef75c" + }, + { + "ImportPath": "github.com/gambol99/go-oidc/oauth2", + "Rev": "2111f98a1397a35f1800f4c3c354a7abebbef75c" + }, + { + "ImportPath": "github.com/gambol99/go-oidc/oidc", + "Rev": "2111f98a1397a35f1800f4c3c354a7abebbef75c" + }, { "ImportPath": "github.com/gambol99/goproxy", "Comment": "v1.0-87-gc3b6ff1", @@ -173,8 +181,13 @@ }, { "ImportPath": "github.com/stretchr/testify/assert", - "Comment": "v1.1.4-27-g4d4bfba", - "Rev": "4d4bfba8f1d1027c4fdbe371823030df51419987" + "Comment": "v1.1.4-66-gf6abca5", + "Rev": "f6abca593680b2315d2075e0f5e2a9751e3f431a" + }, + { + "ImportPath": "github.com/stretchr/testify/require", + "Comment": "v1.1.4-66-gf6abca5", + "Rev": "f6abca593680b2315d2075e0f5e2a9751e3f431a" }, { "ImportPath": "github.com/unrolled/secure", @@ -266,15 +279,23 @@ "ImportPath": "gopkg.in/yaml.v2", "Rev": "49c95bdc21843256fb6c4e0d370a05f24a0bf213" }, + { + "ImportPath": "github.com/gambol99/go-oidc/http", + "Rev": "2111f98a1397a35f1800f4c3c354a7abebbef75c" + }, + { + "ImportPath": "github.com/gambol99/go-oidc/key", + "Rev": "2111f98a1397a35f1800f4c3c354a7abebbef75c" + }, { "ImportPath": "github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew", - "Comment": "v1.1.4-27-g4d4bfba", - "Rev": "4d4bfba8f1d1027c4fdbe371823030df51419987" + "Comment": "v1.1.4-66-gf6abca5", + "Rev": "f6abca593680b2315d2075e0f5e2a9751e3f431a" }, { "ImportPath": "github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib", - "Comment": "v1.1.4-27-g4d4bfba", - "Rev": "4d4bfba8f1d1027c4fdbe371823030df51419987" + "Comment": "v1.1.4-66-gf6abca5", + "Rev": "f6abca593680b2315d2075e0f5e2a9751e3f431a" } ] } diff --git a/doc.go b/doc.go index a75b0390..2670cbb9 100644 --- a/doc.go +++ b/doc.go @@ -22,7 +22,7 @@ import ( "strconv" "time" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" ) var ( diff --git a/forwarding.go b/forwarding.go index 9c93eac2..296d900f 100644 --- a/forwarding.go +++ b/forwarding.go @@ -21,8 +21,8 @@ import ( "time" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/oidc" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/oidc" "github.com/labstack/echo" ) diff --git a/handlers.go b/handlers.go index 023eb63d..9a5ef1e4 100644 --- a/handlers.go +++ b/handlers.go @@ -30,7 +30,7 @@ import ( "time" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/oauth2" + "github.com/gambol99/go-oidc/oauth2" "github.com/labstack/echo" ) diff --git a/middleware.go b/middleware.go index 470fcb1d..1a0ba03a 100644 --- a/middleware.go +++ b/middleware.go @@ -24,7 +24,7 @@ import ( "github.com/PuerkitoBio/purell" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" "github.com/labstack/echo" "github.com/prometheus/client_golang/prometheus" "github.com/unrolled/secure" diff --git a/middleware_test.go b/middleware_test.go index 78ab7568..6f51fdee 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -25,7 +25,7 @@ import ( "time" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" "github.com/go-resty/resty" "github.com/labstack/echo/middleware" "github.com/stretchr/testify/assert" diff --git a/misc.go b/misc.go index 4f238bf1..82d9c06f 100644 --- a/misc.go +++ b/misc.go @@ -23,7 +23,7 @@ import ( "time" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" "github.com/labstack/echo" ) diff --git a/oauth.go b/oauth.go index 018ee968..41787390 100644 --- a/oauth.go +++ b/oauth.go @@ -24,9 +24,9 @@ import ( "strings" "time" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/oauth2" - "github.com/coreos/go-oidc/oidc" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/oauth2" + "github.com/gambol99/go-oidc/oidc" ) // getOAuthClient returns a oauth2 client from the openid client diff --git a/oauth_test.go b/oauth_test.go index 3f36d4f6..ec1c4ed6 100644 --- a/oauth_test.go +++ b/oauth_test.go @@ -27,8 +27,8 @@ import ( "testing" "time" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/oauth2" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/oauth2" "github.com/labstack/echo" "github.com/stretchr/testify/assert" ) diff --git a/server.go b/server.go index 8e73e06e..2c1892dc 100644 --- a/server.go +++ b/server.go @@ -34,7 +34,7 @@ import ( log "github.com/Sirupsen/logrus" "github.com/armon/go-proxyproto" - "github.com/coreos/go-oidc/oidc" + "github.com/gambol99/go-oidc/oidc" "github.com/gambol99/goproxy" "github.com/labstack/echo" "github.com/labstack/echo/middleware" diff --git a/server_test.go b/server_test.go index 3106ddb6..52fb3992 100644 --- a/server_test.go +++ b/server_test.go @@ -28,7 +28,7 @@ import ( "time" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" "github.com/stretchr/testify/assert" ) diff --git a/session.go b/session.go index 312a360f..a8423693 100644 --- a/session.go +++ b/session.go @@ -20,7 +20,7 @@ import ( "strings" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" ) // getIdentity retrieves the user identity from a request, either from a session cookie or a bearer token diff --git a/stores.go b/stores.go index a5db9973..4eda6fea 100644 --- a/stores.go +++ b/stores.go @@ -20,7 +20,7 @@ import ( "net/url" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" ) // createStorage creates the store client for use diff --git a/user_context.go b/user_context.go index 4d1bbad5..875085f2 100644 --- a/user_context.go +++ b/user_context.go @@ -20,8 +20,8 @@ import ( "strings" "time" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/oidc" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/oidc" ) // extractIdentity parse the jwt token and extracts the various elements is order to construct diff --git a/utils.go b/utils.go index 4b33b122..77213cc9 100644 --- a/utils.go +++ b/utils.go @@ -41,8 +41,8 @@ import ( "unicode/utf8" log "github.com/Sirupsen/logrus" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/oidc" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/oidc" "github.com/labstack/echo" "github.com/urfave/cli" "gopkg.in/yaml.v2" diff --git a/vendor/github.com/coreos/go-oidc/oidc/doc.go b/vendor/github.com/coreos/go-oidc/oidc/doc.go deleted file mode 100644 index 196611ec..00000000 --- a/vendor/github.com/coreos/go-oidc/oidc/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package oidc is DEPRECATED. Use github.com/coreos/go-oidc instead. -package oidc diff --git a/vendor/github.com/gambol99/go-oidc/LICENSE b/vendor/github.com/gambol99/go-oidc/LICENSE new file mode 100644 index 00000000..e06d2081 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/vendor/github.com/gambol99/go-oidc/NOTICE b/vendor/github.com/gambol99/go-oidc/NOTICE new file mode 100644 index 00000000..b39ddfa5 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/NOTICE @@ -0,0 +1,5 @@ +CoreOS Project +Copyright 2014 CoreOS, Inc + +This product includes software developed at CoreOS, Inc. +(http://www.coreos.com/). diff --git a/vendor/github.com/gambol99/go-oidc/http/client.go b/vendor/github.com/gambol99/go-oidc/http/client.go new file mode 100644 index 00000000..fd079b49 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/http/client.go @@ -0,0 +1,7 @@ +package http + +import "net/http" + +type Client interface { + Do(*http.Request) (*http.Response, error) +} diff --git a/vendor/github.com/gambol99/go-oidc/http/doc.go b/vendor/github.com/gambol99/go-oidc/http/doc.go new file mode 100644 index 00000000..5687e8b8 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/http/doc.go @@ -0,0 +1,2 @@ +// Package http is DEPRECATED. Use net/http instead. +package http diff --git a/vendor/github.com/gambol99/go-oidc/http/http.go b/vendor/github.com/gambol99/go-oidc/http/http.go new file mode 100644 index 00000000..c3f51215 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/http/http.go @@ -0,0 +1,156 @@ +package http + +import ( + "encoding/base64" + "encoding/json" + "errors" + "log" + "net/http" + "net/url" + "path" + "strconv" + "strings" + "time" +) + +func WriteError(w http.ResponseWriter, code int, msg string) { + e := struct { + Error string `json:"error"` + }{ + Error: msg, + } + b, err := json.Marshal(e) + if err != nil { + log.Printf("go-oidc: failed to marshal %#v: %v", e, err) + code = http.StatusInternalServerError + b = []byte(`{"error":"server_error"}`) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + w.Write(b) +} + +// BasicAuth parses a username and password from the request's +// Authorization header. This was pulled from golang master: +// https://codereview.appspot.com/76540043 +func BasicAuth(r *http.Request) (username, password string, ok bool) { + auth := r.Header.Get("Authorization") + if auth == "" { + return + } + + if !strings.HasPrefix(auth, "Basic ") { + return + } + c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic ")) + if err != nil { + return + } + cs := string(c) + s := strings.IndexByte(cs, ':') + if s < 0 { + return + } + return cs[:s], cs[s+1:], true +} + +func cacheControlMaxAge(hdr string) (time.Duration, bool, error) { + for _, field := range strings.Split(hdr, ",") { + parts := strings.SplitN(strings.TrimSpace(field), "=", 2) + k := strings.ToLower(strings.TrimSpace(parts[0])) + if k != "max-age" { + continue + } + + if len(parts) == 1 { + return 0, false, errors.New("max-age has no value") + } + + v := strings.TrimSpace(parts[1]) + if v == "" { + return 0, false, errors.New("max-age has empty value") + } + + age, err := strconv.Atoi(v) + if err != nil { + return 0, false, err + } + + if age <= 0 { + return 0, false, nil + } + + return time.Duration(age) * time.Second, true, nil + } + + return 0, false, nil +} + +func expires(date, expires string) (time.Duration, bool, error) { + if date == "" || expires == "" { + return 0, false, nil + } + + te, err := time.Parse(time.RFC1123, expires) + if err != nil { + return 0, false, err + } + + td, err := time.Parse(time.RFC1123, date) + if err != nil { + return 0, false, err + } + + ttl := te.Sub(td) + + // headers indicate data already expired, caller should not + // have to care about this case + if ttl <= 0 { + return 0, false, nil + } + + return ttl, true, nil +} + +func Cacheable(hdr http.Header) (time.Duration, bool, error) { + ttl, ok, err := cacheControlMaxAge(hdr.Get("Cache-Control")) + if err != nil || ok { + return ttl, ok, err + } + + return expires(hdr.Get("Date"), hdr.Get("Expires")) +} + +// MergeQuery appends additional query values to an existing URL. +func MergeQuery(u url.URL, q url.Values) url.URL { + uv := u.Query() + for k, vs := range q { + for _, v := range vs { + uv.Add(k, v) + } + } + u.RawQuery = uv.Encode() + return u +} + +// NewResourceLocation appends a resource id to the end of the requested URL path. +func NewResourceLocation(reqURL *url.URL, id string) string { + var u url.URL + u = *reqURL + u.Path = path.Join(u.Path, id) + u.RawQuery = "" + u.Fragment = "" + return u.String() +} + +// CopyRequest returns a clone of the provided *http.Request. +// The returned object is a shallow copy of the struct and a +// deep copy of its Header field. +func CopyRequest(r *http.Request) *http.Request { + r2 := *r + r2.Header = make(http.Header) + for k, s := range r.Header { + r2.Header[k] = s + } + return &r2 +} diff --git a/vendor/github.com/gambol99/go-oidc/http/url.go b/vendor/github.com/gambol99/go-oidc/http/url.go new file mode 100644 index 00000000..df60eb1a --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/http/url.go @@ -0,0 +1,29 @@ +package http + +import ( + "errors" + "net/url" +) + +// ParseNonEmptyURL checks that a string is a parsable URL which is also not empty +// since `url.Parse("")` does not return an error. Must contian a scheme and a host. +func ParseNonEmptyURL(u string) (*url.URL, error) { + if u == "" { + return nil, errors.New("url is empty") + } + + ur, err := url.Parse(u) + if err != nil { + return nil, err + } + + if ur.Scheme == "" { + return nil, errors.New("url scheme is empty") + } + + if ur.Host == "" { + return nil, errors.New("url host is empty") + } + + return ur, nil +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/claims.go b/vendor/github.com/gambol99/go-oidc/jose/claims.go new file mode 100644 index 00000000..8b48bfd2 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/claims.go @@ -0,0 +1,126 @@ +package jose + +import ( + "encoding/json" + "fmt" + "math" + "time" +) + +type Claims map[string]interface{} + +func (c Claims) Add(name string, value interface{}) { + c[name] = value +} + +func (c Claims) StringClaim(name string) (string, bool, error) { + cl, ok := c[name] + if !ok { + return "", false, nil + } + + v, ok := cl.(string) + if !ok { + return "", false, fmt.Errorf("unable to parse claim as string: %v", name) + } + + return v, true, nil +} + +func (c Claims) StringsClaim(name string) ([]string, bool, error) { + cl, ok := c[name] + if !ok { + return nil, false, nil + } + + if v, ok := cl.([]string); ok { + return v, true, nil + } + + // When unmarshaled, []string will become []interface{}. + if v, ok := cl.([]interface{}); ok { + var ret []string + for _, vv := range v { + str, ok := vv.(string) + if !ok { + return nil, false, fmt.Errorf("unable to parse claim as string array: %v", name) + } + ret = append(ret, str) + } + return ret, true, nil + } + + return nil, false, fmt.Errorf("unable to parse claim as string array: %v", name) +} + +func (c Claims) Int64Claim(name string) (int64, bool, error) { + cl, ok := c[name] + if !ok { + return 0, false, nil + } + + v, ok := cl.(int64) + if !ok { + vf, ok := cl.(float64) + if !ok { + return 0, false, fmt.Errorf("unable to parse claim as int64: %v", name) + } + v = int64(vf) + } + + return v, true, nil +} + +func (c Claims) Float64Claim(name string) (float64, bool, error) { + cl, ok := c[name] + if !ok { + return 0, false, nil + } + + v, ok := cl.(float64) + if !ok { + vi, ok := cl.(int64) + if !ok { + return 0, false, fmt.Errorf("unable to parse claim as float64: %v", name) + } + v = float64(vi) + } + + return v, true, nil +} + +func (c Claims) TimeClaim(name string) (time.Time, bool, error) { + v, ok, err := c.Float64Claim(name) + if !ok || err != nil { + return time.Time{}, ok, err + } + + s := math.Trunc(v) + ns := (v - s) * math.Pow(10, 9) + return time.Unix(int64(s), int64(ns)).UTC(), true, nil +} + +func decodeClaims(payload []byte) (Claims, error) { + var c Claims + if err := json.Unmarshal(payload, &c); err != nil { + return nil, fmt.Errorf("malformed JWT claims, unable to decode: %v", err) + } + return c, nil +} + +func marshalClaims(c Claims) ([]byte, error) { + b, err := json.Marshal(c) + if err != nil { + return nil, err + } + return b, nil +} + +func encodeClaims(c Claims) (string, error) { + b, err := marshalClaims(c) + if err != nil { + return "", err + } + + return encodeSegment(b), nil +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/doc.go b/vendor/github.com/gambol99/go-oidc/jose/doc.go new file mode 100644 index 00000000..b5e13217 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/doc.go @@ -0,0 +1,2 @@ +// Package jose is DEPRECATED. Use gopkg.in/square/go-jose.v2 instead. +package jose diff --git a/vendor/github.com/gambol99/go-oidc/jose/jose.go b/vendor/github.com/gambol99/go-oidc/jose/jose.go new file mode 100644 index 00000000..62099265 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/jose.go @@ -0,0 +1,112 @@ +package jose + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strings" +) + +const ( + HeaderMediaType = "typ" + HeaderKeyAlgorithm = "alg" + HeaderKeyID = "kid" +) + +const ( + // Encryption Algorithm Header Parameter Values for JWS + // See: https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#page-6 + AlgHS256 = "HS256" + AlgHS384 = "HS384" + AlgHS512 = "HS512" + AlgRS256 = "RS256" + AlgRS384 = "RS384" + AlgRS512 = "RS512" + AlgES256 = "ES256" + AlgES384 = "ES384" + AlgES512 = "ES512" + AlgPS256 = "PS256" + AlgPS384 = "PS384" + AlgPS512 = "PS512" + AlgNone = "none" +) + +const ( + // Algorithm Header Parameter Values for JWE + // See: https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-4.1 + AlgRSA15 = "RSA1_5" + AlgRSAOAEP = "RSA-OAEP" + AlgRSAOAEP256 = "RSA-OAEP-256" + AlgA128KW = "A128KW" + AlgA192KW = "A192KW" + AlgA256KW = "A256KW" + AlgDir = "dir" + AlgECDHES = "ECDH-ES" + AlgECDHESA128KW = "ECDH-ES+A128KW" + AlgECDHESA192KW = "ECDH-ES+A192KW" + AlgECDHESA256KW = "ECDH-ES+A256KW" + AlgA128GCMKW = "A128GCMKW" + AlgA192GCMKW = "A192GCMKW" + AlgA256GCMKW = "A256GCMKW" + AlgPBES2HS256A128KW = "PBES2-HS256+A128KW" + AlgPBES2HS384A192KW = "PBES2-HS384+A192KW" + AlgPBES2HS512A256KW = "PBES2-HS512+A256KW" +) + +const ( + // Encryption Algorithm Header Parameter Values for JWE + // See: https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#page-22 + EncA128CBCHS256 = "A128CBC-HS256" + EncA128CBCHS384 = "A128CBC-HS384" + EncA256CBCHS512 = "A256CBC-HS512" + EncA128GCM = "A128GCM" + EncA192GCM = "A192GCM" + EncA256GCM = "A256GCM" +) + +type JOSEHeader map[string]string + +func (j JOSEHeader) Validate() error { + if _, exists := j[HeaderKeyAlgorithm]; !exists { + return fmt.Errorf("header missing %q parameter", HeaderKeyAlgorithm) + } + + return nil +} + +func decodeHeader(seg string) (JOSEHeader, error) { + b, err := decodeSegment(seg) + if err != nil { + return nil, err + } + + var h JOSEHeader + err = json.Unmarshal(b, &h) + if err != nil { + return nil, err + } + + return h, nil +} + +func encodeHeader(h JOSEHeader) (string, error) { + b, err := json.Marshal(h) + if err != nil { + return "", err + } + + return encodeSegment(b), nil +} + +// Decode JWT specific base64url encoding with padding stripped +func decodeSegment(seg string) ([]byte, error) { + if l := len(seg) % 4; l != 0 { + seg += strings.Repeat("=", 4-l) + } + return base64.URLEncoding.DecodeString(seg) +} + +// Encode JWT specific base64url encoding with padding stripped +func encodeSegment(seg []byte) string { + return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/jwk.go b/vendor/github.com/gambol99/go-oidc/jose/jwk.go new file mode 100644 index 00000000..119f073f --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/jwk.go @@ -0,0 +1,135 @@ +package jose + +import ( + "bytes" + "encoding/base64" + "encoding/binary" + "encoding/json" + "math/big" + "strings" +) + +// JSON Web Key +// https://tools.ietf.org/html/draft-ietf-jose-json-web-key-36#page-5 +type JWK struct { + ID string + Type string + Alg string + Use string + Exponent int + Modulus *big.Int + Secret []byte +} + +type jwkJSON struct { + ID string `json:"kid"` + Type string `json:"kty"` + Alg string `json:"alg"` + Use string `json:"use"` + Exponent string `json:"e"` + Modulus string `json:"n"` +} + +func (j *JWK) MarshalJSON() ([]byte, error) { + t := jwkJSON{ + ID: j.ID, + Type: j.Type, + Alg: j.Alg, + Use: j.Use, + Exponent: encodeExponent(j.Exponent), + Modulus: encodeModulus(j.Modulus), + } + + return json.Marshal(&t) +} + +func (j *JWK) UnmarshalJSON(data []byte) error { + var t jwkJSON + err := json.Unmarshal(data, &t) + if err != nil { + return err + } + + e, err := decodeExponent(t.Exponent) + if err != nil { + return err + } + + n, err := decodeModulus(t.Modulus) + if err != nil { + return err + } + + j.ID = t.ID + j.Type = t.Type + j.Alg = t.Alg + j.Use = t.Use + j.Exponent = e + j.Modulus = n + + return nil +} + +type JWKSet struct { + Keys []JWK `json:"keys"` +} + +func decodeExponent(e string) (int, error) { + decE, err := decodeBase64URLPaddingOptional(e) + if err != nil { + return 0, err + } + var eBytes []byte + if len(decE) < 8 { + eBytes = make([]byte, 8-len(decE), 8) + eBytes = append(eBytes, decE...) + } else { + eBytes = decE + } + eReader := bytes.NewReader(eBytes) + var E uint64 + err = binary.Read(eReader, binary.BigEndian, &E) + if err != nil { + return 0, err + } + return int(E), nil +} + +func encodeExponent(e int) string { + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, uint64(e)) + var idx int + for ; idx < 8; idx++ { + if b[idx] != 0x0 { + break + } + } + return base64.RawURLEncoding.EncodeToString(b[idx:]) +} + +// Turns a URL encoded modulus of a key into a big int. +func decodeModulus(n string) (*big.Int, error) { + decN, err := decodeBase64URLPaddingOptional(n) + if err != nil { + return nil, err + } + N := big.NewInt(0) + N.SetBytes(decN) + return N, nil +} + +func encodeModulus(n *big.Int) string { + return base64.RawURLEncoding.EncodeToString(n.Bytes()) +} + +// decodeBase64URLPaddingOptional decodes Base64 whether there is padding or not. +// The stdlib version currently doesn't handle this. +// We can get rid of this is if this bug: +// https://github.com/golang/go/issues/4237 +// ever closes. +func decodeBase64URLPaddingOptional(e string) ([]byte, error) { + if m := len(e) % 4; m != 0 { + e += strings.Repeat("=", 4-m) + } + return base64.URLEncoding.DecodeString(e) +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/jws.go b/vendor/github.com/gambol99/go-oidc/jose/jws.go new file mode 100644 index 00000000..1049ece8 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/jws.go @@ -0,0 +1,51 @@ +package jose + +import ( + "fmt" + "strings" +) + +type JWS struct { + RawHeader string + Header JOSEHeader + RawPayload string + Payload []byte + Signature []byte +} + +// Given a raw encoded JWS token parses it and verifies the structure. +func ParseJWS(raw string) (JWS, error) { + parts := strings.Split(raw, ".") + if len(parts) != 3 { + return JWS{}, fmt.Errorf("malformed JWS, only %d segments", len(parts)) + } + + rawSig := parts[2] + jws := JWS{ + RawHeader: parts[0], + RawPayload: parts[1], + } + + header, err := decodeHeader(jws.RawHeader) + if err != nil { + return JWS{}, fmt.Errorf("malformed JWS, unable to decode header, %s", err) + } + if err = header.Validate(); err != nil { + return JWS{}, fmt.Errorf("malformed JWS, %s", err) + } + jws.Header = header + + payload, err := decodeSegment(jws.RawPayload) + if err != nil { + return JWS{}, fmt.Errorf("malformed JWS, unable to decode payload: %s", err) + } + jws.Payload = payload + + sig, err := decodeSegment(rawSig) + if err != nil { + return JWS{}, fmt.Errorf("malformed JWS, unable to decode signature: %s", err) + } + jws.Signature = sig + + return jws, nil +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/jwt.go b/vendor/github.com/gambol99/go-oidc/jose/jwt.go new file mode 100644 index 00000000..3b3e9634 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/jwt.go @@ -0,0 +1,82 @@ +package jose + +import "strings" + +type JWT JWS + +func ParseJWT(token string) (jwt JWT, err error) { + jws, err := ParseJWS(token) + if err != nil { + return + } + + return JWT(jws), nil +} + +func NewJWT(header JOSEHeader, claims Claims) (jwt JWT, err error) { + jwt = JWT{} + + jwt.Header = header + jwt.Header[HeaderMediaType] = "JWT" + + claimBytes, err := marshalClaims(claims) + if err != nil { + return + } + jwt.Payload = claimBytes + + eh, err := encodeHeader(header) + if err != nil { + return + } + jwt.RawHeader = eh + + ec, err := encodeClaims(claims) + if err != nil { + return + } + jwt.RawPayload = ec + + return +} + +func (j *JWT) KeyID() (string, bool) { + kID, ok := j.Header[HeaderKeyID] + return kID, ok +} + +func (j *JWT) Claims() (Claims, error) { + return decodeClaims(j.Payload) +} + +// Encoded data part of the token which may be signed. +func (j *JWT) Data() string { + return strings.Join([]string{j.RawHeader, j.RawPayload}, ".") +} + +// Full encoded JWT token string in format: header.claims.signature +func (j *JWT) Encode() string { + d := j.Data() + s := encodeSegment(j.Signature) + return strings.Join([]string{d, s}, ".") +} + +func NewSignedJWT(claims Claims, s Signer) (*JWT, error) { + header := JOSEHeader{ + HeaderKeyAlgorithm: s.Alg(), + HeaderKeyID: s.ID(), + } + + jwt, err := NewJWT(header, claims) + if err != nil { + return nil, err + } + + sig, err := s.Sign([]byte(jwt.Data())) + if err != nil { + return nil, err + } + jwt.Signature = sig + + return &jwt, nil +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/sig.go b/vendor/github.com/gambol99/go-oidc/jose/sig.go new file mode 100755 index 00000000..7b2b253c --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/sig.go @@ -0,0 +1,24 @@ +package jose + +import ( + "fmt" +) + +type Verifier interface { + ID() string + Alg() string + Verify(sig []byte, data []byte) error +} + +type Signer interface { + Verifier + Sign(data []byte) (sig []byte, err error) +} + +func NewVerifier(jwk JWK) (Verifier, error) { + if jwk.Type != "RSA" { + return nil, fmt.Errorf("unsupported key type %q", jwk.Type) + } + + return NewVerifierRSA(jwk) +} diff --git a/vendor/github.com/gambol99/go-oidc/jose/sig_rsa.go b/vendor/github.com/gambol99/go-oidc/jose/sig_rsa.go new file mode 100755 index 00000000..004e45dd --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/jose/sig_rsa.go @@ -0,0 +1,67 @@ +package jose + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "fmt" +) + +type VerifierRSA struct { + KeyID string + Hash crypto.Hash + PublicKey rsa.PublicKey +} + +type SignerRSA struct { + PrivateKey rsa.PrivateKey + VerifierRSA +} + +func NewVerifierRSA(jwk JWK) (*VerifierRSA, error) { + if jwk.Alg != "" && jwk.Alg != "RS256" { + return nil, fmt.Errorf("unsupported key algorithm %q", jwk.Alg) + } + + v := VerifierRSA{ + KeyID: jwk.ID, + PublicKey: rsa.PublicKey{ + N: jwk.Modulus, + E: jwk.Exponent, + }, + Hash: crypto.SHA256, + } + + return &v, nil +} + +func NewSignerRSA(kid string, key rsa.PrivateKey) *SignerRSA { + return &SignerRSA{ + PrivateKey: key, + VerifierRSA: VerifierRSA{ + KeyID: kid, + PublicKey: key.PublicKey, + Hash: crypto.SHA256, + }, + } +} + +func (v *VerifierRSA) ID() string { + return v.KeyID +} + +func (v *VerifierRSA) Alg() string { + return "RS256" +} + +func (v *VerifierRSA) Verify(sig []byte, data []byte) error { + h := v.Hash.New() + h.Write(data) + return rsa.VerifyPKCS1v15(&v.PublicKey, v.Hash, h.Sum(nil), sig) +} + +func (s *SignerRSA) Sign(data []byte) ([]byte, error) { + h := s.Hash.New() + h.Write(data) + return rsa.SignPKCS1v15(rand.Reader, &s.PrivateKey, s.Hash, h.Sum(nil)) +} diff --git a/vendor/github.com/gambol99/go-oidc/key/doc.go b/vendor/github.com/gambol99/go-oidc/key/doc.go new file mode 100644 index 00000000..c5ecc491 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/key/doc.go @@ -0,0 +1,2 @@ +// Package key is DEPRECATED. Use github.com/gambol99/go-oidc instead. +package key diff --git a/vendor/github.com/gambol99/go-oidc/key/key.go b/vendor/github.com/gambol99/go-oidc/key/key.go new file mode 100644 index 00000000..034d6363 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/key/key.go @@ -0,0 +1,153 @@ +package key + +import ( + "crypto/rand" + "crypto/rsa" + "encoding/hex" + "encoding/json" + "io" + "time" + + "github.com/gambol99/go-oidc/jose" +) + +func NewPublicKey(jwk jose.JWK) *PublicKey { + return &PublicKey{jwk: jwk} +} + +type PublicKey struct { + jwk jose.JWK +} + +func (k *PublicKey) MarshalJSON() ([]byte, error) { + return json.Marshal(&k.jwk) +} + +func (k *PublicKey) UnmarshalJSON(data []byte) error { + var jwk jose.JWK + if err := json.Unmarshal(data, &jwk); err != nil { + return err + } + k.jwk = jwk + return nil +} + +func (k *PublicKey) ID() string { + return k.jwk.ID +} + +func (k *PublicKey) Verifier() (jose.Verifier, error) { + return jose.NewVerifierRSA(k.jwk) +} + +type PrivateKey struct { + KeyID string + PrivateKey *rsa.PrivateKey +} + +func (k *PrivateKey) ID() string { + return k.KeyID +} + +func (k *PrivateKey) Signer() jose.Signer { + return jose.NewSignerRSA(k.ID(), *k.PrivateKey) +} + +func (k *PrivateKey) JWK() jose.JWK { + return jose.JWK{ + ID: k.KeyID, + Type: "RSA", + Alg: "RS256", + Use: "sig", + Exponent: k.PrivateKey.PublicKey.E, + Modulus: k.PrivateKey.PublicKey.N, + } +} + +type KeySet interface { + ExpiresAt() time.Time +} + +type PublicKeySet struct { + keys []PublicKey + index map[string]*PublicKey + expiresAt time.Time +} + +func NewPublicKeySet(jwks []jose.JWK, exp time.Time) *PublicKeySet { + keys := make([]PublicKey, len(jwks)) + index := make(map[string]*PublicKey) + for i, jwk := range jwks { + keys[i] = *NewPublicKey(jwk) + index[keys[i].ID()] = &keys[i] + } + return &PublicKeySet{ + keys: keys, + index: index, + expiresAt: exp, + } +} + +func (s *PublicKeySet) ExpiresAt() time.Time { + return s.expiresAt +} + +func (s *PublicKeySet) Keys() []PublicKey { + return s.keys +} + +func (s *PublicKeySet) Key(id string) *PublicKey { + return s.index[id] +} + +type PrivateKeySet struct { + keys []*PrivateKey + ActiveKeyID string + expiresAt time.Time +} + +func NewPrivateKeySet(keys []*PrivateKey, exp time.Time) *PrivateKeySet { + return &PrivateKeySet{ + keys: keys, + ActiveKeyID: keys[0].ID(), + expiresAt: exp.UTC(), + } +} + +func (s *PrivateKeySet) Keys() []*PrivateKey { + return s.keys +} + +func (s *PrivateKeySet) ExpiresAt() time.Time { + return s.expiresAt +} + +func (s *PrivateKeySet) Active() *PrivateKey { + for i, k := range s.keys { + if k.ID() == s.ActiveKeyID { + return s.keys[i] + } + } + + return nil +} + +type GeneratePrivateKeyFunc func() (*PrivateKey, error) + +func GeneratePrivateKey() (*PrivateKey, error) { + pk, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return nil, err + } + keyID := make([]byte, 20) + if _, err := io.ReadFull(rand.Reader, keyID); err != nil { + return nil, err + } + + k := PrivateKey{ + KeyID: hex.EncodeToString(keyID), + PrivateKey: pk, + } + + return &k, nil +} diff --git a/vendor/github.com/gambol99/go-oidc/key/manager.go b/vendor/github.com/gambol99/go-oidc/key/manager.go new file mode 100644 index 00000000..d5f1b203 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/key/manager.go @@ -0,0 +1,99 @@ +package key + +import ( + "errors" + "time" + + "github.com/jonboulle/clockwork" + + "github.com/coreos/pkg/health" + "github.com/gambol99/go-oidc/jose" +) + +type PrivateKeyManager interface { + ExpiresAt() time.Time + Signer() (jose.Signer, error) + JWKs() ([]jose.JWK, error) + PublicKeys() ([]PublicKey, error) + + WritableKeySetRepo + health.Checkable +} + +func NewPrivateKeyManager() PrivateKeyManager { + return &privateKeyManager{ + clock: clockwork.NewRealClock(), + } +} + +type privateKeyManager struct { + keySet *PrivateKeySet + clock clockwork.Clock +} + +func (m *privateKeyManager) ExpiresAt() time.Time { + if m.keySet == nil { + return m.clock.Now().UTC() + } + + return m.keySet.ExpiresAt() +} + +func (m *privateKeyManager) Signer() (jose.Signer, error) { + if err := m.Healthy(); err != nil { + return nil, err + } + + return m.keySet.Active().Signer(), nil +} + +func (m *privateKeyManager) JWKs() ([]jose.JWK, error) { + if err := m.Healthy(); err != nil { + return nil, err + } + + keys := m.keySet.Keys() + jwks := make([]jose.JWK, len(keys)) + for i, k := range keys { + jwks[i] = k.JWK() + } + return jwks, nil +} + +func (m *privateKeyManager) PublicKeys() ([]PublicKey, error) { + jwks, err := m.JWKs() + if err != nil { + return nil, err + } + keys := make([]PublicKey, len(jwks)) + for i, jwk := range jwks { + keys[i] = *NewPublicKey(jwk) + } + return keys, nil +} + +func (m *privateKeyManager) Healthy() error { + if m.keySet == nil { + return errors.New("private key manager uninitialized") + } + + if len(m.keySet.Keys()) == 0 { + return errors.New("private key manager zero keys") + } + + if m.keySet.ExpiresAt().Before(m.clock.Now().UTC()) { + return errors.New("private key manager keys expired") + } + + return nil +} + +func (m *privateKeyManager) Set(keySet KeySet) error { + privKeySet, ok := keySet.(*PrivateKeySet) + if !ok { + return errors.New("unable to cast to PrivateKeySet") + } + + m.keySet = privKeySet + return nil +} diff --git a/vendor/github.com/gambol99/go-oidc/key/repo.go b/vendor/github.com/gambol99/go-oidc/key/repo.go new file mode 100644 index 00000000..1acdeb36 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/key/repo.go @@ -0,0 +1,55 @@ +package key + +import ( + "errors" + "sync" +) + +var ErrorNoKeys = errors.New("no keys found") + +type WritableKeySetRepo interface { + Set(KeySet) error +} + +type ReadableKeySetRepo interface { + Get() (KeySet, error) +} + +type PrivateKeySetRepo interface { + WritableKeySetRepo + ReadableKeySetRepo +} + +func NewPrivateKeySetRepo() PrivateKeySetRepo { + return &memPrivateKeySetRepo{} +} + +type memPrivateKeySetRepo struct { + mu sync.RWMutex + pks PrivateKeySet +} + +func (r *memPrivateKeySetRepo) Set(ks KeySet) error { + pks, ok := ks.(*PrivateKeySet) + if !ok { + return errors.New("unable to cast to PrivateKeySet") + } else if pks == nil { + return errors.New("nil KeySet") + } + + r.mu.Lock() + defer r.mu.Unlock() + + r.pks = *pks + return nil +} + +func (r *memPrivateKeySetRepo) Get() (KeySet, error) { + r.mu.RLock() + defer r.mu.RUnlock() + + if r.pks.keys == nil { + return nil, ErrorNoKeys + } + return KeySet(&r.pks), nil +} diff --git a/vendor/github.com/gambol99/go-oidc/key/rotate.go b/vendor/github.com/gambol99/go-oidc/key/rotate.go new file mode 100644 index 00000000..bc6cdfb1 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/key/rotate.go @@ -0,0 +1,159 @@ +package key + +import ( + "errors" + "log" + "time" + + ptime "github.com/coreos/pkg/timeutil" + "github.com/jonboulle/clockwork" +) + +var ( + ErrorPrivateKeysExpired = errors.New("private keys have expired") +) + +func NewPrivateKeyRotator(repo PrivateKeySetRepo, ttl time.Duration) *PrivateKeyRotator { + return &PrivateKeyRotator{ + repo: repo, + ttl: ttl, + + keep: 2, + generateKey: GeneratePrivateKey, + clock: clockwork.NewRealClock(), + } +} + +type PrivateKeyRotator struct { + repo PrivateKeySetRepo + generateKey GeneratePrivateKeyFunc + clock clockwork.Clock + keep int + ttl time.Duration +} + +func (r *PrivateKeyRotator) expiresAt() time.Time { + return r.clock.Now().UTC().Add(r.ttl) +} + +func (r *PrivateKeyRotator) Healthy() error { + pks, err := r.privateKeySet() + if err != nil { + return err + } + + if r.clock.Now().After(pks.ExpiresAt()) { + return ErrorPrivateKeysExpired + } + + return nil +} + +func (r *PrivateKeyRotator) privateKeySet() (*PrivateKeySet, error) { + ks, err := r.repo.Get() + if err != nil { + return nil, err + } + + pks, ok := ks.(*PrivateKeySet) + if !ok { + return nil, errors.New("unable to cast to PrivateKeySet") + } + return pks, nil +} + +func (r *PrivateKeyRotator) nextRotation() (time.Duration, error) { + pks, err := r.privateKeySet() + if err == ErrorNoKeys { + return 0, nil + } + if err != nil { + return 0, err + } + + now := r.clock.Now() + + // Ideally, we want to rotate after half the TTL has elapsed. + idealRotationTime := pks.ExpiresAt().Add(-r.ttl / 2) + + // If we are past the ideal rotation time, rotate immediatly. + return max(0, idealRotationTime.Sub(now)), nil +} + +func max(a, b time.Duration) time.Duration { + if a > b { + return a + } + return b +} + +func (r *PrivateKeyRotator) Run() chan struct{} { + attempt := func() { + k, err := r.generateKey() + if err != nil { + log.Printf("go-oidc: failed generating signing key: %v", err) + return + } + + exp := r.expiresAt() + if err := rotatePrivateKeys(r.repo, k, r.keep, exp); err != nil { + log.Printf("go-oidc: key rotation failed: %v", err) + return + } + } + + stop := make(chan struct{}) + go func() { + for { + var nextRotation time.Duration + var sleep time.Duration + var err error + for { + if nextRotation, err = r.nextRotation(); err == nil { + break + } + sleep = ptime.ExpBackoff(sleep, time.Minute) + log.Printf("go-oidc: error getting nextRotation, retrying in %v: %v", sleep, err) + time.Sleep(sleep) + } + + select { + case <-r.clock.After(nextRotation): + attempt() + case <-stop: + return + } + } + }() + + return stop +} + +func rotatePrivateKeys(repo PrivateKeySetRepo, k *PrivateKey, keep int, exp time.Time) error { + ks, err := repo.Get() + if err != nil && err != ErrorNoKeys { + return err + } + + var keys []*PrivateKey + if ks != nil { + pks, ok := ks.(*PrivateKeySet) + if !ok { + return errors.New("unable to cast to PrivateKeySet") + } + keys = pks.Keys() + } + + keys = append([]*PrivateKey{k}, keys...) + if l := len(keys); l > keep { + keys = keys[0:keep] + } + + nks := PrivateKeySet{ + keys: keys, + ActiveKeyID: k.ID(), + expiresAt: exp, + } + + return repo.Set(KeySet(&nks)) +} diff --git a/vendor/github.com/gambol99/go-oidc/key/sync.go b/vendor/github.com/gambol99/go-oidc/key/sync.go new file mode 100644 index 00000000..b887f7b5 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/key/sync.go @@ -0,0 +1,91 @@ +package key + +import ( + "errors" + "log" + "time" + + "github.com/jonboulle/clockwork" + + "github.com/coreos/pkg/timeutil" +) + +func NewKeySetSyncer(r ReadableKeySetRepo, w WritableKeySetRepo) *KeySetSyncer { + return &KeySetSyncer{ + readable: r, + writable: w, + clock: clockwork.NewRealClock(), + } +} + +type KeySetSyncer struct { + readable ReadableKeySetRepo + writable WritableKeySetRepo + clock clockwork.Clock +} + +func (s *KeySetSyncer) Run() chan struct{} { + stop := make(chan struct{}) + go func() { + var failing bool + var next time.Duration + for { + exp, err := syncKeySet(s.readable, s.writable, s.clock) + if err != nil || exp == 0 { + if !failing { + failing = true + next = time.Second + } else { + next = timeutil.ExpBackoff(next, time.Minute) + } + if exp == 0 { + log.Printf("Synced to already expired key set, retrying in %v: %v", next, err) + + } else { + log.Printf("Failed syncing key set, retrying in %v: %v", next, err) + } + } else { + failing = false + next = exp / 2 + } + + select { + case <-s.clock.After(next): + continue + case <-stop: + return + } + } + }() + + return stop +} + +func Sync(r ReadableKeySetRepo, w WritableKeySetRepo) (time.Duration, error) { + return syncKeySet(r, w, clockwork.NewRealClock()) +} + +// syncKeySet copies the keyset from r to the KeySet at w and returns the duration in which the KeySet will expire. +// If keyset has already expired, returns a zero duration. +func syncKeySet(r ReadableKeySetRepo, w WritableKeySetRepo, clock clockwork.Clock) (exp time.Duration, err error) { + var ks KeySet + ks, err = r.Get() + if err != nil { + return + } + + if ks == nil { + err = errors.New("no source KeySet") + return + } + + if err = w.Set(ks); err != nil { + return + } + + now := clock.Now() + if ks.ExpiresAt().After(now) { + exp = ks.ExpiresAt().Sub(now) + } + return +} diff --git a/vendor/github.com/gambol99/go-oidc/oauth2/doc.go b/vendor/github.com/gambol99/go-oidc/oauth2/doc.go new file mode 100644 index 00000000..52eb3085 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/oauth2/doc.go @@ -0,0 +1,2 @@ +// Package oauth2 is DEPRECATED. Use golang.org/x/oauth instead. +package oauth2 diff --git a/vendor/github.com/gambol99/go-oidc/oauth2/error.go b/vendor/github.com/gambol99/go-oidc/oauth2/error.go new file mode 100644 index 00000000..50d89094 --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/oauth2/error.go @@ -0,0 +1,29 @@ +package oauth2 + +const ( + ErrorAccessDenied = "access_denied" + ErrorInvalidClient = "invalid_client" + ErrorInvalidGrant = "invalid_grant" + ErrorInvalidRequest = "invalid_request" + ErrorServerError = "server_error" + ErrorUnauthorizedClient = "unauthorized_client" + ErrorUnsupportedGrantType = "unsupported_grant_type" + ErrorUnsupportedResponseType = "unsupported_response_type" +) + +type Error struct { + Type string `json:"error"` + Description string `json:"error_description,omitempty"` + State string `json:"state,omitempty"` +} + +func (e *Error) Error() string { + if e.Description != "" { + return e.Type + ": " + e.Description + } + return e.Type +} + +func NewError(typ string) *Error { + return &Error{Type: typ} +} diff --git a/vendor/github.com/gambol99/go-oidc/oauth2/oauth2.go b/vendor/github.com/gambol99/go-oidc/oauth2/oauth2.go new file mode 100644 index 00000000..fdb69abb --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/oauth2/oauth2.go @@ -0,0 +1,416 @@ +package oauth2 + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "mime" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + + phttp "github.com/gambol99/go-oidc/http" +) + +// ResponseTypesEqual compares two response_type values. If either +// contains a space, it is treated as an unordered list. For example, +// comparing "code id_token" and "id_token code" would evaluate to true. +func ResponseTypesEqual(r1, r2 string) bool { + if !strings.Contains(r1, " ") || !strings.Contains(r2, " ") { + // fast route, no split needed + return r1 == r2 + } + + // split, sort, and compare + r1Fields := strings.Fields(r1) + r2Fields := strings.Fields(r2) + if len(r1Fields) != len(r2Fields) { + return false + } + sort.Strings(r1Fields) + sort.Strings(r2Fields) + for i, r1Field := range r1Fields { + if r1Field != r2Fields[i] { + return false + } + } + return true +} + +const ( + // OAuth2.0 response types registered by OIDC. + // + // See: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#RegistryContents + ResponseTypeCode = "code" + ResponseTypeCodeIDToken = "code id_token" + ResponseTypeCodeIDTokenToken = "code id_token token" + ResponseTypeIDToken = "id_token" + ResponseTypeIDTokenToken = "id_token token" + ResponseTypeToken = "token" + ResponseTypeNone = "none" +) + +const ( + GrantTypeAuthCode = "authorization_code" + GrantTypeClientCreds = "client_credentials" + GrantTypeUserCreds = "password" + GrantTypeImplicit = "implicit" + GrantTypeRefreshToken = "refresh_token" + + AuthMethodClientSecretPost = "client_secret_post" + AuthMethodClientSecretBasic = "client_secret_basic" + AuthMethodClientSecretJWT = "client_secret_jwt" + AuthMethodPrivateKeyJWT = "private_key_jwt" +) + +type Config struct { + Credentials ClientCredentials + Scope []string + RedirectURL string + AuthURL string + TokenURL string + + // Must be one of the AuthMethodXXX methods above. Right now, only + // AuthMethodClientSecretPost and AuthMethodClientSecretBasic are supported. + AuthMethod string +} + +type Client struct { + hc phttp.Client + creds ClientCredentials + scope []string + authURL *url.URL + redirectURL *url.URL + tokenURL *url.URL + authMethod string +} + +type ClientCredentials struct { + ID string + Secret string +} + +func NewClient(hc phttp.Client, cfg Config) (c *Client, err error) { + if len(cfg.Credentials.ID) == 0 { + err = errors.New("missing client id") + return + } + + if len(cfg.Credentials.Secret) == 0 { + err = errors.New("missing client secret") + return + } + + if cfg.AuthMethod == "" { + cfg.AuthMethod = AuthMethodClientSecretBasic + } else if cfg.AuthMethod != AuthMethodClientSecretPost && cfg.AuthMethod != AuthMethodClientSecretBasic { + err = fmt.Errorf("auth method %q is not supported", cfg.AuthMethod) + return + } + + au, err := phttp.ParseNonEmptyURL(cfg.AuthURL) + if err != nil { + return + } + + tu, err := phttp.ParseNonEmptyURL(cfg.TokenURL) + if err != nil { + return + } + + // Allow empty redirect URL in the case where the client + // only needs to verify a given token. + ru, err := url.Parse(cfg.RedirectURL) + if err != nil { + return + } + + c = &Client{ + creds: cfg.Credentials, + scope: cfg.Scope, + redirectURL: ru, + authURL: au, + tokenURL: tu, + hc: hc, + authMethod: cfg.AuthMethod, + } + + return +} + +// Return the embedded HTTP client +func (c *Client) HttpClient() phttp.Client { + return c.hc +} + +// Generate the url for initial redirect to oauth provider. +func (c *Client) AuthCodeURL(state, accessType, prompt string) string { + v := c.commonURLValues() + v.Set("state", state) + if strings.ToLower(accessType) == "offline" { + v.Set("access_type", "offline") + } + + if prompt != "" { + v.Set("prompt", prompt) + } + v.Set("response_type", "code") + + q := v.Encode() + u := *c.authURL + if u.RawQuery == "" { + u.RawQuery = q + } else { + u.RawQuery += "&" + q + } + return u.String() +} + +func (c *Client) commonURLValues() url.Values { + return url.Values{ + "redirect_uri": {c.redirectURL.String()}, + "scope": {strings.Join(c.scope, " ")}, + "client_id": {c.creds.ID}, + } +} + +func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) { + var req *http.Request + var err error + switch c.authMethod { + case AuthMethodClientSecretPost: + values.Set("client_secret", c.creds.Secret) + req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) + if err != nil { + return nil, err + } + case AuthMethodClientSecretBasic: + req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) + if err != nil { + return nil, err + } + encodedID := url.QueryEscape(c.creds.ID) + encodedSecret := url.QueryEscape(c.creds.Secret) + req.SetBasicAuth(encodedID, encodedSecret) + default: + panic("misconfigured client: auth method not supported") + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + return req, nil + +} + +// ClientCredsToken posts the client id and secret to obtain a token scoped to the OAuth2 client via the "client_credentials" grant type. +// May not be supported by all OAuth2 servers. +func (c *Client) ClientCredsToken(scope []string) (result TokenResponse, err error) { + v := url.Values{ + "scope": {strings.Join(scope, " ")}, + "grant_type": {GrantTypeClientCreds}, + } + + req, err := c.newAuthenticatedRequest(c.tokenURL.String(), v) + if err != nil { + return + } + + resp, err := c.hc.Do(req) + if err != nil { + return + } + defer resp.Body.Close() + + return parseTokenResponse(resp) +} + +// UserCredsToken posts the username and password to obtain a token scoped to the OAuth2 client via the "password" grant_type +// May not be supported by all OAuth2 servers. +func (c *Client) UserCredsToken(username, password string) (result TokenResponse, err error) { + v := url.Values{ + "scope": {strings.Join(c.scope, " ")}, + "grant_type": {GrantTypeUserCreds}, + "username": {username}, + "password": {password}, + } + + req, err := c.newAuthenticatedRequest(c.tokenURL.String(), v) + if err != nil { + return + } + + resp, err := c.hc.Do(req) + if err != nil { + return + } + defer resp.Body.Close() + + return parseTokenResponse(resp) +} + +// RequestToken requests a token from the Token Endpoint with the specified grantType. +// If 'grantType' == GrantTypeAuthCode, then 'value' should be the authorization code. +// If 'grantType' == GrantTypeRefreshToken, then 'value' should be the refresh token. +func (c *Client) RequestToken(grantType, value string) (result TokenResponse, err error) { + v := c.commonURLValues() + + v.Set("grant_type", grantType) + v.Set("client_secret", c.creds.Secret) + switch grantType { + case GrantTypeAuthCode: + v.Set("code", value) + case GrantTypeRefreshToken: + v.Set("refresh_token", value) + default: + err = fmt.Errorf("unsupported grant_type: %v", grantType) + return + } + + req, err := c.newAuthenticatedRequest(c.tokenURL.String(), v) + if err != nil { + return + } + + resp, err := c.hc.Do(req) + if err != nil { + return + } + defer resp.Body.Close() + + return parseTokenResponse(resp) +} + +func parseTokenResponse(resp *http.Response) (result TokenResponse, err error) { + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return + } + badStatusCode := resp.StatusCode < 200 || resp.StatusCode > 299 + + contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return + } + + result = TokenResponse{ + RawBody: body, + } + + newError := func(typ, desc, state string) error { + if typ == "" { + return fmt.Errorf("unrecognized error %s", body) + } + return &Error{typ, desc, state} + } + + if contentType == "application/x-www-form-urlencoded" || contentType == "text/plain" { + var vals url.Values + vals, err = url.ParseQuery(string(body)) + if err != nil { + return + } + if error := vals.Get("error"); error != "" || badStatusCode { + err = newError(error, vals.Get("error_description"), vals.Get("state")) + return + } + e := vals.Get("expires_in") + if e == "" { + e = vals.Get("expires") + } + if e != "" { + result.Expires, err = strconv.Atoi(e) + if err != nil { + return + } + } + result.AccessToken = vals.Get("access_token") + result.TokenType = vals.Get("token_type") + result.IDToken = vals.Get("id_token") + result.RefreshToken = vals.Get("refresh_token") + result.Scope = vals.Get("scope") + } else { + var r struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + IDToken string `json:"id_token"` + RefreshToken string `json:"refresh_token"` + Scope string `json:"scope"` + State string `json:"state"` + ExpiresIn json.Number `json:"expires_in"` // Azure AD returns string + Expires int `json:"expires"` + Error string `json:"error"` + Desc string `json:"error_description"` + } + if err = json.Unmarshal(body, &r); err != nil { + return + } + if r.Error != "" || badStatusCode { + err = newError(r.Error, r.Desc, r.State) + return + } + result.AccessToken = r.AccessToken + result.TokenType = r.TokenType + result.IDToken = r.IDToken + result.RefreshToken = r.RefreshToken + result.Scope = r.Scope + if expiresIn, err := r.ExpiresIn.Int64(); err != nil { + result.Expires = r.Expires + } else { + result.Expires = int(expiresIn) + } + } + return +} + +type TokenResponse struct { + AccessToken string + TokenType string + Expires int + IDToken string + RefreshToken string // OPTIONAL. + Scope string // OPTIONAL, if identical to the scope requested by the client, otherwise, REQUIRED. + RawBody []byte // In case callers need some other non-standard info from the token response +} + +type AuthCodeRequest struct { + ResponseType string + ClientID string + RedirectURL *url.URL + Scope []string + State string +} + +func ParseAuthCodeRequest(q url.Values) (AuthCodeRequest, error) { + acr := AuthCodeRequest{ + ResponseType: q.Get("response_type"), + ClientID: q.Get("client_id"), + State: q.Get("state"), + Scope: make([]string, 0), + } + + qs := strings.TrimSpace(q.Get("scope")) + if qs != "" { + acr.Scope = strings.Split(qs, " ") + } + + err := func() error { + if acr.ClientID == "" { + return NewError(ErrorInvalidRequest) + } + + redirectURL := q.Get("redirect_uri") + if redirectURL != "" { + ru, err := url.Parse(redirectURL) + if err != nil { + return NewError(ErrorInvalidRequest) + } + acr.RedirectURL = ru + } + + return nil + }() + + return acr, err +} diff --git a/vendor/github.com/coreos/go-oidc/oidc/client.go b/vendor/github.com/gambol99/go-oidc/oidc/client.go similarity index 96% rename from vendor/github.com/coreos/go-oidc/oidc/client.go rename to vendor/github.com/gambol99/go-oidc/oidc/client.go index 7a3cb40f..063461fa 100644 --- a/vendor/github.com/coreos/go-oidc/oidc/client.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/client.go @@ -10,10 +10,10 @@ import ( "sync" "time" - phttp "github.com/coreos/go-oidc/http" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/key" - "github.com/coreos/go-oidc/oauth2" + phttp "github.com/gambol99/go-oidc/http" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/key" + "github.com/gambol99/go-oidc/oauth2" ) const ( @@ -408,7 +408,7 @@ func emailsToStrings(addrs []mail.Address) []string { // // NOTE(ericchiang): For development purposes Valid does not mandate 'https' for // URLs fields where the OIDC spec requires it. This may change in future releases -// of this package. See: https://github.com/coreos/go-oidc/issues/34 +// of this package. See: https://github.com/gambol99/go-oidc/issues/34 func (m *ClientMetadata) Valid() error { if len(m.RedirectURIs) == 0 { return errors.New("zero redirect URLs") @@ -556,12 +556,13 @@ func (c *ClientRegistrationResponse) UnmarshalJSON(data []byte) error { } type ClientConfig struct { - HTTPClient phttp.Client - Credentials ClientCredentials - Scope []string - RedirectURL string - ProviderConfig ProviderConfig - KeySet key.PublicKeySet + Credentials ClientCredentials + HTTPClient phttp.Client + KeySet key.PublicKeySet + ProviderConfig ProviderConfig + RedirectURL string + Scope []string + SkipClientIDCheck bool } func NewClient(cfg ClientConfig) (*Client, error) { @@ -579,6 +580,7 @@ func NewClient(cfg ClientConfig) (*Client, error) { redirectURL: ru.String(), providerConfig: newProviderConfigRepo(cfg.ProviderConfig), keySet: cfg.KeySet, + skipClientID: cfg.SkipClientIDCheck, } if c.httpClient == nil { @@ -593,19 +595,21 @@ func NewClient(cfg ClientConfig) (*Client, error) { return &c, nil } +// Client is the oidc client type Client struct { - httpClient phttp.Client - providerConfig *providerConfigRepo - credentials ClientCredentials - redirectURL string - scope []string - keySet key.PublicKeySet - providerSyncer *ProviderConfigSyncer - + credentials ClientCredentials + httpClient phttp.Client + keySet key.PublicKeySet keySetSyncMutex sync.RWMutex lastKeySetSync time.Time + providerConfig *providerConfigRepo + providerSyncer *ProviderConfigSyncer + redirectURL string + scope []string + skipClientID bool } +// Healthy checks the provider is healthy func (c *Client) Healthy() error { now := time.Now().UTC() @@ -622,6 +626,7 @@ func (c *Client) Healthy() error { return nil } +// OAuthClient returns a oauth2 client func (c *Client) OAuthClient() (*oauth2.Client, error) { cfg := c.providerConfig.Get() authMethod, err := chooseAuthMethod(cfg) @@ -771,10 +776,11 @@ func (c *Client) RefreshToken(refreshToken string) (jose.JWT, error) { return jwt, c.VerifyJWT(jwt) } +// VerifyJWT verifies the JWT tokens func (c *Client) VerifyJWT(jwt jose.JWT) error { var keysFunc func() []key.PublicKey - if kID, ok := jwt.KeyID(); ok { - keysFunc = c.keysFuncWithID(kID) + if kid, ok := jwt.KeyID(); ok { + keysFunc = c.keysFuncWithID(kid) } else { keysFunc = c.keysFuncAll() } @@ -782,7 +788,9 @@ func (c *Client) VerifyJWT(jwt jose.JWT) error { v := NewJWTVerifier( c.providerConfig.Get().Issuer.String(), c.credentials.ID, - c.maybeSyncKeys, keysFunc) + c.maybeSyncKeys, + keysFunc, + c.skipClientID) return v.Verify(jwt) } diff --git a/vendor/github.com/gambol99/go-oidc/oidc/doc.go b/vendor/github.com/gambol99/go-oidc/oidc/doc.go new file mode 100644 index 00000000..5f99aaed --- /dev/null +++ b/vendor/github.com/gambol99/go-oidc/oidc/doc.go @@ -0,0 +1,2 @@ +// Package oidc is DEPRECATED. Use github.com/gambol99/go-oidc instead. +package oidc diff --git a/vendor/github.com/coreos/go-oidc/oidc/identity.go b/vendor/github.com/gambol99/go-oidc/oidc/identity.go similarity index 95% rename from vendor/github.com/coreos/go-oidc/oidc/identity.go rename to vendor/github.com/gambol99/go-oidc/oidc/identity.go index 9bfa8e34..34793277 100644 --- a/vendor/github.com/coreos/go-oidc/oidc/identity.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/identity.go @@ -4,7 +4,7 @@ import ( "errors" "time" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" ) type Identity struct { diff --git a/vendor/github.com/coreos/go-oidc/oidc/interface.go b/vendor/github.com/gambol99/go-oidc/oidc/interface.go similarity index 100% rename from vendor/github.com/coreos/go-oidc/oidc/interface.go rename to vendor/github.com/gambol99/go-oidc/oidc/interface.go diff --git a/vendor/github.com/coreos/go-oidc/oidc/key.go b/vendor/github.com/gambol99/go-oidc/oidc/key.go similarity index 93% rename from vendor/github.com/coreos/go-oidc/oidc/key.go rename to vendor/github.com/gambol99/go-oidc/oidc/key.go index 82a0f567..33e5d911 100755 --- a/vendor/github.com/coreos/go-oidc/oidc/key.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/key.go @@ -6,9 +6,9 @@ import ( "net/http" "time" - phttp "github.com/coreos/go-oidc/http" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/key" + phttp "github.com/gambol99/go-oidc/http" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/key" ) // DefaultPublicKeySetTTL is the default TTL set on the PublicKeySet if no diff --git a/vendor/github.com/coreos/go-oidc/oidc/provider.go b/vendor/github.com/gambol99/go-oidc/oidc/provider.go similarity index 98% rename from vendor/github.com/coreos/go-oidc/oidc/provider.go rename to vendor/github.com/gambol99/go-oidc/oidc/provider.go index 42197ff1..57d907d7 100644 --- a/vendor/github.com/coreos/go-oidc/oidc/provider.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/provider.go @@ -14,8 +14,8 @@ import ( "github.com/coreos/pkg/timeutil" "github.com/jonboulle/clockwork" - phttp "github.com/coreos/go-oidc/http" - "github.com/coreos/go-oidc/oauth2" + phttp "github.com/gambol99/go-oidc/http" + "github.com/gambol99/go-oidc/oauth2" ) const ( @@ -325,7 +325,7 @@ func contains(sli []string, ele string) bool { // // NOTE(ericchiang): For development purposes Valid does not mandate 'https' for // URLs fields where the OIDC spec requires it. This may change in future releases -// of this package. See: https://github.com/coreos/go-oidc/issues/34 +// of this package. See: https://github.com/gambol99/go-oidc/issues/34 func (p ProviderConfig) Valid() error { grantTypes := p.GrantTypesSupported if len(grantTypes) == 0 { @@ -353,9 +353,6 @@ func (p ProviderConfig) Valid() error { if !contains(p.IDTokenSigningAlgValues, "RS256") { return errors.New("id_token_signing_alg_values_supported must include 'RS256'") } - if contains(p.TokenEndpointAuthMethodsSupported, "none") { - return errors.New("token_endpoint_auth_signing_alg_values_supported cannot include 'none'") - } uris := []struct { val *url.URL diff --git a/vendor/github.com/coreos/go-oidc/oidc/transport.go b/vendor/github.com/gambol99/go-oidc/oidc/transport.go similarity index 95% rename from vendor/github.com/coreos/go-oidc/oidc/transport.go rename to vendor/github.com/gambol99/go-oidc/oidc/transport.go index 61c926d7..963bfbbe 100644 --- a/vendor/github.com/coreos/go-oidc/oidc/transport.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/transport.go @@ -5,8 +5,8 @@ import ( "net/http" "sync" - phttp "github.com/coreos/go-oidc/http" - "github.com/coreos/go-oidc/jose" + phttp "github.com/gambol99/go-oidc/http" + "github.com/gambol99/go-oidc/jose" ) type TokenRefresher interface { diff --git a/vendor/github.com/coreos/go-oidc/oidc/util.go b/vendor/github.com/gambol99/go-oidc/oidc/util.go similarity index 98% rename from vendor/github.com/coreos/go-oidc/oidc/util.go rename to vendor/github.com/gambol99/go-oidc/oidc/util.go index f2a5a195..a5a50846 100644 --- a/vendor/github.com/coreos/go-oidc/oidc/util.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/util.go @@ -11,7 +11,7 @@ import ( "strings" "time" - "github.com/coreos/go-oidc/jose" + "github.com/gambol99/go-oidc/jose" ) // RequestTokenExtractor funcs extract a raw encoded token from a request. diff --git a/vendor/github.com/coreos/go-oidc/oidc/verification.go b/vendor/github.com/gambol99/go-oidc/oidc/verification.go similarity index 75% rename from vendor/github.com/coreos/go-oidc/oidc/verification.go rename to vendor/github.com/gambol99/go-oidc/oidc/verification.go index d9c6afa6..33d62946 100644 --- a/vendor/github.com/coreos/go-oidc/oidc/verification.go +++ b/vendor/github.com/gambol99/go-oidc/oidc/verification.go @@ -7,8 +7,8 @@ import ( "github.com/jonboulle/clockwork" - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/key" + "github.com/gambol99/go-oidc/jose" + "github.com/gambol99/go-oidc/key" ) func VerifySignature(jwt jose.JWT, keys []key.PublicKey) (bool, error) { @@ -36,9 +36,9 @@ func containsString(needle string, haystack []string) bool { return false } -// Verify claims in accordance with OIDC spec +// VerifyClaims claims in accordance with OIDC spec // http://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation -func VerifyClaims(jwt jose.JWT, issuer, clientID string) error { +func VerifyClaims(jwt jose.JWT, issuer, clientID string, skipClientID bool) error { now := time.Now().UTC() claims, err := jwt.Claims() @@ -60,7 +60,7 @@ func VerifyClaims(jwt jose.JWT, issuer, clientID string) error { // host, and optionally, port number and path components and no query or fragment components. if iss, exists := claims["iss"].(string); exists { if !urlEqual(iss, issuer) { - return fmt.Errorf("invalid claim value: 'iss'. expected=%s, found=%s.", issuer, iss) + return fmt.Errorf("Invalid claim value: 'iss'. expected=%s, found=%s", issuer, iss) } } else { return errors.New("missing claim: 'iss'") @@ -78,16 +78,18 @@ func VerifyClaims(jwt jose.JWT, issuer, clientID string) error { // It MAY also contain identifiers for other audiences. In the general case, the aud // value is an array of case sensitive strings. In the common special case when there // is one audience, the aud value MAY be a single case sensitive string. - if aud, ok, err := claims.StringClaim("aud"); err == nil && ok { - if aud != clientID { - return fmt.Errorf("invalid claims, 'aud' claim and 'client_id' do not match, aud=%s, client_id=%s", aud, clientID) - } - } else if aud, ok, err := claims.StringsClaim("aud"); err == nil && ok { - if !containsString(clientID, aud) { - return fmt.Errorf("invalid claims, cannot find 'client_id' in 'aud' claim, aud=%v, client_id=%s", aud, clientID) + if !skipClientID { + if aud, ok, err := claims.StringClaim("aud"); err == nil && ok { + if aud != clientID { + return fmt.Errorf("invalid claims, 'aud' claim and 'client_id' do not match, aud=%s, client_id=%s", aud, clientID) + } + } else if aud, ok, err := claims.StringsClaim("aud"); err == nil && ok { + if !containsString(clientID, aud) { + return fmt.Errorf("invalid claims, cannot find 'client_id' in 'aud' claim, aud=%v, client_id=%s", aud, clientID) + } + } else { + return errors.New("invalid claim value: 'aud' is required, and should be either string or string array") } - } else { - return errors.New("invalid claim value: 'aud' is required, and should be either string or string array") } return nil @@ -142,29 +144,34 @@ func VerifyClientClaims(jwt jose.JWT, issuer string) (string, error) { return sub, nil } +// JWTVerifier is a verifications checker type JWTVerifier struct { - issuer string - clientID string - syncFunc func() error - keysFunc func() []key.PublicKey - clock clockwork.Clock + issuer string + clientID string + skipClientIDCheck bool + syncFunc func() error + keysFunc func() []key.PublicKey + clock clockwork.Clock } -func NewJWTVerifier(issuer, clientID string, syncFunc func() error, keysFunc func() []key.PublicKey) JWTVerifier { +// NewJWTVerifier returns a JWT verifier +func NewJWTVerifier(issuer, clientID string, syncFunc func() error, keysFunc func() []key.PublicKey, skipClientID bool) JWTVerifier { return JWTVerifier{ - issuer: issuer, - clientID: clientID, - syncFunc: syncFunc, - keysFunc: keysFunc, - clock: clockwork.NewRealClock(), + issuer: issuer, + clientID: clientID, + syncFunc: syncFunc, + keysFunc: keysFunc, + skipClientIDCheck: skipClientID, + clock: clockwork.NewRealClock(), } } +// Verify is responsible for verifying the token func (v *JWTVerifier) Verify(jwt jose.JWT) error { // Verify claims before verifying the signature. This is an optimization to throw out // tokens we know are invalid without undergoing an expensive signature check and // possibly a re-sync event. - if err := VerifyClaims(jwt, v.issuer, v.clientID); err != nil { + if err := VerifyClaims(jwt, v.issuer, v.clientID, v.skipClientIDCheck); err != nil { return fmt.Errorf("oidc: JWT claims invalid: %v", err) } diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go new file mode 100644 index 00000000..23838c4c --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -0,0 +1,379 @@ +/* +* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen +* THIS FILE MUST NOT BE EDITED BY HAND + */ + +package assert + +import ( + http "net/http" + url "net/url" + time "time" +) + +// Conditionf uses a Comparison to assert a complex condition. +func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { + return Condition(t, comp, append([]interface{}{msg}, args...)...) +} + +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { + return Contains(t, s, contains, append([]interface{}{msg}, args...)...) +} + +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Emptyf(t, obj, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + return Empty(t, object, append([]interface{}{msg}, args...)...) +} + +// Equalf asserts that two objects are equal. +// +// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { + return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) +} + +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { + return Error(t, err, append([]interface{}{msg}, args...)...) +} + +// Exactlyf asserts that two objects are equal is value and type. +// +// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// Failf reports a failure through +func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { + return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) +} + +// FailNowf fails test +func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { + return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) +} + +// Falsef asserts that the specified value is false. +// +// assert.Falsef(t, myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { + return False(t, value, append([]interface{}{msg}, args...)...) +} + +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { + return HTTPBodyContains(t, handler, method, url, values, str) +} + +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { + return HTTPBodyNotContains(t, handler, method, url, values, str) +} + +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPError(t, handler, method, url, values) +} + +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPRedirect(t, handler, method, url, values) +} + +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPSuccess(t, handler, method, url, values) +} + +// Implementsf asserts that an object is implemented by the specified interface. +// +// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) +} + +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) +} + +// IsTypef asserts that the specified objects are of the same type. +func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { + return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) +} + +// JSONEqf asserts that two JSON strings are equivalent. +// +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { + return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { + return Len(t, object, length, append([]interface{}{msg}, args...)...) +} + +// Nilf asserts that the specified object is nil. +// +// assert.Nilf(t, err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + return Nil(t, object, append([]interface{}{msg}, args...)...) +} + +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { + return NoError(t, err, append([]interface{}{msg}, args...)...) +} + +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { + return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) +} + +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + return NotEmpty(t, object, append([]interface{}{msg}, args...)...) +} + +// NotEqualf asserts that the specified values are NOT equal. +// +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) +} + +// NotNilf asserts that the specified object is not nil. +// +// assert.NotNilf(t, err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { + return NotNil(t, object, append([]interface{}{msg}, args...)...) +} + +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { + return NotPanics(t, f, append([]interface{}{msg}, args...)...) +} + +// NotRegexpf asserts that a specified regexp does not match a string. +// +// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { + return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { + return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) +} + +// NotZerof asserts that i is not the zero value for its type and returns the truth. +func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { + return NotZero(t, i, append([]interface{}{msg}, args...)...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { + return Panics(t, f, append([]interface{}{msg}, args...)...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { + return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) +} + +// Regexpf asserts that a specified regexp matches a string. +// +// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { + return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { + return Subset(t, list, subset, append([]interface{}{msg}, args...)...) +} + +// Truef asserts that the specified value is true. +// +// assert.Truef(t, myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { + return True(t, value, append([]interface{}{msg}, args...)...) +} + +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { + return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) +} + +// Zerof asserts that i is the zero value for its type and returns the truth. +func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { + return Zero(t, i, append([]interface{}{msg}, args...)...) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl new file mode 100644 index 00000000..c5cc66f4 --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl @@ -0,0 +1,4 @@ +{{.CommentFormat}} +func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { + return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go index aa4311ff..fcccbd01 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -16,18 +16,35 @@ func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool return Condition(a.t, comp, msgAndArgs...) } +// Conditionf uses a Comparison to assert a complex condition. +func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { + return Conditionf(a.t, comp, msg, args...) +} + // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { return Contains(a.t, s, contains, msgAndArgs...) } +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { + return Containsf(a.t, s, contains, msg, args...) +} + // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -38,14 +55,25 @@ func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { return Empty(a.t, object, msgAndArgs...) } +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Emptyf(obj, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { + return Emptyf(a.t, object, msg, args...) +} + // Equal asserts that two objects are equal. // -// a.Equal(123, 123, "123 and 123 should be equal") +// a.Equal(123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return Equal(a.t, expected, actual, msgAndArgs...) } @@ -54,28 +82,62 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs // and that it is equal to the provided error. // // actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString, "An error was expected") +// a.EqualError(err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { return EqualError(a.t, theError, errString, msgAndArgs...) } +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { + return EqualErrorf(a.t, theError, errString, msg, args...) +} + // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") +// a.EqualValues(uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return EqualValues(a.t, expected, actual, msgAndArgs...) } +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return EqualValuesf(a.t, expected, actual, msg, args...) +} + +// Equalf asserts that two objects are equal. +// +// a.Equalf(123, 123, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return Equalf(a.t, expected, actual, msg, args...) +} + // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() -// if a.Error(err, "An error was expected") { -// assert.Equal(t, err, expectedError) +// if a.Error(err) { +// assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). @@ -83,15 +145,36 @@ func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { return Error(a.t, err, msgAndArgs...) } +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { + return Errorf(a.t, err, msg, args...) +} + // Exactly asserts that two objects are equal is value and type. // -// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") +// a.Exactly(int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return Exactly(a.t, expected, actual, msgAndArgs...) } +// Exactlyf asserts that two objects are equal is value and type. +// +// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return Exactlyf(a.t, expected, actual, msg, args...) +} + // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { return Fail(a.t, failureMessage, msgAndArgs...) @@ -102,15 +185,34 @@ func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) b return FailNow(a.t, failureMessage, msgAndArgs...) } +// FailNowf fails test +func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { + return FailNowf(a.t, failureMessage, msg, args...) +} + +// Failf reports a failure through +func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { + return Failf(a.t, failureMessage, msg, args...) +} + // False asserts that the specified value is false. // -// a.False(myBool, "myBool should be false") +// a.False(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { return False(a.t, value, msgAndArgs...) } +// Falsef asserts that the specified value is false. +// +// a.Falsef(myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { + return Falsef(a.t, value, msg, args...) +} + // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // @@ -121,6 +223,16 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, u return HTTPBodyContains(a.t, handler, method, url, values, str) } +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { + return HTTPBodyContainsf(a.t, handler, method, url, values, str) +} + // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // @@ -131,6 +243,16 @@ func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string return HTTPBodyNotContains(a.t, handler, method, url, values, str) } +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { + return HTTPBodyNotContainsf(a.t, handler, method, url, values, str) +} + // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} @@ -140,6 +262,15 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri return HTTPError(a.t, handler, method, url, values) } +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPErrorf(a.t, handler, method, url, values) +} + // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} @@ -149,6 +280,15 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s return HTTPRedirect(a.t, handler, method, url, values) } +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPRedirectf(a.t, handler, method, url, values) +} + // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) @@ -158,13 +298,29 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url st return HTTPSuccess(a.t, handler, method, url, values) } +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values) bool { + return HTTPSuccessf(a.t, handler, method, url, values) +} + // Implements asserts that an object is implemented by the specified interface. // -// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") +// a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { return Implements(a.t, interfaceObject, object, msgAndArgs...) } +// Implementsf asserts that an object is implemented by the specified interface. +// +// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + return Implementsf(a.t, interfaceObject, object, msg, args...) +} + // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) @@ -179,6 +335,20 @@ func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delt return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { + return InDeltaf(a.t, expected, actual, delta, msg, args...) +} + // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). @@ -191,11 +361,28 @@ func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, ep return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { + return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) +} + // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { return IsType(a.t, expectedType, object, msgAndArgs...) } +// IsTypef asserts that the specified objects are of the same type. +func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { + return IsTypef(a.t, expectedType, object, msg, args...) +} + // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) @@ -205,30 +392,58 @@ func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interf return JSONEq(a.t, expected, actual, msgAndArgs...) } +// JSONEqf asserts that two JSON strings are equivalent. +// +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { + return JSONEqf(a.t, expected, actual, msg, args...) +} + // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// a.Len(mySlice, 3, "The size of slice is not 3") +// a.Len(mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { return Len(a.t, object, length, msgAndArgs...) } +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// a.Lenf(mySlice, 3, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { + return Lenf(a.t, object, length, msg, args...) +} + // Nil asserts that the specified object is nil. // -// a.Nil(err, "err should be nothing") +// a.Nil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { return Nil(a.t, object, msgAndArgs...) } +// Nilf asserts that the specified object is nil. +// +// a.Nilf(err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { + return Nilf(a.t, object, msg, args...) +} + // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { -// assert.Equal(t, actualObj, expectedObj) +// assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). @@ -236,18 +451,42 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { return NoError(a.t, err, msgAndArgs...) } +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { + return NoErrorf(a.t, err, msg, args...) +} + // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { return NotContains(a.t, s, contains, msgAndArgs...) } +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { + return NotContainsf(a.t, s, contains, msg, args...) +} + // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -260,9 +499,21 @@ func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) boo return NotEmpty(a.t, object, msgAndArgs...) } +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { + return NotEmptyf(a.t, object, msg, args...) +} + // NotEqual asserts that the specified values are NOT equal. // -// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") +// a.NotEqual(obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // @@ -272,26 +523,54 @@ func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndAr return NotEqual(a.t, expected, actual, msgAndArgs...) } +// NotEqualf asserts that the specified values are NOT equal. +// +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + return NotEqualf(a.t, expected, actual, msg, args...) +} + // NotNil asserts that the specified object is not nil. // -// a.NotNil(err, "err should be something") +// a.NotNil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { return NotNil(a.t, object, msgAndArgs...) } +// NotNilf asserts that the specified object is not nil. +// +// a.NotNilf(err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { + return NotNilf(a.t, object, msg, args...) +} + // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// a.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") +// a.NotPanics(func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return NotPanics(a.t, f, msgAndArgs...) } +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { + return NotPanicsf(a.t, f, msg, args...) +} + // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") @@ -302,22 +581,84 @@ func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...in return NotRegexp(a.t, rx, str, msgAndArgs...) } +// NotRegexpf asserts that a specified regexp does not match a string. +// +// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { + return NotRegexpf(a.t, rx, str, msg, args...) +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { + return NotSubset(a.t, list, subset, msgAndArgs...) +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { + return NotSubsetf(a.t, list, subset, msg, args...) +} + // NotZero asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { return NotZero(a.t, i, msgAndArgs...) } +// NotZerof asserts that i is not the zero value for its type and returns the truth. +func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool { + return NotZerof(a.t, i, msg, args...) +} + // Panics asserts that the code inside the specified PanicTestFunc panics. // -// a.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") +// a.Panics(func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return Panics(a.t, f, msgAndArgs...) } +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { + return PanicsWithValue(a.t, expected, f, msgAndArgs...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { + return PanicsWithValuef(a.t, expected, f, msg, args...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { + return Panicsf(a.t, f, msg, args...) +} + // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") @@ -328,25 +669,78 @@ func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...inter return Regexp(a.t, rx, str, msgAndArgs...) } +// Regexpf asserts that a specified regexp matches a string. +// +// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { + return Regexpf(a.t, rx, str, msg, args...) +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { + return Subset(a.t, list, subset, msgAndArgs...) +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { + return Subsetf(a.t, list, subset, msg, args...) +} + // True asserts that the specified value is true. // -// a.True(myBool, "myBool should be true") +// a.True(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { return True(a.t, value, msgAndArgs...) } +// Truef asserts that the specified value is true. +// +// a.Truef(myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { + return Truef(a.t, value, msg, args...) +} + // WithinDuration asserts that the two times are within duration delta of each other. // -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { + return WithinDurationf(a.t, expected, actual, delta, msg, args...) +} + // Zero asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { return Zero(a.t, i, msgAndArgs...) } + +// Zerof asserts that i is the zero value for its type and returns the truth. +func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool { + return Zerof(a.t, i, msg, args...) +} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go index d1552e5e..c8034f68 100644 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "math" "reflect" @@ -18,6 +19,8 @@ import ( "github.com/pmezard/go-difflib/difflib" ) +//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl + // TestingT is an interface wrapper around *testing.T type TestingT interface { Errorf(format string, args ...interface{}) @@ -38,7 +41,15 @@ func ObjectsAreEqual(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } - + if exp, ok := expected.([]byte); ok { + act, ok := actual.([]byte) + if !ok { + return false + } else if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) + } return reflect.DeepEqual(expected, actual) } @@ -108,10 +119,12 @@ func CallerInfo() []string { } parts := strings.Split(file, "/") - dir := parts[len(parts)-2] file = parts[len(parts)-1] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - callers = append(callers, fmt.Sprintf("%s:%d", file, line)) + if len(parts) > 1 { + dir := parts[len(parts)-2] + if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { + callers = append(callers, fmt.Sprintf("%s:%d", file, line)) + } } // Drop the package @@ -181,7 +194,7 @@ func indentMessageLines(message string, longestLabelLen int) string { // no need to align first line because it starts at the correct location (after the label) if i != 0 { // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab - outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen +1) + "\t") + outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") } outBuf.WriteString(scanner.Text()) } @@ -223,13 +236,13 @@ func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { content = append(content, labeledContent{"Messages", message}) } - t.Errorf("\r" + getWhitespaceString() + labeledOutput(content...)) + t.Errorf("%s", "\r"+getWhitespaceString()+labeledOutput(content...)) return false } type labeledContent struct { - label string + label string content string } @@ -258,7 +271,7 @@ func labeledOutput(content ...labeledContent) string { // Implements asserts that an object is implemented by the specified interface. // -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { interfaceType := reflect.TypeOf(interfaceObject).Elem() @@ -283,20 +296,25 @@ func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs // Equal asserts that two objects are equal. // -// assert.Equal(t, 123, 123, "123 and 123 should be equal") +// assert.Equal(t, 123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if err := validateEqualArgs(expected, actual); err != nil { + return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", + expected, actual, err), msgAndArgs...) + } if !ObjectsAreEqual(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ - "received: %s%s", expected, actual, diff), msgAndArgs...) + "actual: %s%s", expected, actual, diff), msgAndArgs...) } return true @@ -322,7 +340,7 @@ func formatUnequalValues(expected, actual interface{}) (e string, a string) { // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") +// assert.EqualValues(t, uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { @@ -332,7 +350,7 @@ func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interfa expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ - "received: %s%s", expected, actual, diff), msgAndArgs...) + "actual: %s%s", expected, actual, diff), msgAndArgs...) } return true @@ -341,7 +359,7 @@ func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interfa // Exactly asserts that two objects are equal is value and type. // -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") +// assert.Exactly(t, int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { @@ -359,7 +377,7 @@ func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{} // NotNil asserts that the specified object is not nil. // -// assert.NotNil(t, err, "err should be something") +// assert.NotNil(t, err) // // Returns whether the assertion was successful (true) or not (false). func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { @@ -386,7 +404,7 @@ func isNil(object interface{}) bool { // Nil asserts that the specified object is nil. // -// assert.Nil(t, err, "err should be nothing") +// assert.Nil(t, err) // // Returns whether the assertion was successful (true) or not (false). func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { @@ -509,7 +527,7 @@ func getLen(x interface{}) (ok bool, length int) { // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// assert.Len(t, mySlice, 3, "The size of slice is not 3") +// assert.Len(t, mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { @@ -526,7 +544,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) // True asserts that the specified value is true. // -// assert.True(t, myBool, "myBool should be true") +// assert.True(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { @@ -541,7 +559,7 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { // False asserts that the specified value is false. // -// assert.False(t, myBool, "myBool should be false") +// assert.False(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { @@ -556,13 +574,17 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { // NotEqual asserts that the specified values are NOT equal. // -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") +// assert.NotEqual(t, obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if err := validateEqualArgs(expected, actual); err != nil { + return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", + expected, actual, err), msgAndArgs...) + } if ObjectsAreEqual(expected, actual) { return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) @@ -613,9 +635,9 @@ func includeElement(list interface{}, element interface{}) (ok, found bool) { // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { @@ -635,9 +657,9 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { @@ -654,6 +676,92 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) } +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { + if subset == nil { + return true // we consider nil to be equal to the nil set + } + + subsetValue := reflect.ValueOf(subset) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + + listKind := reflect.TypeOf(list).Kind() + subsetKind := reflect.TypeOf(subset).Kind() + + if listKind != reflect.Array && listKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) + } + + if subsetKind != reflect.Array && subsetKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) + } + + for i := 0; i < subsetValue.Len(); i++ { + element := subsetValue.Index(i).Interface() + ok, found := includeElement(list, element) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) + } + if !found { + return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) + } + } + + return true +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { + if subset == nil { + return false // we consider nil to be equal to the nil set + } + + subsetValue := reflect.ValueOf(subset) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + + listKind := reflect.TypeOf(list).Kind() + subsetKind := reflect.TypeOf(subset).Kind() + + if listKind != reflect.Array && listKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) + } + + if subsetKind != reflect.Array && subsetKind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) + } + + for i := 0; i < subsetValue.Len(); i++ { + element := subsetValue.Index(i).Interface() + ok, found := includeElement(list, element) + if !ok { + return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) + } + if !found { + return true + } + } + + return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) +} + // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { result := comp() @@ -691,9 +799,7 @@ func didPanic(f PanicTestFunc) (bool, interface{}) { // Panics asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") +// assert.Panics(t, func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { @@ -705,11 +811,28 @@ func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { return true } +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +// +// Returns whether the assertion was successful (true) or not (false). +func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { + + funcDidPanic, panicValue := didPanic(f) + if !funcDidPanic { + return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) + } + if panicValue != expected { + return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%v\n\r\tPanic value:\t%v", f, expected, panicValue), msgAndArgs...) + } + + return true +} + // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") +// assert.NotPanics(t, func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { @@ -723,7 +846,7 @@ func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { // WithinDuration asserts that the two times are within duration delta of each other. // -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { @@ -812,7 +935,7 @@ func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAn expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { - result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) + result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) if !result { return result } @@ -882,7 +1005,7 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) +// assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). @@ -897,8 +1020,8 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). @@ -915,7 +1038,7 @@ func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { // and that it is equal to the provided error. // // actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString, "An error was expected") +// assert.EqualError(t, err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { @@ -928,7 +1051,7 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte if expected != actual { return Fail(t, fmt.Sprintf("Error message not equal:\n"+ "expected: %q\n"+ - "received: %q", expected, actual), msgAndArgs...) + "actual: %q", expected, actual), msgAndArgs...) } return true } @@ -1061,6 +1184,22 @@ func diff(expected interface{}, actual interface{}) string { return "\n\nDiff:\n" + diff } +// validateEqualArgs checks whether provided arguments can be safely used in the +// Equal/NotEqual functions. +func validateEqualArgs(expected, actual interface{}) error { + if isFunction(expected) || isFunction(actual) { + return errors.New("cannot take func type as argument") + } + return nil +} + +func isFunction(arg interface{}) bool { + if arg == nil { + return false + } + return reflect.TypeOf(arg).Kind() == reflect.Func +} + var spewConfig = spew.ConfigState{ Indent: " ", DisablePointerAddresses: true, diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go index b867e95e..9ad56851 100644 --- a/vendor/github.com/stretchr/testify/assert/forward_assertions.go +++ b/vendor/github.com/stretchr/testify/assert/forward_assertions.go @@ -13,4 +13,4 @@ func New(t TestingT) *Assertions { } } -//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl +//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go index fa7ab89b..ba811c04 100644 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -8,16 +8,16 @@ import ( "strings" ) -// httpCode is a helper that returns HTTP code of the response. It returns -1 -// if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { +// httpCode is a helper that returns HTTP code of the response. It returns -1 and +// an error if building a new request fails. +func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { w := httptest.NewRecorder() req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) if err != nil { - return -1 + return -1, err } handler(w, req) - return w.Code + return w.Code, nil } // HTTPSuccess asserts that a specified handler returns a success status code. @@ -26,11 +26,18 @@ func httpCode(handler http.HandlerFunc, method, url string, values url.Values) i // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } - return code >= http.StatusOK && code <= http.StatusPartialContent + + isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent + if !isSuccessCode { + Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) + } + + return isSuccessCode } // HTTPRedirect asserts that a specified handler returns a redirect status code. @@ -39,11 +46,18 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, value // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } - return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect + + isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect + if !isRedirectCode { + Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) + } + + return isRedirectCode } // HTTPError asserts that a specified handler returns an error status code. @@ -52,11 +66,18 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, valu // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } - return code >= http.StatusBadRequest + + isErrorCode := code >= http.StatusBadRequest + if !isErrorCode { + Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) + } + + return isErrorCode } // HTTPBody is a helper that returns HTTP body of the response. It returns diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go index d3c2ab9b..ac71d405 100644 --- a/vendor/github.com/stretchr/testify/require/forward_requirements.go +++ b/vendor/github.com/stretchr/testify/require/forward_requirements.go @@ -13,4 +13,4 @@ func New(t TestingT) *Assertions { } } -//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl +//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl -include-format-funcs diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go index fc567f14..2fe05578 100644 --- a/vendor/github.com/stretchr/testify/require/require.go +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -19,12 +19,19 @@ func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { } } +// Conditionf uses a Comparison to assert a complex condition. +func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { + if !assert.Conditionf(t, comp, msg, args...) { + t.FailNow() + } +} + // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { @@ -33,6 +40,20 @@ func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...int } } +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { + if !assert.Containsf(t, s, contains, msg, args...) { + t.FailNow() + } +} + // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -45,14 +66,27 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { } } +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Emptyf(t, obj, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.Emptyf(t, object, msg, args...) { + t.FailNow() + } +} + // Equal asserts that two objects are equal. // -// assert.Equal(t, 123, 123, "123 and 123 should be equal") +// assert.Equal(t, 123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() @@ -63,7 +97,7 @@ func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...i // and that it is equal to the provided error. // // actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString, "An error was expected") +// assert.EqualError(t, err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { @@ -72,10 +106,23 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte } } +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { + if !assert.EqualErrorf(t, theError, errString, msg, args...) { + t.FailNow() + } +} + // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") +// assert.EqualValues(t, uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { @@ -84,11 +131,38 @@ func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArg } } +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.EqualValuesf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + +// Equalf asserts that two objects are equal. +// +// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.Equalf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). @@ -98,9 +172,23 @@ func Error(t TestingT, err error, msgAndArgs ...interface{}) { } } +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func Errorf(t TestingT, err error, msg string, args ...interface{}) { + if !assert.Errorf(t, err, msg, args...) { + t.FailNow() + } +} + // Exactly asserts that two objects are equal is value and type. // -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") +// assert.Exactly(t, int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { @@ -109,6 +197,17 @@ func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs .. } } +// Exactlyf asserts that two objects are equal is value and type. +// +// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.Exactlyf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if !assert.Fail(t, failureMessage, msgAndArgs...) { @@ -123,9 +222,23 @@ func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { } } +// FailNowf fails test +func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { + if !assert.FailNowf(t, failureMessage, msg, args...) { + t.FailNow() + } +} + +// Failf reports a failure through +func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { + if !assert.Failf(t, failureMessage, msg, args...) { + t.FailNow() + } +} + // False asserts that the specified value is false. // -// assert.False(t, myBool, "myBool should be false") +// assert.False(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func False(t TestingT, value bool, msgAndArgs ...interface{}) { @@ -134,6 +247,17 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) { } } +// Falsef asserts that the specified value is false. +// +// assert.Falsef(t, myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Falsef(t TestingT, value bool, msg string, args ...interface{}) { + if !assert.Falsef(t, value, msg, args...) { + t.FailNow() + } +} + // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // @@ -146,6 +270,18 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url s } } +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + if !assert.HTTPBodyContainsf(t, handler, method, url, values, str) { + t.FailNow() + } +} + // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // @@ -158,6 +294,18 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, ur } } +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + if !assert.HTTPBodyNotContainsf(t, handler, method, url, values, str) { + t.FailNow() + } +} + // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} @@ -169,6 +317,17 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, } } +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { + if !assert.HTTPErrorf(t, handler, method, url, values) { + t.FailNow() + } +} + // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} @@ -180,6 +339,17 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url strin } } +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { + if !assert.HTTPRedirectf(t, handler, method, url, values) { + t.FailNow() + } +} + // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) @@ -191,15 +361,35 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string } } +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { + if !assert.HTTPSuccessf(t, handler, method, url, values) { + t.FailNow() + } +} + // Implements asserts that an object is implemented by the specified interface. // -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } +// Implementsf asserts that an object is implemented by the specified interface. +// +// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + if !assert.Implementsf(t, interfaceObject, object, msg, args...) { + t.FailNow() + } +} + // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) @@ -218,6 +408,24 @@ func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta fl } } +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if !assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + if !assert.InDeltaf(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). @@ -234,6 +442,22 @@ func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilo } } +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if !assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { + t.FailNow() + } +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + if !assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { + t.FailNow() + } +} + // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.IsType(t, expectedType, object, msgAndArgs...) { @@ -241,6 +465,13 @@ func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs } } +// IsTypef asserts that the specified objects are of the same type. +func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { + if !assert.IsTypef(t, expectedType, object, msg, args...) { + t.FailNow() + } +} + // JSONEq asserts that two JSON strings are equivalent. // // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) @@ -252,10 +483,21 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{ } } +// JSONEqf asserts that two JSON strings are equivalent. +// +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { + if !assert.JSONEqf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// assert.Len(t, mySlice, 3, "The size of slice is not 3") +// assert.Len(t, mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { @@ -264,9 +506,21 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) } } +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { + if !assert.Lenf(t, object, length, msg, args...) { + t.FailNow() + } +} + // Nil asserts that the specified object is nil. // -// assert.Nil(t, err, "err should be nothing") +// assert.Nil(t, err) // // Returns whether the assertion was successful (true) or not (false). func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { @@ -275,11 +529,22 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { } } +// Nilf asserts that the specified object is nil. +// +// assert.Nilf(t, err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.Nilf(t, object, msg, args...) { + t.FailNow() + } +} + // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) +// assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). @@ -289,12 +554,26 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) { } } +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { + if !assert.NoErrorf(t, err, msg, args...) { + t.FailNow() + } +} + // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { @@ -303,6 +582,20 @@ func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ... } } +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { + if !assert.NotContainsf(t, s, contains, msg, args...) { + t.FailNow() + } +} + // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -317,9 +610,23 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { } } +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.NotEmptyf(t, object, msg, args...) { + t.FailNow() + } +} + // NotEqual asserts that the specified values are NOT equal. // -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") +// assert.NotEqual(t, obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // @@ -331,9 +638,23 @@ func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs . } } +// NotEqualf asserts that the specified values are NOT equal. +// +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if !assert.NotEqualf(t, expected, actual, msg, args...) { + t.FailNow() + } +} + // NotNil asserts that the specified object is not nil. // -// assert.NotNil(t, err, "err should be something") +// assert.NotNil(t, err) // // Returns whether the assertion was successful (true) or not (false). func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { @@ -342,11 +663,20 @@ func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { } } +// NotNilf asserts that the specified object is not nil. +// +// assert.NotNilf(t, err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { + if !assert.NotNilf(t, object, msg, args...) { + t.FailNow() + } +} + // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") +// assert.NotPanics(t, func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { @@ -355,6 +685,17 @@ func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { } } +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { + if !assert.NotPanicsf(t, f, msg, args...) { + t.FailNow() + } +} + // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") @@ -367,6 +708,42 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf } } +// NotRegexpf asserts that a specified regexp does not match a string. +// +// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { + if !assert.NotRegexpf(t, rx, str, msg, args...) { + t.FailNow() + } +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if !assert.NotSubset(t, list, subset, msgAndArgs...) { + t.FailNow() + } +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { + if !assert.NotSubsetf(t, list, subset, msg, args...) { + t.FailNow() + } +} + // NotZero asserts that i is not the zero value for its type and returns the truth. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.NotZero(t, i, msgAndArgs...) { @@ -374,11 +751,16 @@ func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { } } +// NotZerof asserts that i is not the zero value for its type and returns the truth. +func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { + if !assert.NotZerof(t, i, msg, args...) { + t.FailNow() + } +} + // Panics asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") +// assert.Panics(t, func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { @@ -387,6 +769,41 @@ func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { } } +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +// +// Returns whether the assertion was successful (true) or not (false). +func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + if !assert.PanicsWithValue(t, expected, f, msgAndArgs...) { + t.FailNow() + } +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { + if !assert.PanicsWithValuef(t, expected, f, msg, args...) { + t.FailNow() + } +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { + if !assert.Panicsf(t, f, msg, args...) { + t.FailNow() + } +} + // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") @@ -399,9 +816,45 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface } } +// Regexpf asserts that a specified regexp matches a string. +// +// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { + if !assert.Regexpf(t, rx, str, msg, args...) { + t.FailNow() + } +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { + if !assert.Subset(t, list, subset, msgAndArgs...) { + t.FailNow() + } +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { + if !assert.Subsetf(t, list, subset, msg, args...) { + t.FailNow() + } +} + // True asserts that the specified value is true. // -// assert.True(t, myBool, "myBool should be true") +// assert.True(t, myBool) // // Returns whether the assertion was successful (true) or not (false). func True(t TestingT, value bool, msgAndArgs ...interface{}) { @@ -410,9 +863,20 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) { } } +// Truef asserts that the specified value is true. +// +// assert.Truef(t, myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func Truef(t TestingT, value bool, msg string, args ...interface{}) { + if !assert.Truef(t, value, msg, args...) { + t.FailNow() + } +} + // WithinDuration asserts that the two times are within duration delta of each other. // -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { @@ -421,9 +885,27 @@ func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time } } +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { + if !assert.WithinDurationf(t, expected, actual, delta, msg, args...) { + t.FailNow() + } +} + // Zero asserts that i is the zero value for its type and returns the truth. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.Zero(t, i, msgAndArgs...) { t.FailNow() } } + +// Zerof asserts that i is the zero value for its type and returns the truth. +func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { + if !assert.Zerof(t, i, msg, args...) { + t.FailNow() + } +} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go index caa18793..c59c3c7b 100644 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -17,18 +17,35 @@ func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{} Condition(a.t, comp, msgAndArgs...) } +// Conditionf uses a Comparison to assert a complex condition. +func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { + Conditionf(a.t, comp, msg, args...) +} + // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { Contains(a.t, s, contains, msgAndArgs...) } +// Containsf asserts that the specified string, list(array, slice...) or map contains the +// specified substring or element. +// +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { + Containsf(a.t, s, contains, msg, args...) +} + // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -39,14 +56,25 @@ func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { Empty(a.t, object, msgAndArgs...) } +// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// a.Emptyf(obj, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { + Emptyf(a.t, object, msg, args...) +} + // Equal asserts that two objects are equal. // -// a.Equal(123, 123, "123 and 123 should be equal") +// a.Equal(123, 123) // // Returns whether the assertion was successful (true) or not (false). // // Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { Equal(a.t, expected, actual, msgAndArgs...) } @@ -55,28 +83,62 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs // and that it is equal to the provided error. // // actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString, "An error was expected") +// a.EqualError(err, expectedErrorString) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { EqualError(a.t, theError, errString, msgAndArgs...) } +// EqualErrorf asserts that a function returned an error (i.e. not `nil`) +// and that it is equal to the provided error. +// +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { + EqualErrorf(a.t, theError, errString, msg, args...) +} + // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") +// a.EqualValues(uint32(123), int32(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { EqualValues(a.t, expected, actual, msgAndArgs...) } +// EqualValuesf asserts that two objects are equal or convertable to the same types +// and equal. +// +// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + EqualValuesf(a.t, expected, actual, msg, args...) +} + +// Equalf asserts that two objects are equal. +// +// a.Equalf(123, 123, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). Function equality +// cannot be determined and will always fail. +func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + Equalf(a.t, expected, actual, msg, args...) +} + // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() -// if a.Error(err, "An error was expected") { -// assert.Equal(t, err, expectedError) +// if a.Error(err) { +// assert.Equal(t, expectedError, err) // } // // Returns whether the assertion was successful (true) or not (false). @@ -84,15 +146,36 @@ func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { Error(a.t, err, msgAndArgs...) } +// Errorf asserts that a function returned an error (i.e. not `nil`). +// +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { + Errorf(a.t, err, msg, args...) +} + // Exactly asserts that two objects are equal is value and type. // -// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") +// a.Exactly(int32(123), int64(123)) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { Exactly(a.t, expected, actual, msgAndArgs...) } +// Exactlyf asserts that two objects are equal is value and type. +// +// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + Exactlyf(a.t, expected, actual, msg, args...) +} + // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { Fail(a.t, failureMessage, msgAndArgs...) @@ -103,15 +186,34 @@ func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { FailNow(a.t, failureMessage, msgAndArgs...) } +// FailNowf fails test +func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { + FailNowf(a.t, failureMessage, msg, args...) +} + +// Failf reports a failure through +func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { + Failf(a.t, failureMessage, msg, args...) +} + // False asserts that the specified value is false. // -// a.False(myBool, "myBool should be false") +// a.False(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { False(a.t, value, msgAndArgs...) } +// Falsef asserts that the specified value is false. +// +// a.Falsef(myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { + Falsef(a.t, value, msg, args...) +} + // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // @@ -122,6 +224,16 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, u HTTPBodyContains(a.t, handler, method, url, values, str) } +// HTTPBodyContainsf asserts that a specified handler returns a +// body that contains a string. +// +// a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + HTTPBodyContainsf(a.t, handler, method, url, values, str) +} + // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // @@ -132,6 +244,16 @@ func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string HTTPBodyNotContains(a.t, handler, method, url, values, str) } +// HTTPBodyNotContainsf asserts that a specified handler returns a +// body that does not contain a string. +// +// a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { + HTTPBodyNotContainsf(a.t, handler, method, url, values, str) +} + // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} @@ -141,6 +263,15 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri HTTPError(a.t, handler, method, url, values) } +// HTTPErrorf asserts that a specified handler returns an error status code. +// +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values) { + HTTPErrorf(a.t, handler, method, url, values) +} + // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} @@ -150,6 +281,15 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s HTTPRedirect(a.t, handler, method, url, values) } +// HTTPRedirectf asserts that a specified handler returns a redirect status code. +// +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// +// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values) { + HTTPRedirectf(a.t, handler, method, url, values) +} + // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) @@ -159,13 +299,29 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url st HTTPSuccess(a.t, handler, method, url, values) } +// HTTPSuccessf asserts that a specified handler returns a success status code. +// +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values) { + HTTPSuccessf(a.t, handler, method, url, values) +} + // Implements asserts that an object is implemented by the specified interface. // -// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") +// a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { Implements(a.t, interfaceObject, object, msgAndArgs...) } +// Implementsf asserts that an object is implemented by the specified interface. +// +// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { + Implementsf(a.t, interfaceObject, object, msg, args...) +} + // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) @@ -180,6 +336,20 @@ func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delt InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } +// InDeltaSlicef is the same as InDelta, except it compares two slices. +func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + InDeltaSlicef(a.t, expected, actual, delta, msg, args...) +} + +// InDeltaf asserts that the two numerals are within delta of each other. +// +// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { + InDeltaf(a.t, expected, actual, delta, msg, args...) +} + // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). @@ -192,11 +362,28 @@ func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, ep InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } +// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. +func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) +} + +// InEpsilonf asserts that expected and actual have a relative error less than epsilon +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { + InEpsilonf(a.t, expected, actual, epsilon, msg, args...) +} + // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { IsType(a.t, expectedType, object, msgAndArgs...) } +// IsTypef asserts that the specified objects are of the same type. +func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { + IsTypef(a.t, expectedType, object, msg, args...) +} + // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) @@ -206,30 +393,58 @@ func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interf JSONEq(a.t, expected, actual, msgAndArgs...) } +// JSONEqf asserts that two JSON strings are equivalent. +// +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { + JSONEqf(a.t, expected, actual, msg, args...) +} + // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// a.Len(mySlice, 3, "The size of slice is not 3") +// a.Len(mySlice, 3) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { Len(a.t, object, length, msgAndArgs...) } +// Lenf asserts that the specified object has specific length. +// Lenf also fails if the object has a type that len() not accept. +// +// a.Lenf(mySlice, 3, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { + Lenf(a.t, object, length, msg, args...) +} + // Nil asserts that the specified object is nil. // -// a.Nil(err, "err should be nothing") +// a.Nil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { Nil(a.t, object, msgAndArgs...) } +// Nilf asserts that the specified object is nil. +// +// a.Nilf(err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { + Nilf(a.t, object, msg, args...) +} + // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { -// assert.Equal(t, actualObj, expectedObj) +// assert.Equal(t, expectedObj, actualObj) // } // // Returns whether the assertion was successful (true) or not (false). @@ -237,18 +452,42 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { NoError(a.t, err, msgAndArgs...) } +// NoErrorf asserts that a function returned no error (i.e. `nil`). +// +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { + NoErrorf(a.t, err, msg, args...) +} + // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { NotContains(a.t, s, contains, msgAndArgs...) } +// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the +// specified substring or element. +// +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { + NotContainsf(a.t, s, contains, msg, args...) +} + // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // @@ -261,9 +500,21 @@ func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { NotEmpty(a.t, object, msgAndArgs...) } +// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { + NotEmptyf(a.t, object, msg, args...) +} + // NotEqual asserts that the specified values are NOT equal. // -// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") +// a.NotEqual(obj1, obj2) // // Returns whether the assertion was successful (true) or not (false). // @@ -273,26 +524,54 @@ func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndAr NotEqual(a.t, expected, actual, msgAndArgs...) } +// NotEqualf asserts that the specified values are NOT equal. +// +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +// +// Pointer variable equality is determined based on the equality of the +// referenced values (as opposed to the memory addresses). +func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + NotEqualf(a.t, expected, actual, msg, args...) +} + // NotNil asserts that the specified object is not nil. // -// a.NotNil(err, "err should be something") +// a.NotNil(err) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { NotNil(a.t, object, msgAndArgs...) } +// NotNilf asserts that the specified object is not nil. +// +// a.NotNilf(err, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { + NotNilf(a.t, object, msg, args...) +} + // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// a.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") +// a.NotPanics(func(){ RemainCalm() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { NotPanics(a.t, f, msgAndArgs...) } +// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. +// +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { + NotPanicsf(a.t, f, msg, args...) +} + // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") @@ -303,22 +582,84 @@ func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...in NotRegexp(a.t, rx, str, msgAndArgs...) } +// NotRegexpf asserts that a specified regexp does not match a string. +// +// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { + NotRegexpf(a.t, rx, str, msg, args...) +} + +// NotSubset asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { + NotSubset(a.t, list, subset, msgAndArgs...) +} + +// NotSubsetf asserts that the specified list(array, slice...) contains not all +// elements given in the specified subset(array, slice...). +// +// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { + NotSubsetf(a.t, list, subset, msg, args...) +} + // NotZero asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { NotZero(a.t, i, msgAndArgs...) } +// NotZerof asserts that i is not the zero value for its type and returns the truth. +func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { + NotZerof(a.t, i, msg, args...) +} + // Panics asserts that the code inside the specified PanicTestFunc panics. // -// a.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") +// a.Panics(func(){ GoCrazy() }) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { Panics(a.t, f, msgAndArgs...) } +// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { + PanicsWithValue(a.t, expected, f, msgAndArgs...) +} + +// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that +// the recovered panic value equals the expected panic value. +// +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { + PanicsWithValuef(a.t, expected, f, msg, args...) +} + +// Panicsf asserts that the code inside the specified PanicTestFunc panics. +// +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { + Panicsf(a.t, f, msg, args...) +} + // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") @@ -329,25 +670,78 @@ func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...inter Regexp(a.t, rx, str, msgAndArgs...) } +// Regexpf asserts that a specified regexp matches a string. +// +// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { + Regexpf(a.t, rx, str, msg, args...) +} + +// Subset asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { + Subset(a.t, list, subset, msgAndArgs...) +} + +// Subsetf asserts that the specified list(array, slice...) contains all +// elements given in the specified subset(array, slice...). +// +// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { + Subsetf(a.t, list, subset, msg, args...) +} + // True asserts that the specified value is true. // -// a.True(myBool, "myBool should be true") +// a.True(myBool) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { True(a.t, value, msgAndArgs...) } +// Truef asserts that the specified value is true. +// +// a.Truef(myBool, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { + Truef(a.t, value, msg, args...) +} + // WithinDuration asserts that the two times are within duration delta of each other. // -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } +// WithinDurationf asserts that the two times are within duration delta of each other. +// +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { + WithinDurationf(a.t, expected, actual, delta, msg, args...) +} + // Zero asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { Zero(a.t, i, msgAndArgs...) } + +// Zerof asserts that i is the zero value for its type and returns the truth. +func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { + Zerof(a.t, i, msg, args...) +} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go index 41147562..e404f016 100644 --- a/vendor/github.com/stretchr/testify/require/requirements.go +++ b/vendor/github.com/stretchr/testify/require/requirements.go @@ -6,4 +6,4 @@ type TestingT interface { FailNow() } -//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl +//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl -include-format-funcs From 0f4f114fa14d8fdd109444e800122a493d0fada3 Mon Sep 17 00:00:00 2001 From: Rohith Date: Sun, 11 Jun 2017 16:24:07 +0100 Subject: [PATCH 2/4] - changing the base image to alpine 3.6 --- Dockerfile | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6332748b..a2fbdf68 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,7 @@ -FROM alpine:3.5 +FROM alpine:3.6 MAINTAINER Rohith -RUN apk update && \ - apk add ca-certificates +RUN apk add ca-certificates --update ADD templates/ /opt/templates ADD bin/keycloak-proxy /opt/keycloak-proxy From 0a7ec0803195e192c3705858875c6ca1e53ad2e9 Mon Sep 17 00:00:00 2001 From: Rohith Date: Sun, 11 Jun 2017 16:24:51 +0100 Subject: [PATCH 3/4] - adding the skip-client-id check option, to skip verification of the audience claim in the token --- Makefile | 2 +- doc.go | 2 ++ middleware.go | 3 ++- middleware_test.go | 1 + server_test.go | 64 ++++++++++++++++++++++++++++++++++++++++++++++ utils.go | 15 ++++++----- 6 files changed, 78 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index aab38eef..5b3f5158 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ NAME=keycloak-proxy AUTHOR=gambol99 AUTHOR_EMAIL=gambol99@gmail.com REGISTRY=quay.io -GOVERSION ?= 1.8.1 +GOVERSION ?= 1.8.3 ROOT_DIR=${PWD} HARDWARE=$(shell uname -m) GIT_SHA=$(shell git --no-pager describe --always --dirty) diff --git a/doc.go b/doc.go index 2670cbb9..f6abfcc2 100644 --- a/doc.go +++ b/doc.go @@ -184,6 +184,8 @@ type Config struct { TLSClientCertificate string `json:"tls-client-certificate" yaml:"tls-client-certificate" usage:"path to the client certificate for outbound connections in reverse and forwarding proxy modes"` // SkipUpstreamTLSVerify skips the verification of any upstream tls SkipUpstreamTLSVerify bool `json:"skip-upstream-tls-verify" yaml:"skip-upstream-tls-verify" usage:"skip the verification of any upstream TLS"` + // SkipClientID indicates we don't need to check the client id of the token + SkipClientID bool `json:"skip-client-id" yaml:"skip-client-id" usage:"skip the check on the client token"` // CorsOrigins is a list of origins permitted CorsOrigins []string `json:"cors-origins" yaml:"cors-origins" usage:"origins to add to the CORE origins control (Access-Control-Allow-Origin)"` diff --git a/middleware.go b/middleware.go index 1a0ba03a..309ab6a6 100644 --- a/middleware.go +++ b/middleware.go @@ -101,7 +101,7 @@ func (r *oauthProxy) metricsMiddleware() echo.MiddlewareFunc { }, []string{"code", "method"}, ) - prometheus.MustRegisterOrGet(statusMetrics) + prometheus.MustRegister(statusMetrics) return func(next echo.HandlerFunc) echo.HandlerFunc { return func(cx echo.Context) error { @@ -303,6 +303,7 @@ func (r *oauthProxy) admissionMiddleware(resource *Resource) echo.MiddlewareFunc log.WithFields(log.Fields{ "access": "permitted", + "client": user.audience, "email": user.email, "expires": time.Until(user.expiresAt).String(), "resource": resource.URL, diff --git a/middleware_test.go b/middleware_test.go index 6f51fdee..553c87a8 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -78,6 +78,7 @@ func newFakeProxy(c *Config) *fakeProxy { auth := newFakeAuthServer() c.DiscoveryURL = auth.getLocation() c.RevocationEndpoint = auth.getRevocationURL() + c.Verbose = false proxy, err := newProxy(c) if err != nil { panic("failed to create fake proxy service, error: " + err.Error()) diff --git a/server_test.go b/server_test.go index 52fb3992..28e518d6 100644 --- a/server_test.go +++ b/server_test.go @@ -226,6 +226,70 @@ func TestTokenEncryption(t *testing.T) { newFakeProxy(c).RunTests(t, requests) } +func TestSkipClientIDDisabled(t *testing.T) { + c := newFakeKeycloakConfig() + p := newFakeProxy(c) + // create two token, one with a bad client id + bad := newTestToken(p.idp.getLocation()) + bad.merge(jose.Claims{"aud": "bad_client_id"}) + badSigned, _ := p.idp.signToken(bad.claims) + // and the good + good := newTestToken(p.idp.getLocation()) + goodSigned, _ := p.idp.signToken(good.claims) + requests := []fakeRequest{ + { + URI: "/auth_all/test", + RawToken: goodSigned.Encode(), + ExpectedProxy: true, + ExpectedCode: http.StatusOK, + }, + { + URI: "/auth_all/test", + RawToken: badSigned.Encode(), + ExpectedCode: http.StatusForbidden, + }, + } + p.RunTests(t, requests) +} + +func TestSkipClientIDEnabled(t *testing.T) { + c := newFakeKeycloakConfig() + c.SkipClientID = true + p := newFakeProxy(c) + // create two token, one with a bad client id + bad := newTestToken(p.idp.getLocation()) + bad.merge(jose.Claims{"aud": "bad_client_id"}) + badSigned, _ := p.idp.signToken(bad.claims) + // and the good + good := newTestToken(p.idp.getLocation()) + goodSigned, _ := p.idp.signToken(good.claims) + // bad issuer + badIssurer := newTestToken("http://someone_else") + badIssurer.merge(jose.Claims{"aud": "bad_client_id"}) + badIssuerSigned, _ := p.idp.signToken(badIssurer.claims) + + requests := []fakeRequest{ + { + URI: "/auth_all/test", + RawToken: goodSigned.Encode(), + ExpectedProxy: true, + ExpectedCode: http.StatusOK, + }, + { + URI: "/auth_all/test", + RawToken: badSigned.Encode(), + ExpectedProxy: true, + ExpectedCode: http.StatusOK, + }, + { + URI: "/auth_all/test", + RawToken: badIssuerSigned.Encode(), + ExpectedCode: http.StatusForbidden, + }, + } + p.RunTests(t, requests) +} + func newTestService() string { _, _, u := newTestProxyService(nil) return u diff --git a/utils.go b/utils.go index 77213cc9..6a9ae0b0 100644 --- a/utils.go +++ b/utils.go @@ -150,22 +150,22 @@ func newOpenIDClient(cfg *Config) (*oidc.Client, oidc.ProviderConfig, *http.Clie var err error var config oidc.ProviderConfig - // step: fix up the url if required, the underlining lib will add the .well-known/openid-configuration to the discovery url for us. + // fix up the url if required, the underlining lib will add the .well-known/openid-configuration to the discovery url for us. if strings.HasSuffix(cfg.DiscoveryURL, "/.well-known/openid-configuration") { cfg.DiscoveryURL = strings.TrimSuffix(cfg.DiscoveryURL, "/.well-known/openid-configuration") } - // step: create a idp http client hc := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: cfg.SkipOpenIDProviderTLSVerify, }, + IdleConnTimeout: time.Second * 10, }, Timeout: time.Second * 10, } - // step: attempt to retrieve the provider configuration + // attempt to retrieve the provider configuration completeCh := make(chan bool) go func() { for { @@ -178,7 +178,7 @@ func newOpenIDClient(cfg *Config) (*oidc.Client, oidc.ProviderConfig, *http.Clie } completeCh <- true }() - // step: wait for timeout or successful retrieval + // wait for timeout or successful retrieval select { case <-time.After(30 * time.Second): return nil, config, nil, errors.New("failed to retrieve the provider configuration from discovery url") @@ -192,9 +192,10 @@ func newOpenIDClient(cfg *Config) (*oidc.Client, oidc.ProviderConfig, *http.Clie ID: cfg.ClientID, Secret: cfg.ClientSecret, }, - RedirectURL: fmt.Sprintf("%s/oauth/callback", cfg.RedirectionURL), - Scope: append(cfg.Scopes, oidc.DefaultScope...), - HTTPClient: hc, + RedirectURL: fmt.Sprintf("%s/oauth/callback", cfg.RedirectionURL), + Scope: append(cfg.Scopes, oidc.DefaultScope...), + SkipClientIDCheck: cfg.SkipClientID, + HTTPClient: hc, }) if err != nil { return nil, config, hc, err From ae2570e80355c1de9b37e19bfc8f5670763e9ef6 Mon Sep 17 00:00:00 2001 From: Rohith Date: Sun, 11 Jun 2017 16:28:23 +0100 Subject: [PATCH 4/4] - updated the CHANGELOG to reflect the changes --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13ffe760..1c620dee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,7 +23,8 @@ FEATURES * added spelling code coverage to the ci build [#PR208](https://github.com/gambol99/keycloak-proxy/pull/208) * update the encryption to use aes gcm [#PR220](https://github.com/gambol99/keycloak-proxy/pull/220) * added the --enable-encrypted-token option to enable encrypting the access token:wq - +* added the --skip-client-id option to permit skipping the verification of the auduence against client in token [#PR236](https://github.com/gambol99/keycloak-proxy/pull/236) +* updated the base image to apline 3.6 in commit [0fdebaf821](https://github.com/gambol99/keycloak-proxy/pull/236/commits/0fdebaf8215e9480896f01ec7ab2ef7caa242da1) BREAKING CHANGES: * the proxy no longer uses prefixes for resources, if you wish to use wildcard urls you need @@ -33,6 +34,9 @@ BREAKING CHANGES: * changed option from log-requests -> enable-logging [#PR199](https://github.com/gambol99/keycloak-proxy/pull/199) * changed option from json-format -> enable-json-logging [#PR199](https://github.com/gambol99/keycloak-proxy/pull/199) +MISC: +* Switch to using a go-oidc [fork](https://github.com/gambol99/go-oidc/commit/2111f98a1397a35f1800f4c3c354a7abebbef75c) for now, until i get the various bit merged upstream + #### **2.0.7** FIXES: