Add CoreOS Dex support

Change-Id: I97a8797428caf9c4f213057f67e897936c59b6c1
diff --git a/README.md b/README.md
index 98070bc..d9595c2 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@
 
 * [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/)
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/DexApi.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/DexApi.java
new file mode 100644
index 0000000..389dd8e
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/DexApi.java
@@ -0,0 +1,136 @@
+// 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.OAuthConstants;
+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.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) {
+    // TODO can't use this until updating to newer scribe lib
+    // return new OAuth20ServiceImpl(this,config);
+    return new DexOAuthService(this, config);
+  }
+
+  @Override
+  public AccessTokenExtractor getAccessTokenExtractor() {
+    return new JsonTokenExtractor();
+  }
+
+  private static final class DexOAuthService 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;
+
+    /**
+     * Default constructor
+     *
+     * @param api OAuth2.0 api information
+     * @param config OAuth 2.0 configuration param object
+     */
+    public DexOAuthService(DefaultApi20 api, OAuthConfig config) {
+      this.api = api;
+      this.config = config;
+    }
+
+    /** {@inheritDoc} */
+    @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);
+      Response response = request.send();
+      return api.getAccessTokenExtractor().extract(response.getBody());
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public Token getRequestToken() {
+      throw new UnsupportedOperationException(
+          "Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String getVersion() {
+      return VERSION;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void signRequest(Token accessToken, OAuthRequest request) {
+      request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String getAuthorizationUrl(Token requestToken) {
+      return api.getAuthorizationUrl(config);
+    }
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/DexOAuthService.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/DexOAuthService.java
new file mode 100644
index 0000000..ae1ca98
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/DexOAuthService.java
@@ -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.server.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(String.format("Response doesn't contain email field"));
+    }
+    if (nameElement == null || nameElement.isJsonNull()) {
+      throw new IOException(String.format("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;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
index 9636ca6..6b49663 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
@@ -77,5 +77,12 @@
           .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);
+    }
   }
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
index 6d6095d..49b0bb7 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
@@ -28,6 +28,7 @@
   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 SERVICE_NAME = "service-name";
   static String FIX_LEGACY_USER_ID_QUESTION = "Fix legacy user id, without oauth provider prefix?";
 
   private final ConsoleUI ui;
@@ -37,6 +38,7 @@
   private final Section casOAuthProviderSection;
   private final Section facebookOAuthProviderSection;
   private final Section gitlabOAuthProviderSection;
+  private final Section dexOAuthProviderSection;
 
   @Inject
   InitOAuth(ConsoleUI ui, Section.Factory sections, @PluginName String pluginName) {
@@ -53,6 +55,8 @@
         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);
   }
 
   @Override
@@ -100,6 +104,12 @@
       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);
+    }
   }
 
   private void configureOAuth(Section s) {
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md
index 8bb6969..bc0ddc7 100644
--- a/src/main/resources/Documentation/config.md
+++ b/src/main/resources/Documentation/config.md
@@ -31,6 +31,13 @@
       root-url = "<gitlab url>"
       client-id = "<client-id>"
       client-secret = "<client-secret>"
+
+  [plugin "@PLUGIN@-dex-oauth"]
+      domain = "<domain for username manipulation (optional)>"
+      service-name = "<custom service name (optional)>"
+      root-url = "<dex url>"
+      client-id = "<client-id>"
+      client-secret = "<client-secret>"
 ```
 
 When one from the sections above is omitted, OAuth SSO is used.
@@ -96,6 +103,16 @@
 | email |  Email address | no |
 | name | Display name | no |
 
+### CoreOS Dex OAuth
+
+For Dex OAuth setting
+
+```
+plugin.gerrit-oauth-provider-dex-oauth.root-url = "https://example.com"
+```
+
+is required, since Dex is a self-hosted application.
+
 ## Obtaining provider authorizations
 
 ### Google
@@ -174,3 +191,12 @@
 secret.
 
 ![Generated client id and secret](images/gitlab-2.png)
+
+### CoreOS Dex
+
+The client-id and client-secret for Dex OAuth are part of the Dex
+setup and need to be set manually.
+
+See
+[Using Dex](https://github.com/coreos/dex/blob/master/Documentation/using-dex.md)
+for an example.