Accès tablette : vérification du réseau et autorisation pare-feu en un clic
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 42s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 51s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 1m33s
Build & Push Images / build (brain) (push) Successful in 1m39s
Build & Push Images / build (web) (push) Successful in 2m3s
Build & Push Images / build-switcher (push) Successful in 25s
Build & Push Images / build (core) (push) Successful in 4m13s

Constat terrain : le téléphone chargeait sans fin — le pare-feu Windows
n'avait aucune règle pour DM Loremind (la fenêtre d'autorisation n'apparaît
pas toujours) et le Wi-Fi était classé « Public » par défaut.

- Bloc « Vérification du réseau » dans Paramètres > Accès depuis une
  tablette : lit le type des réseaux connectés et les règles entrantes du
  pare-feu visant l'appli (PowerShell, lecture seule, sans droits admin).
- Bouton « Autoriser dans le pare-feu » : confirmation administrateur
  Windows (UAC), règle limitée aux réseaux privés, blocages éventuels de
  l'appli retirés ; résultat affiché (appliqué / annulé / échec).
- Réseau classé « Public » : explication + bouton « Ouvrir les réglages
  réseau » (le profil réseau reste un choix de l'utilisateur).
- Textes et doc corrigés (fin de la consigne trompeuse « réseaux privés
  uniquement ») ; section « La tablette charge sans fin » avec la commande
  manuelle de secours.

Vérifié : core clean verify (1219 tests, dont une vraie lecture du système
sur Windows), web build + 337 vitest, lint sans erreur, bloc vérifié en mode
bureau isolé.
À redéployer : core + web (mode bureau ; aucune migration).
This commit is contained in:
2026-10-17 14:41:54 +02:00
parent d926545e3d
commit 8c6b642975
15 changed files with 782 additions and 7 deletions
@@ -0,0 +1,67 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Verdict « une tablette peut-elle joindre ce PC ? », calculé à partir des faits lus sur
* le système. Logique pure (testable sans Windows).
*
* @param supported vérification possible (Windows)
* @param ready rien ne bloque côté PC
* @param publicNetworks réseaux connectés classés « Public » que le pare-feu ne laisse pas passer
* @param firewallAllowed une règle active autorise l'application sur les réseaux privés
* @param firewallBlocked une règle active BLOQUE l'application (ex. « Annuler » dans la fenêtre Windows)
* @param program exécutable concerné
*/
public record NetworkReadiness(
boolean supported,
boolean ready,
List<String> publicNetworks,
boolean firewallAllowed,
boolean firewallBlocked,
String program
) {
static final String PUBLIC = "Public";
static final String PRIVATE = "Private";
public static NetworkReadiness evaluate(NetworkSnapshot snapshot) {
if (snapshot == null || !snapshot.supported()) {
return new NetworkReadiness(false, false, List.of(), false, false, null);
}
List<NetworkSnapshot.FirewallRule> rules = snapshot.rules() == null ? List.of() : snapshot.rules();
boolean allowedPrivate = covers(rules, "Allow", PRIVATE);
boolean blockedPrivate = covers(rules, "Block", PRIVATE);
boolean publicOpen = covers(rules, "Allow", PUBLIC) && !covers(rules, "Block", PUBLIC);
List<String> publicNetworks = (snapshot.networks() == null ? List.<NetworkSnapshot.Network>of() : snapshot.networks())
.stream()
.filter(n -> PUBLIC.equalsIgnoreCase(n.category()))
.map(n -> n.name() != null && !n.name().isBlank() ? n.name() : n.alias())
.toList();
// Un réseau public n'est un obstacle que si le pare-feu ne l'ouvre pas explicitement.
List<String> blockingPublic = publicOpen ? List.of() : publicNetworks;
boolean ready = allowedPrivate && !blockedPrivate && blockingPublic.isEmpty();
return new NetworkReadiness(true, ready, blockingPublic, allowedPrivate, blockedPrivate, snapshot.program());
}
/** Une règle ACTIVE de cette action couvre-t-elle ce profil (« Any » couvre tout) ? */
private static boolean covers(List<NetworkSnapshot.FirewallRule> rules, String action, String profile) {
return rules.stream()
.filter(r -> action.equalsIgnoreCase(r.action()) && "True".equalsIgnoreCase(r.enabled()))
.anyMatch(r -> profiles(r.profile()).stream().anyMatch(p -> p.equals("any") || p.equals(profile.toLowerCase(Locale.ROOT))));
}
private static List<String> profiles(String raw) {
if (raw == null) return List.of();
return Arrays.stream(raw.split(","))
.map(s -> s.trim().toLowerCase(Locale.ROOT))
.filter(s -> !s.isEmpty())
.toList();
}
}
@@ -0,0 +1,30 @@
package com.loremind.domain.remoteaccess;
import java.util.List;
/**
* Faits bruts sur la machine hôte, lus par le système (pas d'interprétation ici) :
* réseaux connectés avec leur catégorie Windows, et règles ENTRANTES du pare-feu qui
* visent l'exécutable de l'application.
*
* @param supported vérification possible sur ce système (Windows uniquement)
* @param program exécutable visé par les règles (DM Loremind.exe en bureau)
* @param networks réseaux connectés
* @param rules règles entrantes du pare-feu pour ce programme
*/
public record NetworkSnapshot(boolean supported, String program, List<Network> networks, List<FirewallRule> rules) {
/** Catégorie Windows : {@code Public}, {@code Private} ou {@code DomainAuthenticated}. */
public record Network(String name, String alias, String category) {}
/**
* @param action {@code Allow} ou {@code Block}
* @param profile profils couverts : {@code Any}, ou liste comme {@code Private, Public}
* @param enabled {@code True} / {@code False}
*/
public record FirewallRule(String action, String profile, String enabled) {}
public static NetworkSnapshot unsupported() {
return new NetworkSnapshot(false, null, List.of(), List.of());
}
}
@@ -0,0 +1,26 @@
package com.loremind.domain.remoteaccess.ports;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
/**
* Port vers le système hôte pour que l'accès distant fonctionne vraiment : sans règle
* de pare-feu, ou sur un réseau classé « Public », Windows jette en silence les requêtes
* de la tablette (elle charge sans fin).
*/
public interface HostNetworkAccess {
/** Résultat de la demande d'autorisation dans le pare-feu. */
enum FirewallFixOutcome { APPLIED, CANCELLED, FAILED, UNSUPPORTED }
/** Lecture seule, sans droits administrateur. */
NetworkSnapshot inspect();
/**
* Autorise l'application en entrée sur les réseaux privés. Passe par la confirmation
* administrateur du système (UAC) : bloque jusqu'à la réponse de l'utilisateur.
*/
FirewallFixOutcome allowThroughFirewall();
/** Ouvre la page des réglages réseau du système (pour passer un Wi-Fi en « Privé »). */
void openNetworkSettings();
}
@@ -0,0 +1,208 @@
package com.loremind.infrastructure.desktop;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* Accès au réseau et au pare-feu de Windows pour l'accès distant (mode bureau).
* <p>
* Lecture via PowerShell, sans droits administrateur. L'autorisation dans le pare-feu
* passe par {@code Start-Process -Verb RunAs} : Windows affiche sa confirmation
* administrateur (UAC) et l'utilisateur garde la main. La règle créée n'ouvre DM Loremind
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
* (réglage système, jamais modifié par l'application).
* <p>
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
*/
@Component
@Profile("local")
public class WindowsHostNetworkAccess implements HostNetworkAccess {
private static final Logger log = LoggerFactory.getLogger(WindowsHostNetworkAccess.class);
static final String RULE_NAME = "DM Loremind (accès tablette)";
private static final long INSPECT_TIMEOUT_S = 20;
/** Le temps pour l'utilisateur de lire et de répondre à la fenêtre UAC. */
private static final long ELEVATION_TIMEOUT_S = 180;
/** Code Windows ERROR_CANCELLED : l'utilisateur a refusé la confirmation administrateur. */
private static final int EXIT_CANCELLED = 1223;
private final ObjectMapper objectMapper;
public WindowsHostNetworkAccess(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public NetworkSnapshot inspect() {
String program = currentProgram();
if (!isWindows() || program == null) return NetworkSnapshot.unsupported();
try {
String json = runPowerShell(inspectScript(program), INSPECT_TIMEOUT_S).output();
return parseSnapshot(objectMapper, program, json);
} catch (IOException | RuntimeException e) {
log.warn("Accès distant : lecture du réseau / pare-feu impossible : {}", e.getMessage());
return NetworkSnapshot.unsupported();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return NetworkSnapshot.unsupported();
}
}
@Override
public FirewallFixOutcome allowThroughFirewall() {
String program = currentProgram();
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
String outer = "try {\n"
+ " $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
+ "-ArgumentList @('-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','"
+ encode(allowScript(program)) + "')\n"
+ " exit $p.ExitCode\n"
+ "} catch { exit " + EXIT_CANCELLED + " }\n";
try {
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode();
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
log.info("Accès distant : autorisation pare-feu → {}", outcome);
return outcome;
} catch (IOException | RuntimeException e) {
log.warn("Accès distant : autorisation pare-feu impossible : {}", e.getMessage());
return FirewallFixOutcome.FAILED;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return FirewallFixOutcome.FAILED;
}
}
@Override
public void openNetworkSettings() {
if (!isWindows()) return;
try {
// « État du réseau » : le réseau connecté et son bouton « Propriétés » (type de profil).
new ProcessBuilder("cmd", "/c", "start", "", "ms-settings:network-status").start();
} catch (IOException e) {
log.warn("Ouverture des réglages réseau impossible : {}", e.getMessage());
}
}
// --- Scripts --------------------------------------------------------------------------
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */
static String inspectScript(String program) {
return "$ErrorActionPreference = 'SilentlyContinue'\n"
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
+ "$p = '" + psQuote(program) + "'\n"
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n"
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
+ "[pscustomobject]@{ networks = $nets; rules = $rules } | ConvertTo-Json -Depth 4 -Compress\n";
}
/**
* Exécuté ÉLEVÉ : retire les blocages entrants visant CE programme (créés par un « Annuler »
* dans la fenêtre du pare-feu, ils l'emporteraient sur toute autorisation), remplace notre
* propre règle si elle existe, puis autorise sur les réseaux privés uniquement.
*/
static String allowScript(String program) {
String name = psQuote(RULE_NAME);
return "try {\n"
+ " $p = '" + psQuote(program) + "'\n"
+ " Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' -and $_.Action.ToString() -eq 'Block' } | "
+ "Remove-NetFirewallRule\n"
+ " Get-NetFirewallRule -DisplayName '" + name + "' -ErrorAction SilentlyContinue | Remove-NetFirewallRule\n"
+ " New-NetFirewallRule -DisplayName '" + name + "' -Direction Inbound -Program $p -Action Allow "
+ "-Profile Private -ErrorAction Stop | Out-Null\n"
+ " exit 0\n"
+ "} catch { exit 2 }\n";
}
static NetworkSnapshot parseSnapshot(ObjectMapper mapper, String program, String json) throws IOException {
JsonNode root = mapper.readTree(json == null || json.isBlank() ? "{}" : json.trim());
List<NetworkSnapshot.Network> networks = new ArrayList<>();
for (JsonNode n : array(root.path("networks"))) {
networks.add(new NetworkSnapshot.Network(text(n, "name"), text(n, "alias"), text(n, "category")));
}
List<NetworkSnapshot.FirewallRule> rules = new ArrayList<>();
for (JsonNode r : array(root.path("rules"))) {
rules.add(new NetworkSnapshot.FirewallRule(text(r, "action"), text(r, "profile"), text(r, "enabled")));
}
return new NetworkSnapshot(true, program, networks, rules);
}
/** ConvertTo-Json écrit un objet seul (pas un tableau) quand la liste n'a qu'un élément. */
private static Iterable<JsonNode> array(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) return List.of();
return node.isArray() ? node : List.of(node);
}
private static String text(JsonNode node, String field) {
JsonNode v = node.get(field);
return v == null || v.isNull() ? null : v.asText();
}
static String psQuote(String value) {
return value.replace("'", "''");
}
static String encode(String script) {
return Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_16LE));
}
// --- Exécution ------------------------------------------------------------------------
private record Result(int exitCode, String output) {}
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start();
process.getOutputStream().close();
// Lecture en parallèle : un tampon de sortie plein bloquerait le processus avant sa fin.
CompletableFuture<String> output = CompletableFuture.supplyAsync(() -> {
try (InputStream out = process.getInputStream()) {
return new String(out.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
return "";
}
});
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
process.destroyForcibly();
throw new IOException("PowerShell n'a pas répondu en " + timeoutSeconds + " s");
}
return new Result(process.exitValue(), output.join());
}
private static boolean isWindows() {
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
}
/** Exécutable du processus courant : DM Loremind.exe en bureau (java.exe en développement). */
private static String currentProgram() {
return ProcessHandle.current().info().command().orElse(null);
}
}
@@ -1,8 +1,10 @@
package com.loremind.infrastructure.web.controller;
import com.loremind.application.remoteaccess.NetworkReadiness;
import com.loremind.application.remoteaccess.PairingCode;
import com.loremind.application.remoteaccess.RemoteAccessService;
import com.loremind.application.remoteaccess.RemoteAccessStatus;
import com.loremind.domain.remoteaccess.ports.HostNetworkAccess;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -29,13 +31,18 @@ import java.util.Map;
public class RemoteAccessAdminController {
private final RemoteAccessService remoteAccessService;
private final HostNetworkAccess hostNetworkAccess;
public RemoteAccessAdminController(RemoteAccessService remoteAccessService) {
public RemoteAccessAdminController(RemoteAccessService remoteAccessService, HostNetworkAccess hostNetworkAccess) {
this.remoteAccessService = remoteAccessService;
this.hostNetworkAccess = hostNetworkAccess;
}
public record ConfigureRequest(boolean enabled, int port) {}
/** Réponse du bouton « Autoriser dans le pare-feu » : ce qui s'est passé + le nouvel état. */
public record FirewallFixResponse(HostNetworkAccess.FirewallFixOutcome outcome, NetworkReadiness readiness) {}
@GetMapping
public RemoteAccessStatus status() {
return remoteAccessService.status();
@@ -51,6 +58,26 @@ public class RemoteAccessAdminController {
return remoteAccessService.newPairingCode();
}
/** Une tablette peut-elle joindre ce PC ? (type de réseau, règle du pare-feu) */
@GetMapping("/network-check")
public NetworkReadiness networkCheck() {
return NetworkReadiness.evaluate(hostNetworkAccess.inspect());
}
/** Ajoute la règle du pare-feu ; attend la réponse de l'utilisateur à la confirmation Windows (UAC). */
@PostMapping("/firewall-rule")
public FirewallFixResponse allowThroughFirewall() {
HostNetworkAccess.FirewallFixOutcome outcome = hostNetworkAccess.allowThroughFirewall();
return new FirewallFixResponse(outcome, NetworkReadiness.evaluate(hostNetworkAccess.inspect()));
}
/** Ouvre les réglages réseau de Windows (pour passer un Wi-Fi « Public » en « Privé »). */
@PostMapping("/open-network-settings")
public ResponseEntity<Void> openNetworkSettings() {
hostNetworkAccess.openNetworkSettings();
return ResponseEntity.noContent().build();
}
@DeleteMapping("/devices/{id}")
public ResponseEntity<Void> revoke(@PathVariable String id) {
return remoteAccessService.revoke(id) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
@@ -0,0 +1,79 @@
package com.loremind.application.remoteaccess;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import com.loremind.domain.remoteaccess.NetworkSnapshot.FirewallRule;
import com.loremind.domain.remoteaccess.NetworkSnapshot.Network;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/** Test du verdict « une tablette peut-elle joindre ce PC ? » à partir des faits lus sur Windows. */
class NetworkReadinessTest {
private static final Network HOME_PRIVATE = new Network("Bbox-Maison", "Wi-Fi", "Private");
private static final Network HOME_PUBLIC = new Network("Bbox-Maison", "Wi-Fi", "Public");
private static final FirewallRule ALLOW_PRIVATE = new FirewallRule("Allow", "Private", "True");
private static NetworkReadiness eval(List<Network> networks, List<FirewallRule> rules) {
return NetworkReadiness.evaluate(new NetworkSnapshot(true, "C:\\DM Loremind.exe", networks, rules));
}
@Test
void unsupported_whenNotWindows() {
NetworkReadiness r = NetworkReadiness.evaluate(NetworkSnapshot.unsupported());
assertFalse(r.supported());
assertFalse(r.ready());
}
@Test
void ready_onPrivateNetwork_withAllowRule() {
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of(ALLOW_PRIVATE));
assertTrue(r.ready());
assertTrue(r.firewallAllowed());
assertTrue(r.publicNetworks().isEmpty());
}
@Test
void notReady_withoutAnyRule_evenOnPrivateNetwork() {
// Cas réel du 2026-10-17 : Wi-Fi passé en privé, mais aucune règle → la tablette charge sans fin.
NetworkReadiness r = eval(List.of(HOME_PRIVATE), List.of());
assertFalse(r.ready());
assertFalse(r.firewallAllowed());
}
@Test
void notReady_onPublicNetwork_evenWithPrivateRule() {
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(ALLOW_PRIVATE));
assertFalse(r.ready());
assertEquals(List.of("Bbox-Maison"), r.publicNetworks());
}
@Test
void publicNetwork_isNotAnObstacle_whenPublicExplicitlyAllowed() {
NetworkReadiness r = eval(List.of(HOME_PUBLIC), List.of(new FirewallRule("Allow", "Private, Public", "True")));
assertTrue(r.ready());
assertTrue(r.publicNetworks().isEmpty());
}
@Test
void blockRule_winsOverAllow() {
NetworkReadiness r = eval(List.of(HOME_PRIVATE),
List.of(ALLOW_PRIVATE, new FirewallRule("Block", "Any", "True")));
assertFalse(r.ready());
assertTrue(r.firewallBlocked());
}
@Test
void disabledRules_areIgnored_andAnyCoversPrivate() {
assertFalse(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Private", "False"))).ready());
assertTrue(eval(List.of(HOME_PRIVATE), List.of(new FirewallRule("Allow", "Any", "True"))).ready());
}
@Test
void publicNetwork_withoutName_usesInterfaceAlias() {
NetworkReadiness r = eval(List.of(new Network(null, "Wi-Fi", "Public")), List.of(ALLOW_PRIVATE));
assertEquals(List.of("Wi-Fi"), r.publicNetworks());
}
}
@@ -0,0 +1,73 @@
package com.loremind.infrastructure.desktop;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loremind.domain.remoteaccess.NetworkSnapshot;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test de {@link WindowsHostNetworkAccess} : lecture du JSON de PowerShell (objet seul ou
* tableau), contenu des scripts, et — sur Windows seulement — un vrai appel en lecture seule.
*/
class WindowsHostNetworkAccessTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void parse_handlesSingleObjectsAndArrays() throws Exception {
// ConvertTo-Json écrit un objet (pas un tableau) quand il n'y a qu'un élément.
String json = "{\"networks\":{\"name\":\"Bbox\",\"alias\":\"Wi-Fi\",\"category\":\"Private\"},"
+ "\"rules\":[{\"action\":\"Allow\",\"profile\":\"Private\",\"enabled\":\"True\"},"
+ "{\"action\":\"Block\",\"profile\":\"Public\",\"enabled\":\"True\"}]}";
NetworkSnapshot s = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", json);
assertTrue(s.supported());
assertEquals(1, s.networks().size());
assertEquals("Private", s.networks().get(0).category());
assertEquals(2, s.rules().size());
assertEquals("Block", s.rules().get(1).action());
}
@Test
void parse_handlesEmptyLists_andEmptyOutput() throws Exception {
NetworkSnapshot empty = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", "{\"networks\":[],\"rules\":[]}");
assertTrue(empty.networks().isEmpty());
assertTrue(empty.rules().isEmpty());
NetworkSnapshot blank = WindowsHostNetworkAccess.parseSnapshot(mapper, "C:\\app.exe", " ");
assertTrue(blank.networks().isEmpty());
}
@Test
void scripts_quoteThePath_andOnlyOpenPrivateNetworks() {
String path = "C:\\Users\\l'MJ\\DM Loremind.exe";
String allow = WindowsHostNetworkAccess.allowScript(path);
assertTrue(allow.contains("'C:\\Users\\l''MJ\\DM Loremind.exe'"), "apostrophe doublée dans la chaîne PowerShell");
assertTrue(allow.contains("-Profile Private"));
assertFalse(allow.contains("Public"), "la règle ne doit jamais ouvrir les réseaux publics");
assertTrue(allow.contains("Remove-NetFirewallRule"), "les blocages de CE programme sont retirés");
assertTrue(WindowsHostNetworkAccess.inspectScript(path).contains("ConvertTo-Json"));
}
@Test
void encode_isUtf16LeBase64_asExpectedByEncodedCommand() {
String encoded = WindowsHostNetworkAccess.encode("é");
assertEquals("é", new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_16LE));
}
@Test
@EnabledOnOs(OS.WINDOWS)
void inspect_readsTheRealSystem_onWindows() {
NetworkSnapshot s = new WindowsHostNetworkAccess(mapper).inspect();
assertTrue(s.supported(), "PowerShell doit répondre en lecture seule sur Windows");
assertNotNull(s.program());
}
}