diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d2d2bf..771df74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,24 @@ +## 2026-10-19 (177) — La carte céleste : ce que les plans déclarent, en une page qu'on peut remettre + +**95 preuves.** `make verifier` : 95 OK, 0 échec. Une nouvelle garde, `test_carte_reseaux.py` (9 cas, sur des écosystèmes fictifs aux adresses de documentation), vérifie la collecte, la portée et l'étanchéité de la page. + +**Ce qui manquait.** Personne ne voyait d'un coup d'œil la couche 3 de la flotte : zones de chaque site, frontières et tunnels, VRF des locataires, adresse de chaque machine. L'information existait, mais dispersée dans six fichiers par site et deux par locataire. `make carte` la rassemble en un atlas céleste : la frontière est un astre majeur, chaque zone une nébuleuse, chaque machine une étoile avec son adresse, et chaque site porte le nom de son étoile (`etoiles.domaine_site`). La page sert à livrer un site ou à ouvrir un partenariat. + +**Une vue, pas une fonction (AGENTS §12).** Rien n'est saisi ni déduit. Sites et locataires viennent de `contexte.Site` et `Locataire`. Les sous-réseaux, passerelles, VNet et VNI viennent des dérivations du moteur (`underlay.charger_resolu`, `inventory_rules`, `devis_sdn`). Un locataire paraît hébergé chez son hébergeur actif, et en reprise chez le site qui le déclare aussi. La page dit ce que les plans déclarent ; les devis restent les juges du réel. + +**Le moteur se dessinait en troisième site.** Son `underlay.yml` est le lien qui monte la carte de `SITE-Chezlepro`. Une découverte par `*/underlay.yml` le comptait comme un site, double de celui qu'il monte (mesuré à la première collecte). Une carte montée par lien n'est plus un site ; un cas le garde. + +**Ce que la page ne fuit pas.** + +- Elle porte des adresses internes : `carte_reseaux.py` refuse de l'écrire dans ce dépôt public hors de `tmp/` (code 2). Sa place est le dépôt privé du site, ou la remise en main propre. +- `SITE=` la borne à un site, à ses locataires et à ses reprises. Un partenaire reçoit son site, pas les adresses des autres écosystèmes. +- Aucune voûte n'est lue, aucune clé publique WireGuard n'est reportée, et un `` venu d'un plan ne ferme pas le script. +- Les polices (OFL, sous-ensemble latin, `scripts/carte/polices/`, licences jointes) sont embarquées : la page s'ouvre hors ligne et n'appelle aucun service. Le chargement depuis Google Fonts aurait signalé chaque ouverture d'une livraison. + +**Deux gardes ont fait leur travail.** P83 a refusé une cible documentée qu'aucun runbook ne porte. La carte en est exemptée avec son motif : lancée depuis la console, elle resterait sur le runner, loin de qui doit la remettre. P31 a ensuite refusé une cible absente de `docs/usage.md`. + +**Témoin.** La carte complète des plans du jour porte 2 sites, 2 locataires hébergés, 26 zones et 44 machines ; celle bornée à `SITE-Technolibre`, 9 machines et 2 VRF de reprise. Le même jour, avant ce code, les 44 adresses ont été confrontées au réel depuis le poste : les 18 machines des sites ont déclaré leur nom et leur adresse par SSH, et les 26 des locataires ont répondu au ping. + ## 2026-10-19 (176) — Le site de TechnoLibre déployé sous `achird31`, et ce que le renommage a révélé **95 preuves.** `make verifier` : 95 OK, 0 échec. `test_step_ca_identite.py` passe à 5 cas (l'adresse que retient le `step` de l'autorité). diff --git a/Makefile b/Makefile index 649de64..a5651b2 100644 --- a/Makefile +++ b/Makefile @@ -337,6 +337,7 @@ test: ## Lance les tests unitaires (derivation de nomenclature et d'inventaire) python3 scripts/tests/test_console_venv.py python3 scripts/tests/test_etoiles.py python3 scripts/tests/test_step_ca_identite.py + python3 scripts/tests/test_carte_reseaux.py python3 scripts/tests/test_forge_cles.py python3 scripts/tests/test_devis_placement.py python3 scripts/tests/test_sonder.py @@ -540,6 +541,14 @@ instance-courante: ## Affiche vers quel ecosysteme pointe l'instance active instances: ## Liste les ecosystemes decouverts (dossiers freres) et signale les collisions d'index @python3 scripts/instances.py +# LA CARTE CELESTE (2026-10-19) : la couche 3 des sites et de leurs locataires en une page +# autonome — zones, frontieres, tunnels, VRF, machines et adresses, tirees des plans. Une VUE : +# elle ne mesure rien. Elle porte des adresses internes : jamais dans ce depot public (sortie +# par defaut dans tmp/, ignore par git) ; sa place est le depot prive du site, ou la remise. +.PHONY: carte +carte: ## La carte celeste des reseaux (couche 3) en une page autonome — [SITE=] [VERS=] + @python3 scripts/carte_reseaux.py $(if $(SITE),--site "$(SITE)",) $(if $(VERS),--vers "$(VERS)",) + # (Re)génère le plan de recette (docs/audit/plan-de-recette.md) depuis les exercices # du wiki. La preuve P22 vérifie qu'il reste à jour. plan-recette: ## Regenere docs/audit/plan-de-recette.md depuis le wiki diff --git a/docs/runbooks-construction.yml b/docs/runbooks-construction.yml index 358e692..b06981a 100644 --- a/docs/runbooks-construction.yml +++ b/docs/runbooks-construction.yml @@ -1134,6 +1134,10 @@ hors_assistant: racines: >- La vue « Confiance » du GUI la porte deja : racines, empreintes, etat des magasins. Un assistant en serait une seconde copie, qui finirait par dire autre chose. + carte: >- + Elle ecrit un fichier sur la machine qui l'execute : lancee depuis la console, la carte + resterait sur le runner, loin de la personne qui doit la remettre. Elle se fait au + poste, qui porte les depots freres et le depot prive du site ou la verser. racines-importer: >- Meme raison, et une de plus : l'import touche les magasins du navigateur LOCAL. La vue « Confiance » le garde (`navigateur-local`) ; un assistant lance depuis un serveur diff --git a/docs/usage.md b/docs/usage.md index ed42479..43456f4 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -32,11 +32,11 @@ toujours `set -o pipefail; make … < /dev/null 2>&1 | cat`. Sans tube, l'échec | `GROUPE` | un groupe Ansible (= un playbook de `playbooks/groupes/`) | `deployer-groupe`, `appliquer`, `site-appliquer` | | `TENANT` | le dépôt d'un locataire (`OPS-X`) vu depuis le site | `locataire-creer`, `inseminer`, `placement-plan`, … | | `INSTANCE` | le nom court d'un écosystème, exigé par les cibles destructives | `raser`, `locataire-raser`, `parefeu-*-flotte` | -| `SITE` | le dépôt d'un site, exigé par `site-raser` | `site-raser` | +| `SITE` | le dépôt d'un site, exigé par `site-raser` ; borne `carte` à ce site | `site-raser`, `carte` | | `CONFIRMER` | `true` pour écrire | toute cible `-appliquer` ou destructive | | `LIMITE` | motif d'hôtes Ansible | `faits`, `verifier-hote` | | `MACHINE` | une seule machine (vide = toutes les machines actives) | `mises-a-jour`, `site-mises-a-jour`, et leur `-appliquer` | -| `VERS` | un répertoire de destination (support externe) | `cles-exporter`, `voutes-exporter`, `remise-paquet`, … | +| `VERS` | un répertoire de destination (support externe) ; pour `carte`, le fichier HTML à écrire | `cles-exporter`, `voutes-exporter`, `remise-paquet`, `carte`, … | | `DEPOT` | un seul dépôt du génome | `publier`, `genome-pousser` | | `PARALLELE` | nombre de VM créées à la fois | `flotte-creer`, `locataire-creer` | | `NOM`, `MODELE`, `INDEX` | nouvel écosystème | `instance-creer`, `instance-utiliser`, `model-creer` | @@ -136,6 +136,7 @@ documente ses options (`--help`) dans sa docstring. | `make instance-utiliser` | Bascule l'instance active (symlink instance/) vers un dossier frere — NOM= | | `make instance-courante` | Affiche vers quel ecosysteme pointe l'instance active | | `make instances` | Liste les ecosystemes decouverts (dossiers freres) et signale les collisions d'index | +| `make carte` | La carte céleste des réseaux (couche 3) : chaque site, ses zones, sa frontière, ses tunnels, les VRF de ses locataires et l'adresse de chaque machine, en une page autonome (polices embarquées, aucun appel extérieur). Tirée des plans, elle ne mesure rien. `SITE=` la borne à un site, ses locataires et ses reprises ; `VERS=` (défaut : `tmp/carte-des-reseaux.html`). Elle porte des adresses internes : refusée dans ce dépôt public hors de `tmp/` | | `make model-creer` | Cree un modele d'ecosysteme — MODE= NOM= | | `make genome` | Les depots requis a la reproduction de cet ecosysteme, et leur etat | | `make genome-inscrire` | Inscrit la parente dans l'instance (instance/parente.yml) | diff --git a/scripts/carte/gabarit.html b/scripts/carte/gabarit.html new file mode 100644 index 0000000..7708985 --- /dev/null +++ b/scripts/carte/gabarit.html @@ -0,0 +1,766 @@ + + + + + +Carte céleste des réseaux + + + + + +
+
+
+

