Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
097a27fcf3 | ||
|
|
93f66d6aca | ||
|
|
eef81ea323 | ||
|
|
a21acaa409 | ||
|
|
f261fed1af |
+5
-2
@@ -28,7 +28,9 @@ PRONOTE_AUTH_MODE=password
|
|||||||
# PRONOTE_ACCOUNT_PIN=
|
# PRONOTE_ACCOUNT_PIN=
|
||||||
|
|
||||||
# --- CalDAV ---
|
# --- 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_USERNAME=user@example.com
|
||||||
CALDAV_PASSWORD=your_caldav_password
|
CALDAV_PASSWORD=your_caldav_password
|
||||||
CALDAV_CALENDAR_PATH=/pronote-sync/
|
CALDAV_CALENDAR_PATH=/pronote-sync/
|
||||||
@@ -92,7 +94,8 @@ AI_BASE_URL=https://api.openai.com/v1
|
|||||||
|
|
||||||
# --- Blog ---
|
# --- Blog ---
|
||||||
BLOG_ENABLED=false
|
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 ---
|
# --- Divers ---
|
||||||
DRY_RUN=false
|
DRY_RUN=false
|
||||||
|
|||||||
+2
-2
@@ -140,7 +140,7 @@
|
|||||||
"filename": "GUIDE_DEV_PYTHON.md",
|
"filename": "GUIDE_DEV_PYTHON.md",
|
||||||
"hashed_secret": "90bd1b48e958257948487b90bee080ba5ed00caa",
|
"hashed_secret": "90bd1b48e958257948487b90bee080ba5ed00caa",
|
||||||
"is_verified": false,
|
"is_verified": false,
|
||||||
"line_number": 5186
|
"line_number": 5183
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"tests/unit/test_caldav_gateway.py": [
|
"tests/unit/test_caldav_gateway.py": [
|
||||||
@@ -185,5 +185,5 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"generated_at": "2026-09-12T22:12:56Z"
|
"generated_at": "2026-09-13T09:52:29Z"
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-3
@@ -40,7 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [0.1.0] - 2026-09-08
|
## [0.1.0] - 2026-09-08
|
||||||
|
|
||||||
Initial release covering milestones M1 through M15.
|
Initial release covering milestones M1 through M15, except the optional Gitea Actions workflow.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- **M1 (Scaffolding)**: Python project structure with `pyproject.toml`, and tooling configuration for `ruff`, `mypy`, `bandit`, and `pre-commit`.
|
- **M1 (Scaffolding)**: Python project structure with `pyproject.toml`, and tooling configuration for `ruff`, `mypy`, `bandit`, and `pre-commit`.
|
||||||
@@ -57,5 +57,4 @@ Initial release covering milestones M1 through M15.
|
|||||||
- **M12 (CLI entry point)**: `pronote-sync` command with `--dry-run` and `--log-level` options, redacted error display, and safe traceback in DEBUG mode.
|
- **M12 (CLI entry point)**: `pronote-sync` command with `--dry-run` and `--log-level` options, redacted error display, and safe traceback in DEBUG mode.
|
||||||
- **M13 (Tests & coverage)**: 636 tests with 95.67% coverage, test fixtures (`pronote-4e.ics`, `pronote-6e.ics`), shared `conftest.py`, and secret non-leak tests.
|
- **M13 (Tests & coverage)**: 636 tests with 95.67% coverage, test fixtures (`pronote-4e.ics`, `pronote-6e.ics`), shared `conftest.py`, and secret non-leak tests.
|
||||||
- **M14 (Deployment)**: systemd service and timer (daily at 18:00), logrotate configuration (daily, rotate 7, compress), `check_secrets.py` pre-deployment scanner, and exploitation guide.
|
- **M14 (Deployment)**: systemd service and timer (daily at 18:00), logrotate configuration (daily, rotate 7, compress), `check_secrets.py` pre-deployment scanner, and exploitation guide.
|
||||||
- **M15 (Documentation)**: README, README.LLM.md (AI agent setup guide), MIT LICENSE, CHANGELOG, and Gitea Actions CI/CD reference for LXC/VPS (Debian/CentOS).
|
- **M15 (Documentation)**: README, README.LLM.md (AI agent setup guide), MIT LICENSE, CHANGELOG, and local validation procedures. Gitea Actions CI/CD remains optional and is not delivered in this release.
|
||||||
- **Other**: MIT License. Gitea Actions CI/CD reference for LXC/VPS (Debian/CentOS) is planned and optional, not delivered in this release.
|
|
||||||
|
|||||||
+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_USERNAME` | Identifiant Pronote (si `pronotepy` utilisé). | `parent.dupont` | `str` |
|
||||||
| `PRONOTE_PASSWORD` | Mot de passe Pronote (si `pronotepy` utilisé). | `SecretStr` (masqué) | `SecretStr` |
|
| `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` |
|
| `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_USERNAME` | Identifiant CalDAV. | `user@example.com` | `str` |
|
||||||
| `CALDAV_PASSWORD` | Mot de passe CalDAV. | `SecretStr` (masqué) | `SecretStr` |
|
| `CALDAV_PASSWORD` | Mot de passe CalDAV. | `SecretStr` (masqué) | `SecretStr` |
|
||||||
| `CALDAV_CALENDAR_PATH` | Chemin du calendrier CalDAV de destination. | `/pronote-sync/` | `str` |
|
| `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.
|
Aucun fichier d'état local n'est utilisé : l'état est géré en mémoire par run.
|
||||||
# Initialisation
|
# 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)()
|
blog_state = ## (section obsolète supprimée)()
|
||||||
|
|
||||||
# Récupération des nouveaux articles
|
# Récupération des nouveaux articles
|
||||||
@@ -1218,7 +1218,7 @@ Ajouter les variables suivantes dans la configuration :
|
|||||||
| **Variable** | **Description** | **Valeur par défaut** | **Type** |
|
| **Variable** | **Description** | **Valeur par défaut** | **Type** |
|
||||||
|----------------------------|-------------------------------------------------------------------------------|-----------------------|-------------------|
|
|----------------------------|-------------------------------------------------------------------------------|-----------------------|-------------------|
|
||||||
| `BLOG_ENABLED` | Activer la récupération du blog. | `False` | `bool` |
|
| `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
|
#### 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):
|
class BlogSettings(BaseSettings):
|
||||||
model_config = SettingsConfigDict(env_prefix="BLOG_", env_file=".env", extra="ignore")
|
model_config = SettingsConfigDict(env_prefix="BLOG_", env_file=".env", extra="ignore")
|
||||||
enabled: bool = Field(False, description="Activer la récupération du blog")
|
enabled: bool = Field(False, description="Activer la récupération du blog")
|
||||||
rss_url: str = Field(
|
endpoint: ExternalEndpoint
|
||||||
"https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2",
|
|
||||||
description="URL du flux RSS du blog",
|
|
||||||
)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Intégration dans `Settings`** :
|
**Intégration dans `Settings`** :
|
||||||
@@ -1253,7 +1250,7 @@ class Settings(BaseSettings):
|
|||||||
```ini
|
```ini
|
||||||
# --- Blog du collège ---
|
# --- Blog du collège ---
|
||||||
BLOG_ENABLED=true
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ Synchronise l'agenda et les devoirs de **Pronote** vers un calendrier **CalDAV**
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Cloner le dépôt
|
# Cloner le dépôt
|
||||||
git clone <repo-url>
|
git clone https://git.antoineve.me/AntoineVe/college-infos
|
||||||
cd pronote-sync
|
cd college-infos
|
||||||
|
|
||||||
# Créer l'environnement virtuel
|
# Créer l'environnement virtuel
|
||||||
python3.13 -m venv .venv
|
python3.13 -m venv .venv
|
||||||
@@ -48,6 +48,23 @@ pas garantir un état persistant cohérent pendant une simulation.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Validation et CI
|
||||||
|
|
||||||
|
Aucun workflow Gitea Actions n'est livré actuellement. Les validations du projet sont donc
|
||||||
|
exécutées localement avec les commandes suivantes :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest
|
||||||
|
ruff check .
|
||||||
|
mypy .
|
||||||
|
bandit -r pronote_sync/
|
||||||
|
```
|
||||||
|
|
||||||
|
`pre-commit run --all-files` regroupe également les contrôles de formatage, typage, sécurité et
|
||||||
|
détection de secrets.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 🛠️ Déploiement
|
## 🛠️ Déploiement
|
||||||
|
|
||||||
Les artefacts pour **systemd/timer** et **logrotate** sont fournis dans `deploy/`. Voir [docs/exploitation.md](docs/exploitation.md) pour plus de détails.
|
Les artefacts pour **systemd/timer** et **logrotate** sont fournis dans `deploy/`. Voir [docs/exploitation.md](docs/exploitation.md) pour plus de détails.
|
||||||
|
|||||||
@@ -308,5 +308,5 @@ Rédiger la documentation utilisateur et finaliser le projet.
|
|||||||
|
|
||||||
### Critères d'acceptation
|
### Critères d'acceptation
|
||||||
- `README.md` permet d'installer et de lancer le projet sans le guide.
|
- `README.md` permet d'installer et de lancer le projet sans le guide.
|
||||||
- Gitea Actions exécute tests + lint + sécurité.
|
- Les procédures locales de test, lint et sécurité sont documentées et exécutables.
|
||||||
- Aucun secret dans la documentation.
|
- Aucun secret dans la documentation.
|
||||||
|
|||||||
+162
-41
@@ -10,21 +10,76 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import warnings
|
import warnings
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Literal
|
from typing import Annotated, Literal
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
from pydantic import (
|
from pydantic import (
|
||||||
|
AfterValidator,
|
||||||
|
BaseModel,
|
||||||
|
ConfigDict,
|
||||||
Field,
|
Field,
|
||||||
SecretStr,
|
SecretStr,
|
||||||
ValidationInfo,
|
|
||||||
field_serializer,
|
field_serializer,
|
||||||
field_validator,
|
|
||||||
model_validator,
|
model_validator,
|
||||||
)
|
)
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
from pronote_sync.utils.redaction import redact_url
|
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):
|
class PronoteSettings(BaseSettings):
|
||||||
"""Paramètres d'accès à Pronote (flux iCal et API ``pronotepy``).
|
"""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
|
Les variables d'environnement correspondantes sont préfixées par
|
||||||
``CALDAV_``. L'URL est traitée comme potentiellement sensible (au même
|
``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é ;
|
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``,
|
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``.
|
``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
|
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
|
username: str | None = None
|
||||||
password: SecretStr | None = None
|
password: SecretStr | None = None
|
||||||
calendar_path: str = "/pronote-sync/"
|
calendar_path: str = "/pronote-sync/"
|
||||||
|
|
||||||
@field_serializer("url")
|
@model_validator(mode="before")
|
||||||
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")
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _validate_url_https(cls, v: SecretStr | None, info: ValidationInfo) -> SecretStr | None:
|
def _migrate_legacy_url(cls, data: object) -> object:
|
||||||
"""Valide le schéma de l'URL CalDAV (HTTPS obligatoire par défaut).
|
"""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
|
HTTPS est toujours accepté. HTTP n'est accepté que pour un hôte de
|
||||||
boucle locale (``localhost``, ``127.0.0.1``, ``::1``) et uniquement
|
boucle locale (``localhost``, ``127.0.0.1``, ``::1``) et uniquement
|
||||||
lorsque ``allow_insecure_http`` vaut ``True``. Les messages d'erreur
|
lorsque ``allow_insecure_http`` vaut ``True``. Les autres schémas du
|
||||||
ne contiennent jamais l'URL brute (susceptible de contenir des
|
socle commun sont refusés pour ce connecteur.
|
||||||
identifiants).
|
|
||||||
|
|
||||||
:param v: Valeur du champ ``url`` à valider.
|
:return: Instance validée inchangée.
|
||||||
:param info: Contexte de validation (accès aux autres champs).
|
:rtype: CalDAVSettings
|
||||||
:return: La valeur validée inchangée.
|
|
||||||
:rtype: SecretStr | None
|
|
||||||
:raises ValueError: Si le schéma n'est pas supporté ou si l'URL HTTP
|
:raises ValueError: Si le schéma n'est pas supporté ou si l'URL HTTP
|
||||||
n'est pas autorisée.
|
n'est pas autorisée.
|
||||||
"""
|
"""
|
||||||
if v is None:
|
if self.endpoint is None:
|
||||||
return v
|
return self
|
||||||
raw_url = v.get_secret_value()
|
raw_url = self.endpoint.url.get_secret_value()
|
||||||
parsed = urlparse(raw_url)
|
parsed = urlparse(raw_url)
|
||||||
if parsed.scheme not in ("http", "https"):
|
if parsed.scheme not in ("http", "https"):
|
||||||
raise ValueError("URL CalDAV invalide : schéma non supporté") from None
|
raise ValueError("URL CalDAV invalide : schéma non supporté") from None
|
||||||
if parsed.scheme == "https":
|
if parsed.scheme == "https":
|
||||||
return v
|
return self
|
||||||
# HTTP — check allow_insecure_http flag and loopback
|
# HTTP — check allow_insecure_http flag and loopback
|
||||||
allow_insecure = info.data.get("allow_insecure_http", False)
|
if not self.allow_insecure_http:
|
||||||
if not allow_insecure:
|
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"URL CalDAV non sécurisée : HTTPS requis (ou activer "
|
"URL CalDAV non sécurisée : HTTPS requis (ou activer "
|
||||||
"CALDAV_ALLOW_INSECURE_HTTP pour localhost)"
|
"CALDAV_ALLOW_INSECURE_HTTP pour localhost)"
|
||||||
) from None
|
) from None
|
||||||
hostname = parsed.hostname or ""
|
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(
|
raise ValueError(
|
||||||
"URL CalDAV non sécurisée : HTTP autorisé uniquement pour localhost"
|
"URL CalDAV non sécurisée : HTTP autorisé uniquement pour localhost"
|
||||||
) from None
|
) from None
|
||||||
return v
|
return self
|
||||||
|
|
||||||
|
|
||||||
_XMPP_LOOPBACK_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
_XMPP_LOOPBACK_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
||||||
@@ -282,10 +352,60 @@ class BlogSettings(BaseSettings):
|
|||||||
``BLOG_``.
|
``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
|
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):
|
class AppSettings(BaseSettings):
|
||||||
@@ -342,9 +462,10 @@ class Settings(BaseSettings):
|
|||||||
self.pronote.password,
|
self.pronote.password,
|
||||||
self.pronote.qr_pin,
|
self.pronote.qr_pin,
|
||||||
self.pronote.account_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.caldav.password,
|
||||||
self.xmpp.password,
|
self.xmpp.password,
|
||||||
self.ai.api_key,
|
self.ai.api_key,
|
||||||
|
self.blog.endpoint.url,
|
||||||
]
|
]
|
||||||
return tuple(dict.fromkeys(secret for secret in secrets if secret is not None))
|
return tuple(dict.fromkeys(secret for secret in secrets if secret is not None))
|
||||||
|
|||||||
@@ -138,7 +138,11 @@ class PipelineRunner:
|
|||||||
comparator = (
|
comparator = (
|
||||||
AgendaComparator(theoretical_provider) if theoretical_provider is not None else None
|
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 = (
|
blog_state = (
|
||||||
BlogRSSState(persistence_enabled=persistence_enabled) if settings.blog.enabled else None
|
BlogRSSState(persistence_enabled=persistence_enabled) if settings.blog.enabled else None
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -97,7 +97,10 @@ class BlogRSSState:
|
|||||||
redact_exception(exc),
|
redact_exception(exc),
|
||||||
)
|
)
|
||||||
|
|
||||||
def _save(self) -> None:
|
def _save(
|
||||||
|
self,
|
||||||
|
state: tuple[set[str], str | None, str | None] | None = None,
|
||||||
|
) -> bool:
|
||||||
"""Sauvegarde l'état dans le fichier JSON de manière atomique.
|
"""Sauvegarde l'état dans le fichier JSON de manière atomique.
|
||||||
|
|
||||||
La sortie est déterministe : ``known_guids`` est trié
|
La sortie est déterministe : ``known_guids`` est trié
|
||||||
@@ -107,20 +110,30 @@ class BlogRSSState:
|
|||||||
jamais laisser un fichier partiel en cas d'interruption. En cas
|
jamais laisser un fichier partiel en cas d'interruption. En cas
|
||||||
d'erreur d'écriture, une erreur est journalisée sans être
|
d'erreur d'écriture, une erreur est journalisée sans être
|
||||||
propagée et le fichier temporaire est supprimé.
|
propagée et le fichier temporaire est supprimé.
|
||||||
|
|
||||||
|
:param state: État à sauvegarder ; l'état courant est utilisé par défaut.
|
||||||
|
:return: ``True`` si l'état a été sauvegardé ou si la persistance est désactivée.
|
||||||
|
:rtype: bool
|
||||||
"""
|
"""
|
||||||
if not self._persistence_enabled:
|
if not self._persistence_enabled:
|
||||||
return
|
return True
|
||||||
|
known_guids, etag, last_modified = state or (
|
||||||
|
self._known_guids,
|
||||||
|
self._etag,
|
||||||
|
self._last_modified,
|
||||||
|
)
|
||||||
payload = {
|
payload = {
|
||||||
"version": _STATE_VERSION,
|
"version": _STATE_VERSION,
|
||||||
"known_guids": sorted(self._known_guids),
|
"known_guids": sorted(known_guids),
|
||||||
"etag": self._etag,
|
"etag": etag,
|
||||||
"last_modified": self._last_modified,
|
"last_modified": last_modified,
|
||||||
}
|
}
|
||||||
tmp_file = self._state_file.with_suffix(".tmp")
|
tmp_file = self._state_file.with_suffix(".tmp")
|
||||||
try:
|
try:
|
||||||
with open(tmp_file, "w", encoding="utf-8") as handle:
|
with open(tmp_file, "w", encoding="utf-8") as handle:
|
||||||
json.dump(payload, handle, indent=2)
|
json.dump(payload, handle, indent=2)
|
||||||
tmp_file.replace(self._state_file)
|
tmp_file.replace(self._state_file)
|
||||||
|
return True
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.error(
|
logger.error(
|
||||||
"Impossible d'écrire le fichier d'état blog RSS %s : %s.",
|
"Impossible d'écrire le fichier d'état blog RSS %s : %s.",
|
||||||
@@ -134,6 +147,7 @@ class BlogRSSState:
|
|||||||
"Nettoyage du fichier temporaire échoué : %s",
|
"Nettoyage du fichier temporaire échoué : %s",
|
||||||
redact_exception(cleanup_exc),
|
redact_exception(cleanup_exc),
|
||||||
)
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
def get_known_guids(self) -> frozenset[str]:
|
def get_known_guids(self) -> frozenset[str]:
|
||||||
"""Renvoie une copie immuable des GUID d'articles déjà connus.
|
"""Renvoie une copie immuable des GUID d'articles déjà connus.
|
||||||
@@ -168,10 +182,13 @@ class BlogRSSState:
|
|||||||
"""
|
"""
|
||||||
if result.not_modified:
|
if result.not_modified:
|
||||||
return
|
return
|
||||||
self._known_guids.update(article.id for article in result.articles)
|
new_state = (
|
||||||
self._etag = result.etag
|
self._known_guids | {article.id for article in result.articles},
|
||||||
self._last_modified = result.last_modified
|
result.etag,
|
||||||
self._save()
|
result.last_modified,
|
||||||
|
)
|
||||||
|
if self._save(new_state):
|
||||||
|
self._known_guids, self._etag, self._last_modified = new_state
|
||||||
|
|
||||||
def get_cache_headers(self) -> tuple[str | None, str | None]:
|
def get_cache_headers(self) -> tuple[str | None, str | None]:
|
||||||
"""Renvoie les en-têtes de cache HTTP mémorisés.
|
"""Renvoie les en-têtes de cache HTTP mémorisés.
|
||||||
|
|||||||
@@ -79,11 +79,12 @@ class CalDAVGateway:
|
|||||||
else cast(Callable[..., Any], caldav.DAVClient)
|
else cast(Callable[..., Any], caldav.DAVClient)
|
||||||
)
|
)
|
||||||
self._calendar_path: str = settings.calendar_path
|
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 = (
|
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._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._password_secret: SecretStr | None = settings.password
|
||||||
self._client: Any = None
|
self._client: Any = None
|
||||||
self._calendar: Any = None
|
self._calendar: Any = None
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ def synchronize(
|
|||||||
)
|
)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
settings.caldav.url is None
|
settings.caldav.endpoint is None
|
||||||
or settings.caldav.username is None
|
or settings.caldav.username is None
|
||||||
or settings.caldav.password is None
|
or settings.caldav.password is None
|
||||||
):
|
):
|
||||||
|
|||||||
+6
-5
@@ -7,9 +7,10 @@ name = "pronote-sync"
|
|||||||
version = "0.1.2"
|
version = "0.1.2"
|
||||||
description = "Synchronisation Pronote → CalDAV + XMPP"
|
description = "Synchronisation Pronote → CalDAV + XMPP"
|
||||||
license = {text = "MIT"}
|
license = {text = "MIT"}
|
||||||
|
readme = "README.md"
|
||||||
requires-python = ">=3.13.5"
|
requires-python = ">=3.13.5"
|
||||||
authors = [
|
authors = [
|
||||||
{name = "Votre Nom", email = "votre@email.com"}
|
{name = "Antoine Van Elstraete", email = "antoine@van-elstraete.net"}
|
||||||
]
|
]
|
||||||
keywords = ["pronote", "caldav", "xmpp", "sync", "school"]
|
keywords = ["pronote", "caldav", "xmpp", "sync", "school"]
|
||||||
classifiers = [
|
classifiers = [
|
||||||
@@ -57,10 +58,10 @@ dev = [
|
|||||||
pronote-sync = "pronote_sync.cli.main:main"
|
pronote-sync = "pronote_sync.cli.main:main"
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
Homepage = "https://github.com/votre-utilisateur/pronote-sync"
|
Homepage = "https://git.antoineve.me/AntoineVe/college-infos"
|
||||||
Documentation = "https://github.com/votre-utilisateur/pronote-sync#readme"
|
Documentation = "https://git.antoineve.me/AntoineVe/college-infos/wiki"
|
||||||
Repository = "https://github.com/votre-utilisateur/pronote-sync"
|
Repository = "https://git.antoineve.me/AntoineVe/college-infos"
|
||||||
Issues = "https://github.com/votre-utilisateur/pronote-sync/issues"
|
Issues = "https://git.antoineve.me/AntoineVe/college-infos/issues"
|
||||||
|
|
||||||
[tool.setuptools.packages.find]
|
[tool.setuptools.packages.find]
|
||||||
where = ["."]
|
where = ["."]
|
||||||
|
|||||||
@@ -425,4 +425,41 @@ def test_atomic_save_preserves_on_error(tmp_path: Path) -> None:
|
|||||||
assert state.get_known_guids() == frozenset({"original-guid-1", "original-guid-2", "new-guid"})
|
assert state.get_known_guids() == frozenset({"original-guid-1", "original-guid-2", "new-guid"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_acknowledge_does_not_advance_memory_when_save_fails(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Conserve l'état précédent en mémoire si l'acquittement ne peut pas être sauvegardé.
|
||||||
|
|
||||||
|
:param tmp_path: Fixture pytest pour un répertoire temporaire.
|
||||||
|
:return: None
|
||||||
|
"""
|
||||||
|
state_file = tmp_path / "state.json"
|
||||||
|
state = BlogRSSState(state_file)
|
||||||
|
state.add_guids(["existing-guid"])
|
||||||
|
state.update_cache_headers("old-etag", "old-last-modified")
|
||||||
|
article = BlogArticle(
|
||||||
|
id="new-guid",
|
||||||
|
title="Article",
|
||||||
|
url="https://example.com/article",
|
||||||
|
published_at=datetime(2026, 9, 12, 8, 0, tzinfo=UTC),
|
||||||
|
updated_at=None,
|
||||||
|
category=None,
|
||||||
|
author=None,
|
||||||
|
content_html="<p>Contenu</p>",
|
||||||
|
content_text="Contenu",
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch.object(Path, "replace", side_effect=OSError("replace failed")):
|
||||||
|
state.acknowledge(
|
||||||
|
BlogRSSFetchResult(
|
||||||
|
articles=(article,),
|
||||||
|
etag="new-etag",
|
||||||
|
last_modified="new-last-modified",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assert state.get_known_guids() == frozenset({"existing-guid"})
|
||||||
|
assert state.get_cache_headers() == ("old-etag", "old-last-modified")
|
||||||
|
|
||||||
|
|
||||||
# Ensure trailing newline
|
# Ensure trailing newline
|
||||||
|
|||||||
Reference in New Issue
Block a user