forked from hswaw/hscloud
Merge changes I4ef1f6ed,I20b0ecbb,Ida9dff72,I92e70536
* changes: cluster/cube/lib/cockroachdb: clean up topology cluster/kube/lib/cockroach: move client to deployment app/gerrit/kube: implement app/gerrit: import OAuth provider and add SSO support
This commit is contained in:
commit
1e5e81227a
53 changed files with 3723 additions and 41 deletions
3
.bazelrc
Normal file
3
.bazelrc
Normal file
|
@ -0,0 +1,3 @@
|
|||
# Required for app/gerrit/gerrit-oauth-provider
|
||||
build --workspace_status_command=./tools/workspace-status.sh
|
||||
test --build_tests_only
|
39
WORKSPACE
39
WORKSPACE
|
@ -60,6 +60,7 @@ container_repositories()
|
|||
# Docker base images
|
||||
|
||||
load("@io_bazel_rules_docker//container:container.bzl", "container_pull")
|
||||
|
||||
container_pull(
|
||||
name = "prodimage-bionic",
|
||||
registry = "index.docker.io",
|
||||
|
@ -68,6 +69,14 @@ container_pull(
|
|||
digest = "sha256:b36667c98cf8f68d4b7f1fb8e01f742c2ed26b5f0c965a788e98dfe589a4b3e4",
|
||||
)
|
||||
|
||||
container_pull(
|
||||
name = "gerrit-3.0.0",
|
||||
registry = "index.docker.io",
|
||||
repository = "gerritcodereview/gerrit",
|
||||
tag = "3.0.0-ubuntu18",
|
||||
digest = "sha256:f107729011d8b81611e35a0ad452f21a424c1820664e9f95d135ad411e87b9bb",
|
||||
)
|
||||
|
||||
# HTTP stuff from the Internet
|
||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
|
||||
http_file(
|
||||
|
@ -110,6 +119,36 @@ load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")
|
|||
|
||||
gazelle_dependencies()
|
||||
|
||||
# For app/gerrit/gerrit-oauth-provider
|
||||
|
||||
git_repository(
|
||||
name = "com_googlesource_gerrit_bazlets",
|
||||
remote = "https://gerrit.googlesource.com/bazlets",
|
||||
commit = "8528a0df69dadf6311d8d3f81c1b693afda8bcf1",
|
||||
)
|
||||
|
||||
load(
|
||||
"@com_googlesource_gerrit_bazlets//:gerrit_api.bzl",
|
||||
"gerrit_api",
|
||||
)
|
||||
|
||||
gerrit_api()
|
||||
|
||||
load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", "maven_jar")
|
||||
|
||||
maven_jar(
|
||||
name = "scribe",
|
||||
artifact = "org.scribe:scribe:1.3.7",
|
||||
sha1 = "583921bed46635d9f529ef5f14f7c9e83367bc6e",
|
||||
)
|
||||
|
||||
maven_jar(
|
||||
name = "commons-codec",
|
||||
artifact = "commons-codec:commons-codec:1.4",
|
||||
sha1 = "4216af16d38465bbab0f3dff8efa14204f7a399a",
|
||||
)
|
||||
|
||||
|
||||
# Go repositories
|
||||
|
||||
go_repository(
|
||||
|
|
33
app/gerrit/BUILD
Normal file
33
app/gerrit/BUILD
Normal file
|
@ -0,0 +1,33 @@
|
|||
load("@io_bazel_rules_docker//container:container.bzl", "container_image")
|
||||
|
||||
container_image(
|
||||
name="with_plugins",
|
||||
base="@gerrit-3.0.0//image",
|
||||
files = [
|
||||
"//app/gerrit/gerrit-oauth-provider:gerrit-oauth-provider",
|
||||
],
|
||||
# we cannot drop it directly in /var/gerrit/plugins as that changes the
|
||||
# directory owner to 0:0 and then breaks the gerrit installer that wants
|
||||
# to overwrite plugins.
|
||||
directory = "/var/gerrit-plugins",
|
||||
)
|
||||
container_image(
|
||||
name="3.0.0-r7",
|
||||
base=":with_plugins",
|
||||
files = [":entrypoint.sh"],
|
||||
directory = "/",
|
||||
entrypoint = ["/entrypoint.sh"],
|
||||
)
|
||||
|
||||
genrule(
|
||||
name = "push_latest",
|
||||
srcs = [":3.0.0-r7"],
|
||||
outs = ["version.sh"],
|
||||
executable = True,
|
||||
cmd = """
|
||||
tag=3.0.0-r7
|
||||
docker tag bazel/app/gerrit:$$tag registry.k0.hswaw.net/app/gerrit:$$tag
|
||||
docker push registry.k0.hswaw.net/app/gerrit:$$tag
|
||||
echo -ne "#!/bin/sh\necho Pushed $$tag.\n" > $(OUTS)
|
||||
""",
|
||||
)
|
43
app/gerrit/entrypoint.sh
Executable file
43
app/gerrit/entrypoint.sh
Executable file
|
@ -0,0 +1,43 @@
|
|||
#!/bin/bash -e
|
||||
|
||||
ls -la /var/gerrit/*
|
||||
|
||||
if [ ! -d /var/gerrit/git/All-Projects.git ] || [ "$1" == "init" ]
|
||||
then
|
||||
echo "Initializing Gerrit site ..."
|
||||
java -jar /var/gerrit/bin/gerrit.war init --batch --install-all-plugins -d /var/gerrit
|
||||
java -jar /var/gerrit/bin/gerrit.war reindex -d /var/gerrit
|
||||
fi
|
||||
|
||||
echo "Running hscloud init setup..."
|
||||
|
||||
rm -f /var/gerrit/etc/gerrit.config
|
||||
cp /var/gerrit-config/gerrit.config /var/gerrit/etc/gerrit.config
|
||||
|
||||
rm -f /var/gerrit/etc/secure.config
|
||||
cp /var/gerrit-secure/secure.config /var/gerrit/etc/secure.config
|
||||
|
||||
cp /var/gerrit-plugins/* /var/gerrit/plugins/
|
||||
|
||||
echo "Starting config updater..."
|
||||
# Keep copying config over in background. We cannot run directly from
|
||||
# the configmap filesystem as gerrit really wants a read-write FS.
|
||||
(
|
||||
src=/var/gerrit-config/gerrit.config
|
||||
dst=/var/gerrit/etc/gerrit.config
|
||||
while true; do
|
||||
sleep 60
|
||||
if ! cmp -s $src $dst; then
|
||||
echo "HSCLOUD: bumping config"
|
||||
cp $src $dst
|
||||
fi
|
||||
done
|
||||
) &
|
||||
|
||||
ls -la /var/gerrit/*
|
||||
|
||||
if [ "$1" != "init" ]
|
||||
then
|
||||
echo "Running Gerrit ..."
|
||||
exec /var/gerrit/bin/gerrit.sh run
|
||||
fi
|
11
app/gerrit/gerrit-oauth-provider/.gitignore
vendored
Normal file
11
app/gerrit/gerrit-oauth-provider/.gitignore
vendored
Normal file
|
@ -0,0 +1,11 @@
|
|||
/.classpath
|
||||
/.project
|
||||
/.settings
|
||||
/bazel-bin
|
||||
/bazel-genfiles
|
||||
/bazel-gerrit-oauth-provider
|
||||
/bazel-out
|
||||
/bazel-testlogs
|
||||
/eclipse-out
|
||||
/.idea
|
||||
*.swp
|
43
app/gerrit/gerrit-oauth-provider/BUILD
Normal file
43
app/gerrit/gerrit-oauth-provider/BUILD
Normal file
|
@ -0,0 +1,43 @@
|
|||
load("//app/gerrit/gerrit-oauth-provider/tools/bzl:junit.bzl", "junit_tests")
|
||||
load(
|
||||
"//app/gerrit/gerrit-oauth-provider/tools/bzl:plugin.bzl",
|
||||
"PLUGIN_DEPS",
|
||||
"PLUGIN_TEST_DEPS",
|
||||
"gerrit_plugin",
|
||||
)
|
||||
|
||||
gerrit_plugin(
|
||||
name = "gerrit-oauth-provider",
|
||||
srcs = glob(["src/main/java/**/*.java"]),
|
||||
manifest_entries = [
|
||||
"Gerrit-PluginName: gerrit-oauth-provider",
|
||||
"Gerrit-HttpModule: com.googlesource.gerrit.plugins.oauth.HttpModule",
|
||||
"Gerrit-InitStep: com.googlesource.gerrit.plugins.oauth.InitOAuth",
|
||||
"Implementation-Title: Gerrit OAuth authentication provider",
|
||||
"Implementation-URL: https://github.com/davido/gerrit-oauth-provider",
|
||||
],
|
||||
resources = glob(["src/main/resources/**/*"]),
|
||||
deps = [
|
||||
"@commons-codec//jar:neverlink",
|
||||
"@scribe//jar",
|
||||
],
|
||||
)
|
||||
|
||||
junit_tests(
|
||||
name = "gerrit-oauth-provider_tests",
|
||||
srcs = glob(["src/test/java/**/*.java"]),
|
||||
tags = ["oauth"],
|
||||
deps = [
|
||||
":gerrit-oauth-provider__plugin_test_deps",
|
||||
],
|
||||
)
|
||||
|
||||
java_library(
|
||||
name = "gerrit-oauth-provider__plugin_test_deps",
|
||||
testonly = 1,
|
||||
visibility = ["//visibility:public"],
|
||||
exports = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
|
||||
":gerrit-oauth-provider__plugin",
|
||||
"@scribe//jar",
|
||||
],
|
||||
)
|
201
app/gerrit/gerrit-oauth-provider/LICENSE-Apache2.0
Normal file
201
app/gerrit/gerrit-oauth-provider/LICENSE-Apache2.0
Normal file
|
@ -0,0 +1,201 @@
|
|||
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.
|
22
app/gerrit/gerrit-oauth-provider/LICENSE-scribe
Normal file
22
app/gerrit/gerrit-oauth-provider/LICENSE-scribe
Normal file
|
@ -0,0 +1,22 @@
|
|||
The MIT License
|
||||
|
||||
Copyright (c) 2010 Pablo Fernandez
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
68
app/gerrit/gerrit-oauth-provider/README.md
Normal file
68
app/gerrit/gerrit-oauth-provider/README.md
Normal file
|
@ -0,0 +1,68 @@
|
|||
Gerrit OAuth2 authentication provider
|
||||
=====================================
|
||||
|
||||
[![Build Status](https://travis-ci.org/davido/gerrit-oauth-provider.svg?branch=master)](https://travis-ci.org/davido/gerrit-oauth-provider)
|
||||
|
||||
|
||||
With this plugin Gerrit can use OAuth2 protocol for authentication.
|
||||
Supported OAuth providers:
|
||||
|
||||
* [AirVantage](https://doc.airvantage.net/av/reference/cloud/API/#API-GeneralInformation-Authentication)
|
||||
* [Bitbucket](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html)
|
||||
* [CAS](https://www.apereo.org/projects/cas)
|
||||
* [CoreOS Dex](https://github.com/coreos/dex)
|
||||
* [Facebook](https://developers.facebook.com/docs/facebook-login)
|
||||
* [GitHub](https://developer.github.com/v3/oauth/)
|
||||
* [GitLab](https://about.gitlab.com/)
|
||||
* [Google](https://developers.google.com/identity/protocols/OAuth2)
|
||||
* [Keycloak](http://www.keycloak.org/)
|
||||
* [Office365](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols)
|
||||
|
||||
See the [Wiki](https://github.com/davido/gerrit-oauth-provider/wiki) what it can do for you.
|
||||
|
||||
Prebuilt artifacts
|
||||
------------------
|
||||
|
||||
Prebuilt binary artifacts are available on [release page](https://github.com/davido/gerrit-oauth-provider/releases). Make sure to pick the right JAR for your Gerrit version.
|
||||
|
||||
Build
|
||||
-----
|
||||
|
||||
To build the plugin with Bazel, install
|
||||
[Bazel](https://bazel.build/versions/master/docs/install.html) and run the
|
||||
following:
|
||||
|
||||
```
|
||||
git clone https://gerrit.googlesource.com/plugins/oauth gerrit-oauth-provider
|
||||
cd gerrit-oauth-provider && bazel build gerrit-oauth-provider
|
||||
```
|
||||
|
||||
Install
|
||||
-------
|
||||
|
||||
Copy the `bazel-genfiles/oauth.jar` to
|
||||
`$gerrit_site/plugins` and re-run init to configure it:
|
||||
|
||||
```
|
||||
java -jar gerrit.war init -d <site>
|
||||
[...]
|
||||
*** OAuth Authentication Provider
|
||||
***
|
||||
Use Bitbucket OAuth provider for Gerrit login ? [Y/n]? n
|
||||
Use Google OAuth provider for Gerrit login ? [Y/n]?
|
||||
Application client id : <client-id>
|
||||
Application client secret :
|
||||
confirm password :
|
||||
Link to OpenID accounts? [true]:
|
||||
Use GitHub OAuth provider for Gerrit login ? [Y/n]? n
|
||||
```
|
||||
|
||||
Reporting bugs
|
||||
--------------
|
||||
|
||||
Make sure to read the [FAQ](https://github.com/davido/gerrit-oauth-provider/wiki/FAQ) before reporting issues.
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Apache License 2.0
|
18
app/gerrit/gerrit-oauth-provider/bazlets.bzl
Normal file
18
app/gerrit/gerrit-oauth-provider/bazlets.bzl
Normal file
|
@ -0,0 +1,18 @@
|
|||
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
|
||||
|
||||
NAME = "com_googlesource_gerrit_bazlets"
|
||||
|
||||
def load_bazlets(
|
||||
commit,
|
||||
local_path = None):
|
||||
if not local_path:
|
||||
git_repository(
|
||||
name = NAME,
|
||||
remote = "https://gerrit.googlesource.com/bazlets",
|
||||
commit = commit,
|
||||
)
|
||||
else:
|
||||
native.local_repository(
|
||||
name = NAME,
|
||||
path = local_path,
|
||||
)
|
14
app/gerrit/gerrit-oauth-provider/external_plugin_deps.bzl
Normal file
14
app/gerrit/gerrit-oauth-provider/external_plugin_deps.bzl
Normal file
|
@ -0,0 +1,14 @@
|
|||
load("//tools/bzl:maven_jar.bzl", "maven_jar")
|
||||
|
||||
def external_plugin_deps(omit_commons_codec = True):
|
||||
maven_jar(
|
||||
name = "scribe",
|
||||
artifact = "org.scribe:scribe:1.3.7",
|
||||
sha1 = "583921bed46635d9f529ef5f14f7c9e83367bc6e",
|
||||
)
|
||||
if not omit_commons_codec:
|
||||
maven_jar(
|
||||
name = "commons-codec",
|
||||
artifact = "commons-codec:commons-codec:1.4",
|
||||
sha1 = "4216af16d38465bbab0f3dff8efa14204f7a399a",
|
||||
)
|
|
@ -0,0 +1,56 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.extractors.JsonTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
|
||||
public class AirVantageApi extends DefaultApi20 {
|
||||
|
||||
private static final String AUTHORIZE_URL =
|
||||
"https://eu.airvantage.net/api/oauth/authorize?client_id=%s&response_type=code";
|
||||
private static final String ACCESS_TOKEN_ENDPOINT = "https://eu.airvantage.net/api/oauth/token";
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return format(AUTHORIZE_URL, config.getApiKey());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return ACCESS_TOKEN_ENDPOINT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return new JsonTokenExtractor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
||||
import static org.slf4j.LoggerFactory.getLogger;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@Singleton
|
||||
public class AirVantageOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = getLogger(AirVantageOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-airvantage-oauth";
|
||||
private static final String AV_PROVIDER_PREFIX = "airvantage-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL =
|
||||
"https://eu.airvantage.net/api/v1/users/current";
|
||||
private final OAuthService service;
|
||||
|
||||
@Inject
|
||||
AirVantageOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(AirVantageApi.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
Response response = request.send();
|
||||
if (response.getCode() != SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get("uid");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain uid field");
|
||||
}
|
||||
JsonElement email = jsonObject.get("email");
|
||||
JsonElement name = jsonObject.get("name");
|
||||
return new OAuthUserInfo(
|
||||
AV_PROVIDER_PREFIX + id.getAsString(),
|
||||
null,
|
||||
email.getAsString(),
|
||||
name.getAsString(),
|
||||
id.getAsString());
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "AirVantage OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
import static java.lang.String.format;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
||||
import static org.scribe.model.OAuthConstants.ACCESS_TOKEN;
|
||||
import static org.scribe.model.OAuthConstants.CODE;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.exceptions.OAuthException;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
|
||||
public class BitbucketApi extends DefaultApi20 {
|
||||
|
||||
private static final String AUTHORIZE_URL =
|
||||
"https://bitbucket.org/site/oauth2/authorize?client_id=%s&response_type=code";
|
||||
private static final String ACCESS_TOKEN_ENDPOINT =
|
||||
"https://bitbucket.org/site/oauth2/access_token";
|
||||
|
||||
public BitbucketApi() {}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return format(AUTHORIZE_URL, config.getApiKey());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return ACCESS_TOKEN_ENDPOINT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new BitbucketOAuthService(this, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return new BitbucketTokenExtractor();
|
||||
}
|
||||
|
||||
private static final class BitbucketOAuthService implements OAuthService {
|
||||
private static final String VERSION = "2.0";
|
||||
|
||||
private static final String GRANT_TYPE = "grant_type";
|
||||
private static final String GRANT_TYPE_VALUE = "authorization_code";
|
||||
|
||||
private final DefaultApi20 api;
|
||||
private final OAuthConfig config;
|
||||
|
||||
private BitbucketOAuthService(DefaultApi20 api, OAuthConfig config) {
|
||||
this.config = config;
|
||||
this.api = api;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Token getAccessToken(Token token, Verifier verifier) {
|
||||
OAuthRequest request =
|
||||
new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
|
||||
request.addHeader("Authorization", prepareAuthorizationHeaderValue());
|
||||
request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_VALUE);
|
||||
request.addBodyParameter(CODE, verifier.getValue());
|
||||
Response response = request.send();
|
||||
if (response.getCode() == SC_OK) {
|
||||
Token t = api.getAccessTokenExtractor().extract(response.getBody());
|
||||
return new Token(t.getToken(), config.getApiSecret());
|
||||
}
|
||||
|
||||
throw new OAuthException(
|
||||
String.format(
|
||||
"Error response received: %s, HTTP status: %s",
|
||||
response.getBody(), response.getCode()));
|
||||
}
|
||||
|
||||
private String prepareAuthorizationHeaderValue() {
|
||||
String value = String.format("%s:%s", config.getApiKey(), config.getApiSecret());
|
||||
String valueBase64 = BaseEncoding.base64().encode(value.getBytes());
|
||||
return String.format("Basic %s", valueBase64);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Token getRequestToken() {
|
||||
throw new UnsupportedOperationException(
|
||||
"Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return VERSION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void signRequest(Token token, OAuthRequest request) {
|
||||
request.addQuerystringParameter(ACCESS_TOKEN, token.getToken());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(Token token) {
|
||||
return api.getAuthorizationUrl(config);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class BitbucketTokenExtractor implements AccessTokenExtractor {
|
||||
|
||||
@Override
|
||||
public Token extract(String response) {
|
||||
JsonElement json = JSON.newGson().fromJson(response, JsonElement.class);
|
||||
if (json.isJsonObject()) {
|
||||
JsonObject jsonObject = json.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get(ACCESS_TOKEN);
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new OAuthException("Response doesn't contain 'access_token' field");
|
||||
}
|
||||
JsonElement accessToken = jsonObject.get(ACCESS_TOKEN);
|
||||
return new Token(accessToken.getAsString(), "");
|
||||
}
|
||||
|
||||
throw new OAuthException(String.format("Invalid JSON '%s': not a JSON Object", json));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,130 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
||||
import static org.slf4j.LoggerFactory.getLogger;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@Singleton
|
||||
public class BitbucketOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = getLogger(BitbucketOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-bitbucket-oauth";
|
||||
private static final String BITBUCKET_PROVIDER_PREFIX = "bitbucket-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL = "https://bitbucket.org/api/1.0/user/";
|
||||
private final boolean fixLegacyUserId;
|
||||
private final OAuthService service;
|
||||
|
||||
@Inject
|
||||
BitbucketOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(BitbucketApi.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
Response response = request.send();
|
||||
if (response.getCode() != SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonObject userObject = jsonObject.getAsJsonObject("user");
|
||||
if (userObject == null || userObject.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain 'user' field");
|
||||
}
|
||||
JsonElement usernameElement = userObject.get("username");
|
||||
String username = usernameElement.getAsString();
|
||||
|
||||
JsonElement displayName = jsonObject.get("display_name");
|
||||
return new OAuthUserInfo(
|
||||
BITBUCKET_PROVIDER_PREFIX + username,
|
||||
username,
|
||||
null,
|
||||
displayName == null || displayName.isJsonNull() ? null : displayName.getAsString(),
|
||||
fixLegacyUserId ? username : null);
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Bitbucket OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
// Copyright (C) 2016 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.scribe.utils.OAuthEncoder;
|
||||
|
||||
public class CasApi extends DefaultApi20 {
|
||||
private static final String AUTHORIZE_URL =
|
||||
"%s/oauth2.0/authorize?response_type=code&client_id=%s&redirect_uri=%s";
|
||||
|
||||
private final String rootUrl;
|
||||
|
||||
public CasApi(String rootUrl) {
|
||||
this.rootUrl = rootUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return String.format("%s/oauth2.0/accessToken", rootUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return String.format(
|
||||
AUTHORIZE_URL, rootUrl, config.getApiKey(), OAuthEncoder.encode(config.getCallback()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,171 @@
|
|||
// Copyright (C) 2016 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Singleton
|
||||
class CasOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = LoggerFactory.getLogger(CasOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-cas-oauth";
|
||||
private static final String CAS_PROVIDER_PREFIX = "cas-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL = "%s/oauth2.0/profile";
|
||||
|
||||
private final String rootUrl;
|
||||
private final boolean fixLegacyUserId;
|
||||
private final OAuthService service;
|
||||
|
||||
@Inject
|
||||
CasOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
rootUrl = cfg.getString(InitOAuth.ROOT_URL);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(new CasApi(rootUrl))
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
final String protectedResourceUrl = String.format(PROTECTED_RESOURCE_URL, rootUrl);
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, protectedResourceUrl);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
|
||||
Response response = request.send();
|
||||
if (response.getCode() != HttpServletResponse.SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (!userJson.isJsonObject()) {
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
|
||||
JsonElement id = jsonObject.get("id");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException(String.format("CAS response missing id: %s", response.getBody()));
|
||||
}
|
||||
|
||||
JsonElement attrListJson = jsonObject.get("attributes");
|
||||
if (attrListJson == null) {
|
||||
throw new IOException(
|
||||
String.format("CAS response missing attributes: %s", response.getBody()));
|
||||
}
|
||||
|
||||
String email = null, name = null, login = null;
|
||||
|
||||
if (attrListJson.isJsonArray()) {
|
||||
// It is possible for CAS to be configured to not return any attributes (email, name, login),
|
||||
// in which case,
|
||||
// CAS returns an empty JSON object "attributes":{}, rather than "null" or an empty JSON array
|
||||
// "attributes": []
|
||||
|
||||
JsonArray attrJson = attrListJson.getAsJsonArray();
|
||||
for (JsonElement elem : attrJson) {
|
||||
if (elem == null || !elem.isJsonObject()) {
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", elem));
|
||||
}
|
||||
JsonObject obj = elem.getAsJsonObject();
|
||||
|
||||
String property = getStringElement(obj, "email");
|
||||
if (property != null) email = property;
|
||||
property = getStringElement(obj, "name");
|
||||
if (property != null) name = property;
|
||||
property = getStringElement(obj, "login");
|
||||
if (property != null) login = property;
|
||||
}
|
||||
}
|
||||
|
||||
return new OAuthUserInfo(
|
||||
CAS_PROVIDER_PREFIX + id.getAsString(),
|
||||
login,
|
||||
email,
|
||||
name,
|
||||
fixLegacyUserId ? id.getAsString() : null);
|
||||
}
|
||||
|
||||
private String getStringElement(JsonObject o, String name) {
|
||||
JsonElement elem = o.get(name);
|
||||
if (elem == null || elem.isJsonNull()) return null;
|
||||
|
||||
return elem.getAsString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Generic CAS OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.extractors.JsonTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.scribe.utils.OAuthEncoder;
|
||||
|
||||
public class DexApi extends DefaultApi20 {
|
||||
|
||||
private static final String AUTHORIZE_URL =
|
||||
"%s/dex/auth?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
|
||||
|
||||
private final String rootUrl;
|
||||
|
||||
public DexApi(String rootUrl) {
|
||||
this.rootUrl = rootUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return String.format(
|
||||
AUTHORIZE_URL,
|
||||
rootUrl,
|
||||
config.getApiKey(),
|
||||
OAuthEncoder.encode(config.getCallback()),
|
||||
config.getScope().replaceAll(" ", "+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return String.format("%s/dex/token", rootUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return new JsonTokenExtractor();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
|
||||
@Singleton
|
||||
public class DexOAuthService implements OAuthServiceProvider {
|
||||
|
||||
static final String CONFIG_SUFFIX = "-dex-oauth";
|
||||
private static final String DEX_PROVIDER_PREFIX = "dex-oauth:";
|
||||
private final OAuthService service;
|
||||
private final String rootUrl;
|
||||
private final String domain;
|
||||
private final String serviceName;
|
||||
|
||||
@Inject
|
||||
DexOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
|
||||
rootUrl = cfg.getString(InitOAuth.ROOT_URL);
|
||||
domain = cfg.getString(InitOAuth.DOMAIN, null);
|
||||
serviceName = cfg.getString(InitOAuth.SERVICE_NAME, "Dex OAuth2");
|
||||
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(new DexApi(rootUrl))
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.scope("openid profile email offline_access")
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
private String parseJwt(String input) {
|
||||
String[] parts = input.split("\\.");
|
||||
Preconditions.checkState(parts.length == 3);
|
||||
Preconditions.checkNotNull(parts[1]);
|
||||
return new String(Base64.decodeBase64(parts[1]));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
JsonElement tokenJson = JSON.newGson().fromJson(token.getRaw(), JsonElement.class);
|
||||
JsonObject tokenObject = tokenJson.getAsJsonObject();
|
||||
JsonElement id_token = tokenObject.get("id_token");
|
||||
|
||||
JsonElement claimJson =
|
||||
JSON.newGson().fromJson(parseJwt(id_token.getAsString()), JsonElement.class);
|
||||
|
||||
// Dex does not support basic profile currently (2017-09), extracting info
|
||||
// from access token claim
|
||||
|
||||
JsonObject claimObject = claimJson.getAsJsonObject();
|
||||
JsonElement emailElement = claimObject.get("email");
|
||||
JsonElement nameElement = claimObject.get("name");
|
||||
if (emailElement == null || emailElement.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain email field");
|
||||
}
|
||||
if (nameElement == null || nameElement.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain name field");
|
||||
}
|
||||
String email = emailElement.getAsString();
|
||||
String name = nameElement.getAsString();
|
||||
String username = email;
|
||||
if (domain != null && domain.length() > 0) {
|
||||
username = email.replace("@" + domain, "");
|
||||
}
|
||||
|
||||
return new OAuthUserInfo(
|
||||
DEX_PROVIDER_PREFIX + email /*externalId*/,
|
||||
username /*username*/,
|
||||
email /*email*/,
|
||||
name /*displayName*/,
|
||||
null /*claimedIdentity*/);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return serviceName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
|
||||
@Singleton
|
||||
class DisabledOAuthLoginProvider implements OAuthLoginProvider {
|
||||
private final String pluginName;
|
||||
|
||||
@Inject
|
||||
DisabledOAuthLoginProvider(@PluginName String pluginName) {
|
||||
this.pluginName = pluginName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo login(String username, String secret) throws IOException {
|
||||
throw new UnsupportedOperationException(
|
||||
"git over oauth is not implemented by " + pluginName + " plugin");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import org.scribe.builder.api.FacebookApi;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
|
||||
public class Facebook2Api extends FacebookApi {
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return OAuth2AccessTokenJsonExtractor.instance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,142 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Singleton
|
||||
class FacebookOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = LoggerFactory.getLogger(FacebookOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-facebook-oauth";
|
||||
private static final String PROTECTED_RESOURCE_URL = "https://graph.facebook.com/me";
|
||||
|
||||
private static final String FACEBOOK_PROVIDER_PREFIX = "facebook-oauth:";
|
||||
private static final String SCOPE = "email";
|
||||
private static final String FIELDS_QUERY = "fields";
|
||||
private static final String FIELDS = "email,name";
|
||||
private final OAuthService service;
|
||||
|
||||
@Inject
|
||||
FacebookOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(Facebook2Api.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.scope(SCOPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
request.addQuerystringParameter(FIELDS_QUERY, FIELDS);
|
||||
service.signRequest(t, request);
|
||||
Response response = request.send();
|
||||
|
||||
if (response.getCode() != HttpServletResponse.SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get("id");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain id field");
|
||||
}
|
||||
JsonElement email = jsonObject.get("email");
|
||||
JsonElement name = jsonObject.get("name");
|
||||
// Heads up!
|
||||
// Lets keep `login` equal to `email`, since `username` field is
|
||||
// deprecated for Facebook API versions v2.0 and higher
|
||||
JsonElement login = jsonObject.get("email");
|
||||
|
||||
return new OAuthUserInfo(
|
||||
FACEBOOK_PROVIDER_PREFIX + id.getAsString(),
|
||||
login == null || login.isJsonNull() ? null : login.getAsString(),
|
||||
email == null || email.isJsonNull() ? null : email.getAsString(),
|
||||
name == null || name.isJsonNull() ? null : name.getAsString(),
|
||||
null);
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Facebook OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.utils.OAuthEncoder;
|
||||
|
||||
public class GitHub2Api extends DefaultApi20 {
|
||||
private static final String AUTHORIZE_URL =
|
||||
"https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s";
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return "https://github.com/login/oauth/access_token";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return String.format(
|
||||
AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,132 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Singleton
|
||||
class GitHubOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = LoggerFactory.getLogger(GitHubOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-github-oauth";
|
||||
private static final String GITHUB_PROVIDER_PREFIX = "github-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL = "https://api.github.com/user";
|
||||
|
||||
private static final String SCOPE = "user:email";
|
||||
private final boolean fixLegacyUserId;
|
||||
private final OAuthService service;
|
||||
|
||||
@Inject
|
||||
GitHubOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(GitHub2Api.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.scope(SCOPE)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
Response response = request.send();
|
||||
if (response.getCode() != HttpServletResponse.SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get("id");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain id field");
|
||||
}
|
||||
JsonElement email = jsonObject.get("email");
|
||||
JsonElement name = jsonObject.get("name");
|
||||
JsonElement login = jsonObject.get("login");
|
||||
return new OAuthUserInfo(
|
||||
GITHUB_PROVIDER_PREFIX + id.getAsString(),
|
||||
login == null || login.isJsonNull() ? null : login.getAsString(),
|
||||
email == null || email.isJsonNull() ? null : email.getAsString(),
|
||||
name == null || name.isJsonNull() ? null : name.getAsString(),
|
||||
fixLegacyUserId ? id.getAsString() : null);
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "GitHub OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
|
||||
public class GitLabApi extends DefaultApi20 {
|
||||
private static final String AUTHORIZE_URL =
|
||||
"%s/oauth/authorize?client_id=%s&response_type=code&redirect_uri=%s";
|
||||
|
||||
private final String rootUrl;
|
||||
|
||||
public GitLabApi(String rootUrl) {
|
||||
this.rootUrl = rootUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return String.format(AUTHORIZE_URL, rootUrl, config.getApiKey(), config.getCallback());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return String.format("%s/oauth/token", rootUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return OAuth2AccessTokenJsonExtractor.instance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,126 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
||||
import static org.slf4j.LoggerFactory.getLogger;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@Singleton
|
||||
public class GitLabOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = getLogger(GitLabOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-gitlab-oauth";
|
||||
private static final String PROTECTED_RESOURCE_URL = "%s/api/v3/user";
|
||||
private static final String GITLAB_PROVIDER_PREFIX = "gitlab-oauth:";
|
||||
private final OAuthService service;
|
||||
private final String rootUrl;
|
||||
|
||||
@Inject
|
||||
GitLabOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
rootUrl = cfg.getString(InitOAuth.ROOT_URL);
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(new GitLabApi(rootUrl))
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
final String protectedResourceUrl = String.format(PROTECTED_RESOURCE_URL, rootUrl);
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, protectedResourceUrl);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
|
||||
Response response = request.send();
|
||||
if (response.getCode() != SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
if (jsonObject == null || jsonObject.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain 'user' field" + jsonObject);
|
||||
}
|
||||
JsonElement id = jsonObject.get("id");
|
||||
JsonElement username = jsonObject.get("username");
|
||||
JsonElement email = jsonObject.get("email");
|
||||
JsonElement name = jsonObject.get("name");
|
||||
return new OAuthUserInfo(
|
||||
GITLAB_PROVIDER_PREFIX + id.getAsString(),
|
||||
username == null || username.isJsonNull() ? null : username.getAsString(),
|
||||
email == null || email.isJsonNull() ? null : email.getAsString(),
|
||||
name == null || name.isJsonNull() ? null : name.getAsString(),
|
||||
null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "GitLab OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static org.scribe.utils.OAuthEncoder.encode;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.scribe.utils.Preconditions;
|
||||
|
||||
// Source: https://github.com/FeedTheCoffers/scribe-java-extras
|
||||
// License: Apache 2
|
||||
// https://github.com/FeedTheCoffers/scribe-java-extras/blob/master/pom.xml
|
||||
public class Google2Api extends DefaultApi20 {
|
||||
private static final String AUTHORIZE_URL =
|
||||
"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%s&redirect_uri=%s&scope=%s";
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return "https://accounts.google.com/o/oauth2/token";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
Preconditions.checkValidUrl(
|
||||
config.getCallback(), "Must provide a valid url as callback. Google does not support OOB");
|
||||
Preconditions.checkEmptyString(
|
||||
config.getScope(), "Must provide a valid value as scope. Google does not support no scope");
|
||||
|
||||
return String.format(
|
||||
AUTHORIZE_URL, config.getApiKey(), encode(config.getCallback()), encode(config.getScope()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return OAuth2AccessTokenJsonExtractor.instance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,233 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Singleton
|
||||
class GoogleOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = LoggerFactory.getLogger(GoogleOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-google-oauth";
|
||||
private static final String GOOGLE_PROVIDER_PREFIX = "google-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL =
|
||||
"https://www.googleapis.com/oauth2/v2/userinfo";
|
||||
private static final String SCOPE = "email profile";
|
||||
private final OAuthService service;
|
||||
private final String canonicalWebUrl;
|
||||
private final List<String> domains;
|
||||
private final boolean useEmailAsUsername;
|
||||
private final boolean fixLegacyUserId;
|
||||
|
||||
@Inject
|
||||
GoogleOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
this.canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
if (cfg.getBoolean(InitOAuth.LINK_TO_EXISTING_OPENID_ACCOUNT, false)) {
|
||||
log.warn(
|
||||
String.format(
|
||||
"The support for: %s is disconinued", InitOAuth.LINK_TO_EXISTING_OPENID_ACCOUNT));
|
||||
}
|
||||
fixLegacyUserId = cfg.getBoolean(InitOAuth.FIX_LEGACY_USER_ID, false);
|
||||
this.domains = Arrays.asList(cfg.getStringList(InitOAuth.DOMAIN));
|
||||
this.useEmailAsUsername = cfg.getBoolean(InitOAuth.USE_EMAIL_AS_USERNAME, false);
|
||||
this.service =
|
||||
new ServiceBuilder()
|
||||
.provider(Google2Api.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.scope(SCOPE)
|
||||
.build();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("OAuth2: canonicalWebUrl={}", canonicalWebUrl);
|
||||
log.debug("OAuth2: scope={}", SCOPE);
|
||||
log.debug("OAuth2: domains={}", domains);
|
||||
log.debug("OAuth2: useEmailAsUsername={}", useEmailAsUsername);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
Response response = request.send();
|
||||
if (response.getCode() != HttpServletResponse.SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get("id");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain id field");
|
||||
}
|
||||
JsonElement email = jsonObject.get("email");
|
||||
JsonElement name = jsonObject.get("name");
|
||||
String login = null;
|
||||
|
||||
if (domains.size() > 0) {
|
||||
boolean domainMatched = false;
|
||||
JsonObject jwtToken = retrieveJWTToken(token);
|
||||
String hdClaim = retrieveHostedDomain(jwtToken);
|
||||
for (String domain : domains) {
|
||||
if (domain.equalsIgnoreCase(hdClaim)) {
|
||||
domainMatched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!domainMatched) {
|
||||
// TODO(davido): improve error reporting in OAuth extension point
|
||||
log.error("Error: hosted domain validation failed: {}", Strings.nullToEmpty(hdClaim));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (useEmailAsUsername && !email.isJsonNull()) {
|
||||
login = email.getAsString().split("@")[0];
|
||||
}
|
||||
return new OAuthUserInfo(
|
||||
GOOGLE_PROVIDER_PREFIX + id.getAsString() /*externalId*/,
|
||||
login /*username*/,
|
||||
email == null || email.isJsonNull() ? null : email.getAsString() /*email*/,
|
||||
name == null || name.isJsonNull() ? null : name.getAsString() /*displayName*/,
|
||||
fixLegacyUserId ? id.getAsString() : null /*claimedIdentity*/);
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
private JsonObject retrieveJWTToken(OAuthToken token) {
|
||||
JsonElement idToken = JSON.newGson().fromJson(token.getRaw(), JsonElement.class);
|
||||
if (idToken != null && idToken.isJsonObject()) {
|
||||
JsonObject idTokenObj = idToken.getAsJsonObject();
|
||||
JsonElement idTokenElement = idTokenObj.get("id_token");
|
||||
if (idTokenElement != null && !idTokenElement.isJsonNull()) {
|
||||
String payload = decodePayload(idTokenElement.getAsString());
|
||||
if (!Strings.isNullOrEmpty(payload)) {
|
||||
JsonElement tokenJsonElement = JSON.newGson().fromJson(payload, JsonElement.class);
|
||||
if (tokenJsonElement.isJsonObject()) {
|
||||
return tokenJsonElement.getAsJsonObject();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String retrieveHostedDomain(JsonObject jwtToken) {
|
||||
JsonElement hdClaim = jwtToken.get("hd");
|
||||
if (hdClaim != null && !hdClaim.isJsonNull()) {
|
||||
String hd = hdClaim.getAsString();
|
||||
log.debug("OAuth2: hd={}", hd);
|
||||
return hd;
|
||||
}
|
||||
log.debug("OAuth2: JWT doesn't contain hd element");
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode payload from JWT according to spec: "header.payload.signature"
|
||||
*
|
||||
* @param idToken Base64 encoded tripple, separated with dot
|
||||
* @return openid_id part of payload, when contained, null otherwise
|
||||
*/
|
||||
private static String decodePayload(String idToken) {
|
||||
Preconditions.checkNotNull(idToken);
|
||||
String[] jwtParts = idToken.split("\\.");
|
||||
Preconditions.checkState(jwtParts.length == 3);
|
||||
String payloadStr = jwtParts[1];
|
||||
Preconditions.checkNotNull(payloadStr);
|
||||
return new String(Base64.decodeBase64(payloadStr));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
String url = service.getAuthorizationUrl(null);
|
||||
try {
|
||||
if (domains.size() == 1) {
|
||||
url += "&hd=" + URLEncoder.encode(domains.get(0), StandardCharsets.UTF_8.name());
|
||||
} else if (domains.size() > 1) {
|
||||
url += "&hd=*";
|
||||
}
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("OAuth2: authorization URL={}", url);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Google OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import com.google.gerrit.extensions.annotations.Exports;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.servlet.ServletModule;
|
||||
|
||||
class HttpModule extends ServletModule {
|
||||
|
||||
private final PluginConfigFactory cfgFactory;
|
||||
private final String pluginName;
|
||||
|
||||
@Inject
|
||||
HttpModule(PluginConfigFactory cfgFactory, @PluginName String pluginName) {
|
||||
this.cfgFactory = cfgFactory;
|
||||
this.pluginName = pluginName;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureServlets() {
|
||||
PluginConfig cfg =
|
||||
cfgFactory.getFromGerritConfig(pluginName + GoogleOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(GoogleOAuthService.CONFIG_SUFFIX))
|
||||
.to(GoogleOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + GitHubOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(GitHubOAuthService.CONFIG_SUFFIX))
|
||||
.to(GitHubOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + BitbucketOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(BitbucketOAuthService.CONFIG_SUFFIX))
|
||||
.to(BitbucketOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + CasOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(CasOAuthService.CONFIG_SUFFIX))
|
||||
.to(CasOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + FacebookOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(FacebookOAuthService.CONFIG_SUFFIX))
|
||||
.to(FacebookOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + GitLabOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(GitLabOAuthService.CONFIG_SUFFIX))
|
||||
.to(GitLabOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + DexOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(DexOAuthService.CONFIG_SUFFIX))
|
||||
.to(DexOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + KeycloakOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(KeycloakOAuthService.CONFIG_SUFFIX))
|
||||
.to(KeycloakOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + Office365OAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(Office365OAuthService.CONFIG_SUFFIX))
|
||||
.to(Office365OAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(WarsawHackerspaceOAuthService.CONFIG_SUFFIX))
|
||||
.to(WarsawHackerspaceOAuthService.class);
|
||||
}
|
||||
|
||||
cfg = cfgFactory.getFromGerritConfig(pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
|
||||
if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
|
||||
bind(OAuthServiceProvider.class)
|
||||
.annotatedWith(Exports.named(WarsawHackerspaceOAuthService.CONFIG_SUFFIX))
|
||||
.to(WarsawHackerspaceOAuthService.class);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,161 @@
|
|||
// Copyright (C) 2015 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.pgm.init.api.ConsoleUI;
|
||||
import com.google.gerrit.pgm.init.api.InitStep;
|
||||
import com.google.gerrit.pgm.init.api.Section;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
class InitOAuth implements InitStep {
|
||||
static final String PLUGIN_SECTION = "plugin";
|
||||
static final String CLIENT_ID = "client-id";
|
||||
static final String CLIENT_SECRET = "client-secret";
|
||||
static final String LINK_TO_EXISTING_OPENID_ACCOUNT = "link-to-existing-openid-accounts";
|
||||
static final String FIX_LEGACY_USER_ID = "fix-legacy-user-id";
|
||||
static final String DOMAIN = "domain";
|
||||
static final String USE_EMAIL_AS_USERNAME = "use-email-as-username";
|
||||
static final String ROOT_URL = "root-url";
|
||||
static final String REALM = "realm";
|
||||
static final String SERVICE_NAME = "service-name";
|
||||
static String FIX_LEGACY_USER_ID_QUESTION = "Fix legacy user id, without oauth provider prefix?";
|
||||
|
||||
private final ConsoleUI ui;
|
||||
private final Section googleOAuthProviderSection;
|
||||
private final Section githubOAuthProviderSection;
|
||||
private final Section bitbucketOAuthProviderSection;
|
||||
private final Section casOAuthProviderSection;
|
||||
private final Section facebookOAuthProviderSection;
|
||||
private final Section gitlabOAuthProviderSection;
|
||||
private final Section dexOAuthProviderSection;
|
||||
private final Section keycloakOAuthProviderSection;
|
||||
private final Section office365OAuthProviderSection;
|
||||
private final Section airVantageOAuthProviderSection;
|
||||
private final Section warsawHackerspaceOAuthProviderSection;
|
||||
|
||||
@Inject
|
||||
InitOAuth(ConsoleUI ui, Section.Factory sections, @PluginName String pluginName) {
|
||||
this.ui = ui;
|
||||
this.googleOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + GoogleOAuthService.CONFIG_SUFFIX);
|
||||
this.githubOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + GitHubOAuthService.CONFIG_SUFFIX);
|
||||
this.bitbucketOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + BitbucketOAuthService.CONFIG_SUFFIX);
|
||||
this.casOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + CasOAuthService.CONFIG_SUFFIX);
|
||||
this.facebookOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + FacebookOAuthService.CONFIG_SUFFIX);
|
||||
this.gitlabOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + GitLabOAuthService.CONFIG_SUFFIX);
|
||||
this.dexOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + DexOAuthService.CONFIG_SUFFIX);
|
||||
this.keycloakOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + KeycloakOAuthService.CONFIG_SUFFIX);
|
||||
this.office365OAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + Office365OAuthService.CONFIG_SUFFIX);
|
||||
this.airVantageOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + AirVantageOAuthService.CONFIG_SUFFIX);
|
||||
this.warsawHackerspaceOAuthProviderSection =
|
||||
sections.get(PLUGIN_SECTION, pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
ui.header("OAuth Authentication Provider");
|
||||
|
||||
boolean configureGoogleOAuthProvider =
|
||||
ui.yesno(true, "Use Google OAuth provider for Gerrit login ?");
|
||||
if (configureGoogleOAuthProvider) {
|
||||
configureOAuth(googleOAuthProviderSection);
|
||||
googleOAuthProviderSection.string(FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
|
||||
}
|
||||
|
||||
boolean configueGitHubOAuthProvider =
|
||||
ui.yesno(true, "Use GitHub OAuth provider for Gerrit login ?");
|
||||
if (configueGitHubOAuthProvider) {
|
||||
configureOAuth(githubOAuthProviderSection);
|
||||
githubOAuthProviderSection.string(FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
|
||||
}
|
||||
|
||||
boolean configureBitbucketOAuthProvider =
|
||||
ui.yesno(true, "Use Bitbucket OAuth provider for Gerrit login ?");
|
||||
if (configureBitbucketOAuthProvider) {
|
||||
configureOAuth(bitbucketOAuthProviderSection);
|
||||
bitbucketOAuthProviderSection.string(
|
||||
FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
|
||||
}
|
||||
|
||||
boolean configureCasOAuthProvider = ui.yesno(true, "Use CAS OAuth provider for Gerrit login ?");
|
||||
if (configureCasOAuthProvider) {
|
||||
casOAuthProviderSection.string("CAS Root URL", ROOT_URL, null);
|
||||
configureOAuth(casOAuthProviderSection);
|
||||
casOAuthProviderSection.string(FIX_LEGACY_USER_ID_QUESTION, FIX_LEGACY_USER_ID, "false");
|
||||
}
|
||||
|
||||
boolean configueFacebookOAuthProvider =
|
||||
ui.yesno(true, "Use Facebook OAuth provider for Gerrit login ?");
|
||||
if (configueFacebookOAuthProvider) {
|
||||
configureOAuth(facebookOAuthProviderSection);
|
||||
}
|
||||
|
||||
boolean configureGitLabOAuthProvider =
|
||||
ui.yesno(true, "Use GitLab OAuth provider for Gerrit login ?");
|
||||
if (configureGitLabOAuthProvider) {
|
||||
gitlabOAuthProviderSection.string("GitLab Root URL", ROOT_URL, null);
|
||||
configureOAuth(gitlabOAuthProviderSection);
|
||||
}
|
||||
|
||||
boolean configureDexOAuthProvider = ui.yesno(true, "Use Dex OAuth provider for Gerrit login ?");
|
||||
if (configureDexOAuthProvider) {
|
||||
dexOAuthProviderSection.string("Dex Root URL", ROOT_URL, null);
|
||||
configureOAuth(dexOAuthProviderSection);
|
||||
}
|
||||
|
||||
boolean configureKeycloakOAuthProvider =
|
||||
ui.yesno(true, "Use Keycloak OAuth provider for Gerrit login ?");
|
||||
if (configureKeycloakOAuthProvider) {
|
||||
keycloakOAuthProviderSection.string("Keycloak Root URL", ROOT_URL, null);
|
||||
keycloakOAuthProviderSection.string("Keycloak Realm", REALM, null);
|
||||
configureOAuth(keycloakOAuthProviderSection);
|
||||
}
|
||||
|
||||
boolean configureOffice365OAuthProvider =
|
||||
ui.yesno(true, "Use Office365 OAuth provider for Gerrit login ?");
|
||||
if (configureOffice365OAuthProvider) {
|
||||
configureOAuth(office365OAuthProviderSection);
|
||||
}
|
||||
|
||||
boolean configureAirVantageOAuthProvider =
|
||||
ui.yesno(true, "Use AirVantage OAuth provider for Gerrit login ?");
|
||||
if (configureAirVantageOAuthProvider) {
|
||||
configureOAuth(airVantageOAuthProviderSection);
|
||||
}
|
||||
|
||||
boolean configureWarsawHackerspaceOAuthProvider =
|
||||
ui.yesno(true, "Use Warsaw Hackerspace OAuth provider for Gerrit login?");
|
||||
if (configureWarsawHackerspaceOAuthProvider) {
|
||||
configureOAuth(warsawHackerspaceOAuthProviderSection);
|
||||
}
|
||||
}
|
||||
|
||||
private void configureOAuth(Section s) {
|
||||
s.string("Application client id", CLIENT_ID, null);
|
||||
s.passwordForKey("Application client secret", CLIENT_SECRET);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postRun() throws Exception {}
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.extractors.JsonTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.scribe.utils.OAuthEncoder;
|
||||
|
||||
public class KeycloakApi extends DefaultApi20 {
|
||||
|
||||
private static final String AUTHORIZE_URL =
|
||||
"%s/auth/realms/%s/protocol/openid-connect/auth?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
|
||||
|
||||
private final String rootUrl;
|
||||
private final String realm;
|
||||
|
||||
public KeycloakApi(String rootUrl, String realm) {
|
||||
this.rootUrl = rootUrl;
|
||||
this.realm = realm;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
return String.format(
|
||||
AUTHORIZE_URL,
|
||||
rootUrl,
|
||||
realm,
|
||||
config.getApiKey(),
|
||||
OAuthEncoder.encode(config.getCallback()),
|
||||
config.getScope().replaceAll(" ", "+"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return String.format("%s/auth/realms/%s/protocol/openid-connect/token", rootUrl, realm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return new JsonTokenExtractor();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,138 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import java.io.IOException;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class KeycloakOAuthService implements OAuthServiceProvider {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(KeycloakOAuthService.class);
|
||||
|
||||
static final String CONFIG_SUFFIX = "-keycloak-oauth";
|
||||
private static final String KEYCLOAK_PROVIDER_PREFIX = "keycloak-oauth:";
|
||||
private final OAuthService service;
|
||||
private final String serviceName;
|
||||
|
||||
@Inject
|
||||
KeycloakOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
|
||||
String rootUrl = cfg.getString(InitOAuth.ROOT_URL);
|
||||
String realm = cfg.getString(InitOAuth.REALM);
|
||||
serviceName = cfg.getString(InitOAuth.SERVICE_NAME, "Keycloak OAuth2");
|
||||
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(new KeycloakApi(rootUrl, realm))
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.scope("openid")
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
private String parseJwt(String input) {
|
||||
String[] parts = input.split("\\.");
|
||||
Preconditions.checkState(parts.length == 3);
|
||||
Preconditions.checkNotNull(parts[1]);
|
||||
return new String(Base64.decodeBase64(parts[1]));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
JsonElement tokenJson = JSON.newGson().fromJson(token.getRaw(), JsonElement.class);
|
||||
JsonObject tokenObject = tokenJson.getAsJsonObject();
|
||||
JsonElement id_token = tokenObject.get("id_token");
|
||||
|
||||
JsonElement claimJson =
|
||||
JSON.newGson().fromJson(parseJwt(id_token.getAsString()), JsonElement.class);
|
||||
|
||||
JsonObject claimObject = claimJson.getAsJsonObject();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Claim object: {}", claimObject);
|
||||
}
|
||||
JsonElement usernameElement = claimObject.get("preferred_username");
|
||||
JsonElement emailElement = claimObject.get("email");
|
||||
JsonElement nameElement = claimObject.get("name");
|
||||
if (usernameElement == null || usernameElement.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain preferred_username field");
|
||||
}
|
||||
if (emailElement == null || emailElement.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain email field");
|
||||
}
|
||||
if (nameElement == null || nameElement.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain name field");
|
||||
}
|
||||
String username = usernameElement.getAsString();
|
||||
String email = emailElement.getAsString();
|
||||
String name = nameElement.getAsString();
|
||||
|
||||
return new OAuthUserInfo(
|
||||
KEYCLOAK_PROVIDER_PREFIX + username /*externalId*/,
|
||||
username /*username*/,
|
||||
email /*email*/,
|
||||
name /*displayName*/,
|
||||
null /*claimedIdentity*/);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return serviceName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import com.google.gerrit.extensions.annotations.Exports;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
public class Module extends AbstractModule {
|
||||
private final String pluginName;
|
||||
|
||||
@Inject
|
||||
Module(@PluginName String pluginName) {
|
||||
this.pluginName = pluginName;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(OAuthLoginProvider.class)
|
||||
.annotatedWith(Exports.named(pluginName))
|
||||
.to(DisabledOAuthLoginProvider.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,93 @@
|
|||
// Copyright (C) 2017 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static org.slf4j.LoggerFactory.getLogger;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.OAuthConstants;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/** TODO(gildur): remove when updating to newer scribe lib */
|
||||
final class OAuth20ServiceImpl implements OAuthService {
|
||||
private static final Logger log = getLogger(OAuth20ServiceImpl.class);
|
||||
|
||||
private static final String VERSION = "2.0";
|
||||
|
||||
private static final String GRANT_TYPE = "grant_type";
|
||||
private static final String GRANT_TYPE_VALUE = "authorization_code";
|
||||
|
||||
private final DefaultApi20 api;
|
||||
private final OAuthConfig config;
|
||||
|
||||
/**
|
||||
* Default constructor
|
||||
*
|
||||
* @param api OAuth2.0 api information
|
||||
* @param config OAuth 2.0 configuration param object
|
||||
*/
|
||||
public OAuth20ServiceImpl(DefaultApi20 api, OAuthConfig config) {
|
||||
this.api = api;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Token getAccessToken(Token requestToken, Verifier verifier) {
|
||||
OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
|
||||
request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
|
||||
request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
|
||||
request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
|
||||
request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
|
||||
if (config.hasScope()) {
|
||||
request.addBodyParameter(OAuthConstants.SCOPE, config.getScope());
|
||||
}
|
||||
request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_VALUE);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Access token request: {}", request);
|
||||
}
|
||||
Response response = request.send();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Access token response: {}", response.getBody());
|
||||
}
|
||||
return api.getAccessTokenExtractor().extract(response.getBody());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Token getRequestToken() {
|
||||
throw new UnsupportedOperationException(
|
||||
"Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return VERSION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void signRequest(Token accessToken, OAuthRequest request) {
|
||||
request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(Token requestToken) {
|
||||
return api.getAuthorizationUrl(config);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static org.scribe.model.OAuthConstants.ACCESS_TOKEN;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.scribe.exceptions.OAuthException;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.utils.Preconditions;
|
||||
|
||||
class OAuth2AccessTokenJsonExtractor implements AccessTokenExtractor {
|
||||
private static final Pattern ACCESS_TOKEN_REGEX_PATTERN =
|
||||
Pattern.compile("\"" + ACCESS_TOKEN + "\"\\s*:\\s*\"(\\S*?)\"");
|
||||
|
||||
private OAuth2AccessTokenJsonExtractor() {}
|
||||
|
||||
private static final AccessTokenExtractor INSTANCE = new OAuth2AccessTokenJsonExtractor();
|
||||
|
||||
static AccessTokenExtractor instance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@Override
|
||||
public Token extract(String response) {
|
||||
Preconditions.checkEmptyString(response, "Cannot extract a token from a null or empty String");
|
||||
Matcher matcher = ACCESS_TOKEN_REGEX_PATTERN.matcher(response);
|
||||
if (matcher.find()) {
|
||||
return new Token(matcher.group(1), "", response);
|
||||
}
|
||||
throw new OAuthException("Cannot extract an access token. Response was: " + response);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static org.scribe.utils.OAuthEncoder.encode;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.scribe.utils.Preconditions;
|
||||
|
||||
public class Office365Api extends DefaultApi20 {
|
||||
private static final String AUTHORIZE_URL =
|
||||
"https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=%s";
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return "https://login.microsoftonline.com/organizations/oauth2/v2.0/token";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
Preconditions.checkValidUrl(
|
||||
config.getCallback(),
|
||||
"Must provide a valid url as callback. Office365 does not support OOB");
|
||||
Preconditions.checkEmptyString(
|
||||
config.getScope(),
|
||||
"Must provide a valid value as scope. Office365 does not support no scope");
|
||||
|
||||
return String.format(
|
||||
AUTHORIZE_URL, config.getApiKey(), encode(config.getCallback()), encode(config.getScope()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return OAuth2AccessTokenJsonExtractor.instance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Singleton
|
||||
class Office365OAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = LoggerFactory.getLogger(Office365OAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-office365-oauth";
|
||||
private static final String OFFICE365_PROVIDER_PREFIX = "office365-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL = "https://graph.microsoft.com/v1.0/me";
|
||||
private static final String SCOPE =
|
||||
"openid offline_access https://graph.microsoft.com/user.readbasic.all";
|
||||
private final OAuthService service;
|
||||
private final String canonicalWebUrl;
|
||||
private final boolean useEmailAsUsername;
|
||||
|
||||
@Inject
|
||||
Office365OAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
this.canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
this.useEmailAsUsername = cfg.getBoolean(InitOAuth.USE_EMAIL_AS_USERNAME, false);
|
||||
this.service =
|
||||
new ServiceBuilder()
|
||||
.provider(Office365Api.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.scope(SCOPE)
|
||||
.build();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("OAuth2: canonicalWebUrl={}", canonicalWebUrl);
|
||||
log.debug("OAuth2: scope={}", SCOPE);
|
||||
log.debug("OAuth2: useEmailAsUsername={}", useEmailAsUsername);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
request.addHeader("Accept", "*/*");
|
||||
request.addHeader("Authorization", "Bearer " + token.getToken());
|
||||
Response response = request.send();
|
||||
if (response.getCode() != HttpServletResponse.SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get("id");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain id field");
|
||||
}
|
||||
JsonElement email = jsonObject.get("mail");
|
||||
JsonElement name = jsonObject.get("displayName");
|
||||
String login = null;
|
||||
|
||||
if (useEmailAsUsername && !email.isJsonNull()) {
|
||||
login = email.getAsString().split("@")[0];
|
||||
}
|
||||
return new OAuthUserInfo(
|
||||
OFFICE365_PROVIDER_PREFIX + id.getAsString() /*externalId*/,
|
||||
login /*username*/,
|
||||
email == null || email.isJsonNull() ? null : email.getAsString() /*email*/,
|
||||
name == null || name.isJsonNull() ? null : name.getAsString() /*displayName*/,
|
||||
null);
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
OAuthToken result = new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
String url = service.getAuthorizationUrl(null);
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Office365 OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
// Copyright (C) 2019 Serge Bazanski <q3k@hackerspace.pl>
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static java.lang.String.format;
|
||||
import static org.scribe.utils.OAuthEncoder.encode;
|
||||
|
||||
import org.scribe.builder.api.DefaultApi20;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.extractors.JsonTokenExtractor;
|
||||
import org.scribe.model.OAuthConfig;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.scribe.utils.Preconditions;
|
||||
|
||||
public class WarsawHackerspaceApi extends DefaultApi20 {
|
||||
|
||||
private static final String AUTHORIZE_URL =
|
||||
"https://sso.hackerspace.pl/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s";
|
||||
private static final String ACCESS_TOKEN_ENDPOINT = "https://sso.hackerspace.pl/oauth/token";
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl(OAuthConfig config) {
|
||||
Preconditions.checkValidUrl(
|
||||
config.getCallback(),
|
||||
"Must provide a valid url as callback. Warsaw Hackerspace SSO does not support OOB");
|
||||
Preconditions.checkEmptyString(
|
||||
config.getScope(),
|
||||
"Must provide a valid value as scope. Warsaw Hackerspace SSO does not support no scope");
|
||||
return format(AUTHORIZE_URL, config.getApiKey(), encode(config.getScope()), encode(config.getCallback()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenEndpoint() {
|
||||
return ACCESS_TOKEN_ENDPOINT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Verb getAccessTokenVerb() {
|
||||
return Verb.POST;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessTokenExtractor getAccessTokenExtractor() {
|
||||
return new JsonTokenExtractor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthService createService(OAuthConfig config) {
|
||||
return new OAuth20ServiceImpl(this, config);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,128 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
// Copyright (C) 2019 Serge Bazanski <q3k@hackerspace.pl>
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static com.google.gerrit.json.OutputFormat.JSON;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_OK;
|
||||
import static org.slf4j.LoggerFactory.getLogger;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.gerrit.extensions.annotations.PluginName;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthToken;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo;
|
||||
import com.google.gerrit.extensions.auth.oauth.OAuthVerifier;
|
||||
import com.google.gerrit.server.config.CanonicalWebUrl;
|
||||
import com.google.gerrit.server.config.PluginConfig;
|
||||
import com.google.gerrit.server.config.PluginConfigFactory;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Singleton;
|
||||
import java.io.IOException;
|
||||
import org.scribe.builder.ServiceBuilder;
|
||||
import org.scribe.model.OAuthRequest;
|
||||
import org.scribe.model.Response;
|
||||
import org.scribe.model.Token;
|
||||
import org.scribe.model.Verb;
|
||||
import org.scribe.model.Verifier;
|
||||
import org.scribe.oauth.OAuthService;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
@Singleton
|
||||
public class WarsawHackerspaceOAuthService implements OAuthServiceProvider {
|
||||
private static final Logger log = getLogger(WarsawHackerspaceOAuthService.class);
|
||||
static final String CONFIG_SUFFIX = "-warsawhackerspace-oauth";
|
||||
private static final String HSWAW_PROVIDER_PREFIX = "warsawhackerspace-oauth:";
|
||||
private static final String PROTECTED_RESOURCE_URL =
|
||||
"https://sso.hackerspace.pl/api/1/userinfo";
|
||||
private final OAuthService service;
|
||||
|
||||
@Inject
|
||||
WarsawHackerspaceOAuthService(
|
||||
PluginConfigFactory cfgFactory,
|
||||
@PluginName String pluginName,
|
||||
@CanonicalWebUrl Provider<String> urlProvider) {
|
||||
PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
|
||||
String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
|
||||
|
||||
service =
|
||||
new ServiceBuilder()
|
||||
.provider(WarsawHackerspaceApi.class)
|
||||
.apiKey(cfg.getString(InitOAuth.CLIENT_ID))
|
||||
.apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
|
||||
.scope("profile:read")
|
||||
.callback(canonicalWebUrl + "oauth")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
|
||||
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
|
||||
Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
|
||||
service.signRequest(t, request);
|
||||
Response response = request.send();
|
||||
if (response.getCode() != SC_OK) {
|
||||
throw new IOException(
|
||||
String.format(
|
||||
"Status %s (%s) for request %s",
|
||||
response.getCode(), response.getBody(), request.getUrl()));
|
||||
}
|
||||
JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User info response: {}", response.getBody());
|
||||
}
|
||||
if (userJson.isJsonObject()) {
|
||||
JsonObject jsonObject = userJson.getAsJsonObject();
|
||||
JsonElement id = jsonObject.get("sub");
|
||||
if (id == null || id.isJsonNull()) {
|
||||
throw new IOException("Response doesn't contain uid field");
|
||||
}
|
||||
JsonElement email = jsonObject.get("email");
|
||||
return new OAuthUserInfo(
|
||||
HSWAW_PROVIDER_PREFIX + id.getAsString(),
|
||||
id.getAsString(),
|
||||
email.getAsString(),
|
||||
id.getAsString(),
|
||||
id.getAsString());
|
||||
}
|
||||
|
||||
throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthToken getAccessToken(OAuthVerifier rv) {
|
||||
Verifier vi = new Verifier(rv.getValue());
|
||||
Token to = service.getAccessToken(null, vi);
|
||||
return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthorizationUrl() {
|
||||
return service.getAuthorizationUrl(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return service.getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Warsaw Hackerspace OAuth2";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
// Copyright (C) 2018 The Android Open Source Project
|
||||
//
|
||||
// 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.
|
||||
|
||||
package com.googlesource.gerrit.plugins.oauth;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.scribe.model.OAuthConstants.ACCESS_TOKEN;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.scribe.exceptions.OAuthException;
|
||||
import org.scribe.extractors.AccessTokenExtractor;
|
||||
import org.scribe.model.Token;
|
||||
|
||||
public class OAuth2AccessTokenJsonExtractorTest {
|
||||
private static final AccessTokenExtractor extractor = OAuth2AccessTokenJsonExtractor.instance();
|
||||
private static final String TOKEN = "I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X";
|
||||
private static final String RESPONSE = "{\"" + ACCESS_TOKEN + "\":\"" + TOKEN + "\"}'";
|
||||
private static final String RESPONSE_NON_JSON = ACCESS_TOKEN + "=" + TOKEN;
|
||||
private static final String RESPONSE_WITH_BLANKS =
|
||||
"{ \"" + ACCESS_TOKEN + "\" : \"" + TOKEN + "\"}'";
|
||||
private static final String MESSAGE = "Cannot extract a token from a null or empty String";
|
||||
|
||||
@Rule public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void parseResponse() throws Exception {
|
||||
Token token = extractor.extract(RESPONSE);
|
||||
assertEquals(token.getToken(), TOKEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseResponseWithBlanks() throws Exception {
|
||||
Token token = extractor.extract(RESPONSE_WITH_BLANKS);
|
||||
assertEquals(token.getToken(), TOKEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failParseNonJsonResponse() throws Exception {
|
||||
exception.expect(OAuthException.class);
|
||||
exception.expectMessage("Cannot extract an access token. Response was: " + RESPONSE_NON_JSON);
|
||||
extractor.extract(RESPONSE_NON_JSON);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldThrowExceptionIfForNullParameter() throws Exception {
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage(MESSAGE);
|
||||
extractor.extract(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldThrowExceptionIfForEmptyString() throws Exception {
|
||||
exception.expect(IllegalArgumentException.class);
|
||||
exception.expectMessage(MESSAGE);
|
||||
extractor.extract("");
|
||||
}
|
||||
}
|
1
app/gerrit/gerrit-oauth-provider/tools/bzl/BUILD
Normal file
1
app/gerrit/gerrit-oauth-provider/tools/bzl/BUILD
Normal file
|
@ -0,0 +1 @@
|
|||
# Empty file required by Bazel
|
6
app/gerrit/gerrit-oauth-provider/tools/bzl/classpath.bzl
Normal file
6
app/gerrit/gerrit-oauth-provider/tools/bzl/classpath.bzl
Normal file
|
@ -0,0 +1,6 @@
|
|||
load(
|
||||
"@com_googlesource_gerrit_bazlets//tools:classpath.bzl",
|
||||
_classpath_collector = "classpath_collector",
|
||||
)
|
||||
|
||||
classpath_collector = _classpath_collector
|
6
app/gerrit/gerrit-oauth-provider/tools/bzl/junit.bzl
Normal file
6
app/gerrit/gerrit-oauth-provider/tools/bzl/junit.bzl
Normal file
|
@ -0,0 +1,6 @@
|
|||
load(
|
||||
"@com_googlesource_gerrit_bazlets//tools:junit.bzl",
|
||||
_junit_tests = "junit_tests",
|
||||
)
|
||||
|
||||
junit_tests = _junit_tests
|
3
app/gerrit/gerrit-oauth-provider/tools/bzl/maven_jar.bzl
Normal file
3
app/gerrit/gerrit-oauth-provider/tools/bzl/maven_jar.bzl
Normal file
|
@ -0,0 +1,3 @@
|
|||
load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", _maven_jar = "maven_jar")
|
||||
|
||||
maven_jar = _maven_jar
|
10
app/gerrit/gerrit-oauth-provider/tools/bzl/plugin.bzl
Normal file
10
app/gerrit/gerrit-oauth-provider/tools/bzl/plugin.bzl
Normal file
|
@ -0,0 +1,10 @@
|
|||
load(
|
||||
"@com_googlesource_gerrit_bazlets//:gerrit_plugin.bzl",
|
||||
_gerrit_plugin = "gerrit_plugin",
|
||||
_plugin_deps = "PLUGIN_DEPS",
|
||||
_plugin_test_deps = "PLUGIN_TEST_DEPS",
|
||||
)
|
||||
|
||||
gerrit_plugin = _gerrit_plugin
|
||||
PLUGIN_DEPS = _plugin_deps
|
||||
PLUGIN_TEST_DEPS = _plugin_test_deps
|
9
app/gerrit/gerrit-oauth-provider/tools/eclipse/BUILD
Normal file
9
app/gerrit/gerrit-oauth-provider/tools/eclipse/BUILD
Normal file
|
@ -0,0 +1,9 @@
|
|||
load("//app/gerrit/gerrit-oauth-provider/tools/bzl:classpath.bzl", "classpath_collector")
|
||||
|
||||
classpath_collector(
|
||||
name = "main_classpath_collect",
|
||||
testonly = 1,
|
||||
deps = [
|
||||
"//:gerrit-oauth-provider__plugin_test_deps",
|
||||
],
|
||||
)
|
15
app/gerrit/gerrit-oauth-provider/tools/eclipse/project.sh
Executable file
15
app/gerrit/gerrit-oauth-provider/tools/eclipse/project.sh
Executable file
|
@ -0,0 +1,15 @@
|
|||
#!/bin/bash
|
||||
# Copyright (C) 2017 The Android Open Source Project
|
||||
#
|
||||
# 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.
|
||||
`bazel query @com_googlesource_gerrit_bazlets//tools/eclipse:project --output location | sed s/BUILD:.*//`project.py -n oauth -r .
|
17
app/gerrit/gerrit-oauth-provider/tools/workspace-status.sh
Executable file
17
app/gerrit/gerrit-oauth-provider/tools/workspace-status.sh
Executable file
|
@ -0,0 +1,17 @@
|
|||
#!/bin/bash
|
||||
|
||||
# This script will be run by bazel when the build process starts to
|
||||
# generate key-value information that represents the status of the
|
||||
# workspace. The output should be like
|
||||
#
|
||||
# KEY1 VALUE1
|
||||
# KEY2 VALUE2
|
||||
#
|
||||
# If the script exits with non-zero code, it's considered as a failure
|
||||
# and the output will be discarded.
|
||||
|
||||
function rev() {
|
||||
cd $1; git describe --always --match "v[0-9].*" --dirty
|
||||
}
|
||||
|
||||
echo STABLE_BUILD_GERRIT-OAUTH-PROVIDER_LABEL $(rev .)
|
209
app/gerrit/kube/gerrit.libsonnet
Normal file
209
app/gerrit/kube/gerrit.libsonnet
Normal file
|
@ -0,0 +1,209 @@
|
|||
local kube = import "../../../kube/kube.libsonnet";
|
||||
|
||||
{
|
||||
local gerrit = self,
|
||||
local cfg = gerrit.cfg,
|
||||
|
||||
cfg:: {
|
||||
namespace: error "namespace must be set",
|
||||
appName: "gerrit",
|
||||
prefix: "", # if set, should be 'foo-'
|
||||
domain: error "domain must be set",
|
||||
identity: error "identity (UUID) must be set",
|
||||
|
||||
// The secret must contain a key named 'secure.config' containing (at least):
|
||||
// [auth]
|
||||
// registerEmailPrivateKey = <random>
|
||||
// [plugin "gerrit-oauth-provider-warsawhackerspace-oauth"]
|
||||
// client-id = foo
|
||||
// client-secret = bar
|
||||
// [sendemail]
|
||||
// smtpPass = foo
|
||||
// [receiveemail]
|
||||
// password = bar
|
||||
secureSecret: error "secure secret name must be set",
|
||||
|
||||
storageClass: error "storage class must be set",
|
||||
storageSize: {
|
||||
git: "50Gi", // Main storage for repositories and NoteDB.
|
||||
index: "10Gi", // Secondary Lucene index
|
||||
cache: "10Gi", // H2 cache databases
|
||||
db: "1Gi", // NoteDB is used, so database is basically empty (H2 accountPatchReviewDatabase)
|
||||
etc: "1Gi", // Random site stuff.
|
||||
},
|
||||
|
||||
email: {
|
||||
server: "mail.hackerspace.pl",
|
||||
username: "gerrit",
|
||||
address: "gerrit@hackerspace.pl",
|
||||
},
|
||||
|
||||
tag: "3.0.0-r7",
|
||||
image: "registry.k0.hswaw.net/app/gerrit:" + cfg.tag,
|
||||
resources: {
|
||||
requests: {
|
||||
cpu: "100m",
|
||||
memory: "500Mi",
|
||||
},
|
||||
limits: {
|
||||
cpu: "1",
|
||||
memory: "2Gi",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
name(suffix):: cfg.prefix + suffix,
|
||||
|
||||
metadata(component):: {
|
||||
namespace: cfg.namespace,
|
||||
labels: {
|
||||
"app.kubernetes.io/name": cfg.appName,
|
||||
"app.kubernetes.io/managed-by": "kubecfg",
|
||||
"app.kubernetes.io/component": "component",
|
||||
},
|
||||
},
|
||||
|
||||
configmap: kube.ConfigMap(gerrit.name("gerrit")) {
|
||||
metadata+: gerrit.metadata("configmap"),
|
||||
data: {
|
||||
"gerrit.config": |||
|
||||
[gerrit]
|
||||
basePath = git
|
||||
canonicalWebUrl = https://%(domain)s/
|
||||
serverId = %(identity)s
|
||||
|
||||
[container]
|
||||
javaOptions = -Djava.security.edg=file:/dev/./urandom
|
||||
|
||||
[auth]
|
||||
type = OAUTH
|
||||
gitBasicAuthPolicy = HTTP
|
||||
|
||||
[httpd]
|
||||
listenUrl = proxy-http://*:8080
|
||||
|
||||
[sshd]
|
||||
advertisedAddress = %(domain)s
|
||||
|
||||
[user]
|
||||
email = %(emailAddress)s
|
||||
|
||||
[sendemail]
|
||||
enable = true
|
||||
from = MIXED
|
||||
smtpServer = %(emailServer)s
|
||||
smtpServerPort = 465
|
||||
smtpEncryption = ssl
|
||||
smtpUser = %(emailUser)s
|
||||
|
||||
[receiveemail]
|
||||
protocol = IMAP
|
||||
host = %(emailServer)s
|
||||
username = %(emailUser)s
|
||||
encryption = TLS
|
||||
enableImapIdle = true
|
||||
|
||||
||| % {
|
||||
domain: cfg.domain,
|
||||
identity: cfg.identity,
|
||||
emailAddress: cfg.email.address,
|
||||
emailServer: cfg.email.server,
|
||||
emailUser: cfg.email.username,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
volumes: {
|
||||
[name]: kube.PersistentVolumeClaim(gerrit.name(name)) {
|
||||
metadata+: gerrit.metadata("storage"),
|
||||
spec+: {
|
||||
storageClassName: cfg.storageClassName,
|
||||
accessModes: ["ReadWriteOnce"],
|
||||
resources: {
|
||||
requests: {
|
||||
storage: cfg.storageSize[name],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for name in ["etc", "git", "index", "cache", "db"]
|
||||
},
|
||||
|
||||
local volumeMounts = {
|
||||
[name]: { mountPath: "/var/gerrit/%s" % name }
|
||||
for name in ["etc", "git", "index", "cache", "db"]
|
||||
} {
|
||||
// ConfigMap gets mounted here
|
||||
config: { mountPath: "/var/gerrit-config" },
|
||||
// SecureSecret gets mounted here
|
||||
secure: { mountPath: "/var/gerrit-secure" },
|
||||
},
|
||||
deployment: kube.Deployment(gerrit.name("gerrit")) {
|
||||
metadata+: gerrit.metadata("deployment"),
|
||||
spec+: {
|
||||
replicas: 1,
|
||||
template+: {
|
||||
spec+: {
|
||||
securityContext: {
|
||||
fsGroup: 1000, # gerrit uid
|
||||
},
|
||||
volumes_: {
|
||||
config: kube.ConfigMapVolume(gerrit.configmap),
|
||||
secure: { secret: { secretName: cfg.secureSecret} },
|
||||
} {
|
||||
[name]: kube.PersistentVolumeClaimVolume(gerrit.volumes[name])
|
||||
for name in ["etc", "git", "index", "cache", "db"]
|
||||
},
|
||||
containers_: {
|
||||
gerrit: kube.Container(gerrit.name("gerrit")) {
|
||||
image: cfg.image,
|
||||
ports_: {
|
||||
http: { containerPort: 8080 },
|
||||
ssh: { containerPort: 29418 },
|
||||
},
|
||||
resources: cfg.resources,
|
||||
volumeMounts_: volumeMounts,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
svc: kube.Service(gerrit.name("gerrit")) {
|
||||
metadata+: gerrit.metadata("service"),
|
||||
target_pod:: gerrit.deployment.spec.template,
|
||||
spec+: {
|
||||
ports: [
|
||||
{ name: "http", port: 80, targetPort: 8080, protocol: "TCP" },
|
||||
{ name: "ssh", port: 22, targetPort: 29418, protocol: "TCP" },
|
||||
],
|
||||
type: "ClusterIP",
|
||||
},
|
||||
},
|
||||
|
||||
ingress: kube.Ingress(gerrit.name("gerrit")) {
|
||||
metadata+: gerrit.metadata("ingress") {
|
||||
annotations+: {
|
||||
"kubernetes.io/tls-acme": "true",
|
||||
"certmanager.k8s.io/cluster-issuer": "letsencrypt-prod",
|
||||
"nginx.ingress.kubernetes.io/proxy-body-size": "0",
|
||||
},
|
||||
},
|
||||
spec+: {
|
||||
tls: [
|
||||
{ hosts: [cfg.domain], secretName: gerrit.name("acme") },
|
||||
],
|
||||
rules: [
|
||||
{
|
||||
host: cfg.domain,
|
||||
http: {
|
||||
paths: [
|
||||
{ path: "/", backend: gerrit.svc.name_port },
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
19
app/gerrit/kube/prod.jsonnet
Normal file
19
app/gerrit/kube/prod.jsonnet
Normal file
|
@ -0,0 +1,19 @@
|
|||
local kube = import "../../../kube/kube.libsonnet";
|
||||
local gerrit = import "gerrit.libsonnet";
|
||||
{
|
||||
namespace: kube.Namespace("gerrit"),
|
||||
|
||||
gerrit: gerrit {
|
||||
cfg+: {
|
||||
namespace: "gerrit",
|
||||
prefix: "",
|
||||
|
||||
domain: "gerrit.hackerspace.pl",
|
||||
identity: "7b6244cf-e30b-42c5-ba91-c329ef4e6cf1",
|
||||
|
||||
storageClassName: "waw-hdd-redundant-1",
|
||||
|
||||
secureSecret: "gerrit",
|
||||
},
|
||||
},
|
||||
}
|
|
@ -99,9 +99,9 @@ local Cluster(fqdn) = {
|
|||
waw1: cockroachdb.Cluster("crdb-waw1") {
|
||||
cfg+: {
|
||||
topology: [
|
||||
{ name: "bc01n01", node: "bc01n01.hswaw.net", ip: "185.236.240.35" },
|
||||
{ name: "bc01n02", node: "bc01n02.hswaw.net", ip: "185.236.240.36" },
|
||||
{ name: "bc01n03", node: "bc01n03.hswaw.net", ip: "185.236.240.37" },
|
||||
{ name: "bc01n01", node: "bc01n01.hswaw.net" },
|
||||
{ name: "bc01n02", node: "bc01n02.hswaw.net" },
|
||||
{ name: "bc01n03", node: "bc01n03.hswaw.net" },
|
||||
],
|
||||
hostPath: "/var/db/crdb-waw1",
|
||||
},
|
||||
|
|
|
@ -6,16 +6,16 @@
|
|||
# cfg+: {
|
||||
# namespace: "q3k", // if not given, will create 'q3kdb' namespace
|
||||
# topology: [
|
||||
# { name: "a", node: "bc01n01.hswaw.net", ip: "185.236.240.35" },
|
||||
# { name: "b", node: "bc01n02.hswaw.net", ip: "185.236.240.36" },
|
||||
# { name: "c", node: "bc01n03.hswaw.net", ip: "185.236.240.37" },
|
||||
# { name: "a", node: "bc01n01.hswaw.net" },
|
||||
# { name: "b", node: "bc01n02.hswaw.net" },
|
||||
# { name: "c", node: "bc01n03.hswaw.net" },
|
||||
# ],
|
||||
# hostPath: "/var/db/cockroach-q3k",
|
||||
# },
|
||||
#},
|
||||
#
|
||||
# After the cluster is up, you can get to an administrateive SQL shell:
|
||||
# $ kubectl -n q3k exec -it q3kdb-client /cockroach/cockroach sql
|
||||
# $ NS=q3k kubectl -n $NS exec -it $(kubectl -n $NS get pods -o name | grep client- | cut -d/ -f 2) /cockroach/cockroach sql
|
||||
# root@q3kdb-cockroachdb-0.q3kdb-internal.q3k.svc.cluster.local:26257/defaultdb>
|
||||
#
|
||||
# Then, you can create some users and databases for applications:
|
||||
|
@ -365,51 +365,56 @@ local cm = import "cert-manager.libsonnet";
|
|||
},
|
||||
},
|
||||
|
||||
clientPod: kube.Pod(cluster.name("client")) {
|
||||
client: kube.Deployment(cluster.name("client")) {
|
||||
metadata+: cluster.metadata {
|
||||
labels+: {
|
||||
"app.kubernetes.io/component": "client",
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
terminationGracePeriodSeconds: 5,
|
||||
containers: [
|
||||
kube.Container("cockroachdb-client") {
|
||||
image: cluster.cfg.image,
|
||||
env_: {
|
||||
"COCKROACH_CERTS_DIR": "/cockroach/cockroach-certs",
|
||||
"COCKROACH_HOST": cluster.publicService.host,
|
||||
"COCKROACH_PORT": std.toString(cluster.cfg.portServe),
|
||||
},
|
||||
command: ["sleep", "2147483648"], //(FIXME) keep the client pod running indefinitely
|
||||
volumeMounts: [
|
||||
{
|
||||
name: "certs",
|
||||
mountPath: "/cockroach/cockroach-certs/ca.crt",
|
||||
subPath: "ca.crt",
|
||||
spec+: {
|
||||
template: {
|
||||
metadata: cluster.client.metadata,
|
||||
spec+: {
|
||||
terminationGracePeriodSeconds: 5,
|
||||
containers: [
|
||||
kube.Container("cockroachdb-client") {
|
||||
image: cluster.cfg.image,
|
||||
env_: {
|
||||
"COCKROACH_CERTS_DIR": "/cockroach/cockroach-certs",
|
||||
"COCKROACH_HOST": cluster.publicService.host,
|
||||
"COCKROACH_PORT": std.toString(cluster.cfg.portServe),
|
||||
},
|
||||
command: ["sleep", "2147483648"], //(FIXME) keep the client pod running indefinitely
|
||||
volumeMounts: [
|
||||
{
|
||||
name: "certs",
|
||||
mountPath: "/cockroach/cockroach-certs/ca.crt",
|
||||
subPath: "ca.crt",
|
||||
},
|
||||
{
|
||||
name: "certs",
|
||||
mountPath: "/cockroach/cockroach-certs/client.root.crt",
|
||||
subPath: "tls.crt",
|
||||
},
|
||||
{
|
||||
name: "certs",
|
||||
mountPath: "/cockroach/cockroach-certs/client.root.key",
|
||||
subPath: "tls.key",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
volumes: [
|
||||
{
|
||||
name: "certs",
|
||||
mountPath: "/cockroach/cockroach-certs/client.root.crt",
|
||||
subPath: "tls.crt",
|
||||
},
|
||||
{
|
||||
name: "certs",
|
||||
mountPath: "/cockroach/cockroach-certs/client.root.key",
|
||||
subPath: "tls.key",
|
||||
secret: {
|
||||
secretName: cluster.pki.clientCertificate.spec.secretName,
|
||||
defaultMode: kube.parseOctal("400")
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
volumes: [
|
||||
{
|
||||
name: "certs",
|
||||
secret: {
|
||||
secretName: cluster.pki.clientCertificate.spec.secretName,
|
||||
defaultMode: kube.parseOctal("400")
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
17
tools/workspace-status.sh
Executable file
17
tools/workspace-status.sh
Executable file
|
@ -0,0 +1,17 @@
|
|||
#!/bin/bash
|
||||
|
||||
# This script will be run by bazel when the build process starts to
|
||||
# generate key-value information that represents the status of the
|
||||
# workspace. The output should be like
|
||||
#
|
||||
# KEY1 VALUE1
|
||||
# KEY2 VALUE2
|
||||
#
|
||||
# If the script exits with non-zero code, it's considered as a failure
|
||||
# and the output will be discarded.
|
||||
|
||||
function rev() {
|
||||
cd $1; git describe --always --match "v[0-9].*" --dirty
|
||||
}
|
||||
|
||||
echo STABLE_BUILD_GERRIT-OAUTH-PROVIDER_LABEL $(rev .)
|
Loading…
Reference in a new issue