Appli de bureau : accès depuis une tablette sur le réseau local (appairage par code, migration V25)
- Activation dans Paramètres > « Accès depuis une tablette » (raccourci tray « Connecter une tablette… ») : un second connecteur Tomcat s'ouvre à chaud sur le réseau local (port 8765 par défaut, modifiable) ; le connecteur habituel reste sur 127.0.0.1, rien ne change pour qui n'active rien. - Appairage : QR code + code à 6 chiffres (5 min, usage unique, 5 essais, 20 échecs/min au total) échangé contre un jeton d'appareil posé en cookie HttpOnly + SameSite=Strict ; seule son empreinte SHA-256 est stockée (tables remote_access_config et remote_devices, migration V25). - RemoteAccessFilter (avant le HTTP Basic) : depuis le réseau, API réservée aux appareils appairés (sinon 401 → écran /pair côté front) ; Paramètres, données, mises à jour et licence toujours refusés (403), même appairé. - Front : section Paramètres (adresse, QR code, compte à rebours, appareils autorisés avec « Retirer l'accès »), écran d'appairage plein écran, intercepteur de redirection ; dépendance qrcode. - Mode bureau uniquement (profil local) : Docker inchangé. Vérifié : core clean verify (1205 tests, dont un test d'intégration sur un vrai Tomcat : ouverture/fermeture du port, filtre, appairage + cookie), migration V25 sur H2, web build + 303 vitest, lint sans erreur, parcours PC et tablette testés en mode bureau isolé ; doc à jour (accès tablette + Tailscale). À redéployer : core (migration V25) + web.
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Vue publique d'un appareil appairé (jamais l'empreinte du jeton). */
|
||||
public record PairedDevice(String id, String name, String userAgent, Instant createdAt, Instant lastSeenAt) {
|
||||
|
||||
static PairedDevice of(RemoteDevice d) {
|
||||
return new PairedDevice(d.getId(), d.getName(), d.getUserAgent(), d.getCreatedAt(), d.getLastSeenAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Code d'appairage à 6 chiffres affiché sur le PC (usage unique). */
|
||||
public record PairingCode(String code, Instant expiresAt) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
/** Appairage refusé : code absent, faux, expiré, ou trop d'essais. Message prêt à afficher. */
|
||||
public class PairingRejectedException extends RuntimeException {
|
||||
|
||||
public PairingRejectedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
/**
|
||||
* Résultat d'un appairage réussi.
|
||||
*
|
||||
* @param token jeton d'appareil en clair : à poser en cookie, jamais renvoyé dans le corps
|
||||
* @param device l'appareil enregistré
|
||||
*/
|
||||
public record PairingResult(String token, PairedDevice device) {
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.Deque;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||
* <p>
|
||||
* Modèle de confiance : le connecteur habituel reste limité à la machine (127.0.0.1) et
|
||||
* n'exige rien, comme avant. Quand le MJ active l'accès distant, un SECOND connecteur
|
||||
* s'ouvre sur le réseau local ; tout ce qui y arrive doit présenter un jeton d'appareil,
|
||||
* obtenu en saisissant un code à 6 chiffres affiché sur le PC (usage unique, 5 minutes,
|
||||
* 5 essais). Les Paramètres restent réservés à la machine (filtre {@code RemoteAccessFilter}).
|
||||
* <p>
|
||||
* Uniquement en mode bureau (profil {@code local}) : en Docker, rien de tout ceci n'existe.
|
||||
*/
|
||||
@Service
|
||||
@Profile("local")
|
||||
public class RemoteAccessService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RemoteAccessService.class);
|
||||
|
||||
static final Duration CODE_TTL = Duration.ofMinutes(5);
|
||||
static final int CODE_MAX_ATTEMPTS = 5;
|
||||
/** Garde-fou anti force brute tous codes confondus : au-delà, plus aucun essai pendant 1 min. */
|
||||
static final int GLOBAL_MAX_FAILURES_PER_MINUTE = 20;
|
||||
/** On ne réécrit « vu pour la dernière fois » qu'au plus une fois par minute et par appareil. */
|
||||
static final Duration TOUCH_INTERVAL = Duration.ofMinutes(1);
|
||||
static final int DEVICE_NAME_MAX = 100;
|
||||
static final int USER_AGENT_MAX = 300;
|
||||
|
||||
private final RemoteAccessConfigRepository configRepository;
|
||||
private final RemoteDeviceRepository deviceRepository;
|
||||
private final LanConnector lanConnector;
|
||||
private final int localPort;
|
||||
private final Clock clock;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
private PairingCode currentCode;
|
||||
private int attemptsLeft;
|
||||
private final Deque<Instant> recentFailures = new ArrayDeque<>();
|
||||
private String lastError;
|
||||
|
||||
@Autowired
|
||||
public RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||
RemoteDeviceRepository deviceRepository,
|
||||
LanConnector lanConnector,
|
||||
@Value("${server.port:8080}") int localPort) {
|
||||
this(configRepository, deviceRepository, lanConnector, localPort, Clock.systemUTC());
|
||||
}
|
||||
|
||||
RemoteAccessService(RemoteAccessConfigRepository configRepository,
|
||||
RemoteDeviceRepository deviceRepository,
|
||||
LanConnector lanConnector,
|
||||
int localPort,
|
||||
Clock clock) {
|
||||
this.configRepository = configRepository;
|
||||
this.deviceRepository = deviceRepository;
|
||||
this.lanConnector = lanConnector;
|
||||
this.localPort = localPort;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// --- Réglage -----------------------------------------------------------------------
|
||||
|
||||
/** Au démarrage : rouvre le connecteur si l'accès distant était activé. Ne bloque jamais le lancement. */
|
||||
public synchronized void applySavedConfig() {
|
||||
RemoteAccessConfig config = currentConfig();
|
||||
if (!config.enabled()) return;
|
||||
try {
|
||||
lanConnector.start(config.port());
|
||||
lastError = null;
|
||||
} catch (IllegalStateException e) {
|
||||
lastError = e.getMessage();
|
||||
log.warn("Accès distant activé mais connecteur impossible à ouvrir : {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Active ou désactive l'accès distant. À l'activation, le connecteur est ouvert AVANT
|
||||
* d'enregistrer le réglage : un port occupé laisse l'accès désactivé.
|
||||
*
|
||||
* @throws IllegalArgumentException port hors plage ou identique au port local
|
||||
* @throws IllegalStateException port déjà occupé
|
||||
*/
|
||||
public synchronized RemoteAccessStatus configure(boolean enabled, int port) {
|
||||
if (port < 1024 || port > 65535) {
|
||||
throw new IllegalArgumentException("Le port doit être compris entre 1024 et 65535.");
|
||||
}
|
||||
if (port == localPort) {
|
||||
throw new IllegalArgumentException("Choisissez un port différent de celui de l'application (" + localPort + ").");
|
||||
}
|
||||
if (enabled) {
|
||||
lanConnector.start(port);
|
||||
} else {
|
||||
lanConnector.stop();
|
||||
currentCode = null;
|
||||
}
|
||||
lastError = null;
|
||||
configRepository.save(new RemoteAccessConfig(enabled, port));
|
||||
return status();
|
||||
}
|
||||
|
||||
public synchronized RemoteAccessStatus status() {
|
||||
RemoteAccessConfig config = currentConfig();
|
||||
int running = lanConnector.runningPort();
|
||||
List<String> urls = running > 0
|
||||
? lanConnector.lanAddresses().stream().map(ip -> "http://" + ip + ":" + running).toList()
|
||||
: List.of();
|
||||
List<PairedDevice> devices = deviceRepository.findAll().stream()
|
||||
.sorted(Comparator.comparing(RemoteDevice::getCreatedAt, Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.map(PairedDevice::of)
|
||||
.toList();
|
||||
return new RemoteAccessStatus(config.enabled(), config.port(), running > 0, urls, lastError, devices);
|
||||
}
|
||||
|
||||
private RemoteAccessConfig currentConfig() {
|
||||
return configRepository.find().orElseGet(RemoteAccessConfig::disabledByDefault);
|
||||
}
|
||||
|
||||
// --- Appairage -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Nouveau code d'appairage (remplace le précédent).
|
||||
*
|
||||
* @throws IllegalStateException si l'accès distant n'est pas ouvert
|
||||
*/
|
||||
public synchronized PairingCode newPairingCode() {
|
||||
if (lanConnector.runningPort() <= 0) {
|
||||
throw new IllegalStateException("Activez d'abord l'accès depuis le réseau local.");
|
||||
}
|
||||
String code = String.format("%06d", random.nextInt(1_000_000));
|
||||
currentCode = new PairingCode(code, clock.instant().plus(CODE_TTL));
|
||||
attemptsLeft = CODE_MAX_ATTEMPTS;
|
||||
return currentCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Échange un code valide contre un jeton d'appareil (à poser en cookie). Le code est
|
||||
* consommé : un second appareil demande un nouveau code.
|
||||
*
|
||||
* @throws PairingRejectedException code absent, faux, expiré ou trop d'essais
|
||||
*/
|
||||
public synchronized PairingResult pair(String code, String deviceName, String userAgent) {
|
||||
Instant now = clock.instant();
|
||||
pruneFailures(now);
|
||||
if (recentFailures.size() >= GLOBAL_MAX_FAILURES_PER_MINUTE) {
|
||||
throw new PairingRejectedException("Trop d'essais. Patientez une minute.");
|
||||
}
|
||||
if (currentCode == null || now.isAfter(currentCode.expiresAt())) {
|
||||
currentCode = null;
|
||||
recordFailure(now);
|
||||
throw new PairingRejectedException("Aucun code valide : affichez un nouveau code sur le PC.");
|
||||
}
|
||||
if (code == null || !constantTimeEquals(code.trim(), currentCode.code())) {
|
||||
recordFailure(now);
|
||||
if (--attemptsLeft <= 0) {
|
||||
currentCode = null;
|
||||
throw new PairingRejectedException("Trop d'essais : affichez un nouveau code sur le PC.");
|
||||
}
|
||||
throw new PairingRejectedException("Code incorrect.");
|
||||
}
|
||||
currentCode = null;
|
||||
|
||||
String token = newToken();
|
||||
RemoteDevice device = deviceRepository.save(RemoteDevice.builder()
|
||||
.name(clean(deviceName, DEVICE_NAME_MAX, "Appareil"))
|
||||
.tokenHash(sha256(token))
|
||||
.userAgent(clean(userAgent, USER_AGENT_MAX, null))
|
||||
.createdAt(now)
|
||||
.lastSeenAt(now)
|
||||
.build());
|
||||
log.info("Accès distant : appareil appairé « {} »", device.getName());
|
||||
return new PairingResult(token, PairedDevice.of(device));
|
||||
}
|
||||
|
||||
/** Appareil correspondant au jeton présenté, s'il est connu (sinon : appairage requis). */
|
||||
public Optional<RemoteDevice> authenticate(String token) {
|
||||
if (token == null || token.isBlank()) return Optional.empty();
|
||||
Optional<RemoteDevice> device = deviceRepository.findByTokenHash(sha256(token));
|
||||
device.ifPresent(d -> {
|
||||
Instant now = clock.instant();
|
||||
if (d.getLastSeenAt() == null || d.getLastSeenAt().plus(TOUCH_INTERVAL).isBefore(now)) {
|
||||
deviceRepository.touch(d.getId(), now);
|
||||
}
|
||||
});
|
||||
return device;
|
||||
}
|
||||
|
||||
/** Coupe l'accès d'un appareil. */
|
||||
public boolean revoke(String deviceId) {
|
||||
return deviceRepository.deleteById(deviceId);
|
||||
}
|
||||
|
||||
/** Port du connecteur réseau ouvert, ou -1 (pour le filtre : qui vient « de l'extérieur » ?). */
|
||||
public int lanPort() {
|
||||
return lanConnector.runningPort();
|
||||
}
|
||||
|
||||
// --- Outils -----------------------------------------------------------------------------
|
||||
|
||||
private void recordFailure(Instant now) {
|
||||
recentFailures.addLast(now);
|
||||
}
|
||||
|
||||
private void pruneFailures(Instant now) {
|
||||
Instant limit = now.minus(Duration.ofMinutes(1));
|
||||
while (!recentFailures.isEmpty() && recentFailures.peekFirst().isBefore(limit)) {
|
||||
recentFailures.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
static String sha256(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 indisponible", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean constantTimeEquals(String a, String b) {
|
||||
return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String clean(String value, int max, String fallback) {
|
||||
if (value == null || value.isBlank()) return fallback;
|
||||
String trimmed = value.strip();
|
||||
return trimmed.length() > max ? trimmed.substring(0, max) : trimmed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* État de l'accès distant, pour l'écran Paramètres du PC.
|
||||
*
|
||||
* @param enabled accès activé (réglage enregistré)
|
||||
* @param port port réseau dédié
|
||||
* @param running connecteur réseau effectivement ouvert
|
||||
* @param urls adresses à taper sur la tablette (une par interface réseau locale)
|
||||
* @param lastError dernière erreur d'ouverture (ex. port occupé au démarrage), ou null
|
||||
* @param devices appareils appairés
|
||||
*/
|
||||
public record RemoteAccessStatus(
|
||||
boolean enabled,
|
||||
int port,
|
||||
boolean running,
|
||||
List<String> urls,
|
||||
String lastError,
|
||||
List<PairedDevice> devices
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.loremind.domain.remoteaccess;
|
||||
|
||||
/**
|
||||
* Réglage de l'accès distant (singleton) : activé ou non, et port réseau ouvert
|
||||
* sur le réseau local quand il l'est.
|
||||
*
|
||||
* @param enabled accès depuis le réseau local autorisé
|
||||
* @param port port réseau dédié (distinct du port local de l'application)
|
||||
*/
|
||||
public record RemoteAccessConfig(boolean enabled, int port) {
|
||||
|
||||
/** Port proposé par défaut : libre en pratique, et distinct du 8080 local. */
|
||||
public static final int DEFAULT_PORT = 8765;
|
||||
|
||||
public static RemoteAccessConfig disabledByDefault() {
|
||||
return new RemoteAccessConfig(false, DEFAULT_PORT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.loremind.domain.remoteaccess;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Appareil (tablette, téléphone) autorisé à accéder à l'application de bureau depuis
|
||||
* le réseau local, après appairage par code.
|
||||
* <p>
|
||||
* <b>Sécurité :</b> seule l'empreinte SHA-256 du jeton est conservée ; le jeton en
|
||||
* clair n'existe que dans le cookie de l'appareil. Révoquer = supprimer la ligne.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class RemoteDevice {
|
||||
|
||||
private String id;
|
||||
|
||||
/** Nom choisi à l'appairage (« Tablette de Léa »), pour s'y retrouver dans la liste. */
|
||||
private String name;
|
||||
|
||||
/** Empreinte SHA-256 (hex) du jeton d'appareil. */
|
||||
private String tokenHash;
|
||||
|
||||
private String userAgent;
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
private Instant lastSeenAt;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Port vers le « second guichet » réseau de l'application de bureau : un connecteur
|
||||
* HTTP ouvert sur le réseau local (toutes interfaces) à côté du connecteur habituel,
|
||||
* qui reste limité à la machine (127.0.0.1).
|
||||
* <p>
|
||||
* Tout ce qui arrive par ce connecteur vient d'un autre appareil (ou de la machine
|
||||
* elle-même via son adresse réseau) et doit présenter un jeton d'appareil.
|
||||
*/
|
||||
public interface LanConnector {
|
||||
|
||||
/**
|
||||
* Ouvre le connecteur sur ce port (le referme d'abord s'il tournait sur un autre).
|
||||
*
|
||||
* @throws IllegalStateException si le port est déjà occupé ou ne peut pas être ouvert
|
||||
*/
|
||||
void start(int port);
|
||||
|
||||
void stop();
|
||||
|
||||
/** Port du connecteur ouvert, ou -1 s'il est fermé. */
|
||||
int runningPort();
|
||||
|
||||
/** Adresses IPv4 de la machine sur le réseau local (pour composer l'URL à taper). */
|
||||
List<String> lanAddresses();
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** Port de persistance du réglage d'accès distant (singleton). */
|
||||
public interface RemoteAccessConfigRepository {
|
||||
|
||||
Optional<RemoteAccessConfig> find();
|
||||
|
||||
RemoteAccessConfig save(RemoteAccessConfig config);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.loremind.domain.remoteaccess.ports;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Port de persistance des appareils appairés. */
|
||||
public interface RemoteDeviceRepository {
|
||||
|
||||
RemoteDevice save(RemoteDevice device);
|
||||
|
||||
Optional<RemoteDevice> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RemoteDevice> findAll();
|
||||
|
||||
void touch(String id, Instant lastSeenAt);
|
||||
|
||||
boolean deleteById(String id);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Mode bureau : rouvre l'accès distant au démarrage s'il avait été activé. */
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class RemoteAccessBootstrap {
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessBootstrap(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void reopenIfEnabled() {
|
||||
remoteAccessService.applySavedConfig();
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,13 @@ public class SystemTrayManager {
|
||||
open.addActionListener(e -> DesktopSingleInstance.openAppInBrowser());
|
||||
popup.add(open);
|
||||
|
||||
// Acces distant : ouvre la section Parametres ou l'on active l'acces
|
||||
// depuis une tablette et ou l'on affiche le code d'appairage.
|
||||
MenuItem remote = new MenuItem("Connecter une tablette…");
|
||||
remote.addActionListener(e -> DesktopSingleInstance.openUrl(
|
||||
"http://localhost:" + DesktopUserConfig.runningPort() + "/settings?section=remote-access"));
|
||||
popup.add(remote);
|
||||
|
||||
popup.addSeparator();
|
||||
|
||||
// Reglages : ouvre loremind.properties (port, identifiants admin) dans
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import org.apache.catalina.connector.Connector;
|
||||
import org.apache.catalina.startup.Tomcat;
|
||||
import org.apache.coyote.http11.AbstractHttp11Protocol;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
|
||||
import org.springframework.boot.web.server.WebServer;
|
||||
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.SocketException;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Second connecteur HTTP de Tomcat, ouvert À CHAUD sur toutes les interfaces quand le MJ
|
||||
* active l'accès distant (mode bureau uniquement).
|
||||
* <p>
|
||||
* Pourquoi un second connecteur plutôt que d'ouvrir le principal : le connecteur habituel
|
||||
* reste sur 127.0.0.1 (aucun changement de comportement, pas d'alerte du pare-feu Windows
|
||||
* chez qui n'active rien), et le port d'arrivée suffit à distinguer une requête locale d'une
|
||||
* requête venue du réseau (cf. {@code RemoteAccessFilter}). Ouverture et fermeture sans
|
||||
* redémarrer l'application.
|
||||
*/
|
||||
@Component
|
||||
@Profile("local")
|
||||
public class TomcatLanConnector implements LanConnector {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TomcatLanConnector.class);
|
||||
|
||||
/** Interfaces à ignorer pour composer l'URL : réseaux virtuels (VM, WSL, Docker, VPN…). */
|
||||
private static final List<String> VIRTUAL_HINTS = List.of(
|
||||
"virtual", "vmware", "vbox", "hyper-v", "vethernet", "docker", "wsl", "loopback", "tap-", "tun");
|
||||
|
||||
private final ApplicationContext context;
|
||||
private Connector connector;
|
||||
|
||||
public TomcatLanConnector(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void start(int port) {
|
||||
if (connector != null && connector.getPort() == port) return;
|
||||
stop();
|
||||
ensurePortFree(port);
|
||||
|
||||
Tomcat tomcat = tomcat();
|
||||
Connector main = tomcat.getConnector();
|
||||
Connector lan = new Connector(main.getProtocolHandlerClassName());
|
||||
lan.setPort(port);
|
||||
lan.setProperty("address", "0.0.0.0");
|
||||
// Mêmes limites d'upload que le connecteur principal (imports PDF volumineux).
|
||||
lan.setMaxPostSize(main.getMaxPostSize());
|
||||
if (main.getProtocolHandler() instanceof AbstractHttp11Protocol<?> mainProtocol
|
||||
&& lan.getProtocolHandler() instanceof AbstractHttp11Protocol<?> lanProtocol) {
|
||||
lanProtocol.setMaxSwallowSize(mainProtocol.getMaxSwallowSize());
|
||||
}
|
||||
try {
|
||||
tomcat.getService().addConnector(lan); // démarre le connecteur : le service tourne déjà
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalStateException("Impossible d'ouvrir le port " + port + " : " + e.getMessage(), e);
|
||||
}
|
||||
connector = lan;
|
||||
log.info("Accès distant : connecteur réseau ouvert sur le port {}", port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void stop() {
|
||||
if (connector == null) return;
|
||||
try {
|
||||
tomcat().getService().removeConnector(connector);
|
||||
connector.destroy();
|
||||
} catch (Exception e) {
|
||||
log.warn("Fermeture du connecteur réseau incomplète : {}", e.getMessage());
|
||||
}
|
||||
log.info("Accès distant : connecteur réseau fermé (port {})", connector.getPort());
|
||||
connector = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int runningPort() {
|
||||
return connector != null ? connector.getPort() : -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> lanAddresses() {
|
||||
try {
|
||||
return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
|
||||
.filter(TomcatLanConnector::isPhysicalAndUp)
|
||||
.flatMap(nic -> Collections.list(nic.getInetAddresses()).stream())
|
||||
.filter(a -> a instanceof Inet4Address && a.isSiteLocalAddress())
|
||||
.map(a -> a.getHostAddress())
|
||||
.distinct()
|
||||
// Box domestique d'abord (192.168.x), puis 10.x / 172.16-31.x.
|
||||
.sorted(Comparator.comparing((String ip) -> !ip.startsWith("192.168.")).thenComparing(ip -> ip))
|
||||
.toList();
|
||||
} catch (SocketException e) {
|
||||
log.warn("Lecture des interfaces réseau impossible : {}", e.getMessage());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPhysicalAndUp(NetworkInterface nic) {
|
||||
try {
|
||||
if (!nic.isUp() || nic.isLoopback() || nic.isVirtual() || nic.isPointToPoint()) return false;
|
||||
} catch (SocketException e) {
|
||||
return false;
|
||||
}
|
||||
String label = (nic.getName() + " " + nic.getDisplayName()).toLowerCase(Locale.ROOT);
|
||||
return VIRTUAL_HINTS.stream().noneMatch(label::contains);
|
||||
}
|
||||
|
||||
/** Vérification préalable pour un message clair (sinon Tomcat ne log qu'une trace obscure). */
|
||||
private static void ensurePortFree(int port) {
|
||||
try (ServerSocket probe = new ServerSocket()) {
|
||||
probe.setReuseAddress(false);
|
||||
probe.bind(new InetSocketAddress(port));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Le port " + port + " est déjà utilisé par une autre application.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Tomcat tomcat() {
|
||||
if (context instanceof ServletWebServerApplicationContext web) {
|
||||
WebServer server = web.getWebServer();
|
||||
if (server instanceof TomcatWebServer tomcatServer) {
|
||||
return tomcatServer.getTomcat();
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Serveur web embarqué indisponible.");
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Entité JPA du réglage d'accès distant (migration V25). Singleton : une seule ligne,
|
||||
* {@code id = "current"}, comme la licence.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "remote_access_config")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoteAccessConfigJpaEntity {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean enabled;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int port;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Entité JPA d'un appareil appairé pour l'accès distant (migration V25). */
|
||||
@Entity
|
||||
@Table(name = "remote_devices")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RemoteDeviceJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, length = 64, unique = true)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "user_agent", length = 300)
|
||||
private String userAgent;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "last_seen_at")
|
||||
private Instant lastSeenAt;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteAccessConfigJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface RemoteAccessConfigJpaRepository extends JpaRepository<RemoteAccessConfigJpaEntity, String> {
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteDeviceJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface RemoteDeviceJpaRepository extends JpaRepository<RemoteDeviceJpaEntity, Long> {
|
||||
|
||||
Optional<RemoteDeviceJpaEntity> findByTokenHash(String tokenHash);
|
||||
|
||||
/** Mise à jour ciblée (pas de relecture de l'entité à chaque requête d'une tablette). */
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("update RemoteDeviceJpaEntity d set d.lastSeenAt = :seenAt where d.id = :id")
|
||||
void touch(@Param("id") Long id, @Param("seenAt") Instant seenAt);
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteAccessConfigJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.RemoteAccessConfigJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresRemoteAccessConfigRepository implements RemoteAccessConfigRepository {
|
||||
|
||||
static final String CURRENT_ID = "current";
|
||||
|
||||
private final RemoteAccessConfigJpaRepository jpa;
|
||||
|
||||
public PostgresRemoteAccessConfigRepository(RemoteAccessConfigJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RemoteAccessConfig> find() {
|
||||
return jpa.findById(CURRENT_ID).map(e -> new RemoteAccessConfig(e.isEnabled(), e.getPort()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoteAccessConfig save(RemoteAccessConfig config) {
|
||||
jpa.save(RemoteAccessConfigJpaEntity.builder()
|
||||
.id(CURRENT_ID)
|
||||
.enabled(config.enabled())
|
||||
.port(config.port())
|
||||
.updatedAt(Instant.now())
|
||||
.build());
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.RemoteDeviceJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.RemoteDeviceJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class PostgresRemoteDeviceRepository implements RemoteDeviceRepository {
|
||||
|
||||
private final RemoteDeviceJpaRepository jpa;
|
||||
|
||||
public PostgresRemoteDeviceRepository(RemoteDeviceJpaRepository jpa) {
|
||||
this.jpa = jpa;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoteDevice save(RemoteDevice device) {
|
||||
RemoteDeviceJpaEntity entity = RemoteDeviceJpaEntity.builder()
|
||||
.id(device.getId() != null ? Long.parseLong(device.getId()) : null)
|
||||
.name(device.getName())
|
||||
.tokenHash(device.getTokenHash())
|
||||
.userAgent(device.getUserAgent())
|
||||
.createdAt(device.getCreatedAt() != null ? device.getCreatedAt() : Instant.now())
|
||||
.lastSeenAt(device.getLastSeenAt())
|
||||
.build();
|
||||
return toDomain(jpa.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RemoteDevice> findByTokenHash(String tokenHash) {
|
||||
return jpa.findByTokenHash(tokenHash).map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RemoteDevice> findAll() {
|
||||
return jpa.findAll().stream().map(this::toDomain).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void touch(String id, Instant lastSeenAt) {
|
||||
jpa.touch(Long.parseLong(id), lastSeenAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteById(String id) {
|
||||
Long key = Long.parseLong(id);
|
||||
if (!jpa.existsById(key)) return false;
|
||||
jpa.deleteById(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
private RemoteDevice toDomain(RemoteDeviceJpaEntity e) {
|
||||
return RemoteDevice.builder()
|
||||
.id(String.valueOf(e.getId()))
|
||||
.name(e.getName())
|
||||
.tokenHash(e.getTokenHash())
|
||||
.userAgent(e.getUserAgent())
|
||||
.createdAt(e.getCreatedAt())
|
||||
.lastSeenAt(e.getLastSeenAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Garde de l'accès distant (mode bureau). Ne concerne QUE les requêtes arrivées par le
|
||||
* connecteur réseau local (port dédié) : celles du connecteur habituel (127.0.0.1) passent
|
||||
* sans changement.
|
||||
* <ul>
|
||||
* <li>front statique (hors {@code /api/}) : libre — la tablette doit pouvoir afficher l'écran d'appairage ;</li>
|
||||
* <li>{@code /api/config}, {@code /api/version}, appairage : libres ;</li>
|
||||
* <li>administration (Paramètres, données, mises à jour, licence) : refusée, toujours, même appairé ;</li>
|
||||
* <li>tout le reste de l'API : cookie d'appareil valide, sinon 401 {@code remote_pairing_required}.</li>
|
||||
* </ul>
|
||||
* Pas un {@code @Component} : instancié par {@link SecurityConfig} pour ne pas être enregistré
|
||||
* deux fois (chaîne de sécurité + filtre servlet automatique).
|
||||
*/
|
||||
public class RemoteAccessFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String DEVICE_COOKIE = "lm_device";
|
||||
|
||||
private static final List<String> PUBLIC_PATHS = List.of(
|
||||
"/api/config", "/api/version", "/api/remote-access/pair", "/api/remote-access/session");
|
||||
private static final List<String> LOCAL_ONLY_PREFIXES = List.of(
|
||||
"/api/settings", "/api/admin", "/api/license");
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessFilter(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (!isFromLan(request, remoteAccessService.lanPort())) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String path = request.getRequestURI();
|
||||
if (!path.startsWith("/api/") || PUBLIC_PATHS.contains(path)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
if (LOCAL_ONLY_PREFIXES.stream().anyMatch(path::startsWith)) {
|
||||
reject(response, HttpServletResponse.SC_FORBIDDEN, "remote_forbidden");
|
||||
return;
|
||||
}
|
||||
if (remoteAccessService.authenticate(deviceToken(request)).isPresent()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
reject(response, HttpServletResponse.SC_UNAUTHORIZED, "remote_pairing_required");
|
||||
}
|
||||
|
||||
/** Arrivée par le connecteur réseau local ? (le port d'arrivée suffit : l'autre connecteur est sur 127.0.0.1). */
|
||||
public static boolean isFromLan(HttpServletRequest request, int lanPort) {
|
||||
return lanPort > 0 && request.getLocalPort() == lanPort;
|
||||
}
|
||||
|
||||
public static String deviceToken(HttpServletRequest request) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) return null;
|
||||
for (Cookie cookie : cookies) {
|
||||
if (DEVICE_COOKIE.equals(cookie.getName())) return cookie.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void reject(HttpServletResponse response, int status, String error) throws IOException {
|
||||
response.setStatus(status);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.getWriter().write("{\"error\":\"" + error + "\"}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -14,6 +16,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* Configuration Spring Security.
|
||||
@@ -24,6 +27,9 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
* l'UI elle-meme n'est pas authentifiee (trust model : reseau local ou
|
||||
* reverse-proxy front amont).
|
||||
* <p>
|
||||
* Mode bureau : l'acces depuis une tablette passe par un connecteur reseau dedie,
|
||||
* garde par {@link RemoteAccessFilter} (jeton d'appareil obtenu par code d'appairage).
|
||||
* <p>
|
||||
* Fail-closed : refuse de demarrer si admin.password n'est pas defini.
|
||||
*/
|
||||
@Configuration
|
||||
@@ -58,7 +64,15 @@ public class SecurityConfig {
|
||||
// S4502 : API stateless en HTTP Basic sans cookie — CSRF sans objet (voir javadoc de classe).
|
||||
@SuppressWarnings("java:S4502")
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
public SecurityFilterChain filterChain(HttpSecurity http,
|
||||
ObjectProvider<RemoteAccessService> remoteAccess) throws Exception {
|
||||
// Mode bureau : garde de l'accès distant (tablette sur le réseau local), placée AVANT
|
||||
// le HTTP Basic pour qu'un appareil du réseau ne puisse même pas tenter le mot de
|
||||
// passe admin. Absente en Docker (le service n'existe que sous le profil local).
|
||||
RemoteAccessService remoteAccessService = remoteAccess.getIfAvailable();
|
||||
if (remoteAccessService != null) {
|
||||
http.addFilterBefore(new RemoteAccessFilter(remoteAccessService), BasicAuthenticationFilter.class);
|
||||
}
|
||||
http
|
||||
// API stateless : pas de session, pas de cookie => CSRF sans objet.
|
||||
// Les credentials HTTP Basic sont envoyes a chaque requete, donc
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.remoteaccess.PairingCode;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessStatus;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Réglage de l'accès distant, côté PC (mode bureau). Sous {@code /api/settings} : réservé
|
||||
* à l'admin (HTTP Basic) ET à la machine elle-même ({@code RemoteAccessFilter} refuse ces
|
||||
* routes à tout appareil du réseau, même appairé). 404 en Docker (profil {@code local} absent).
|
||||
*/
|
||||
@RestController
|
||||
@Profile("local")
|
||||
@RequestMapping("/api/settings/remote-access")
|
||||
public class RemoteAccessAdminController {
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemoteAccessAdminController(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
public record ConfigureRequest(boolean enabled, int port) {}
|
||||
|
||||
@GetMapping
|
||||
public RemoteAccessStatus status() {
|
||||
return remoteAccessService.status();
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public RemoteAccessStatus configure(@RequestBody ConfigureRequest request) {
|
||||
return remoteAccessService.configure(request.enabled(), request.port());
|
||||
}
|
||||
|
||||
@PostMapping("/pairing-code")
|
||||
public PairingCode newPairingCode() {
|
||||
return remoteAccessService.newPairingCode();
|
||||
}
|
||||
|
||||
@DeleteMapping("/devices/{id}")
|
||||
public ResponseEntity<Void> revoke(@PathVariable String id) {
|
||||
return remoteAccessService.revoke(id) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
/** Port occupé, accès non ouvert… : conflit d'état, message prêt à afficher. */
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<Map<String, String>> conflict(IllegalStateException e) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.remoteaccess.PairedDevice;
|
||||
import com.loremind.application.remoteaccess.PairingRejectedException;
|
||||
import com.loremind.application.remoteaccess.PairingResult;
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.infrastructure.web.config.RemoteAccessFilter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Appairage d'une tablette (mode bureau) : seules routes d'API joignables depuis le réseau
|
||||
* sans jeton (avec {@code /api/config} et {@code /api/version}).
|
||||
* <p>
|
||||
* Le jeton est posé en cookie {@code HttpOnly} + {@code SameSite=Strict} : envoyé
|
||||
* automatiquement par le navigateur (y compris pour les {@code <img>}), illisible par le
|
||||
* JavaScript de la page, et jamais joint à une requête venue d'un autre site (anti-CSRF).
|
||||
*/
|
||||
@RestController
|
||||
@Profile("local")
|
||||
@RequestMapping("/api/remote-access")
|
||||
public class RemotePairingController {
|
||||
|
||||
static final Duration COOKIE_LIFETIME = Duration.ofDays(365);
|
||||
|
||||
private final RemoteAccessService remoteAccessService;
|
||||
|
||||
public RemotePairingController(RemoteAccessService remoteAccessService) {
|
||||
this.remoteAccessService = remoteAccessService;
|
||||
}
|
||||
|
||||
public record PairRequest(String code, String deviceName) {}
|
||||
|
||||
/** Ce que le front a besoin de savoir pour décider d'afficher l'écran d'appairage. */
|
||||
public record SessionInfo(boolean remote, boolean paired, String deviceName) {}
|
||||
|
||||
@PostMapping("/pair")
|
||||
public ResponseEntity<PairedDevice> pair(@RequestBody PairRequest request,
|
||||
@RequestHeader(value = HttpHeaders.USER_AGENT, required = false) String userAgent) {
|
||||
PairingResult result = remoteAccessService.pair(request.code(), request.deviceName(), userAgent);
|
||||
ResponseCookie cookie = ResponseCookie.from(RemoteAccessFilter.DEVICE_COOKIE, result.token())
|
||||
.httpOnly(true)
|
||||
.sameSite("Strict")
|
||||
.path("/")
|
||||
.maxAge(COOKIE_LIFETIME)
|
||||
.build();
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()).body(result.device());
|
||||
}
|
||||
|
||||
@GetMapping("/session")
|
||||
public SessionInfo session(HttpServletRequest request) {
|
||||
boolean remote = RemoteAccessFilter.isFromLan(request, remoteAccessService.lanPort());
|
||||
if (!remote) return new SessionInfo(false, true, null);
|
||||
Optional<RemoteDevice> device = remoteAccessService.authenticate(RemoteAccessFilter.deviceToken(request));
|
||||
return new SessionInfo(true, device.isPresent(), device.map(RemoteDevice::getName).orElse(null));
|
||||
}
|
||||
|
||||
@ExceptionHandler(PairingRejectedException.class)
|
||||
public ResponseEntity<Map<String, String>> rejected(PairingRejectedException e) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Accès distant à l'application de bureau (tablette / téléphone sur le réseau local).
|
||||
-- remote_access_config : réglage singleton (id = 'current') — activé ou non, port réseau.
|
||||
-- remote_devices : appareils appairés par code ; seule l'EMPREINTE SHA-256 du jeton
|
||||
-- est stockée (le jeton lui-même ne vit que dans le cookie de l'appareil).
|
||||
-- Tables présentes partout (Docker compris) mais utilisées uniquement en mode bureau.
|
||||
-- Compatible Postgres et H2 (MODE=PostgreSQL).
|
||||
create table remote_access_config (
|
||||
id varchar(32) not null,
|
||||
enabled boolean not null,
|
||||
port integer not null,
|
||||
updated_at timestamp(6) with time zone not null,
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
create table remote_devices (
|
||||
id bigint generated by default as identity,
|
||||
name varchar(100) not null,
|
||||
token_hash varchar(64) not null,
|
||||
user_agent varchar(300),
|
||||
created_at timestamp(6) with time zone not null,
|
||||
last_seen_at timestamp(6) with time zone,
|
||||
primary key (id)
|
||||
);
|
||||
create unique index ux_remote_device_token on remote_devices (token_hash);
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
package com.loremind.application.remoteaccess;
|
||||
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test unitaire de {@link RemoteAccessService} avec des doublures en mémoire (pas de Mockito :
|
||||
* l'état des appareils et du connecteur doit vraiment évoluer d'un appel à l'autre).
|
||||
*/
|
||||
class RemoteAccessServiceTest {
|
||||
|
||||
private static final int LOCAL_PORT = 8080;
|
||||
|
||||
private MutableClock clock;
|
||||
private FakeLan lan;
|
||||
private InMemoryDevices devices;
|
||||
private InMemoryConfig config;
|
||||
private RemoteAccessService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock = new MutableClock(Instant.parse("2026-10-17T10:00:00Z"));
|
||||
lan = new FakeLan();
|
||||
devices = new InMemoryDevices();
|
||||
config = new InMemoryConfig();
|
||||
service = new RemoteAccessService(config, devices, lan, LOCAL_PORT, clock);
|
||||
}
|
||||
|
||||
private String freshCode() {
|
||||
service.configure(true, 8765);
|
||||
return service.newPairingCode().code();
|
||||
}
|
||||
|
||||
// --- Réglage ---
|
||||
|
||||
@Test
|
||||
void disabledByDefault_noConnector() {
|
||||
RemoteAccessStatus status = service.status();
|
||||
assertFalse(status.enabled());
|
||||
assertFalse(status.running());
|
||||
assertEquals(RemoteAccessConfig.DEFAULT_PORT, status.port());
|
||||
assertTrue(status.urls().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enable_opensConnector_persists_andListsUrls() {
|
||||
RemoteAccessStatus status = service.configure(true, 8765);
|
||||
|
||||
assertEquals(8765, lan.port);
|
||||
assertTrue(status.running());
|
||||
assertEquals(List.of("http://192.168.1.20:8765"), status.urls());
|
||||
assertEquals(new RemoteAccessConfig(true, 8765), config.saved);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enable_onBusyPort_staysDisabled() {
|
||||
lan.busy = true;
|
||||
assertThrows(IllegalStateException.class, () -> service.configure(true, 8765));
|
||||
assertNull(config.saved);
|
||||
assertFalse(service.status().enabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_portOutOfRange_orSameAsLocalPort() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.configure(true, 80));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.configure(true, LOCAL_PORT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disable_closesConnector_andInvalidatesPendingCode() {
|
||||
String code = freshCode();
|
||||
service.configure(false, 8765);
|
||||
|
||||
assertEquals(-1, lan.port);
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void applySavedConfig_reopensOnBoot_withoutCrashingOnBusyPort() {
|
||||
config.saved = new RemoteAccessConfig(true, 8765);
|
||||
lan.busy = true;
|
||||
|
||||
service.applySavedConfig();
|
||||
|
||||
assertEquals(-1, lan.port);
|
||||
assertNotNull(service.status().lastError());
|
||||
}
|
||||
|
||||
// --- Appairage ---
|
||||
|
||||
@Test
|
||||
void pairingCode_requiresOpenConnector() {
|
||||
assertThrows(IllegalStateException.class, () -> service.newPairingCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pairingCode_isSixDigits() {
|
||||
assertTrue(freshCode().matches("\\d{6}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_withRightCode_issuesToken_storesOnlyItsHash_andConsumesTheCode() {
|
||||
String code = freshCode();
|
||||
|
||||
PairingResult result = service.pair(code, " Tablette de Léa ", "Mozilla/5.0 (iPad)");
|
||||
|
||||
assertEquals("Tablette de Léa", result.device().name());
|
||||
RemoteDevice stored = devices.items.get(0);
|
||||
assertNotEquals(result.token(), stored.getTokenHash());
|
||||
assertEquals(RemoteAccessService.sha256(result.token()), stored.getTokenHash());
|
||||
assertTrue(service.authenticate(result.token()).isPresent());
|
||||
// Code à usage unique.
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Autre", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_rejectsExpiredCode() {
|
||||
String code = freshCode();
|
||||
clock.advance(RemoteAccessService.CODE_TTL.plusSeconds(1));
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
assertTrue(devices.items.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_invalidatesCodeAfterTooManyWrongAttempts() {
|
||||
String code = freshCode();
|
||||
String wrong = code.equals("000000") ? "111111" : "000000";
|
||||
for (int i = 0; i < RemoteAccessService.CODE_MAX_ATTEMPTS; i++) {
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(wrong, "Tablette", null));
|
||||
}
|
||||
// Même le bon code ne passe plus : il faut en afficher un nouveau.
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pair_globalThrottle_blocksBurstAcrossCodes() {
|
||||
for (int i = 0; i < RemoteAccessService.GLOBAL_MAX_FAILURES_PER_MINUTE; i++) {
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair("123456", "x", null));
|
||||
}
|
||||
String code = freshCode();
|
||||
PairingRejectedException blocked =
|
||||
assertThrows(PairingRejectedException.class, () -> service.pair(code, "Tablette", null));
|
||||
assertTrue(blocked.getMessage().contains("minute"));
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
assertDoesNotThrow(() -> service.pair(code, "Tablette", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceName_defaultsAndIsTruncated() {
|
||||
PairingResult unnamed = service.pair(freshCode(), " ", null);
|
||||
assertEquals("Appareil", unnamed.device().name());
|
||||
|
||||
PairingResult longName = service.pair(service.newPairingCode().code(), "x".repeat(300), null);
|
||||
assertEquals(RemoteAccessService.DEVICE_NAME_MAX, longName.device().name().length());
|
||||
}
|
||||
|
||||
// --- Authentification & révocation ---
|
||||
|
||||
@Test
|
||||
void authenticate_unknownOrBlankToken_isEmpty() {
|
||||
assertTrue(service.authenticate(null).isEmpty());
|
||||
assertTrue(service.authenticate("").isEmpty());
|
||||
assertTrue(service.authenticate("inconnu").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticate_touchesLastSeen_atMostOncePerMinute() {
|
||||
String token = service.pair(freshCode(), "Tablette", null).token();
|
||||
devices.touches = 0;
|
||||
|
||||
service.authenticate(token);
|
||||
assertEquals(0, devices.touches);
|
||||
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
service.authenticate(token);
|
||||
assertEquals(1, devices.touches);
|
||||
}
|
||||
|
||||
@Test
|
||||
void revoke_cutsAccess() {
|
||||
PairingResult result = service.pair(freshCode(), "Tablette", null);
|
||||
|
||||
assertTrue(service.revoke(result.device().id()));
|
||||
assertTrue(service.authenticate(result.token()).isEmpty());
|
||||
assertFalse(service.revoke(result.device().id()));
|
||||
}
|
||||
|
||||
// --- Doublures ---
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now;
|
||||
|
||||
MutableClock(Instant now) { this.now = now; }
|
||||
|
||||
void advance(Duration d) { now = now.plus(d); }
|
||||
|
||||
@Override public Instant instant() { return now; }
|
||||
@Override public java.time.ZoneId getZone() { return ZoneOffset.UTC; }
|
||||
@Override public Clock withZone(java.time.ZoneId zone) { return this; }
|
||||
}
|
||||
|
||||
private static final class FakeLan implements LanConnector {
|
||||
int port = -1;
|
||||
boolean busy;
|
||||
|
||||
@Override public void start(int p) {
|
||||
if (busy) throw new IllegalStateException("Le port " + p + " est déjà utilisé par une autre application.");
|
||||
port = p;
|
||||
}
|
||||
@Override public void stop() { port = -1; }
|
||||
@Override public int runningPort() { return port; }
|
||||
@Override public List<String> lanAddresses() { return List.of("192.168.1.20"); }
|
||||
}
|
||||
|
||||
private static final class InMemoryConfig implements RemoteAccessConfigRepository {
|
||||
RemoteAccessConfig saved;
|
||||
|
||||
@Override public Optional<RemoteAccessConfig> find() { return Optional.ofNullable(saved); }
|
||||
@Override public RemoteAccessConfig save(RemoteAccessConfig c) { saved = c; return c; }
|
||||
}
|
||||
|
||||
private static final class InMemoryDevices implements RemoteDeviceRepository {
|
||||
final List<RemoteDevice> items = new ArrayList<>();
|
||||
int touches;
|
||||
private int nextId = 1;
|
||||
|
||||
@Override public RemoteDevice save(RemoteDevice d) {
|
||||
d.setId(String.valueOf(nextId++));
|
||||
items.add(d);
|
||||
return d;
|
||||
}
|
||||
@Override public Optional<RemoteDevice> findByTokenHash(String h) {
|
||||
return items.stream().filter(d -> d.getTokenHash().equals(h)).findFirst();
|
||||
}
|
||||
@Override public List<RemoteDevice> findAll() { return List.copyOf(items); }
|
||||
@Override public void touch(String id, Instant at) {
|
||||
touches++;
|
||||
items.stream().filter(d -> d.getId().equals(id)).forEach(d -> d.setLastSeenAt(at));
|
||||
}
|
||||
@Override public boolean deleteById(String id) { return items.removeIf(d -> d.getId().equals(id)); }
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package com.loremind.infrastructure.desktop;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteAccessConfig;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import com.loremind.domain.remoteaccess.ports.LanConnector;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteAccessConfigRepository;
|
||||
import com.loremind.domain.remoteaccess.ports.RemoteDeviceRepository;
|
||||
import com.loremind.infrastructure.web.config.RemoteAccessFilter;
|
||||
import com.loremind.infrastructure.web.controller.RemotePairingController;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Test d'intégration de l'accès distant sur un VRAI Tomcat : ouverture à chaud du second
|
||||
* connecteur, garde du filtre, appairage par code avec pose du cookie, puis fermeture.
|
||||
* Contexte Spring minimal (ni base, ni sécurité) : seules les briques de l'accès distant.
|
||||
*/
|
||||
@SpringBootTest(classes = TomcatLanConnectorIntegrationTest.App.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = "spring.main.banner-mode=off")
|
||||
class TomcatLanConnectorIntegrationTest {
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration(exclude = {
|
||||
DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, FlywayAutoConfiguration.class,
|
||||
SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
|
||||
@Import(App.Ping.class)
|
||||
static class App {
|
||||
|
||||
@RestController
|
||||
static class Ping {
|
||||
@GetMapping("/api/ping")
|
||||
String ping() { return "pong"; }
|
||||
|
||||
@GetMapping("/api/settings/secret")
|
||||
String secret() { return "admin"; }
|
||||
}
|
||||
|
||||
@Bean
|
||||
TomcatLanConnector lanConnector(ApplicationContext context) {
|
||||
return new TomcatLanConnector(context);
|
||||
}
|
||||
|
||||
@Bean
|
||||
RemoteAccessService remoteAccessService(LanConnector lan) {
|
||||
return new RemoteAccessService(new InMemoryConfig(), new InMemoryDevices(), lan, 1);
|
||||
}
|
||||
|
||||
/** En @Bean : un @Import ignorerait la classe, annotée @Profile("local"). */
|
||||
@Bean
|
||||
RemotePairingController remotePairingController(RemoteAccessService service) {
|
||||
return new RemotePairingController(service);
|
||||
}
|
||||
|
||||
@Bean
|
||||
FilterRegistrationBean<RemoteAccessFilter> remoteAccessFilter(RemoteAccessService service) {
|
||||
return new FilterRegistrationBean<>(new RemoteAccessFilter(service));
|
||||
}
|
||||
}
|
||||
|
||||
@LocalServerPort private int localPort;
|
||||
@Autowired private RemoteAccessService service;
|
||||
@Autowired private TomcatLanConnector lan;
|
||||
|
||||
private final HttpClient http = HttpClient.newHttpClient();
|
||||
|
||||
@AfterEach
|
||||
void closeLan() {
|
||||
lan.stop();
|
||||
}
|
||||
|
||||
private HttpResponse<String> get(int port, String path, String cookie) throws Exception {
|
||||
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path)).GET();
|
||||
if (cookie != null) req.header("Cookie", cookie);
|
||||
return http.send(req.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private HttpResponse<String> post(int port, String path, String json) throws Exception {
|
||||
return http.send(HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + path))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static int freePort() throws IOException {
|
||||
try (ServerSocket s = new ServerSocket(0)) {
|
||||
return s.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void lanConnector_guardsApi_pairsWithCode_andClosesCleanly() throws Exception {
|
||||
// Connecteur habituel : inchangé, aucun jeton demandé.
|
||||
assertEquals(200, get(localPort, "/api/ping", null).statusCode());
|
||||
|
||||
int lanPort = freePort();
|
||||
assertTrue(service.configure(true, lanPort).running());
|
||||
|
||||
// Depuis le réseau : appairage exigé, administration interdite.
|
||||
HttpResponse<String> unpaired = get(lanPort, "/api/ping", null);
|
||||
assertEquals(401, unpaired.statusCode());
|
||||
assertTrue(unpaired.body().contains("remote_pairing_required"));
|
||||
assertEquals(403, get(lanPort, "/api/settings/secret", null).statusCode());
|
||||
|
||||
// Mauvais code puis bon code : le bon pose un cookie HttpOnly + SameSite=Strict.
|
||||
assertEquals(403, post(lanPort, "/api/remote-access/pair", "{\"code\":\"abcdef\",\"deviceName\":\"x\"}").statusCode());
|
||||
String code = service.newPairingCode().code();
|
||||
HttpResponse<String> paired = post(lanPort, "/api/remote-access/pair",
|
||||
"{\"code\":\"" + code + "\",\"deviceName\":\"Tablette de test\"}");
|
||||
assertEquals(200, paired.statusCode());
|
||||
String setCookie = paired.headers().firstValue("Set-Cookie").orElseThrow();
|
||||
assertTrue(setCookie.startsWith(RemoteAccessFilter.DEVICE_COOKIE + "="));
|
||||
assertTrue(setCookie.contains("HttpOnly"));
|
||||
assertTrue(setCookie.contains("SameSite=Strict"));
|
||||
String cookie = setCookie.split(";", 2)[0];
|
||||
|
||||
HttpResponse<String> authorized = get(lanPort, "/api/ping", cookie);
|
||||
assertEquals(200, authorized.statusCode());
|
||||
assertEquals("pong", authorized.body());
|
||||
assertEquals(403, get(lanPort, "/api/settings/secret", cookie).statusCode());
|
||||
assertTrue(get(lanPort, "/api/remote-access/session", cookie).body().contains("\"paired\":true"));
|
||||
|
||||
// Désactivation : le port réseau se ferme, le connecteur local continue.
|
||||
service.configure(false, lanPort);
|
||||
assertThrows(ConnectException.class, () -> get(lanPort, "/api/ping", cookie));
|
||||
assertEquals(200, get(localPort, "/api/ping", null).statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void busyPort_isReportedClearly() throws Exception {
|
||||
try (ServerSocket occupied = new ServerSocket(0)) {
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> service.configure(true, occupied.getLocalPort()));
|
||||
assertTrue(e.getMessage().contains("déjà utilisé"));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Doublures de persistance ---
|
||||
|
||||
static final class InMemoryConfig implements RemoteAccessConfigRepository {
|
||||
private RemoteAccessConfig saved;
|
||||
|
||||
@Override public Optional<RemoteAccessConfig> find() { return Optional.ofNullable(saved); }
|
||||
@Override public RemoteAccessConfig save(RemoteAccessConfig c) { saved = c; return c; }
|
||||
}
|
||||
|
||||
static final class InMemoryDevices implements RemoteDeviceRepository {
|
||||
private final List<RemoteDevice> items = new ArrayList<>();
|
||||
|
||||
@Override public synchronized RemoteDevice save(RemoteDevice d) {
|
||||
d.setId(String.valueOf(items.size() + 1));
|
||||
items.add(d);
|
||||
return d;
|
||||
}
|
||||
@Override public synchronized Optional<RemoteDevice> findByTokenHash(String h) {
|
||||
return items.stream().filter(d -> d.getTokenHash().equals(h)).findFirst();
|
||||
}
|
||||
@Override public synchronized List<RemoteDevice> findAll() { return List.copyOf(items); }
|
||||
@Override public void touch(String id, Instant at) { /* sans objet ici */ }
|
||||
@Override public synchronized boolean deleteById(String id) { return items.removeIf(d -> d.getId().equals(id)); }
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,15 @@ class FlywayMigrationTest {
|
||||
"values ('C', 0, now(), now())");
|
||||
st.executeUpdate("insert into arcs (name, campaign_id, \"order\", type, created_at, updated_at) " +
|
||||
"select 'Quêtes libres', id, 9999, 'SYSTEM', now(), now() from campaigns");
|
||||
|
||||
// V25 : accès distant — réglage singleton + appareils, empreinte de jeton unique.
|
||||
st.executeUpdate("insert into remote_access_config (id, enabled, port, updated_at) " +
|
||||
"values ('current', true, 8765, now())");
|
||||
st.executeUpdate("insert into remote_devices (name, token_hash, created_at) values ('Tablette', 'abc', now())");
|
||||
assertThrows(SQLException.class,
|
||||
() -> st.executeUpdate("insert into remote_devices (name, token_hash, created_at) " +
|
||||
"values ('Doublon', 'abc', now())"),
|
||||
"remote_devices.token_hash doit être unique (V25)");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.application.remoteaccess.RemoteAccessService;
|
||||
import com.loremind.domain.remoteaccess.RemoteDevice;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire de {@link RemoteAccessFilter} : ce qui passe et ce qui est refusé selon
|
||||
* le connecteur d'arrivée (local / réseau), le chemin et le cookie d'appareil.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class RemoteAccessFilterTest {
|
||||
|
||||
private static final int LOCAL_PORT = 8080;
|
||||
private static final int LAN_PORT = 8765;
|
||||
|
||||
@Mock private RemoteAccessService service;
|
||||
private RemoteAccessFilter filter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
filter = new RemoteAccessFilter(service);
|
||||
when(service.lanPort()).thenReturn(LAN_PORT);
|
||||
when(service.authenticate("bon-jeton")).thenReturn(Optional.of(RemoteDevice.builder().id("1").name("Tablette").build()));
|
||||
when(service.authenticate(null)).thenReturn(Optional.empty());
|
||||
when(service.authenticate("mauvais")).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
private record Outcome(boolean passed, int status, String body) {}
|
||||
|
||||
private Outcome run(int localPort, String path, String token) throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", path);
|
||||
request.setLocalPort(localPort);
|
||||
if (token != null) request.setCookies(new Cookie(RemoteAccessFilter.DEVICE_COOKIE, token));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(request, response, chain);
|
||||
return new Outcome(chain.getRequest() != null, response.getStatus(), response.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void localConnector_isUntouched_evenForSettings() throws Exception {
|
||||
assertTrue(run(LOCAL_PORT, "/api/campaigns", null).passed());
|
||||
assertTrue(run(LOCAL_PORT, "/api/settings", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lanClosed_meansEverythingIsLocal() throws Exception {
|
||||
when(service.lanPort()).thenReturn(-1);
|
||||
assertTrue(run(LOCAL_PORT, "/api/campaigns", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_staticFrontAndPublicApi_passWithoutToken() throws Exception {
|
||||
assertTrue(run(LAN_PORT, "/", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/pair", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/main-ABC123.js", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/config", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/remote-access/pair", null).passed());
|
||||
assertTrue(run(LAN_PORT, "/api/remote-access/session", null).passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_api_requiresValidDeviceToken() throws Exception {
|
||||
Outcome none = run(LAN_PORT, "/api/campaigns", null);
|
||||
assertFalse(none.passed());
|
||||
assertEquals(401, none.status());
|
||||
assertTrue(none.body().contains("remote_pairing_required"));
|
||||
|
||||
assertEquals(401, run(LAN_PORT, "/api/images/42", "mauvais").status());
|
||||
assertTrue(run(LAN_PORT, "/api/campaigns", "bon-jeton").passed());
|
||||
assertTrue(run(LAN_PORT, "/api/images/42", "bon-jeton").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lan_adminRoutes_areAlwaysForbidden_evenWhenPaired() throws Exception {
|
||||
for (String path : new String[]{"/api/settings", "/api/settings/remote-access", "/api/admin/data/export", "/api/license"}) {
|
||||
Outcome outcome = run(LAN_PORT, path, "bon-jeton");
|
||||
assertFalse(outcome.passed(), path);
|
||||
assertEquals(403, outcome.status(), path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user