Skip to content

Commit

Permalink
Migrate Tauri to v2.0 and implement socket security
Browse files Browse the repository at this point in the history
  • Loading branch information
zelytra committed Apr 3, 2024
1 parent 7e9f718 commit 061ece8
Show file tree
Hide file tree
Showing 25 changed files with 6,418 additions and 1,134 deletions.
27 changes: 6 additions & 21 deletions backend/src/main/java/fr/zelytra/session/SessionSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@
import fr.zelytra.session.server.SotServer;
import fr.zelytra.session.socket.MessageType;
import fr.zelytra.session.socket.SocketMessage;
import fr.zelytra.session.socket.security.SocketSecurityEntity;
import io.quarkus.logging.Log;
import io.smallrye.jwt.auth.principal.DefaultJWTTokenParser;
import io.smallrye.jwt.auth.principal.JWTAuthContextInfo;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
Expand All @@ -25,7 +23,6 @@

// WebSocket endpoint
@ServerEndpoint(value = "/sessions/{token}/{sessionId}")
@ApplicationScoped
public class SessionSocket {

private final ExecutorService executor = Executors.newSingleThreadExecutor();
Expand All @@ -44,11 +41,6 @@ public class SessionSocket {
@Inject
ExecutorService sqlExecutor;

@Inject
JWTAuthContextInfo contextInfo;

private final DefaultJWTTokenParser parser = new DefaultJWTTokenParser();

@OnOpen
public void onOpen(Session session) {
// Start a timeout task
Expand Down Expand Up @@ -147,19 +139,22 @@ private void handleLeaveServerMessage(Session session, SotServer sotServer) {
}

// Extracted method to handle CONNECT messages
private void handleConnectMessage(Player player, Session session, String sessionId, String token) throws IOException {
public void handleConnectMessage(Player player, Session session, String sessionId, String token) throws IOException {
// Cancel the timeout task since we've received the message
Future<?> timeoutTask = sessionTimeoutTasks.remove(session.getId());
if (timeoutTask != null) {
timeoutTask.cancel(true);
}

if (!isTokenValid(token)) {
// Checking security
SocketSecurityEntity socketSecurity = SocketSecurityEntity.websocketUser.get(token);
if (socketSecurity == null || !socketSecurity.isValid()) {
Log.info("Invalid token, session will be closed");
sessionManager.sendDataToPlayer(session, MessageType.CONNECTION_REFUSED, null);
session.close();
return;
}
SocketSecurityEntity.websocketUser.remove(token);

// Refuse connection from client with different version
if (player.getClientVersion() == null || !player.getClientVersion().equalsIgnoreCase(appVersion)) {
Expand Down Expand Up @@ -235,14 +230,4 @@ private void handleSocketClose(Session session) {
Log.warn("[UNDEFINED PLAYER] Disconnected");
}
}

private boolean isTokenValid(String token) {
try {
parser.parse(token, contextInfo);
return true;
} catch (Exception e) {
Log.info(e);
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package fr.zelytra.session.socket.security;

import io.quarkus.security.Authenticated;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

@Authenticated
@Path("/socket")
public class SocketSecurityEndpoints {

@GET
@Path("/register")
@Transactional
@Produces(MediaType.TEXT_PLAIN)
public Response registerClient() {
SocketSecurityEntity socketSecurity = new SocketSecurityEntity();
return Response.ok(socketSecurity.getKey()).build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package fr.zelytra.session.socket.security;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SocketSecurityEntity {


public static Map<String, SocketSecurityEntity> websocketUser = new HashMap<>();

private String key;

private long validity;

public SocketSecurityEntity() {
this.validity = new Date().toInstant().plusSeconds(30).toEpochMilli();
this.key = UUID.randomUUID().toString();
websocketUser.put(this.key, this);
}

public boolean isValid() {
return this.validity >= new Date().toInstant().toEpochMilli();
}

public String getKey() {
return key;
}
}
8 changes: 2 additions & 6 deletions backend/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,9 @@ quarkus.hibernate-orm.database.generation=update
quarkus.oidc.auth-server-url=${KEYCLOAK_HOST:http://127.0.0.1:2604/auth}/realms/Betterfleet
quarkus.oidc.client-id=${KEYCLOAK_CLIENT_ID:application}

# SmallRye JWT
mp.jwt.verify.publickey.location=${KEYCLOAK_HOST:http://127.0.0.1:2604/auth}/realms/Betterfleet/protocol/openid-connect/certs
mp.jwt.verify.issuer=${KEYCLOAK_HOST:http://127.0.0.1:2604/auth}/realms/Betterfleet

# Debug
quarkus.log.category."io.quarkus.oidc".level=DEBUG
quarkus.log.category."io.smallrye.jwt".level=DEBUG
#quarkus.log.category."io.quarkus.oidc".level=DEBUG
#quarkus.log.category."io.smallrye.jwt".level=DEBUG

# Custom variables
proxy.check.api.key=${PROXY_CHECK_API_KEY}
Expand Down
2 changes: 2 additions & 0 deletions deployment/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ services:
DB_DATABASE: BetterFleet
DB_USER: ${POSTGRES_USER}
DB_PASSWORD: ${POSTGRES_PASSWORD}
KEYCLOAK_HOST: ${PUBLIC_KEYCLOAK_HOSTNAME}
restart: unless-stopped

frontend:
Expand All @@ -43,6 +44,7 @@ services:
- "2602:80"
environment:
VITE_BACKEND_HOST: ${PUBLIC_QUARKUS_HOSTNAME}
VITE_KEYCLOAK_HOST: ${PUBLIC_KEYCLOAK_HOSTNAME}
restart: unless-stopped

postgres-auth:
Expand Down
1 change: 1 addition & 0 deletions webapp/.env.production
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
VITE_BACKEND_HOST="https://pre-prod.betterfleet.fr/api"
VITE_SOCKET_HOST=wss://pre-prod.betterfleet.fr/api/sessions
VITE_KEYCLOAK_HOST=https://pre-prod.betterfleet.fr/auth
VITE_VERSION=$npm_package_version
Loading

0 comments on commit 061ece8

Please sign in to comment.