Skip to content

Commit

Permalink
Merge pull request #1345 from research-software-directory/sonarcloud-…
Browse files Browse the repository at this point in the history
…fixes

Fix some SonarCloud issues
  • Loading branch information
ewan-escience authored Nov 13, 2024
2 parents 0b7397a + 9876c6f commit 70029ae
Show file tree
Hide file tree
Showing 31 changed files with 294 additions and 218 deletions.
14 changes: 14 additions & 0 deletions authentication/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,20 @@ SPDX-License-Identifier: Apache-2.0
<version>11.10.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.6</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
Expand All @@ -38,7 +35,7 @@ public AzureLogin(String code, String redirectUrl) {
}

@Override
public OpenIdInfo openidInfo() throws IOException, InterruptedException {
public OpenIdInfo openidInfo() throws IOException, InterruptedException, RsdResponseException {
Map<String, String> form = createForm();
String tokenResponse = getTokensFromAzureconext(form);
String idToken = extractIdToken(tokenResponse);
Expand All @@ -61,23 +58,12 @@ private Map<String, String> createForm() {
return form;
}

private String getTokensFromAzureconext(Map<String, String> form) throws IOException, InterruptedException {
private String getTokensFromAzureconext(Map<String, String> form) throws IOException, InterruptedException, RsdResponseException {
URI tokenEndpoint = Utils.getTokenUrlFromWellKnownUrl(URI.create(Config.azureWellknown()));
return postForm(tokenEndpoint, form);
return Utils.postForm(tokenEndpoint, form);
}

private String extractIdToken(String response) {
return JsonParser.parseString(response).getAsJsonObject().getAsJsonPrimitive("id_token").getAsString();
}

private String postForm(URI uri, Map<String, String> form) throws IOException, InterruptedException {
HttpRequest request = Utils.formToHttpRequest(uri, form);
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) {
throw new RuntimeException("Error fetching data from " + uri.toString() + ": " + response.body());
}
return response.body();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2022 - 2023 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2022 - 2023 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 - 2024 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2022 - 2024 Helmholtz Centre Potsdam - GFZ German Research Centre for Geosciences
// SPDX-FileCopyrightText: 2022 - 2024 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 Dusan Mijatovic (dv4all)
// SPDX-FileCopyrightText: 2022 Matthias Rüster (GFZ) <[email protected]>
// SPDX-FileCopyrightText: 2022 dv4all
Expand All @@ -21,6 +21,9 @@ public static String jwtSigningSecret() {
return System.getenv("PGRST_JWT_SECRET");
}

private Config() {
}

private static Collection<String> rsdAuthCoupleProviders() {
return Optional.ofNullable(System.getenv("RSD_AUTH_COUPLE_PROVIDERS"))
.map(String::toUpperCase)
Expand All @@ -39,10 +42,10 @@ public static boolean isDevEnv() {

private static Collection<String> rsdLoginProviders() {
return Optional.ofNullable(System.getenv("RSD_AUTH_PROVIDERS"))
.map(String::toUpperCase)
.map(s -> s.split(";"))
.map(Set::of)
.orElse(Collections.emptySet());
.map(String::toUpperCase)
.map(s -> s.split(";"))
.map(Set::of)
.orElse(Collections.emptySet());
}

public static boolean isLocalLoginEnabled() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// SPDX-FileCopyrightText: 2022 - 2023 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2022 - 2023 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 - 2024 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2022 - 2024 Helmholtz Centre Potsdam - GFZ German Research Centre for Geosciences
// SPDX-FileCopyrightText: 2022 - 2024 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 Matthias Rüster (GFZ) <[email protected]>
// SPDX-FileCopyrightText: 2023 - 2024 Christian Meeßen (GFZ) <[email protected]>
//
Expand Down Expand Up @@ -50,7 +50,7 @@ public class HelmholtzIdLogin implements Login {
static final String DEFAULT_ORGANISATION = "Helmholtz";

// See https://hifis.net/doc/helmholtz-aai/list-of-vos/#vos-representing-helmholtz-centres
static private final Collection<String> knownHgfOrganisations = Set.of(
private static final Collection<String> knownHgfOrganisations = Set.of(
"AWI", "CISPA", "DESY", "DKFZ", "DLR", "DZNE", "FZJ", "GEOMAR", "GFZ", "GSI", "hereon", "HMGU", "HZB", "KIT", "MDC", "UFZ"
);

Expand Down Expand Up @@ -198,8 +198,8 @@ public OpenIdInfo openidInfo() throws IOException, InterruptedException {

JSONArray entitlements = new JSONArray();
Object edupersonClaim = userInfo.getClaim("eduperson_entitlement");
if (edupersonClaim instanceof JSONArray) {
entitlements = (JSONArray) edupersonClaim;
if (edupersonClaim instanceof JSONArray jsonArray) {
entitlements = jsonArray;
} else if (edupersonClaim instanceof String) {
entitlements.appendElement(edupersonClaim);
} else if (edupersonClaim == null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2022 - 2023 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2022 - 2023 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 - 2024 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2022 - 2024 Netherlands eScience Center
// SPDX-FileCopyrightText: 2022 Dusan Mijatovic (dv4all)
// SPDX-FileCopyrightText: 2022 dv4all
// SPDX-FileCopyrightText: 2024 Christian Meeßen (GFZ) <[email protected]>
Expand All @@ -25,40 +25,40 @@ public class JwtCreator {
private final Algorithm signingAlgorithm;

public JwtCreator(String signingSecret) {
signingSecret = Objects.requireNonNull(signingSecret);
Objects.requireNonNull(signingSecret);
this.signingSecret = signingSecret;
this.signingAlgorithm = Algorithm.HMAC256(this.signingSecret);
}

String createUserJwt(AccountInfo accountInfo) {
return JWT.create()
.withClaim("iss", "rsd_auth")
.withClaim("role", accountInfo.isAdmin() ? "rsd_admin" : "rsd_user")
.withClaim("account", accountInfo.account().toString())
.withClaim("name", accountInfo.name())
.withClaim("data", accountInfo.data())
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
.withClaim("iss", "rsd_auth")
.withClaim("role", accountInfo.isAdmin() ? "rsd_admin" : "rsd_user")
.withClaim("account", accountInfo.account().toString())
.withClaim("name", accountInfo.name())
.withClaim("data", accountInfo.data())
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
}


String createAdminJwt() {
return JWT.create()
.withClaim("iss", "rsd_auth")
.withClaim("role", "rsd_admin")
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
.withClaim("iss", "rsd_auth")
.withClaim("role", "rsd_admin")
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
}

String refreshToken(String token) {
DecodedJWT oldJwt = JWT.decode(token);
String payloadEncoded = oldJwt.getPayload();
String payloadDecoded = Main.decode(payloadEncoded);
Gson gson = new Gson();
Map claimsMap = gson.fromJson(payloadDecoded, Map.class);
Map<String, ?> claimsMap = gson.<Map<String, ?>>fromJson(payloadDecoded, Map.class);
return JWT.create()
.withPayload(claimsMap)
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
.withPayload(claimsMap)
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// SPDX-FileCopyrightText: 2021 - 2023 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2021 - 2023 Netherlands eScience Center
// SPDX-FileCopyrightText: 2021 - 2024 Ewan Cahen (Netherlands eScience Center) <[email protected]>
// SPDX-FileCopyrightText: 2021 - 2024 Netherlands eScience Center
//
// SPDX-License-Identifier: Apache-2.0

Expand All @@ -9,5 +9,5 @@

public interface Login {

OpenIdInfo openidInfo() throws IOException, InterruptedException;
OpenIdInfo openidInfo() throws IOException, InterruptedException, RsdResponseException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import com.auth0.jwt.interfaces.DecodedJWT;
import io.javalin.Javalin;
import io.javalin.http.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Base64;
import java.util.Collections;
Expand All @@ -25,6 +27,9 @@ public class Main {
static final long ONE_HOUR_IN_SECONDS = 3600; // 60 * 60
static final long ONE_MINUTE_IN_SECONDS = 60;

private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
private static final String LOGIN_FAILED_PATH = "/login/failed";

public static boolean userIsAllowed(OpenIdInfo info) {
String whitelist = Config.userMailWhitelist();

Expand Down Expand Up @@ -191,27 +196,33 @@ public static void main(String[] args) {
String token = jwtCreator.refreshToken(tokenToVerify);
setJwtCookie(ctx, token);
} catch (RuntimeException ex) {
ex.printStackTrace();
LOGGER.error("RuntimeException", ex);
ctx.status(400);
ctx.json("{\"message\": \"failed to refresh token\"}");
}
});

app.exception(JWTVerificationException.class, (ex, ctx) -> {
ex.printStackTrace();
LOGGER.error("JWTVerificationException", ex);
ctx.status(400);
ctx.json("{\"message\": \"invalid JWT\"}");
});

app.exception(RsdAuthenticationException.class, (ex, ctx) -> {
setLoginFailureCookie(ctx, ex.getMessage());
ctx.redirect("/login/failed");
ctx.redirect(LOGIN_FAILED_PATH);
});

app.exception(RuntimeException.class, (ex, ctx) -> {
ex.printStackTrace();
LOGGER.error("RuntimeException", ex);
setLoginFailureCookie(ctx, "Something unexpected went wrong, please try again or contact us.");
ctx.redirect(LOGIN_FAILED_PATH);
});

app.exception(Exception.class, (ex, ctx) -> {
LOGGER.error("Exception", ex);
setLoginFailureCookie(ctx, "Something unexpected went wrong, please try again or contact us.");
ctx.redirect("/login/failed");
ctx.redirect(LOGIN_FAILED_PATH);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
Expand All @@ -33,7 +30,7 @@ public OrcidLogin(String code, String redirectUrl) {
}

@Override
public OpenIdInfo openidInfo() throws IOException, InterruptedException {
public OpenIdInfo openidInfo() throws IOException, InterruptedException, RsdResponseException {
Map<String, String> form = createForm();
String tokenResponse = getTokensFromOrcidconext(form);
String idToken = extractIdToken(tokenResponse);
Expand Down Expand Up @@ -63,23 +60,12 @@ private Map<String, String> createForm() {
return form;
}

private String getTokensFromOrcidconext(Map<String, String> form) throws IOException, InterruptedException {
private String getTokensFromOrcidconext(Map<String, String> form) throws IOException, InterruptedException, RsdResponseException {
URI tokenEndpoint = Utils.getTokenUrlFromWellKnownUrl(URI.create(Config.orcidWellknown()));
return postForm(tokenEndpoint, form);
return Utils.postForm(tokenEndpoint, form);
}

private String extractIdToken(String response) {
return JsonParser.parseString(response).getAsJsonObject().getAsJsonPrimitive("id_token").getAsString();
}

private String postForm(URI uri, Map<String, String> form) throws IOException, InterruptedException {
HttpRequest request = Utils.formToHttpRequest(uri, form);
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) {
throw new RuntimeException("Error fetching data from " + uri.toString() + ": " + response.body());
}
return response.body();
}
}
}
Loading

0 comments on commit 70029ae

Please sign in to comment.