Add Keycloak support

Change-Id: Ie89539b2489b7c2b677b56f9c3e0c72d141109d5
diff --git a/README.md b/README.md
index d9595c2..57147ce 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,7 @@
 * [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/)
 
 See the [Wiki](https://github.com/davido/gerrit-oauth-provider/wiki) what it can do for you.
 
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 6b49663..06d2f90 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
@@ -84,5 +84,12 @@
           .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);
+    }
   }
 }
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 49b0bb7..3d10f72 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 REALM = "realm";
   static final String SERVICE_NAME = "service-name";
   static String FIX_LEGACY_USER_ID_QUESTION = "Fix legacy user id, without oauth provider prefix?";
 
@@ -39,6 +40,7 @@
   private final Section facebookOAuthProviderSection;
   private final Section gitlabOAuthProviderSection;
   private final Section dexOAuthProviderSection;
+  private final Section keycloakOAuthProviderSection;
 
   @Inject
   InitOAuth(ConsoleUI ui, Section.Factory sections, @PluginName String pluginName) {
@@ -57,6 +59,8 @@
         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);
   }
 
   @Override
@@ -110,6 +114,14 @@
       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);
+    }
   }
 
   private void configureOAuth(Section s) {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakApi.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakApi.java
new file mode 100644
index 0000000..581d562
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakApi.java
@@ -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();
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakOAuthService.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakOAuthService.java
new file mode 100644
index 0000000..4b47fdf
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/KeycloakOAuthService.java
@@ -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.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 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;
+  }
+}