Carte céleste des réseaux

+

+
+
+ +
+
+ + + + + + + +
+
+
Glisser pour se déplacer · molette ou +/− pour s'approcher · Entrée dans la recherche centre la première étoile trouvée · survoler une étoile donne son VMID et son nœud.
+
+ +
+ +
+
+ + + + diff --git a/scripts/carte/polices/LICENCES.md b/scripts/carte/polices/LICENCES.md new file mode 100644 index 0000000..1001404 --- /dev/null +++ b/scripts/carte/polices/LICENCES.md @@ -0,0 +1,15 @@ +# Polices de la carte céleste + +Embarquées par `scripts/carte_reseaux.py` dans chaque carte, pour qu'elle s'ouvre hors ligne +et n'appelle aucun service. Toutes sont libres, sous **SIL Open Font License 1.1** ; le texte +de chaque licence, avec son avis de droit d'auteur, est dans le fichier `OFL-*.txt` voisin. + +Sous-ensemble **latin** seulement (français compris), au format WOFF2, tel que le distribue +Google Fonts. Relevé le 2026-10-19. + +| Fichier | Famille | Licence | +|---|---|---| +| `imfellenglishsc-400.woff2` | IM Fell English SC — Igino Marini | `OFL-imfellenglishsc.txt` | +| `imfellenglish-italic-400.woff2` | IM Fell English, italique — Igino Marini | `OFL-imfellenglish.txt` | +| `spectral-300.woff2`, `spectral-italic-300.woff2`, `spectral-400.woff2`, `spectral-600.woff2` | Spectral — Production Type | `OFL-spectral.txt` | +| `jetbrainsmono-400.woff2` | JetBrains Mono — JetBrains | `OFL-jetbrainsmono.txt` | diff --git a/scripts/carte/polices/OFL-imfellenglish.txt b/scripts/carte/polices/OFL-imfellenglish.txt new file mode 100644 index 0000000..68632c1 --- /dev/null +++ b/scripts/carte/polices/OFL-imfellenglish.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010, Igino Marini (mail@iginomarini.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/scripts/carte/polices/OFL-imfellenglishsc.txt b/scripts/carte/polices/OFL-imfellenglishsc.txt new file mode 100644 index 0000000..68632c1 --- /dev/null +++ b/scripts/carte/polices/OFL-imfellenglishsc.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010, Igino Marini (mail@iginomarini.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/scripts/carte/polices/OFL-jetbrainsmono.txt b/scripts/carte/polices/OFL-jetbrainsmono.txt new file mode 100644 index 0000000..821a3da --- /dev/null +++ b/scripts/carte/polices/OFL-jetbrainsmono.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/scripts/carte/polices/OFL-spectral.txt b/scripts/carte/polices/OFL-spectral.txt new file mode 100644 index 0000000..163d3a5 --- /dev/null +++ b/scripts/carte/polices/OFL-spectral.txt @@ -0,0 +1,93 @@ +Copyright 2017 The Spectral Project Authors (https://github.com/productiontype/Spectral) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/scripts/carte/polices/imfellenglish-italic-400.woff2 b/scripts/carte/polices/imfellenglish-italic-400.woff2 new file mode 100644 index 0000000..9a03c61 Binary files /dev/null and b/scripts/carte/polices/imfellenglish-italic-400.woff2 differ diff --git a/scripts/carte/polices/imfellenglishsc-400.woff2 b/scripts/carte/polices/imfellenglishsc-400.woff2 new file mode 100644 index 0000000..d8df2f9 Binary files /dev/null and b/scripts/carte/polices/imfellenglishsc-400.woff2 differ diff --git a/scripts/carte/polices/jetbrainsmono-400.woff2 b/scripts/carte/polices/jetbrainsmono-400.woff2 new file mode 100644 index 0000000..5858873 Binary files /dev/null and b/scripts/carte/polices/jetbrainsmono-400.woff2 differ diff --git a/scripts/carte/polices/spectral-300.woff2 b/scripts/carte/polices/spectral-300.woff2 new file mode 100644 index 0000000..8d12931 Binary files /dev/null and b/scripts/carte/polices/spectral-300.woff2 differ diff --git a/scripts/carte/polices/spectral-400.woff2 b/scripts/carte/polices/spectral-400.woff2 new file mode 100644 index 0000000..71700f8 Binary files /dev/null and b/scripts/carte/polices/spectral-400.woff2 differ diff --git a/scripts/carte/polices/spectral-600.woff2 b/scripts/carte/polices/spectral-600.woff2 new file mode 100644 index 0000000..3f56161 Binary files /dev/null and b/scripts/carte/polices/spectral-600.woff2 differ diff --git a/scripts/carte/polices/spectral-italic-300.woff2 b/scripts/carte/polices/spectral-italic-300.woff2 new file mode 100644 index 0000000..f9b0676 Binary files /dev/null and b/scripts/carte/polices/spectral-italic-300.woff2 differ diff --git a/scripts/carte_reseaux.py b/scripts/carte_reseaux.py new file mode 100644 index 0000000..59adb2e --- /dev/null +++ b/scripts/carte_reseaux.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""La carte celeste des reseaux : la couche 3 des sites et de leurs locataires, en une page. + +POURQUOI (2026-10-19). Personne ne voyait d'un coup d'oeil ce que les plans declarent : les +zones de chaque site, ses frontieres et tunnels, les VRF de ses locataires, et l'adresse de +chaque machine. L'information existait, dispersee dans six fichiers par site et deux par +locataire. Cette page la rassemble pour la livraison d'un site ou l'ouverture d'un partenariat. + +UNE VUE, PAS UNE FONCTION (AGENTS §12). Rien n'est saisi ni deduit ici : chaque adresse vient +d'un plan, d'une carte (`underlay.yml`) ou d'une face reseau publiee, et se derive par les +fonctions memes du moteur (`underlay.charger_resolu`, `inventory_rules`, `devis_sdn`, +`etoiles`). La carte dit ce que les plans DECLARENT ; elle ne mesure rien. Les devis +(`make underlay-plan`, `make sdn-plan`, `make frontiere-plan`) confrontent au reel. + +LA CARTE PORTE DES ADRESSES INTERNES. Elle ne s'ecrit donc jamais dans le moteur public, sauf +dans `tmp/` (ignore par git) : sa place est le depot prive du site, ou la remise en main +propre. `--site` borne la carte a un site, ses locataires et ses reprises : un partenaire +recoit son site, pas les adresses des autres ecosystemes. + +Aucune voute n'est lue, aucune cle publique WireGuard n'est reportee. Les polices (OFL) sont +embarquees : la page s'ouvre hors ligne et n'appelle aucun service. + +Usage : + python3 scripts/carte_reseaux.py # tous les sites, -> tmp/ + python3 scripts/carte_reseaux.py --site SITE-Technolibre # un site et ses locataires + python3 scripts/carte_reseaux.py --vers ../SITE-X/carte-des-reseaux.html + python3 scripts/carte_reseaux.py --json # les donnees seules +""" +from __future__ import annotations + +import argparse +import base64 +import datetime +import ipaddress +import json +import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import yaml # noqa: E402 + +import contexte # noqa: E402 +import etoiles # noqa: E402 +import underlay as underlay_mod # noqa: E402 +from devis_sdn import vnet_de, zone_de # noqa: E402 +from inventory_rules import passerelle_de, sous_reseau_de, supernet_de, vlan_de # noqa: E402 + +RACINE = Path(__file__).resolve().parents[1] +GABARIT = RACINE / "scripts" / "carte" / "gabarit.html" +POLICES = RACINE / "scripts" / "carte" / "polices" +SORTIE_DEFAUT = RACINE / "tmp" / "carte-des-reseaux.html" +# (famille CSS, style, graisse, fichier) — sous-ensemble latin, licence OFL (polices/LICENCES.md). +FACES = ( + ("IM Fell English SC", "normal", 400, "imfellenglishsc-400.woff2"), + ("IM Fell English", "italic", 400, "imfellenglish-italic-400.woff2"), + ("Spectral", "normal", 300, "spectral-300.woff2"), + ("Spectral", "italic", 300, "spectral-italic-300.woff2"), + ("Spectral", "normal", 400, "spectral-400.woff2"), + ("Spectral", "normal", 600, "spectral-600.woff2"), + ("JetBrains Mono", "normal", 400, "jetbrainsmono-400.woff2"), +) + + +class CarteRefusee(Exception): + """Une demande que la carte ne doit pas satisfaire (portee inconnue, sortie publique).""" + + +def _yaml(chemin: Path) -> dict: + if not chemin.is_file(): + return {} + d = yaml.safe_load(chemin.read_text(encoding="utf-8")) + return d if isinstance(d, dict) else {} + + +def _commit(depot: Path) -> str: + """Le commit court du depot, suivi de `+` si l'arbre porte des modifications.""" + r = subprocess.run(["git", "-C", str(depot), "rev-parse", "--short", "HEAD"], + capture_output=True, text=True) + if r.returncode != 0: + return "" + sale = subprocess.run(["git", "-C", str(depot), "status", "--porcelain"], + capture_output=True, text=True).stdout.strip() + return r.stdout.strip() + ("+" if sale else "") + + +def _tri_ip(vms: list[dict]) -> list[dict]: + return sorted(vms, key=lambda v: ipaddress.ip_address(v["ip"])) + + +def _hote(h: dict) -> dict: + """Un hote de la carte, sans sa cle publique : la carte n'en a pas l'usage.""" + out = {"nom": h.get("nom"), "ip": h.get("ip"), "role": h.get("role", "")} + if h.get("etat"): + out["etat"] = h["etat"] + return out + + +# --- SITE --------------------------------------------------------------------------------- + +def _site(site: contexte.Site) -> dict: + carte = underlay_mod.charger_resolu(site.underlay) or {} + intrants = site.lire_plan("10-intrants.yml") + opn = _yaml(site.depot / "opnsense.yml") + px = _yaml(site.depot / "proxmox-hebergeur.yml") + serveurs = site.lire_plan("serveurs.yml").get("serveurs") or {} + index = carte.get("index") + reseaux = carte.get("reseaux") or [] + hotes = carte.get("hotes") or [] + transit = underlay_mod.reseau_transit(carte) or {} + + frontieres = [h for h in hotes if h.get("role") == "frontiere"] + frontiere = next((h["nom"] for h in frontieres if h.get("reseau") == "management"), + frontieres[0]["nom"] if frontieres else "frontière") + + zones, fabric, liens, relais = [], [], [], None + for r in reseaux: + hs = [_hote(h) for h in hotes if h.get("reseau") == r.get("nom")] + if r.get("nature") == "site": + vms = [{"nom": n, "ip": d["ip"], "noeud": d.get("noeud"), "vmid": d.get("vmid")} + for n, d in serveurs.items() + if isinstance(d, dict) and d.get("reseau") == r["nom"] + and d.get("etat", "actif") == "actif" and d.get("ip")] + zones.append({"nom": r["nom"], "vlan": r.get("vlan"), "sous_reseau": r.get("sous_reseau"), + "passerelle": r.get("passerelle"), "description": r.get("description", ""), + "vms": _tri_ip(vms)}) + continue + fab = underlay_mod.fabric_de(r) + if fab == "inter-sites": + local = next((h for h in hotes if h.get("reseau") == r["nom"] and h.get("role") == "frontiere"), {}) + pair = next((h for h in hotes if h.get("reseau") == r["nom"] and h.get("role") == "frontiere_pair"), {}) + pairs_dns = {str(p.get("site")) for p in (intrants.get("dns_public_pairs") or []) + if isinstance(p, dict) and p.get("etat") == "actif"} + liens.append({"sous_reseau": r.get("sous_reseau"), "mtu": r.get("mtu"), + "local": {"nom": local.get("nom"), "ip": local.get("ip")}, + "pair": {"nom": pair.get("nom"), "ip": pair.get("ip"), "site": pair.get("site"), + "point_arrivee": pair.get("point_arrivee")}, + "dns_public": pair.get("site") in pairs_dns}) + continue + rel = next((h for h in hotes if h.get("reseau") == r["nom"] and h.get("role") == "relais"), None) + if rel: + bout = next((h for h in hotes if h.get("reseau") == r["nom"] and h.get("role") == "frontiere"), {}) + relais = {"nom": rel.get("nom"), "console": rel.get("console"), "ip": rel.get("ip"), + "ip_frontiere": bout.get("ip"), "sous_reseau": r.get("sous_reseau"), "mtu": r.get("mtu")} + continue + fabric.append({"nom": r["nom"], "vlan": r.get("vlan"), "sous_reseau": r.get("sous_reseau"), + "mtu": r.get("mtu"), "tunnel": r.get("tunnel"), "fabric": fab, + "transit": r.get("nom") == transit.get("nom"), + "description": r.get("description", ""), "hotes": hs}) + + hyperviseurs: dict[str, dict] = {} + for h in hotes: + if h.get("role") == "hyperviseur": + hyperviseurs.setdefault(h["nom"], {"nom": h["nom"], "adresses": {}})["adresses"][h["reseau"]] = h["ip"] + + pool = opn.get("opnsense_ips_publiques") or {} + publiques = ([{"ip": opn["opnsense_wan_ip"], "pour": site.nom}] if opn.get("opnsense_wan_ip") else []) + publiques += [{"ip": ip, "pour": str(pour)} for ip, pour in pool.items()] + + vpn = intrants.get("acces_admin_vpn") or {} + admins = None + if vpn.get("reseau"): + admins = {"reseau": vpn["reseau"], "port": vpn.get("port"), "mtu": vpn.get("mtu"), + "frontiere": str(vpn.get("adresse_frontiere") or "").split("/")[0], + "pairs": [{"nom": p.get("nom"), "adresse": str(p.get("adresse", "")).split("/")[0]} + for p in vpn.get("pairs") or [] + if isinstance(p, dict) and p.get("etat", "present") == "present"]} + + locataires, reprises = [], [] + for loc in site.locataires(): + if loc.nom_hebergeur() == site.nom: + t = _locataire(loc) + if t: + locataires.append(t) + else: + reprises.append(_reprise(loc, pool)) + + return { + "nom": site.nom, "commit": _commit(site.depot), "index": index, + "etoile": etoiles.domaine_site(index) if isinstance(index, int) else "", + "domaine": intrants.get("domaine_interne", ""), "organisation": intrants.get("organisation", ""), + "frontiere": frontiere, "opnsense": bool(opn), + "dns_public_nom": intrants.get("dns_public_nom"), + "transit": {"nom": transit.get("nom"), "vlan": transit.get("vlan"), + "sous_reseau": transit.get("sous_reseau"), "sortie": transit.get("passerelle_sortie")}, + "hyperviseurs": list(hyperviseurs.values()), + "sdn": px.get("proxmox_sdn") or {}, "noeuds": px.get("proxmox_noeuds") or [], + "publiques": publiques, "relais": relais, "admins": admins, "liens": liens, + "fabric": fabric, "zones": zones, + "locataires": locataires, "reprises": reprises, "absents": site.locataires_absents(), + } + + +# --- LOCATAIRE ------------------------------------------------------------------------------ + +def _categories(face: dict) -> list[tuple[int, str]]: + cats = ((face.get("nomenclature") or {}).get("categories")) or {} + return sorted((int(k), str((v or {}).get("libelle", f"zone-{k}"))) for k, v in cats.items()) + + +def _locataire(loc: contexte.Locataire) -> dict | None: + """Un locataire heberge ICI, d'apres la face qu'il publie pour son site. Sans face publiee, + rien : le site ne lit pas les fichiers internes de ses locataires (§2.4).""" + face = loc.face_publiee() + if not face: + return None + index = face.get("index") + machines = face.get("machines") or {} + fiche = loc.fiche_du_site() or {} + domaine = next((str((m.get("clonage") or {}).get("SETOPS_DOMAINE") or "") for m in machines.values() + if (m.get("clonage") or {}).get("SETOPS_DOMAINE")), "") or loc.domaine_interne() + zones = [] + for k, libelle in _categories(face): + gw = passerelle_de(index, k) + vms = [{"nom": n, "ip": m["ip"], "noeud": (m.get("materialisation") or {}).get("proxmox_noeud"), + "vmid": (m.get("materialisation") or {}).get("proxmox_vmid")} + for n, m in machines.items() + if m.get("etat") == "actif" and (m.get("materialisation") or {}).get("proxmox_passerelle") == gw] + zones.append({"libelle": libelle, "sous_reseau": sous_reseau_de(index, k), "passerelle": gw, + "vnet": vnet_de(index, libelle), "tag": vlan_de(index, k), "vms": _tri_ip(vms)}) + adm = face.get("administration") or {} + return { + "nom": loc.nom, "commit": _commit(loc.depot), "index": index, "domaine": domaine, + "vrf": zone_de(index), "vni": index, "supernet": supernet_de(index), + "ip_publique": ((fiche.get("attribue") or {}).get("ip_publique")), + "tunnel": {"reseau": (adm.get("tunnel") or [None])[0], "port": adm.get("port_tunnel"), + "pairs": [{"nom": n, "adresse": str(p.get("adresse", "")).split("/")[0]} + for n, p in (adm.get("pairs") or {}).items() + if isinstance(p, dict) and p.get("etat", "present") == "present"]}, + "dns_public": face.get("dns_public") or {}, + "zones": zones, + } + + +def _reprise(loc: contexte.Locataire, pool: dict) -> dict: + """Un locataire que ce site peut REPRENDRE : ses zones lui sont reservees, rien n'y tourne.""" + index = loc.index + face = loc.face_publiee() or {"nomenclature": loc.nomenclature()} + return {"nom": loc.nom, "index": index, "vrf": zone_de(index), "supernet": supernet_de(index), + "zones": [sous_reseau_de(index, k) for k, _ in _categories(face)], + "ip_publique": next((ip for ip, pour in pool.items() if str(pour) == loc.nom), None)} + + +# --- LA CARTE --------------------------------------------------------------------------------- + +def collecter(dossier: Path = contexte.DOSSIER_ECOSYSTEMES, site: str | None = None) -> dict: + """Les donnees de la carte : tous les sites freres, ou le seul site nomme.""" + # Un lien `underlay.yml` est un MONTAGE (le moteur monte la carte de son site) : le site + # est le depot qui porte la carte elle-meme. Sans ce filtre, le moteur se dessinait en + # troisieme site, double de celui qu'il monte. + sites = [contexte.Site(p.parent) for p in sorted(Path(dossier).glob("*/underlay.yml")) + if not p.is_symlink()] + if site: + sites = [s for s in sites if s.nom == site] + if not sites: + raise CarteRefusee(f"site « {site} » introuvable : pas de {Path(dossier) / site}/underlay.yml") + donnees = {"date": datetime.date.today().isoformat(), "portee": site, "sites": [_site(s) for s in sites]} + if not site: + # Ce qui reste hors de la carte, et pourquoi : un filtre qui oublie en silence est un defaut. + vus = {t["nom"] for s in donnees["sites"] for t in s["locataires"] + s["reprises"]} + hors = [] + for nomen in sorted(Path(dossier).glob("*/plan/nomenclature.yml")): + depot = nomen.parent.parent + if depot.name in vus: + continue + federe = _yaml(nomen).get("federe", True) + hors.append({"nom": depot.name, "index": _yaml(nomen).get("index"), + "raison": "bac à sable local, non fédéré" if federe is False + else "déclaré par aucun site"}) + donnees["hors_carte"] = hors + return donnees + + +def _polices() -> str: + regles = [] + for famille, style, graisse, fichier in FACES: + b64 = base64.b64encode((POLICES / fichier).read_bytes()).decode("ascii") + regles.append(f"@font-face{{font-family:\"{famille}\";font-style:{style};font-weight:{graisse};" + f"font-display:swap;src:url(data:font/woff2;base64,{b64}) format(\"woff2\");}}") + return "\n".join(regles) + + +def rendre(donnees: dict) -> str: + """La page autonome : gabarit + polices embarquees + donnees.""" + page = GABARIT.read_text(encoding="utf-8") + # ` qui la porte. + brut = json.dumps(donnees, ensure_ascii=False).replace(" Path: + """Refuse d'ecrire la carte dans le moteur public, hors de `tmp/` (ignore par git).""" + cible = vers.expanduser().resolve() + if cible.is_relative_to(RACINE) and not cible.is_relative_to(RACINE / "tmp"): + raise CarteRefusee( + f"{cible} est dans le moteur public : la carte porte des adresses internes. " + f"Ecrire dans tmp/, dans le depot prive du site, ou hors des depots.") + return cible + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description="La carte celeste des reseaux (couche 3).") + ap.add_argument("--site", help="borner la carte a ce site (dossier frere), ses locataires et ses reprises") + ap.add_argument("--vers", type=Path, default=SORTIE_DEFAUT, help="fichier HTML a ecrire") + ap.add_argument("--json", action="store_true", help="afficher les donnees, ne rien ecrire") + a = ap.parse_args(argv) + try: + donnees = collecter(site=a.site) + if a.json: + json.dump(donnees, sys.stdout, ensure_ascii=False, indent=1) + print() + return 0 + cible = verifier_sortie(a.vers) + except CarteRefusee as e: + print(f"refus : {e}", file=sys.stderr) + return 2 + cible.parent.mkdir(parents=True, exist_ok=True) + cible.write_text(rendre(donnees), encoding="utf-8") + nb_vm = sum(len(z["vms"]) for s in donnees["sites"] + for g in [s, *s["locataires"]] for z in g["zones"]) + nb_loc = sum(len(s["locataires"]) for s in donnees["sites"]) + print(f"carte : {len(donnees['sites'])} site(s), {nb_loc} locataire(s) heberge(s), {nb_vm} machine(s)") + for s in donnees["sites"]: + print(f" {s['nom']}@{s['commit'] or '?'} — {s['etoile']}, {len(s['zones'])} zones, " + f"{len(s['locataires'])} locataire(s), {len(s['reprises'])} reprise(s)") + print(f"ecrite : {cible}") + print("Elle porte des adresses internes : la remettre en main propre, ou la verser au depot prive du site.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/tests/test_carte_reseaux.py b/scripts/tests/test_carte_reseaux.py new file mode 100644 index 0000000..aba96f6 --- /dev/null +++ b/scripts/tests/test_carte_reseaux.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""La carte celeste des reseaux : une vue des plans, autonome, qui ne fuit rien. + +Ecosystemes FICTIFS (adresses de documentation, RFC 5737) : le moteur est public, les vraies +adresses n'y entrent pas. Ces cas gardent : + 1. un site est un depot qui PORTE sa carte ; un lien `underlay.yml` (montage du moteur) n'en + fait pas un troisieme site ; + 2. les zones du site et celles du locataire viennent des derivations du moteur ; + 3. un locataire paraît heberge chez son hebergeur actif, en reprise chez l'autre site ; + 4. `--site` borne la carte : les adresses des autres ecosystemes n'y entrent pas ; + 5. la page est autonome (polices embarquees, aucune adresse web) et ne porte ni cle + publique, ni contenu de voute, ni `` venu d'un plan ; + 6. la carte ne s'ecrit jamais dans le moteur public, hors de `tmp/`. +""" +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +import yaml + +RACINE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(RACINE / "scripts")) + +import carte_reseaux as C # noqa: E402 +import etoiles # noqa: E402 +from inventory_rules import vlan_de # noqa: E402 + +CLE_SITE = "CLEPUBLIQUEDUPORTEEXEMPLE0000000000000000000=" +CLE_PAIR = "CLEPUBLIQUEALICE000000000000000000000000000=" +CLE_BOB = "CLEPUBLIQUEBOB00000000000000000000000000000=" +SECRET = "SECRET-NE-JAMAIS-LIRE" + + +def _ecrire(base: Path, chemin: str, contenu) -> None: + f = base / chemin + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(contenu if isinstance(contenu, str) else yaml.safe_dump(contenu, allow_unicode=True), + encoding="utf-8") + + +def _flotte(d: Path) -> None: + """Deux sites relies, un locataire heberge par l'un et repris par l'autre, un bac a sable.""" + _ecrire(d, "SITE-Exemple/underlay.yml", {"underlay": { + "index": 41, "tenants": {"OPS-Exemple": 19}, + "reseaux": [ + {"nom": "management", "nature": "fabric", "sous_reseau": "10.41.0.0/24", "mtu": 1500}, + {"nom": "site-pilotage", "nature": "site", "vlan": 31, "mtu": 1500, + "description": "injection"}, + {"nom": "site-genome", "nature": "site", "vlan": 33, "mtu": 1500}, + {"nom": "transit-frontiere", "nature": "fabric", "vlan": 40, "sous_reseau": "10.0.4.0/24", + "passerelle_sortie": "10.0.4.1", "mtu": 1500}, + {"nom": "inter-sites", "nature": "fabric", "fabric": "inter-sites", "tunnel": "wireguard", + "sous_reseau": "172.30.0.0/30", "mtu": 1412}], + "hotes": [ + {"nom": "porte", "reseau": "management", "ip": "10.41.0.1", "role": "frontiere"}, + {"nom": "porte", "reseau": "transit-frontiere", "ip": "10.0.4.1", "role": "frontiere"}, + {"nom": "porte", "reseau": "inter-sites", "ip": "172.30.0.1", "role": "frontiere", "cle_publique": CLE_SITE}, + {"nom": "autre-porte", "reseau": "inter-sites", "ip": "172.30.0.2", "role": "frontiere_pair", + "site": "SITE-Autre"}, + {"nom": "noeud1", "reseau": "transit-frontiere", "ip": "10.0.4.11", "role": "hyperviseur"}]}}) + _ecrire(d, "SITE-Exemple/opnsense.yml", {"opnsense_wan_ip": "203.0.113.10", + "opnsense_ips_publiques": {"203.0.113.11": "OPS-Exemple"}}) + _ecrire(d, "SITE-Exemple/underlay.vault.yml", f"vault_secret: {SECRET}\n") + _ecrire(d, "SITE-Exemple/proxmox-hebergeur.yml", {"proxmox_noeuds": ["noeud1"], "proxmox_sdn": { + "asn": 65041, "controleur": "EVPN0041", "noeuds_de_sortie": ["noeud1"], "sortie_primaire": "noeud1"}}) + _ecrire(d, "SITE-Exemple/plan/10-intrants.yml", { + "domaine_interne": etoiles.domaine_site(41), + "dns_public_pairs": [{"site": "SITE-Autre", "etat": "actif"}], + "acces_admin_vpn": {"reseau": "10.41.29.0/24", "port": 51821, "mtu": 1412, "adresse_frontiere": "10.41.29.1/24", + "pairs": [{"nom": "alice-portable", "cle_publique": CLE_PAIR, + "adresse": "10.41.29.2/32", "etat": "present"}]}}) + _ecrire(d, "SITE-Exemple/plan/serveurs.yml", {"serveurs": { + "site-ops-01": {"etat": "actif", "reseau": "site-pilotage", "ip": "10.41.31.11", "noeud": "noeud1", "vmid": 9001}, + "site-forge-01": {"etat": "actif", "reseau": "site-genome", "ip": "10.41.33.11", "noeud": "noeud1", "vmid": 9003}, + "site-vieux-01": {"etat": "retire", "reseau": "site-genome", "ip": "10.41.33.99"}}}) + + _ecrire(d, "SITE-Autre/underlay.yml", {"underlay": { + "index": 43, "tenants": {"OPS-Exemple": 19}, + "reseaux": [ + {"nom": "site-pilotage", "nature": "site", "vlan": 31, "mtu": 1500}, + {"nom": "transit-frontiere", "nature": "fabric", "vlan": 40, "sous_reseau": "10.0.4.0/24", + "passerelle_sortie": "10.0.4.1", "mtu": 1500}, + {"nom": "inter-sites", "nature": "fabric", "fabric": "inter-sites", "tunnel": "wireguard", + "sous_reseau": "172.30.0.0/30", "mtu": 1412}], + "hotes": [ + {"nom": "autre-porte", "reseau": "transit-frontiere", "ip": "10.0.4.1", "role": "frontiere"}, + {"nom": "autre-porte", "reseau": "inter-sites", "ip": "172.30.0.2", "role": "frontiere"}, + {"nom": "porte", "reseau": "inter-sites", "ip": "172.30.0.1", "role": "frontiere_pair", + "site": "SITE-Exemple", "point_arrivee": "203.0.113.10:51820"}]}}) + _ecrire(d, "SITE-Autre/opnsense.yml", {"opnsense_wan_ip": "198.51.100.6", + "opnsense_ips_publiques": {"198.51.100.7": "OPS-Exemple"}}) + _ecrire(d, "SITE-Autre/plan/serveurs.yml", {"serveurs": { + "site-ops-01": {"etat": "actif", "reseau": "site-pilotage", "ip": "10.43.31.11", "vmid": 9001}}}) + + cats = {1: {"libelle": "Frontiere"}, 4: {"libelle": "Services-infra"}} + _ecrire(d, "OPS-Exemple/plan/nomenclature.yml", {"index": 19, "categories": cats}) + _ecrire(d, "OPS-Exemple/parente.yml", {"parente": {"depots": {"hebergeur": {"nom": "SITE-Exemple"}}}}) + _ecrire(d, "OPS-Exemple/fiche-site.yml", {"attribue": {"index": 19, "ip_publique": "203.0.113.11"}}) + machine = lambda ip, gw: {"ip": ip, "etat": "actif", "clonage": {"SETOPS_DOMAINE": "exemple.internal"}, + "materialisation": {"proxmox_noeud": "noeud1", "proxmox_passerelle": gw, "proxmox_vmid": 1}} + _ecrire(d, "OPS-Exemple/face-reseau.yml", { + "index": 19, "nomenclature": {"index": 19, "categories": cats}, + "machines": {"infra-edge-01": machine("10.19.16.11", "10.19.16.1"), + "infra-dns-01": machine("10.19.19.11", "10.19.19.1")}, + "administration": {"tunnel": ["10.19.29.0/24"], "port_tunnel": 52019, + "pairs": {"bob-portable": {"cle_publique": CLE_BOB, "adresse": "10.19.29.2/32", "etat": "present"}}}, + "dns_public": {"zones": ["exemple.ca"], "primaire": "10.19.19.11", "port": 5300}}) + + _ecrire(d, "OPS-Bac/plan/nomenclature.yml", {"index": 21, "federe": False, "categories": cats}) + (d / "Moteur").mkdir() + os.symlink("../SITE-Exemple/underlay.yml", d / "Moteur" / "underlay.yml") + + +class Carte(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._tmp = tempfile.TemporaryDirectory() + cls.d = Path(cls._tmp.name) + _flotte(cls.d) + cls.tout = C.collecter(cls.d) + cls.sites = {s["nom"]: s for s in cls.tout["sites"]} + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_un_montage_n_est_pas_un_site(self): + self.assertEqual(sorted(self.sites), ["SITE-Autre", "SITE-Exemple"]) + + def test_zones_du_site_derivees(self): + s = self.sites["SITE-Exemple"] + self.assertEqual(s["etoile"], etoiles.domaine_site(41)) + self.assertEqual([(z["sous_reseau"], z["passerelle"]) for z in s["zones"]], + [("10.41.31.0/24", "10.41.31.1"), ("10.41.33.0/24", "10.41.33.1")]) + self.assertEqual([v["nom"] for z in s["zones"] for v in z["vms"]], ["site-ops-01", "site-forge-01"], + "une machine retiree ne parait pas") + self.assertEqual(s["frontiere"], "porte") + self.assertEqual(s["hyperviseurs"], [{"nom": "noeud1", "adresses": {"transit-frontiere": "10.0.4.11"}}]) + + def test_locataire_heberge_ici_repris_la_bas(self): + t = self.sites["SITE-Exemple"]["locataires"][0] + self.assertEqual((t["nom"], t["vrf"], t["supernet"], t["ip_publique"]), + ("OPS-Exemple", "t19", "10.19.0.0/16", "203.0.113.11")) + self.assertEqual([(z["vnet"], z["tag"], z["sous_reseau"], [v["ip"] for v in z["vms"]]) for z in t["zones"]], + [("t19fron", vlan_de(19, 1), "10.19.16.0/24", ["10.19.16.11"]), + ("t19serv", vlan_de(19, 4), "10.19.19.0/24", ["10.19.19.11"])]) + self.assertEqual(self.sites["SITE-Autre"]["locataires"], []) + r = self.sites["SITE-Autre"]["reprises"][0] + self.assertEqual((r["nom"], r["ip_publique"], r["zones"]), + ("OPS-Exemple", "198.51.100.7", ["10.19.16.0/24", "10.19.19.0/24"])) + + def test_lien_entre_les_sites(self): + l = self.sites["SITE-Exemple"]["liens"][0] + self.assertEqual((l["local"]["ip"], l["pair"]["site"], l["dns_public"]), ("172.30.0.1", "SITE-Autre", True)) + self.assertEqual(self.sites["SITE-Autre"]["liens"][0]["pair"]["point_arrivee"], "203.0.113.10:51820") + + def test_hors_carte_dit_pourquoi(self): + self.assertEqual(self.tout["hors_carte"], + [{"nom": "OPS-Bac", "index": 21, "raison": "bac à sable local, non fédéré"}]) + + def test_portee_bornee_a_un_site(self): + donnees = C.collecter(self.d, site="SITE-Autre") + page = C.rendre(donnees) + self.assertEqual([s["nom"] for s in donnees["sites"]], ["SITE-Autre"]) + self.assertIn("10.43.31.11", page) + for ailleurs in ("10.41.31.11", "10.19.16.11", "10.19.19.11", "203.0.113.11", "alice-portable", "bob-portable"): + self.assertNotIn(ailleurs, page, f"{ailleurs} appartient a un autre ecosysteme") + with self.assertRaises(C.CarteRefusee): + C.collecter(self.d, site="SITE-Inconnu") + + def test_page_autonome_et_sans_fuite(self): + page = C.rendre(self.tout) + for g in self.tout["sites"]: + for e in [g, *g["locataires"]]: + for z in e["zones"]: + for v in z["vms"]: + self.assertIn(v["ip"], page) + self.assertEqual(page.count("@font-face"), len(C.FACES)) + self.assertIn("data:font/woff2;base64,", page) + self.assertEqual(set(re.findall(r"https?://[^\s\"'<>)]+", page)), {"http://www.w3.org/2000/svg"}, + "aucune ressource exterieure : la page s'ouvre hors ligne") + for fuite in (CLE_SITE, CLE_PAIR, CLE_BOB, SECRET): + self.assertNotIn(fuite, page) + self.assertEqual(page.count(""), 1, "un `` venu d'un plan fermerait le script") + + def test_script_de_la_page_se_lit(self): + node = shutil.which("node") + if not node: + self.skipTest("node absent : syntaxe du script non verifiee") + page = C.rendre(self.tout) + with tempfile.NamedTemporaryFile("w", suffix=".js", delete=False, encoding="utf-8") as f: + f.write(page[page.rindex("")]) + try: + r = subprocess.run([node, "--check", f.name], capture_output=True, text=True) + finally: + os.unlink(f.name) + self.assertEqual(r.returncode, 0, r.stderr) + + +class Sortie(unittest.TestCase): + def test_jamais_dans_le_moteur_public(self): + with self.assertRaises(C.CarteRefusee): + C.verifier_sortie(RACINE / "docs" / "carte.html") + with self.assertRaises(C.CarteRefusee): + C.verifier_sortie(RACINE / "carte.html") + self.assertEqual(C.verifier_sortie(RACINE / "tmp" / "carte.html"), RACINE / "tmp" / "carte.html") + dehors = RACINE.parent / "SITE-Quelconque" / "carte.html" + self.assertEqual(C.verifier_sortie(dehors), dehors.resolve()) + + +if __name__ == "__main__": + unittest.main(verbosity=2)