Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/audit_debug_entrees.baseline
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Total de scripts/audit_debug_entrees.py --total (issue #954, SOCLE §8).
# Ne doit pas augmenter : le baisser après avoir instrumenté des fonctions.
218
212
2 changes: 1 addition & 1 deletion scripts/audit_debug_sorties.baseline
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Total de scripts/audit_debug_sorties.py --total (issue #954, SOCLE §8).
# Ne doit pas augmenter : le baisser après avoir instrumenté des fonctions.
255
164
11 changes: 10 additions & 1 deletion src/netcross_api/annotations_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
remove_annotation,
sort_annotations,
)
from netcross_core.logging_config import get_logger
from netcross_core.logging_config import get_logger, summarize
from netcross_core.models import PacketAnnotation

logger = get_logger(__name__)
Expand All @@ -57,19 +57,23 @@ class AnnotationBody(BaseModel):

class _Routes:
def __init__(self, completed_entry: Callable[[str], dict], get_store: Callable[[], Any]) -> None:
logger.debug("_Routes.__init__: entrée")
self._completed_entry = completed_entry
self._get_store = get_store
logger.debug("_Routes.__init__: fin")

def _load(self, analysis_id: str) -> tuple[list[str], dict[str, list[PacketAnnotation]]]:
entry = self._completed_entry(analysis_id)
points = [str(p) for p in (entry.get("document") or {}).get("points", [])]
brut = (entry.get("metadata") or {}).get(METADATA_KEY) or {}
by_point = {p: [annotation_from_dict(i) for i in items] for p, items in brut.items()}
logger.debug("_Routes._load: retour tuple de 2")
return points, by_point

def _save(self, analysis_id: str, by_point: dict[str, list[PacketAnnotation]]) -> None:
doc = {p: [annotation_to_dict(a) for a in sort_annotations(lst)] for p, lst in by_point.items() if lst}
self._get_store().set_metadata(analysis_id, METADATA_KEY, doc)
logger.debug("_Routes._save: fin")

@staticmethod
def _check_point(points: list[str], point: str) -> str:
Expand All @@ -79,10 +83,12 @@ def _check_point(points: list[str], point: str) -> str:
raise HTTPException(
status_code=404, detail=f"Point {point!r} absent de l'analyse (points : {', '.join(points)})"
)
logger.debug("_Routes._check_point: retour point={}", summarize(point, "point"))
return point

@staticmethod
def _document(by_point: dict[str, list[PacketAnnotation]]) -> dict[str, Any]:
logger.debug("_Routes._document: retour dictionnaire")
return {
"annotations": {
p: [annotation_to_dict(a) for a in sort_annotations(lst)] for p, lst in sorted(by_point.items()) if lst
Expand All @@ -102,6 +108,7 @@ def list(
by_point = {cle: by_point.get(cle, [])}
if tag is not None:
by_point = {p: [a for a in lst if a.tag == tag.strip()] for p, lst in by_point.items()}
logger.debug("_Routes.list: retour self._document(…)")
return self._document(by_point)

def add(self, analysis_id: str, body: AnnotationBody) -> dict[str, Any]:
Expand All @@ -115,6 +122,7 @@ def add(self, analysis_id: str, body: AnnotationBody) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=str(exc)) from exc
by_point[point] = add_annotation(by_point.get(point, []), nouvelle)
self._save(analysis_id, by_point)
logger.debug("_Routes.add: retour self._document(…)")
return self._document(by_point)

def delete(
Expand All @@ -136,6 +144,7 @@ def delete(
logger.debug("annotations.delete: absente ({})", exc)
raise HTTPException(status_code=404, detail=f"Annotation introuvable : {exc.args[0]}") from exc
self._save(analysis_id, by_point)
logger.debug("_Routes.delete: retour self._document(…)")
return self._document(by_point)


Expand Down
19 changes: 18 additions & 1 deletion src/netcross_api/bpf_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from pydantic import BaseModel, Field

from netcross_core import bpf_filters
from netcross_core.logging_config import get_logger
from netcross_core.logging_config import get_logger, summarize
from netcross_core.models import BPFFilter

logger = get_logger(__name__)
Expand All @@ -50,11 +50,13 @@ class BPFFilterBody(BaseModel):
def filters_path() -> Path | None:
"""Fichier utilisé : ``$NETCROSS_API_BPF_FILTERS`` ou ``None`` (défaut du cœur)."""
valeur = os.environ.get(BPF_FILTERS_ENV, "").strip()
logger.debug("filters_path: retour Path(valeur).expanduser() if valeur else None")
return Path(valeur).expanduser() if valeur else None


def _document(filtres: list[BPFFilter]) -> dict[str, Any]:
reserves = {f.name for f in bpf_filters.PREDEFINED_BPF_FILTERS}
logger.debug("_document: retour dictionnaire")
return {
"filters": [
{
Expand All @@ -70,12 +72,14 @@ def _document(filtres: list[BPFFilter]) -> dict[str, Any]:

def _erreur_fichier(exc: Exception) -> HTTPException:
logger.warning("bpf-filters : {}", exc)
logger.debug("_erreur_fichier: retour HTTPException(…)")
return HTTPException(status_code=500, detail=str(exc))


def list_bpf_filters() -> dict[str, Any]:
"""Catalogue prédéfini puis filtres enregistrés (la liste de la GUI)."""
try:
logger.debug("list_bpf_filters: retour _document(…)")
return _document(bpf_filters.available_bpf_filters(filters_path()))
except (ValueError, OSError) as exc:
logger.debug("list_bpf_filters: (ValueError, OSError) -> {}", exc)
Expand All @@ -91,11 +95,15 @@ def put_bpf_filter(nom: str, body: BPFFilterBody) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=str(exc)) from exc
cle = nom.strip().casefold()
if any(f.name.casefold() == cle for f in bpf_filters.PREDEFINED_BPF_FILTERS):
logger.debug(
"put_bpf_filter: si any((f.name.casefold() == cle for f in bpf_filters.PREDEFIN… -> levée HTTPException"
)
raise HTTPException(
status_code=409,
detail=f"le nom '{nom.strip()}' est reserve au catalogue predefini : choisir un autre nom",
)
try:
logger.debug("put_bpf_filter: retour _document(…)")
return _document(bpf_filters.upsert_bpf_filter(nouveau, filters_path()))
except (ValueError, OSError) as exc:
logger.debug("put_bpf_filter: (ValueError, OSError) -> {}", exc)
Expand All @@ -106,11 +114,15 @@ def delete_bpf_filter(nom: str) -> dict[str, Any]:
"""Supprime le filtre enregistré ``nom`` ; renvoie la liste à jour."""
cle = nom.strip().casefold()
if any(f.name.casefold() == cle for f in bpf_filters.PREDEFINED_BPF_FILTERS):
logger.debug(
"delete_bpf_filter: si any((f.name.casefold() == cle for f in bpf_filters.PREDEFIN… -> levée HTTPException"
)
raise HTTPException(
status_code=409,
detail=f"le nom '{nom.strip()}' appartient au catalogue predefini : il ne peut pas etre supprime",
)
try:
logger.debug("delete_bpf_filter: retour _document(…)")
return _document(bpf_filters.delete_bpf_filter(nom, filters_path()))
except KeyError as exc:
logger.debug("delete_bpf_filter: KeyError -> {}", exc)
Expand All @@ -132,8 +144,13 @@ def resolve_bpf_library(nom: str) -> str:
cle = nom.strip().casefold()
for f in filtres:
if f.name.casefold() == cle:
logger.debug(
"resolve_bpf_library: si f.name.casefold() == cle -> retour f.expression={}",
summarize(f.expression, "expression"),
)
return f.expression
disponibles = ", ".join(f.name for f in filtres)
logger.debug("resolve_bpf_library: levée HTTPException")
raise HTTPException(
status_code=400,
detail=f"Filtre BPF '{nom.strip()}' introuvable dans la bibliotheque (disponibles : {disponibles})",
Expand Down
14 changes: 13 additions & 1 deletion src/netcross_api/history_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

from fastapi import Depends, FastAPI, HTTPException, Query

from netcross_core.logging_config import get_logger
from netcross_core.logging_config import get_logger, summarize

logger = get_logger(__name__)

Expand All @@ -40,10 +40,12 @@ def require_history_db() -> str:
"""Base configurée, sinon 400 (demande d'enregistrement refusée)."""
path = history_db_path()
if path is None:
logger.debug("require_history_db: si path is None -> levée HTTPException")
raise HTTPException(
status_code=400,
detail=f"historique desactive sur ce serveur : {HISTORY_DB_ENV} non defini",
)
logger.debug("require_history_db: retour path={}", summarize(path, "path"))
return path


Expand All @@ -54,6 +56,7 @@ def record_comparison(findings, baseline_report, current_report, label: str | No

path = history_db_path()
if path is None:
logger.debug("record_comparison: si path is None -> retour dictionnaire vide")
return {}
try:
run_id = record_diff_run(
Expand All @@ -66,8 +69,10 @@ def record_comparison(findings, baseline_report, current_report, label: str | No
)
except HistoryDatabaseError as exc:
logger.warning("historique : enregistrement impossible ({})", exc)
logger.debug("record_comparison: except HistoryDatabaseError -> retour dictionnaire")
return {"history_error": str(exc)}
logger.info("comparaison enregistree dans l'historique (id {}, etiquette {})", run_id, label)
logger.debug("record_comparison: retour dictionnaire")
return {"history_id": run_id}


Expand All @@ -93,8 +98,10 @@ def record_analysis(report, findings, tls_findings, quic_findings, label: str |
)
except HistoryDatabaseError as exc:
logger.warning("historique : enregistrement de l'analyse impossible ({})", exc)
logger.debug("record_analysis: except HistoryDatabaseError -> retour dictionnaire")
return {"history_error": str(exc)}
logger.info("analyse enregistree dans l'historique (id {}, etiquette {})", run_id, label)
logger.debug("record_analysis: retour dictionnaire")
return {"history_id": run_id}


Expand All @@ -111,14 +118,19 @@ async def list_history_route(

path = history_db_path()
if path is None:
logger.debug("register.list_history_route: si path is None -> levée HTTPException")
raise HTTPException(status_code=503, detail=f"historique non configure ({HISTORY_DB_ENV})")
if run_type is not None and run_type not in RUN_TYPES:
logger.debug(
"register.list_history_route: si run_type is not None and run_type not in RUN_TYPES -> levée HTTPExce…"
)
raise HTTPException(status_code=400, detail=f"run_type : analyse ou diff (recu {run_type!r})")
try:
entries = list_history(path, limit=limit, label=label, run_type=run_type)
except HistoryDatabaseError as exc:
logger.warning("historique illisible : {}", exc)
raise HTTPException(status_code=500, detail=str(exc)) from exc
logger.debug("register.list_history_route: retour dictionnaire")
return {"entries": [dataclasses.asdict(e) for e in entries]}

logger.debug("history_routes.register: 1 route")
Loading
Loading