Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86482a048a | ||
|
|
097a27fcf3 | ||
|
|
93f66d6aca | ||
|
|
eef81ea323 |
+5
-2
@@ -28,7 +28,9 @@ PRONOTE_AUTH_MODE=password
|
||||
# PRONOTE_ACCOUNT_PIN=
|
||||
|
||||
# --- CalDAV ---
|
||||
CALDAV_URL=https://caldav.example.com/calendars/user/pronote/
|
||||
# Endpoint commun (URL potentiellement sensible, masquée dans les journaux)
|
||||
CALDAV_ENDPOINT__URL=https://caldav.example.com/calendars/user/pronote/
|
||||
# Ancien nom temporairement supporté avec un avertissement de dépréciation : CALDAV_URL
|
||||
CALDAV_USERNAME=user@example.com
|
||||
CALDAV_PASSWORD=your_caldav_password
|
||||
CALDAV_CALENDAR_PATH=/pronote-sync/
|
||||
@@ -92,7 +94,8 @@ AI_BASE_URL=https://api.openai.com/v1
|
||||
|
||||
# --- Blog ---
|
||||
BLOG_ENABLED=false
|
||||
BLOG_RSS_URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
BLOG_ENDPOINT__URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
# Ancien nom temporairement supporté avec un avertissement de dépréciation : BLOG_RSS_URL
|
||||
|
||||
# --- Divers ---
|
||||
DRY_RUN=false
|
||||
|
||||
+2
-2
@@ -140,7 +140,7 @@
|
||||
"filename": "GUIDE_DEV_PYTHON.md",
|
||||
"hashed_secret": "90bd1b48e958257948487b90bee080ba5ed00caa",
|
||||
"is_verified": false,
|
||||
"line_number": 5186
|
||||
"line_number": 5183
|
||||
}
|
||||
],
|
||||
"tests/unit/test_caldav_gateway.py": [
|
||||
@@ -185,5 +185,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"generated_at": "2026-09-12T22:12:56Z"
|
||||
"generated_at": "2026-09-13T09:52:29Z"
|
||||
}
|
||||
|
||||
+5
-8
@@ -264,7 +264,7 @@ Le projet utilise **`pydantic-settings`** pour valider et charger la configurati
|
||||
| `PRONOTE_USERNAME` | Identifiant Pronote (si `pronotepy` utilisé). | `parent.dupont` | `str` |
|
||||
| `PRONOTE_PASSWORD` | Mot de passe Pronote (si `pronotepy` utilisé). | `SecretStr` (masqué) | `SecretStr` |
|
||||
| `PRONOTE_ENT` | Slug ENT supporté, résolu vers une fonction de `pronotepy.ent`. | `monbureaunumerique` | `str` |
|
||||
| `CALDAV_URL` | URL du serveur CalDAV (masquée en `SecretStr`). | `https://caldav.example.com/calendars/...` | `SecretStr` |
|
||||
| `CALDAV_ENDPOINT__URL` | URL du serveur CalDAV, via l'endpoint commun (masquée en `SecretStr`). | `https://caldav.example.com/calendars/...` | `ExternalEndpoint` |
|
||||
| `CALDAV_USERNAME` | Identifiant CalDAV. | `user@example.com` | `str` |
|
||||
| `CALDAV_PASSWORD` | Mot de passe CalDAV. | `SecretStr` (masqué) | `SecretStr` |
|
||||
| `CALDAV_CALENDAR_PATH` | Chemin du calendrier CalDAV de destination. | `/pronote-sync/` | `str` |
|
||||
@@ -1113,7 +1113,7 @@ La déduplication des articles du blog repose sur leur **GUID** (ou leur URL si
|
||||
|
||||
Aucun fichier d'état local n'est utilisé : l'état est géré en mémoire par run.
|
||||
# Initialisation
|
||||
rss_client = BlogRSSClient(rss_url=settings.blog.rss_url)
|
||||
rss_client = BlogRSSClient(rss_url=settings.blog.endpoint.url.get_secret_value())
|
||||
blog_state = ## (section obsolète supprimée)()
|
||||
|
||||
# Récupération des nouveaux articles
|
||||
@@ -1218,7 +1218,7 @@ Ajouter les variables suivantes dans la configuration :
|
||||
| **Variable** | **Description** | **Valeur par défaut** | **Type** |
|
||||
|----------------------------|-------------------------------------------------------------------------------|-----------------------|-------------------|
|
||||
| `BLOG_ENABLED` | Activer la récupération du blog. | `False` | `bool` |
|
||||
| `BLOG_RSS_URL` | URL du flux RSS du blog. | `https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2` | `str` |
|
||||
| `BLOG_ENDPOINT__URL` | URL du flux RSS via l'endpoint commun (masquée en `SecretStr`). | `https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2` | `ExternalEndpoint` |
|
||||
|
||||
#### 5 bis.9.2 Modèle Pydantic pour la configuration du blog
|
||||
|
||||
@@ -1230,10 +1230,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
class BlogSettings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_prefix="BLOG_", env_file=".env", extra="ignore")
|
||||
enabled: bool = Field(False, description="Activer la récupération du blog")
|
||||
rss_url: str = Field(
|
||||
"https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2",
|
||||
description="URL du flux RSS du blog",
|
||||
)
|
||||
endpoint: ExternalEndpoint
|
||||
```
|
||||
|
||||
**Intégration dans `Settings`** :
|
||||
@@ -1253,7 +1250,7 @@ class Settings(BaseSettings):
|
||||
```ini
|
||||
# --- Blog du collège ---
|
||||
BLOG_ENABLED=true
|
||||
BLOG_RSS_URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
BLOG_ENDPOINT__URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+162
-41
@@ -10,21 +10,76 @@ from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
from datetime import date
|
||||
from typing import Literal
|
||||
from typing import Annotated, Literal
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import (
|
||||
AfterValidator,
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
SecretStr,
|
||||
ValidationInfo,
|
||||
field_serializer,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from pronote_sync.utils.redaction import redact_url
|
||||
|
||||
_EXTERNAL_ENDPOINT_SCHEMES: frozenset[str] = frozenset({"file", "http", "https"})
|
||||
_LOOPBACK_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
||||
|
||||
|
||||
def _validate_external_endpoint_url(value: SecretStr) -> SecretStr:
|
||||
"""Valide la structure et le schéma d'une URL d'endpoint externe.
|
||||
|
||||
:param value: URL potentiellement sensible à valider.
|
||||
:return: URL validée, toujours encapsulée dans ``SecretStr``.
|
||||
:rtype: SecretStr
|
||||
:raises ValueError: Si l'URL est malformée ou utilise un schéma inconnu.
|
||||
"""
|
||||
is_valid = False
|
||||
try:
|
||||
parsed = urlparse(value.get_secret_value())
|
||||
_ = parsed.port
|
||||
is_valid = (
|
||||
parsed.scheme in _EXTERNAL_ENDPOINT_SCHEMES
|
||||
and (parsed.scheme not in {"http", "https"} or parsed.hostname is not None)
|
||||
and (parsed.scheme != "file" or bool(parsed.path))
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
if not is_valid:
|
||||
raise ValueError("Endpoint externe invalide : URL ou schéma non supporté") from None
|
||||
return value
|
||||
|
||||
|
||||
EndpointUrl = Annotated[SecretStr, AfterValidator(_validate_external_endpoint_url)]
|
||||
|
||||
|
||||
class ExternalEndpoint(BaseModel):
|
||||
"""Représente un endpoint externe potentiellement sensible.
|
||||
|
||||
Le socle accepte les transports ``https``, ``http`` et ``file``. Chaque
|
||||
connecteur restreint ensuite cette liste selon sa propre politique de
|
||||
sécurité. L'URL reste encapsulée dans :class:`pydantic.SecretStr` et sa
|
||||
sérialisation conserve uniquement une représentation expurgée.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
|
||||
|
||||
url: EndpointUrl
|
||||
|
||||
@field_serializer("url")
|
||||
def _serialize_url(self, value: SecretStr) -> str:
|
||||
"""Expurge l'URL lors de la sérialisation.
|
||||
|
||||
:param value: URL encapsulée à sérialiser.
|
||||
:return: URL expurgée.
|
||||
:rtype: str
|
||||
"""
|
||||
return redact_url(value.get_secret_value())
|
||||
|
||||
|
||||
class PronoteSettings(BaseSettings):
|
||||
"""Paramètres d'accès à Pronote (flux iCal et API ``pronotepy``).
|
||||
@@ -91,73 +146,88 @@ class CalDAVSettings(BaseSettings):
|
||||
|
||||
Les variables d'environnement correspondantes sont préfixées par
|
||||
``CALDAV_``. L'URL est traitée comme potentiellement sensible (au même
|
||||
titre que ``PRONOTE_ICAL_URL``) : elle est de type ``SecretStr`` et
|
||||
titre que ``PRONOTE_ICAL_ENDPOINT__URL``) : elle est de type ``SecretStr`` et
|
||||
masquée lors de la sérialisation. Par défaut, seul HTTPS est accepté ;
|
||||
HTTP n'est toléré que pour un hôte de boucle locale (``localhost``,
|
||||
``127.0.0.1``, ``::1``) lorsque ``allow_insecure_http`` vaut ``True``.
|
||||
Le nouvel endpoint se configure avec ``CALDAV_ENDPOINT__URL`` ;
|
||||
``CALDAV_URL`` reste temporairement pris en charge avec un avertissement
|
||||
de dépréciation.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_prefix="CALDAV_")
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_nested_delimiter="__",
|
||||
extra="ignore",
|
||||
env_prefix="CALDAV_",
|
||||
)
|
||||
|
||||
allow_insecure_http: bool = False
|
||||
url: SecretStr | None = None
|
||||
endpoint: ExternalEndpoint | None = None
|
||||
url: SecretStr | None = Field(
|
||||
default=None,
|
||||
exclude=True,
|
||||
deprecated="Utiliser endpoint.url à la place (CALDAV_URL obsolète).",
|
||||
)
|
||||
username: str | None = None
|
||||
password: SecretStr | None = None
|
||||
calendar_path: str = "/pronote-sync/"
|
||||
|
||||
@field_serializer("url")
|
||||
def _serialize_url(self, value: SecretStr | None) -> str | None:
|
||||
"""Masque l'URL CalDAV lors de la sérialisation (repr, str, JSON).
|
||||
|
||||
:param value: Valeur du champ ``url`` (secret potentiel).
|
||||
:return: URL avec les éléments sensibles remplacés par ``REDACTED``,
|
||||
ou ``None`` si la valeur est absente.
|
||||
:rtype: str | None
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
return redact_url(value.get_secret_value())
|
||||
|
||||
@field_validator("url")
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _validate_url_https(cls, v: SecretStr | None, info: ValidationInfo) -> SecretStr | None:
|
||||
"""Valide le schéma de l'URL CalDAV (HTTPS obligatoire par défaut).
|
||||
def _migrate_legacy_url(cls, data: object) -> object:
|
||||
"""Migre ``url`` vers l'endpoint commun avec un avertissement.
|
||||
|
||||
:param data: Données brutes du modèle.
|
||||
:return: Données complétées avec ``endpoint`` si nécessaire.
|
||||
:rtype: object
|
||||
"""
|
||||
if not isinstance(data, dict) or data.get("url") is None:
|
||||
return data
|
||||
migrated_data = data.copy()
|
||||
warnings.warn(
|
||||
"CALDAV_URL est obsolète : utiliser CALDAV_ENDPOINT__URL.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if migrated_data.get("endpoint") is None:
|
||||
migrated_data["endpoint"] = {"url": migrated_data["url"]}
|
||||
return migrated_data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_endpoint_policy(self) -> CalDAVSettings:
|
||||
"""Applique la politique HTTPS/HTTP loopback propre à CalDAV.
|
||||
|
||||
HTTPS est toujours accepté. HTTP n'est accepté que pour un hôte de
|
||||
boucle locale (``localhost``, ``127.0.0.1``, ``::1``) et uniquement
|
||||
lorsque ``allow_insecure_http`` vaut ``True``. Les messages d'erreur
|
||||
ne contiennent jamais l'URL brute (susceptible de contenir des
|
||||
identifiants).
|
||||
lorsque ``allow_insecure_http`` vaut ``True``. Les autres schémas du
|
||||
socle commun sont refusés pour ce connecteur.
|
||||
|
||||
:param v: Valeur du champ ``url`` à valider.
|
||||
:param info: Contexte de validation (accès aux autres champs).
|
||||
:return: La valeur validée inchangée.
|
||||
:rtype: SecretStr | None
|
||||
:return: Instance validée inchangée.
|
||||
:rtype: CalDAVSettings
|
||||
:raises ValueError: Si le schéma n'est pas supporté ou si l'URL HTTP
|
||||
n'est pas autorisée.
|
||||
"""
|
||||
if v is None:
|
||||
return v
|
||||
raw_url = v.get_secret_value()
|
||||
if self.endpoint is None:
|
||||
return self
|
||||
raw_url = self.endpoint.url.get_secret_value()
|
||||
parsed = urlparse(raw_url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise ValueError("URL CalDAV invalide : schéma non supporté") from None
|
||||
if parsed.scheme == "https":
|
||||
return v
|
||||
return self
|
||||
# HTTP — check allow_insecure_http flag and loopback
|
||||
allow_insecure = info.data.get("allow_insecure_http", False)
|
||||
if not allow_insecure:
|
||||
if not self.allow_insecure_http:
|
||||
raise ValueError(
|
||||
"URL CalDAV non sécurisée : HTTPS requis (ou activer "
|
||||
"CALDAV_ALLOW_INSECURE_HTTP pour localhost)"
|
||||
) from None
|
||||
hostname = parsed.hostname or ""
|
||||
loopback_hosts = {"localhost", "127.0.0.1", "::1"}
|
||||
if hostname not in loopback_hosts:
|
||||
if hostname not in _LOOPBACK_HOSTS:
|
||||
raise ValueError(
|
||||
"URL CalDAV non sécurisée : HTTP autorisé uniquement pour localhost"
|
||||
) from None
|
||||
return v
|
||||
return self
|
||||
|
||||
|
||||
_XMPP_LOOPBACK_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
||||
@@ -282,10 +352,60 @@ class BlogSettings(BaseSettings):
|
||||
``BLOG_``.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_prefix="BLOG_")
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_nested_delimiter="__",
|
||||
extra="ignore",
|
||||
env_prefix="BLOG_",
|
||||
)
|
||||
|
||||
enabled: bool = False
|
||||
rss_url: str = "https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2"
|
||||
endpoint: ExternalEndpoint = Field(
|
||||
default_factory=lambda: ExternalEndpoint(
|
||||
url=SecretStr("https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2")
|
||||
)
|
||||
)
|
||||
rss_url: str | None = Field(
|
||||
default=None,
|
||||
exclude=True,
|
||||
deprecated="Utiliser endpoint.url à la place (BLOG_RSS_URL obsolète).",
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _migrate_legacy_rss_url(cls, data: object) -> object:
|
||||
"""Migre ``rss_url`` vers l'endpoint commun avec un avertissement.
|
||||
|
||||
:param data: Données brutes du modèle.
|
||||
:return: Données complétées avec ``endpoint`` si nécessaire.
|
||||
:rtype: object
|
||||
"""
|
||||
if not isinstance(data, dict) or data.get("rss_url") is None:
|
||||
return data
|
||||
migrated_data = data.copy()
|
||||
warnings.warn(
|
||||
"BLOG_RSS_URL est obsolète : utiliser BLOG_ENDPOINT__URL.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if migrated_data.get("endpoint") is None:
|
||||
migrated_data["endpoint"] = {"url": migrated_data["rss_url"]}
|
||||
return migrated_data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_endpoint_policy(self) -> BlogSettings:
|
||||
"""Refuse les transports non sûrs pour le flux RSS de production.
|
||||
|
||||
Le transport ``file`` reste autorisé pour les fixtures locales.
|
||||
|
||||
:return: Instance validée inchangée.
|
||||
:rtype: BlogSettings
|
||||
:raises ValueError: Si le schéma n'est ni ``https`` ni ``file``.
|
||||
"""
|
||||
scheme = urlparse(self.endpoint.url.get_secret_value()).scheme
|
||||
if scheme not in {"https", "file"}:
|
||||
raise ValueError("URL RSS invalide : HTTPS ou file requis") from None
|
||||
return self
|
||||
|
||||
|
||||
class AppSettings(BaseSettings):
|
||||
@@ -342,9 +462,10 @@ class Settings(BaseSettings):
|
||||
self.pronote.password,
|
||||
self.pronote.qr_pin,
|
||||
self.pronote.account_pin,
|
||||
self.caldav.url,
|
||||
self.caldav.endpoint.url if self.caldav.endpoint is not None else None,
|
||||
self.caldav.password,
|
||||
self.xmpp.password,
|
||||
self.ai.api_key,
|
||||
self.blog.endpoint.url,
|
||||
]
|
||||
return tuple(dict.fromkeys(secret for secret in secrets if secret is not None))
|
||||
|
||||
@@ -138,7 +138,11 @@ class PipelineRunner:
|
||||
comparator = (
|
||||
AgendaComparator(theoretical_provider) if theoretical_provider is not None else None
|
||||
)
|
||||
blog_client = BlogRSSClient(settings.blog.rss_url) if settings.blog.enabled else None
|
||||
blog_client = (
|
||||
BlogRSSClient(settings.blog.endpoint.url.get_secret_value())
|
||||
if settings.blog.enabled
|
||||
else None
|
||||
)
|
||||
blog_state = (
|
||||
BlogRSSState(persistence_enabled=persistence_enabled) if settings.blog.enabled else None
|
||||
)
|
||||
|
||||
@@ -79,11 +79,12 @@ class CalDAVGateway:
|
||||
else cast(Callable[..., Any], caldav.DAVClient)
|
||||
)
|
||||
self._calendar_path: str = settings.calendar_path
|
||||
url_secret = settings.endpoint.url if settings.endpoint is not None else None
|
||||
self._redacted_url: str | None = (
|
||||
redact_url(settings.url.get_secret_value()) if settings.url else None
|
||||
redact_url(url_secret.get_secret_value()) if url_secret else None
|
||||
)
|
||||
self._username: str | None = settings.username
|
||||
self._url_secret: SecretStr | None = settings.url
|
||||
self._url_secret: SecretStr | None = url_secret
|
||||
self._password_secret: SecretStr | None = settings.password
|
||||
self._client: Any = None
|
||||
self._calendar: Any = None
|
||||
|
||||
@@ -96,7 +96,7 @@ def synchronize(
|
||||
)
|
||||
|
||||
if (
|
||||
settings.caldav.url is None
|
||||
settings.caldav.endpoint is None
|
||||
or settings.caldav.username is None
|
||||
or settings.caldav.password is None
|
||||
):
|
||||
|
||||
Reference in New Issue
Block a user