Skip to content

Commit

Permalink
Set up an error page when the token could not be validated. (#344)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vlatombe authored Jun 30, 2024
1 parent bfee059 commit 6f5e8da
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.jenkinsci.plugins.oic;

Check warning on line 1 in src/main/java/org/jenkinsci/plugins/oic/FailedCheckOfTokenException.java

View check run for this annotation

ci.jenkins.io / Java Compiler

checkstyle:check

ERROR: (misc) NewlineAtEndOfFile: Expected line ending for file is LF(\n), but CRLF(\r\n) is detected.

import edu.umd.cs.findbugs.annotations.CheckForNull;
import java.io.IOException;
import javax.servlet.ServletException;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
* Exception to be thrown when the received ID Token did not pass the expected check.
* It offers a link to log out from the OpenID Connect provider.
*/
public class FailedCheckOfTokenException extends RuntimeException implements HttpResponse {
@CheckForNull
private final String idpLogoutUrl;

public FailedCheckOfTokenException(@CheckForNull String idpLogoutUrl) {
this.idpLogoutUrl = idpLogoutUrl;
}

@CheckForNull
@SuppressWarnings("unused") // stapler/jelly
public String getIdpLogoutUrl() {
return idpLogoutUrl;
}

@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
throws IOException, ServletException {
req.getView(this, "error").forward(req, rsp);
}
}
53 changes: 35 additions & 18 deletions src/main/java/org/jenkinsci/plugins/oic/OicSecurityRealm.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import com.google.api.client.util.Data;
import com.google.common.base.Strings;
import com.google.gson.JsonParseException;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.Util;
Expand All @@ -64,12 +65,12 @@
import io.burt.jmespath.jcf.JcfRuntime;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
Expand All @@ -80,6 +81,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -899,7 +901,8 @@ public HttpResponse onSuccess(String authorizationCode, AuthorizationCodeFlow fl
}

if (failedCheckOfTokenField(idToken)) {
return HttpResponses.errorWithoutStack(401, "Unauthorized");
throw new FailedCheckOfTokenException(
maybeOpenIdLogoutEndpoint(response.getIdToken(), state, buildOauthCommenceLogin()));
}

this.setIdToken(response.getIdToken());
Expand Down Expand Up @@ -1194,24 +1197,30 @@ public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException

@Override
public String getPostLogOutUrl2(StaplerRequest req, Authentication auth) {
Object idToken = req.getAttribute(ID_TOKEN_REQUEST_ATTRIBUTE);
Object state = req.getAttribute(STATE_REQUEST_ATTRIBUTE);
var openidLogoutEndpoint = maybeOpenIdLogoutEndpoint(
Objects.toString(idToken), Objects.toString(state), this.postLogoutRedirectUrl);
if (openidLogoutEndpoint != null) {
return openidLogoutEndpoint;
}
return getFinalLogoutUrl(req, auth);
}

@CheckForNull
private String maybeOpenIdLogoutEndpoint(String idToken, String state, String postLogoutRedirectUrl) {
if (this.logoutFromOpenidProvider && !Strings.isNullOrEmpty(this.endSessionEndpoint)) {
StringBuilder openidLogoutEndpoint = new StringBuilder(this.endSessionEndpoint);
openidLogoutEndpoint.append("?id_token_hint=").append(req.getAttribute(ID_TOKEN_REQUEST_ATTRIBUTE));
openidLogoutEndpoint.append("&state=").append(req.getAttribute(STATE_REQUEST_ATTRIBUTE));

if (this.postLogoutRedirectUrl != null) {
try {
openidLogoutEndpoint
.append("&post_logout_redirect_uri=")
.append(URLEncoder.encode(this.postLogoutRedirectUrl, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
openidLogoutEndpoint.append("?id_token_hint=").append(idToken);
openidLogoutEndpoint.append("&state=").append(state);
if (postLogoutRedirectUrl != null) {
openidLogoutEndpoint
.append("&post_logout_redirect_uri=")
.append(URLEncoder.encode(postLogoutRedirectUrl, StandardCharsets.UTF_8));
}
return openidLogoutEndpoint.toString();
}

return getFinalLogoutUrl(req, auth);
return null;
}

private String getFinalLogoutUrl(StaplerRequest req, Authentication auth) {
Expand All @@ -1229,15 +1238,23 @@ private String getRootUrl() {
}
}

private String buildOAuthRedirectUrl() throws NullPointerException {
private String ensureRootUrl() {
String rootUrl = getRootUrl();
if (rootUrl == null) {
throw new NullPointerException("Jenkins root url should not be null");
throw new NullPointerException("Jenkins root url must not be null");

Check warning on line 1244 in src/main/java/org/jenkinsci/plugins/oic/OicSecurityRealm.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 1244 is not covered by tests
} else {
return rootUrl + "securityRealm/finishLogin";
return rootUrl;
}
}

private String buildOauthCommenceLogin() {
return ensureRootUrl() + getLoginUrl();
}

private String buildOAuthRedirectUrl() throws NullPointerException {
return ensureRootUrl() + "securityRealm/finishLogin";
}

/**
* This is where the user comes back to at the end of the OpenID redirect ping-pong.
* @param request The user's request
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<!--
The MIT License
Copyright (c) 2024, CloudBees, Inc.
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.
-->
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
<st:statusCode value="401"/>
<l:layout title="${%Unauthorized}">
<l:main-panel>
<div class="error">
<h1>${%Unauthorized}</h1>
<p>${%You do not have permission to access this instance.}</p>
<j:if test="${it.idpLogoutUrl != null}">
<p><a href="${it.idpLogoutUrl}">${%Log out from OpenID Connect Provider}</a></p>
</j:if>
</div>
</l:main-panel>
</l:layout>
</j:jelly>
28 changes: 28 additions & 0 deletions src/test/java/org/jenkinsci/plugins/oic/PluginTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,34 @@ public void testLoginWithUnreadableIdTokenShouldBeRefused() throws Exception {
webClient.assertFails(jenkins.getSecurityRealm().getLoginUrl(), 403);
}

@Test
public void loginWithCheckTokenSuccess() throws Exception {
mockAuthorizationRedirectsToFinishLogin();
mockTokenReturnsIdTokenWithGroup();
configureTestRealm(belongsToGroup("group1"));
assertAnonymous();
browseLoginPage();
assertTestUser();
}

@Test
public void loginWithCheckTokenFailure() throws Exception {
mockAuthorizationRedirectsToFinishLogin();
mockTokenReturnsIdTokenWithGroup();
configureTestRealm(belongsToGroup("missing-group"));
assertAnonymous();
webClient.setThrowExceptionOnFailingStatusCode(false);
browseLoginPage();
assertAnonymous();
}

private static @NonNull Consumer<OicSecurityRealm> belongsToGroup(String groupName) {
return sc -> {
sc.setTokenFieldToCheckKey("contains(groups, '" + groupName + "')");
sc.setTokenFieldToCheckValue("true");
};
}

/** Generate JWKS entry with public key of keyPair */
String encodePublicKey(KeyPair keyPair) {
final RSAPublicKey rsaPKey = (RSAPublicKey) (keyPair.getPublic());
Expand Down

0 comments on commit 6f5e8da

Please sign in to comment.