.editorconfig 0000644 00000000564 15174273671 0007243 0 ustar 00 # EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
charset = utf-8
# Get rid of whitespace to avoid diffs with a bunch of EOL changes
trim_trailing_whitespace = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# PHP-Files
[*.php]
indent_style = space
indent_size = 4
.github/CONTRIBUTING.md 0000644 00000007107 15174273671 0010357 0 ustar 00 # How to become a contributor and submit your own code
## Contributor License Agreements
We'd love to accept your sample apps and patches! Before we can take them, we
have to jump a couple of legal hurdles.
Please fill out either the individual or corporate Contributor License Agreement
(CLA).
* If you are an individual writing original source code and you're sure you
own the intellectual property, then you'll need to sign an [individual CLA]
(http://code.google.com/legal/individual-cla-v1.0.html).
* If you work for a company that wants to allow you to contribute your work,
then you'll need to sign a [corporate CLA]
(http://code.google.com/legal/corporate-cla-v1.0.html).
Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.
## Issue reporting
* Check that the issue has not already been reported.
* Check that the issue has not already been fixed in the latest code
(a.k.a. `master`).
* Be clear, concise and precise in your description of the problem.
* Open an issue with a descriptive title and a summary in grammatically correct,
complete sentences.
* Include any relevant code to the issue summary.
## Pull requests
* Read [how to properly contribute to open source projects on Github][2].
* Fork the project.
* Use a topic/feature branch to easily amend a pull request later, if necessary.
* Write [good commit messages][3].
* Use the same coding conventions as the rest of the project.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it
in a future version unintentionally.
* Add an entry to the [Changelog](CHANGELOG.md) accordingly. See [changelog entry format](#changelog-entry-format).
* Please try not to mess with the Rakefile, version, or history. If you want to
have your own version, or is otherwise necessary, that is fine, but please
isolate to its own commit so I can cherry-pick around it.
* Make sure the test suite is passing and the code you wrote doesn't produce
phpunit or phplint offenses.
* [Squash related commits together][5].
* Open a [pull request][4] that relates to *only* one subject with a clear title
and description in grammatically correct, complete sentences.
### Changelog entry format
Here are a few examples:
```
* ADC Support for User Refresh Tokens (@tbetbetbe[])
* [#16](https://github.com/google/google-auth-library-php/issues/16): ADC Support for User Refresh Tokens ([@tbetbetbe][])
```
* Mark it up in [Markdown syntax][6].
* The entry line should start with `* ` (an asterisk and a space).
* If the change has a related GitHub issue (e.g. a bug fix for a reported issue), put a link to the issue as `[#16](https://github.com/google/google-auth-library-php/issues/16): `.
* Describe the brief of the change. The sentence should end with a punctuation.
* At the end of the entry, add an implicit link to your GitHub user page as `([@username][])`.
* If this is your first contribution to google-auth-library-php project, add a link definition for the implicit link to the bottom of the changelog as `[@username]: https://github.com/username`.
[1]: https://github.com/google/google-auth-php-library/issues
[2]: http://gun.io/blog/how-to-github-fork-branch-and-pull-request
[3]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
[4]: https://help.github.com/articles/using-pull-requests
[5]: http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html
[6]: http://daringfireball.net/projects/markdown/syntax
.github/ISSUE_TEMPLATE/bug_report.md 0000644 00000001711 15174273671 0012776 0 ustar 00 ---
name: Bug report
about: Create a report to help us improve
---
Thanks for stopping by to let us know something could be better!
**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response.
Please run down the following list and make sure you've tried the usual "quick fixes":
- Search the issues already opened: https://github.com/googleapis/google-auth-library-php/issues
- Search StackOverflow: http://stackoverflow.com/questions/tagged/google-cloud-platform+php
If you are still having issues, please be sure to include as much information as possible:
#### Environment details
- OS:
- PHP version:
- Package name and version:
#### Steps to reproduce
1. ...
#### Code example
```php
# example
```
Making sure to follow these steps will guarantee the quickest resolution possible.
Thanks!
.github/ISSUE_TEMPLATE/feature_request.md 0000644 00000001510 15174273671 0014026 0 ustar 00 ---
name: Feature request
about: Suggest an idea for this library
---
Thanks for stopping by to let us know something could be better!
**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response.
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
.github/ISSUE_TEMPLATE/support_request.md 0000644 00000000540 15174273671 0014111 0 ustar 00 ---
name: Support request
about: If you have a support contract with Google, please create an issue in the Google Cloud Support console.
---
**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response.
.gitignore 0000644 00000000060 15174273671 0006545 0 ustar 00 *~
vendor
composer.lock
# IntelliJ
.idea
*.iml
.php_cs 0000644 00000003343 15174273671 0006041 0 ustar 00 exclude('vendor')
->in(__DIR__);
// Return a Code Sniffing configuration using
// all sniffers needed for PSR-2
// and additionally:
// - Remove leading slashes in use clauses.
// - PHP single-line arrays should not have trailing comma.
// - Single-line whitespace before closing semicolon are prohibited.
// - Remove unused use statements in the PHP source code
// - Ensure Concatenation to have at least one whitespace around
// - Remove trailing whitespace at the end of blank lines.
return Symfony\CS\Config\Config::create()
->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
->fixers([
'remove_leading_slash_use',
'single_array_no_trailing_comma',
'spaces_before_semicolon',
'unused_use',
'concat_with_spaces',
'whitespacy_lines',
'ordered_use',
'single_quote',
'duplicate_semicolon',
'extra_empty_lines',
'phpdoc_no_package',
'phpdoc_scalar',
'no_empty_lines_after_phpdocs'
])
->finder($finder);
.travis.yml 0000644 00000002436 15174273671 0006677 0 ustar 00 language: php
matrix:
include:
- name: "PHP 5.4"
php: "5.4"
- name: "PHP 5.4 (Prefer Lowest Dependency Version)"
php: "5.4"
env: COMPOSER_ARGS="--prefer-lowest"
- name: "PHP 5.5"
php: "5.5"
- name: "PHP 5.5 (Prefer Lowest Dependency Version)"
php: "5.5"
env: COMPOSER_ARGS="--prefer-lowest"
- name: "PHP 5.6"
php: "5.6"
- name: "PHP 5.6 (Prefer Lowest Dependency Version)"
php: "5.6"
env: COMPOSER_ARGS="--prefer-lowest"
- name: "PHP 7.0"
php: "7.0"
- name: "PHP 7.0 (Prefer Lowest Dependency Version)"
php: "7.0"
env: COMPOSER_ARGS="--prefer-lowest"
- name: "PHP 7.1"
php: "7.1"
- name: "PHP 7.1 (Prefer Lowest Dependency Version)"
php: "7.1"
env: COMPOSER_ARGS="--prefer-lowest"
- name: "PHP 7.2"
php: "7.2"
- name: "PHP 7.2 (Prefer Lowest Dependency Version)"
php: "7.2"
env: COMPOSER_ARGS="--prefer-lowest"
- name: "PHP 7.3"
php: "7.3"
- name: "Check Style"
php: "7.3"
env: RUN_CS_FIXER=true
before_script:
- composer update $COMPOSER_ARGS
script:
- if [ "${RUN_CS_FIXER}" = "true" ]; then
vendor/bin/php-cs-fixer fix --dry-run --diff --config-file=.php_cs .;
else
vendor/bin/phpunit;
fi
CHANGELOG.md 0000644 00000004462 15174273671 0006400 0 ustar 00 ## 1.5.1 (04/16/2019)
* [fix] Moved `getClientName()` from `Google\Auth\FetchAuthTokenInterface`
to `Google\Auth\SignBlobInterface`, and removed `getClientName()` from
`InsecureCredentials` and `UserRefreshCredentials`. (#223)
## 1.5.0 (04/15/2019)
### Changes
* Add support for signing strings with a Credentials instance. (#221)
* [Docs] Describe the arrays returned by fetchAuthToken. (#216)
* [Testing] Fix failing tests (#217)
* Update GitHub issue templates (#214, #213)
## 1.4.0 (09/17/2018)
### Changes
* Add support for insecure credentials (#208)
## 1.3.3 (08/27/2018)
### Changes
* Add retry and increase timeout for GCE credentials (#195)
* [Docs] Fix spelling (#204)
* Update token url (#206)
## 1.3.2 (07/23/2018)
### Changes
* Only emits a warning for gcloud credentials (#202)
## 1.3.1 (07/19/2018)
### Changes
* Added a warning for 3 legged OAuth credentials (#199)
* [Code cleanup] Removed useless else after return (#193)
## 1.3.0 (06/04/2018)
### Changes
* Fixes usage of deprecated env var for GAE Flex (#189)
* fix - guzzlehttp/psr7 dependency version definition (#190)
* Added SystemV shared memory based CacheItemPool (#191)
## 1.2.1 (24/01/2018)
### Changes
* Fixes array merging bug in Guzzle5HttpHandler (#186)
* Fixes constructor argument bug in Subscriber & Middleware (#184)
## 1.2.0 (6/12/2017)
### Changes
* Adds async method to HTTP handlers (#176)
* Misc bug fixes and improvements (#177, #175, #178)
## 1.1.0 (10/10/2017)
### Changes
* Supports additional claims in JWT tokens (#171)
* Adds makeHttpClient for creating authorized Guzzle clients (#162)
* Misc bug fixes/improvements (#168, #161, #167, #170, #143)
## 1.0.1 (31/07/2017)
### Changes
* Adds support for Firebase 5.0 (#159)
## 1.0.0 (12/06/2017)
### Changes
* Adds hashing and shortening to enforce max key length ([@bshaffer])
* Fix for better PSR-6 compliance - verifies a hit before getting the cache item ([@bshaffer])
* README fixes ([@bshaffer])
* Change authorization header key to lowercase ([@stanley-cheung])
## 0.4.0 (23/04/2015)
### Changes
* Export callback function to update auth metadata ([@stanley-cheung][])
* Adds an implementation of User Refresh Token auth ([@stanley-cheung][])
[@bshaffer]: https://github.com/bshaffer
[@stanley-cheung]: https://github.com/stanley-cheung
CODE_OF_CONDUCT.md 0000644 00000003675 15174273671 0007373 0 ustar 00 # Contributor Code of Conduct
As contributors and maintainers of this project,
and in the interest of fostering an open and welcoming community,
we pledge to respect all people who contribute through reporting issues,
posting feature requests, updating documentation,
submitting pull requests or patches, and other activities.
We are committed to making participation in this project
a harassment-free experience for everyone,
regardless of level of experience, gender, gender identity and expression,
sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information,
such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct.
By adopting this Code of Conduct,
project maintainers commit themselves to fairly and consistently
applying these principles to every aspect of managing this project.
Project maintainers who do not follow or enforce the Code of Conduct
may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior
may be reported by opening an issue
or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0,
available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
COPYING 0000644 00000026116 15174273671 0005622 0 ustar 00
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 2015 Google Inc.
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.
LICENSE 0000644 00000024020 15174273671 0005564 0 ustar 00 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.
README.md 0000644 00000011724 15174273671 0006045 0 ustar 00 # Google Auth Library for PHP
- Homepage
- http://www.github.com/google/google-auth-library-php
- Authors
- Tim Emiola
- Stanley Cheung
- Brent Shaffer
- Copyright
- Copyright © 2015 Google, Inc.
- License
- Apache 2.0
## Description
This is Google's officially supported PHP client library for using OAuth 2.0
authorization and authentication with Google APIs.
### Installing via Composer
The recommended way to install the google auth library is through
[Composer](http://getcomposer.org).
```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
```
Next, run the Composer command to install the latest stable version:
```bash
composer.phar require google/auth
```
## Application Default Credentials
This library provides an implementation of
[application default credentials][application default credentials] for PHP.
The Application Default Credentials provide a simple way to get authorization
credentials for use in calling Google APIs.
They are best suited for cases when the call needs to have the same identity
and authorization level for the application independent of the user. This is
the recommended approach to authorize calls to Cloud APIs, particularly when
you're building an application that uses Google Compute Engine.
#### Download your Service Account Credentials JSON file
To use `Application Default Credentials`, You first need to download a set of
JSON credentials for your project. Go to **APIs & Auth** > **Credentials** in
the [Google Developers Console][developer console] and select
**Service account** from the **Add credentials** dropdown.
> This file is your *only copy* of these credentials. It should never be
> committed with your source code, and should be stored securely.
Once downloaded, store the path to this file in the
`GOOGLE_APPLICATION_CREDENTIALS` environment variable.
```php
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
```
> PHP's `putenv` function is just one way to set an environment variable.
> Consider using `.htaccess` or apache configuration files as well.
#### Enable the API you want to use
Before making your API call, you must be sure the API you're calling has been
enabled. Go to **APIs & Auth** > **APIs** in the
[Google Developers Console][developer console] and enable the APIs you'd like to
call. For the example below, you must enable the `Drive API`.
#### Call the APIs
As long as you update the environment variable below to point to *your* JSON
credentials file, the following code should output a list of your Drive files.
```php
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];
// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://www.googleapis.com',
'auth' => 'google_auth' // authorize all requests
]);
// make the request
$response = $client->get('drive/v2/files');
// show the result!
print_r((string) $response->getBody());
```
##### Guzzle 5 Compatibility
If you are using [Guzzle 5][Guzzle 5], replace the `create middleware` and
`create the HTTP Client` steps with the following:
```php
// create the HTTP client
$client = new Client([
'base_url' => 'https://www.googleapis.com',
'auth' => 'google_auth' // authorize all requests
]);
// create subscriber
$subscriber = ApplicationDefaultCredentials::getSubscriber($scopes);
$client->getEmitter()->attach($subscriber);
```
## License
This library is licensed under Apache 2.0. Full license text is
available in [COPYING][copying].
## Contributing
See [CONTRIBUTING][contributing].
## Support
Please
[report bugs at the project on Github](https://github.com/google/google-auth-library-php/issues). Don't
hesitate to
[ask questions](http://stackoverflow.com/questions/tagged/google-auth-library-php)
about the client or APIs on [StackOverflow](http://stackoverflow.com).
[google-apis-php-client]: https://github.com/google/google-api-php-client
[application default credentials]: https://developers.google.com/accounts/docs/application-default-credentials
[contributing]: https://github.com/google/google-auth-library-php/tree/master/.github/CONTRIBUTING.md
[copying]: https://github.com/google/google-auth-library-php/tree/master/COPYING
[Guzzle]: https://github.com/guzzle/guzzle
[Guzzle 5]: http://docs.guzzlephp.org/en/5.3
[developer console]: https://console.developers.google.com
autoload.php 0000644 00000002127 15174273671 0007104 0 ustar 00 3) {
// Maximum class file path depth in this project is 3.
$classPath = array_slice($classPath, 0, 3);
}
$filePath = dirname(__FILE__) . '/src/' . implode('/', $classPath) . '.php';
if (file_exists($filePath)) {
require_once $filePath;
}
}
spl_autoload_register('oauth2client_php_autoload');
composer.json 0000644 00000001554 15174273671 0007310 0 ustar 00 {
"name": "google/auth",
"type": "library",
"description": "Google Auth Library for PHP",
"keywords": ["google", "oauth2", "authentication"],
"homepage": "http://github.com/google/google-auth-library-php",
"license": "Apache-2.0",
"require": {
"php": ">=5.4",
"firebase/php-jwt": "~2.0|~3.0|~4.0|~5.0",
"guzzlehttp/guzzle": "~5.3.1|~6.0",
"guzzlehttp/psr7": "^1.2",
"psr/http-message": "^1.0",
"psr/cache": "^1.0"
},
"require-dev": {
"guzzlehttp/promises": "0.1.1|^1.3",
"friendsofphp/php-cs-fixer": "^1.11",
"phpunit/phpunit": "^4.8.36|^5.7",
"sebastian/comparator": ">=1.2.3",
"phpseclib/phpseclib": "^2"
},
"suggest": {
"phpseclib/phpseclib": "May be used in place of OpenSSL for signing strings. Please require version ^2."
},
"autoload": {
"psr-4": {
"Google\\Auth\\": "src"
}
}
}
phpunit.xml.dist 0000644 00000001026 15174273671 0007733 0 ustar 00
tests
src
src/
src/ApplicationDefaultCredentials.php 0000644 00000015216 15174273671 0014014 0 ustar 00 push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'google_auth' // authorize all requests
* ]);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*/
class ApplicationDefaultCredentials
{
/**
* Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface
* implementation to use in this environment.
*
* If supplied, $scope is used to in creating the credentials instance if
* this does not fallback to the compute engine defaults.
*
* @param string|array scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param callable $httpHandler callback which delivers psr7 request
* @param array $cacheConfig configuration for the cache when it's present
* @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface
*
* @return AuthTokenSubscriber
*
* @throws DomainException if no implementation can be obtained.
*/
public static function getSubscriber(
$scope = null,
callable $httpHandler = null,
array $cacheConfig = null,
CacheItemPoolInterface $cache = null
) {
$creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
return new AuthTokenSubscriber($creds, $httpHandler);
}
/**
* Obtains an AuthTokenMiddleware that uses the default FetchAuthTokenInterface
* implementation to use in this environment.
*
* If supplied, $scope is used to in creating the credentials instance if
* this does not fallback to the compute engine defaults.
*
* @param string|array scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param callable $httpHandler callback which delivers psr7 request
* @param array $cacheConfig configuration for the cache when it's present
* @param CacheItemPoolInterface $cache
*
* @return AuthTokenMiddleware
*
* @throws DomainException if no implementation can be obtained.
*/
public static function getMiddleware(
$scope = null,
callable $httpHandler = null,
array $cacheConfig = null,
CacheItemPoolInterface $cache = null
) {
$creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
return new AuthTokenMiddleware($creds, $httpHandler);
}
/**
* Obtains the default FetchAuthTokenInterface implementation to use
* in this environment.
*
* If supplied, $scope is used to in creating the credentials instance if
* this does not fallback to the Compute Engine defaults.
*
* @param string|array scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param callable $httpHandler callback which delivers psr7 request
* @param array $cacheConfig configuration for the cache when it's present
* @param CacheItemPoolInterface $cache
*
* @return CredentialsLoader
*
* @throws DomainException if no implementation can be obtained.
*/
public static function getCredentials(
$scope = null,
callable $httpHandler = null,
array $cacheConfig = null,
CacheItemPoolInterface $cache = null
) {
$creds = null;
$jsonKey = CredentialsLoader::fromEnv()
?: CredentialsLoader::fromWellKnownFile();
if (!$httpHandler) {
if (!($client = HttpClientCache::getHttpClient())) {
$client = new Client();
HttpClientCache::setHttpClient($client);
}
$httpHandler = HttpHandlerFactory::build($client);
}
if (!is_null($jsonKey)) {
$creds = CredentialsLoader::makeCredentials($scope, $jsonKey);
} elseif (AppIdentityCredentials::onAppEngine() && !GCECredentials::onAppEngineFlexible()) {
$creds = new AppIdentityCredentials($scope);
} elseif (GCECredentials::onGce($httpHandler)) {
$creds = new GCECredentials();
}
if (is_null($creds)) {
throw new \DomainException(self::notFound());
}
if (!is_null($cache)) {
$creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);
}
return $creds;
}
private static function notFound()
{
$msg = 'Could not load the default credentials. Browse to ';
$msg .= 'https://developers.google.com';
$msg .= '/accounts/docs/application-default-credentials';
$msg .= ' for more information';
return $msg;
}
}
src/Cache/InvalidArgumentException.php 0000644 00000001454 15174273671 0014040 0 ustar 00 key = $key;
}
/**
* {@inheritdoc}
*/
public function getKey()
{
return $this->key;
}
/**
* {@inheritdoc}
*/
public function get()
{
return $this->isHit() ? $this->value : null;
}
/**
* {@inheritdoc}
*/
public function isHit()
{
if (!$this->isHit) {
return false;
}
if ($this->expiration === null) {
return true;
}
return new \DateTime() < $this->expiration;
}
/**
* {@inheritdoc}
*/
public function set($value)
{
$this->isHit = true;
$this->value = $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function expiresAt($expiration)
{
if ($this->isValidExpiration($expiration)) {
$this->expiration = $expiration;
return $this;
}
$implementationMessage = interface_exists('DateTimeInterface')
? 'implement interface DateTimeInterface'
: 'be an instance of DateTime';
$error = sprintf(
'Argument 1 passed to %s::expiresAt() must %s, %s given',
get_class($this),
$implementationMessage,
gettype($expiration)
);
$this->handleError($error);
}
/**
* {@inheritdoc}
*/
public function expiresAfter($time)
{
if (is_int($time)) {
$this->expiration = new \DateTime("now + $time seconds");
} elseif ($time instanceof \DateInterval) {
$this->expiration = (new \DateTime())->add($time);
} elseif ($time === null) {
$this->expiration = $time;
} else {
$message = 'Argument 1 passed to %s::expiresAfter() must be an ' .
'instance of DateInterval or of the type integer, %s given';
$error = sprintf($message, get_class($this), gettype($time));
$this->handleError($error);
}
return $this;
}
/**
* Handles an error.
*
* @param string $error
* @throws \TypeError
*/
private function handleError($error)
{
if (class_exists('TypeError')) {
throw new \TypeError($error);
}
trigger_error($error, E_USER_ERROR);
}
/**
* Determines if an expiration is valid based on the rules defined by PSR6.
*
* @param mixed $expiration
* @return bool
*/
private function isValidExpiration($expiration)
{
if ($expiration === null) {
return true;
}
// We test for two types here due to the fact the DateTimeInterface
// was not introduced until PHP 5.5. Checking for the DateTime type as
// well allows us to support 5.4.
if ($expiration instanceof \DateTimeInterface) {
return true;
}
if ($expiration instanceof \DateTime) {
return true;
}
return false;
}
}
src/Cache/MemoryCacheItemPool.php 0000644 00000006147 15174273671 0012741 0 ustar 00 getItems([$key]));
}
/**
* {@inheritdoc}
*/
public function getItems(array $keys = [])
{
$items = [];
foreach ($keys as $key) {
$items[$key] = $this->hasItem($key) ? clone $this->items[$key] : new Item($key);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function hasItem($key)
{
$this->isValidKey($key);
return isset($this->items[$key]) && $this->items[$key]->isHit();
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->items = [];
$this->deferredItems = [];
return true;
}
/**
* {@inheritdoc}
*/
public function deleteItem($key)
{
return $this->deleteItems([$key]);
}
/**
* {@inheritdoc}
*/
public function deleteItems(array $keys)
{
array_walk($keys, [$this, 'isValidKey']);
foreach ($keys as $key) {
unset($this->items[$key]);
}
return true;
}
/**
* {@inheritdoc}
*/
public function save(CacheItemInterface $item)
{
$this->items[$item->getKey()] = $item;
return true;
}
/**
* {@inheritdoc}
*/
public function saveDeferred(CacheItemInterface $item)
{
$this->deferredItems[$item->getKey()] = $item;
return true;
}
/**
* {@inheritdoc}
*/
public function commit()
{
foreach ($this->deferredItems as $item) {
$this->save($item);
}
$this->deferredItems = [];
return true;
}
/**
* Determines if the provided key is valid.
*
* @param string $key
* @return bool
* @throws InvalidArgumentException
*/
private function isValidKey($key)
{
$invalidCharacters = '{}()/\\\\@:';
if (!is_string($key) || preg_match("#[$invalidCharacters]#", $key)) {
throw new InvalidArgumentException('The provided key is not valid: ' . var_export($key, true));
}
return true;
}
}
src/Cache/SysVCacheItemPool.php 0000644 00000013243 15174273671 0012370 0 ustar 00 sysvKey,
$this->options['memsize'],
$this->options['perm']
);
if ($shmid !== false) {
$ret = shm_put_var(
$shmid,
$this->options['variableKey'],
$this->items
);
shm_detach($shmid);
return $ret;
}
return false;
}
/**
* Load the items from the shared memory.
*
* @return bool true when success, false upon failure
*/
private function loadItems()
{
$shmid = shm_attach(
$this->sysvKey,
$this->options['memsize'],
$this->options['perm']
);
if ($shmid !== false) {
$data = @shm_get_var($shmid, $this->options['variableKey']);
if (!empty($data)) {
$this->items = $data;
} else {
$this->items = [];
}
shm_detach($shmid);
return true;
}
return false;
}
/**
* Create a SystemV shared memory based CacheItemPool.
*
* @param array $options [optional] {
* Configuration options.
*
* @type int $variableKey The variable key for getting the data from
* the shared memory. **Defaults to** 1.
* @type string $proj The project identifier for ftok. This needs to
* be a one character string. **Defaults to** 'A'.
* @type int $memsize The memory size in bytes for shm_attach.
* **Defaults to** 10000.
* @type int $perm The permission for shm_attach. **Defaults to** 0600.
*/
public function __construct($options = [])
{
if (! extension_loaded('sysvshm')) {
throw \RuntimeException(
'sysvshm extension is required to use this ItemPool');
}
$this->options = $options + [
'variableKey' => self::VAR_KEY,
'proj' => self::DEFAULT_PROJ,
'memsize' => self::DEFAULT_MEMSIZE,
'perm' => self::DEFAULT_PERM
];
$this->items = [];
$this->deferredItems = [];
$this->sysvKey = ftok(__FILE__, $this->options['proj']);
$this->loadItems();
}
/**
* {@inheritdoc}
*/
public function getItem($key)
{
$this->loadItems();
return current($this->getItems([$key]));
}
/**
* {@inheritdoc}
*/
public function getItems(array $keys = [])
{
$this->loadItems();
$items = [];
foreach ($keys as $key) {
$items[$key] = $this->hasItem($key) ?
clone $this->items[$key] :
new Item($key);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function hasItem($key)
{
$this->loadItems();
return isset($this->items[$key]) && $this->items[$key]->isHit();
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->items = [];
$this->deferredItems = [];
return $this->saveCurrentItems();
}
/**
* {@inheritdoc}
*/
public function deleteItem($key)
{
return $this->deleteItems([$key]);
}
/**
* {@inheritdoc}
*/
public function deleteItems(array $keys)
{
foreach ($keys as $key) {
unset($this->items[$key]);
}
return $this->saveCurrentItems();
}
/**
* {@inheritdoc}
*/
public function save(CacheItemInterface $item)
{
$this->items[$item->getKey()] = $item;
return $this->saveCurrentItems();
}
/**
* {@inheritdoc}
*/
public function saveDeferred(CacheItemInterface $item)
{
$this->deferredItems[$item->getKey()] = $item;
return true;
}
/**
* {@inheritdoc}
*/
public function commit()
{
foreach ($this->deferredItems as $item) {
if ($this->save($item) === false) {
return false;
}
}
$this->deferredItems = [];
return true;
}
}
src/CacheTrait.php 0000644 00000004166 15174273671 0010077 0 ustar 00 cache)) {
return;
}
$key = $this->getFullCacheKey($k);
if (is_null($key)) {
return;
}
$cacheItem = $this->cache->getItem($key);
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
}
/**
* Saves the value in the cache when that is available.
*/
private function setCachedValue($k, $v)
{
if (is_null($this->cache)) {
return;
}
$key = $this->getFullCacheKey($k);
if (is_null($key)) {
return;
}
$cacheItem = $this->cache->getItem($key);
$cacheItem->set($v);
$cacheItem->expiresAfter($this->cacheConfig['lifetime']);
return $this->cache->save($cacheItem);
}
private function getFullCacheKey($key)
{
if (is_null($key)) {
return;
}
$key = $this->cacheConfig['prefix'] . $key;
// ensure we do not have illegal characters
$key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $key);
// Hash keys if they exceed $maxKeyLength (defaults to 64)
if ($this->maxKeyLength && strlen($key) > $this->maxKeyLength) {
$key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
}
return $key;
}
}
src/Credentials/AppIdentityCredentials.php 0000644 00000014062 15174273671 0014731 0 ustar 00 push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/books/v1',
* 'auth' => 'google_auth'
* ]);
*
* $res = $client->get('volumes?q=Henry+David+Thoreau&country=US');
*/
class AppIdentityCredentials extends CredentialsLoader implements SignBlobInterface
{
/**
* Result of fetchAuthToken.
*
* @array
*/
protected $lastReceivedToken;
/**
* Array of OAuth2 scopes to be requested.
*/
private $scope;
/**
* @var string
*/
private $clientName;
public function __construct($scope = array())
{
$this->scope = $scope;
}
/**
* Determines if this an App Engine instance, by accessing the
* SERVER_SOFTWARE environment variable (prod) or the APPENGINE_RUNTIME
* environment variable (dev).
*
* @return true if this an App Engine Instance, false otherwise
*/
public static function onAppEngine()
{
$appEngineProduction = isset($_SERVER['SERVER_SOFTWARE']) &&
0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine');
if ($appEngineProduction) {
return true;
}
$appEngineDevAppServer = isset($_SERVER['APPENGINE_RUNTIME']) &&
$_SERVER['APPENGINE_RUNTIME'] == 'php';
if ($appEngineDevAppServer) {
return true;
}
return false;
}
/**
* Implements FetchAuthTokenInterface#fetchAuthToken.
*
* Fetches the auth tokens using the AppIdentityService if available.
* As the AppIdentityService uses protobufs to fetch the access token,
* the GuzzleHttp\ClientInterface instance passed in will not be used.
*
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array A set of auth related metadata, containing the following
* keys:
* - access_token (string)
* - expiration_time (string)
*/
public function fetchAuthToken(callable $httpHandler = null)
{
try {
$this->checkAppEngineContext();
} catch (\Exception $e) {
return [];
}
// AppIdentityService expects an array when multiple scopes are supplied
$scope = is_array($this->scope) ? $this->scope : explode(' ', $this->scope);
$token = AppIdentityService::getAccessToken($scope);
$this->lastReceivedToken = $token;
return $token;
}
/**
* Sign a string using AppIdentityService.
*
* @param string $stringToSign The string to sign.
* @param bool $forceOpenSsl [optional] Does not apply to this credentials
* type.
* @return string The signature, base64-encoded.
* @throws \Exception If AppEngine SDK or mock is not available.
*/
public function signBlob($stringToSign, $forceOpenSsl = false)
{
$this->checkAppEngineContext();
return base64_encode(AppIdentityService::signForApp($stringToSign)['signature']);
}
/**
* Get the client name from AppIdentityService.
*
* Subsequent calls to this method will return a cached value.
*
* @param callable $httpHandler Not used in this implementation.
* @return string
* @throws \Exception If AppEngine SDK or mock is not available.
*/
public function getClientName(callable $httpHandler = null)
{
$this->checkAppEngineContext();
if (!$this->clientName) {
$this->clientName = AppIdentityService::getServiceAccountName();
}
return $this->clientName;
}
/**
* @return array|null
*/
public function getLastReceivedToken()
{
if ($this->lastReceivedToken) {
return [
'access_token' => $this->lastReceivedToken['access_token'],
'expires_at' => $this->lastReceivedToken['expiration_time'],
];
}
return null;
}
/**
* Caching is handled by the underlying AppIdentityService, return empty string
* to prevent caching.
*
* @return string
*/
public function getCacheKey()
{
return '';
}
private function checkAppEngineContext()
{
if (!self::onAppEngine() || !class_exists('google\appengine\api\app_identity\AppIdentityService')) {
throw new \Exception(
'This class must be run in App Engine, or you must include the AppIdentityService '
. 'mock class defined in tests/mocks/AppIdentityService.php'
);
}
}
}
src/Credentials/GCECredentials.php 0000644 00000024664 15174273671 0013106 0 ustar 00 push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'google_auth'
* ]);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*/
class GCECredentials extends CredentialsLoader implements SignBlobInterface
{
const cacheKey = 'GOOGLE_AUTH_PHP_GCE';
/**
* The metadata IP address on appengine instances.
*
* The IP is used instead of the domain 'metadata' to avoid slow responses
* when not on Compute Engine.
*/
const METADATA_IP = '169.254.169.254';
/**
* The metadata path of the default token.
*/
const TOKEN_URI_PATH = 'v1/instance/service-accounts/default/token';
/**
* The metadata path of the client ID.
*/
const CLIENT_ID_URI_PATH = 'v1/instance/service-accounts/default/email';
/**
* The header whose presence indicates GCE presence.
*/
const FLAVOR_HEADER = 'Metadata-Flavor';
/**
* Note: the explicit `timeout` and `tries` below is a workaround. The underlying
* issue is that resolving an unknown host on some networks will take
* 20-30 seconds; making this timeout short fixes the issue, but
* could lead to false negatives in the event that we are on GCE, but
* the metadata resolution was particularly slow. The latter case is
* "unlikely" since the expected 4-nines time is about 0.5 seconds.
* This allows us to limit the total ping maximum timeout to 1.5 seconds
* for developer desktop scenarios.
*/
const MAX_COMPUTE_PING_TRIES = 3;
const COMPUTE_PING_CONNECTION_TIMEOUT_S = 0.5;
/**
* Flag used to ensure that the onGCE test is only done once;.
*
* @var bool
*/
private $hasCheckedOnGce = false;
/**
* Flag that stores the value of the onGCE check.
*
* @var bool
*/
private $isOnGce = false;
/**
* Result of fetchAuthToken.
*/
protected $lastReceivedToken;
/**
* @var string
*/
private $clientName;
/**
* @var Iam|null
*/
private $iam;
/**
* @param Iam $iam [optional] An IAM instance.
*/
public function __construct(Iam $iam = null)
{
$this->iam = $iam;
}
/**
* The full uri for accessing the default token.
*
* @return string
*/
public static function getTokenUri()
{
$base = 'http://' . self::METADATA_IP . '/computeMetadata/';
return $base . self::TOKEN_URI_PATH;
}
/**
* The full uri for accessing the default service account.
*
* @return string
*/
public static function getClientNameUri()
{
$base = 'http://' . self::METADATA_IP . '/computeMetadata/';
return $base . self::CLIENT_ID_URI_PATH;
}
/**
* Determines if this an App Engine Flexible instance, by accessing the
* GAE_INSTANCE environment variable.
*
* @return true if this an App Engine Flexible Instance, false otherwise
*/
public static function onAppEngineFlexible()
{
return substr(getenv('GAE_INSTANCE'), 0, 4) === 'aef-';
}
/**
* Determines if this a GCE instance, by accessing the expected metadata
* host.
* If $httpHandler is not specified a the default HttpHandler is used.
*
* @param callable $httpHandler callback which delivers psr7 request
*
* @return true if this a GCEInstance false otherwise
*/
public static function onGce(callable $httpHandler = null)
{
$httpHandler = $httpHandler
?: HttpHandlerFactory::build(HttpClientCache::getHttpClient());
$checkUri = 'http://' . self::METADATA_IP;
for ($i = 1; $i <= self::MAX_COMPUTE_PING_TRIES; $i++) {
try {
// Comment from: oauth2client/client.py
//
// Note: the explicit `timeout` below is a workaround. The underlying
// issue is that resolving an unknown host on some networks will take
// 20-30 seconds; making this timeout short fixes the issue, but
// could lead to false negatives in the event that we are on GCE, but
// the metadata resolution was particularly slow. The latter case is
// "unlikely".
$resp = $httpHandler(
new Request('GET', $checkUri),
['timeout' => self::COMPUTE_PING_CONNECTION_TIMEOUT_S]
);
return $resp->getHeaderLine(self::FLAVOR_HEADER) == 'Google';
} catch (ClientException $e) {
} catch (ServerException $e) {
} catch (RequestException $e) {
}
}
return false;
}
/**
* Implements FetchAuthTokenInterface#fetchAuthToken.
*
* Fetches the auth tokens from the GCE metadata host if it is available.
* If $httpHandler is not specified a the default HttpHandler is used.
*
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array A set of auth related metadata, containing the following
* keys:
* - access_token (string)
* - expires_in (int)
* - token_type (string)
*
* @throws \Exception
*/
public function fetchAuthToken(callable $httpHandler = null)
{
$httpHandler = $httpHandler
?: HttpHandlerFactory::build(HttpClientCache::getHttpClient());
if (!$this->hasCheckedOnGce) {
$this->isOnGce = self::onGce($httpHandler);
$this->hasCheckedOnGce = true;
}
if (!$this->isOnGce) {
return array(); // return an empty array with no access token
}
$json = $this->getFromMetadata($httpHandler, self::getTokenUri());
if (null === $json = json_decode($json, true)) {
throw new \Exception('Invalid JSON response');
}
// store this so we can retrieve it later
$this->lastReceivedToken = $json;
$this->lastReceivedToken['expires_at'] = time() + $json['expires_in'];
return $json;
}
/**
* @return string
*/
public function getCacheKey()
{
return self::cacheKey;
}
/**
* @return array|null
*/
public function getLastReceivedToken()
{
if ($this->lastReceivedToken) {
return [
'access_token' => $this->lastReceivedToken['access_token'],
'expires_at' => $this->lastReceivedToken['expires_at'],
];
}
return null;
}
/**
* Get the client name from GCE metadata.
*
* Subsequent calls will return a cached value.
*
* @param callable $httpHandler callback which delivers psr7 request
* @return string
*/
public function getClientName(callable $httpHandler = null)
{
if ($this->clientName) {
return $this->clientName;
}
$httpHandler = $httpHandler
?: HttpHandlerFactory::build(HttpClientCache::getHttpClient());
if (!$this->hasCheckedOnGce) {
$this->isOnGce = self::onGce($httpHandler);
$this->hasCheckedOnGce = true;
}
if (!$this->isOnGce) {
return '';
}
$this->clientName = $this->getFromMetadata($httpHandler, self::getClientNameUri());
return $this->clientName;
}
/**
* Sign a string using the default service account private key.
*
* This implementation uses IAM's signBlob API.
*
* @see https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlob SignBlob
*
* @param string $stringToSign The string to sign.
* @param bool $forceOpenSsl [optional] Does not apply to this credentials
* type.
* @return string
*/
public function signBlob($stringToSign, $forceOpenSsl = false)
{
$httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient());
// Providing a signer is useful for testing, but it's undocumented
// because it's not something a user would generally need to do.
$signer = $this->iam ?: new Iam($httpHandler);
$email = $this->getClientName($httpHandler);
$previousToken = $this->getLastReceivedToken();
$accessToken = $previousToken
? $previousToken['access_token']
: $this->fetchAuthToken($httpHandler)['access_token'];
return $signer->signBlob($email, $accessToken, $stringToSign);
}
/**
* Fetch the value of a GCE metadata server URI.
*
* @param callable $httpHandler An HTTP Handler to deliver PSR7 requests.
* @param string $uri The metadata URI.
* @return string
*/
private function getFromMetadata(callable $httpHandler, $uri)
{
$resp = $httpHandler(
new Request(
'GET',
$uri,
[GCECredentials::FLAVOR_HEADER => 'Google']
)
);
return (string) $resp->getBody();
}
}
src/Credentials/IAMCredentials.php 0000644 00000004641 15174273671 0013107 0 ustar 00 selector = $selector;
$this->token = $token;
}
/**
* export a callback function which updates runtime metadata.
*
* @return array updateMetadata function
*/
public function getUpdateMetadataFunc()
{
return array($this, 'updateMetadata');
}
/**
* Updates metadata with the appropriate header metadata.
*
* @param array $metadata metadata hashmap
* @param string $unusedAuthUri optional auth uri
* @param callable $httpHandler callback which delivers psr7 request
* Note: this param is unused here, only included here for
* consistency with other credentials class
*
* @return array updated metadata hashmap
*/
public function updateMetadata(
$metadata,
$unusedAuthUri = null,
callable $httpHandler = null
) {
$metadata_copy = $metadata;
$metadata_copy[self::SELECTOR_KEY] = $this->selector;
$metadata_copy[self::TOKEN_KEY] = $this->token;
return $metadata_copy;
}
}
src/Credentials/InsecureCredentials.php 0000644 00000003470 15174273671 0014255 0 ustar 00 ''
];
/**
* Fetches the auth token. In this case it returns an empty string.
*
* @param callable $httpHandler
* @return array A set of auth related metadata, containing the following
* keys:
* - access_token (string)
*/
public function fetchAuthToken(callable $httpHandler = null)
{
return $this->token;
}
/**
* Returns the cache key. In this case it returns a null value, disabling
* caching.
*
* @return string|null
*/
public function getCacheKey()
{
return null;
}
/**
* Fetches the last received token. In this case, it returns the same empty string
* auth token.
*
* @return array
*/
public function getLastReceivedToken()
{
return $this->token;
}
}
src/Credentials/ServiceAccountCredentials.php 0000644 00000014140 15174273671 0015411 0 ustar 00 push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'google_auth' // authorize all requests
* ]);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*/
class ServiceAccountCredentials extends CredentialsLoader implements SignBlobInterface
{
use ServiceAccountSignerTrait;
/**
* The OAuth2 instance used to conduct authorization.
*
* @var OAuth2
*/
protected $auth;
/**
* Create a new ServiceAccountCredentials.
*
* @param string|array $scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param string|array $jsonKey JSON credential file path or JSON credentials
* as an associative array
* @param string $sub an email address account to impersonate, in situations when
* the service account has been delegated domain wide access.
*/
public function __construct(
$scope,
$jsonKey,
$sub = null
) {
if (is_string($jsonKey)) {
if (!file_exists($jsonKey)) {
throw new \InvalidArgumentException('file does not exist');
}
$jsonKeyStream = file_get_contents($jsonKey);
if (!$jsonKey = json_decode($jsonKeyStream, true)) {
throw new \LogicException('invalid json for auth config');
}
}
if (!array_key_exists('client_email', $jsonKey)) {
throw new \InvalidArgumentException(
'json key is missing the client_email field');
}
if (!array_key_exists('private_key', $jsonKey)) {
throw new \InvalidArgumentException(
'json key is missing the private_key field');
}
$this->auth = new OAuth2([
'audience' => self::TOKEN_CREDENTIAL_URI,
'issuer' => $jsonKey['client_email'],
'scope' => $scope,
'signingAlgorithm' => 'RS256',
'signingKey' => $jsonKey['private_key'],
'sub' => $sub,
'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI,
]);
}
/**
* @param callable $httpHandler
*
* @return array A set of auth related metadata, containing the following
* keys:
* - access_token (string)
* - expires_in (int)
* - token_type (string)
*/
public function fetchAuthToken(callable $httpHandler = null)
{
return $this->auth->fetchAuthToken($httpHandler);
}
/**
* @return string
*/
public function getCacheKey()
{
$key = $this->auth->getIssuer() . ':' . $this->auth->getCacheKey();
if ($sub = $this->auth->getSub()) {
$key .= ':' . $sub;
}
return $key;
}
/**
* @return array
*/
public function getLastReceivedToken()
{
return $this->auth->getLastReceivedToken();
}
/**
* Updates metadata with the authorization token.
*
* @param array $metadata metadata hashmap
* @param string $authUri optional auth uri
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array updated metadata hashmap
*/
public function updateMetadata(
$metadata,
$authUri = null,
callable $httpHandler = null
) {
// scope exists. use oauth implementation
$scope = $this->auth->getScope();
if (!is_null($scope)) {
return parent::updateMetadata($metadata, $authUri, $httpHandler);
}
// no scope found. create jwt with the auth uri
$credJson = array(
'private_key' => $this->auth->getSigningKey(),
'client_email' => $this->auth->getIssuer(),
);
$jwtCreds = new ServiceAccountJwtAccessCredentials($credJson);
return $jwtCreds->updateMetadata($metadata, $authUri, $httpHandler);
}
/**
* @param string $sub an email address account to impersonate, in situations when
* the service account has been delegated domain wide access.
*/
public function setSub($sub)
{
$this->auth->setSub($sub);
}
/**
* Get the client name from the keyfile.
*
* In this case, it returns the keyfile's client_email key.
*
* @param callable $httpHandler Not used by this credentials type.
* @return string
*/
public function getClientName(callable $httpHandler = null)
{
return $this->auth->getIssuer();
}
}
src/Credentials/ServiceAccountJwtAccessCredentials.php 0000644 00000010533 15174273671 0017222 0 ustar 00 auth = new OAuth2([
'issuer' => $jsonKey['client_email'],
'sub' => $jsonKey['client_email'],
'signingAlgorithm' => 'RS256',
'signingKey' => $jsonKey['private_key'],
]);
}
/**
* Updates metadata with the authorization token.
*
* @param array $metadata metadata hashmap
* @param string $authUri optional auth uri
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array updated metadata hashmap
*/
public function updateMetadata(
$metadata,
$authUri = null,
callable $httpHandler = null
) {
if (empty($authUri)) {
return $metadata;
}
$this->auth->setAudience($authUri);
return parent::updateMetadata($metadata, $authUri, $httpHandler);
}
/**
* Implements FetchAuthTokenInterface#fetchAuthToken.
*
* @param callable $httpHandler
*
* @return array|void A set of auth related metadata, containing the
* following keys:
* - access_token (string)
*/
public function fetchAuthToken(callable $httpHandler = null)
{
$audience = $this->auth->getAudience();
if (empty($audience)) {
return null;
}
$access_token = $this->auth->toJwt();
return array('access_token' => $access_token);
}
/**
* @return string
*/
public function getCacheKey()
{
return $this->auth->getCacheKey();
}
/**
* @return array
*/
public function getLastReceivedToken()
{
return $this->auth->getLastReceivedToken();
}
/**
* Get the client name from the keyfile.
*
* In this case, it returns the keyfile's client_email key.
*
* @param callable $httpHandler Not used by this credentials type.
* @return string
*/
public function getClientName(callable $httpHandler = null)
{
return $this->auth->getIssuer();
}
}
src/Credentials/UserRefreshCredentials.php 0000644 00000011217 15174273671 0014733 0 ustar 00 auth = new OAuth2([
'clientId' => $jsonKey['client_id'],
'clientSecret' => $jsonKey['client_secret'],
'refresh_token' => $jsonKey['refresh_token'],
'scope' => $scope,
'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI,
]);
if ($jsonKey['client_id'] === self::CLOUD_SDK_CLIENT_ID
&& getenv(self::SUPPRESS_CLOUD_SDK_CREDS_WARNING_ENV) !== 'true') {
trigger_error(
'Your application has authenticated using end user credentials '
. 'from Google Cloud SDK. We recommend that most server '
. 'applications use service accounts instead. If your '
. 'application continues to use end user credentials '
. 'from Cloud SDK, you might receive a "quota exceeded" '
. 'or "API not enabled" error. For more information about '
. 'service accounts, see '
. 'https://cloud.google.com/docs/authentication/. '
. 'To disable this warning, set '
. self::SUPPRESS_CLOUD_SDK_CREDS_WARNING_ENV
. ' environment variable to "true".',
E_USER_WARNING);
}
}
/**
* @param callable $httpHandler
*
* @return array A set of auth related metadata, containing the following
* keys:
* - access_token (string)
* - expires_in (int)
* - scope (string)
* - token_type (string)
* - id_token (string)
*/
public function fetchAuthToken(callable $httpHandler = null)
{
return $this->auth->fetchAuthToken($httpHandler);
}
/**
* @return string
*/
public function getCacheKey()
{
return $this->auth->getClientId() . ':' . $this->auth->getCacheKey();
}
/**
* @return array
*/
public function getLastReceivedToken()
{
return $this->auth->getLastReceivedToken();
}
}
src/CredentialsLoader.php 0000644 00000016102 15174273671 0011445 0 ustar 00 setDefaultOption('auth', 'google_auth');
$subscriber = new Subscriber\AuthTokenSubscriber(
$fetcher,
$httpHandler,
$tokenCallback
);
$client->getEmitter()->attach($subscriber);
return $client;
case '6':
$middleware = new Middleware\AuthTokenMiddleware(
$fetcher,
$httpHandler,
$tokenCallback
);
$stack = \GuzzleHttp\HandlerStack::create();
$stack->push($middleware);
return new \GuzzleHttp\Client([
'handler' => $stack,
'auth' => 'google_auth',
] + $httpClientOptions);
default:
throw new \Exception('Version not supported');
}
}
/**
* Create a new instance of InsecureCredentials.
*
* @return InsecureCredentials
*/
public static function makeInsecureCredentials()
{
return new InsecureCredentials();
}
/**
* export a callback function which updates runtime metadata.
*
* @return array updateMetadata function
*/
public function getUpdateMetadataFunc()
{
return array($this, 'updateMetadata');
}
/**
* Updates metadata with the authorization token.
*
* @param array $metadata metadata hashmap
* @param string $authUri optional auth uri
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array updated metadata hashmap
*/
public function updateMetadata(
$metadata,
$authUri = null,
callable $httpHandler = null
) {
$result = $this->fetchAuthToken($httpHandler);
if (!isset($result['access_token'])) {
return $metadata;
}
$metadata_copy = $metadata;
$metadata_copy[self::AUTH_METADATA_KEY] = array('Bearer ' . $result['access_token']);
return $metadata_copy;
}
}
src/FetchAuthTokenCache.php 0000644 00000007666 15174273671 0011700 0 ustar 00 fetcher = $fetcher;
$this->cache = $cache;
$this->cacheConfig = array_merge([
'lifetime' => 1500,
'prefix' => '',
], (array) $cacheConfig);
}
/**
* Implements FetchAuthTokenInterface#fetchAuthToken.
*
* Checks the cache for a valid auth token and fetches the auth tokens
* from the supplied fetcher.
*
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array the response
*
* @throws \Exception
*/
public function fetchAuthToken(callable $httpHandler = null)
{
// Use the cached value if its available.
//
// TODO: correct caching; update the call to setCachedValue to set the expiry
// to the value returned with the auth token.
//
// TODO: correct caching; enable the cache to be cleared.
$cacheKey = $this->fetcher->getCacheKey();
$cached = $this->getCachedValue($cacheKey);
if (!empty($cached)) {
return ['access_token' => $cached];
}
$auth_token = $this->fetcher->fetchAuthToken($httpHandler);
if (isset($auth_token['access_token'])) {
$this->setCachedValue($cacheKey, $auth_token['access_token']);
}
return $auth_token;
}
/**
* @return string
*/
public function getCacheKey()
{
return $this->getFullCacheKey($this->fetcher->getCacheKey());
}
/**
* @return array|null
*/
public function getLastReceivedToken()
{
return $this->fetcher->getLastReceivedToken();
}
/**
* Get the client name from the fetcher.
*
* @param callable $httpHandler An HTTP handler to deliver PSR7 requests.
* @return string
*/
public function getClientName(callable $httpHandler = null)
{
return $this->fetcher->getClientName($httpHandler);
}
/**
* Sign a blob using the fetcher.
*
* @param string $stringToSign The string to sign.
* @param bool $forceOpenssl Require use of OpenSSL for local signing. Does
* not apply to signing done using external services. **Defaults to**
* `false`.
* @return string The resulting signature.
* @throws \RuntimeException If the fetcher does not implement
* `Google\Auth\SignBlobInterface`.
*/
public function signBlob($stringToSign, $forceOpenSsl = false)
{
if (!$this->fetcher instanceof SignBlobInterface) {
throw new \RuntimeException(
'Credentials fetcher does not implement ' .
'Google\Auth\SignBlobInterface'
);
}
return $this->fetcher->signBlob($stringToSign, $forceOpenSsl);
}
}
src/FetchAuthTokenInterface.php 0000644 00000003163 15174273671 0012561 0 ustar 00 client = $client;
}
/**
* Accepts a PSR-7 Request and an array of options and returns a PSR-7 response.
*
* @param RequestInterface $request
* @param array $options
*
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, array $options = [])
{
$response = $this->client->send(
$this->createGuzzle5Request($request, $options)
);
return $this->createPsr7Response($response);
}
/**
* Accepts a PSR-7 request and an array of options and returns a PromiseInterface
*
* @param RequestInterface $request
* @param array $options
*
* @return Promise
*/
public function async(RequestInterface $request, array $options = [])
{
if (!class_exists('GuzzleHttp\Promise\Promise')) {
throw new Exception('Install guzzlehttp/promises to use async with Guzzle 5');
}
$futureResponse = $this->client->send(
$this->createGuzzle5Request(
$request,
['future' => true] + $options
)
);
$promise = new Promise(
function () use ($futureResponse) {
try {
$futureResponse->wait();
} catch (Exception $e) {
// The promise is already delivered when the exception is
// thrown, so don't rethrow it.
}
},
[$futureResponse, 'cancel']
);
$futureResponse->then([$promise, 'resolve'], [$promise, 'reject']);
return $promise->then(
function (Guzzle5ResponseInterface $response) {
// Adapt the Guzzle 5 Response to a PSR-7 Response.
return $this->createPsr7Response($response);
},
function (Exception $e) {
return new RejectedPromise($e);
}
);
}
private function createGuzzle5Request(RequestInterface $request, array $options)
{
return $this->client->createRequest(
$request->getMethod(),
$request->getUri(),
array_merge_recursive([
'headers' => $request->getHeaders(),
'body' => $request->getBody(),
], $options)
);
}
private function createPsr7Response(Guzzle5ResponseInterface $response)
{
return new Response(
$response->getStatusCode(),
$response->getHeaders() ?: [],
$response->getBody(),
$response->getProtocolVersion(),
$response->getReasonPhrase()
);
}
}
src/HttpHandler/Guzzle6HttpHandler.php 0000644 00000002171 15174273671 0014003 0 ustar 00 client = $client;
}
/**
* Accepts a PSR-7 request and an array of options and returns a PSR-7 response.
*
* @param RequestInterface $request
* @param array $options
*
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, array $options = [])
{
return $this->client->send($request, $options);
}
/**
* Accepts a PSR-7 request and an array of options and returns a PromiseInterface
*
* @param RequestInterface $request
* @param array $options
*
* @return \GuzzleHttp\Promise\Promise
*/
public function async(RequestInterface $request, array $options = [])
{
return $this->client->sendAsync($request, $options);
}
}
src/HttpHandler/HttpClientCache.php 0000644 00000002517 15174273671 0013305 0 ustar 00 httpHandler = $httpHandler
?: HttpHandlerFactory::build(HttpClientCache::getHttpClient());
}
/**
* Sign a string using the IAM signBlob API.
*
* Note that signing using IAM requires your service account to have the
* `iam.serviceAccounts.signBlob` permission, part of the "Service Account
* Token Creator" IAM role.
*
* @param string $email The service account email.
* @param string $accessToken An access token from the service account.
* @param string $stringToSign The string to be signed.
* @param array $delegates [optional] A list of service account emails to
* add to the delegate chain. If omitted, the value of `$email` will
* be used.
* @return string The signed string, base64-encoded.
*/
public function signBlob($email, $accessToken, $stringToSign, array $delegates = [])
{
$httpHandler = $this->httpHandler;
$name = sprintf(self::SERVICE_ACCOUNT_NAME, $email);
$uri = self::IAM_API_ROOT . '/' . sprintf(self::SIGN_BLOB_PATH, $name);
if ($delegates) {
foreach ($delegates as &$delegate) {
$delegate = sprintf(self::SERVICE_ACCOUNT_NAME, $delegate);
}
} else {
$delegates = [$name];
}
$body = [
'delegates' => $delegates,
'payload' => base64_encode($stringToSign),
];
$headers = [
'Authorization' => 'Bearer ' . $accessToken
];
$request = new Psr7\Request(
'POST',
$uri,
$headers,
Psr7\stream_for(json_encode($body))
);
$res = $httpHandler($request);
$body = json_decode((string) $res->getBody(), true);
return $body['signedBlob'];
}
}
src/Middleware/AuthTokenMiddleware.php 0000644 00000007532 15174273671 0014045 0 ustar 00 '
*/
class AuthTokenMiddleware
{
/**
* @var callback
*/
private $httpHandler;
/**
* @var FetchAuthTokenInterface
*/
private $fetcher;
/**
* @var callable
*/
private $tokenCallback;
/**
* Creates a new AuthTokenMiddleware.
*
* @param FetchAuthTokenInterface $fetcher is used to fetch the auth token
* @param callable $httpHandler (optional) callback which delivers psr7 request
* @param callable $tokenCallback (optional) function to be called when a new token is fetched.
*/
public function __construct(
FetchAuthTokenInterface $fetcher,
callable $httpHandler = null,
callable $tokenCallback = null
) {
$this->fetcher = $fetcher;
$this->httpHandler = $httpHandler;
$this->tokenCallback = $tokenCallback;
}
/**
* Updates the request with an Authorization header when auth is 'google_auth'.
*
* use Google\Auth\Middleware\AuthTokenMiddleware;
* use Google\Auth\OAuth2;
* use GuzzleHttp\Client;
* use GuzzleHttp\HandlerStack;
*
* $config = [...];
* $oauth2 = new OAuth2($config)
* $middleware = new AuthTokenMiddleware($oauth2);
* $stack = HandlerStack::create();
* $stack->push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'google_auth' // authorize all requests
* ]);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*
* @param callable $handler
*
* @return \Closure
*/
public function __invoke(callable $handler)
{
return function (RequestInterface $request, array $options) use ($handler) {
// Requests using "auth"="google_auth" will be authorized.
if (!isset($options['auth']) || $options['auth'] !== 'google_auth') {
return $handler($request, $options);
}
$request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken());
return $handler($request, $options);
};
}
/**
* Call fetcher to fetch the token.
*
* @return string
*/
private function fetchToken()
{
$auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler);
if (array_key_exists('access_token', $auth_tokens)) {
// notify the callback if applicable
if ($this->tokenCallback) {
call_user_func($this->tokenCallback, $this->fetcher->getCacheKey(), $auth_tokens['access_token']);
}
return $auth_tokens['access_token'];
}
}
}
src/Middleware/ScopedAccessTokenMiddleware.php 0000644 00000011731 15174273671 0015477 0 ustar 00 '
*/
class ScopedAccessTokenMiddleware
{
use CacheTrait;
const DEFAULT_CACHE_LIFETIME = 1500;
/**
* @var CacheItemPoolInterface
*/
private $cache;
/**
* @var array configuration
*/
private $cacheConfig;
/**
* @var callable
*/
private $tokenFunc;
/**
* @var array|string
*/
private $scopes;
/**
* Creates a new ScopedAccessTokenMiddleware.
*
* @param callable $tokenFunc a token generator function
* @param array|string $scopes the token authentication scopes
* @param array $cacheConfig configuration for the cache when it's present
* @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface
*/
public function __construct(
callable $tokenFunc,
$scopes,
array $cacheConfig = null,
CacheItemPoolInterface $cache = null
) {
$this->tokenFunc = $tokenFunc;
if (!(is_string($scopes) || is_array($scopes))) {
throw new \InvalidArgumentException(
'wants scope should be string or array');
}
$this->scopes = $scopes;
if (!is_null($cache)) {
$this->cache = $cache;
$this->cacheConfig = array_merge([
'lifetime' => self::DEFAULT_CACHE_LIFETIME,
'prefix' => '',
], $cacheConfig);
}
}
/**
* Updates the request with an Authorization header when auth is 'scoped'.
*
* E.g this could be used to authenticate using the AppEngine
* AppIdentityService.
*
* use google\appengine\api\app_identity\AppIdentityService;
* use Google\Auth\Middleware\ScopedAccessTokenMiddleware;
* use GuzzleHttp\Client;
* use GuzzleHttp\HandlerStack;
*
* $scope = 'https://www.googleapis.com/auth/taskqueue'
* $middleware = new ScopedAccessTokenMiddleware(
* 'AppIdentityService::getAccessToken',
* $scope,
* [ 'prefix' => 'Google\Auth\ScopedAccessToken::' ],
* $cache = new Memcache()
* );
* $stack = HandlerStack::create();
* $stack->push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'scoped' // authorize all requests
* ]);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*
* @param callable $handler
*
* @return \Closure
*/
public function __invoke(callable $handler)
{
return function (RequestInterface $request, array $options) use ($handler) {
// Requests using "auth"="scoped" will be authorized.
if (!isset($options['auth']) || $options['auth'] !== 'scoped') {
return $handler($request, $options);
}
$request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken());
return $handler($request, $options);
};
}
/**
* @return string
*/
private function getCacheKey()
{
$key = null;
if (is_string($this->scopes)) {
$key .= $this->scopes;
} elseif (is_array($this->scopes)) {
$key .= implode(':', $this->scopes);
}
return $key;
}
/**
* Determine if token is available in the cache, if not call tokenFunc to
* fetch it.
*
* @return string
*/
private function fetchToken()
{
$cacheKey = $this->getCacheKey();
$cached = $this->getCachedValue($cacheKey);
if (!empty($cached)) {
return $cached;
}
$token = call_user_func($this->tokenFunc, $this->scopes);
$this->setCachedValue($cacheKey, $token);
return $token;
}
}
src/Middleware/SimpleMiddleware.php 0000644 00000005440 15174273671 0013370 0 ustar 00 config = array_merge(['key' => null], $config);
}
/**
* Updates the request query with the developer key if auth is set to simple.
*
* use Google\Auth\Middleware\SimpleMiddleware;
* use GuzzleHttp\Client;
* use GuzzleHttp\HandlerStack;
*
* $my_key = 'is not the same as yours';
* $middleware = new SimpleMiddleware(['key' => $my_key]);
* $stack = HandlerStack::create();
* $stack->push($middleware);
*
* $client = new Client([
* 'handler' => $stack,
* 'base_uri' => 'https://www.googleapis.com/discovery/v1/',
* 'auth' => 'simple'
* ]);
*
* $res = $client->get('drive/v2/rest');
*
* @param callable $handler
*
* @return \Closure
*/
public function __invoke(callable $handler)
{
return function (RequestInterface $request, array $options) use ($handler) {
// Requests using "auth"="scoped" will be authorized.
if (!isset($options['auth']) || $options['auth'] !== 'simple') {
return $handler($request, $options);
}
$query = Psr7\parse_query($request->getUri()->getQuery());
$params = array_merge($query, $this->config);
$uri = $request->getUri()->withQuery(Psr7\build_query($params));
$request = $request->withUri($uri);
return $handler($request, $options);
};
}
}
src/OAuth2.php 0000644 00000103521 15174273671 0007165 0 ustar 00 self::DEFAULT_EXPIRY_SECONDS,
'extensionParams' => [],
'authorizationUri' => null,
'redirectUri' => null,
'tokenCredentialUri' => null,
'state' => null,
'username' => null,
'password' => null,
'clientId' => null,
'clientSecret' => null,
'issuer' => null,
'sub' => null,
'audience' => null,
'signingKey' => null,
'signingAlgorithm' => null,
'scope' => null,
'additionalClaims' => [],
], $config);
$this->setAuthorizationUri($opts['authorizationUri']);
$this->setRedirectUri($opts['redirectUri']);
$this->setTokenCredentialUri($opts['tokenCredentialUri']);
$this->setState($opts['state']);
$this->setUsername($opts['username']);
$this->setPassword($opts['password']);
$this->setClientId($opts['clientId']);
$this->setClientSecret($opts['clientSecret']);
$this->setIssuer($opts['issuer']);
$this->setSub($opts['sub']);
$this->setExpiry($opts['expiry']);
$this->setAudience($opts['audience']);
$this->setSigningKey($opts['signingKey']);
$this->setSigningAlgorithm($opts['signingAlgorithm']);
$this->setScope($opts['scope']);
$this->setExtensionParams($opts['extensionParams']);
$this->setAdditionalClaims($opts['additionalClaims']);
$this->updateToken($opts);
}
/**
* Verifies the idToken if present.
*
* - if none is present, return null
* - if present, but invalid, raises DomainException.
* - otherwise returns the payload in the idtoken as a PHP object.
*
* if $publicKey is null, the key is decoded without being verified.
*
* @param string $publicKey The public key to use to authenticate the token
* @param array $allowed_algs List of supported verification algorithms
*
* @return null|object
*/
public function verifyIdToken($publicKey = null, $allowed_algs = array())
{
$idToken = $this->getIdToken();
if (is_null($idToken)) {
return null;
}
$resp = $this->jwtDecode($idToken, $publicKey, $allowed_algs);
if (!property_exists($resp, 'aud')) {
throw new \DomainException('No audience found the id token');
}
if ($resp->aud != $this->getAudience()) {
throw new \DomainException('Wrong audience present in the id token');
}
return $resp;
}
/**
* Obtains the encoded jwt from the instance data.
*
* @param array $config array optional configuration parameters
*
* @return string
*/
public function toJwt(array $config = [])
{
if (is_null($this->getSigningKey())) {
throw new \DomainException('No signing key available');
}
if (is_null($this->getSigningAlgorithm())) {
throw new \DomainException('No signing algorithm specified');
}
$now = time();
$opts = array_merge([
'skew' => self::DEFAULT_SKEW_SECONDS,
], $config);
$assertion = [
'iss' => $this->getIssuer(),
'aud' => $this->getAudience(),
'exp' => ($now + $this->getExpiry()),
'iat' => ($now - $opts['skew']),
];
foreach ($assertion as $k => $v) {
if (is_null($v)) {
throw new \DomainException($k . ' should not be null');
}
}
if (!(is_null($this->getScope()))) {
$assertion['scope'] = $this->getScope();
}
if (!(is_null($this->getSub()))) {
$assertion['sub'] = $this->getSub();
}
$assertion += $this->getAdditionalClaims();
return $this->jwtEncode($assertion, $this->getSigningKey(),
$this->getSigningAlgorithm());
}
/**
* Generates a request for token credentials.
*
* @return RequestInterface the authorization Url.
*/
public function generateCredentialsRequest()
{
$uri = $this->getTokenCredentialUri();
if (is_null($uri)) {
throw new \DomainException('No token credential URI was set.');
}
$grantType = $this->getGrantType();
$params = array('grant_type' => $grantType);
switch ($grantType) {
case 'authorization_code':
$params['code'] = $this->getCode();
$params['redirect_uri'] = $this->getRedirectUri();
$this->addClientCredentials($params);
break;
case 'password':
$params['username'] = $this->getUsername();
$params['password'] = $this->getPassword();
$this->addClientCredentials($params);
break;
case 'refresh_token':
$params['refresh_token'] = $this->getRefreshToken();
$this->addClientCredentials($params);
break;
case self::JWT_URN:
$params['assertion'] = $this->toJwt();
break;
default:
if (!is_null($this->getRedirectUri())) {
# Grant type was supposed to be 'authorization_code', as there
# is a redirect URI.
throw new \DomainException('Missing authorization code');
}
unset($params['grant_type']);
if (!is_null($grantType)) {
$params['grant_type'] = $grantType;
}
$params = array_merge($params, $this->getExtensionParams());
}
$headers = [
'Cache-Control' => 'no-store',
'Content-Type' => 'application/x-www-form-urlencoded',
];
return new Request(
'POST',
$uri,
$headers,
Psr7\build_query($params)
);
}
/**
* Fetches the auth tokens based on the current state.
*
* @param callable $httpHandler callback which delivers psr7 request
*
* @return array the response
*/
public function fetchAuthToken(callable $httpHandler = null)
{
if (is_null($httpHandler)) {
$httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient());
}
$response = $httpHandler($this->generateCredentialsRequest());
$credentials = $this->parseTokenResponse($response);
$this->updateToken($credentials);
return $credentials;
}
/**
* Obtains a key that can used to cache the results of #fetchAuthToken.
*
* The key is derived from the scopes.
*
* @return string a key that may be used to cache the auth token.
*/
public function getCacheKey()
{
if (is_string($this->scope)) {
return $this->scope;
}
if (is_array($this->scope)) {
return implode(':', $this->scope);
}
// If scope has not set, return null to indicate no caching.
return null;
}
/**
* Parses the fetched tokens.
*
* @param ResponseInterface $resp the response.
*
* @return array the tokens parsed from the response body.
*
* @throws \Exception
*/
public function parseTokenResponse(ResponseInterface $resp)
{
$body = (string)$resp->getBody();
if ($resp->hasHeader('Content-Type') &&
$resp->getHeaderLine('Content-Type') == 'application/x-www-form-urlencoded'
) {
$res = array();
parse_str($body, $res);
return $res;
}
// Assume it's JSON; if it's not throw an exception
if (null === $res = json_decode($body, true)) {
throw new \Exception('Invalid JSON response');
}
return $res;
}
/**
* Updates an OAuth 2.0 client.
*
* @example
* client.updateToken([
* 'refresh_token' => 'n4E9O119d',
* 'access_token' => 'FJQbwq9',
* 'expires_in' => 3600
* ])
*
* @param array $config
* The configuration parameters related to the token.
*
* - refresh_token
* The refresh token associated with the access token
* to be refreshed.
*
* - access_token
* The current access token for this client.
*
* - id_token
* The current ID token for this client.
*
* - expires_in
* The time in seconds until access token expiration.
*
* - expires_at
* The time as an integer number of seconds since the Epoch
*
* - issued_at
* The timestamp that the token was issued at.
*/
public function updateToken(array $config)
{
$opts = array_merge([
'extensionParams' => [],
'access_token' => null,
'id_token' => null,
'expires_in' => null,
'expires_at' => null,
'issued_at' => null,
], $config);
$this->setExpiresAt($opts['expires_at']);
$this->setExpiresIn($opts['expires_in']);
// By default, the token is issued at `Time.now` when `expiresIn` is set,
// but this can be used to supply a more precise time.
if (!is_null($opts['issued_at'])) {
$this->setIssuedAt($opts['issued_at']);
}
$this->setAccessToken($opts['access_token']);
$this->setIdToken($opts['id_token']);
// The refresh token should only be updated if a value is explicitly
// passed in, as some access token responses do not include a refresh
// token.
if (array_key_exists('refresh_token', $opts)) {
$this->setRefreshToken($opts['refresh_token']);
}
}
/**
* Builds the authorization Uri that the user should be redirected to.
*
* @param array $config configuration options that customize the return url
*
* @return UriInterface the authorization Url.
*
* @throws InvalidArgumentException
*/
public function buildFullAuthorizationUri(array $config = [])
{
if (is_null($this->getAuthorizationUri())) {
throw new InvalidArgumentException(
'requires an authorizationUri to have been set');
}
$params = array_merge([
'response_type' => 'code',
'access_type' => 'offline',
'client_id' => $this->clientId,
'redirect_uri' => $this->redirectUri,
'state' => $this->state,
'scope' => $this->getScope(),
], $config);
// Validate the auth_params
if (is_null($params['client_id'])) {
throw new InvalidArgumentException(
'missing the required client identifier');
}
if (is_null($params['redirect_uri'])) {
throw new InvalidArgumentException('missing the required redirect URI');
}
if (!empty($params['prompt']) && !empty($params['approval_prompt'])) {
throw new InvalidArgumentException(
'prompt and approval_prompt are mutually exclusive');
}
// Construct the uri object; return it if it is valid.
$result = clone $this->authorizationUri;
$existingParams = Psr7\parse_query($result->getQuery());
$result = $result->withQuery(
Psr7\build_query(array_merge($existingParams, $params))
);
if ($result->getScheme() != 'https') {
throw new InvalidArgumentException(
'Authorization endpoint must be protected by TLS');
}
return $result;
}
/**
* Sets the authorization server's HTTP endpoint capable of authenticating
* the end-user and obtaining authorization.
*
* @param string $uri
*/
public function setAuthorizationUri($uri)
{
$this->authorizationUri = $this->coerceUri($uri);
}
/**
* Gets the authorization server's HTTP endpoint capable of authenticating
* the end-user and obtaining authorization.
*
* @return UriInterface
*/
public function getAuthorizationUri()
{
return $this->authorizationUri;
}
/**
* Gets the authorization server's HTTP endpoint capable of issuing tokens
* and refreshing expired tokens.
*
* @return string
*/
public function getTokenCredentialUri()
{
return $this->tokenCredentialUri;
}
/**
* Sets the authorization server's HTTP endpoint capable of issuing tokens
* and refreshing expired tokens.
*
* @param string $uri
*/
public function setTokenCredentialUri($uri)
{
$this->tokenCredentialUri = $this->coerceUri($uri);
}
/**
* Gets the redirection URI used in the initial request.
*
* @return string
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* Sets the redirection URI used in the initial request.
*
* @param string $uri
*/
public function setRedirectUri($uri)
{
if (is_null($uri)) {
$this->redirectUri = null;
return;
}
// redirect URI must be absolute
if (!$this->isAbsoluteUri($uri)) {
// "postmessage" is a reserved URI string in Google-land
// @see https://developers.google.com/identity/sign-in/web/server-side-flow
if ('postmessage' !== (string)$uri) {
throw new InvalidArgumentException(
'Redirect URI must be absolute');
}
}
$this->redirectUri = (string)$uri;
}
/**
* Gets the scope of the access requests as a space-delimited String.
*
* @return string
*/
public function getScope()
{
if (is_null($this->scope)) {
return $this->scope;
}
return implode(' ', $this->scope);
}
/**
* Sets the scope of the access request, expressed either as an Array or as
* a space-delimited String.
*
* @param string|array $scope
*
* @throws InvalidArgumentException
*/
public function setScope($scope)
{
if (is_null($scope)) {
$this->scope = null;
} elseif (is_string($scope)) {
$this->scope = explode(' ', $scope);
} elseif (is_array($scope)) {
foreach ($scope as $s) {
$pos = strpos($s, ' ');
if ($pos !== false) {
throw new InvalidArgumentException(
'array scope values should not contain spaces');
}
}
$this->scope = $scope;
} else {
throw new InvalidArgumentException(
'scopes should be a string or array of strings');
}
}
/**
* Gets the current grant type.
*
* @return string
*/
public function getGrantType()
{
if (!is_null($this->grantType)) {
return $this->grantType;
}
// Returns the inferred grant type, based on the current object instance
// state.
if (!is_null($this->code)) {
return 'authorization_code';
}
if (!is_null($this->refreshToken)) {
return 'refresh_token';
}
if (!is_null($this->username) && !is_null($this->password)) {
return 'password';
}
if (!is_null($this->issuer) && !is_null($this->signingKey)) {
return self::JWT_URN;
}
return null;
}
/**
* Sets the current grant type.
*
* @param $grantType
*
* @throws InvalidArgumentException
*/
public function setGrantType($grantType)
{
if (in_array($grantType, self::$knownGrantTypes)) {
$this->grantType = $grantType;
} else {
// validate URI
if (!$this->isAbsoluteUri($grantType)) {
throw new InvalidArgumentException(
'invalid grant type');
}
$this->grantType = (string)$grantType;
}
}
/**
* Gets an arbitrary string designed to allow the client to maintain state.
*
* @return string
*/
public function getState()
{
return $this->state;
}
/**
* Sets an arbitrary string designed to allow the client to maintain state.
*
* @param string $state
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Gets the authorization code issued to this client.
*/
public function getCode()
{
return $this->code;
}
/**
* Sets the authorization code issued to this client.
*
* @param string $code
*/
public function setCode($code)
{
$this->code = $code;
}
/**
* Gets the resource owner's username.
*/
public function getUsername()
{
return $this->username;
}
/**
* Sets the resource owner's username.
*
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Gets the resource owner's password.
*/
public function getPassword()
{
return $this->password;
}
/**
* Sets the resource owner's password.
*
* @param $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Sets a unique identifier issued to the client to identify itself to the
* authorization server.
*/
public function getClientId()
{
return $this->clientId;
}
/**
* Sets a unique identifier issued to the client to identify itself to the
* authorization server.
*
* @param $clientId
*/
public function setClientId($clientId)
{
$this->clientId = $clientId;
}
/**
* Gets a shared symmetric secret issued by the authorization server, which
* is used to authenticate the client.
*/
public function getClientSecret()
{
return $this->clientSecret;
}
/**
* Sets a shared symmetric secret issued by the authorization server, which
* is used to authenticate the client.
*
* @param $clientSecret
*/
public function setClientSecret($clientSecret)
{
$this->clientSecret = $clientSecret;
}
/**
* Gets the Issuer ID when using assertion profile.
*/
public function getIssuer()
{
return $this->issuer;
}
/**
* Sets the Issuer ID when using assertion profile.
*
* @param string $issuer
*/
public function setIssuer($issuer)
{
$this->issuer = $issuer;
}
/**
* Gets the target sub when issuing assertions.
*/
public function getSub()
{
return $this->sub;
}
/**
* Sets the target sub when issuing assertions.
*
* @param string $sub
*/
public function setSub($sub)
{
$this->sub = $sub;
}
/**
* Gets the target audience when issuing assertions.
*/
public function getAudience()
{
return $this->audience;
}
/**
* Sets the target audience when issuing assertions.
*
* @param string $audience
*/
public function setAudience($audience)
{
$this->audience = $audience;
}
/**
* Gets the signing key when using an assertion profile.
*/
public function getSigningKey()
{
return $this->signingKey;
}
/**
* Sets the signing key when using an assertion profile.
*
* @param string $signingKey
*/
public function setSigningKey($signingKey)
{
$this->signingKey = $signingKey;
}
/**
* Gets the signing algorithm when using an assertion profile.
*
* @return string
*/
public function getSigningAlgorithm()
{
return $this->signingAlgorithm;
}
/**
* Sets the signing algorithm when using an assertion profile.
*
* @param string $signingAlgorithm
*/
public function setSigningAlgorithm($signingAlgorithm)
{
if (is_null($signingAlgorithm)) {
$this->signingAlgorithm = null;
} elseif (!in_array($signingAlgorithm, self::$knownSigningAlgorithms)) {
throw new InvalidArgumentException('unknown signing algorithm');
} else {
$this->signingAlgorithm = $signingAlgorithm;
}
}
/**
* Gets the set of parameters used by extension when using an extension
* grant type.
*/
public function getExtensionParams()
{
return $this->extensionParams;
}
/**
* Sets the set of parameters used by extension when using an extension
* grant type.
*
* @param $extensionParams
*/
public function setExtensionParams($extensionParams)
{
$this->extensionParams = $extensionParams;
}
/**
* Gets the number of seconds assertions are valid for.
*/
public function getExpiry()
{
return $this->expiry;
}
/**
* Sets the number of seconds assertions are valid for.
*
* @param int $expiry
*/
public function setExpiry($expiry)
{
$this->expiry = $expiry;
}
/**
* Gets the lifetime of the access token in seconds.
*/
public function getExpiresIn()
{
return $this->expiresIn;
}
/**
* Sets the lifetime of the access token in seconds.
*
* @param int $expiresIn
*/
public function setExpiresIn($expiresIn)
{
if (is_null($expiresIn)) {
$this->expiresIn = null;
$this->issuedAt = null;
} else {
$this->issuedAt = time();
$this->expiresIn = (int)$expiresIn;
}
}
/**
* Gets the time the current access token expires at.
*
* @return int
*/
public function getExpiresAt()
{
if (!is_null($this->expiresAt)) {
return $this->expiresAt;
}
if (!is_null($this->issuedAt) && !is_null($this->expiresIn)) {
return $this->issuedAt + $this->expiresIn;
}
return null;
}
/**
* Returns true if the acccess token has expired.
*
* @return bool
*/
public function isExpired()
{
$expiration = $this->getExpiresAt();
$now = time();
return !is_null($expiration) && $now >= $expiration;
}
/**
* Sets the time the current access token expires at.
*
* @param int $expiresAt
*/
public function setExpiresAt($expiresAt)
{
$this->expiresAt = $expiresAt;
}
/**
* Gets the time the current access token was issued at.
*/
public function getIssuedAt()
{
return $this->issuedAt;
}
/**
* Sets the time the current access token was issued at.
*
* @param int $issuedAt
*/
public function setIssuedAt($issuedAt)
{
$this->issuedAt = $issuedAt;
}
/**
* Gets the current access token.
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* Sets the current access token.
*
* @param string $accessToken
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
}
/**
* Gets the current ID token.
*/
public function getIdToken()
{
return $this->idToken;
}
/**
* Sets the current ID token.
*
* @param $idToken
*/
public function setIdToken($idToken)
{
$this->idToken = $idToken;
}
/**
* Gets the refresh token associated with the current access token.
*/
public function getRefreshToken()
{
return $this->refreshToken;
}
/**
* Sets the refresh token associated with the current access token.
*
* @param $refreshToken
*/
public function setRefreshToken($refreshToken)
{
$this->refreshToken = $refreshToken;
}
/**
* Sets additional claims to be included in the JWT token
*
* @param array $additionalClaims
*/
public function setAdditionalClaims(array $additionalClaims)
{
$this->additionalClaims = $additionalClaims;
}
/**
* Gets the additional claims to be included in the JWT token.
*
* @return array
*/
public function getAdditionalClaims()
{
return $this->additionalClaims;
}
/**
* The expiration of the last received token.
*
* @return array
*/
public function getLastReceivedToken()
{
if ($token = $this->getAccessToken()) {
return [
'access_token' => $token,
'expires_at' => $this->getExpiresAt(),
];
}
return null;
}
/**
* Get the client ID.
*
* Alias of {@see Google\Auth\OAuth2::getClientId()}.
*
* @param callable $httpHandler
* @return string
* @access private
*/
public function getClientName(callable $httpHandler = null)
{
return $this->getClientId();
}
/**
* @todo handle uri as array
*
* @param string $uri
*
* @return null|UriInterface
*/
private function coerceUri($uri)
{
if (is_null($uri)) {
return;
}
return Psr7\uri_for($uri);
}
/**
* @param string $idToken
* @param string|array|null $publicKey
* @param array $allowedAlgs
*
* @return object
*/
private function jwtDecode($idToken, $publicKey, $allowedAlgs)
{
if (class_exists('Firebase\JWT\JWT')) {
return \Firebase\JWT\JWT::decode($idToken, $publicKey, $allowedAlgs);
}
return \JWT::decode($idToken, $publicKey, $allowedAlgs);
}
private function jwtEncode($assertion, $signingKey, $signingAlgorithm)
{
if (class_exists('Firebase\JWT\JWT')) {
return \Firebase\JWT\JWT::encode($assertion, $signingKey,
$signingAlgorithm);
}
return \JWT::encode($assertion, $signingKey, $signingAlgorithm);
}
/**
* Determines if the URI is absolute based on its scheme and host or path
* (RFC 3986).
*
* @param string $uri
*
* @return bool
*/
private function isAbsoluteUri($uri)
{
$uri = $this->coerceUri($uri);
return $uri->getScheme() && ($uri->getHost() || $uri->getPath());
}
/**
* @param array $params
*
* @return array
*/
private function addClientCredentials(&$params)
{
$clientId = $this->getClientId();
$clientSecret = $this->getClientSecret();
if ($clientId && $clientSecret) {
$params['client_id'] = $clientId;
$params['client_secret'] = $clientSecret;
}
return $params;
}
}
src/ServiceAccountSignerTrait.php 0000644 00000003440 15174273671 0013153 0 ustar 00 auth->getSigningKey();
$signedString = '';
if (class_exists('RSA') && !$forceOpenssl) {
$rsa = new RSA;
$rsa->loadKey($privateKey);
$rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
$rsa->setHash('sha256');
$signedString = $rsa->sign($stringToSign);
} elseif (extension_loaded('openssl')) {
openssl_sign($stringToSign, $signedString, $privateKey, 'sha256WithRSAEncryption');
} else {
// @codeCoverageIgnoreStart
throw new \RuntimeException('OpenSSL is not installed.');
}
// @codeCoverageIgnoreEnd
return base64_encode($signedString);
}
}
src/SignBlobInterface.php 0000644 00000002773 15174273671 0011412 0 ustar 00 '
*/
class AuthTokenSubscriber implements SubscriberInterface
{
/**
* @var callable
*/
private $httpHandler;
/**
* @var FetchAuthTokenInterface
*/
private $fetcher;
/**
* @var callable
*/
private $tokenCallback;
/**
* Creates a new AuthTokenSubscriber.
*
* @param FetchAuthTokenInterface $fetcher is used to fetch the auth token
* @param callable $httpHandler (optional) http client to fetch the token.
* @param callable $tokenCallback (optional) function to be called when a new token is fetched.
*/
public function __construct(
FetchAuthTokenInterface $fetcher,
callable $httpHandler = null,
callable $tokenCallback = null
) {
$this->fetcher = $fetcher;
$this->httpHandler = $httpHandler;
$this->tokenCallback = $tokenCallback;
}
/**
* @return array
*/
public function getEvents()
{
return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]];
}
/**
* Updates the request with an Authorization header when auth is 'fetched_auth_token'.
*
* use GuzzleHttp\Client;
* use Google\Auth\OAuth2;
* use Google\Auth\Subscriber\AuthTokenSubscriber;
*
* $config = [...];
* $oauth2 = new OAuth2($config)
* $subscriber = new AuthTokenSubscriber($oauth2);
*
* $client = new Client([
* 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'defaults' => ['auth' => 'google_auth']
* ]);
* $client->getEmitter()->attach($subscriber);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*
* @param BeforeEvent $event
*/
public function onBefore(BeforeEvent $event)
{
// Requests using "auth"="google_auth" will be authorized.
$request = $event->getRequest();
if ($request->getConfig()['auth'] != 'google_auth') {
return;
}
// Fetch the auth token.
$auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler);
if (array_key_exists('access_token', $auth_tokens)) {
$request->setHeader('authorization', 'Bearer ' . $auth_tokens['access_token']);
// notify the callback if applicable
if ($this->tokenCallback) {
call_user_func($this->tokenCallback, $this->fetcher->getCacheKey(), $auth_tokens['access_token']);
}
}
}
}
src/Subscriber/ScopedAccessTokenSubscriber.php 0000644 00000012004 15174273671 0015545 0 ustar 00 '
*/
class ScopedAccessTokenSubscriber implements SubscriberInterface
{
use CacheTrait;
const DEFAULT_CACHE_LIFETIME = 1500;
/**
* @var CacheItemPoolInterface
*/
private $cache;
/**
* @var callable The access token generator function
*/
private $tokenFunc;
/**
* @var array|string The scopes used to generate the token
*/
private $scopes;
/**
* @var array
*/
private $cacheConfig;
/**
* Creates a new ScopedAccessTokenSubscriber.
*
* @param callable $tokenFunc a token generator function
* @param array|string $scopes the token authentication scopes
* @param array $cacheConfig configuration for the cache when it's present
* @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface
*/
public function __construct(
callable $tokenFunc,
$scopes,
array $cacheConfig = null,
CacheItemPoolInterface $cache = null
) {
$this->tokenFunc = $tokenFunc;
if (!(is_string($scopes) || is_array($scopes))) {
throw new \InvalidArgumentException(
'wants scope should be string or array');
}
$this->scopes = $scopes;
if (!is_null($cache)) {
$this->cache = $cache;
$this->cacheConfig = array_merge([
'lifetime' => self::DEFAULT_CACHE_LIFETIME,
'prefix' => '',
], $cacheConfig);
}
}
/**
* @return array
*/
public function getEvents()
{
return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]];
}
/**
* Updates the request with an Authorization header when auth is 'scoped'.
*
* E.g this could be used to authenticate using the AppEngine
* AppIdentityService.
*
* use google\appengine\api\app_identity\AppIdentityService;
* use Google\Auth\Subscriber\ScopedAccessTokenSubscriber;
* use GuzzleHttp\Client;
*
* $scope = 'https://www.googleapis.com/auth/taskqueue'
* $subscriber = new ScopedAccessToken(
* 'AppIdentityService::getAccessToken',
* $scope,
* ['prefix' => 'Google\Auth\ScopedAccessToken::'],
* $cache = new Memcache()
* );
*
* $client = new Client([
* 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'defaults' => ['auth' => 'scoped']
* ]);
* $client->getEmitter()->attach($subscriber);
*
* $res = $client->get('myproject/taskqueues/myqueue');
*
* @param BeforeEvent $event
*/
public function onBefore(BeforeEvent $event)
{
// Requests using "auth"="scoped" will be authorized.
$request = $event->getRequest();
if ($request->getConfig()['auth'] != 'scoped') {
return;
}
$auth_header = 'Bearer ' . $this->fetchToken();
$request->setHeader('authorization', $auth_header);
}
/**
* @return string
*/
private function getCacheKey()
{
$key = null;
if (is_string($this->scopes)) {
$key .= $this->scopes;
} elseif (is_array($this->scopes)) {
$key .= implode(':', $this->scopes);
}
return $key;
}
/**
* Determine if token is available in the cache, if not call tokenFunc to
* fetch it.
*
* @return string
*/
private function fetchToken()
{
$cacheKey = $this->getCacheKey();
$cached = $this->getCachedValue($cacheKey);
if (!empty($cached)) {
return $cached;
}
$token = call_user_func($this->tokenFunc, $this->scopes);
$this->setCachedValue($cacheKey, $token);
return $token;
}
}
src/Subscriber/SimpleSubscriber.php 0000644 00000005053 15174273671 0013444 0 ustar 00 config = array_merge([], $config);
}
/**
* @return array
*/
public function getEvents()
{
return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]];
}
/**
* Updates the request query with the developer key if auth is set to simple.
*
* use Google\Auth\Subscriber\SimpleSubscriber;
* use GuzzleHttp\Client;
*
* $my_key = 'is not the same as yours';
* $subscriber = new SimpleSubscriber(['key' => $my_key]);
*
* $client = new Client([
* 'base_url' => 'https://www.googleapis.com/discovery/v1/',
* 'defaults' => ['auth' => 'simple']
* ]);
* $client->getEmitter()->attach($subscriber);
*
* $res = $client->get('drive/v2/rest');
*
* @param BeforeEvent $event
*/
public function onBefore(BeforeEvent $event)
{
// Requests using "auth"="simple" with the developer key.
$request = $event->getRequest();
if ($request->getConfig()['auth'] != 'simple') {
return;
}
$request->getQuery()->overwriteWith($this->config);
}
}
tests/ApplicationDefaultCredentialsTest.php 0000644 00000024522 15174273671 0015227 0 ustar 00 originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
putenv(ServiceAccountCredentials::ENV_VAR); // removes it from
}
/**
* @expectedException DomainException
*/
public function testIsFailsEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getCredentials('a scope');
}
public function testLoadsOKIfEnvSpecifiedIsValid()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
public function testLoadsDefaultFileIfPresentAndEnvVarIsNotSet()
{
putenv('HOME=' . __DIR__ . '/fixtures');
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
/**
* @expectedException DomainException
*/
public function testFailsIfNotOnGceAndNoDefaultFileFound()
{
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// simulate not being GCE and retry attempts by returning multiple 500s
$httpHandler = getHandler([
buildResponse(500),
buildResponse(500),
buildResponse(500)
]);
ApplicationDefaultCredentials::getCredentials('a scope', $httpHandler);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
// simulate the response from GCE.
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope', $httpHandler)
);
}
}
class ADCGetMiddlewareTest extends TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
putenv(ServiceAccountCredentials::ENV_VAR); // removes it if assigned
}
/**
* @expectedException DomainException
*/
public function testIsFailsEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getMiddleware('a scope');
}
public function testLoadsOKIfEnvSpecifiedIsValid()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getMiddleware('a scope'));
}
public function testLoadsDefaultFileIfPresentAndEnvVarIsNotSet()
{
putenv('HOME=' . __DIR__ . '/fixtures');
$this->assertNotNull(ApplicationDefaultCredentials::getMiddleware('a scope'));
}
/**
* @expectedException DomainException
*/
public function testFailsIfNotOnGceAndNoDefaultFileFound()
{
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// simulate not being GCE and retry attempts by returning multiple 500s
$httpHandler = getHandler([
buildResponse(500),
buildResponse(500),
buildResponse(500)
]);
ApplicationDefaultCredentials::getMiddleware('a scope', $httpHandler);
}
public function testWithCacheOptions()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$httpHandler = getHandler([
buildResponse(200),
]);
$cacheOptions = [];
$cachePool = $this->prophesize('Psr\Cache\CacheItemPoolInterface');
$middleware = ApplicationDefaultCredentials::getMiddleware(
'a scope',
$httpHandler,
$cacheOptions,
$cachePool->reveal()
);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
// simulate the response from GCE.
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$this->assertNotNull(ApplicationDefaultCredentials::getMiddleware('a scope', $httpHandler));
}
}
class ADCGetCredentialsAppEngineTest extends BaseTest
{
private $originalHome;
private $originalServiceAccount;
protected function setUp()
{
// set home to be somewhere else
$this->originalHome = getenv('HOME');
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// remove service account path
$this->originalServiceAccount = getenv(ServiceAccountCredentials::ENV_VAR);
putenv(ServiceAccountCredentials::ENV_VAR);
}
protected function tearDown()
{
// removes it if assigned
putenv('HOME=' . $this->originalHome);
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $this->originalServiceAccount);
putenv('GAE_INSTANCE');
}
public function testAppEngineStandard()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$this->assertInstanceOf(
'Google\Auth\Credentials\AppIdentityCredentials',
ApplicationDefaultCredentials::getCredentials()
);
}
public function testAppEngineFlexible()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
putenv('GAE_INSTANCE=aef-default-20180313t154438');
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
]);
$this->assertInstanceOf(
'Google\Auth\Credentials\GCECredentials',
ApplicationDefaultCredentials::getCredentials(null, $httpHandler)
);
}
}
// @todo consider a way to DRY this and above class up
class ADCGetSubscriberTest extends BaseTest
{
private $originalHome;
protected function setUp()
{
$this->onlyGuzzle5();
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
putenv(ServiceAccountCredentials::ENV_VAR); // removes it if assigned
}
/**
* @expectedException DomainException
*/
public function testIsFailsEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getSubscriber('a scope');
}
public function testLoadsOKIfEnvSpecifiedIsValid()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getSubscriber('a scope'));
}
public function testLoadsDefaultFileIfPresentAndEnvVarIsNotSet()
{
putenv('HOME=' . __DIR__ . '/fixtures');
$this->assertNotNull(ApplicationDefaultCredentials::getSubscriber('a scope'));
}
/**
* @expectedException DomainException
*/
public function testFailsIfNotOnGceAndNoDefaultFileFound()
{
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// simulate not being GCE by return 500
$httpHandler = getHandler([
buildResponse(500),
]);
ApplicationDefaultCredentials::getSubscriber('a scope', $httpHandler);
}
public function testWithCacheOptions()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$httpHandler = getHandler([
buildResponse(200),
]);
$cacheOptions = [];
$cachePool = $this->getMock('Psr\Cache\CacheItemPoolInterface');
$subscriber = ApplicationDefaultCredentials::getSubscriber(
'a scope',
$httpHandler,
$cacheOptions,
$cachePool
);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
// simulate the response from GCE.
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$this->assertNotNull(ApplicationDefaultCredentials::getSubscriber('a scope', $httpHandler));
}
}
tests/BaseTest.php 0000644 00000001302 15174273671 0010142 0 ustar 00 markTestSkipped('Guzzle 6 only');
}
}
public function onlyGuzzle5()
{
$version = ClientInterface::VERSION;
if ('5' !== $version[0]) {
$this->markTestSkipped('Guzzle 5 only');
}
}
/**
* @see Google\Auth\$this->getValidKeyName
*/
public function getValidKeyName($key)
{
return preg_replace('|[^a-zA-Z0-9_\.! ]|', '', $key);
}
}
tests/Cache/ItemTest.php 0000644 00000005376 15174273671 0011210 0 ustar 00 assertEquals($key, $this->getItem($key)->getKey());
}
public function testGetsNull()
{
$item = $this->getItem('item');
$this->assertNull($item->get());
$this->assertFalse($item->isHit());
}
public function testGetsValue()
{
$value = 'value';
$item = $this->getItem('item');
$item->set($value);
$this->assertEquals('value', $item->get());
}
/**
* @dataProvider values
*/
public function testSetsValue($value)
{
$item = $this->getItem('item');
$item->set($value);
$this->assertEquals($value, $item->get());
}
public function values()
{
return [
[1],
[1.5],
[true],
[null],
[new \DateTime()],
[['test']],
['value']
];
}
public function testIsHit()
{
$item = $this->getItem('item');
$this->assertFalse($item->isHit());
$item->set('value');
$this->assertTrue($item->isHit());
}
public function testExpiresAt()
{
$item = $this->getItem('item');
$item->set('value');
$item->expiresAt(new \DateTime('now + 1 hour'));
$this->assertTrue($item->isHit());
$item->expiresAt(null);
$this->assertTrue($item->isHit());
$item->expiresAt(new \DateTime('yesterday'));
$this->assertFalse($item->isHit());
}
public function testExpiresAfter()
{
$item = $this->getItem('item');
$item->set('value');
$item->expiresAfter(30);
$this->assertTrue($item->isHit());
$item->expiresAfter(0);
$this->assertFalse($item->isHit());
$item->expiresAfter(new \DateInterval('PT30S'));
$this->assertTrue($item->isHit());
$item->expiresAfter(null);
$this->assertTrue($item->isHit());
}
}
tests/Cache/MemoryCacheItemPoolTest.php 0000644 00000013260 15174273671 0014146 0 ustar 00 pool = new MemoryCacheItemPool();
}
public function saveItem($key, $value)
{
$item = $this->pool->getItem($key);
$item->set($value);
$this->assertTrue($this->pool->save($item));
return $item;
}
public function testGetsFreshItem()
{
$item = $this->pool->getItem('item');
$this->assertInstanceOf('Google\Auth\Cache\Item', $item);
$this->assertNull($item->get());
$this->assertFalse($item->isHit());
}
public function testGetsExistingItem()
{
$key = 'item';
$value = 'value';
$this->saveItem($key, $value);
$item = $this->pool->getItem($key);
$this->assertInstanceOf('Google\Auth\Cache\Item', $item);
$this->assertEquals($value, $item->get());
$this->assertTrue($item->isHit());
}
public function testGetsMultipleItems()
{
$keys = ['item1', 'item2'];
$items = $this->pool->getItems($keys);
$this->assertEquals($keys, array_keys($items));
$this->assertContainsOnlyInstancesOf('Google\Auth\Cache\Item', $items);
}
public function testHasItem()
{
$existsKey = 'does-exist';
$this->saveItem($existsKey, 'value');
$this->assertTrue($this->pool->hasItem($existsKey));
$this->assertFalse($this->pool->hasItem('does-not-exist'));
}
public function testClear()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->hasItem($key));
$this->assertTrue($this->pool->clear());
$this->assertFalse($this->pool->hasItem($key));
}
public function testDeletesItem()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->deleteItem($key));
$this->assertFalse($this->pool->hasItem($key));
}
public function testDeletesItems()
{
$keys = ['item1', 'item2'];
foreach ($keys as $key) {
$this->saveItem($key, 'value');
}
$this->assertTrue($this->pool->deleteItems($keys));
$this->assertFalse($this->pool->hasItem($keys[0]));
$this->assertFalse($this->pool->hasItem($keys[1]));
}
public function testDoesNotDeleteItemsWithInvalidKey()
{
$keys = ['item1', '{item2}', 'item3'];
$value = 'value';
$this->saveItem($keys[0], $value);
$this->saveItem($keys[2], $value);
try {
$this->pool->deleteItems($keys);
} catch (InvalidArgumentException $ex) {
// continue execution
}
$this->assertTrue($this->pool->hasItem($keys[0]));
$this->assertTrue($this->pool->hasItem($keys[2]));
}
public function testSavesItem()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->hasItem($key));
}
public function testSavesDeferredItem()
{
$item = $this->pool->getItem('item');
$this->assertTrue($this->pool->saveDeferred($item));
}
public function testCommitsDeferredItems()
{
$keys = ['item1', 'item2'];
foreach ($keys as $key) {
$item = $this->pool->getItem($key);
$item->set('value');
$this->pool->saveDeferred($item);
}
$this->assertTrue($this->pool->commit());
$this->assertTrue($this->pool->hasItem($keys[0]));
$this->assertTrue($this->pool->hasItem($keys[1]));
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnGetItem($key)
{
$this->pool->getItem($key);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnGetItems($key)
{
$this->pool->getItems([$key]);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnHasItem($key)
{
$this->pool->hasItem($key);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnDeleteItem($key)
{
$this->pool->deleteItem($key);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnDeleteItems($key)
{
$this->pool->deleteItems([$key]);
}
public function invalidKeys()
{
return [
[1],
[true],
[null],
[new \DateTime()],
['{'],
['}'],
['('],
[')'],
['/'],
['\\'],
['@'],
[':'],
[[]]
];
}
}
tests/Cache/SysVCacheItemPoolTest.php 0000644 00000010606 15174273671 0013603 0 ustar 00 markTestSkipped(
'sysvshm extension is required for running the test'
);
}
$this->pool = new SysVCacheItemPool(['variableKey' => 99]);
$this->pool->clear();
}
public function saveItem($key, $value)
{
$item = $this->pool->getItem($key);
$item->set($value);
$this->assertTrue($this->pool->save($item));
return $item;
}
public function testGetsFreshItem()
{
$item = $this->pool->getItem('item');
$this->assertInstanceOf('Google\Auth\Cache\Item', $item);
$this->assertNull($item->get());
$this->assertFalse($item->isHit());
}
public function testCacheAmongProcesses()
{
$expectedValue = 'val-' . rand();
exec(sprintf('php %s/sysv_cache_creator.php %s', __DIR__, $expectedValue));
$this->assertEquals(
$expectedValue,
$this->pool->getItem('separate-process-item')->get()
);
}
public function testGetsExistingItem()
{
$key = 'item';
$value = 'value';
$this->saveItem($key, $value);
$item = $this->pool->getItem($key);
$this->assertInstanceOf('Google\Auth\Cache\Item', $item);
$this->assertEquals($value, $item->get());
$this->assertTrue($item->isHit());
}
public function testGetsMultipleItems()
{
$keys = ['item1', 'item2'];
$items = $this->pool->getItems($keys);
$this->assertEquals($keys, array_keys($items));
$this->assertContainsOnlyInstancesOf('Google\Auth\Cache\Item', $items);
}
public function testHasItem()
{
$existsKey = 'does-exist';
$this->saveItem($existsKey, 'value');
$this->assertTrue($this->pool->hasItem($existsKey));
$this->assertFalse($this->pool->hasItem('does-not-exist'));
}
public function testClear()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->hasItem($key));
$this->assertTrue($this->pool->clear());
$this->assertFalse($this->pool->hasItem($key));
}
public function testDeletesItem()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->deleteItem($key));
$this->assertFalse($this->pool->hasItem($key));
}
public function testDeletesItems()
{
$keys = ['item1', 'item2'];
foreach ($keys as $key) {
$this->saveItem($key, 'value');
}
$this->assertTrue($this->pool->deleteItems($keys));
$this->assertFalse($this->pool->hasItem($keys[0]));
$this->assertFalse($this->pool->hasItem($keys[1]));
}
public function testSavesItem()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->hasItem($key));
}
public function testSavesDeferredItem()
{
$item = $this->pool->getItem('item');
$this->assertTrue($this->pool->saveDeferred($item));
}
public function testCommitsDeferredItems()
{
$keys = ['item1', 'item2'];
foreach ($keys as $key) {
$item = $this->pool->getItem($key);
$item->set('value');
$this->pool->saveDeferred($item);
}
$this->assertTrue($this->pool->commit());
$this->assertTrue($this->pool->hasItem($keys[0]));
$this->assertTrue($this->pool->hasItem($keys[1]));
$this->assertEquals(
$item->get(),
$this->pool->getItem($keys[1])->get()
);
}
}
tests/Cache/sysv_cache_creator.php 0000644 00000001671 15174273671 0013312 0 ustar 00 99]);
$item = new Item('separate-process-item');
$item->set($value);
$pool->save($item);
tests/CacheTraitTest.php 0000644 00000014422 15174273671 0011306 0 ustar 00 mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
}
public function testSuccessfullyPullsFromCache()
{
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($expectedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
]);
$cachedValue = $implementation->gCachedValue();
$this->assertEquals($expectedValue, $cachedValue);
}
public function testSuccessfullyPullsFromCacheWithInvalidKey()
{
$key = 'this-key-has-@-illegal-characters';
$expectedKey = 'thiskeyhasillegalcharacters';
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($expectedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($expectedKey)
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => $key,
]);
$cachedValue = $implementation->gCachedValue();
$this->assertEquals($expectedValue, $cachedValue);
}
public function testSuccessfullyPullsFromCacheWithLongKey()
{
$key = 'this-key-is-over-64-characters-and-it-will-still-work'
. '-but-it-will-be-hashed-and-shortened';
$expectedKey = str_replace('-', '', $key);
$expectedKey = substr(hash('sha256', $expectedKey), 0, 64);
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($expectedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($expectedKey)
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => $key
]);
$cachedValue = $implementation->gCachedValue();
$this->assertEquals($expectedValue, $cachedValue);
}
public function testFailsPullFromCacheWithNoCache()
{
$implementation = new CacheTraitImplementation();
$cachedValue = $implementation->gCachedValue();
$this->assertEquals(null, $cachedValue);
}
public function testFailsPullFromCacheWithoutKey()
{
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => null,
]);
$cachedValue = $implementation->gCachedValue();
}
public function testSuccessfullySetsToCache()
{
$value = '1234';
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($value);
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo('key'))
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
]);
$implementation->sCachedValue($value);
}
public function testFailsSetToCacheWithNoCache()
{
$implementation = new CacheTraitImplementation();
$implementation->sCachedValue('1234');
$cachedValue = $implementation->sCachedValue('1234');
$this->assertNull($cachedValue);
}
public function testFailsSetToCacheWithoutKey()
{
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => null,
]);
$cachedValue = $implementation->sCachedValue('1234');
$this->assertNull($cachedValue);
}
}
class CacheTraitImplementation
{
use CacheTrait;
private $cache;
private $cacheConfig;
public function __construct(array $config = [])
{
$this->key = array_key_exists('key', $config) ? $config['key'] : 'key';
$this->cache = isset($config['cache']) ? $config['cache'] : null;
$this->cacheConfig = [
'prefix' => '',
'lifetime' => 1000,
];
}
// allows us to keep trait methods private
public function gCachedValue()
{
return $this->getCachedValue($this->key);
}
public function sCachedValue($v)
{
$this->setCachedValue($this->key, $v);
}
}
tests/Credentials/AppIdentityCredentialsTest.php 0000644 00000014320 15174273671 0016141 0 ustar 00 assertFalse(AppIdentityCredentials::onAppEngine());
}
/**
* @runInSeparateProcess
*/
public function testOnAppEngineIsTrueWhenServerSoftwareIsGoogleAppEngine()
{
$this->imitateInAppEngine();
$this->assertTrue(AppIdentityCredentials::onAppEngine());
}
/**
* @runInSeparateProcess
*/
public function testOnAppEngineIsTrueWhenAppEngineRuntimeIsPhp()
{
$this->imitateInAppEngine();
$this->assertTrue(AppIdentityCredentials::onAppEngine());
}
/**
* @runInSeparateProcess
*/
public function testOnAppEngineIsTrueInDevelopmentServer()
{
$_SERVER['APPENGINE_RUNTIME'] = 'php';
$this->assertTrue(AppIdentityCredentials::onAppEngine());
}
public function testGetCacheKeyShouldBeEmpty()
{
$g = new AppIdentityCredentials();
$this->assertEmpty($g->getCacheKey());
}
public function testFetchAuthTokenShouldBeEmptyIfNotOnAppEngine()
{
$g = new AppIdentityCredentials();
$this->assertEquals(array(), $g->fetchAuthToken());
}
/* @expectedException */
public function testThrowsExceptionIfClassDoesntExist()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$g = new AppIdentityCredentials();
}
/**
* @runInSeparateProcess
*/
public function testFetchAuthTokenReturnsExpectedToken()
{
$this->imitateInAppEngine();
$wantedToken = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
AppIdentityService::$accessToken = $wantedToken;
$g = new AppIdentityCredentials();
$this->assertEquals($wantedToken, $g->fetchAuthToken());
}
/**
* @runInSeparateProcess
*/
public function testScopeIsAlwaysArray()
{
$this->imitateInAppEngine();
$scope1 = ['scopeA', 'scopeB'];
$scope2 = 'scopeA scopeB';
$scope3 = 'scopeA';
$g = new AppIdentityCredentials($scope1);
$g->fetchAuthToken();
$this->assertEquals($scope1, AppIdentityService::$scope);
$g = new AppIdentityCredentials($scope2);
$g->fetchAuthToken();
$this->assertEquals(explode(' ', $scope2), AppIdentityService::$scope);
$g = new AppIdentityCredentials($scope3);
$g->fetchAuthToken();
$this->assertEquals([$scope3], AppIdentityService::$scope);
}
/**
* @dataProvider appEngineRequired
*/
public function testMethodsFailWhenNotInAppEngine($method, $args = [], $expected = null)
{
if ($expected === null) {
if (method_exists($this, 'expectException')) {
$this->expectException('\Exception');
} else {
$this->setExpectedException('\Exception');
}
}
$creds = new AppIdentityCredentials;
$res = call_user_func_array([$creds, $method], $args);
if ($expected) {
$this->assertEquals($expected, $res);
}
}
public function appEngineRequired()
{
return [
['fetchAuthToken', [], []],
['signBlob', ['foo']],
['getClientName']
];
}
/**
* @runInSeparateProcess
*/
public function testSignBlob()
{
$this->imitateInAppEngine();
$creds = new AppIdentityCredentials;
$string = 'test';
$res = $creds->signBlob($string);
$this->assertEquals(base64_encode('Signed: ' . $string), $res);
}
/**
* @runInSeparateProcess
*/
public function testGetClientName()
{
$this->imitateInAppEngine();
$creds = new AppIdentityCredentials;
$expected = 'foobar';
AppIdentityService::$serviceAccountName = $expected;
$this->assertEquals($expected, $creds->getClientName());
AppIdentityService::$serviceAccountName = 'notreturned';
$this->assertEquals($expected, $creds->getClientName());
}
public function testGetLastReceivedTokenNullByDefault()
{
$creds = new AppIdentityCredentials;
$this->assertNull($creds->getLastReceivedToken());
}
/**
* @runInSeparateProcess
*/
public function testGetLastReceviedTokenCaches()
{
$this->imitateInAppEngine();
$creds = new AppIdentityCredentials;
$wantedToken = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'expiration_time' => time() + 57,
'token_type' => 'Bearer',
];
AppIdentityService::$accessToken = $wantedToken;
$creds->fetchAuthToken();
$this->assertEquals([
'access_token' => $wantedToken['access_token'],
'expires_at' => $wantedToken['expiration_time']
], $creds->getLastReceivedToken());
}
private function imitateInAppEngine()
{
// include the mock AppIdentityService class
require_once __DIR__ . '/../mocks/AppIdentityService.php';
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
// $_SERVER['APPENGINE_RUNTIME'] = 'php';
}
}
tests/Credentials/GCECredentialsTest.php 0000644 00000020165 15174273671 0014311 0 ustar 00 assertFalse(GCECredentials::onGCE($httpHandler));
}
public function testOnGCEIsFalseOnServerErrorStatus()
{
// simulate retry attempts by returning multiple 500s
$httpHandler = getHandler([
buildResponse(500),
buildResponse(500),
buildResponse(500)
]);
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}
public function testOnGCEIsFalseOnOkStatusWithoutExpectedHeader()
{
$httpHandler = getHandler([
buildResponse(200),
]);
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}
public function testOnGCEIsOkIfGoogleIsTheFlavor()
{
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
]);
$this->assertTrue(GCECredentials::onGCE($httpHandler));
}
public function testOnAppEngineFlexIsFalseByDefault()
{
$this->assertFalse(GCECredentials::onAppEngineFlexible());
}
public function testOnAppEngineFlexIsTrueWhenGaeInstanceHasAefPrefix()
{
putenv('GAE_INSTANCE=aef-default-20180313t154438');
$this->assertTrue(GCECredentials::onAppEngineFlexible());
putenv('GAE_INSTANCE');
}
public function testGetCacheKeyShouldNotBeEmpty()
{
$g = new GCECredentials();
$this->assertNotEmpty($g->getCacheKey());
}
public function testFetchAuthTokenShouldBeEmptyIfNotOnGCE()
{
// simulate retry attempts by returning multiple 500s
$httpHandler = getHandler([
buildResponse(500),
buildResponse(500),
buildResponse(500)
]);
$g = new GCECredentials();
$this->assertEquals(array(), $g->fetchAuthToken($httpHandler));
}
/**
* @expectedException Exception
* @expectedExceptionMessage Invalid JSON response
*/
public function testFetchAuthTokenShouldFailIfResponseIsNotJson()
{
$notJson = '{"foo": , this is cannot be passed as json" "bar"}';
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], $notJson),
]);
$g = new GCECredentials();
$g->fetchAuthToken($httpHandler);
}
public function testFetchAuthTokenShouldReturnTokenInfo()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$g = new GCECredentials();
$this->assertEquals($wantedTokens, $g->fetchAuthToken($httpHandler));
$this->assertEquals(time() + 57, $g->getLastReceivedToken()['expires_at']);
}
public function testGetLastReceivedTokenIsNullByDefault()
{
$creds = new GCECredentials;
$this->assertNull($creds->getLastReceivedToken());
}
public function testGetClientName()
{
$expected = 'foobar';
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($expected)),
buildResponse(200, [], Psr7\stream_for('notexpected'))
]);
$creds = new GCECredentials;
$this->assertEquals($expected, $creds->getClientName($httpHandler));
// call again to test cached value
$this->assertEquals($expected, $creds->getClientName($httpHandler));
}
public function testGetClientNameShouldBeEmptyIfNotOnGCE()
{
// simulate retry attempts by returning multiple 500s
$httpHandler = getHandler([
buildResponse(500),
buildResponse(500),
buildResponse(500)
]);
$creds = new GCECredentials;
$this->assertEquals('', $creds->getClientName($httpHandler));
}
public function testSignBlob()
{
$guzzleVersion = ClientInterface::VERSION;
if ($guzzleVersion[0] === '5') {
$this->markTestSkipped('Only compatible with guzzle 6+');
}
$expectedEmail = 'test@test.com';
$expectedAccessToken = 'token';
$stringToSign = 'inputString';
$resultString = 'foobar';
$token = [
'access_token' => $expectedAccessToken,
'expires_in' => '57',
'token_type' => 'Bearer',
];
$iam = $this->prophesize('Google\Auth\Iam');
$iam->signBlob($expectedEmail, $expectedAccessToken, $stringToSign)
->shouldBeCalled()
->willReturn($resultString);
$client = $this->prophesize('GuzzleHttp\ClientInterface');
$client->send(Argument::any(), Argument::any())
->willReturn(
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($expectedEmail)),
buildResponse(200, [], Psr7\stream_for(json_encode($token)))
);
HttpClientCache::setHttpClient($client->reveal());
$creds = new GCECredentials($iam->reveal());
$signature = $creds->signBlob($stringToSign);
}
public function testSignBlobWithLastReceivedAccessToken()
{
$guzzleVersion = ClientInterface::VERSION;
if ($guzzleVersion[0] === '5') {
$this->markTestSkipped('Only compatible with guzzle 6+');
}
$expectedEmail = 'test@test.com';
$expectedAccessToken = 'token';
$notExpectedAccessToken = 'othertoken';
$stringToSign = 'inputString';
$resultString = 'foobar';
$token1 = [
'access_token' => $expectedAccessToken,
'expires_in' => '57',
'token_type' => 'Bearer',
];
$token2 = [
'access_token' => $notExpectedAccessToken,
'expires_in' => '57',
'token_type' => 'Bearer',
];
$iam = $this->prophesize('Google\Auth\Iam');
$iam->signBlob($expectedEmail, $expectedAccessToken, $stringToSign)
->shouldBeCalled()
->willReturn($resultString);
$client = $this->prophesize('GuzzleHttp\ClientInterface');
$client->send(Argument::any(), Argument::any())
->willReturn(
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for(json_encode($token1))),
buildResponse(200, [], Psr7\stream_for($expectedEmail)),
buildResponse(200, [], Psr7\stream_for(json_encode($token2)))
);
HttpClientCache::setHttpClient($client->reveal());
$creds = new GCECredentials($iam->reveal());
// cache a token
$creds->fetchAuthToken();
$signature = $creds->signBlob($stringToSign);
}
}
tests/Credentials/IAMCredentialsTest.php 0000644 00000004506 15174273671 0014322 0 ustar 00 assertNotNull(
new IAMCredentials('iam-selector', 'iam-token')
);
}
}
class IAMUpdateMetadataCallbackTest extends TestCase
{
public function testUpdateMetadataFunc()
{
$selector = 'iam-selector';
$token = 'iam-token';
$iam = new IAMCredentials(
$selector,
$token
);
$update_metadata = $iam->getUpdateMetadataFunc();
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'));
$this->assertArrayHasKey(IAMCredentials::SELECTOR_KEY, $actual_metadata);
$this->assertEquals(
$actual_metadata[IAMCredentials::SELECTOR_KEY],
$selector);
$this->assertArrayHasKey(IAMCredentials::TOKEN_KEY, $actual_metadata);
$this->assertEquals(
$actual_metadata[IAMCredentials::TOKEN_KEY],
$token);
}
}
tests/Credentials/InsecureCredentialsTest.php 0000644 00000002512 15174273671 0015464 0 ustar 00 assertEquals(['access_token' => ''], $insecure->fetchAuthToken());
}
public function testGetCacheKey()
{
$insecure = new InsecureCredentials();
$this->assertNull($insecure->getCacheKey());
}
public function testGetLastReceivedToken()
{
$insecure = new InsecureCredentials();
$this->assertEquals(['access_token' => ''], $insecure->getLastReceivedToken());
}
}
tests/Credentials/ServiceAccountCredentialsTest.php 0000644 00000042105 15174273671 0016626 0 ustar 00 'key123',
'private_key' => 'privatekey',
'client_email' => 'test@example.com',
'client_id' => 'client123',
'type' => 'service_account',
];
}
class SACGetCacheKeyTest extends TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountCredentials(
$scope,
$testJson);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_email'] . ':' . $o->getCacheKey(),
$sa->getCacheKey()
);
}
public function testShouldBeTheSameAsOAuth2WithTheSameScopeWithSub()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sub = 'sub123';
$sa = new ServiceAccountCredentials(
$scope,
$testJson,
$sub);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_email'] . ':' . $o->getCacheKey() . ':' . $sub,
$sa->getCacheKey()
);
}
public function testShouldBeTheSameAsOAuth2WithTheSameScopeWithSubAddedLater()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sub = 'sub123';
$sa = new ServiceAccountCredentials(
$scope,
$testJson,
null);
$sa->setSub($sub);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_email'] . ':' . $o->getCacheKey() . ':' . $sub,
$sa->getCacheKey()
);
}
}
class SACConstructorTest extends TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfScopeIsNotAValidType()
{
$testJson = createTestJson();
$notAnArrayOrString = new \stdClass();
$sa = new ServiceAccountCredentials(
$notAnArrayOrString,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveClientEmail()
{
$testJson = createTestJson();
unset($testJson['client_email']);
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHavePrivateKey()
{
$testJson = createTestJson();
unset($testJson['private_key']);
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsToInitalizeFromANonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
new ServiceAccountCredentials('scope/1', $keyFile);
}
public function testInitalizeFromAFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/private.json';
$this->assertNotNull(
new ServiceAccountCredentials('scope/1', $keyFile)
);
}
/**
* @expectedException LogicException
*/
public function testFailsToInitializeFromInvalidJsonData()
{
$tmp = tmpfile();
fwrite($tmp, '{');
$path = stream_get_meta_data($tmp)['uri'];
try {
new ServiceAccountCredentials('scope/1', $path);
} catch (\Exception $e) {
fclose($tmp);
throw $e;
}
}
}
class SACFromEnvTest extends TestCase
{
protected function tearDown()
{
putenv(ServiceAccountCredentials::ENV_VAR); // removes it from
}
public function testIsNullIfEnvVarIsNotSet()
{
$this->assertNull(ServiceAccountCredentials::fromEnv());
}
/**
* @expectedException DomainException
*/
public function testFailsIfEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getCredentials('a scope');
}
public function testSucceedIfFileExists()
{
$keyFile = __DIR__ . '/../fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope'));
}
}
class SACFromWellKnownFileTest extends TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
}
public function testIsNullIfFileDoesNotExist()
{
putenv('HOME=' . __DIR__ . '/../not_exists_fixtures');
$this->assertNull(
ServiceAccountCredentials::fromWellKnownFile()
);
}
public function testSucceedIfFileIsPresent()
{
putenv('HOME=' . __DIR__ . '/../fixtures');
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
}
class SACFetchAuthTokenTest extends TestCase
{
private $privateKey;
public function setUp()
{
$this->privateKey =
file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
}
private function createTestJson()
{
$testJson = createTestJson();
$testJson['private_key'] = $this->privateKey;
return $testJson;
}
/**
* @expectedException GuzzleHttp\Exception\ClientException
*/
public function testFailsOnClientErrors()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(400),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testFailsOnServerErrors()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(500),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
public function testCanFetchCredsOK()
{
$testJson = $this->createTestJson();
$testJsonText = json_encode($testJson);
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($testJsonText)),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$tokens = $sa->fetchAuthToken($httpHandler);
$this->assertEquals($testJson, $tokens);
}
public function testUpdateMetadataFunc()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$access_token = 'accessToken123';
$responseText = json_encode(array('access_token' => $access_token));
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($responseText)),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = null,
$httpHandler);
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
$this->assertEquals(
$actual_metadata[CredentialsLoader::AUTH_METADATA_KEY],
array('Bearer ' . $access_token));
}
}
class SACGetClientNameTest extends TestCase
{
public function testReturnsClientEmail()
{
$testJson = createTestJson();
$sa = new ServiceAccountCredentials('scope/1', $testJson);
$this->assertEquals($testJson['client_email'], $sa->getClientName());
}
}
class SACJwtAccessTest extends TestCase
{
private $privateKey;
public function setUp()
{
$this->privateKey =
file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
}
private function createTestJson()
{
$testJson = createTestJson();
$testJson['private_key'] = $this->privateKey;
return $testJson;
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsToInitalizeFromANonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
new ServiceAccountJwtAccessCredentials($keyFile);
}
public function testInitalizeFromAFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/private.json';
$this->assertNotNull(
new ServiceAccountJwtAccessCredentials($keyFile)
);
}
/**
* @expectedException LogicException
*/
public function testFailsToInitializeFromInvalidJsonData()
{
$tmp = tmpfile();
fwrite($tmp, '{');
$path = stream_get_meta_data($tmp)['uri'];
try {
new ServiceAccountJwtAccessCredentials($path);
} catch (\Exception $e) {
fclose($tmp);
throw $e;
}
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnMissingClientEmail()
{
$testJson = $this->createTestJson();
unset($testJson['client_email']);
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnMissingPrivateKey()
{
$testJson = $this->createTestJson();
unset($testJson['private_key']);
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
}
public function testCanInitializeFromJson()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
}
public function testNoOpOnFetchAuthToken()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
$httpHandler = getHandler([
buildResponse(200),
]);
$result = $sa->fetchAuthToken($httpHandler); // authUri has not been set
$this->assertNull($result);
}
public function testAuthUriIsNotSet()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = null);
$this->assertArrayNotHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
}
public function testUpdateMetadataFunc()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = 'https://example.com/service');
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
$authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertInternalType('array', $authorization);
$bearer_token = current($authorization);
$this->assertInternalType('string', $bearer_token);
$this->assertEquals(0, strpos($bearer_token, 'Bearer '));
$this->assertGreaterThan(30, strlen($bearer_token));
$actual_metadata2 = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = 'https://example.com/anotherService');
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata2
);
$authorization2 = $actual_metadata2[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertInternalType('array', $authorization2);
$bearer_token2 = current($authorization2);
$this->assertInternalType('string', $bearer_token2);
$this->assertEquals(0, strpos($bearer_token2, 'Bearer '));
$this->assertGreaterThan(30, strlen($bearer_token2));
$this->assertNotEquals($bearer_token2, $bearer_token);
}
}
class SACJwtAccessComboTest extends TestCase
{
private $privateKey;
public function setUp()
{
$this->privateKey =
file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
}
private function createTestJson()
{
$testJson = createTestJson();
$testJson['private_key'] = $this->privateKey;
return $testJson;
}
public function testNoScopeUseJwtAccess()
{
$testJson = $this->createTestJson();
// no scope, jwt access should be used, no outbound
// call should be made
$scope = null;
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = 'https://example.com/service');
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
$authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertInternalType('array', $authorization);
$bearer_token = current($authorization);
$this->assertInternalType('string', $bearer_token);
$this->assertEquals(0, strpos($bearer_token, 'Bearer '));
$this->assertGreaterThan(30, strlen($bearer_token));
}
public function testNoScopeAndNoAuthUri()
{
$testJson = $this->createTestJson();
// no scope, jwt access should be used, no outbound
// call should be made
$scope = null;
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = null);
// no access_token is added to the metadata hash
// but also, no error should be thrown
$this->assertInternalType('array', $actual_metadata);
$this->assertArrayNotHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
}
}
class SACJWTGetCacheKeyTest extends TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountJwtAccessCredentials($testJson);
$this->assertNull($sa->getCacheKey());
}
}
class SACJWTGetClientNameTest extends TestCase
{
public function testReturnsClientEmail()
{
$testJson = createTestJson();
$sa = new ServiceAccountJwtAccessCredentials($testJson);
$this->assertEquals($testJson['client_email'], $sa->getClientName());
}
}
tests/Credentials/UserRefreshCredentialsTest.php 0000644 00000016724 15174273671 0016156 0 ustar 00 'client123',
'client_secret' => 'clientSecret123',
'refresh_token' => 'refreshToken123',
'type' => 'authorized_user',
];
}
class URCGetCacheKeyTest extends TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
$testJson = createURCTestJson();
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_id'] . ':' . $o->getCacheKey(),
$sa->getCacheKey()
);
}
}
class URCConstructorTest extends TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfScopeIsNotAValidType()
{
$testJson = createURCTestJson();
$notAnArrayOrString = new \stdClass();
$sa = new UserRefreshCredentials(
$notAnArrayOrString,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveClientSecret()
{
$testJson = createURCTestJson();
unset($testJson['client_secret']);
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveRefreshToken()
{
$testJson = createURCTestJson();
unset($testJson['refresh_token']);
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveClientId()
{
$testJson = createURCTestJson();
unset($testJson['client_id']);
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsToInitalizeFromANonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures/does-not-exist-private.json';
new UserRefreshCredentials('scope/1', $keyFile);
}
public function testInitalizeFromAFile()
{
$keyFile = __DIR__ . '/../fixtures2' . '/private.json';
$this->assertNotNull(
new UserRefreshCredentials('scope/1', $keyFile)
);
}
/**
* @expectedException LogicException
*/
public function testFailsToInitializeFromInvalidJsonData()
{
$tmp = tmpfile();
fwrite($tmp, '{');
$path = stream_get_meta_data($tmp)['uri'];
try {
new UserRefreshCredentials('scope/1', $path);
} catch (\Exception $e) {
fclose($tmp);
throw $e;
}
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testGcloudWarning()
{
putenv('SUPPRESS_GCLOUD_CREDS_WARNING=false');
$keyFile = __DIR__ . '/../fixtures2/gcloud.json';
$this->assertNotNull(
new UserRefreshCredentials('scope/1', $keyFile)
);
}
public function testValid3LOauthCreds()
{
putenv('SUPPRESS_GCLOUD_CREDS_WARNING=false');
$keyFile = __DIR__ . '/../fixtures2/valid_oauth_creds.json';
$this->assertNotNull(
new UserRefreshCredentials('scope/1', $keyFile)
);
}
}
class URCFromEnvTest extends TestCase
{
protected function tearDown()
{
putenv(UserRefreshCredentials::ENV_VAR); // removes it from
}
public function testIsNullIfEnvVarIsNotSet()
{
$this->assertNull(UserRefreshCredentials::fromEnv('a scope'));
}
/**
* @expectedException DomainException
*/
public function testFailsIfEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures/does-not-exist-private.json';
putenv(UserRefreshCredentials::ENV_VAR . '=' . $keyFile);
UserRefreshCredentials::fromEnv('a scope');
}
public function testSucceedIfFileExists()
{
$keyFile = __DIR__ . '/../fixtures2/private.json';
putenv(UserRefreshCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope'));
}
}
class URCFromWellKnownFileTest extends TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
}
public function testIsNullIfFileDoesNotExist()
{
putenv('HOME=' . __DIR__ . '/../not_exist_fixtures');
$this->assertNull(
UserRefreshCredentials::fromWellKnownFile('a scope')
);
}
public function testSucceedIfFileIsPresent()
{
putenv('HOME=' . __DIR__ . '/../fixtures2');
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
}
class URCFetchAuthTokenTest extends TestCase
{
/**
* @expectedException GuzzleHttp\Exception\ClientException
*/
public function testFailsOnClientErrors()
{
$testJson = createURCTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(400),
]);
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testFailsOnServerErrors()
{
$testJson = createURCTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(500),
]);
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
public function testCanFetchCredsOK()
{
$testJson = createURCTestJson();
$testJsonText = json_encode($testJson);
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($testJsonText)),
]);
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
$tokens = $sa->fetchAuthToken($httpHandler);
$this->assertEquals($testJson, $tokens);
}
}
tests/FetchAuthTokenCacheTest.php 0000644 00000016253 15174273671 0013103 0 ustar 00 mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
null,
$this->mockCache
);
$accessToken = $cachedFetcher->fetchAuthToken();
$this->assertEquals($accessToken, ['access_token' => $cachedValue]);
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$accessToken = $cachedFetcher->fetchAuthToken();
$this->assertEquals($accessToken, ['access_token' => $cachedValue]);
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$prefix = 'test_prefix_';
$lifetime = '70707';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$accessToken = $cachedFetcher->fetchAuthToken();
$this->assertEquals($accessToken, ['access_token' => $token]);
}
public function testGetLastReceivedToken()
{
$token = 'foo';
$mockFetcher = $this->prophesize('Google\Auth\FetchAuthTokenInterface');
$mockFetcher->getLastReceivedToken()
->shouldBeCalled()
->willReturn([
'access_token' => $token
]);
$fetcher = new FetchAuthTokenCache(
$mockFetcher->reveal(),
[],
$this->mockCache
);
$this->assertEquals($token, $fetcher->getLastReceivedToken()['access_token']);
}
public function testGetClientName()
{
$name = 'test@example.com';
$mockFetcher = $this->prophesize('Google\Auth\SignBlobInterface');
$mockFetcher->getClientName(null)
->shouldBeCalled()
->willReturn($name);
$fetcher = new FetchAuthTokenCache(
$mockFetcher->reveal(),
[],
$this->mockCache
);
$this->assertEquals($name, $fetcher->getClientName());
}
public function testSignBlob()
{
$stringToSign = 'foobar';
$signature = 'helloworld';
$mockFetcher = $this->prophesize('Google\Auth\SignBlobInterface');
$mockFetcher->willImplement('Google\Auth\FetchAuthTokenInterface');
$mockFetcher->signBlob($stringToSign, true)
->shouldBeCalled()
->willReturn($signature);
$fetcher = new FetchAuthTokenCache(
$mockFetcher->reveal(),
[],
$this->mockCache
);
$this->assertEquals($signature, $fetcher->signBlob($stringToSign, true));
}
/**
* @expectedException RuntimeException
*/
public function testSignBlobInvalidFetcher()
{
$mockFetcher = $this->prophesize('Google\Auth\FetchAuthTokenInterface');
$mockFetcher->signBlob('test')
->shouldNotbeCalled();
$fetcher = new FetchAuthTokenCache(
$mockFetcher->reveal(),
[],
$this->mockCache
);
$this->assertEquals($signature, $fetcher->signBlob('test'));
}
}
tests/FetchAuthTokenTest.php 0000644 00000016143 15174273671 0012155 0 ustar 00 getMockBuilder($fetcherClass)
->disableOriginalConstructor()
->getMock();
$mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnCallback(function ($httpHandler) {
return $httpHandler();
}));
$httpHandlerCalled = false;
$httpHandler = function () use (&$httpHandlerCalled) {
$httpHandlerCalled = true;
return ['access_token' => 'xyz'];
};
$tokenCallbackCalled = false;
$tokenCallback = function ($cacheKey, $accessToken) use (&$tokenCallbackCalled) {
$tokenCallbackCalled = true;
$this->assertEquals('xyz', $accessToken);
};
$client = CredentialsLoader::makeHttpClient(
$mockFetcher,
[
'base_url' => 'https://www.googleapis.com/books/v1/',
'base_uri' => 'https://www.googleapis.com/books/v1/',
'exceptions' => false,
'defaults' => ['exceptions' => false]
],
$httpHandler,
$tokenCallback
);
$response = $client->get(
'volumes?q=Henry+David+Thoreau&country=US'
);
$this->assertEquals(401, $response->getStatusCode());
$this->assertTrue($httpHandlerCalled);
$this->assertTrue($tokenCallbackCalled);
}
public function provideMakeHttpClient()
{
return [
['Google\Auth\Credentials\AppIdentityCredentials'],
['Google\Auth\Credentials\GCECredentials'],
['Google\Auth\Credentials\ServiceAccountCredentials'],
['Google\Auth\Credentials\ServiceAccountJwtAccessCredentials'],
['Google\Auth\Credentials\UserRefreshCredentials'],
['Google\Auth\OAuth2'],
];
}
public function testAppIdentityCredentialsGetLastReceivedToken()
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\AppIdentityCredentials'
);
$property = $class->getProperty('lastReceivedToken');
$property->setAccessible(true);
$credentials = new AppIdentityCredentials();
$property->setValue($credentials, [
'access_token' => 'xyz',
'expiration_time' => strtotime('2001'),
]);
$this->assertGetLastReceivedToken($credentials);
}
public function testGCECredentialsGetLastReceivedToken()
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\GCECredentials'
);
$property = $class->getProperty('lastReceivedToken');
$property->setAccessible(true);
$credentials = new GCECredentials();
$property->setValue($credentials, [
'access_token' => 'xyz',
'expires_at' => strtotime('2001'),
]);
$this->assertGetLastReceivedToken($credentials);
}
public function testServiceAccountCredentialsGetLastReceivedToken()
{
$jsonPath = sprintf(
'%s/fixtures/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$class = new \ReflectionClass(
'Google\Auth\Credentials\ServiceAccountCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new ServiceAccountCredentials($this->scopes, $jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
$this->assertGetLastReceivedToken($credentials);
}
public function testServiceAccountJwtAccessCredentialsGetLastReceivedToken()
{
$jsonPath = sprintf(
'%s/fixtures/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$class = new \ReflectionClass(
'Google\Auth\Credentials\ServiceAccountJwtAccessCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new ServiceAccountJwtAccessCredentials($jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
$this->assertGetLastReceivedToken($credentials);
}
public function testUserRefreshCredentialsGetLastReceivedToken()
{
$jsonPath = sprintf(
'%s/fixtures2/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$class = new \ReflectionClass(
'Google\Auth\Credentials\UserRefreshCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new UserRefreshCredentials($this->scopes, $jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
$this->assertGetLastReceivedToken($credentials);
}
private function getOAuth2()
{
$oauth = new OAuth2([
'access_token' => 'xyz',
'expires_at' => strtotime('2001'),
]);
$this->assertGetLastReceivedToken($oauth);
}
private function getOAuth2Mock()
{
$mock = $this->getMockBuilder('Google\Auth\OAuth2')
->disableOriginalConstructor()
->getMock();
$mock
->expects($this->once())
->method('getLastReceivedToken')
->will($this->returnValue([
'access_token' => 'xyz',
'expires_at' => strtotime('2001'),
]));
return $mock;
}
private function assertGetLastReceivedToken(FetchAuthTokenInterface $fetcher)
{
$accessToken = $fetcher->getLastReceivedToken();
$this->assertNotNull($accessToken);
$this->assertArrayHasKey('access_token', $accessToken);
$this->assertArrayHasKey('expires_at', $accessToken);
$this->assertEquals('xyz', $accessToken['access_token']);
$this->assertEquals(strtotime('2001'), $accessToken['expires_at']);
}
}
tests/HttpHandler/Guzzle5HttpHandlerTest.php 0000644 00000017311 15174273671 0015217 0 ustar 00 onlyGuzzle5();
$this->mockPsr7Request =
$this
->getMockBuilder('Psr\Http\Message\RequestInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Message\RequestInterface')
->getMock();
$this->mockClient =
$this
->getMockBuilder('GuzzleHttp\Client')
->disableOriginalConstructor()
->getMock();
$this->mockFuture =
$this
->getMockBuilder('GuzzleHttp\Ring\Future\FutureInterface')
->disableOriginalConstructor()
->getMock();
}
public function testSuccessfullySendsRealRequest()
{
$request = new \GuzzleHttp\Psr7\Request('get', 'https://httpbin.org/get');
$client = new \GuzzleHttp\Client();
$handler = new Guzzle5HttpHandler($client);
$response = $handler($request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
$this->assertEquals(200, $response->getStatusCode());
$json = json_decode((string) $response->getBody(), true);
$this->assertArrayHasKey('url', $json);
$this->assertEquals((string) $request->getUri(), $json['url']);
}
public function testSuccessfullySendsMockRequest()
{
$response = new Response(
200,
[],
Stream::factory('Body Text')
);
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue($response));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$response = $handler($this->mockPsr7Request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Body Text', (string) $response->getBody());
}
public function testAsyncWithoutGuzzlePromiseThrowsException()
{
// Pretend the promise library doesn't exist
foreach (spl_autoload_functions() as $function) {
if ($function[0] instanceof ClassLoader) {
$newAutoloader = clone $function[0];
$newAutoloader->setPsr4('GuzzleHttp\\Promise\\', '/tmp');
spl_autoload_register($newAutoloadFunc = [$newAutoloader, 'loadClass']);
spl_autoload_unregister($previousAutoloadFunc = $function);
}
}
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new FutureResponse($this->mockFuture)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$errorThrown = false;
try {
$handler->async($this->mockPsr7Request);
} catch (Exception $e) {
$this->assertEquals(
'Install guzzlehttp/promises to use async with Guzzle 5',
$e->getMessage()
);
$errorThrown = true;
}
// Restore autoloader before assertion (in case it fails)
spl_autoload_register($previousAutoloadFunc);
spl_autoload_unregister($newAutoloadFunc);
$this->assertTrue($errorThrown);
}
public function testSuccessfullySendsRequestAsync()
{
$response = new Response(
200,
[],
Stream::factory('Body Text')
);
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new FutureResponse(
new CompletedFutureValue($response)
)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$promise = $handler->async($this->mockPsr7Request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $promise->wait());
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Body Text', (string) $response->getBody());
}
/**
* @expectedException Exception
* @expectedExceptionMessage This is a test rejection message
*/
public function testPromiseHandlesException()
{
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new FutureResponse(
(new CompletedFutureValue(new Response(200)))
->then(function () {
throw new Exception('This is a test rejection message');
})
)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$promise = $handler->async($this->mockPsr7Request);
$promise->wait();
}
public function testCreateGuzzle5Request()
{
$requestHeaders = [
'header1' => 'value1',
'header2' => 'value2',
];
$this->mockPsr7Request
->expects($this->once())
->method('getHeaders')
->will($this->returnValue($requestHeaders));
$mockBody = $this->getMock('Psr\Http\Message\StreamInterface');
$this->mockPsr7Request
->expects($this->once())
->method('getBody')
->will($this->returnValue($mockBody));
$this->mockClient
->expects($this->once())
->method('createRequest')
->with(null, null, [
'headers' => $requestHeaders + ['header3' => 'value3'],
'body' => $mockBody,
])
->will($this->returnValue(
$this->getMock('GuzzleHttp\Message\RequestInterface')
));
$responseMock = $this->getMockBuilder('GuzzleHttp\Message\ResponseInterface')
->getMock();
$responseMock
->method('getStatusCode')
->will($this->returnValue(200));
$this->mockClient
->expects($this->once())
->method('send')
->will($this->returnValue($responseMock));
$handler = new Guzzle5HttpHandler($this->mockClient);
$handler($this->mockPsr7Request, [
'headers' => [
'header3' => 'value3'
]
]);
}
}
tests/HttpHandler/Guzzle6HttpHandlerTest.php 0000644 00000004327 15174273671 0015223 0 ustar 00 onlyGuzzle6();
$this->mockRequest =
$this
->getMockBuilder('Psr\Http\Message\RequestInterface')
->getMock();
$this->mockClient =
$this
->getMockBuilder('GuzzleHttp\Client')
->getMock();
}
public function testSuccessfullySendsRequest()
{
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new Response(200)));
$handler = new Guzzle6HttpHandler($this->mockClient);
$response = $handler($this->mockRequest);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
}
public function testSuccessfullySendsRequestAsync()
{
$this->mockClient
->expects($this->any())
->method('sendAsync')
->will($this->returnValue(new Promise(function () use (&$promise) {
return $promise->resolve(new Response(200, [], 'Body Text'));
})));
$handler = new Guzzle6HttpHandler($this->mockClient);
$promise = $handler->async($this->mockRequest);
$response = $promise->wait();
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Body Text', (string) $response->getBody());
}
}
tests/HttpHandler/HttpHandlerFactoryTest.php 0000644 00000002453 15174273671 0015262 0 ustar 00 onlyGuzzle5();
HttpClientCache::setHttpClient(null);
$handler = HttpHandlerFactory::build();
$this->assertInstanceOf('Google\Auth\HttpHandler\Guzzle5HttpHandler', $handler);
}
public function testBuildsGuzzle6Handler()
{
$this->onlyGuzzle6();
HttpClientCache::setHttpClient(null);
$handler = HttpHandlerFactory::build();
$this->assertInstanceOf('Google\Auth\HttpHandler\Guzzle6HttpHandler', $handler);
}
}
tests/IamTest.php 0000644 00000005545 15174273671 0010013 0 ustar 00 assertEquals($expectedUri, (string) $request->getUri());
$this->assertEquals('Bearer ' . $expectedAccessToken, $request->getHeaderLine('Authorization'));
$this->assertEquals([
'delegates' => $expectedDelegates,
'payload' => base64_encode($expectedString)
], json_decode((string) $request->getBody(), true));
return new Psr7\Response(200, [], Psr7\stream_for(json_encode([
'signedBlob' => $expectedResponse
])));
};
$iam = new Iam($httpHandler);
$res = $iam->signBlob(
$expectedEmail,
$expectedAccessToken,
$expectedString,
$delegates
);
$this->assertEquals($expectedResponse, $res);
}
public function delegates()
{
return [
[],
[['foo@bar.com']],
[
[
'foo@bar.com',
'bar@bar.com'
]
],
];
}
}
tests/Middleware/AuthTokenMiddlewareTest.php 0000644 00000027164 15174273671 0015263 0 ustar 00 onlyGuzzle6();
$this->mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$this->mockFetcher
->expects($this->any())
->method('fetchAuthToken')
->will($this->returnValue([]));
$this->mockRequest
->expects($this->never())
->method('withHeader');
$middleware = new AuthTokenMiddleware($this->mockFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'not_google_auth']);
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$authResult = ['access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $authResult['access_token'])
->will($this->returnValue($this->mockRequest));
// Run the test.
$middleware = new AuthTokenMiddleware($this->mockFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testDoesNotAddAnAuthorizationHeaderOnNoAccessToken()
{
$authResult = ['not_access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ')
->will($this->returnValue($this->mockRequest));
// Run the test.
$middleware = new AuthTokenMiddleware($this->mockFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
null,
$this->mockCache
);
$middleware = new AuthTokenMiddleware($cachedFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testGetsCachedAuthTokenUsingCacheOptions()
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$middleware = new AuthTokenMiddleware($cachedFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testShouldSaveValueInCacheWithSpecifiedPrefix()
{
$prefix = 'test_prefix_';
$lifetime = '70707';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->any())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$middleware = new AuthTokenMiddleware($cachedFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
/** @dataProvider provideShouldNotifyTokenCallback */
public function testShouldNotifyTokenCallback(callable $tokenCallback)
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCache
->expects($this->any())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->will($this->returnValue($this->mockRequest));
MiddlewareCallback::$expectedKey = $this->getValidKeyName($prefix . $cacheKey);
MiddlewareCallback::$expectedValue = $token;
MiddlewareCallback::$called = false;
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$middleware = new AuthTokenMiddleware(
$cachedFetcher,
null,
$tokenCallback
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
$this->assertTrue(MiddlewareCallback::$called);
}
public function provideShouldNotifyTokenCallback()
{
MiddlewareCallback::$phpunit = $this;
$anonymousFunc = function ($key, $value) {
MiddlewareCallback::staticInvoke($key, $value);
};
return [
['Google\Auth\Tests\MiddlewareCallbackFunction'],
['Google\Auth\Tests\MiddlewareCallback::staticInvoke'],
[['Google\Auth\Tests\MiddlewareCallback', 'staticInvoke']],
[$anonymousFunc],
[[new MiddlewareCallback, 'staticInvoke']],
[[new MiddlewareCallback, 'methodInvoke']],
[new MiddlewareCallback],
];
}
}
class MiddlewareCallback
{
public static $phpunit;
public static $expectedKey;
public static $expectedValue;
public static $called = false;
public function __invoke($key, $value)
{
self::$phpunit->assertEquals(self::$expectedKey, $key);
self::$phpunit->assertEquals(self::$expectedValue, $value);
self::$called = true;
}
public function methodInvoke($key, $value)
{
return $this($key, $value);
}
public static function staticInvoke($key, $value)
{
$instance = new self();
return $instance($key, $value);
}
}
function MiddlewareCallbackFunction($key, $value)
{
return MiddlewareCallback::staticInvoke($key, $value);
}
tests/Middleware/ScopedAccessTokenMiddlewareTest.php 0000644 00000020724 15174273671 0016714 0 ustar 00 onlyGuzzle6();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresScopeAsAStringOrArray()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
new ScopedAccessTokenMiddleware($fakeAuthFunc, new \stdClass());
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$token = '1/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) use ($token) {
return $token;
};
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware($fakeAuthFunc, self::TEST_SCOPE);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testUsesCachedAuthToken()
{
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
[],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
['prefix' => $prefix],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testShouldSaveValueInCache()
{
$token = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) use ($token) {
return $token;
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
[],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$token = '2/abcdef1234567890';
$prefix = 'test_prefix_';
$lifetime = '70707';
$fakeAuthFunc = function ($unused_scopes) use ($token) {
return $token;
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($prefix . $this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$this->mockRequest
->expects($this->never())
->method('withHeader');
// Run the test
$middleware = new ScopedAccessTokenMiddleware($fakeAuthFunc, self::TEST_SCOPE);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'not_scoped']);
}
}
tests/Middleware/SimpleMiddlewareTest.php 0000644 00000002024 15174273671 0014576 0 ustar 00 onlyGuzzle6();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
public function testTest()
{
}
}
tests/OAuth2Test.php 0000644 00000070755 15174273671 0010414 0 ustar 00 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
/**
* @expectedException InvalidArgumentException
*/
public function testIsNullIfAuthorizationUriIsNull()
{
$o = new OAuth2([]);
$this->assertNull($o->buildFullAuthorizationUri());
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresTheClientId()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/auth/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
]);
$o->buildFullAuthorizationUri();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresTheRedirectUri()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/auth/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri();
}
/**
* @expectedException InvalidArgumentException
*/
public function testCannotHavePromptAndApprovalPrompt()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/auth/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri([
'approval_prompt' => 'an approval prompt',
'prompt' => 'a prompt',
]);
}
/**
* @expectedException InvalidArgumentException
*/
public function testCannotHaveInsecureAuthorizationUri()
{
$o = new OAuth2([
'authorizationUri' => 'http://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri();
}
/**
* @expectedException InvalidArgumentException
*/
public function testCannotHaveRelativeRedirectUri()
{
$o = new OAuth2([
'authorizationUri' => 'http://accounts.test.org/insecure/url',
'redirectUri' => '/redirect/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri();
}
public function testHasDefaultXXXTypeParams()
{
$o = new OAuth2($this->minimal);
$q = Psr7\parse_query($o->buildFullAuthorizationUri()->getQuery());
$this->assertEquals('code', $q['response_type']);
$this->assertEquals('offline', $q['access_type']);
}
public function testCanBeUrlObject()
{
$config = array_merge($this->minimal, [
'authorizationUri' => Psr7\uri_for('https://another/uri'),
]);
$o = new OAuth2($config);
$this->assertEquals('/uri', $o->buildFullAuthorizationUri()->getPath());
}
public function testCanOverrideParams()
{
$overrides = [
'access_type' => 'o_access_type',
'client_id' => 'o_client_id',
'redirect_uri' => 'o_redirect_uri',
'response_type' => 'o_response_type',
'state' => 'o_state',
];
$config = array_merge($this->minimal, ['state' => 'the_state']);
$o = new OAuth2($config);
$q = Psr7\parse_query($o->buildFullAuthorizationUri($overrides)->getQuery());
$this->assertEquals('o_access_type', $q['access_type']);
$this->assertEquals('o_client_id', $q['client_id']);
$this->assertEquals('o_redirect_uri', $q['redirect_uri']);
$this->assertEquals('o_response_type', $q['response_type']);
$this->assertEquals('o_state', $q['state']);
}
public function testIncludesTheScope()
{
$with_strings = array_merge($this->minimal, ['scope' => 'scope1 scope2']);
$o = new OAuth2($with_strings);
$q = Psr7\parse_query($o->buildFullAuthorizationUri()->getQuery());
$this->assertEquals('scope1 scope2', $q['scope']);
$with_array = array_merge($this->minimal, [
'scope' => ['scope1', 'scope2'],
]);
$o = new OAuth2($with_array);
$q = Psr7\parse_query($o->buildFullAuthorizationUri()->getQuery());
$this->assertEquals('scope1 scope2', $q['scope']);
}
public function testRedirectUriPostmessageIsAllowed()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'postmessage',
'clientId' => 'aClientID',
]);
$this->assertEquals('postmessage', $o->getRedirectUri());
$url = $o->buildFullAuthorizationUri();
$parts = parse_url((string)$url);
parse_str($parts['query'], $query);
$this->assertArrayHasKey('redirect_uri', $query);
$this->assertEquals('postmessage', $query['redirect_uri']);
}
}
class OAuth2GrantTypeTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
public function testReturnsNullIfCannotBeInferred()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getGrantType());
}
public function testInfersAuthorizationCode()
{
$o = new OAuth2($this->minimal);
$o->setCode('an auth code');
$this->assertEquals('authorization_code', $o->getGrantType());
}
public function testInfersRefreshToken()
{
$o = new OAuth2($this->minimal);
$o->setRefreshToken('a refresh token');
$this->assertEquals('refresh_token', $o->getGrantType());
}
public function testInfersPassword()
{
$o = new OAuth2($this->minimal);
$o->setPassword('a password');
$o->setUsername('a username');
$this->assertEquals('password', $o->getGrantType());
}
public function testInfersJwtBearer()
{
$o = new OAuth2($this->minimal);
$o->setIssuer('an issuer');
$o->setSigningKey('a key');
$this->assertEquals('urn:ietf:params:oauth:grant-type:jwt-bearer',
$o->getGrantType());
}
public function testSetsKnownTypes()
{
$o = new OAuth2($this->minimal);
foreach (OAuth2::$knownGrantTypes as $t) {
$o->setGrantType($t);
$this->assertEquals($t, $o->getGrantType());
}
}
public function testSetsUrlAsGrantType()
{
$o = new OAuth2($this->minimal);
$o->setGrantType('http://a/grant/url');
$this->assertEquals('http://a/grant/url', $o->getGrantType());
}
}
class OAuth2GetCacheKeyTest extends TestCase
{
private $minimal = [
'clientID' => 'aClientID',
];
public function testIsNullWithNoScopes()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getCacheKey());
}
public function testIsScopeIfSingleScope()
{
$o = new OAuth2($this->minimal);
$o->setScope('test/scope/1');
$this->assertEquals('test/scope/1', $o->getCacheKey());
}
public function testIsAllScopesWhenScopeIsArray()
{
$o = new OAuth2($this->minimal);
$o->setScope(['test/scope/1', 'test/scope/2']);
$this->assertEquals('test/scope/1:test/scope/2', $o->getCacheKey());
}
}
class OAuth2TimingTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
public function testIssuedAtDefaultsToNull()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getIssuedAt());
}
public function testExpiresAtDefaultsToNull()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getExpiresAt());
}
public function testExpiresInDefaultsToNull()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getExpiresIn());
}
public function testSettingExpiresInSetsIssuedAt()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getIssuedAt());
$aShortWhile = 5;
$o->setExpiresIn($aShortWhile);
$this->assertEquals($aShortWhile, $o->getExpiresIn());
$this->assertNotNull($o->getIssuedAt());
}
public function testSettingExpiresInSetsExpireAt()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getExpiresAt());
$aShortWhile = 5;
$o->setExpiresIn($aShortWhile);
$this->assertNotNull($o->getExpiresAt());
$this->assertEquals($aShortWhile, $o->getExpiresAt() - $o->getIssuedAt());
}
public function testIsNotExpiredByDefault()
{
$o = new OAuth2($this->minimal);
$this->assertFalse($o->isExpired());
}
public function testIsNotExpiredIfExpiresAtIsOld()
{
$o = new OAuth2($this->minimal);
$o->setExpiresAt(time() - 2);
$this->assertTrue($o->isExpired());
}
}
class OAuth2GeneralTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnUnknownSigningAlgorithm()
{
$o = new OAuth2($this->minimal);
$o->setSigningAlgorithm('this is definitely not an algorithm name');
}
public function testAllowsKnownSigningAlgorithms()
{
$o = new OAuth2($this->minimal);
foreach (OAuth2::$knownSigningAlgorithms as $a) {
$o->setSigningAlgorithm($a);
$this->assertEquals($a, $o->getSigningAlgorithm());
}
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnRelativeRedirectUri()
{
$o = new OAuth2($this->minimal);
$o->setRedirectUri('/relative/url');
}
public function testAllowsUrnRedirectUri()
{
$urn = 'urn:ietf:wg:oauth:2.0:oob';
$o = new OAuth2($this->minimal);
$o->setRedirectUri($urn);
$this->assertEquals($urn, $o->getRedirectUri());
}
}
class OAuth2JwtTest extends TestCase
{
private $signingMinimal = [
'signingKey' => 'example_key',
'signingAlgorithm' => 'HS256',
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'issuer' => 'app@example.com',
'audience' => 'accounts.google.com',
'clientId' => 'aClientID',
];
/**
* @expectedException DomainException
*/
public function testFailsWithMissingAudience()
{
$testConfig = $this->signingMinimal;
unset($testConfig['audience']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
* @expectedException DomainException
*/
public function testFailsWithMissingIssuer()
{
$testConfig = $this->signingMinimal;
unset($testConfig['issuer']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
*/
public function testCanHaveNoScope()
{
$testConfig = $this->signingMinimal;
unset($testConfig['scope']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
* @expectedException DomainException
*/
public function testFailsWithMissingSigningKey()
{
$testConfig = $this->signingMinimal;
unset($testConfig['signingKey']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
* @expectedException DomainException
*/
public function testFailsWithMissingSigningAlgorithm()
{
$testConfig = $this->signingMinimal;
unset($testConfig['signingAlgorithm']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
public function testCanHS256EncodeAValidPayload()
{
$testConfig = $this->signingMinimal;
$o = new OAuth2($testConfig);
$payload = $o->toJwt();
$roundTrip = $this->jwtDecode($payload, $testConfig['signingKey'], array('HS256'));
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
}
public function testCanRS256EncodeAValidPayload()
{
$publicKey = file_get_contents(__DIR__ . '/fixtures' . '/public.pem');
$privateKey = file_get_contents(__DIR__ . '/fixtures' . '/private.pem');
$testConfig = $this->signingMinimal;
$o = new OAuth2($testConfig);
$o->setSigningAlgorithm('RS256');
$o->setSigningKey($privateKey);
$payload = $o->toJwt();
$roundTrip = $this->jwtDecode($payload, $publicKey, array('RS256'));
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
}
public function testCanHaveAdditionalClaims()
{
$publicKey = file_get_contents(__DIR__ . '/fixtures' . '/public.pem');
$privateKey = file_get_contents(__DIR__ . '/fixtures' . '/private.pem');
$testConfig = $this->signingMinimal;
$targetAud = '123@456.com';
$testConfig['additionalClaims'] = ['target_audience' => $targetAud];
$o = new OAuth2($testConfig);
$o->setSigningAlgorithm('RS256');
$o->setSigningKey($privateKey);
$payload = $o->toJwt();
$roundTrip = $this->jwtDecode($payload, $publicKey, array('RS256'));
$this->assertEquals($roundTrip->target_audience, $targetAud);
}
private function jwtDecode()
{
$args = func_get_args();
$class = 'JWT';
if (class_exists('Firebase\JWT\JWT')) {
$class = 'Firebase\JWT\JWT';
}
return call_user_func_array("$class::decode", $args);
}
}
class OAuth2GenerateAccessTokenRequestTest extends TestCase
{
private $tokenRequestMinimal = [
'tokenCredentialUri' => 'https://tokens_r_us/test',
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'issuer' => 'app@example.com',
'audience' => 'accounts.google.com',
'clientId' => 'aClientID',
];
/**
* @expectedException DomainException
*/
public function testFailsIfNoTokenCredentialUri()
{
$testConfig = $this->tokenRequestMinimal;
unset($testConfig['tokenCredentialUri']);
$o = new OAuth2($testConfig);
$o->generateCredentialsRequest();
}
/**
* @expectedException DomainException
*/
public function testFailsIfAuthorizationCodeIsMissing()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['redirectUri'] = 'https://has/redirect/uri';
$o = new OAuth2($testConfig);
$o->generateCredentialsRequest();
}
public function testGeneratesAuthorizationCodeRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['redirectUri'] = 'https://has/redirect/uri';
$o = new OAuth2($testConfig);
$o->setCode('an_auth_code');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('authorization_code', $fields['grant_type']);
$this->assertEquals('an_auth_code', $fields['code']);
}
public function testGeneratesPasswordRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setUsername('a_username');
$o->setPassword('a_password');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('password', $fields['grant_type']);
$this->assertEquals('a_password', $fields['password']);
$this->assertEquals('a_username', $fields['username']);
}
public function testGeneratesRefreshTokenRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setRefreshToken('a_refresh_token');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('refresh_token', $fields['grant_type']);
$this->assertEquals('a_refresh_token', $fields['refresh_token']);
}
public function testClientSecretAddedIfSetForAuthorizationCodeRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['clientSecret'] = 'a_client_secret';
$testConfig['redirectUri'] = 'https://has/redirect/uri';
$o = new OAuth2($testConfig);
$o->setCode('an_auth_code');
$request = $o->generateCredentialsRequest();
$fields = Psr7\parse_query((string)$request->getBody());
$this->assertEquals('a_client_secret', $fields['client_secret']);
}
public function testClientSecretAddedIfSetForRefreshTokenRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['clientSecret'] = 'a_client_secret';
$o = new OAuth2($testConfig);
$o->setRefreshToken('a_refresh_token');
$request = $o->generateCredentialsRequest();
$fields = Psr7\parse_query((string)$request->getBody());
$this->assertEquals('a_client_secret', $fields['client_secret']);
}
public function testClientSecretAddedIfSetForPasswordRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['clientSecret'] = 'a_client_secret';
$o = new OAuth2($testConfig);
$o->setUsername('a_username');
$o->setPassword('a_password');
$request = $o->generateCredentialsRequest();
$fields = Psr7\parse_query((string)$request->getBody());
$this->assertEquals('a_client_secret', $fields['client_secret']);
}
public function testGeneratesAssertionRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setSigningKey('a_key');
$o->setSigningAlgorithm('HS256');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals(OAuth2::JWT_URN, $fields['grant_type']);
$this->assertArrayHasKey('assertion', $fields);
}
public function testGeneratesExtendedRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setGrantType('urn:my_test_grant_type');
$o->setExtensionParams(['my_param' => 'my_value']);
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('my_value', $fields['my_param']);
$this->assertEquals('urn:my_test_grant_type', $fields['grant_type']);
}
}
class OAuth2FetchAuthTokenTest extends TestCase
{
private $fetchAuthTokenMinimal = [
'tokenCredentialUri' => 'https://tokens_r_us/test',
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'signingKey' => 'example_key',
'signingAlgorithm' => 'HS256',
'issuer' => 'app@example.com',
'audience' => 'accounts.google.com',
'clientId' => 'aClientID',
];
/**
* @expectedException GuzzleHttp\Exception\ClientException
*/
public function testFailsOn400()
{
$testConfig = $this->fetchAuthTokenMinimal;
$httpHandler = getHandler([
buildResponse(400),
]);
$o = new OAuth2($testConfig);
$o->fetchAuthToken($httpHandler);
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testFailsOn500()
{
$testConfig = $this->fetchAuthTokenMinimal;
$httpHandler = getHandler([
buildResponse(500),
]);
$o = new OAuth2($testConfig);
$o->fetchAuthToken($httpHandler);
}
/**
* @expectedException Exception
* @expectedExceptionMessage Invalid JSON response
*/
public function testFailsOnNoContentTypeIfResponseIsNotJSON()
{
$testConfig = $this->fetchAuthTokenMinimal;
$notJson = '{"foo": , this is cannot be passed as json" "bar"}';
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($notJson)),
]);
$o = new OAuth2($testConfig);
$o->fetchAuthToken($httpHandler);
}
public function testFetchesJsonResponseOnNoContentTypeOK()
{
$testConfig = $this->fetchAuthTokenMinimal;
$json = '{"foo": "bar"}';
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($json)),
]);
$o = new OAuth2($testConfig);
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals($tokens['foo'], 'bar');
}
public function testFetchesFromFormEncodedResponseOK()
{
$testConfig = $this->fetchAuthTokenMinimal;
$json = 'foo=bar&spice=nice';
$httpHandler = getHandler([
buildResponse(
200,
['Content-Type' => 'application/x-www-form-urlencoded'],
Psr7\stream_for($json)
),
]);
$o = new OAuth2($testConfig);
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals($tokens['foo'], 'bar');
$this->assertEquals($tokens['spice'], 'nice');
}
public function testUpdatesTokenFieldsOnFetch()
{
$testConfig = $this->fetchAuthTokenMinimal;
$wanted_updates = [
'expires_at' => '1',
'expires_in' => '57',
'issued_at' => '2',
'access_token' => 'an_access_token',
'id_token' => 'an_id_token',
'refresh_token' => 'a_refresh_token',
];
$json = json_encode($wanted_updates);
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($json)),
]);
$o = new OAuth2($testConfig);
$this->assertNull($o->getExpiresAt());
$this->assertNull($o->getExpiresIn());
$this->assertNull($o->getIssuedAt());
$this->assertNull($o->getAccessToken());
$this->assertNull($o->getIdToken());
$this->assertNull($o->getRefreshToken());
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals(1, $o->getExpiresAt());
$this->assertEquals(57, $o->getExpiresIn());
$this->assertEquals(2, $o->getIssuedAt());
$this->assertEquals('an_access_token', $o->getAccessToken());
$this->assertEquals('an_id_token', $o->getIdToken());
$this->assertEquals('a_refresh_token', $o->getRefreshToken());
}
public function testUpdatesTokenFieldsOnFetchMissingRefreshToken()
{
$testConfig = $this->fetchAuthTokenMinimal;
$testConfig['refresh_token'] = 'a_refresh_token';
$wanted_updates = [
'expires_at' => '1',
'expires_in' => '57',
'issued_at' => '2',
'access_token' => 'an_access_token',
'id_token' => 'an_id_token',
];
$json = json_encode($wanted_updates);
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($json)),
]);
$o = new OAuth2($testConfig);
$this->assertNull($o->getExpiresAt());
$this->assertNull($o->getExpiresIn());
$this->assertNull($o->getIssuedAt());
$this->assertNull($o->getAccessToken());
$this->assertNull($o->getIdToken());
$this->assertEquals('a_refresh_token', $o->getRefreshToken());
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals(1, $o->getExpiresAt());
$this->assertEquals(57, $o->getExpiresIn());
$this->assertEquals(2, $o->getIssuedAt());
$this->assertEquals('an_access_token', $o->getAccessToken());
$this->assertEquals('an_id_token', $o->getIdToken());
$this->assertEquals('a_refresh_token', $o->getRefreshToken());
}
}
class OAuth2VerifyIdTokenTest extends TestCase
{
private $publicKey;
private $privateKey;
private $verifyIdTokenMinimal = [
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'audience' => 'myaccount.on.host.issuer.com',
'issuer' => 'an.issuer.com',
'clientId' => 'myaccount.on.host.issuer.com',
];
public function setUp()
{
$this->publicKey =
file_get_contents(__DIR__ . '/fixtures' . '/public.pem');
$this->privateKey =
file_get_contents(__DIR__ . '/fixtures' . '/private.pem');
}
/**
* @expectedException UnexpectedValueException
*/
public function testFailsIfIdTokenIsInvalid()
{
$testConfig = $this->verifyIdTokenMinimal;
$not_a_jwt = 'not a jot';
$o = new OAuth2($testConfig);
$o->setIdToken($not_a_jwt);
$o->verifyIdToken($this->publicKey);
}
/**
* @expectedException DomainException
*/
public function testFailsIfAudienceIsMissing()
{
$testConfig = $this->verifyIdTokenMinimal;
$now = time();
$origIdToken = [
'issuer' => $testConfig['issuer'],
'exp' => $now + 65, // arbitrary
'iat' => $now,
];
$o = new OAuth2($testConfig);
$jwtIdToken = $this->jwtEncode($origIdToken, $this->privateKey, 'RS256');
$o->setIdToken($jwtIdToken);
$o->verifyIdToken($this->publicKey, ['RS256']);
}
/**
* @expectedException DomainException
*/
public function testFailsIfAudienceIsWrong()
{
$now = time();
$testConfig = $this->verifyIdTokenMinimal;
$origIdToken = [
'aud' => 'a different audience',
'iss' => $testConfig['issuer'],
'exp' => $now + 65, // arbitrary
'iat' => $now,
];
$o = new OAuth2($testConfig);
$jwtIdToken = $this->jwtEncode($origIdToken, $this->privateKey, 'RS256');
$o->setIdToken($jwtIdToken);
$o->verifyIdToken($this->publicKey, ['RS256']);
}
public function testShouldReturnAValidIdToken()
{
$testConfig = $this->verifyIdTokenMinimal;
$now = time();
$origIdToken = [
'aud' => $testConfig['audience'],
'iss' => $testConfig['issuer'],
'exp' => $now + 65, // arbitrary
'iat' => $now,
];
$o = new OAuth2($testConfig);
$alg = 'RS256';
$jwtIdToken = $this->jwtEncode($origIdToken, $this->privateKey, $alg);
$o->setIdToken($jwtIdToken);
$roundTrip = $o->verifyIdToken($this->publicKey, array($alg));
$this->assertEquals($origIdToken['aud'], $roundTrip->aud);
}
private function jwtEncode()
{
$args = func_get_args();
$class = 'JWT';
if (class_exists('Firebase\JWT\JWT')) {
$class = 'Firebase\JWT\JWT';
}
return call_user_func_array("$class::encode", $args);
}
}
tests/ServiceAccountSignerTraitTest.php 0000644 00000003515 15174273671 0014371 0 ustar 00 signBlob(self::STRING_TO_SIGN, $useOpenSsl);
$this->assertEquals(implode('', $this->signedString), $res);
}
public function useOpenSsl()
{
return [[true], [false]];
}
}
class ServiceAccountSignerTraitImpl
{
use ServiceAccountSignerTrait;
private $auth;
public function __construct($signingKey)
{
$this->auth = new AuthStub;
$this->auth->signingKey = $signingKey;
}
}
class AuthStub
{
public $signingKey;
public function getSigningKey()
{
return $this->signingKey;
}
}
tests/Subscriber/AuthTokenSubscriberTest.php 0000644 00000026312 15174273671 0015331 0 ustar 00 onlyGuzzle5();
$this->mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
}
public function testSubscribesToEvents()
{
$a = new AuthTokenSubscriber($this->mockFetcher);
$this->assertArrayHasKey('before', $a->getEvents());
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$s = new AuthTokenSubscriber($this->mockFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'not_google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame($request->getHeader('authorization'), '');
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$authResult = ['access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test.
$a = new AuthTokenSubscriber($this->mockFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('authorization'),
'Bearer 1/abcdef1234567890');
}
public function testDoesNotAddAnAuthorizationHeaderOnNoAccessToken()
{
$authResult = ['not_access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test.
$a = new AuthTokenSubscriber($this->mockFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('authorization'), '');
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
null,
$this->mockCache
);
$a = new AuthTokenSubscriber($cachedFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('authorization'),
'Bearer 2/abcdef1234567890');
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$a = new AuthTokenSubscriber($cachedFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('authorization'),
'Bearer 2/abcdef1234567890');
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$prefix = 'test_prefix_';
$lifetime = '70707';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$a = new AuthTokenSubscriber($cachedFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('authorization'),
'Bearer 1/abcdef1234567890');
}
/** @dataProvider provideShouldNotifyTokenCallback */
public function testShouldNotifyTokenCallback(callable $tokenCallback)
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCache
->expects($this->any())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
SubscriberCallback::$expectedKey = $this->getValidKeyName($prefix . $cacheKey);
SubscriberCallback::$expectedValue = $token;
SubscriberCallback::$called = false;
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$a = new AuthTokenSubscriber(
$cachedFetcher,
null,
$tokenCallback
);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertTrue(SubscriberCallback::$called);
}
public function provideShouldNotifyTokenCallback()
{
SubscriberCallback::$phpunit = $this;
$anonymousFunc = function ($key, $value) {
SubscriberCallback::staticInvoke($key, $value);
};
return [
['Google\Auth\Tests\SubscriberCallbackFunction'],
['Google\Auth\Tests\SubscriberCallback::staticInvoke'],
[['Google\Auth\Tests\SubscriberCallback', 'staticInvoke']],
[$anonymousFunc],
[[new SubscriberCallback, 'staticInvoke']],
[[new SubscriberCallback, 'methodInvoke']],
[new SubscriberCallback],
];
}
}
class SubscriberCallback
{
public static $phpunit;
public static $expectedKey;
public static $expectedValue;
public static $called = false;
public function __invoke($key, $value)
{
self::$phpunit->assertEquals(self::$expectedKey, $key);
self::$phpunit->assertEquals(self::$expectedValue, $value);
self::$called = true;
}
public function methodInvoke($key, $value)
{
return $this($key, $value);
}
public static function staticInvoke($key, $value)
{
$instance = new self();
return $instance($key, $value);
}
}
function SubscriberCallbackFunction($key, $value)
{
return SubscriberCallback::staticInvoke($key, $value);
}
tests/Subscriber/ScopedAccessTokenSubscriberTest.php 0000644 00000020656 15174273671 0016774 0 ustar 00 onlyGuzzle5();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresScopeAsAStringOrArray()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
new ScopedAccessTokenSubscriber($fakeAuthFunc, new \stdClass(), array());
}
public function testSubscribesToEvents()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array());
$this->assertArrayHasKey('before', $s->getEvents());
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array());
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 1/abcdef1234567890',
$request->getHeader('authorization')
);
}
public function testUsesCachedAuthToken()
{
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
// Run the test
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array(),
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('authorization')
);
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($prefix . $this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
// Run the test
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE,
['prefix' => $prefix],
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('authorization')
);
}
public function testShouldSaveValueInCache()
{
$token = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '2/abcdef1234567890';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array(),
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('authorization')
);
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$token = '2/abcdef1234567890';
$prefix = 'test_prefix_';
$lifetime = '70707';
$fakeAuthFunc = function ($unused_scopes) {
return '2/abcdef1234567890';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($prefix . $this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
// Run the test
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('authorization')
);
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array());
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'notscoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame('', $request->getHeader('authorization'));
}
}
tests/Subscriber/SimpleSubscriberTest.php 0000644 00000004275 15174273671 0014664 0 ustar 00 onlyGuzzle5();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresADeveloperKey()
{
new SimpleSubscriber(['not_key' => 'a test key']);
}
public function testSubscribesToEvents()
{
$events = (new SimpleSubscriber(['key' => 'a test key']))->getEvents();
$this->assertArrayHasKey('before', $events);
}
public function testAddsTheKeyToTheQuery()
{
$s = new SimpleSubscriber(['key' => 'test_key']);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'simple']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertCount(1, $request->getQuery());
$this->assertTrue($request->getQuery()->hasKey('key'));
$this->assertSame($request->getQuery()->get('key'), 'test_key');
}
public function testOnlyTouchesWhenAuthConfigIsSimple()
{
$s = new SimpleSubscriber(['key' => 'test_key']);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'notsimple']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertCount(0, $request->getQuery());
}
}
tests/bootstrap.php 0000644 00000003263 15174273671 0010455 0 ustar 00 $handler]);
return new \Google\Auth\HttpHandler\Guzzle6HttpHandler($client);
}
$client = new \GuzzleHttp\Client();
$client->getEmitter()->attach(
new \GuzzleHttp\Subscriber\Mock($mockResponses)
);
return new \Google\Auth\HttpHandler\Guzzle5HttpHandler($client);
}
tests/fixtures/.config/gcloud/application_default_credentials.json 0000644 00000000242 15174273671 0021651 0 ustar 00 {
"private_key_id": "key123",
"private_key": "privatekey",
"client_email": "hello@youarecool.com",
"client_id": "client123",
"type": "service_account"
} tests/fixtures/private.json 0000644 00000000242 15174273671 0012137 0 ustar 00 {
"private_key_id": "key123",
"private_key": "privatekey",
"client_email": "hello@youarecool.com",
"client_id": "client123",
"type": "service_account"
} tests/fixtures/private.pem 0000644 00000001567 15174273671 0011762 0 ustar 00 -----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDzU+jLTzW6154Joezxrd2+5pCNYP0HcaMoYqEyXfNRpkNE7wrQ
UEG830o4Qcaae2BhqZoujwSW7RkR6h0Fkd0WTR8h5J8rSGNHv/1jJoUUjP9iZ/5S
FAyIIyEYfDPqtnA4iF1QWO2lXWlEFSuZjwM/8jBmeGzoiw17akNThIw8NwIDAQAB
AoGATpboVloEAY/IdFX/QGOmfhTb1T3hG3lheBa695iOkO2BRo9qT7PMN6NqxlbA
PX7ht0lfCfCZS+HSOg4CR50/6WXHMSmwlvcjGuDIDKWjviQTTYE77MlVBQHw9WzY
PfiRBbtouyPGQtO4rk42zkIILC6exBZ1vKpRPOmTAnxrjCECQQD+56r6hYcS6GNp
NOWyv0eVFMBX4iNWAsRf9JVVvGDz2rVuhnkNiN73vfffDWvSXkCydL1jFmalgdQD
gm77UZQHAkEA9F+CauU0aZsJ1SthQ6H0sDQ+eNRUgnz4itnkSC2C20fZ3DaSpCMC
0go81CcZOhftNO730ILqiS67C3d3rqLqUQJBAP10ROHMmz4Fq7MUUcClyPtHIuk/
hXskTTZL76DMKmrN8NDxDLSUf38+eJRkt+z4osPOp/E6eN3gdXr32nox50kCQCl8
hXGMU+eR0IuF/88xkY7Qb8KnmWlFuhQohZ7TSyHbAttl0GNZJkNuRYFm2duI8FZK
M3wMnbCIZGy/7WuScOECQQCV+0yrf5dL1M2GHjJfwuTb00wRKalKQEH1v/kvE5vS
FmdN7BPK5Ra50MaecMNoYqu9rmtyWRBn93dcvKrL57nY
-----END RSA PRIVATE KEY-----
tests/fixtures/public.pem 0000644 00000000420 15174273671 0011551 0 ustar 00 -----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDzU+jLTzW6154Joezxrd2+5pCN
YP0HcaMoYqEyXfNRpkNE7wrQUEG830o4Qcaae2BhqZoujwSW7RkR6h0Fkd0WTR8h
5J8rSGNHv/1jJoUUjP9iZ/5SFAyIIyEYfDPqtnA4iF1QWO2lXWlEFSuZjwM/8jBm
eGzoiw17akNThIw8NwIDAQAB
-----END PUBLIC KEY-----
tests/fixtures2/.config/gcloud/application_default_credentials.json 0000644 00000000210 15174273671 0021726 0 ustar 00 {
"client_id": "client123",
"client_secret": "clientSecret123",
"refresh_token": "refreshToken123",
"type": "authorized_user"
}
tests/fixtures2/gcloud.json 0000644 00000000317 15174273671 0012027 0 ustar 00 {
"client_id": "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com",
"client_secret": "dummy_client_secret",
"refresh_token": "dummy_refresh_token",
"type": "authorized_user"
}
tests/fixtures2/private.json 0000644 00000000210 15174273671 0012214 0 ustar 00 {
"client_id": "client123",
"client_secret": "clientSecret123",
"refresh_token": "refreshToken123",
"type": "authorized_user"
}
tests/fixtures2/valid_oauth_creds.json 0000644 00000000247 15174273671 0014233 0 ustar 00 {
"client_id": "valid.apps.googleusercontent.com",
"client_secret": "dummy_client_secret",
"refresh_token": "dummy_refresh_token",
"type": "authorized_user"
}
tests/mocks/AppIdentityService.php 0000644 00000001211 15174273671 0013316 0 ustar 00 'xyz',
'expiration_time' => '2147483646',
];
public static $serviceAccountName;
public static function getAccessToken($scope)
{
self::$scope = $scope;
return self::$accessToken;
}
public static function signForApp($stringToSign)
{
return [
'signature' => 'Signed: ' . $stringToSign
];
}
public static function getServiceAccountName()
{
return self::$serviceAccountName;
}
}