Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth refresh check admin #1349

Merged
merged 2 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion authentication/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ extra_hosts:
- "host.docker.internal:host-gateway"
```
2. In `nginx.conf`, replace `server auth:7000;` with `server host.docker.internal:7000;`
3. (Optionally) allow TCP traffic on port 7000 of your firewall if logging in seems to hang forever or if you get `504 Gateway Timeout` responses.
3. (Optional) For refreshing your tokens to work, set `RSD_AUTH_URL=http://nginx/auth` in your `.env`.
4. (Optional) Allow TCP traffic on port 7000 of your firewall if signing in seems to hang forever or if you get `504 Gateway Timeout` responses.

Remember to undo these changes before committing!

Expand Down
12 changes: 6 additions & 6 deletions authentication/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ SPDX-License-Identifier: Apache-2.0
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.7.1</version>
<version>3.8.1</version>
</plugin>

<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-assembly-plugin -->
Expand Down Expand Up @@ -101,21 +101,21 @@ SPDX-License-Identifier: Apache-2.0
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
<version>6.2.0</version>
<version>6.3.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.jetbrains/annotations -->
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>24.1.0</version>
<version>26.0.1</version>
</dependency>

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

<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
Expand Down Expand Up @@ -143,14 +143,14 @@ SPDX-License-Identifier: Apache-2.0
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
<version>2.0.16</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>
<version>1.5.12</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,28 @@
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

public class JwtCreator {

static final long ONE_HOUR_IN_MILLISECONDS = 3600_000L; // 60 * 60 * 1000
private final String signingSecret;
private final Algorithm signingAlgorithm;
private static final String RSD_ADMIN_ROLE = "rsd_admin";
private static final String RSD_USER_ROLE = "rsd_user";

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

String createUserJwt(AccountInfo accountInfo) {
return JWT.create()
.withClaim("iss", "rsd_auth")
.withClaim("role", accountInfo.isAdmin() ? "rsd_admin" : "rsd_user")
.withClaim("role", accountInfo.isAdmin() ? RSD_ADMIN_ROLE : RSD_USER_ROLE)
.withClaim("account", accountInfo.account().toString())
.withClaim("name", accountInfo.name())
.withClaim("data", accountInfo.data())
Expand All @@ -45,19 +47,22 @@ String createUserJwt(AccountInfo accountInfo) {
String createAdminJwt() {
return JWT.create()
.withClaim("iss", "rsd_auth")
.withClaim("role", "rsd_admin")
.withClaim("role", RSD_ADMIN_ROLE)
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
}

String refreshToken(String token) {
String refreshToken(String token) throws IOException, InterruptedException {
DecodedJWT oldJwt = JWT.decode(token);
UUID accountId = UUID.fromString(oldJwt.getClaim("account").asString());
boolean isAdmin = PostgrestAccount.isAdmin(accountId);
String payloadEncoded = oldJwt.getPayload();
String payloadDecoded = Main.decode(payloadEncoded);
Gson gson = new Gson();
Map<String, ?> claimsMap = gson.<Map<String, ?>>fromJson(payloadDecoded, Map.class);
return JWT.create()
.withPayload(claimsMap)
.withClaim("role", isAdmin ? RSD_ADMIN_ROLE : RSD_USER_ROLE)
.withExpiresAt(new Date(System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS))
.sign(signingAlgorithm);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
package nl.esciencecenter.rsd.authentication;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

Expand Down Expand Up @@ -100,6 +101,32 @@ else if (accountsWithSub.size() == 1) {
}
}

public static boolean isAdmin(UUID accountId) throws IOException, InterruptedException {
Objects.requireNonNull(accountId);
String backendUri = Config.backendBaseUrl();
URI accountUrl = URI.create(backendUri + "/admin_account?account_id=eq.%s".formatted(accountId));
JwtCreator jwtCreator = new JwtCreator(Config.jwtSigningSecret());
String token = jwtCreator.createAdminJwt();

String response = getAsAdmin(accountUrl, token);
return parseIsAdminResponse(accountId, response);
}

static boolean parseIsAdminResponse(UUID accountId, String response) {
Objects.requireNonNull(accountId);
Objects.requireNonNull(response);
JsonElement jsonTree = JsonParser.parseString(response);
return jsonTree.isJsonArray()
&& jsonTree.getAsJsonArray().size() == 1
&& jsonTree.getAsJsonArray().get(0).getAsJsonObject().get("account_id").isJsonPrimitive()
&& jsonTree.getAsJsonArray()
.get(0)
.getAsJsonObject()
.getAsJsonPrimitive("account_id")
.getAsString()
.equals(accountId.toString());
}

public void coupleLogin(UUID accountId, OpenIdInfo openIdInfo, OpenidProvider provider) throws IOException, InterruptedException {
String backendUri = Config.backendBaseUrl();
JwtCreator jwtCreator = new JwtCreator(Config.jwtSigningSecret());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// SPDX-FileCopyrightText: 2024 Ewan Cahen (Netherlands eScience Center) <e.cahen@esciencecenter.nl>
// SPDX-FileCopyrightText: 2024 Netherlands eScience Center
//
// SPDX-License-Identifier: Apache-2.0

package nl.esciencecenter.rsd.authentication;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.UUID;

class PostgrestAccountTest {

@Test
void givenEmtpyArray_whenCheckingIfAdmin_thenFalseReturned() {
String emptyArray = "[]";
UUID adminUuid = UUID.randomUUID();

Assertions.assertFalse(PostgrestAccount.parseIsAdminResponse(adminUuid, emptyArray));
}

@Test
void givenResponseWithNullValue_whenCheckingIfAdmin_thenFalseReturned() {
String emptyArray = "[{\"account_id\": null}]";
UUID adminUuid = UUID.randomUUID();

Assertions.assertFalse(PostgrestAccount.parseIsAdminResponse(adminUuid, emptyArray));
}

@Test
void givenArrayOfSizeOneWithCorrectUuid_whenCheckingIfAdmin_thenTrueReturned() {
UUID adminUuid = UUID.randomUUID();
String successResponse = "[{\"account_id\": \"%s\"}]".formatted(adminUuid);

Assertions.assertTrue(PostgrestAccount.parseIsAdminResponse(adminUuid, successResponse));
}

@Test
void givenArrayOfSizeOneWithIncorrectUuid_whenCheckingIfAdmin_thenFalseReturned() {
UUID adminUuid = UUID.randomUUID();
String successResponse = "[{\"account_id\": \"%s\"}]".formatted(UUID.randomUUID());

Assertions.assertFalse(PostgrestAccount.parseIsAdminResponse(adminUuid, successResponse));
}

@Test
void givenArrayOfSizeTwoWithCorrectUuid_whenCheckingIfAdmin_thenFalseReturned() {
UUID adminUuid = UUID.randomUUID();
String wrongIdResponse = "[{\"account_id\": \"%s\"}, {\"account_id\": \"%s\"}]".formatted(adminUuid, UUID.randomUUID());

Assertions.assertFalse(PostgrestAccount.parseIsAdminResponse(adminUuid, wrongIdResponse));
}
}
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ services:

auth:
build: ./authentication
image: rsd/auth:1.5.0
image: rsd/auth:1.6.0
ports:
- 5005:5005
expose:
Expand Down