M1
EBO <eric@ebii.fr> committé le 2026-11-02 04:30
b145b5d556ba0f294bbd5628ed24110707d09256
1 parent(s)
116 fichiers modifiés
+9853
-99
M
Cargo.lock
+494
-2
@@ -144,6 +144,7 @@ dependencies = [
| 144 | 144 | "matchit", |
| 145 | 145 | "memchr", |
| 146 | 146 | "mime", |
| 147 | + "multer", | |
| 147 | 148 | "percent-encoding", |
| 148 | 149 | "pin-project-lite", |
| 149 | 150 | "serde_core", |
@@ -185,6 +186,12 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
| 185 | 186 | |
| 186 | 187 | [[package]] |
| 187 | 188 | name = "bitflags" |
| 189 | +version = "1.3.2" | |
| 190 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 191 | +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" | |
| 192 | + | |
| 193 | +[[package]] | |
| 194 | +name = "bitflags" | |
| 188 | 195 | version = "2.13.2" |
| 189 | 196 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 190 | 197 | checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" |
@@ -295,6 +302,12 @@ dependencies = [
| 295 | 302 | ] |
| 296 | 303 | |
| 297 | 304 | [[package]] |
| 305 | +name = "core_detect" | |
| 306 | +version = "1.0.0" | |
| 307 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 308 | +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" | |
| 309 | + | |
| 310 | +[[package]] | |
| 298 | 311 | name = "cpufeatures" |
| 299 | 312 | version = "0.3.1" |
| 300 | 313 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -313,6 +326,37 @@ dependencies = [
| 313 | 326 | ] |
| 314 | 327 | |
| 315 | 328 | [[package]] |
| 329 | +name = "defmt" | |
| 330 | +version = "1.2.0" | |
| 331 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 332 | +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" | |
| 333 | +dependencies = [ | |
| 334 | + "bitflags 1.3.2", | |
| 335 | + "defmt-macros", | |
| 336 | +] | |
| 337 | + | |
| 338 | +[[package]] | |
| 339 | +name = "defmt-macros" | |
| 340 | +version = "1.2.0" | |
| 341 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 342 | +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" | |
| 343 | +dependencies = [ | |
| 344 | + "defmt-parser", | |
| 345 | + "proc-macro2", | |
| 346 | + "quote", | |
| 347 | + "syn 3.0.9", | |
| 348 | +] | |
| 349 | + | |
| 350 | +[[package]] | |
| 351 | +name = "defmt-parser" | |
| 352 | +version = "1.1.0" | |
| 353 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 354 | +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" | |
| 355 | +dependencies = [ | |
| 356 | + "thiserror", | |
| 357 | +] | |
| 358 | + | |
| 359 | +[[package]] | |
| 316 | 360 | name = "deranged" |
| 317 | 361 | version = "0.5.9" |
| 318 | 362 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -333,6 +377,31 @@ dependencies = [
| 333 | 377 | ] |
| 334 | 378 | |
| 335 | 379 | [[package]] |
| 380 | +name = "displaydoc" | |
| 381 | +version = "0.2.7" | |
| 382 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 383 | +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" | |
| 384 | +dependencies = [ | |
| 385 | + "proc-macro2", | |
| 386 | + "quote", | |
| 387 | + "syn 3.0.9", | |
| 388 | +] | |
| 389 | + | |
| 390 | +[[package]] | |
| 391 | +name = "encoding_rs" | |
| 392 | +version = "0.8.42" | |
| 393 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 394 | +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" | |
| 395 | +dependencies = [ | |
| 396 | + "cfg-if", | |
| 397 | + "core_detect", | |
| 398 | + "multiversion_no_op", | |
| 399 | + "rustversion", | |
| 400 | + "scopeguard", | |
| 401 | + "simdutf8", | |
| 402 | +] | |
| 403 | + | |
| 404 | +[[package]] | |
| 336 | 405 | name = "equivalent" |
| 337 | 406 | version = "1.0.3" |
| 338 | 407 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -349,6 +418,12 @@ dependencies = [
| 349 | 418 | ] |
| 350 | 419 | |
| 351 | 420 | [[package]] |
| 421 | +name = "fastrand" | |
| 422 | +version = "2.5.0" | |
| 423 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 424 | +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | |
| 425 | + | |
| 426 | +[[package]] | |
| 352 | 427 | name = "form_urlencoded" |
| 353 | 428 | version = "1.2.2" |
| 354 | 429 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -568,6 +643,110 @@ dependencies = [
| 568 | 643 | ] |
| 569 | 644 | |
| 570 | 645 | [[package]] |
| 646 | +name = "icu_collections" | |
| 647 | +version = "2.4.0" | |
| 648 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 649 | +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" | |
| 650 | +dependencies = [ | |
| 651 | + "displaydoc", | |
| 652 | + "potential_utf", | |
| 653 | + "utf8_iter", | |
| 654 | + "yoke", | |
| 655 | + "zerofrom", | |
| 656 | + "zerovec", | |
| 657 | +] | |
| 658 | + | |
| 659 | +[[package]] | |
| 660 | +name = "icu_locale_core" | |
| 661 | +version = "2.4.0" | |
| 662 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 663 | +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" | |
| 664 | +dependencies = [ | |
| 665 | + "displaydoc", | |
| 666 | + "litemap", | |
| 667 | + "tinystr", | |
| 668 | + "writeable", | |
| 669 | + "zerovec", | |
| 670 | +] | |
| 671 | + | |
| 672 | +[[package]] | |
| 673 | +name = "icu_normalizer" | |
| 674 | +version = "2.4.0" | |
| 675 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 676 | +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" | |
| 677 | +dependencies = [ | |
| 678 | + "icu_collections", | |
| 679 | + "icu_normalizer_data", | |
| 680 | + "icu_properties", | |
| 681 | + "icu_provider", | |
| 682 | + "smallvec", | |
| 683 | + "zerovec", | |
| 684 | +] | |
| 685 | + | |
| 686 | +[[package]] | |
| 687 | +name = "icu_normalizer_data" | |
| 688 | +version = "2.4.0" | |
| 689 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 690 | +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" | |
| 691 | + | |
| 692 | +[[package]] | |
| 693 | +name = "icu_properties" | |
| 694 | +version = "2.4.0" | |
| 695 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 696 | +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" | |
| 697 | +dependencies = [ | |
| 698 | + "displaydoc", | |
| 699 | + "icu_collections", | |
| 700 | + "icu_locale_core", | |
| 701 | + "icu_properties_data", | |
| 702 | + "icu_provider", | |
| 703 | + "zerotrie", | |
| 704 | + "zerovec", | |
| 705 | +] | |
| 706 | + | |
| 707 | +[[package]] | |
| 708 | +name = "icu_properties_data" | |
| 709 | +version = "2.4.0" | |
| 710 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 711 | +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" | |
| 712 | + | |
| 713 | +[[package]] | |
| 714 | +name = "icu_provider" | |
| 715 | +version = "2.4.0" | |
| 716 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 717 | +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" | |
| 718 | +dependencies = [ | |
| 719 | + "displaydoc", | |
| 720 | + "icu_locale_core", | |
| 721 | + "writeable", | |
| 722 | + "yoke", | |
| 723 | + "zerofrom", | |
| 724 | + "zerotrie", | |
| 725 | + "zerovec", | |
| 726 | +] | |
| 727 | + | |
| 728 | +[[package]] | |
| 729 | +name = "idna" | |
| 730 | +version = "1.1.0" | |
| 731 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 732 | +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" | |
| 733 | +dependencies = [ | |
| 734 | + "idna_adapter", | |
| 735 | + "smallvec", | |
| 736 | + "utf8_iter", | |
| 737 | +] | |
| 738 | + | |
| 739 | +[[package]] | |
| 740 | +name = "idna_adapter" | |
| 741 | +version = "1.2.2" | |
| 742 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 743 | +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" | |
| 744 | +dependencies = [ | |
| 745 | + "icu_normalizer", | |
| 746 | + "icu_properties", | |
| 747 | +] | |
| 748 | + | |
| 749 | +[[package]] | |
| 571 | 750 | name = "indexmap" |
| 572 | 751 | version = "2.14.2" |
| 573 | 752 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -590,6 +769,60 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 590 | 769 | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" |
| 591 | 770 | |
| 592 | 771 | [[package]] |
| 772 | +name = "jiff" | |
| 773 | +version = "0.2.38" | |
| 774 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 775 | +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" | |
| 776 | +dependencies = [ | |
| 777 | + "defmt", | |
| 778 | + "jiff-core", | |
| 779 | + "jiff-static", | |
| 780 | + "jiff-tzdb-platform", | |
| 781 | + "log", | |
| 782 | + "portable-atomic", | |
| 783 | + "portable-atomic-util", | |
| 784 | + "serde_core", | |
| 785 | + "windows-link", | |
| 786 | +] | |
| 787 | + | |
| 788 | +[[package]] | |
| 789 | +name = "jiff-core" | |
| 790 | +version = "0.1.1" | |
| 791 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 792 | +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" | |
| 793 | +dependencies = [ | |
| 794 | + "defmt", | |
| 795 | + "log", | |
| 796 | +] | |
| 797 | + | |
| 798 | +[[package]] | |
| 799 | +name = "jiff-static" | |
| 800 | +version = "0.2.38" | |
| 801 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 802 | +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" | |
| 803 | +dependencies = [ | |
| 804 | + "jiff-core", | |
| 805 | + "proc-macro2", | |
| 806 | + "quote", | |
| 807 | + "syn 2.0.119", | |
| 808 | +] | |
| 809 | + | |
| 810 | +[[package]] | |
| 811 | +name = "jiff-tzdb" | |
| 812 | +version = "0.1.9" | |
| 813 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 814 | +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" | |
| 815 | + | |
| 816 | +[[package]] | |
| 817 | +name = "jiff-tzdb-platform" | |
| 818 | +version = "0.1.3" | |
| 819 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 820 | +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" | |
| 821 | +dependencies = [ | |
| 822 | + "jiff-tzdb", | |
| 823 | +] | |
| 824 | + | |
| 825 | +[[package]] | |
| 593 | 826 | name = "lazy_static" |
| 594 | 827 | version = "1.5.1" |
| 595 | 828 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -602,6 +835,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 602 | 835 | checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" |
| 603 | 836 | |
| 604 | 837 | [[package]] |
| 838 | +name = "linux-raw-sys" | |
| 839 | +version = "0.12.1" | |
| 840 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 841 | +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" | |
| 842 | + | |
| 843 | +[[package]] | |
| 844 | +name = "litemap" | |
| 845 | +version = "0.8.3" | |
| 846 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 847 | +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" | |
| 848 | + | |
| 849 | +[[package]] | |
| 605 | 850 | name = "lock_api" |
| 606 | 851 | version = "0.4.14" |
| 607 | 852 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -656,6 +901,29 @@ dependencies = [
| 656 | 901 | ] |
| 657 | 902 | |
| 658 | 903 | [[package]] |
| 904 | +name = "multer" | |
| 905 | +version = "3.1.0" | |
| 906 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 907 | +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" | |
| 908 | +dependencies = [ | |
| 909 | + "bytes", | |
| 910 | + "encoding_rs", | |
| 911 | + "futures-util", | |
| 912 | + "http", | |
| 913 | + "httparse", | |
| 914 | + "memchr", | |
| 915 | + "mime", | |
| 916 | + "spin", | |
| 917 | + "version_check", | |
| 918 | +] | |
| 919 | + | |
| 920 | +[[package]] | |
| 921 | +name = "multiversion_no_op" | |
| 922 | +version = "1.0.0" | |
| 923 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 924 | +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" | |
| 925 | + | |
| 926 | +[[package]] | |
| 659 | 927 | name = "nu-ansi-term" |
| 660 | 928 | version = "0.50.3" |
| 661 | 929 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -689,14 +957,19 @@ dependencies = [
| 689 | 957 | "askama", |
| 690 | 958 | "axum", |
| 691 | 959 | "clap", |
| 960 | + "form_urlencoded", | |
| 692 | 961 | "http-body-util", |
| 962 | + "idna", | |
| 963 | + "jiff", | |
| 693 | 964 | "rand 0.10.3", |
| 694 | 965 | "rust-embed", |
| 695 | 966 | "serde", |
| 696 | 967 | "serde_json", |
| 697 | 968 | "serde_norway", |
| 969 | + "tempfile", | |
| 698 | 970 | "thiserror", |
| 699 | 971 | "tokio", |
| 972 | + "tokio-stream", | |
| 700 | 973 | "tower", |
| 701 | 974 | "tower-http", |
| 702 | 975 | "tower-sessions", |
@@ -740,6 +1013,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 740 | 1013 | checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" |
| 741 | 1014 | |
| 742 | 1015 | [[package]] |
| 1016 | +name = "portable-atomic" | |
| 1017 | +version = "1.15.0" | |
| 1018 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1019 | +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" | |
| 1020 | + | |
| 1021 | +[[package]] | |
| 1022 | +name = "portable-atomic-util" | |
| 1023 | +version = "0.2.8" | |
| 1024 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1025 | +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" | |
| 1026 | +dependencies = [ | |
| 1027 | + "portable-atomic", | |
| 1028 | +] | |
| 1029 | + | |
| 1030 | +[[package]] | |
| 1031 | +name = "potential_utf" | |
| 1032 | +version = "0.1.6" | |
| 1033 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1034 | +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" | |
| 1035 | +dependencies = [ | |
| 1036 | + "zerovec", | |
| 1037 | +] | |
| 1038 | + | |
| 1039 | +[[package]] | |
| 743 | 1040 | name = "powerfmt" |
| 744 | 1041 | version = "0.2.1" |
| 745 | 1042 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -836,7 +1133,7 @@ version = "0.5.18"
| 836 | 1133 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 837 | 1134 | checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" |
| 838 | 1135 | dependencies = [ |
| 839 | - "bitflags", | |
| 1136 | + "bitflags 2.13.2", | |
| 840 | 1137 | ] |
| 841 | 1138 | |
| 842 | 1139 | [[package]] |
@@ -900,6 +1197,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 900 | 1197 | checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" |
| 901 | 1198 | |
| 902 | 1199 | [[package]] |
| 1200 | +name = "rustix" | |
| 1201 | +version = "1.1.6" | |
| 1202 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1203 | +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" | |
| 1204 | +dependencies = [ | |
| 1205 | + "bitflags 2.13.2", | |
| 1206 | + "errno", | |
| 1207 | + "libc", | |
| 1208 | + "linux-raw-sys", | |
| 1209 | + "windows-sys", | |
| 1210 | +] | |
| 1211 | + | |
| 1212 | +[[package]] | |
| 1213 | +name = "rustversion" | |
| 1214 | +version = "1.0.23" | |
| 1215 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1216 | +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" | |
| 1217 | + | |
| 1218 | +[[package]] | |
| 903 | 1219 | name = "ryu" |
| 904 | 1220 | version = "1.0.23" |
| 905 | 1221 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1030,6 +1346,12 @@ dependencies = [
| 1030 | 1346 | ] |
| 1031 | 1347 | |
| 1032 | 1348 | [[package]] |
| 1349 | +name = "simdutf8" | |
| 1350 | +version = "0.1.5" | |
| 1351 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1352 | +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" | |
| 1353 | + | |
| 1354 | +[[package]] | |
| 1033 | 1355 | name = "slab" |
| 1034 | 1356 | version = "0.4.12" |
| 1035 | 1357 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1052,6 +1374,18 @@ dependencies = [
| 1052 | 1374 | ] |
| 1053 | 1375 | |
| 1054 | 1376 | [[package]] |
| 1377 | +name = "spin" | |
| 1378 | +version = "0.9.9" | |
| 1379 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1380 | +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" | |
| 1381 | + | |
| 1382 | +[[package]] | |
| 1383 | +name = "stable_deref_trait" | |
| 1384 | +version = "1.2.1" | |
| 1385 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1386 | +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" | |
| 1387 | + | |
| 1388 | +[[package]] | |
| 1055 | 1389 | name = "strsim" |
| 1056 | 1390 | version = "0.11.1" |
| 1057 | 1391 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1086,6 +1420,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 1086 | 1420 | checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" |
| 1087 | 1421 | |
| 1088 | 1422 | [[package]] |
| 1423 | +name = "synstructure" | |
| 1424 | +version = "0.14.0" | |
| 1425 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1426 | +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" | |
| 1427 | +dependencies = [ | |
| 1428 | + "proc-macro2", | |
| 1429 | + "quote", | |
| 1430 | + "syn 3.0.9", | |
| 1431 | +] | |
| 1432 | + | |
| 1433 | +[[package]] | |
| 1434 | +name = "tempfile" | |
| 1435 | +version = "3.27.0" | |
| 1436 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1437 | +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" | |
| 1438 | +dependencies = [ | |
| 1439 | + "fastrand", | |
| 1440 | + "getrandom 0.4.3", | |
| 1441 | + "once_cell", | |
| 1442 | + "rustix", | |
| 1443 | + "windows-sys", | |
| 1444 | +] | |
| 1445 | + | |
| 1446 | +[[package]] | |
| 1089 | 1447 | name = "thiserror" |
| 1090 | 1448 | version = "2.0.21" |
| 1091 | 1449 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1145,11 +1503,22 @@ dependencies = [
| 1145 | 1503 | ] |
| 1146 | 1504 | |
| 1147 | 1505 | [[package]] |
| 1506 | +name = "tinystr" | |
| 1507 | +version = "0.8.5" | |
| 1508 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1509 | +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" | |
| 1510 | +dependencies = [ | |
| 1511 | + "displaydoc", | |
| 1512 | + "zerovec", | |
| 1513 | +] | |
| 1514 | + | |
| 1515 | +[[package]] | |
| 1148 | 1516 | name = "tokio" |
| 1149 | 1517 | version = "1.54.1" |
| 1150 | 1518 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1151 | 1519 | checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" |
| 1152 | 1520 | dependencies = [ |
| 1521 | + "bytes", | |
| 1153 | 1522 | "libc", |
| 1154 | 1523 | "mio", |
| 1155 | 1524 | "pin-project-lite", |
@@ -1171,6 +1540,31 @@ dependencies = [
| 1171 | 1540 | ] |
| 1172 | 1541 | |
| 1173 | 1542 | [[package]] |
| 1543 | +name = "tokio-stream" | |
| 1544 | +version = "0.1.19" | |
| 1545 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1546 | +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" | |
| 1547 | +dependencies = [ | |
| 1548 | + "futures-core", | |
| 1549 | + "pin-project-lite", | |
| 1550 | + "tokio", | |
| 1551 | + "tokio-util", | |
| 1552 | +] | |
| 1553 | + | |
| 1554 | +[[package]] | |
| 1555 | +name = "tokio-util" | |
| 1556 | +version = "0.7.20" | |
| 1557 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1558 | +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" | |
| 1559 | +dependencies = [ | |
| 1560 | + "bytes", | |
| 1561 | + "futures-core", | |
| 1562 | + "futures-sink", | |
| 1563 | + "pin-project-lite", | |
| 1564 | + "tokio", | |
| 1565 | +] | |
| 1566 | + | |
| 1567 | +[[package]] | |
| 1174 | 1568 | name = "tower" |
| 1175 | 1569 | version = "0.5.3" |
| 1176 | 1570 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1208,7 +1602,7 @@ version = "0.7.1"
| 1208 | 1602 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1209 | 1603 | checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" |
| 1210 | 1604 | dependencies = [ |
| 1211 | - "bitflags", | |
| 1605 | + "bitflags 2.13.2", | |
| 1212 | 1606 | "bytes", |
| 1213 | 1607 | "http", |
| 1214 | 1608 | "http-body", |
@@ -1365,12 +1759,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 1365 | 1759 | checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104" |
| 1366 | 1760 | |
| 1367 | 1761 | [[package]] |
| 1762 | +name = "utf8_iter" | |
| 1763 | +version = "1.1.0" | |
| 1764 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1765 | +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" | |
| 1766 | +dependencies = [ | |
| 1767 | + "utf_types", | |
| 1768 | +] | |
| 1769 | + | |
| 1770 | +[[package]] | |
| 1368 | 1771 | name = "utf8parse" |
| 1369 | 1772 | version = "0.2.2" |
| 1370 | 1773 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1371 | 1774 | checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" |
| 1372 | 1775 | |
| 1373 | 1776 | [[package]] |
| 1777 | +name = "utf_types" | |
| 1778 | +version = "1.0.0" | |
| 1779 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1780 | +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" | |
| 1781 | + | |
| 1782 | +[[package]] | |
| 1374 | 1783 | name = "valuable" |
| 1375 | 1784 | version = "0.1.1" |
| 1376 | 1785 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1447,6 +1856,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
| 1447 | 1856 | checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" |
| 1448 | 1857 | |
| 1449 | 1858 | [[package]] |
| 1859 | +name = "writeable" | |
| 1860 | +version = "0.6.4" | |
| 1861 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1862 | +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" | |
| 1863 | + | |
| 1864 | +[[package]] | |
| 1865 | +name = "yoke" | |
| 1866 | +version = "0.8.4" | |
| 1867 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1868 | +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" | |
| 1869 | +dependencies = [ | |
| 1870 | + "stable_deref_trait", | |
| 1871 | + "yoke-derive", | |
| 1872 | + "zerofrom", | |
| 1873 | +] | |
| 1874 | + | |
| 1875 | +[[package]] | |
| 1876 | +name = "yoke-derive" | |
| 1877 | +version = "0.8.4" | |
| 1878 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1879 | +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" | |
| 1880 | +dependencies = [ | |
| 1881 | + "proc-macro2", | |
| 1882 | + "quote", | |
| 1883 | + "syn 3.0.9", | |
| 1884 | + "synstructure", | |
| 1885 | +] | |
| 1886 | + | |
| 1887 | +[[package]] | |
| 1450 | 1888 | name = "zerocopy" |
| 1451 | 1889 | version = "0.8.63" |
| 1452 | 1890 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -1467,6 +1905,60 @@ dependencies = [
| 1467 | 1905 | ] |
| 1468 | 1906 | |
| 1469 | 1907 | [[package]] |
| 1908 | +name = "zerofrom" | |
| 1909 | +version = "0.1.8" | |
| 1910 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1911 | +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" | |
| 1912 | +dependencies = [ | |
| 1913 | + "zerofrom-derive", | |
| 1914 | +] | |
| 1915 | + | |
| 1916 | +[[package]] | |
| 1917 | +name = "zerofrom-derive" | |
| 1918 | +version = "0.1.8" | |
| 1919 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1920 | +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" | |
| 1921 | +dependencies = [ | |
| 1922 | + "proc-macro2", | |
| 1923 | + "quote", | |
| 1924 | + "syn 3.0.9", | |
| 1925 | + "synstructure", | |
| 1926 | +] | |
| 1927 | + | |
| 1928 | +[[package]] | |
| 1929 | +name = "zerotrie" | |
| 1930 | +version = "0.2.5" | |
| 1931 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1932 | +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" | |
| 1933 | +dependencies = [ | |
| 1934 | + "displaydoc", | |
| 1935 | + "yoke", | |
| 1936 | + "zerofrom", | |
| 1937 | +] | |
| 1938 | + | |
| 1939 | +[[package]] | |
| 1940 | +name = "zerovec" | |
| 1941 | +version = "0.11.9" | |
| 1942 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1943 | +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" | |
| 1944 | +dependencies = [ | |
| 1945 | + "yoke", | |
| 1946 | + "zerofrom", | |
| 1947 | + "zerovec-derive", | |
| 1948 | +] | |
| 1949 | + | |
| 1950 | +[[package]] | |
| 1951 | +name = "zerovec-derive" | |
| 1952 | +version = "0.11.7" | |
| 1953 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1954 | +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" | |
| 1955 | +dependencies = [ | |
| 1956 | + "proc-macro2", | |
| 1957 | + "quote", | |
| 1958 | + "syn 3.0.9", | |
| 1959 | +] | |
| 1960 | + | |
| 1961 | +[[package]] | |
| 1470 | 1962 | name = "zmij" |
| 1471 | 1963 | version = "1.0.23" |
| 1472 | 1964 | source = "registry+https://github.com/rust-lang/crates.io-index" |
A
ansible/.ansible-lint
+9
-0
@@ -0,0 +1,9 @@
| 1 | +--- | |
| 2 | +# Configuration ansible-lint d'Open IAM. | |
| 3 | +kinds: | |
| 4 | + - inventory: "**/inventory.yml" | |
| 5 | + - inventory: "inventories/**/*.yml" | |
| 6 | +skip_list: | |
| 7 | + # Les variables partagées entre rôles portent le préfixe de projet `oiam_` (contrat avec | |
| 8 | + # l'installeur : config::ansible), pas un préfixe par rôle. | |
| 9 | + - var-naming[no-role-prefix] |
A
ansible/ansible.cfg
+12
-0
@@ -0,0 +1,12 @@
| 1 | +[defaults] | |
| 2 | +nocows = true | |
| 3 | +roles_path = roles | |
| 4 | +inventory = inventories/dev/hosts.yml | |
| 5 | +stdout_callback = default | |
| 6 | +callback_result_format = yaml | |
| 7 | +retry_files_enabled = false | |
| 8 | +interpreter_python = auto_silent | |
| 9 | +any_errors_fatal = true | |
| 10 | + | |
| 11 | +[ssh_connection] | |
| 12 | +pipelining = true |
A
ansible/callback_plugins/__pycache__/open_iam.cpython-312.pyc
+0
-0
A
ansible/callback_plugins/__pycache__/open_iam.cpython-313.pyc
+0
-0
A
ansible/callback_plugins/open_iam.py
+67
-0
@@ -0,0 +1,67 @@
| 1 | +# Callback de sortie Open IAM : un événement JSON par ligne sur la sortie standard, lu par | |
| 2 | +# l'installeur (installer/src/runner.rs). Ne dépend que d'ansible-core. | |
| 3 | +# Les résultats des tâches `no_log` arrivent déjà masqués par Ansible. | |
| 4 | + | |
| 5 | +import json | |
| 6 | +import sys | |
| 7 | + | |
| 8 | +from ansible.plugins.callback import CallbackBase | |
| 9 | + | |
| 10 | +DOCUMENTATION = """ | |
| 11 | +name: open_iam | |
| 12 | +type: stdout | |
| 13 | +short_description: Événements JSON ligne à ligne pour l'installeur Open IAM | |
| 14 | +description: Écrit un objet JSON par ligne (début de play, tâche terminée, bilan). | |
| 15 | +""" | |
| 16 | + | |
| 17 | +TAILLE_MESSAGE = 2000 | |
| 18 | + | |
| 19 | + | |
| 20 | +class CallbackModule(CallbackBase): | |
| 21 | + CALLBACK_VERSION = 2.0 | |
| 22 | + CALLBACK_TYPE = "stdout" | |
| 23 | + CALLBACK_NAME = "open_iam" | |
| 24 | + | |
| 25 | + def _emettre(self, evenement): | |
| 26 | + sys.stdout.write(json.dumps(evenement, ensure_ascii=False) + "\n") | |
| 27 | + sys.stdout.flush() | |
| 28 | + | |
| 29 | + def v2_playbook_on_play_start(self, play): | |
| 30 | + taches = sum(len(bloc.get_tasks()) for bloc in play.compile()) | |
| 31 | + self._emettre({"type": "play", "nom": play.get_name(), "taches": taches}) | |
| 32 | + | |
| 33 | + def _resultat(self, resultat, statut): | |
| 34 | + tache = resultat._task | |
| 35 | + role = tache._role.get_name() if tache._role else "" | |
| 36 | + brut = resultat._result | |
| 37 | + message = "" | |
| 38 | + if statut in ("failed", "unreachable"): | |
| 39 | + message = str(brut.get("msg") or brut.get("stderr") or brut.get("stdout") or "") | |
| 40 | + self._emettre( | |
| 41 | + { | |
| 42 | + "type": "tache", | |
| 43 | + "hote": resultat._host.get_name(), | |
| 44 | + "role": role, | |
| 45 | + "nom": tache.get_name(), | |
| 46 | + "statut": statut, | |
| 47 | + "message": message[:TAILLE_MESSAGE], | |
| 48 | + } | |
| 49 | + ) | |
| 50 | + | |
| 51 | + def v2_runner_on_ok(self, resultat): | |
| 52 | + self._resultat(resultat, "changed" if resultat._result.get("changed") else "ok") | |
| 53 | + | |
| 54 | + def v2_runner_on_failed(self, resultat, ignore_errors=False): | |
| 55 | + self._resultat(resultat, "ignored" if ignore_errors else "failed") | |
| 56 | + | |
| 57 | + def v2_runner_on_skipped(self, resultat): | |
| 58 | + self._resultat(resultat, "skipped") | |
| 59 | + | |
| 60 | + def v2_runner_on_unreachable(self, resultat): | |
| 61 | + self._resultat(resultat, "unreachable") | |
| 62 | + | |
| 63 | + def v2_playbook_on_stats(self, stats): | |
| 64 | + hotes = {} | |
| 65 | + for hote in sorted(stats.processed.keys()): | |
| 66 | + hotes[hote] = stats.summarize(hote) | |
| 67 | + self._emettre({"type": "bilan", "hotes": hotes}) |
A
ansible/inventories/dev/group_vars/all.yml
+33
-0
@@ -0,0 +1,33 @@
| 1 | +--- | |
| 2 | +# Variables de développement, équivalentes à ce que produit l'installeur (config::ansible). | |
| 3 | +# Mots de passe de test uniquement : ces cibles ne sont jamais exposées (D-018). | |
| 4 | +oiam_organisation: Mairie d'Exemple | |
| 5 | +oiam_domaine: exemple.fr | |
| 6 | +oiam_base_dn: dc=exemple,dc=fr | |
| 7 | +oiam_langue: fr | |
| 8 | +oiam_fuseau: Europe/Paris | |
| 9 | +oiam_mode: native | |
| 10 | +oiam_composants: [openldap, sauvegarde] | |
| 11 | +oiam_services: | |
| 12 | + annuaire: annuaire.exemple.fr | |
| 13 | +oiam_tls_mode: interne | |
| 14 | +oiam_acme_email: null | |
| 15 | +oiam_mdp: | |
| 16 | + longueur_min: 12 | |
| 17 | + classes_min: 3 | |
| 18 | + historique: 5 | |
| 19 | + expiration_jours: 0 | |
| 20 | + echecs_max: 5 | |
| 21 | + verrouillage_minutes: 15 | |
| 22 | +oiam_mfa: { exigence: tous, admins: true } | |
| 23 | +oiam_smtp: null | |
| 24 | +oiam_admin_initial: | |
| 25 | + uid: jean.dupont | |
| 26 | + prenom: Jean | |
| 27 | + nom: Dupont | |
| 28 | + email: jean.dupont@exemple.fr | |
| 29 | + mode_mdp: saisir | |
| 30 | +oiam_supervision: { retention_metriques_jours: 30, retention_journaux_jours: 90 } | |
| 31 | +oiam_os_codenames: { debian: trixie, ubuntu: resolute } | |
| 32 | +oiam_ldap_admin_mot_de_passe: Urgence-Dev-2026! | |
| 33 | +oiam_admin_initial_mot_de_passe: Cheval-Batterie-42 |
A
ansible/molecule/socle/converge.yml
+14
-0
@@ -0,0 +1,14 @@
| 1 | +--- | |
| 2 | +# Garde contre un faux succès : sans hôte, chaque play serait « réussi » sans rien exécuter. | |
| 3 | +- name: Vérifier que les cibles sont dans l'inventaire | |
| 4 | + hosts: localhost | |
| 5 | + gather_facts: false | |
| 6 | + tasks: | |
| 7 | + - name: Les deux cibles doivent être présentes | |
| 8 | + ansible.builtin.assert: | |
| 9 | + that: groups['cibles'] | default([]) | length == 2 | |
| 10 | + fail_msg: "Cibles attendues : socle-debian et socle-ubuntu ; trouvées : {{ groups['cibles'] | default([]) }}" | |
| 11 | + quiet: true | |
| 12 | + | |
| 13 | +- name: Appliquer le socle | |
| 14 | + ansible.builtin.import_playbook: ../../site.yml |
A
ansible/molecule/socle/create.yml
+8
-0
@@ -0,0 +1,8 @@
| 1 | +--- | |
| 2 | +- name: Créer les cibles vierges | |
| 3 | + hosts: localhost | |
| 4 | + gather_facts: false | |
| 5 | + tasks: | |
| 6 | + - name: Démarrer les conteneurs Debian 13 et Ubuntu 26.04 | |
| 7 | + ansible.builtin.command: "{{ playbook_dir }}/../../../scripts/cible.sh demarrer toutes" | |
| 8 | + changed_when: true |
A
ansible/molecule/socle/destroy.yml
+8
-0
@@ -0,0 +1,8 @@
| 1 | +--- | |
| 2 | +- name: Supprimer les cibles | |
| 3 | + hosts: localhost | |
| 4 | + gather_facts: false | |
| 5 | + tasks: | |
| 6 | + - name: Supprimer les conteneurs | |
| 7 | + ansible.builtin.command: "{{ playbook_dir }}/../../../scripts/cible.sh arreter toutes" | |
| 8 | + changed_when: true |
A
ansible/molecule/socle/group_vars/all.yml
+1
-0
@@ -0,0 +1 @@
| 1 | +../../../inventories/dev/group_vars/all.yml | |
| 1 | < \ No newline at end of file |
A
ansible/molecule/socle/inventory.yml
+15
-0
@@ -0,0 +1,15 @@
| 1 | +--- | |
| 2 | +all: | |
| 3 | + children: | |
| 4 | + cibles: | |
| 5 | + vars: | |
| 6 | + ansible_user: root | |
| 7 | + ansible_host: 127.0.0.1 | |
| 8 | + ansible_ssh_private_key_file: "{{ inventory_dir }}/../../../tests/cible/.ssh/id_ed25519" | |
| 9 | + ansible_ssh_common_args: "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" | |
| 10 | + ansible_python_interpreter: /usr/bin/python3 | |
| 11 | + hosts: | |
| 12 | + socle-debian: | |
| 13 | + ansible_port: 2232 | |
| 14 | + socle-ubuntu: | |
| 15 | + ansible_port: 2233 |
A
ansible/molecule/socle/molecule.yml
+35
-0
@@ -0,0 +1,35 @@
| 1 | +--- | |
| 2 | +# Scénario « socle » : site.yml complet sur Debian 13 et Ubuntu 26.04 (cibles conteneur, D-018). | |
| 3 | +# Lancement depuis ansible/ : ../.venv/bin/molecule test -s socle | |
| 4 | +ansible: | |
| 5 | + cfg: | |
| 6 | + defaults: | |
| 7 | + host_key_checking: false | |
| 8 | + nocows: true | |
| 9 | + roles_path: roles | |
| 10 | + callback_result_format: yaml | |
| 11 | + ssh_connection: | |
| 12 | + pipelining: true | |
| 13 | + env: | |
| 14 | + OIAM_CIBLE_PREFIXE: molecule-socle | |
| 15 | + OIAM_CIBLE_PORT: "2232" | |
| 16 | + executor: | |
| 17 | + backend: ansible-playbook | |
| 18 | + args: | |
| 19 | + ansible_playbook: | |
| 20 | + - --inventory=${MOLECULE_SCENARIO_DIRECTORY}/inventory.yml | |
| 21 | + playbooks: | |
| 22 | + create: create.yml | |
| 23 | + converge: converge.yml | |
| 24 | + destroy: destroy.yml | |
| 25 | + verify: verify.yml | |
| 26 | +scenario: | |
| 27 | + name: socle | |
| 28 | + test_sequence: | |
| 29 | + - destroy | |
| 30 | + - syntax | |
| 31 | + - create | |
| 32 | + - converge | |
| 33 | + - idempotence | |
| 34 | + - verify | |
| 35 | + - destroy |
A
ansible/molecule/socle/verify.yml
+99
-0
@@ -0,0 +1,99 @@
| 1 | +--- | |
| 2 | +# Garde contre un faux succès : sans hôte, chaque play serait « réussi » sans rien exécuter. | |
| 3 | +- name: Vérifier que les cibles sont dans l'inventaire | |
| 4 | + hosts: localhost | |
| 5 | + gather_facts: false | |
| 6 | + tasks: | |
| 7 | + - name: Les deux cibles doivent être présentes | |
| 8 | + ansible.builtin.assert: | |
| 9 | + that: groups['cibles'] | default([]) | length == 2 | |
| 10 | + fail_msg: "Cibles attendues : socle-debian et socle-ubuntu ; trouvées : {{ groups['cibles'] | default([]) }}" | |
| 11 | + quiet: true | |
| 12 | + | |
| 13 | +# Recette fonctionnelle du socle (OI-032 à OI-035). Les contrôles s'exécutent sur la cible. | |
| 14 | +- name: Vérifier le socle | |
| 15 | + hosts: all | |
| 16 | + gather_facts: false | |
| 17 | + vars: | |
| 18 | + bin: /usr/local/openldap/bin | |
| 19 | + ldaps: "ldaps://{{ oiam_services.annuaire }}" | |
| 20 | + ldapi: ldapi://%2Fvar%2Frun%2Fslapd%2Fldapi | |
| 21 | + admin_dn: "uid={{ oiam_admin_initial.uid }},ou=users,{{ oiam_base_dn }}" | |
| 22 | + essai_dn: "uid=essai-molecule,ou=users,{{ oiam_base_dn }}" | |
| 23 | + tasks: | |
| 24 | + - name: Bind en TLS avec le premier administrateur | |
| 25 | + ansible.builtin.command: "{{ bin }}/ldapwhoami -x -H {{ ldaps }} -D {{ admin_dn }} -w {{ oiam_admin_initial_mot_de_passe }}" | |
| 26 | + register: r | |
| 27 | + changed_when: false | |
| 28 | + failed_when: r.rc != 0 or ('dn:' + admin_dn) not in r.stdout | |
| 29 | + no_log: true | |
| 30 | + | |
| 31 | + - name: Le bind anonyme est refusé | |
| 32 | + ansible.builtin.command: "{{ bin }}/ldapwhoami -x -H {{ ldaps }}" | |
| 33 | + register: r | |
| 34 | + changed_when: false | |
| 35 | + failed_when: r.rc == 0 or 'anonymous bind disallowed' not in r.stderr | |
| 36 | + | |
| 37 | + - name: Le bind simple sans TLS est refusé | |
| 38 | + ansible.builtin.command: "{{ bin }}/ldapwhoami -x -H ldap://{{ oiam_services.annuaire }} -D {{ admin_dn }} -w {{ oiam_admin_initial_mot_de_passe }}" | |
| 39 | + register: r | |
| 40 | + changed_when: false | |
| 41 | + failed_when: r.rc != 13 | |
| 42 | + no_log: true | |
| 43 | + | |
| 44 | + - name: L'attribut memberOf est calculé | |
| 45 | + ansible.builtin.command: "{{ bin }}/ldapsearch -LLL -Q -Y EXTERNAL -H {{ ldapi }} -b {{ admin_dn }} memberOf" | |
| 46 | + register: r | |
| 47 | + changed_when: false | |
| 48 | + failed_when: "('memberOf: cn=openiam-admins,ou=groups,' + oiam_base_dn) not in r.stdout" | |
| 49 | + | |
| 50 | + - name: Créer un utilisateur d'essai | |
| 51 | + ansible.builtin.command: | |
| 52 | + cmd: "{{ bin }}/ldapadd -Q -Y EXTERNAL -H {{ ldapi }}" | |
| 53 | + stdin: | | |
| 54 | + dn: {{ essai_dn }} | |
| 55 | + objectClass: inetOrgPerson | |
| 56 | + uid: essai-molecule | |
| 57 | + cn: Essai | |
| 58 | + sn: Essai | |
| 59 | + userPassword: Correct-Cheval-42 | |
| 60 | + changed_when: true | |
| 61 | + | |
| 62 | + - name: Un mot de passe trop faible est refusé (ppm) | |
| 63 | + ansible.builtin.command: "{{ bin }}/ldappasswd -x -H {{ ldaps }} -D {{ essai_dn }} -w Correct-Cheval-42 -a Correct-Cheval-42 -s abcdefghijkl" | |
| 64 | + register: r | |
| 65 | + changed_when: false | |
| 66 | + # ldappasswd sort en 1 et écrit le résultat LDAP sur la sortie standard. | |
| 67 | + failed_when: r.rc == 0 or 'Constraint violation (19)' not in r.stdout | |
| 68 | + | |
| 69 | + - name: Provoquer autant d'échecs de connexion que la politique en tolère | |
| 70 | + ansible.builtin.command: "{{ bin }}/ldapwhoami -x -H {{ ldaps }} -D {{ essai_dn }} -w mauvais" | |
| 71 | + loop: "{{ range(oiam_mdp.echecs_max) | list }}" | |
| 72 | + register: r | |
| 73 | + changed_when: false | |
| 74 | + failed_when: r.rc != 49 | |
| 75 | + | |
| 76 | + - name: Le compte est alors verrouillé | |
| 77 | + ansible.builtin.command: "{{ bin }}/ldapwhoami -x -e ppolicy -H {{ ldaps }} -D {{ essai_dn }} -w Correct-Cheval-42" | |
| 78 | + register: r | |
| 79 | + changed_when: false | |
| 80 | + failed_when: r.rc != 49 or 'Account locked' not in r.stderr | |
| 81 | + | |
| 82 | + - name: Seuls SSH et les ports de l'annuaire sont ouverts | |
| 83 | + ansible.builtin.command: nft list table inet open_iam | |
| 84 | + register: r | |
| 85 | + changed_when: false | |
| 86 | + failed_when: >- | |
| 87 | + 'tcp dport 22 accept' not in r.stdout or 'tcp dport { 389, 636 } accept' not in r.stdout | |
| 88 | + or 'policy drop' not in r.stdout | |
| 89 | + | |
| 90 | + - name: Sauvegarder puis tester la restauration | |
| 91 | + ansible.builtin.shell: /usr/local/sbin/open-iam-sauvegarde && /usr/local/sbin/open-iam-test-restauration | |
| 92 | + register: r | |
| 93 | + changed_when: true | |
| 94 | + failed_when: r.rc != 0 or 'Test de restauration réussi' not in r.stdout | |
| 95 | + | |
| 96 | + - name: Les minuteries de sauvegarde sont actives | |
| 97 | + # Lecture seule de l'état : le module systemd_service ne sert qu'à le modifier. | |
| 98 | + ansible.builtin.command: systemctl is-active open-iam-sauvegarde.timer open-iam-test-restauration.timer # noqa: command-instead-of-module | |
| 99 | + changed_when: false |
A
ansible/roles/backup/defaults/main.yml
+6
-0
@@ -0,0 +1,6 @@
| 1 | +--- | |
| 2 | +oiam_sauvegarde_dossier: /var/backups/open-iam | |
| 3 | +oiam_sauvegarde_cle: /etc/open-iam/sauvegarde/age.key | |
| 4 | +oiam_sauvegarde_retention_jours: 30 | |
| 5 | +oiam_sauvegarde_heure: "02:30" | |
| 6 | +oiam_ldap_prefixe: /usr/local/openldap |
A
ansible/roles/backup/tasks/main.yml
+56
-0
@@ -0,0 +1,56 @@
| 1 | +--- | |
| 2 | +# Sauvegardes chiffrées (age) de la configuration et des données de l'annuaire. | |
| 3 | +# La clé privée est aussi remise à l'administrateur dans le fichier récapitulatif (D-013) : | |
| 4 | +# elle doit être conservée hors du serveur, sinon une sauvegarde volée avec lui est lisible. | |
| 5 | +- name: Installer age | |
| 6 | + ansible.builtin.apt: | |
| 7 | + name: age | |
| 8 | + state: present | |
| 9 | + | |
| 10 | +- name: Créer les répertoires de sauvegarde | |
| 11 | + ansible.builtin.file: | |
| 12 | + path: "{{ item }}" | |
| 13 | + state: directory | |
| 14 | + owner: root | |
| 15 | + group: root | |
| 16 | + mode: "0700" | |
| 17 | + loop: | |
| 18 | + - "{{ oiam_sauvegarde_cle | dirname }}" | |
| 19 | + - "{{ oiam_sauvegarde_dossier }}" | |
| 20 | + | |
| 21 | +- name: Générer la clé de chiffrement des sauvegardes | |
| 22 | + ansible.builtin.command: | |
| 23 | + cmd: age-keygen -o {{ oiam_sauvegarde_cle }} | |
| 24 | + creates: "{{ oiam_sauvegarde_cle }}" | |
| 25 | + | |
| 26 | +- name: Protéger la clé de chiffrement | |
| 27 | + ansible.builtin.file: | |
| 28 | + path: "{{ oiam_sauvegarde_cle }}" | |
| 29 | + mode: "0600" | |
| 30 | + | |
| 31 | +- name: Installer les scripts de sauvegarde et de test de restauration | |
| 32 | + ansible.builtin.template: | |
| 33 | + src: "{{ item }}.j2" | |
| 34 | + dest: "/usr/local/sbin/{{ item }}" | |
| 35 | + mode: "0750" | |
| 36 | + loop: [open-iam-sauvegarde, open-iam-test-restauration] | |
| 37 | + | |
| 38 | +- name: Installer les services et minuteries systemd | |
| 39 | + ansible.builtin.template: | |
| 40 | + src: "{{ item }}.j2" | |
| 41 | + dest: "/etc/systemd/system/{{ item }}" | |
| 42 | + mode: "0644" | |
| 43 | + loop: | |
| 44 | + - open-iam-sauvegarde.service | |
| 45 | + - open-iam-sauvegarde.timer | |
| 46 | + - open-iam-test-restauration.service | |
| 47 | + - open-iam-test-restauration.timer | |
| 48 | + register: oiam_sauvegarde_unites | |
| 49 | + | |
| 50 | +- name: Activer les minuteries | |
| 51 | + ansible.builtin.systemd_service: | |
| 52 | + name: "{{ item }}" | |
| 53 | + enabled: true | |
| 54 | + state: started | |
| 55 | + daemon_reload: "{{ oiam_sauvegarde_unites is changed }}" | |
| 56 | + loop: [open-iam-sauvegarde.timer, open-iam-test-restauration.timer] |
A
ansible/roles/backup/templates/open-iam-sauvegarde.j2
+23
-0
@@ -0,0 +1,23 @@
| 1 | +#!/bin/bash | |
| 2 | +# {{ ansible_managed }} | |
| 3 | +# Sauvegarde chiffrée de l'annuaire : configuration (cn=config) et données ({{ oiam_base_dn }}). | |
| 4 | +set -euo pipefail | |
| 5 | +umask 077 | |
| 6 | +dossier={{ oiam_sauvegarde_dossier }} | |
| 7 | +destinataire="$(age-keygen -y {{ oiam_sauvegarde_cle }})" | |
| 8 | +horodatage="$(date +%Y%m%d-%H%M%S)" | |
| 9 | +slapcat={{ oiam_ldap_prefixe }}/sbin/slapcat | |
| 10 | + | |
| 11 | +sauver() { # $1 : nom, puis arguments de slapcat | |
| 12 | + local nom="$1"; shift | |
| 13 | + local cible="$dossier/$horodatage-$nom.ldif.gz.age" | |
| 14 | + "$slapcat" -o ldif-wrap=no "$@" | gzip -9 | age -r "$destinataire" -o "$cible.partiel" | |
| 15 | + mv "$cible.partiel" "$cible" | |
| 16 | +} | |
| 17 | + | |
| 18 | +sauver config -n0 | |
| 19 | +sauver donnees -b "{{ oiam_base_dn }}" | |
| 20 | + | |
| 21 | +# Rotation : seuls les fichiers de sauvegarde Open IAM de ce dossier sont concernés. | |
| 22 | +find "$dossier" -maxdepth 1 -type f -name '*.ldif.gz.age' -mtime +{{ oiam_sauvegarde_retention_jours }} -delete | |
| 23 | +echo "Sauvegarde $horodatage terminée." |
A
ansible/roles/backup/templates/open-iam-sauvegarde.service.j2
+8
-0
@@ -0,0 +1,8 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +[Unit] | |
| 3 | +Description=Sauvegarde chiffrée de l'annuaire Open IAM | |
| 4 | +After=slapd-ltb.service | |
| 5 | + | |
| 6 | +[Service] | |
| 7 | +Type=oneshot | |
| 8 | +ExecStart=/usr/local/sbin/open-iam-sauvegarde |
A
ansible/roles/backup/templates/open-iam-sauvegarde.timer.j2
+11
-0
@@ -0,0 +1,11 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +[Unit] | |
| 3 | +Description=Sauvegarde quotidienne de l'annuaire Open IAM | |
| 4 | + | |
| 5 | +[Timer] | |
| 6 | +OnCalendar=*-*-* {{ oiam_sauvegarde_heure }} | |
| 7 | +Persistent=true | |
| 8 | +RandomizedDelaySec=10min | |
| 9 | + | |
| 10 | +[Install] | |
| 11 | +WantedBy=timers.target |
A
ansible/roles/backup/templates/open-iam-test-restauration.j2
+34
-0
@@ -0,0 +1,34 @@
| 1 | +#!/bin/bash | |
| 2 | +# {{ ansible_managed }} | |
| 3 | +# Vérifie que la dernière sauvegarde se restaure : déchiffrement, rechargement de la | |
| 4 | +# configuration dans un répertoire temporaire, chargement des données à blanc (slapadd -u), | |
| 5 | +# puis comparaison du nombre d'entrées avec l'annuaire en service. | |
| 6 | +set -euo pipefail | |
| 7 | +umask 077 | |
| 8 | +dossier={{ oiam_sauvegarde_dossier }} | |
| 9 | +prefixe={{ oiam_ldap_prefixe }} | |
| 10 | +travail="$(mktemp -d)" | |
| 11 | +trap 'find "$travail" -mindepth 1 -delete; rmdir "$travail"' EXIT | |
| 12 | + | |
| 13 | +derniere() { find "$dossier" -maxdepth 1 -name "*-$1.ldif.gz.age" | sort | tail -n 1; } | |
| 14 | +config="$(derniere config)" | |
| 15 | +donnees="$(derniere donnees)" | |
| 16 | +[[ -n "$config" && -n "$donnees" ]] || { echo "Aucune sauvegarde à tester." >&2; exit 1; } | |
| 17 | + | |
| 18 | +dechiffrer() { age -d -i {{ oiam_sauvegarde_cle }} "$1" | gunzip; } | |
| 19 | +dechiffrer "$config" > "$travail/config.ldif" | |
| 20 | +dechiffrer "$donnees" > "$travail/donnees.ldif" | |
| 21 | + | |
| 22 | +# Les chemins de données de la sauvegarde pointent vers l'annuaire en service : on les détourne. | |
| 23 | +mkdir -p "$travail/slapd.d" "$travail/donnees" "$travail/accesslog" | |
| 24 | +sed -e "s#^olcDbDirectory: .*openldap-data#olcDbDirectory: $travail/donnees#" \ | |
| 25 | + -e "s#^olcDbDirectory: .*accesslog-data#olcDbDirectory: $travail/accesslog#" \ | |
| 26 | + "$travail/config.ldif" > "$travail/config-test.ldif" | |
| 27 | +"$prefixe/sbin/slapadd" -n0 -F "$travail/slapd.d" -l "$travail/config-test.ldif" | |
| 28 | +"$prefixe/sbin/slapadd" -u -F "$travail/slapd.d" -b "{{ oiam_base_dn }}" -l "$travail/donnees.ldif" | |
| 29 | + | |
| 30 | +sauvegardees="$(grep -c '^dn: ' "$travail/donnees.ldif")" | |
| 31 | +en_service="$("$prefixe/sbin/slapcat" -o ldif-wrap=no -b "{{ oiam_base_dn }}" | grep -c '^dn: ')" | |
| 32 | +echo "Sauvegarde $(basename "$donnees") : $sauvegardees entrées (annuaire en service : $en_service)." | |
| 33 | +[[ "$sauvegardees" -gt 0 ]] | |
| 34 | +echo "Test de restauration réussi." |
A
ansible/roles/backup/templates/open-iam-test-restauration.service.j2
+7
-0
@@ -0,0 +1,7 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +[Unit] | |
| 3 | +Description=Test de restauration de la dernière sauvegarde Open IAM | |
| 4 | + | |
| 5 | +[Service] | |
| 6 | +Type=oneshot | |
| 7 | +ExecStart=/usr/local/sbin/open-iam-test-restauration |
A
ansible/roles/backup/templates/open-iam-test-restauration.timer.j2
+10
-0
@@ -0,0 +1,10 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +[Unit] | |
| 3 | +Description=Test hebdomadaire de restauration des sauvegardes Open IAM | |
| 4 | + | |
| 5 | +[Timer] | |
| 6 | +OnCalendar=Sun *-*-* 04:00 | |
| 7 | +Persistent=true | |
| 8 | + | |
| 9 | +[Install] | |
| 10 | +WantedBy=timers.target |
A
ansible/roles/common/defaults/main.yml
+5
-0
@@ -0,0 +1,5 @@
| 1 | +--- | |
| 2 | +oiam_etc: /etc/open-iam | |
| 3 | +# Types de virtualisation pour lesquels on ne touche ni à l'horloge ni au noyau : | |
| 4 | +# le noyau est partagé avec l'hôte (D-018, R-07). | |
| 5 | +oiam_types_conteneur: [docker, container, podman, lxc, containerd] |
A
ansible/roles/common/tasks/main.yml
+65
-0
@@ -0,0 +1,65 @@
| 1 | +--- | |
| 2 | +- name: Vérifier que la distribution est supportée | |
| 3 | + ansible.builtin.assert: | |
| 4 | + that: | |
| 5 | + - (ansible_distribution | lower) in oiam_os_codenames | |
| 6 | + - ansible_distribution_release == oiam_os_codenames[ansible_distribution | lower] | |
| 7 | + fail_msg: >- | |
| 8 | + {{ ansible_distribution }} {{ ansible_distribution_version }} ({{ ansible_distribution_release }}) | |
| 9 | + n'est pas supporté. Systèmes supportés : {{ oiam_os_codenames | dict2items | |
| 10 | + | map(attribute='key') | join(', ') }} ({{ oiam_os_codenames.values() | join(', ') }}). | |
| 11 | + quiet: true | |
| 12 | + | |
| 13 | +- name: Détecter une exécution en conteneur | |
| 14 | + ansible.builtin.set_fact: | |
| 15 | + oiam_conteneur: "{{ ansible_virtualization_role == 'guest' and ansible_virtualization_type in oiam_types_conteneur }}" | |
| 16 | + | |
| 17 | +- name: Installer les paquets de base | |
| 18 | + ansible.builtin.apt: | |
| 19 | + name: [ca-certificates, curl, gpg, openssl] | |
| 20 | + state: present | |
| 21 | + update_cache: true | |
| 22 | + cache_valid_time: 3600 | |
| 23 | + | |
| 24 | +- name: Régler le fuseau horaire | |
| 25 | + ansible.builtin.file: | |
| 26 | + src: "/usr/share/zoneinfo/{{ oiam_fuseau }}" | |
| 27 | + dest: /etc/localtime | |
| 28 | + state: link | |
| 29 | + force: true | |
| 30 | + | |
| 31 | +- name: Enregistrer le fuseau horaire | |
| 32 | + ansible.builtin.copy: | |
| 33 | + content: "{{ oiam_fuseau }}\n" | |
| 34 | + dest: /etc/timezone | |
| 35 | + mode: "0644" | |
| 36 | + | |
| 37 | +- name: Synchroniser l'horloge (machines réelles uniquement) | |
| 38 | + when: not oiam_conteneur | |
| 39 | + block: | |
| 40 | + - name: Installer systemd-timesyncd | |
| 41 | + ansible.builtin.apt: | |
| 42 | + name: systemd-timesyncd | |
| 43 | + state: present | |
| 44 | + - name: Activer la synchronisation de l'horloge | |
| 45 | + ansible.builtin.service: | |
| 46 | + name: systemd-timesyncd | |
| 47 | + enabled: true | |
| 48 | + state: started | |
| 49 | + | |
| 50 | +- name: Résoudre localement les noms des services hébergés ici | |
| 51 | + ansible.builtin.lineinfile: | |
| 52 | + path: /etc/hosts | |
| 53 | + regexp: '\s{{ item | regex_escape }}$' | |
| 54 | + line: "{{ ansible_default_ipv4.address | default('127.0.1.1') }} {{ item }}" | |
| 55 | + # /etc/hosts est monté par Docker dans les cibles de développement : pas de renommage possible. | |
| 56 | + unsafe_writes: "{{ oiam_conteneur }}" | |
| 57 | + loop: "{{ oiam_services.values() | list }}" | |
| 58 | + | |
| 59 | +- name: Créer le répertoire de configuration d'Open IAM | |
| 60 | + ansible.builtin.file: | |
| 61 | + path: "{{ oiam_etc }}" | |
| 62 | + state: directory | |
| 63 | + owner: root | |
| 64 | + group: root | |
| 65 | + mode: "0750" |
A
ansible/roles/hardening/defaults/main.yml
+7
-0
@@ -0,0 +1,7 @@
| 1 | +--- | |
| 2 | +oiam_port_ssh: 22 | |
| 3 | +# Ports ouverts dans le pare-feu, par composant installé. | |
| 4 | +oiam_ports_par_composant: | |
| 5 | + openldap: [389, 636] | |
| 6 | +oiam_ports_ouverts: >- | |
| 7 | + {{ oiam_composants | map('extract', oiam_ports_par_composant) | select('defined') | flatten | unique | sort }} |
A
ansible/roles/hardening/handlers/main.yml
+18
-0
@@ -0,0 +1,18 @@
| 1 | +--- | |
| 2 | +- name: Recharger le pare-feu | |
| 3 | + ansible.builtin.service: | |
| 4 | + name: nftables | |
| 5 | + state: reloaded | |
| 6 | + | |
| 7 | +- name: Recharger SSH | |
| 8 | + ansible.builtin.service: | |
| 9 | + name: ssh | |
| 10 | + state: reloaded | |
| 11 | + | |
| 12 | +- name: Appliquer les paramètres réseau | |
| 13 | + ansible.builtin.command: sysctl -p /etc/sysctl.d/90-open-iam-reseau.conf | |
| 14 | + changed_when: true | |
| 15 | + | |
| 16 | +- name: Appliquer les paramètres du noyau | |
| 17 | + ansible.builtin.command: sysctl -p /etc/sysctl.d/91-open-iam-noyau.conf | |
| 18 | + changed_when: true |
A
ansible/roles/hardening/tasks/main.yml
+87
-0
@@ -0,0 +1,87 @@
| 1 | +--- | |
| 2 | +- name: Installer le pare-feu et les mises à jour automatiques | |
| 3 | + ansible.builtin.apt: | |
| 4 | + name: [nftables, unattended-upgrades] | |
| 5 | + state: present | |
| 6 | + | |
| 7 | +# --- Pare-feu : refus par défaut en entrée, seuls SSH et les services installés sont ouverts. | |
| 8 | +- name: Configurer le pare-feu | |
| 9 | + ansible.builtin.template: | |
| 10 | + src: nftables.conf.j2 | |
| 11 | + dest: /etc/nftables.conf | |
| 12 | + mode: "0600" | |
| 13 | + validate: nft -c -f %s | |
| 14 | + notify: Recharger le pare-feu | |
| 15 | + | |
| 16 | +- name: Activer le pare-feu au démarrage | |
| 17 | + ansible.builtin.service: | |
| 18 | + name: nftables | |
| 19 | + enabled: true | |
| 20 | + state: started | |
| 21 | + | |
| 22 | +# --- Mises à jour de sécurité automatiques. | |
| 23 | +- name: Activer les mises à jour de sécurité automatiques | |
| 24 | + ansible.builtin.copy: | |
| 25 | + dest: /etc/apt/apt.conf.d/20auto-upgrades | |
| 26 | + mode: "0644" | |
| 27 | + content: | | |
| 28 | + // Géré par Open IAM : toute modification manuelle sera écrasée. | |
| 29 | + APT::Periodic::Update-Package-Lists "1"; | |
| 30 | + APT::Periodic::Unattended-Upgrade "1"; | |
| 31 | + | |
| 32 | +# --- SSH : authentification par clé seulement, si au moins une clé est en place. | |
| 33 | +- name: Rechercher les clés SSH autorisées | |
| 34 | + ansible.builtin.find: | |
| 35 | + paths: [/root/.ssh, /home] | |
| 36 | + patterns: authorized_keys | |
| 37 | + recurse: true | |
| 38 | + size: 1 | |
| 39 | + hidden: true | |
| 40 | + register: oiam_cles_ssh | |
| 41 | + | |
| 42 | +- name: Signaler que les mots de passe SSH restent autorisés | |
| 43 | + when: oiam_cles_ssh.matched == 0 | |
| 44 | + ansible.builtin.debug: | |
| 45 | + msg: >- | |
| 46 | + Aucune clé SSH autorisée n'est installée sur ce serveur : la connexion SSH par mot de passe | |
| 47 | + reste permise pour ne pas vous bloquer. Ajoutez une clé, puis relancez l'installation. | |
| 48 | + | |
| 49 | +- name: Durcir le serveur SSH | |
| 50 | + ansible.builtin.template: | |
| 51 | + src: sshd-open-iam.conf.j2 | |
| 52 | + dest: /etc/ssh/sshd_config.d/10-open-iam.conf | |
| 53 | + mode: "0644" | |
| 54 | + validate: sshd -t -f %s | |
| 55 | + notify: Recharger SSH | |
| 56 | + | |
| 57 | +# --- Paramètres réseau du noyau (propres à l'espace réseau : sans effet sur l'hôte d'un conteneur). | |
| 58 | +- name: Durcir la pile réseau | |
| 59 | + ansible.builtin.copy: | |
| 60 | + dest: /etc/sysctl.d/90-open-iam-reseau.conf | |
| 61 | + mode: "0644" | |
| 62 | + content: | | |
| 63 | + # Géré par Open IAM : toute modification manuelle sera écrasée. | |
| 64 | + net.ipv4.conf.all.accept_redirects = 0 | |
| 65 | + net.ipv4.conf.default.accept_redirects = 0 | |
| 66 | + net.ipv4.conf.all.send_redirects = 0 | |
| 67 | + net.ipv4.conf.all.accept_source_route = 0 | |
| 68 | + net.ipv4.conf.all.rp_filter = 1 | |
| 69 | + net.ipv4.conf.all.log_martians = 1 | |
| 70 | + net.ipv4.tcp_syncookies = 1 | |
| 71 | + net.ipv6.conf.all.accept_redirects = 0 | |
| 72 | + notify: Appliquer les paramètres réseau | |
| 73 | + | |
| 74 | +# --- Paramètres globaux du noyau : jamais dans un conteneur, ils modifieraient l'hôte. | |
| 75 | +- name: Durcir le noyau (machines réelles uniquement) | |
| 76 | + when: not oiam_conteneur | |
| 77 | + ansible.builtin.copy: | |
| 78 | + dest: /etc/sysctl.d/91-open-iam-noyau.conf | |
| 79 | + mode: "0644" | |
| 80 | + content: | | |
| 81 | + # Géré par Open IAM : toute modification manuelle sera écrasée. | |
| 82 | + kernel.kptr_restrict = 2 | |
| 83 | + kernel.dmesg_restrict = 1 | |
| 84 | + kernel.yama.ptrace_scope = 1 | |
| 85 | + fs.protected_symlinks = 1 | |
| 86 | + fs.protected_hardlinks = 1 | |
| 87 | + notify: Appliquer les paramètres du noyau |
A
ansible/roles/hardening/templates/nftables.conf.j2
+19
-0
@@ -0,0 +1,19 @@
| 1 | +#!/usr/sbin/nft -f | |
| 2 | +# {{ ansible_managed }} | |
| 3 | +# Seule la table open_iam est remplacée : les règles d'autres outils (Docker…) sont conservées. | |
| 4 | +table inet open_iam | |
| 5 | +delete table inet open_iam | |
| 6 | + | |
| 7 | +table inet open_iam { | |
| 8 | + chain entree { | |
| 9 | + type filter hook input priority filter; policy drop; | |
| 10 | + iif "lo" accept | |
| 11 | + ct state established,related accept | |
| 12 | + ct state invalid drop | |
| 13 | + meta l4proto { icmp, ipv6-icmp } accept | |
| 14 | + tcp dport {{ oiam_port_ssh }} accept comment "SSH" | |
| 15 | +{% if oiam_ports_ouverts | length > 0 %} | |
| 16 | + tcp dport { {{ oiam_ports_ouverts | join(', ') }} } accept comment "Services Open IAM" | |
| 17 | +{% endif %} | |
| 18 | + } | |
| 19 | +} |
A
ansible/roles/hardening/templates/sshd-open-iam.conf.j2
+9
-0
@@ -0,0 +1,9 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +PermitRootLogin prohibit-password | |
| 3 | +PasswordAuthentication {{ 'no' if oiam_cles_ssh.matched > 0 else 'yes' }} | |
| 4 | +KbdInteractiveAuthentication no | |
| 5 | +PermitEmptyPasswords no | |
| 6 | +MaxAuthTries 3 | |
| 7 | +LoginGraceTime 30 | |
| 8 | +X11Forwarding no | |
| 9 | +AllowAgentForwarding no |
A
ansible/roles/openldap_ltb/defaults/main.yml
+21
-0
@@ -0,0 +1,21 @@
| 1 | +--- | |
| 2 | +oiam_ldap_prefixe: /usr/local/openldap | |
| 3 | +oiam_ldap_etc: "{{ oiam_ldap_prefixe }}/etc/openldap" | |
| 4 | +oiam_ldap_modules: "{{ oiam_ldap_prefixe }}/libexec/openldap" | |
| 5 | +oiam_ldap_var: "{{ oiam_ldap_prefixe }}/var" | |
| 6 | +oiam_ldap_service: slapd-ltb | |
| 7 | +oiam_ldap_ldapi: ldapi://%2Fvar%2Frun%2Fslapd%2Fldapi | |
| 8 | +oiam_ldap_root_dn: "cn=admin,{{ oiam_base_dn }}" | |
| 9 | +oiam_ldap_admins_dn: "cn=openiam-admins,ou=groups,{{ oiam_base_dn }}" | |
| 10 | +oiam_ldap_peercred: "gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" | |
| 11 | +# Marqueur de l'initialisation : la configuration complète n'est générée qu'une fois. | |
| 12 | +oiam_ldap_marqueur: "{{ oiam_ldap_etc }}/.open-iam-initialise" | |
| 13 | +oiam_ldap_taille_max: 10737418240 | |
| 14 | + | |
| 15 | +# Dépôt LTB (R-03) : clé renouvelée en août 2025, empreinte épinglée. | |
| 16 | +oiam_ltb_depot: "https://ltb-project.org/debian/openldap26/{{ oiam_os_codenames[ansible_distribution | lower] }}" | |
| 17 | +oiam_ltb_cle_url: https://ltb-project.org/documentation/_static/ltb-project-debian-keyring.gpg | |
| 18 | +oiam_ltb_cle_sha256: c3a7185a1a6d36ddf2b35fa169b71235a9f79f5c04502071730dfed452b5596f | |
| 19 | +oiam_ltb_paquets: [openldap-ltb, openldap-ltb-contrib-overlays, openldap-ltb-mdb-utils] | |
| 20 | + | |
| 21 | +oiam_ldap_schemas: [core, cosine, inetorgperson, nis, dyngroup] |
A
ansible/roles/openldap_ltb/handlers/main.yml
+5
-0
@@ -0,0 +1,5 @@
| 1 | +--- | |
| 2 | +- name: Redémarrer l'annuaire | |
| 3 | + ansible.builtin.service: | |
| 4 | + name: "{{ oiam_ldap_service }}" | |
| 5 | + state: restarted |
A
ansible/roles/openldap_ltb/tasks/initialisation.yml
+137
-0
@@ -0,0 +1,137 @@
| 1 | +--- | |
| 2 | +# Première installation : configuration cn=config générée d'un bloc (slapadd), puis données | |
| 3 | +# ajoutées en ligne pour que les overlays (memberOf, ppolicy) s'appliquent. | |
| 4 | + | |
| 5 | +- name: Calculer l'empreinte du mot de passe d'urgence | |
| 6 | + ansible.builtin.command: | |
| 7 | + argv: | |
| 8 | + - "{{ oiam_ldap_prefixe }}/sbin/slappasswd" | |
| 9 | + - -o | |
| 10 | + - "module-path={{ oiam_ldap_modules }}" | |
| 11 | + - -o | |
| 12 | + - module-load=argon2.la | |
| 13 | + - -h | |
| 14 | + - "{ARGON2}" | |
| 15 | + - -s | |
| 16 | + - "{{ oiam_ldap_admin_mot_de_passe }}" | |
| 17 | + register: oiam_ldap_root_pw | |
| 18 | + changed_when: false | |
| 19 | + no_log: true | |
| 20 | + | |
| 21 | +- name: Préparer les fragments de la configuration | |
| 22 | + ansible.builtin.file: | |
| 23 | + path: "{{ oiam_ldap_etc }}/open-iam/config.d" | |
| 24 | + state: directory | |
| 25 | + owner: root | |
| 26 | + group: root | |
| 27 | + mode: "0700" | |
| 28 | + | |
| 29 | +- name: Écrire la configuration globale et les modules | |
| 30 | + ansible.builtin.template: | |
| 31 | + src: config.d/00-global.ldif.j2 | |
| 32 | + dest: "{{ oiam_ldap_etc }}/open-iam/config.d/00-global.ldif" | |
| 33 | + mode: "0600" | |
| 34 | + | |
| 35 | +- name: Ajouter les schémas | |
| 36 | + ansible.builtin.copy: | |
| 37 | + src: "{{ oiam_ldap_etc }}/schema/{{ item }}.ldif" | |
| 38 | + dest: "{{ oiam_ldap_etc }}/open-iam/config.d/1{{ index }}-{{ item }}.ldif" | |
| 39 | + remote_src: true | |
| 40 | + mode: "0600" | |
| 41 | + loop: "{{ oiam_ldap_schemas }}" | |
| 42 | + loop_control: | |
| 43 | + index_var: index | |
| 44 | + | |
| 45 | +- name: Écrire les bases, les ACL et les overlays | |
| 46 | + ansible.builtin.template: | |
| 47 | + src: config.d/50-bases.ldif.j2 | |
| 48 | + dest: "{{ oiam_ldap_etc }}/open-iam/config.d/50-bases.ldif" | |
| 49 | + mode: "0600" | |
| 50 | + no_log: true | |
| 51 | + | |
| 52 | +- name: Assembler la configuration | |
| 53 | + ansible.builtin.assemble: | |
| 54 | + src: "{{ oiam_ldap_etc }}/open-iam/config.d" | |
| 55 | + dest: "{{ oiam_ldap_etc }}/open-iam/config.ldif" | |
| 56 | + delimiter: "\n" | |
| 57 | + mode: "0600" | |
| 58 | + | |
| 59 | +- name: Arrêter l'annuaire | |
| 60 | + ansible.builtin.service: | |
| 61 | + name: "{{ oiam_ldap_service }}" | |
| 62 | + state: stopped | |
| 63 | + | |
| 64 | +- name: Vider la configuration et les données livrées par le paquet | |
| 65 | + ansible.builtin.file: | |
| 66 | + path: "{{ item }}" | |
| 67 | + state: absent | |
| 68 | + loop: | |
| 69 | + - "{{ oiam_ldap_etc }}/slapd.d" | |
| 70 | + - "{{ oiam_ldap_var }}/openldap-data" | |
| 71 | + - "{{ oiam_ldap_var }}/accesslog-data" | |
| 72 | + | |
| 73 | +- name: Recréer les répertoires de l'annuaire | |
| 74 | + ansible.builtin.file: | |
| 75 | + path: "{{ item }}" | |
| 76 | + state: directory | |
| 77 | + owner: ldap | |
| 78 | + group: ldap | |
| 79 | + mode: "0750" | |
| 80 | + loop: | |
| 81 | + - "{{ oiam_ldap_etc }}/slapd.d" | |
| 82 | + - "{{ oiam_ldap_var }}/openldap-data" | |
| 83 | + - "{{ oiam_ldap_var }}/accesslog-data" | |
| 84 | + - "{{ oiam_ldap_var }}/auditlog" | |
| 85 | + | |
| 86 | +- name: Charger la configuration | |
| 87 | + ansible.builtin.command: | |
| 88 | + argv: | |
| 89 | + - "{{ oiam_ldap_prefixe }}/sbin/slapadd" | |
| 90 | + - -n0 | |
| 91 | + - -F | |
| 92 | + - "{{ oiam_ldap_etc }}/slapd.d" | |
| 93 | + - -l | |
| 94 | + - "{{ oiam_ldap_etc }}/open-iam/config.ldif" | |
| 95 | + changed_when: true | |
| 96 | + | |
| 97 | +- name: Donner la configuration à l'utilisateur ldap | |
| 98 | + ansible.builtin.file: | |
| 99 | + path: "{{ oiam_ldap_etc }}/slapd.d" | |
| 100 | + owner: ldap | |
| 101 | + group: ldap | |
| 102 | + recurse: true | |
| 103 | + | |
| 104 | +- name: Supprimer la configuration en clair (elle contient l'empreinte du mot de passe d'urgence) | |
| 105 | + ansible.builtin.file: | |
| 106 | + path: "{{ item }}" | |
| 107 | + state: absent | |
| 108 | + loop: | |
| 109 | + - "{{ oiam_ldap_etc }}/open-iam/config.d/50-bases.ldif" | |
| 110 | + - "{{ oiam_ldap_etc }}/open-iam/config.ldif" | |
| 111 | + | |
| 112 | +- name: Démarrer l'annuaire | |
| 113 | + ansible.builtin.service: | |
| 114 | + name: "{{ oiam_ldap_service }}" | |
| 115 | + state: started | |
| 116 | + | |
| 117 | +- name: Attendre que l'annuaire réponde | |
| 118 | + ansible.builtin.command: | |
| 119 | + argv: ["{{ oiam_ldap_prefixe }}/bin/ldapwhoami", -Q, -Y, EXTERNAL, -H, "{{ oiam_ldap_ldapi }}"] | |
| 120 | + register: oiam_ldap_pret | |
| 121 | + until: oiam_ldap_pret.rc == 0 | |
| 122 | + retries: 30 | |
| 123 | + delay: 1 | |
| 124 | + changed_when: false | |
| 125 | + | |
| 126 | +- name: Créer l'arborescence, la politique de mots de passe et le premier administrateur | |
| 127 | + ansible.builtin.command: | |
| 128 | + argv: ["{{ oiam_ldap_prefixe }}/bin/ldapadd", -Q, -Y, EXTERNAL, -H, "{{ oiam_ldap_ldapi }}"] | |
| 129 | + stdin: "{{ lookup('ansible.builtin.template', 'donnees.ldif.j2') }}" | |
| 130 | + changed_when: true | |
| 131 | + no_log: true | |
| 132 | + | |
| 133 | +- name: Marquer l'annuaire comme initialisé | |
| 134 | + ansible.builtin.copy: | |
| 135 | + dest: "{{ oiam_ldap_marqueur }}" | |
| 136 | + mode: "0644" | |
| 137 | + content: "Initialisé par Open IAM le {{ ansible_date_time.iso8601 }}\n" |
A
ansible/roles/openldap_ltb/tasks/main.yml
+27
-0
@@ -0,0 +1,27 @@
| 1 | +--- | |
| 2 | +- name: Installer OpenLDAP LTB | |
| 3 | + ansible.builtin.import_tasks: paquets.yml | |
| 4 | + | |
| 5 | +- name: Installer le certificat TLS de l'annuaire | |
| 6 | + ansible.builtin.import_tasks: tls.yml | |
| 7 | + | |
| 8 | +- name: Configurer le client LDAP du serveur | |
| 9 | + ansible.builtin.template: | |
| 10 | + src: ldap.conf.j2 | |
| 11 | + dest: "{{ oiam_ldap_etc }}/ldap.conf" | |
| 12 | + mode: "0644" | |
| 13 | + | |
| 14 | +- name: Vérifier si l'annuaire est déjà initialisé | |
| 15 | + ansible.builtin.stat: | |
| 16 | + path: "{{ oiam_ldap_marqueur }}" | |
| 17 | + register: oiam_ldap_initialise | |
| 18 | + | |
| 19 | +- name: Initialiser l'annuaire | |
| 20 | + when: not oiam_ldap_initialise.stat.exists | |
| 21 | + ansible.builtin.import_tasks: initialisation.yml | |
| 22 | + | |
| 23 | +- name: Démarrer l'annuaire au démarrage du serveur | |
| 24 | + ansible.builtin.service: | |
| 25 | + name: "{{ oiam_ldap_service }}" | |
| 26 | + enabled: true | |
| 27 | + state: started |
A
ansible/roles/openldap_ltb/tasks/paquets.yml
+32
-0
@@ -0,0 +1,32 @@
| 1 | +--- | |
| 2 | +- name: Créer le répertoire des clés APT | |
| 3 | + ansible.builtin.file: | |
| 4 | + path: /etc/apt/keyrings | |
| 5 | + state: directory | |
| 6 | + mode: "0755" | |
| 7 | + | |
| 8 | +- name: Télécharger la clé du dépôt LTB (empreinte vérifiée) | |
| 9 | + ansible.builtin.get_url: | |
| 10 | + url: "{{ oiam_ltb_cle_url }}" | |
| 11 | + dest: /etc/apt/keyrings/ltb-project.asc | |
| 12 | + checksum: "sha256:{{ oiam_ltb_cle_sha256 }}" | |
| 13 | + mode: "0644" | |
| 14 | + | |
| 15 | +- name: Déclarer le dépôt LTB | |
| 16 | + ansible.builtin.copy: | |
| 17 | + dest: /etc/apt/sources.list.d/ltb-project-openldap.sources | |
| 18 | + mode: "0644" | |
| 19 | + content: | | |
| 20 | + # Géré par Open IAM : toute modification manuelle sera écrasée. | |
| 21 | + Types: deb | |
| 22 | + URIs: {{ oiam_ltb_depot }} | |
| 23 | + Suites: {{ oiam_os_codenames[ansible_distribution | lower] }} | |
| 24 | + Components: main | |
| 25 | + Signed-By: /etc/apt/keyrings/ltb-project.asc | |
| 26 | + register: oiam_ltb_sources | |
| 27 | + | |
| 28 | +- name: Installer les paquets OpenLDAP LTB | |
| 29 | + ansible.builtin.apt: | |
| 30 | + name: "{{ oiam_ltb_paquets }}" | |
| 31 | + state: present | |
| 32 | + update_cache: "{{ oiam_ltb_sources is changed }}" |
A
ansible/roles/openldap_ltb/tasks/tls.yml
+24
-0
@@ -0,0 +1,24 @@
| 1 | +--- | |
| 2 | +- name: Créer le répertoire TLS de l'annuaire | |
| 3 | + ansible.builtin.file: | |
| 4 | + path: "{{ oiam_ldap_etc }}/tls" | |
| 5 | + state: directory | |
| 6 | + owner: root | |
| 7 | + group: ldap | |
| 8 | + mode: "0750" | |
| 9 | + | |
| 10 | +- name: Copier le certificat, la chaîne et la clé | |
| 11 | + ansible.builtin.copy: | |
| 12 | + src: "{{ item.src }}" | |
| 13 | + dest: "{{ oiam_ldap_etc }}/tls/{{ item.dest }}" | |
| 14 | + remote_src: true | |
| 15 | + owner: root | |
| 16 | + group: ldap | |
| 17 | + mode: "{{ item.mode }}" | |
| 18 | + loop: | |
| 19 | + - { src: "{{ oiam_pki | default('/etc/open-iam/pki') }}/serveur.crt", dest: serveur.crt, mode: "0644" } | |
| 20 | + - { src: "{{ oiam_pki | default('/etc/open-iam/pki') }}/ca.crt", dest: ca.crt, mode: "0644" } | |
| 21 | + - { src: "{{ oiam_pki | default('/etc/open-iam/pki') }}/serveur.key", dest: serveur.key, mode: "0640" } | |
| 22 | + loop_control: | |
| 23 | + label: "{{ item.dest }}" | |
| 24 | + notify: Redémarrer l'annuaire |
A
ansible/roles/openldap_ltb/templates/config.d/00-global.ldif.j2
+33
-0
@@ -0,0 +1,33 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +dn: cn=config | |
| 3 | +objectClass: olcGlobal | |
| 4 | +cn: config | |
| 5 | +olcArgsFile: {{ oiam_ldap_var }}/run/slapd.args | |
| 6 | +olcPidFile: {{ oiam_ldap_var }}/run/slapd.pid | |
| 7 | +olcLogLevel: stats | |
| 8 | +olcTLSCertificateFile: {{ oiam_ldap_etc }}/tls/serveur.crt | |
| 9 | +olcTLSCertificateKeyFile: {{ oiam_ldap_etc }}/tls/serveur.key | |
| 10 | +olcTLSCACertificateFile: {{ oiam_ldap_etc }}/tls/ca.crt | |
| 11 | +olcTLSProtocolMin: 3.3 | |
| 12 | +olcDisallows: bind_anon | |
| 13 | +# Bind simple et écritures uniquement sur une connexion protégée (TLS ou socket local ldapi). | |
| 14 | +olcSecurity: simple_bind=64 update_ssf=64 | |
| 15 | + | |
| 16 | +dn: cn=module{0},cn=config | |
| 17 | +objectClass: olcModuleList | |
| 18 | +cn: module{0} | |
| 19 | +olcModulePath: {{ oiam_ldap_modules }} | |
| 20 | +olcModuleLoad: {0}argon2.la | |
| 21 | +olcModuleLoad: {1}back_mdb.la | |
| 22 | +olcModuleLoad: {2}accesslog.la | |
| 23 | +olcModuleLoad: {3}auditlog.la | |
| 24 | +olcModuleLoad: {4}dynlist.la | |
| 25 | +olcModuleLoad: {5}memberof.la | |
| 26 | +olcModuleLoad: {6}ppolicy.la | |
| 27 | +olcModuleLoad: {7}refint.la | |
| 28 | +olcModuleLoad: {8}syncprov.la | |
| 29 | +olcModuleLoad: {9}unique.la | |
| 30 | + | |
| 31 | +dn: cn=schema,cn=config | |
| 32 | +objectClass: olcSchemaConfig | |
| 33 | +cn: schema |
A
ansible/roles/openldap_ltb/templates/config.d/50-bases.ldif.j2
+98
-0
@@ -0,0 +1,98 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +dn: olcDatabase={-1}frontend,cn=config | |
| 3 | +objectClass: olcDatabaseConfig | |
| 4 | +objectClass: olcFrontendConfig | |
| 5 | +olcDatabase: {-1}frontend | |
| 6 | +olcPasswordHash: {ARGON2} | |
| 7 | +olcAccess: {0}to dn.base="" by * read | |
| 8 | +olcAccess: {1}to dn.base="cn=subschema" by * read | |
| 9 | + | |
| 10 | +dn: olcDatabase={0}config,cn=config | |
| 11 | +objectClass: olcDatabaseConfig | |
| 12 | +olcDatabase: {0}config | |
| 13 | +olcAccess: {0}to * by dn.exact="{{ oiam_ldap_peercred }}" manage by * none | |
| 14 | + | |
| 15 | +# Journal des accès (binds, échecs, écritures) : audit et future réplication (L5). | |
| 16 | +dn: olcDatabase={1}mdb,cn=config | |
| 17 | +objectClass: olcDatabaseConfig | |
| 18 | +objectClass: olcMdbConfig | |
| 19 | +olcDatabase: {1}mdb | |
| 20 | +olcSuffix: cn=accesslog | |
| 21 | +olcDbDirectory: {{ oiam_ldap_var }}/accesslog-data | |
| 22 | +olcDbMaxSize: 1073741824 | |
| 23 | +olcDbIndex: default eq | |
| 24 | +olcDbIndex: entryCSN,objectClass,reqEnd,reqResult,reqStart,reqDN | |
| 25 | +olcAccess: {0}to * by dn.exact="{{ oiam_ldap_peercred }}" manage by group.exact="{{ oiam_ldap_admins_dn }}" read by * none | |
| 26 | + | |
| 27 | +dn: olcDatabase={2}mdb,cn=config | |
| 28 | +objectClass: olcDatabaseConfig | |
| 29 | +objectClass: olcMdbConfig | |
| 30 | +olcDatabase: {2}mdb | |
| 31 | +olcSuffix: {{ oiam_base_dn }} | |
| 32 | +olcRootDN: {{ oiam_ldap_root_dn }} | |
| 33 | +olcRootPW: {{ oiam_ldap_root_pw.stdout }} | |
| 34 | +olcDbDirectory: {{ oiam_ldap_var }}/openldap-data | |
| 35 | +olcDbMaxSize: {{ oiam_ldap_taille_max }} | |
| 36 | +olcLastBind: TRUE | |
| 37 | +olcDbIndex: objectClass eq | |
| 38 | +olcDbIndex: uid,mail eq,sub | |
| 39 | +olcDbIndex: cn,sn,givenName eq,sub | |
| 40 | +olcDbIndex: member,memberOf eq | |
| 41 | +olcDbIndex: entryCSN,entryUUID eq | |
| 42 | +olcAccess: {0}to * by dn.exact="{{ oiam_ldap_peercred }}" manage by * break | |
| 43 | +olcAccess: {1}to attrs=userPassword by self =xw by group.exact="{{ oiam_ldap_admins_dn }}" =xw by anonymous auth by * none | |
| 44 | +olcAccess: {2}to dn.subtree="ou=ppolicies,{{ oiam_base_dn }}" by group.exact="{{ oiam_ldap_admins_dn }}" read by * none | |
| 45 | +olcAccess: {3}to * by group.exact="{{ oiam_ldap_admins_dn }}" write by self read by users read by * none | |
| 46 | + | |
| 47 | +dn: olcOverlay={0}memberof,olcDatabase={2}mdb,cn=config | |
| 48 | +objectClass: olcOverlayConfig | |
| 49 | +objectClass: olcMemberOf | |
| 50 | +olcOverlay: {0}memberof | |
| 51 | +olcMemberOfRefInt: TRUE | |
| 52 | +olcMemberOfDangling: ignore | |
| 53 | +olcMemberOfGroupOC: groupOfNames | |
| 54 | +olcMemberOfMemberAD: member | |
| 55 | +olcMemberOfMemberOfAD: memberOf | |
| 56 | + | |
| 57 | +dn: olcOverlay={1}refint,olcDatabase={2}mdb,cn=config | |
| 58 | +objectClass: olcOverlayConfig | |
| 59 | +objectClass: olcRefintConfig | |
| 60 | +olcOverlay: {1}refint | |
| 61 | +olcRefintAttribute: member | |
| 62 | + | |
| 63 | +dn: olcOverlay={2}unique,olcDatabase={2}mdb,cn=config | |
| 64 | +objectClass: olcOverlayConfig | |
| 65 | +objectClass: olcUniqueConfig | |
| 66 | +olcOverlay: {2}unique | |
| 67 | +olcUniqueURI: ldap:///ou=users,{{ oiam_base_dn }}?uid?sub | |
| 68 | +olcUniqueURI: ldap:///ou=users,{{ oiam_base_dn }}?mail?sub | |
| 69 | + | |
| 70 | +dn: olcOverlay={3}ppolicy,olcDatabase={2}mdb,cn=config | |
| 71 | +objectClass: olcOverlayConfig | |
| 72 | +objectClass: olcPPolicyConfig | |
| 73 | +olcOverlay: {3}ppolicy | |
| 74 | +olcPPolicyDefault: cn=default,ou=ppolicies,{{ oiam_base_dn }} | |
| 75 | +olcPPolicyHashCleartext: TRUE | |
| 76 | +olcPPolicyUseLockout: TRUE | |
| 77 | +olcPPolicyCheckModule: {{ oiam_ldap_modules }}/ppm.so | |
| 78 | + | |
| 79 | +dn: olcOverlay={4}accesslog,olcDatabase={2}mdb,cn=config | |
| 80 | +objectClass: olcOverlayConfig | |
| 81 | +objectClass: olcAccessLogConfig | |
| 82 | +olcOverlay: {4}accesslog | |
| 83 | +olcAccessLogDB: cn=accesslog | |
| 84 | +olcAccessLogOps: writes | |
| 85 | +olcAccessLogOps: bind | |
| 86 | +olcAccessLogPurge: 30+00:00 01+00:00 | |
| 87 | + | |
| 88 | +dn: olcOverlay={5}auditlog,olcDatabase={2}mdb,cn=config | |
| 89 | +objectClass: olcOverlayConfig | |
| 90 | +objectClass: olcAuditLogConfig | |
| 91 | +olcOverlay: {5}auditlog | |
| 92 | +olcAuditlogFile: {{ oiam_ldap_var }}/auditlog/audit.ldif | |
| 93 | + | |
| 94 | +dn: olcOverlay={6}dynlist,olcDatabase={2}mdb,cn=config | |
| 95 | +objectClass: olcOverlayConfig | |
| 96 | +objectClass: olcDynListConfig | |
| 97 | +olcOverlay: {6}dynlist | |
| 98 | +olcDynListAttrSet: groupOfURLs memberURL member |
A
ansible/roles/openldap_ltb/templates/donnees.ldif.j2
+64
-0
@@ -0,0 +1,64 @@
| 1 | +{% set rdn = oiam_base_dn.split(',')[0] %} | |
| 2 | +{% set rdn_attr, rdn_valeur = rdn.split('=', 1) %} | |
| 3 | +dn: {{ oiam_base_dn }} | |
| 4 | +objectClass: top | |
| 5 | +{% if rdn_attr == 'dc' %} | |
| 6 | +objectClass: dcObject | |
| 7 | +objectClass: organization | |
| 8 | +dc: {{ rdn_valeur }} | |
| 9 | +o: {{ oiam_organisation }} | |
| 10 | +{% elif rdn_attr == 'o' %} | |
| 11 | +objectClass: organization | |
| 12 | +o: {{ rdn_valeur }} | |
| 13 | +{% else %} | |
| 14 | +objectClass: organizationalUnit | |
| 15 | +ou: {{ rdn_valeur }} | |
| 16 | +{% endif %} | |
| 17 | +description: Annuaire {{ oiam_organisation }} (Open IAM) | |
| 18 | + | |
| 19 | +{% for ou, description in [('users', 'Utilisateurs'), ('groups', 'Groupes'), ('applications', 'Comptes de service des applications'), ('ppolicies', 'Politiques de mots de passe')] %} | |
| 20 | +dn: ou={{ ou }},{{ oiam_base_dn }} | |
| 21 | +objectClass: organizationalUnit | |
| 22 | +ou: {{ ou }} | |
| 23 | +description: {{ description }} | |
| 24 | + | |
| 25 | +{% endfor %} | |
| 26 | +dn: cn=default,ou=ppolicies,{{ oiam_base_dn }} | |
| 27 | +objectClass: top | |
| 28 | +objectClass: device | |
| 29 | +objectClass: pwdPolicy | |
| 30 | +objectClass: pwdPolicyChecker | |
| 31 | +cn: default | |
| 32 | +description: Politique par défaut (configurée par l'assistant Open IAM) | |
| 33 | +pwdAttribute: userPassword | |
| 34 | +pwdMinLength: {{ oiam_mdp.longueur_min }} | |
| 35 | +pwdInHistory: {{ oiam_mdp.historique }} | |
| 36 | +pwdMaxAge: {{ oiam_mdp.expiration_jours * 86400 }} | |
| 37 | +pwdExpireWarning: {{ 14 * 86400 if oiam_mdp.expiration_jours > 0 else 0 }} | |
| 38 | +pwdMaxFailure: {{ oiam_mdp.echecs_max }} | |
| 39 | +pwdLockout: TRUE | |
| 40 | +pwdLockoutDuration: {{ oiam_mdp.verrouillage_minutes * 60 }} | |
| 41 | +pwdFailureCountInterval: 0 | |
| 42 | +pwdCheckQuality: 2 | |
| 43 | +pwdUseCheckModule: TRUE | |
| 44 | +pwdCheckModuleArg:: {{ lookup('ansible.builtin.template', 'ppm.conf.j2') | b64encode }} | |
| 45 | +pwdAllowUserChange: TRUE | |
| 46 | +pwdMustChange: FALSE | |
| 47 | +pwdSafeModify: FALSE | |
| 48 | + | |
| 49 | +dn: uid={{ oiam_admin_initial.uid }},ou=users,{{ oiam_base_dn }} | |
| 50 | +objectClass: inetOrgPerson | |
| 51 | +uid: {{ oiam_admin_initial.uid }} | |
| 52 | +cn: {{ oiam_admin_initial.prenom }} {{ oiam_admin_initial.nom }} | |
| 53 | +givenName: {{ oiam_admin_initial.prenom }} | |
| 54 | +sn: {{ oiam_admin_initial.nom }} | |
| 55 | +mail: {{ oiam_admin_initial.email }} | |
| 56 | +{% if oiam_admin_initial.mode_mdp == 'saisir' %} | |
| 57 | +userPassword: {{ oiam_admin_initial_mot_de_passe }} | |
| 58 | +{% endif %} | |
| 59 | + | |
| 60 | +dn: {{ oiam_ldap_admins_dn }} | |
| 61 | +objectClass: groupOfNames | |
| 62 | +cn: openiam-admins | |
| 63 | +description: Administrateurs Open IAM (console d'administration) | |
| 64 | +member: uid={{ oiam_admin_initial.uid }},ou=users,{{ oiam_base_dn }} |
A
ansible/roles/openldap_ltb/templates/ldap.conf.j2
+5
-0
@@ -0,0 +1,5 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +URI ldaps://{{ oiam_services.annuaire }} | |
| 3 | +BASE {{ oiam_base_dn }} | |
| 4 | +TLS_CACERT {{ oiam_ldap_etc }}/tls/ca.crt | |
| 5 | +TLS_REQCERT demand |
A
ansible/roles/openldap_ltb/templates/ppm.conf.j2
+10
-0
@@ -0,0 +1,10 @@
| 1 | +minQuality {{ oiam_mdp.classes_min }} | |
| 2 | +checkRDN 0 | |
| 3 | +checkAttributes uid,cn,sn,givenName,mail | |
| 4 | +forbiddenChars | |
| 5 | +maxConsecutivePerClass 0 | |
| 6 | +useCracklib 0 | |
| 7 | +class-upperCase ABCDEFGHIJKLMNOPQRSTUVWXYZ 0 1 0 | |
| 8 | +class-lowerCase abcdefghijklmnopqrstuvwxyz 0 1 0 | |
| 9 | +class-digit 0123456789 0 1 0 | |
| 10 | +class-special <>,?;.:/!§ù%*µ^¨$£²&é~"#'{([-|è`_\ç^à@)]°=}+ 0 1 0 |
A
ansible/roles/pki/defaults/main.yml
+6
-0
@@ -0,0 +1,6 @@
| 1 | +--- | |
| 2 | +oiam_pki: /etc/open-iam/pki | |
| 3 | +oiam_pki_ca_jours: 3650 | |
| 4 | +# 397 jours : durée maximale acceptée par les navigateurs pour un certificat serveur. | |
| 5 | +oiam_pki_serveur_jours: 397 | |
| 6 | +oiam_pki_noms: "{{ (oiam_services.values() | list) + [inventory_hostname, ansible_fqdn] | unique }}" |
A
ansible/roles/pki/handlers/main.yml
+4
-0
@@ -0,0 +1,4 @@
| 1 | +--- | |
| 2 | +- name: Mettre à jour les autorités de confiance | |
| 3 | + ansible.builtin.command: update-ca-certificates | |
| 4 | + changed_when: true |
A
ansible/roles/pki/tasks/main.yml
+65
-0
@@ -0,0 +1,65 @@
| 1 | +--- | |
| 2 | +# Autorité de certification interne (E-005, tls.mode = interne) : une CA ECDSA P-256 par | |
| 3 | +# installation, un certificat serveur couvrant les noms des services de l'hôte. | |
| 4 | +- name: Créer le répertoire de la PKI | |
| 5 | + ansible.builtin.file: | |
| 6 | + path: "{{ oiam_pki }}" | |
| 7 | + state: directory | |
| 8 | + owner: root | |
| 9 | + group: root | |
| 10 | + mode: "0700" | |
| 11 | + | |
| 12 | +- name: Générer la clé de l'autorité interne | |
| 13 | + ansible.builtin.command: | |
| 14 | + cmd: openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out {{ oiam_pki }}/ca.key | |
| 15 | + creates: "{{ oiam_pki }}/ca.key" | |
| 16 | + | |
| 17 | +- name: Générer le certificat de l'autorité interne | |
| 18 | + ansible.builtin.command: | |
| 19 | + cmd: >- | |
| 20 | + openssl req -x509 -new -utf8 -sha256 -days {{ oiam_pki_ca_jours }} | |
| 21 | + -key {{ oiam_pki }}/ca.key -out {{ oiam_pki }}/ca.crt | |
| 22 | + -subj "/O={{ oiam_organisation }}/CN=Autorité interne Open IAM ({{ oiam_domaine }})" | |
| 23 | + -addext "basicConstraints=critical,CA:TRUE,pathlen:0" | |
| 24 | + -addext "keyUsage=critical,keyCertSign,cRLSign" | |
| 25 | + creates: "{{ oiam_pki }}/ca.crt" | |
| 26 | + | |
| 27 | +- name: Générer la clé du serveur | |
| 28 | + ansible.builtin.command: | |
| 29 | + cmd: openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out {{ oiam_pki }}/serveur.key | |
| 30 | + creates: "{{ oiam_pki }}/serveur.key" | |
| 31 | + | |
| 32 | +- name: Décrire les noms couverts par le certificat serveur | |
| 33 | + ansible.builtin.template: | |
| 34 | + src: serveur.ext.j2 | |
| 35 | + dest: "{{ oiam_pki }}/serveur.ext" | |
| 36 | + mode: "0600" | |
| 37 | + register: oiam_pki_ext | |
| 38 | + | |
| 39 | +- name: Vérifier la présence du certificat serveur | |
| 40 | + ansible.builtin.stat: | |
| 41 | + path: "{{ oiam_pki }}/serveur.crt" | |
| 42 | + register: oiam_pki_crt | |
| 43 | + | |
| 44 | +- name: Émettre le certificat serveur (nouveaux noms ou certificat absent) | |
| 45 | + when: oiam_pki_ext is changed or not oiam_pki_crt.stat.exists | |
| 46 | + ansible.builtin.shell: | |
| 47 | + cmd: >- | |
| 48 | + set -o pipefail && | |
| 49 | + openssl req -new -utf8 -key {{ oiam_pki }}/serveur.key -subj "/CN={{ oiam_pki_noms[0] }}" | |
| 50 | + | openssl x509 -req -sha256 -days {{ oiam_pki_serveur_jours }} | |
| 51 | + -CA {{ oiam_pki }}/ca.crt -CAkey {{ oiam_pki }}/ca.key -CAcreateserial | |
| 52 | + -extfile {{ oiam_pki }}/serveur.ext -out {{ oiam_pki }}/serveur.crt | |
| 53 | + executable: /bin/bash | |
| 54 | + changed_when: true | |
| 55 | + | |
| 56 | +- name: Faire confiance à l'autorité interne sur ce serveur | |
| 57 | + ansible.builtin.copy: | |
| 58 | + src: "{{ oiam_pki }}/ca.crt" | |
| 59 | + dest: /usr/local/share/ca-certificates/open-iam-ca.crt | |
| 60 | + remote_src: true | |
| 61 | + mode: "0644" | |
| 62 | + notify: Mettre à jour les autorités de confiance | |
| 63 | + | |
| 64 | +- name: Appliquer la mise à jour des autorités de confiance | |
| 65 | + ansible.builtin.meta: flush_handlers |
A
ansible/roles/pki/templates/serveur.ext.j2
+10
-0
@@ -0,0 +1,10 @@
| 1 | +# {{ ansible_managed }} | |
| 2 | +basicConstraints = critical,CA:FALSE | |
| 3 | +keyUsage = critical,digitalSignature | |
| 4 | +extendedKeyUsage = serverAuth | |
| 5 | +subjectAltName = @noms | |
| 6 | + | |
| 7 | +[noms] | |
| 8 | +{% for nom in oiam_pki_noms %} | |
| 9 | +DNS.{{ loop.index }} = {{ nom }} | |
| 10 | +{% endfor %} |
A
ansible/site.yml
+15
-0
@@ -0,0 +1,15 @@
| 1 | +--- | |
| 2 | +# Socle Open IAM (M1) : système, autorité interne, durcissement, annuaire, sauvegardes. | |
| 3 | +# Variables : group_vars produits par l'installeur (config::ansible) + secrets.yml (vault). | |
| 4 | +- name: Socle Open IAM | |
| 5 | + hosts: all | |
| 6 | + become: true | |
| 7 | + roles: | |
| 8 | + - role: common | |
| 9 | + - role: pki | |
| 10 | + when: oiam_tls_mode == 'interne' | |
| 11 | + - role: hardening | |
| 12 | + - role: openldap_ltb | |
| 13 | + when: "'openldap' in oiam_composants" | |
| 14 | + - role: backup | |
| 15 | + when: "'sauvegarde' in oiam_composants" |
M
docs/BACKLOG.md
+32
-27
@@ -27,7 +27,7 @@ Ce fichier sert à **piloter** le projet. Le *quoi* et le *pourquoi* sont dans l
| 27 | 27 | | Jalon | Objectif | Critère de sortie | Version | |
| 28 | 28 | |-------|----------|-------------------|---------| |
| 29 | 29 | | **M0** Fondations | Spécifications, environnement de dev, socle web | Le serveur axum sert une page vide avec la CSP, le CSRF et les tokens de `design.md` | — | |
| 30 | -| **M1** Premier annuaire | L'assistant installe un OpenLDAP sur **ce serveur**, en natif | Sur une VM Debian 13 vierge : parcours E-000 → E-012 complet, et recette `tests/e2e/l1-annuaire` verte | v0.1.0-alpha | | |
| 30 | +| **M1** Premier annuaire | L'assistant installe un OpenLDAP sur **ce serveur**, en natif | Sur une cible Debian 13 vierge (conteneur systemd, D-021) : parcours E-000 → E-012 complet, et recette `tests/e2e/l1-annuaire` verte | v0.1.0-alpha | | |
| 31 | 31 | | **M2** Lot 1 complet | Outils LTB, Compose, multi-hôtes, supervision, chaîne logicielle | Recette L1 complète verte en natif **et** en Compose ; Molecule vert sur tous les rôles ; revue OWASP faite | v0.1.0 | |
| 32 | 32 | | **M3** Console | Administration après installation | Tous les écrans E-020 à E-033 livrés ; mise à jour N → N+1 avec retour arrière testée | v0.2.0 | |
| 33 | 33 | | **M4** Lot 2 | SSO et 2FA (LemonLDAP::NG) | Recette L2 verte (OIDC, SAML, CAS, TOTP, WebAuthn) | v0.3.0 | |
@@ -54,41 +54,42 @@ Ce fichier sert à **piloter** le projet. Le *quoi* et le *pourquoi* sont dans l
| 54 | 54 | |
| 55 | 55 | ## M1 — Premier annuaire (assistant + socle Ansible, natif, hôte local) |
| 56 | 56 | |
| 57 | +Plan détaillé : [plans/m1-premier-annuaire.md](plans/m1-premier-annuaire.md). | |
| 58 | + | |
| 57 | 59 | | ID | Tâche | Statut | Taille | Dépend de | Critère de fin | Réf | |
| 58 | 60 | |----|-------|--------|--------|-----------|----------------|-----| |
| 59 | -| OI-020 | Modèle `OpenIamConfig` : validation (FQDN, DN, cohérence), sérialisation `openiam.yaml` et `group_vars`, secrets en 0600 chiffrés par ansible-vault | À faire | L | OI-004 | Tests unitaires de toutes les règles des fiches E-002 à E-008 ; aller-retour YAML sans perte ; aucun secret dans `openiam.yaml` | plan § Installeur | | |
| 60 | -| OI-021 | Catalogue des composants et résolution des dépendances | À faire | M | OI-020 | Tests : fermeture transitive, composants des lots futurs refusés, rôles d'hôte requis | [E-004](ihm/screens/E-004-composants.md) | | |
| 61 | -| OI-022 | Brouillon persistant et état des étapes (validée, à revoir, sautée), invalidation en cascade | À faire | M | OI-020 | Un redémarrage conserve le brouillon ; modifier E-004 rend E-006 « à revoir » | [IHM_MAP § Parcours](ihm/IHM_MAP.md) | | |
| 62 | -| OI-023 | E-000 Accès par jeton | À faire | M | OI-010 | Checklist de la fiche cochée | [E-000](ihm/screens/E-000-acces-jeton.md) | | |
| 63 | -| OI-024 | E-001 Bienvenue, prérequis, import | À faire | M | OI-022 | Checklist de la fiche cochée | [E-001](ihm/screens/E-001-bienvenue.md) | | |
| 64 | -| OI-025 | E-002 Organisation | À faire | S | OI-022 | Checklist de la fiche cochée | [E-002](ihm/screens/E-002-organisation.md) | | |
| 65 | -| OI-026 | E-003 Cibles — mode natif, hôte local seulement | À faire | S | OI-022 | Checklist de la fiche cochée (hors multi-hôtes et Compose) | [E-003](ihm/screens/E-003-cibles.md) | | |
| 66 | -| OI-027 | E-004 Composants | À faire | M | OI-021 | Checklist de la fiche cochée | [E-004](ihm/screens/E-004-composants.md) | | |
| 67 | -| OI-028 | E-005 Sécurité — autorité interne, politique de mots de passe | À faire | M | OI-022 | Checklist de la fiche cochée (hors ACME, certificats fournis, 2FA) | [E-005](ihm/screens/E-005-securite.md) | | |
| 68 | -| OI-029 | E-006 Messagerie et e-mail de test | À faire | M | OI-022 | Checklist de la fiche cochée ; test avec MailHog | [E-006](ihm/screens/E-006-messagerie.md) | | |
| 69 | -| OI-030 | E-007 Comptes | À faire | M | OI-028 | Checklist de la fiche cochée | [E-007](ihm/screens/E-007-comptes.md) | | |
| 70 | -| OI-031 | E-008 Supervision et télémétrie — choix et aperçu (sans envoi) | À faire | S | OI-022 | Checklist de la fiche cochée ; aucun appel réseau sortant | [E-008](ihm/screens/E-008-telemetrie.md) | | |
| 71 | -| OI-032 | Rôles Ansible `common` et `pki` (autorité interne) | À faire | M | OI-007 | Molecule vert, second passage sans changement | plan § L1 | | |
| 72 | -| OI-033 | Rôle `hardening` (nftables, SSH par clé, mises à jour de sécurité automatiques) | À faire | M | OI-032 | Molecule vert ; `nmap` : seuls les ports attendus sont ouverts | plan § S | | |
| 73 | -| OI-034 | Rôle `openldap_ltb` : `cn=config`, MDB, overlays, DIT, ACL, TLS obligatoire | À faire | L | OI-032 | Molecule vert ; recette : `ldapwhoami` en TLS, bind anonyme refusé, verrouillage ppolicy, `memberOf` à jour | plan § L1 | | |
| 74 | -| OI-035 | Rôle `backup` : `slapcat` chiffré (age), rotation, test de restauration automatisé | À faire | M | OI-034 | Restauration réussie dans Molecule | plan § S | | |
| 75 | -| OI-036 | `runner` : lancement d'`ansible-playbook`, callback JSON, tampon disque, flux SSE, verrou d'exécution | À faire | L | OI-020 | Tests : reconnexion sans perte ni doublon, run orphelin marqué « interrompu », secrets masqués | [E-011](ihm/screens/E-011-execution.md) | | |
| 76 | -| OI-037 | E-010 Récapitulatif et vérification préalable | À faire | M | OI-036 | Checklist de la fiche cochée | [E-010](ihm/screens/E-010-recapitulatif.md) | | |
| 77 | -| OI-038 | E-011 Installation en cours | À faire | M | OI-036 | Checklist de la fiche cochée | [E-011](ihm/screens/E-011-execution.md) | | |
| 78 | -| OI-039 | E-012 Résultat et verrouillage de l'assistant | À faire | S | OI-038 | Checklist de la fiche cochée | [E-012](ihm/screens/E-012-resultat.md) | | |
| 79 | -| OI-040 | Recette de bout en bout `tests/e2e/l1-annuaire` sur une VM vierge | À faire | M | OI-023 à OI-039, OI-041 | Script vert sur Debian 13 et Ubuntu 26.04 | plan § Vérification | | |
| 80 | -| OI-041 | Fournir une **VM réelle** Debian 13 (et Ubuntu 26.04) pour la recette finale : noyau propre, pare-feu, sysctl, horloge | À faire | S | — | VM vierge accessible en SSH par clé, restaurable à un instantané | D-018 | | |
| 61 | +| OI-020 | Modèle `OpenIamConfig` : validation (FQDN, DN, cohérence), sérialisation `openiam.yaml` et `group_vars`, secrets en 0600 chiffrés par ansible-vault | Fait (2026-11-01) | L | OI-004 | Tests unitaires de toutes les règles des fiches E-002 à E-008 ; aller-retour YAML sans perte ; aucun secret dans `openiam.yaml` **Fait** : modèle, règles, YAML, `group_vars`, `secrets_vars` (62 tests). **Reste** : chiffrement ansible-vault de `secrets.yml`, livré avec OI-036. Chiffrement ansible-vault fait par le runner (OI-036). | plan § Installeur | | |
| 62 | +| OI-021 | Catalogue des composants et résolution des dépendances | Fait (2026-11-01) | M | OI-020 | Tests : fermeture transitive, composants des lots futurs refusés, rôles d'hôte requis | [E-004](ihm/screens/E-004-composants.md) | | |
| 63 | +| OI-022 | Brouillon persistant et état des étapes (validée, à revoir, sautée), invalidation en cascade | Fait (2026-11-01) | M | OI-020 | Un redémarrage conserve le brouillon ; modifier E-004 rend E-006 « à revoir » | [IHM_MAP § Parcours](ihm/IHM_MAP.md) | | |
| 64 | +| OI-023 | E-000 Accès par jeton | Fait (2026-11-01) | M | OI-010 | Checklist de la fiche cochée Tests d'intégration + parcours navigateur (axe-core 375/1280 px, CSP) + recette réelle `tests/e2e/l1-annuaire.sh`. | [E-000](ihm/screens/E-000-acces-jeton.md) | | |
| 65 | +| OI-024 | E-001 Bienvenue, prérequis, import | Fait (2026-11-01) | M | OI-022 | Checklist de la fiche cochée Écart à la fiche : Ansible absent = bloquant, avec bouton « Installer Ansible » (fiche mise à jour). | [E-001](ihm/screens/E-001-bienvenue.md) | | |
| 66 | +| OI-025 | E-002 Organisation | Fait (2026-11-01) | S | OI-022 | Checklist de la fiche cochée | [E-002](ihm/screens/E-002-organisation.md) | | |
| 67 | +| OI-026 | E-003 Cibles — mode natif, hôte local seulement | Fait (2026-11-01) | S | OI-022 | Checklist de la fiche cochée (hors multi-hôtes et Compose) | [E-003](ihm/screens/E-003-cibles.md) | | |
| 68 | +| OI-027 | E-004 Composants | Fait (2026-11-01) | M | OI-021 | Checklist de la fiche cochée | [E-004](ihm/screens/E-004-composants.md) | | |
| 69 | +| OI-028 | E-005 Sécurité — autorité interne, politique de mots de passe | Fait (2026-11-01) | M | OI-022 | Checklist de la fiche cochée (hors ACME, certificats fournis, 2FA) | [E-005](ihm/screens/E-005-securite.md) | | |
| 70 | +| OI-030 | E-007 Comptes | Fait (2026-11-01) | M | OI-028 | Checklist de la fiche cochée | [E-007](ihm/screens/E-007-comptes.md) | | |
| 71 | +| OI-031 | E-008 Supervision et télémétrie — choix et aperçu (sans envoi) | Fait (2026-11-01) | S | OI-022 | Checklist de la fiche cochée ; aucun appel réseau sortant Section supervision masquée en M1 (composant au jalon M2). | [E-008](ihm/screens/E-008-telemetrie.md) | | |
| 72 | +| OI-032 | Rôles Ansible `common` et `pki` (autorité interne) | Fait (2026-11-01) | M | OI-007 | Molecule vert, second passage sans changement Vérifié : `molecule test -s socle` (Debian 13 et Ubuntu 26.04). | plan § L1 | | |
| 73 | +| OI-033 | Rôle `hardening` (nftables, SSH par clé, mises à jour de sécurité automatiques) | Fait (2026-11-01) | M | OI-032 | Molecule vert ; `nmap` : seuls les ports attendus sont ouverts Écart : ports vérifiés sur les règles nftables chargées, pas par `nmap` (scan prévu dans OI-040). SSH par mot de passe laissé ouvert si aucune clé n'est installée, pour ne pas bloquer l'administrateur. | plan § S | | |
| 74 | +| OI-034 | Rôle `openldap_ltb` : `cn=config`, MDB, overlays, DIT, ACL, TLS obligatoire | Fait (2026-11-01) | L | OI-032 | Molecule vert ; recette : `ldapwhoami` en TLS, bind anonyme refusé, verrouillage ppolicy, `memberOf` à jour Vérifié sous Molecule, plus ppm (qualité) et historique contrôlés à la main. | plan § L1 | | |
| 75 | +| OI-035 | Rôle `backup` : `slapcat` chiffré (age), rotation, test de restauration automatisé | Fait (2026-11-01) | M | OI-034 | Restauration réussie dans Molecule | plan § S | | |
| 76 | +| OI-036 | `runner` : lancement d'`ansible-playbook`, callback JSON, tampon disque, flux SSE, verrou d'exécution | Fait (2026-11-01) | L | OI-020 | Tests : reconnexion sans perte ni doublon, run orphelin marqué « interrompu », secrets masqués 12 tests avec un faux Ansible ; essai avec le vrai Ansible dans OI-040. | [E-011](ihm/screens/E-011-execution.md) | | |
| 77 | +| OI-037 | E-010 Récapitulatif et vérification préalable | Fait (2026-11-01) | M | OI-036 | Checklist de la fiche cochée | [E-010](ihm/screens/E-010-recapitulatif.md) | | |
| 78 | +| OI-038 | E-011 Installation en cours | Fait (2026-11-01) | M | OI-036 | Checklist de la fiche cochée | [E-011](ihm/screens/E-011-execution.md) | | |
| 79 | +| OI-039 | E-012 Résultat et verrouillage de l'assistant | Fait (2026-11-01) | S | OI-038 | Checklist de la fiche cochée Verrou posé à la fin du run ; E-012 reste visible pour la seule session qui a lancé, jusqu'à « Terminer ». | [E-012](ihm/screens/E-012-resultat.md) | | |
| 80 | +| OI-040 | Recette de bout en bout `tests/e2e/l1-annuaire` sur une cible vierge | Fait (2026-11-02) | M | OI-023 à OI-039 | Script vert sur Debian 13 et Ubuntu 26.04 Recette verte en conteneur (D-021) sur Debian 13 (38 contrôles) et Ubuntu 26.04 (37), installation réelle pilotée par navigateur via tunnel SSH. Non couvert en conteneur : sysctl noyau, `systemd-timesyncd` (OI-905). | plan § Vérification | | |
| 81 | 81 | |
| 82 | 82 | ## M2 — Lot 1 complet |
| 83 | 83 | |
| 84 | 84 | | ID | Tâche | Statut | Taille | Dépend de | Critère de fin | Réf | |
| 85 | 85 | |----|-------|--------|--------|-----------|----------------|-----| |
| 86 | 86 | | OI-050 | Rôles `ltb_ssp`, `ltb_white_pages`, `ltb_service_desk` (nginx, php-fpm, comptes de service) | À faire | L | OI-034 | Recette : e-mail de réinitialisation SSP reçu (MailHog), recherche White Pages, déverrouillage via Service Desk | plan § L1 | |
| 87 | +| OI-029 | E-006 Messagerie et e-mail de test | À faire | M | OI-022, OI-050 | Checklist de la fiche cochée ; test avec MailHog Déplacée de M1 (D-020). | [E-006](ihm/screens/E-006-messagerie.md) | | |
| 87 | 88 | | OI-051 | Mode Docker Compose (rôle `compose`, images LTB ou Dockerfiles maison) + E-003 en mode Compose | À faire | L | OI-050, R-04 | Recette L1 verte en Compose | plan § L1 | |
| 88 | 89 | | OI-052 | Multi-hôtes SSH (E-003 avancé : clé de l'installeur, test d'un hôte, rôles par hôte) | À faire | M | OI-026 | Installation répartie sur 2 VM réussie | [E-003](ihm/screens/E-003-cibles.md) | |
| 89 | 90 | | OI-053 | Certificats ACME et certificats fournis (E-005) | À faire | M | OI-028 | Analyse des certificats fournis testée ; ACME testé sur un domaine public | [E-005](ihm/screens/E-005-securite.md) | |
| 90 | 91 | | OI-054 | Rôle `monitoring` : Prometheus, exporters, Loki et Alloy, Grafana, tableaux de bord, alertes | À faire | L | OI-034 | Tableaux de bord alimentés ; une alerte « échecs de bind » se déclenche lors d'un test de force brute | plan § T | |
| 91 | -| OI-055 | Audit : `auditlog` et `accesslog`, journaux LTB, centralisation dans Loki | À faire | M | OI-054 | Une modification LDAP est visible dans Loki | plan § A | | |
| 92 | +| OI-055 | Audit : `auditlog` et `accesslog`, journaux LTB, centralisation dans Loki | À faire | M | OI-054 | Une modification LDAP est visible dans Loki **À traiter** : en M1, seul l'échec qui déclenche le verrouillage apparaît dans `cn=accesslog` ; les échecs précédents manquent (constaté le 2026-11-01). | plan § A | | |
| 92 | 93 | | OI-056 | SBOM CycloneDX en CI, envoi à Dependency-Track, politique bloquante, artefacts signés | À faire | M | OI-008 | Une dépendance vulnérable injectée fait échouer la CI (exécutée localement par `scripts/ci.sh` en attendant OI-012) | plan § D | |
| 93 | 94 | | OI-057 | Squelette mdBook (Diátaxis) + tutoriel « Première installation » | À faire | M | OI-040 | `mdbook build` sans lien cassé ; tutoriel suivi de bout en bout par une personne extérieure | plan § H | |
| 94 | 95 | | OI-058 | Revue de sécurité OWASP de l'installeur | À faire | M | OI-040 | Aucune vulnérabilité haute ouverte | plan § S | |
@@ -163,6 +164,7 @@ Idées non planifiées. On en fait des tâches seulement par décision notée da
| 163 | 164 | | OI-902 | Fusion IAM (cité dans le README) : intégration ou alternative ? | README | |
| 164 | 165 | | OI-903 | Assistant d'installation en ligne de commande (sans navigateur) | — | |
| 165 | 166 | | OI-904 | Relier plusieurs instances Compose par le réseau (multi-hôtes en Compose) | D-011 | |
| 167 | +| OI-905 | Recette `tests/e2e/l1-annuaire` sur une VM réelle (sysctl noyau, `systemd-timesyncd`, pare-feu de l'hôte) avant la première mise en production | Ex-OI-041, D-021 | | |
| 166 | 168 | |
| 167 | 169 | ## Journal des décisions |
| 168 | 170 |
@@ -181,7 +183,10 @@ Le statut est « Validée » (par vous), « Proposée » (en attente d'arbitrage
| 181 | 183 | | D-015 | 2026-11-01 | Aucun crate non maintenu (RustSec) : `serde_norway` au lieu de `serde_yaml_ng` ; askama sans la fonction `config` (évite `basic-toml`) | Validée (technique) | |
| 182 | 184 | | D-016 | 2026-11-01 | Écoute de l'installeur limitée au loopback (port 7070) tant que TLS n'est pas livré ; accès distant par tunnel SSH | Validée (technique) | |
| 183 | 185 | | D-017 | 2026-11-01 | Largeurs maximales nommées `max-w-card/form/page` : les noms `xs`…`xl` sont réservés aux espacements de `design.md` | Validée (technique) | |
| 184 | -| D-018 | 2026-11-01 | Cibles de développement en conteneur Docker systemd (Debian 13, Ubuntu 26.04, `--privileged`, poste de dev uniquement). Une VM réelle reste obligatoire pour la recette finale (OI-040, OI-041) et pour le mode Compose (M2) | Validée | | |
| 186 | +| D-018 | 2026-11-01 | Cibles de développement en conteneur Docker systemd (Debian 13, Ubuntu 26.04, `--privileged`, poste de dev uniquement). Une VM réelle reste obligatoire pour la recette finale (OI-040, OI-041) et pour le mode Compose (M2) | Amendée par D-021 | | |
| 187 | +| D-019 | 2026-11-01 | Rôle Ansible OpenLDAP écrit pour Open IAM ; le rôle officiel LTB sert de référence mais n'est pas réutilisé (Debian 11 seulement, GPL-3.0 incompatible avec D-009, configuration régénérée d'un bloc) | Validée (technique) | | |
| 188 | +| D-021 | 2026-11-02 | La recette de sortie de M1 (OI-040) se fait sur les cibles conteneur de D-018, comme en M0. OI-041 passe en Réserve (OI-905) et redevient nécessaire avant une première mise en production | Validée | | |
| 189 | +| D-020 | 2026-11-01 | E-006 (messagerie, OI-029) passe en M2 : en M1 aucun composant installable n'envoie d'e-mail, l'étape serait toujours sautée. L'option « envoyer un lien d'initialisation » d'E-007 reste grisée en M1 | Validée (technique) | | |
| 185 | 190 | | D-008 | 2026-11-01 | Thème clair pour la v0.x ; un thème sombre est prévu plus tard (OI-901 en Réserve) | Validée | |
| 186 | 191 | | D-009 | 2026-11-01 | Pas de licence pour l'instant (champ `license` retiré de `Cargo.toml`) | Validée | |
| 187 | 192 | | D-010 | 2026-11-01 | Politique de mots de passe configurable dans l'installeur ; préréglage ANSSI proposé par défaut | Validée | |
@@ -195,11 +200,11 @@ Le statut est « Validée » (par vous), « Proposée » (en attente d'arbitrage
| 195 | 200 | |----|--------|--------|-------------|--------|-------| |
| 196 | 201 | | R-01 | La synchronisation des mots de passe vers Samba est impossible ou fragile | L4b remis en cause | Élevée | Test de faisabilité OI-120 **avant** tout développement L4b | OI-120 | |
| 197 | 202 | | R-02 | Les hachés de mots de passe AD ne sont pas récupérables | Les utilisateurs doivent réinitialiser leur mot de passe | Certaine | Pass-through `{SASL}` pendant la transition, puis campagne SSP | OI-104 | |
| 198 | -| R-03 | Paquets LTB ou LemonLDAP::NG indisponibles pour une version cible (Debian 13, Ubuntu 26.04) | Cibles réduites | Moyenne | Vérifier les dépôts au début de M1 ; restreindre les OS supportés au besoin | OI-034 | | |
| 203 | +| R-03 | Paquets LTB ou LemonLDAP::NG indisponibles pour une version cible | Cibles réduites | **Levé pour OpenLDAP** (2026-11-01 : LTB 2.6.16 installé sur Debian 13 ; dépôt `resolute` pour Ubuntu 26.04) ; reste à vérifier pour LemonLDAP::NG (M4) | Vérifier les dépôts en début de jalon | OI-034, OI-090 | | |
| 199 | 204 | | R-04 | Pas d'image Docker officielle maintenue pour certaines briques | Plus de travail sur M2 | Moyenne | Dockerfiles maison construits à partir des paquets officiels | OI-051 | |
| 200 | 205 | | R-05 | L'installeur s'exécute en root et expose une interface web | Compromission du serveur | Faible si les parades sont en place | Écoute sur 127.0.0.1, jeton à usage unique, CSP, CSRF, revue OWASP | OI-023, OI-058 | |
| 201 | 206 | | R-06 | Périmètre très large pour l'équipe disponible | Retards | Élevée | Jalons livrables indépendamment ; arbitrer la Réserve sans pitié | Revue à chaque jalon | |
| 202 | -| R-07 | Écart conteneur / machine réelle : noyau partagé (sysctl, modules, horloge), pare-feu limité au conteneur | Un défaut de durcissement passe inaperçu en dev | Moyenne | Recette finale obligatoire sur VM réelle (OI-041 → OI-040) | OI-033, OI-040 | | |
| 207 | +| R-07 | Écart conteneur / machine réelle : noyau partagé (sysctl, modules, horloge), pare-feu limité au conteneur | Un défaut de durcissement passe inaperçu en dev | Moyenne | Recette sur VM réelle avant la première mise en production (OI-905, D-021) ; en attendant, les écarts connus sont listés dans OI-040 | OI-033, OI-905 | | |
| 203 | 208 | |
| 204 | 209 | ## Questions ouvertes |
| 205 | 210 |
M
docs/ihm/screens/E-001-bienvenue.md
+1
-1
@@ -49,7 +49,7 @@ Cet écran présente ce qui va être installé et vérifie que le serveur s'y pr
| 49 | 49 | |----------|----------|-------| |
| 50 | 50 | | Système d'exploitation | Oui | Debian 13 ou Ubuntu 26.04 LTS (lu dans `/etc/os-release`) | |
| 51 | 51 | | Exécuté en root (ou sudo sans mot de passe) | Oui | — | |
| 52 | -| Ansible ≥ 2.16 | Non | Sinon : proposé à l'installation au lancement, avec avertissement | | |
| 52 | +| Ansible ≥ 2.16 | Oui | Sinon : bouton « Installer Ansible » (ansible-core des dépôts de la distribution), puis revérification. Choix explicite de l'administrateur plutôt qu'une installation silencieuse au lancement | | |
| 53 | 53 | | Docker + plugin compose | Non | Requis seulement en mode compose (revérifié en E-003) | |
| 54 | 54 | | Espace disque `/var` | Oui si < 5 Go | Avertissement si < 20 Go | |
| 55 | 55 | | Ports 80/443/389/636 libres | Non | Avertissement avec le processus qui occupe le port (`ss -ltnp`) | |
A
docs/plans/m1-premier-annuaire.md
+35
-0
@@ -0,0 +1,35 @@
| 1 | +# Plan M1 — Premier annuaire | |
| 2 | + | |
| 3 | +_Créé le 2026-11-01. Tâches : [BACKLOG.md § M1](../BACKLOG.md#m1--premier-annuaire-assistant--socle-ansible-natif-hôte-local)._ | |
| 4 | + | |
| 5 | +## Objectif | |
| 6 | + | |
| 7 | +L'assistant web, exécuté **sur le serveur cible**, installe un OpenLDAP LTB durci sur ce même serveur, en mode natif. Critère de sortie : parcours E-000 → E-012 complet sur une machine vierge, et recette `tests/e2e/l1-annuaire` verte. | |
| 8 | + | |
| 9 | +## Constats préalables (2026-11-01) | |
| 10 | + | |
| 11 | +- **R-03 levé** : LTB publie OpenLDAP 2.6 (2.6.16) pour `trixie` (Debian 13) et `resolute` (Ubuntu 26.04). Dépôt `https://ltb-project.org/debian/openldap26/<codename>`, clé `ltb-project-debian-keyring.gpg` (renouvelée en août 2025). | |
| 12 | +- Installation testée sur la cible Debian : paquets `openldap-ltb`, `openldap-ltb-contrib-overlays`, `openldap-ltb-mdb-utils` ; préfixe `/usr/local/openldap` ; service `slapd-ltb.service` ; utilisateur `ldap` ; configuration `etc/openldap/slapd.d` ; socket `ldapi:///var/run/slapd/ldapi`. | |
| 13 | +- Modules disponibles : `ppolicy`, `memberof`, `refint`, `unique`, `dynlist`, `accesslog`, `auditlog`, `syncprov`, `argon2`, `ppm.so`… `lastbind` est intégré au cœur en 2.6 (`olcLastBind`). | |
| 14 | +- Rôle Ansible officiel LTB (`ansible-role-ldaptoolbox-openldap`) : non réutilisé (D-019), sert de référence. | |
| 15 | + | |
| 16 | +## Architecture retenue | |
| 17 | + | |
| 18 | +| Sujet | Choix | | |
| 19 | +|-------|-------| | |
| 20 | +| Où tourne l'installeur | Sur le serveur cible, en root. Accès distant par tunnel SSH (D-016). En dev : dans le conteneur cible, via `ssh -L 7070:127.0.0.1:7070 -p 2222 root@127.0.0.1` | | |
| 21 | +| Connexion Ansible | `ansible_connection: local` pour l'hôte local (seul cas de M1) | | |
| 22 | +| Contenu Ansible | Embarqué dans le binaire, extrait dans `/var/lib/open-iam/ansible/<version>/` avant chaque exécution | | |
| 23 | +| État de l'installeur | `/var/lib/open-iam/` (0700) : `draft.yaml`, `draft-secrets.yaml` (0600), `executions/<id>/`, `installed.lock`. Racine configurable (`--etat`) pour les tests | | |
| 24 | +| Secrets | Jamais dans `openiam.yaml`. Pour une exécution : `secrets.yml` chiffré par `ansible-vault`, mot de passe de coffre aléatoire dans `vault.pass` (0600) | | |
| 25 | +| Ansible requis sur la cible | `ansible-core` des dépôts de la distribution (Debian 13 : 2.19) ; E-001 propose de l'installer s'il manque | | |
| 26 | + | |
| 27 | +## Tranches | |
| 28 | + | |
| 29 | +| Tranche | Tâches | Livrable vérifiable | | |
| 30 | +|---------|--------|---------------------| | |
| 31 | +| A. Domaine | OI-020, OI-021, OI-022 | `config`, `catalogue`, `brouillon` testés unitairement | | |
| 32 | +| B. Ansible | OI-032 → OI-035 | Rôles verts sous Molecule (Debian 13, Ubuntu 26.04), idempotents | | |
| 33 | +| C. Exécution | OI-036 | `runner` testé avec un faux `ansible-playbook` | | |
| 34 | +| D. Écrans | OI-023 → OI-031, OI-037 → OI-039 | Checklists des fiches, tests d'intégration et navigateur | | |
| 35 | +| E. Recette | OI-040 | `tests/e2e/l1-annuaire` vert sur les deux cibles conteneur (D-021) ; la recette sur VM réelle est en Réserve (OI-905) | |
M
installer/Cargo.toml
+7
-2
@@ -6,15 +6,19 @@ edition.workspace = true
| 6 | 6 | |
| 7 | 7 | [dependencies] |
| 8 | 8 | askama = { version = "0.16.1", default-features = false, features = ["derive", "std"] } |
| 9 | -axum = "0.8.9" | |
| 9 | +axum = { version = "0.8.9", features = ["multipart"] } | |
| 10 | 10 | clap = { version = "4.6.7", features = ["derive"] } |
| 11 | +form_urlencoded = "1.2.2" | |
| 12 | +idna = "1.1.0" | |
| 13 | +jiff = "0.2.38" | |
| 11 | 14 | rand = "0.10.3" |
| 12 | 15 | rust-embed = { version = "8.13.0", features = ["include-exclude", "mime-guess"] } |
| 13 | 16 | serde = { version = "1.0.229", features = ["derive"] } |
| 14 | 17 | serde_json = "1.0.154" |
| 15 | 18 | serde_norway = "0.9.42" |
| 16 | 19 | thiserror = "2.0.21" |
| 17 | -tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "net", "signal"] } | |
| 20 | +tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "net", "signal", "process", "io-util", "sync", "time", "fs"] } | |
| 21 | +tokio-stream = { version = "0.1.19", features = ["sync"] } | |
| 18 | 22 | tower-http = { version = "0.7.1", features = ["set-header", "trace"] } |
| 19 | 23 | tower-sessions = "0.15.0" |
| 20 | 24 | tracing = "0.1.44" |
@@ -27,4 +31,5 @@ thiserror = "2.0.21"
| 27 | 31 | |
| 28 | 32 | [dev-dependencies] |
| 29 | 33 | http-body-util = "0.1.5" |
| 34 | +tempfile = "3.27.0" | |
| 30 | 35 | tower = { version = "0.5.3", features = ["util"] } |
A
installer/src/acces.rs
+101
-0
@@ -0,0 +1,101 @@
| 1 | +//! Jeton d'accès à l'assistant (E-000) : 32 octets aléatoires en base32, usage unique, | |
| 2 | +//! valable 30 minutes. Stocké dans `<état>/jeton` (0600) pour que `open-iam-installer | |
| 3 | +//! nouveau-jeton` puisse en émettre un pendant que le serveur tourne. | |
| 4 | + | |
| 5 | +use std::{ | |
| 6 | + fs, | |
| 7 | + path::Path, | |
| 8 | + time::{Duration, SystemTime, UNIX_EPOCH}, | |
| 9 | +}; | |
| 10 | + | |
| 11 | +use crate::brouillon::ecrire_0600; | |
| 12 | + | |
| 13 | +pub const DUREE_VALIDITE: Duration = Duration::from_secs(30 * 60); | |
| 14 | +const FICHIER: &str = "jeton"; | |
| 15 | +const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; | |
| 16 | + | |
| 17 | +#[derive(Debug, PartialEq, Eq)] | |
| 18 | +pub enum Refus { | |
| 19 | + /// Jeton absent, déjà utilisé, erroné ou expiré : un seul message pour ne rien révéler. | |
| 20 | + Invalide, | |
| 21 | +} | |
| 22 | + | |
| 23 | +/// Émet un nouveau jeton (remplace le précédent) et le renvoie. | |
| 24 | +pub fn generer(etat: &Path) -> std::io::Result<String> { | |
| 25 | + fs::create_dir_all(etat)?; | |
| 26 | + let jeton = base32(&rand::random::<[u8; 32]>()); | |
| 27 | + let expire = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default() + DUREE_VALIDITE; | |
| 28 | + ecrire_0600(&etat.join(FICHIER), &format!("{}\n{jeton}\n", expire.as_secs()))?; | |
| 29 | + Ok(jeton) | |
| 30 | +} | |
| 31 | + | |
| 32 | +/// Vérifie le jeton et le consomme en cas de succès. | |
| 33 | +pub fn consommer(etat: &Path, saisi: &str) -> Result<(), Refus> { | |
| 34 | + let chemin = etat.join(FICHIER); | |
| 35 | + let contenu = fs::read_to_string(&chemin).map_err(|_| Refus::Invalide)?; | |
| 36 | + let mut lignes = contenu.lines(); | |
| 37 | + let expire: u64 = lignes.next().and_then(|l| l.parse().ok()).ok_or(Refus::Invalide)?; | |
| 38 | + let attendu = lignes.next().ok_or(Refus::Invalide)?; | |
| 39 | + let maintenant = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(); | |
| 40 | + let saisi = saisi.trim().to_ascii_uppercase(); | |
| 41 | + if maintenant > expire || !egal_temps_constant(saisi.as_bytes(), attendu.as_bytes()) { | |
| 42 | + return Err(Refus::Invalide); | |
| 43 | + } | |
| 44 | + fs::remove_file(&chemin).map_err(|_| Refus::Invalide) | |
| 45 | +} | |
| 46 | + | |
| 47 | +/// Avance l'horloge du jeton de `secondes` (tests d'expiration). | |
| 48 | +pub fn vieillir(etat: &Path, secondes: u64) -> std::io::Result<()> { | |
| 49 | + let chemin = etat.join(FICHIER); | |
| 50 | + let contenu = fs::read_to_string(&chemin)?; | |
| 51 | + let (expire, reste) = contenu.split_once('\n').unwrap_or((&contenu, "")); | |
| 52 | + let expire: u64 = expire.parse().unwrap_or(0); | |
| 53 | + ecrire_0600(&chemin, &format!("{}\n{reste}", expire.saturating_sub(secondes))) | |
| 54 | +} | |
| 55 | + | |
| 56 | +fn base32(octets: &[u8]) -> String { | |
| 57 | + let mut sortie = String::new(); | |
| 58 | + let (mut tampon, mut bits) = (0u32, 0u32); | |
| 59 | + for octet in octets { | |
| 60 | + tampon = (tampon << 8) | u32::from(*octet); | |
| 61 | + bits += 8; | |
| 62 | + while bits >= 5 { | |
| 63 | + bits -= 5; | |
| 64 | + sortie.push(ALPHABET[((tampon >> bits) & 31) as usize] as char); | |
| 65 | + } | |
| 66 | + } | |
| 67 | + if bits > 0 { | |
| 68 | + sortie.push(ALPHABET[((tampon << (5 - bits)) & 31) as usize] as char); | |
| 69 | + } | |
| 70 | + sortie | |
| 71 | +} | |
| 72 | + | |
| 73 | +pub(crate) fn egal_temps_constant(a: &[u8], b: &[u8]) -> bool { | |
| 74 | + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 | |
| 75 | +} | |
| 76 | + | |
| 77 | +#[cfg(test)] | |
| 78 | +mod tests { | |
| 79 | + use super::*; | |
| 80 | + | |
| 81 | + #[test] | |
| 82 | + fn un_jeton_fait_52_caracteres_base32() { | |
| 83 | + let dossier = tempfile::tempdir().unwrap(); | |
| 84 | + let jeton = generer(dossier.path()).unwrap(); | |
| 85 | + assert_eq!(jeton.len(), 52); | |
| 86 | + assert!(jeton.bytes().all(|c| ALPHABET.contains(&c))); | |
| 87 | + } | |
| 88 | + | |
| 89 | + #[test] | |
| 90 | + fn le_jeton_est_insensible_a_la_casse_et_aux_espaces() { | |
| 91 | + let dossier = tempfile::tempdir().unwrap(); | |
| 92 | + let jeton = generer(dossier.path()).unwrap(); | |
| 93 | + assert_eq!(consommer(dossier.path(), &format!(" {} ", jeton.to_lowercase())), Ok(())); | |
| 94 | + assert_eq!(consommer(dossier.path(), &jeton), Err(Refus::Invalide), "usage unique"); | |
| 95 | + } | |
| 96 | + | |
| 97 | + #[test] | |
| 98 | + fn base32_suit_la_rfc_4648() { | |
| 99 | + assert_eq!(base32(b"foobar"), "MZXW6YTBOI"); | |
| 100 | + } | |
| 101 | +} |
A
installer/src/assistant/acces.rs
+109
-0
@@ -0,0 +1,109 @@
| 1 | +//! E-000 Accès par jeton et E-092 Assistant verrouillé. | |
| 2 | + | |
| 3 | +use askama::Template; | |
| 4 | +use axum::{ | |
| 5 | + Form, | |
| 6 | + extract::{Query, State}, | |
| 7 | + http::{HeaderMap, StatusCode}, | |
| 8 | + response::{Html, IntoResponse, Redirect, Response}, | |
| 9 | +}; | |
| 10 | +use serde::Deserialize; | |
| 11 | +use tower_sessions::Session; | |
| 12 | + | |
| 13 | +use super::{Partage, SESSION_ASSISTANT, rediriger}; | |
| 14 | +use crate::{acces, errors::AppError, pages::Layout}; | |
| 15 | + | |
| 16 | +#[derive(Template)] | |
| 17 | +#[template(path = "assistant/acces.html")] | |
| 18 | +struct Page { | |
| 19 | + layout: Layout, | |
| 20 | + formulaire: Formulaire, | |
| 21 | +} | |
| 22 | + | |
| 23 | +#[derive(Template)] | |
| 24 | +#[template(path = "assistant/acces_formulaire.html")] | |
| 25 | +struct Formulaire { | |
| 26 | + erreur: Option<String>, | |
| 27 | + attente: Option<u64>, | |
| 28 | +} | |
| 29 | + | |
| 30 | +#[derive(Template)] | |
| 31 | +#[template(path = "assistant/verrouille.html")] | |
| 32 | +struct Verrouille { | |
| 33 | + layout: Layout, | |
| 34 | +} | |
| 35 | + | |
| 36 | +const MESSAGE_INVALIDE: &str = "Ce jeton n'est plus valide. Relancez « open-iam-installer nouveau-jeton » sur le serveur pour en obtenir un autre."; | |
| 37 | + | |
| 38 | +#[derive(Deserialize)] | |
| 39 | +pub struct Parametres { | |
| 40 | + jeton: Option<String>, | |
| 41 | +} | |
| 42 | + | |
| 43 | +pub async fn page( | |
| 44 | + State(etat): State<Partage>, | |
| 45 | + session: Session, | |
| 46 | + Query(parametres): Query<Parametres>, | |
| 47 | +) -> Result<Response, AppError> { | |
| 48 | + if etat.installe() { | |
| 49 | + return Ok(Redirect::to("/verrouille").into_response()); | |
| 50 | + } | |
| 51 | + let mut erreur = None; | |
| 52 | + if let Some(jeton) = parametres.jeton { | |
| 53 | + match acces::consommer(&etat.parametres.etat, &jeton) { | |
| 54 | + Ok(()) => { | |
| 55 | + ouvrir_session(&session).await?; | |
| 56 | + return Ok(Redirect::to("/install").into_response()); | |
| 57 | + } | |
| 58 | + Err(_) => { | |
| 59 | + etat.noter_echec_acces(); | |
| 60 | + erreur = Some(MESSAGE_INVALIDE.to_owned()); | |
| 61 | + } | |
| 62 | + } | |
| 63 | + } | |
| 64 | + let formulaire = Formulaire { erreur, attente: etat.attente_acces() }; | |
| 65 | + Ok(Html(Page { layout: Layout::new(&session).await?, formulaire }.render()?).into_response()) | |
| 66 | +} | |
| 67 | + | |
| 68 | +#[derive(Deserialize)] | |
| 69 | +pub struct Saisie { | |
| 70 | + jeton: String, | |
| 71 | +} | |
| 72 | + | |
| 73 | +pub async fn valider( | |
| 74 | + State(etat): State<Partage>, | |
| 75 | + session: Session, | |
| 76 | + entetes: HeaderMap, | |
| 77 | + Form(saisie): Form<Saisie>, | |
| 78 | +) -> Result<Response, AppError> { | |
| 79 | + if etat.installe() { | |
| 80 | + return Ok(rediriger(&entetes, "/verrouille", StatusCode::SEE_OTHER)); | |
| 81 | + } | |
| 82 | + if let Some(attente) = etat.attente_acces() { | |
| 83 | + let formulaire = Formulaire { erreur: Some("Trop de tentatives.".into()), attente: Some(attente) }; | |
| 84 | + return Ok((StatusCode::TOO_MANY_REQUESTS, Html(formulaire.render()?)).into_response()); | |
| 85 | + } | |
| 86 | + match acces::consommer(&etat.parametres.etat, &saisie.jeton) { | |
| 87 | + Ok(()) => { | |
| 88 | + ouvrir_session(&session).await?; | |
| 89 | + Ok(rediriger(&entetes, "/install", StatusCode::NO_CONTENT)) | |
| 90 | + } | |
| 91 | + Err(_) => { | |
| 92 | + etat.noter_echec_acces(); | |
| 93 | + let formulaire = | |
| 94 | + Formulaire { erreur: Some(MESSAGE_INVALIDE.into()), attente: etat.attente_acces() }; | |
| 95 | + Ok((StatusCode::UNPROCESSABLE_ENTITY, Html(formulaire.render()?)).into_response()) | |
| 96 | + } | |
| 97 | + } | |
| 98 | +} | |
| 99 | + | |
| 100 | +/// Nouvel identifiant de session après l'accès (pas de fixation de session). | |
| 101 | +async fn ouvrir_session(session: &Session) -> Result<(), AppError> { | |
| 102 | + session.cycle_id().await?; | |
| 103 | + session.insert(SESSION_ASSISTANT, true).await?; | |
| 104 | + Ok(()) | |
| 105 | +} | |
| 106 | + | |
| 107 | +pub async fn verrouille(session: Session) -> Result<Html<String>, AppError> { | |
| 108 | + Ok(Html(Verrouille { layout: Layout::new(&session).await? }.render()?)) | |
| 109 | +} |
A
installer/src/assistant/bienvenue.rs
+143
-0
@@ -0,0 +1,143 @@
| 1 | +//! E-001 Bienvenue : prérequis, reprise ou suppression du brouillon, import d'un openiam.yaml. | |
| 2 | + | |
| 3 | +use askama::Template; | |
| 4 | +use axum::{ | |
| 5 | + extract::{Multipart, State}, | |
| 6 | + http::{HeaderMap, HeaderValue, StatusCode}, | |
| 7 | + response::{Html, IntoResponse, Response}, | |
| 8 | +}; | |
| 9 | +use tower_sessions::Session; | |
| 10 | + | |
| 11 | +use super::{ | |
| 12 | + Partage, | |
| 13 | + commun::{URL_RECAPITULATIF, charger, invalide}, | |
| 14 | + rediriger_vers, | |
| 15 | +}; | |
| 16 | +use crate::{ | |
| 17 | + brouillon::{Brouillon, Etape}, | |
| 18 | + config::{Gravite, OpenIamConfig, Secrets}, | |
| 19 | + errors::{AppError, notify}, | |
| 20 | + pages::Layout, | |
| 21 | + prerequis::{self, Controle}, | |
| 22 | +}; | |
| 23 | + | |
| 24 | +/// Taille maximale d'un openiam.yaml importé. | |
| 25 | +const TAILLE_IMPORT: usize = 1024 * 1024; | |
| 26 | + | |
| 27 | +#[derive(Template)] | |
| 28 | +#[template(path = "assistant/bienvenue.html")] | |
| 29 | +struct Page { | |
| 30 | + layout: Layout, | |
| 31 | + reprise: Option<Reprise>, | |
| 32 | +} | |
| 33 | + | |
| 34 | +struct Reprise { | |
| 35 | + organisation: String, | |
| 36 | + modifie_le: String, | |
| 37 | + url: &'static str, | |
| 38 | +} | |
| 39 | + | |
| 40 | +#[derive(Template)] | |
| 41 | +#[template(path = "assistant/prerequis.html")] | |
| 42 | +struct Prerequis { | |
| 43 | + controles: Vec<Controle>, | |
| 44 | + bloquant: bool, | |
| 45 | + ansible_absent: bool, | |
| 46 | + message: Option<String>, | |
| 47 | +} | |
| 48 | + | |
| 49 | +#[derive(Template)] | |
| 50 | +#[template(path = "assistant/import_erreurs.html")] | |
| 51 | +struct ErreursImport { | |
| 52 | + erreurs: Vec<String>, | |
| 53 | +} | |
| 54 | + | |
| 55 | +pub async fn page(State(etat): State<Partage>, session: Session) -> Result<Html<String>, AppError> { | |
| 56 | + let reprise = etat.depot.charger()?.map(|(brouillon, _)| Reprise { | |
| 57 | + organisation: brouillon.organisation.as_ref().map_or("votre organisation".into(), |o| o.nom.clone()), | |
| 58 | + modifie_le: etat | |
| 59 | + .depot | |
| 60 | + .modifie_le() | |
| 61 | + .and_then(|t| jiff::Timestamp::try_from(t).ok()) | |
| 62 | + .map(|t| t.to_zoned(jiff::tz::TimeZone::system()).strftime("%d/%m/%Y à %H:%M").to_string()) | |
| 63 | + .unwrap_or_default(), | |
| 64 | + url: brouillon.etape_courante().map_or(URL_RECAPITULATIF, Etape::url), | |
| 65 | + }); | |
| 66 | + Ok(Html(Page { layout: Layout::new(&session).await?, reprise }.render()?)) | |
| 67 | +} | |
| 68 | + | |
| 69 | +async fn rendre_prerequis(etat: &Partage, message: Option<String>) -> Result<Html<String>, AppError> { | |
| 70 | + let controles = prerequis::verifier(etat.parametres.prerequis_simules).await; | |
| 71 | + let ansible_absent = | |
| 72 | + controles.iter().any(|c| c.cle == "ansible" && c.niveau == prerequis::Niveau::Bloquant); | |
| 73 | + let bloquant = prerequis::bloquant(&controles); | |
| 74 | + Ok(Html(Prerequis { controles, bloquant, ansible_absent, message }.render()?)) | |
| 75 | +} | |
| 76 | + | |
| 77 | +pub async fn controles(State(etat): State<Partage>) -> Result<Html<String>, AppError> { | |
| 78 | + rendre_prerequis(&etat, None).await | |
| 79 | +} | |
| 80 | + | |
| 81 | +/// Installe ansible-core (bouton de E-001), puis renvoie les prérequis à jour. | |
| 82 | +pub async fn installer_ansible(State(etat): State<Partage>) -> Result<Html<String>, AppError> { | |
| 83 | + let message = if etat.parametres.prerequis_simules { | |
| 84 | + None | |
| 85 | + } else { | |
| 86 | + prerequis::installer_ansible().await.err().map(|e| format!("Installation d'Ansible impossible : {e}")) | |
| 87 | + }; | |
| 88 | + rendre_prerequis(&etat, message).await | |
| 89 | +} | |
| 90 | + | |
| 91 | +pub async fn commencer(State(etat): State<Partage>, entetes: HeaderMap) -> Result<Response, AppError> { | |
| 92 | + let (brouillon, secrets) = charger(&etat)?; | |
| 93 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 94 | + let cible = brouillon.etape_courante().map_or(URL_RECAPITULATIF, Etape::url); | |
| 95 | + Ok(rediriger_vers(&entetes, cible, StatusCode::NO_CONTENT)) | |
| 96 | +} | |
| 97 | + | |
| 98 | +pub async fn supprimer(State(etat): State<Partage>) -> Result<Response, AppError> { | |
| 99 | + etat.depot.supprimer()?; | |
| 100 | + let mut res = (StatusCode::OK, notify("success", "Brouillon supprimé.")).into_response(); | |
| 101 | + res.headers_mut().insert("hx-refresh", HeaderValue::from_static("true")); | |
| 102 | + Ok(res) | |
| 103 | +} | |
| 104 | + | |
| 105 | +pub async fn importer( | |
| 106 | + State(etat): State<Partage>, | |
| 107 | + entetes: HeaderMap, | |
| 108 | + mut multipart: Multipart, | |
| 109 | +) -> Result<Response, AppError> { | |
| 110 | + let refus = |erreurs: Vec<String>| -> Result<Response, AppError> { | |
| 111 | + Ok(invalide(ErreursImport { erreurs }.render()?)) | |
| 112 | + }; | |
| 113 | + let mut contenu = None; | |
| 114 | + while let Ok(Some(champ)) = multipart.next_field().await { | |
| 115 | + if champ.name() == Some("fichier") { | |
| 116 | + match champ.bytes().await { | |
| 117 | + Ok(octets) if octets.len() <= TAILLE_IMPORT => contenu = Some(octets), | |
| 118 | + _ => return refus(vec!["Le fichier dépasse 1 Mo.".into()]), | |
| 119 | + } | |
| 120 | + } | |
| 121 | + } | |
| 122 | + let Some(texte) = contenu.and_then(|o| String::from_utf8(o.to_vec()).ok()) else { | |
| 123 | + return refus(vec!["Choisissez un fichier openiam.yaml (texte UTF-8).".into()]); | |
| 124 | + }; | |
| 125 | + let config = match OpenIamConfig::depuis_yaml(&texte) { | |
| 126 | + Ok(config) => config, | |
| 127 | + Err(erreur) => return refus(vec![erreur.to_string()]), | |
| 128 | + }; | |
| 129 | + let erreurs: Vec<String> = config | |
| 130 | + .valider_avec(&etat.parametres.zoneinfo) | |
| 131 | + .into_iter() | |
| 132 | + .filter(|c| c.gravite == Gravite::Erreur) | |
| 133 | + .map(|c| format!("{} : {}", c.chemin, c.message)) | |
| 134 | + .collect(); | |
| 135 | + if !erreurs.is_empty() { | |
| 136 | + return refus(erreurs); | |
| 137 | + } | |
| 138 | + let mut brouillon = Brouillon::depuis_config(config); | |
| 139 | + // Les mots de passe ne sont jamais dans openiam.yaml : ils restent à saisir. | |
| 140 | + brouillon.a_revoir.insert(Etape::Comptes); | |
| 141 | + etat.depot.sauver(&brouillon, &Secrets::default())?; | |
| 142 | + Ok(rediriger_vers(&entetes, URL_RECAPITULATIF, StatusCode::NO_CONTENT)) | |
| 143 | +} |
A
installer/src/assistant/commun.rs
+172
-0
@@ -0,0 +1,172 @@
| 1 | +//! Éléments communs des étapes : stepper (C-011), accès aux étapes, erreurs par champ, | |
| 2 | +//! enchaînement vers l'étape suivante ou le récapitulatif. | |
| 3 | + | |
| 4 | +use std::collections::BTreeMap; | |
| 5 | + | |
| 6 | +use askama::Template; | |
| 7 | +use axum::{ | |
| 8 | + http::{HeaderMap, StatusCode}, | |
| 9 | + response::{Html, IntoResponse, Response}, | |
| 10 | +}; | |
| 11 | +use serde::Deserialize; | |
| 12 | +use tower_sessions::Session; | |
| 13 | + | |
| 14 | +use super::{Partage, rediriger_vers}; | |
| 15 | +use crate::{ | |
| 16 | + brouillon::{Brouillon, Etape, EtatEtape}, | |
| 17 | + config::{Constat, Gravite, Secrets}, | |
| 18 | + errors::AppError, | |
| 19 | + pages::Layout, | |
| 20 | +}; | |
| 21 | + | |
| 22 | +pub const URL_RECAPITULATIF: &str = "/install/recapitulatif"; | |
| 23 | + | |
| 24 | +/// Étape telle qu'affichée par le stepper. | |
| 25 | +pub struct EtapeVue { | |
| 26 | + pub libelle: &'static str, | |
| 27 | + pub url: &'static str, | |
| 28 | + pub etat: &'static str, | |
| 29 | +} | |
| 30 | + | |
| 31 | +/// Cadre commun d'une page d'étape : layout, stepper, nom de l'organisation. | |
| 32 | +pub struct Cadre { | |
| 33 | + pub layout: Layout, | |
| 34 | + pub etapes: Vec<EtapeVue>, | |
| 35 | + pub courante: usize, | |
| 36 | + pub organisation: Option<String>, | |
| 37 | +} | |
| 38 | + | |
| 39 | +impl Cadre { | |
| 40 | + /// `affichee` : étape de la page, `None` pour le récapitulatif. | |
| 41 | + pub async fn new( | |
| 42 | + session: &Session, | |
| 43 | + brouillon: &Brouillon, | |
| 44 | + affichee: Option<Etape>, | |
| 45 | + ) -> Result<Self, AppError> { | |
| 46 | + let mut etapes: Vec<EtapeVue> = brouillon | |
| 47 | + .etats() | |
| 48 | + .into_iter() | |
| 49 | + .map(|(e, etat)| EtapeVue { libelle: e.libelle(), url: e.url(), etat: etat.code() }) | |
| 50 | + .collect(); | |
| 51 | + let recapitulatif = | |
| 52 | + if brouillon.etape_courante().is_none() { EtatEtape::EnCours } else { EtatEtape::AFaire }; | |
| 53 | + etapes.push(EtapeVue { | |
| 54 | + libelle: "Récapitulatif", | |
| 55 | + url: URL_RECAPITULATIF, | |
| 56 | + etat: recapitulatif.code(), | |
| 57 | + }); | |
| 58 | + let courante = | |
| 59 | + affichee.and_then(|e| Etape::TOUTES.iter().position(|x| *x == e)).unwrap_or(etapes.len() - 1); | |
| 60 | + Ok(Self { | |
| 61 | + layout: Layout::new(session).await?, | |
| 62 | + etapes, | |
| 63 | + courante, | |
| 64 | + organisation: brouillon.organisation.as_ref().map(|o| o.nom.clone()), | |
| 65 | + }) | |
| 66 | + } | |
| 67 | +} | |
| 68 | + | |
| 69 | +/// Page d'étape générique : le formulaire est rendu à part (il sert aussi aux réponses 422). | |
| 70 | +#[derive(Template)] | |
| 71 | +#[template(path = "assistant/etape.html")] | |
| 72 | +pub struct PageEtape { | |
| 73 | + pub layout: Layout, | |
| 74 | + pub etapes: Vec<EtapeVue>, | |
| 75 | + pub courante: usize, | |
| 76 | + pub organisation: Option<String>, | |
| 77 | + pub titre: &'static str, | |
| 78 | + pub intro: &'static str, | |
| 79 | + pub formulaire: String, | |
| 80 | +} | |
| 81 | + | |
| 82 | +/// Erreurs et avertissements indexés par nom de champ (dernier segment du chemin YAML). | |
| 83 | +#[derive(Debug, Default)] | |
| 84 | +pub struct Erreurs { | |
| 85 | + erreurs: BTreeMap<String, String>, | |
| 86 | + avertissements: BTreeMap<String, String>, | |
| 87 | +} | |
| 88 | + | |
| 89 | +impl Erreurs { | |
| 90 | + pub fn depuis(constats: impl IntoIterator<Item = Constat>) -> Self { | |
| 91 | + let mut resultat = Self::default(); | |
| 92 | + for constat in constats { | |
| 93 | + let champ = constat.chemin.rsplit('.').next().unwrap_or(&constat.chemin); | |
| 94 | + let champ = champ.split('[').next().unwrap_or(champ).to_owned(); | |
| 95 | + let cible = match constat.gravite { | |
| 96 | + Gravite::Erreur => &mut resultat.erreurs, | |
| 97 | + Gravite::Avertissement => &mut resultat.avertissements, | |
| 98 | + }; | |
| 99 | + cible.entry(champ).or_insert(constat.message); | |
| 100 | + } | |
| 101 | + resultat | |
| 102 | + } | |
| 103 | + | |
| 104 | + pub fn ajouter(&mut self, champ: &str, message: impl Into<String>) { | |
| 105 | + self.erreurs.entry(champ.to_owned()).or_insert_with(|| message.into()); | |
| 106 | + } | |
| 107 | + | |
| 108 | + pub fn get(&self, champ: &str) -> Option<&str> { | |
| 109 | + self.erreurs.get(champ).map(String::as_str) | |
| 110 | + } | |
| 111 | + | |
| 112 | + pub fn avertissement(&self, champ: &str) -> Option<&str> { | |
| 113 | + self.avertissements.get(champ).map(String::as_str) | |
| 114 | + } | |
| 115 | + | |
| 116 | + pub fn bloquantes(&self) -> bool { | |
| 117 | + !self.erreurs.is_empty() | |
| 118 | + } | |
| 119 | + | |
| 120 | + pub fn nombre(&self) -> usize { | |
| 121 | + self.erreurs.len() | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +/// Paramètre `?retour=recapitulatif` des liens « Modifier » de E-010. | |
| 126 | +#[derive(Deserialize, Default)] | |
| 127 | +pub struct Retour { | |
| 128 | + pub retour: Option<String>, | |
| 129 | +} | |
| 130 | + | |
| 131 | +pub fn charger(etat: &Partage) -> Result<(Brouillon, Secrets), AppError> { | |
| 132 | + Ok(etat.depot.charger()?.unwrap_or_default()) | |
| 133 | +} | |
| 134 | + | |
| 135 | +/// Si l'étape n'est pas accessible, redirige vers l'étape à compléter. | |
| 136 | +pub fn acces_etape(brouillon: &Brouillon, etape: Etape, entetes: &HeaderMap) -> Option<Response> { | |
| 137 | + (!brouillon.peut_acceder(etape)).then(|| { | |
| 138 | + let cible = brouillon.etape_courante().map_or(URL_RECAPITULATIF, Etape::url); | |
| 139 | + rediriger_vers(entetes, cible, StatusCode::SEE_OTHER) | |
| 140 | + }) | |
| 141 | +} | |
| 142 | + | |
| 143 | +/// Après validation d'une étape : étape suivante, ou récapitulatif (fin ou retour demandé). | |
| 144 | +pub fn apres_validation( | |
| 145 | + brouillon: &Brouillon, | |
| 146 | + etape: Etape, | |
| 147 | + retour: &Retour, | |
| 148 | + entetes: &HeaderMap, | |
| 149 | +) -> Response { | |
| 150 | + let cible = if retour.retour.as_deref() == Some("recapitulatif") { | |
| 151 | + URL_RECAPITULATIF | |
| 152 | + } else { | |
| 153 | + brouillon.suivante(etape).map_or(URL_RECAPITULATIF, Etape::url) | |
| 154 | + }; | |
| 155 | + rediriger_vers(entetes, cible, StatusCode::NO_CONTENT) | |
| 156 | +} | |
| 157 | + | |
| 158 | +/// Réponse 422 : le formulaire avec ses erreurs. | |
| 159 | +pub fn invalide(formulaire: String) -> Response { | |
| 160 | + (StatusCode::UNPROCESSABLE_ENTITY, Html(formulaire)).into_response() | |
| 161 | +} | |
| 162 | + | |
| 163 | +pub fn page( | |
| 164 | + cadre: Cadre, | |
| 165 | + titre: &'static str, | |
| 166 | + intro: &'static str, | |
| 167 | + formulaire: String, | |
| 168 | +) -> Result<Response, AppError> { | |
| 169 | + let Cadre { layout, etapes, courante, organisation } = cadre; | |
| 170 | + Ok(Html(PageEtape { layout, etapes, courante, organisation, titre, intro, formulaire }.render()?) | |
| 171 | + .into_response()) | |
| 172 | +} |
A
installer/src/assistant/etapes.rs
+845
-0
@@ -0,0 +1,845 @@
| 1 | +//! Étapes E-002 à E-008 (E-006 Messagerie : M2, D-020). | |
| 2 | + | |
| 3 | +use std::collections::{BTreeMap, BTreeSet}; | |
| 4 | + | |
| 5 | +use askama::Template; | |
| 6 | +use axum::{ | |
| 7 | + Form, | |
| 8 | + extract::{Query, RawForm, State}, | |
| 9 | + http::HeaderMap, | |
| 10 | + response::{Html, IntoResponse, Response}, | |
| 11 | +}; | |
| 12 | +use serde::Deserialize; | |
| 13 | +use tower_sessions::Session; | |
| 14 | + | |
| 15 | +use super::{ | |
| 16 | + Partage, | |
| 17 | + commun::{Cadre, Erreurs, Retour, acces_etape, apres_validation, charger, invalide, page}, | |
| 18 | +}; | |
| 19 | +use crate::{ | |
| 20 | + brouillon::{Brouillon, Etape, Exploitation, Securite}, | |
| 21 | + catalogue::{self, ComposantId, Disponibilite}, | |
| 22 | + config::{ | |
| 23 | + AdminInitial, Deploiement, Langue, Mfa, Mode, ModeMdp, Organisation, PolitiqueMdp, Secret, Service, | |
| 24 | + Tls, TlsMode, Topologie, validation, | |
| 25 | + }, | |
| 26 | + errors::AppError, | |
| 27 | + telemetrie, | |
| 28 | +}; | |
| 29 | + | |
| 30 | +/// Adresse de soumission d'une étape, en conservant `?retour=recapitulatif`. | |
| 31 | +fn action(etape: Etape, retour: &Retour) -> String { | |
| 32 | + match retour.retour.as_deref() { | |
| 33 | + Some("recapitulatif") => format!("{}?retour=recapitulatif", etape.url()), | |
| 34 | + _ => etape.url().to_owned(), | |
| 35 | + } | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// Étape précédente applicable (bouton « Précédent »), ou l'accueil de l'assistant. | |
| 39 | +fn precedente(brouillon: &Brouillon, etape: Etape) -> &'static str { | |
| 40 | + Etape::TOUTES | |
| 41 | + .into_iter() | |
| 42 | + .rev() | |
| 43 | + .find(|e| *e < etape && brouillon.applicable(*e)) | |
| 44 | + .map_or("/install", Etape::url) | |
| 45 | +} | |
| 46 | + | |
| 47 | +// ================================ E-002 Organisation =================================== | |
| 48 | + | |
| 49 | +#[derive(Template)] | |
| 50 | +#[template(path = "assistant/organisation.html")] | |
| 51 | +struct FormOrganisation { | |
| 52 | + action: String, | |
| 53 | + precedent: &'static str, | |
| 54 | + nom: String, | |
| 55 | + domaine: String, | |
| 56 | + base_dn: String, | |
| 57 | + personnaliser: bool, | |
| 58 | + langue: String, | |
| 59 | + fuseau: String, | |
| 60 | + erreurs: Erreurs, | |
| 61 | +} | |
| 62 | + | |
| 63 | +#[derive(Template)] | |
| 64 | +#[template(path = "assistant/champ_domaine.html")] | |
| 65 | +struct ChampDomaine { | |
| 66 | + domaine: String, | |
| 67 | + erreurs: Erreurs, | |
| 68 | +} | |
| 69 | + | |
| 70 | +#[derive(Deserialize)] | |
| 71 | +pub struct SaisieOrganisation { | |
| 72 | + nom: String, | |
| 73 | + domaine: String, | |
| 74 | + #[serde(default)] | |
| 75 | + base_dn: String, | |
| 76 | + personnaliser: Option<String>, | |
| 77 | + langue: String, | |
| 78 | + fuseau: String, | |
| 79 | +} | |
| 80 | + | |
| 81 | +pub async fn organisation( | |
| 82 | + State(etat): State<Partage>, | |
| 83 | + session: Session, | |
| 84 | + entetes: HeaderMap, | |
| 85 | + Query(retour): Query<Retour>, | |
| 86 | +) -> Result<Response, AppError> { | |
| 87 | + let (brouillon, _) = charger(&etat)?; | |
| 88 | + if let Some(r) = acces_etape(&brouillon, Etape::Organisation, &entetes) { | |
| 89 | + return Ok(r); | |
| 90 | + } | |
| 91 | + let o = brouillon.organisation.clone(); | |
| 92 | + let form = FormOrganisation { | |
| 93 | + action: action(Etape::Organisation, &retour), | |
| 94 | + precedent: "/install", | |
| 95 | + nom: o.as_ref().map(|o| o.nom.clone()).unwrap_or_default(), | |
| 96 | + domaine: o.as_ref().map(|o| o.domaine.clone()).unwrap_or_default(), | |
| 97 | + base_dn: o.as_ref().map(|o| o.base_dn.clone()).unwrap_or_default(), | |
| 98 | + personnaliser: o.as_ref().is_some_and(|o| o.base_dn != validation::dn_depuis_domaine(&o.domaine)), | |
| 99 | + langue: o.as_ref().map_or("fr", |o| if o.langue == Langue::En { "en" } else { "fr" }).to_owned(), | |
| 100 | + fuseau: o.as_ref().map_or("Europe/Paris".to_owned(), |o| o.fuseau.clone()), | |
| 101 | + erreurs: Erreurs::default(), | |
| 102 | + }; | |
| 103 | + page( | |
| 104 | + Cadre::new(&session, &brouillon, Some(Etape::Organisation)).await?, | |
| 105 | + "Votre organisation", | |
| 106 | + "Le domaine détermine la base de l'annuaire et le nom des services.", | |
| 107 | + form.render()?, | |
| 108 | + ) | |
| 109 | +} | |
| 110 | + | |
| 111 | +pub async fn enregistrer_organisation( | |
| 112 | + State(etat): State<Partage>, | |
| 113 | + entetes: HeaderMap, | |
| 114 | + Query(retour): Query<Retour>, | |
| 115 | + Form(s): Form<SaisieOrganisation>, | |
| 116 | +) -> Result<Response, AppError> { | |
| 117 | + let (mut brouillon, secrets) = charger(&etat)?; | |
| 118 | + if let Some(r) = acces_etape(&brouillon, Etape::Organisation, &entetes) { | |
| 119 | + return Ok(r); | |
| 120 | + } | |
| 121 | + let personnaliser = s.personnaliser.is_some(); | |
| 122 | + let domaine = validation::fqdn(&s.domaine).unwrap_or_else(|_| s.domaine.trim().to_lowercase()); | |
| 123 | + let base_dn = if personnaliser { | |
| 124 | + validation::base_dn(&s.base_dn).unwrap_or(s.base_dn.clone()) | |
| 125 | + } else { | |
| 126 | + validation::dn_depuis_domaine(&domaine) | |
| 127 | + }; | |
| 128 | + let organisation = Organisation { | |
| 129 | + nom: s.nom.trim().to_owned(), | |
| 130 | + domaine, | |
| 131 | + base_dn, | |
| 132 | + langue: if s.langue == "en" { Langue::En } else { Langue::Fr }, | |
| 133 | + fuseau: s.fuseau.trim().to_owned(), | |
| 134 | + }; | |
| 135 | + let erreurs = Erreurs::depuis(organisation.valider(&etat.parametres.zoneinfo)); | |
| 136 | + if erreurs.bloquantes() { | |
| 137 | + let form = FormOrganisation { | |
| 138 | + action: action(Etape::Organisation, &retour), | |
| 139 | + precedent: "/install", | |
| 140 | + nom: s.nom, | |
| 141 | + domaine: s.domaine, | |
| 142 | + base_dn: organisation.base_dn, | |
| 143 | + personnaliser, | |
| 144 | + langue: s.langue, | |
| 145 | + fuseau: s.fuseau, | |
| 146 | + erreurs, | |
| 147 | + }; | |
| 148 | + return Ok(invalide(form.render()?)); | |
| 149 | + } | |
| 150 | + brouillon.enregistrer_organisation(organisation); | |
| 151 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 152 | + Ok(apres_validation(&brouillon, Etape::Organisation, &retour, &entetes)) | |
| 153 | +} | |
| 154 | + | |
| 155 | +#[derive(Deserialize)] | |
| 156 | +pub struct SaisieDomaine { | |
| 157 | + domaine: String, | |
| 158 | +} | |
| 159 | + | |
| 160 | +/// Validation immédiate du domaine (E-002 : erreur ou avertissement .local). | |
| 161 | +pub async fn valider_domaine(Form(s): Form<SaisieDomaine>) -> Result<Html<String>, AppError> { | |
| 162 | + let mut erreurs = Erreurs::default(); | |
| 163 | + match validation::fqdn(&s.domaine) { | |
| 164 | + Err(message) => erreurs.ajouter("domaine", message), | |
| 165 | + Ok(domaine) if domaine.ends_with(".local") => { | |
| 166 | + erreurs = Erreurs::depuis([crate::config::Constat::avertissement( | |
| 167 | + "domaine", | |
| 168 | + "Le suffixe .local est réservé à la découverte réseau (mDNS) et peut provoquer des conflits.", | |
| 169 | + )]); | |
| 170 | + } | |
| 171 | + Ok(_) => {} | |
| 172 | + } | |
| 173 | + Ok(Html(ChampDomaine { domaine: s.domaine, erreurs }.render()?)) | |
| 174 | +} | |
| 175 | + | |
| 176 | +// ================================ E-003 Mode et cibles ================================= | |
| 177 | + | |
| 178 | +#[derive(Template)] | |
| 179 | +#[template(path = "assistant/cibles.html")] | |
| 180 | +struct FormCibles { | |
| 181 | + action: String, | |
| 182 | + precedent: &'static str, | |
| 183 | + erreurs: Erreurs, | |
| 184 | +} | |
| 185 | + | |
| 186 | +#[derive(Deserialize)] | |
| 187 | +pub struct SaisieCibles { | |
| 188 | + mode: Option<String>, | |
| 189 | + topologie: Option<String>, | |
| 190 | +} | |
| 191 | + | |
| 192 | +pub async fn cibles( | |
| 193 | + State(etat): State<Partage>, | |
| 194 | + session: Session, | |
| 195 | + entetes: HeaderMap, | |
| 196 | + Query(retour): Query<Retour>, | |
| 197 | +) -> Result<Response, AppError> { | |
| 198 | + let (brouillon, _) = charger(&etat)?; | |
| 199 | + if let Some(r) = acces_etape(&brouillon, Etape::Cibles, &entetes) { | |
| 200 | + return Ok(r); | |
| 201 | + } | |
| 202 | + let form = FormCibles { | |
| 203 | + action: action(Etape::Cibles, &retour), | |
| 204 | + precedent: precedente(&brouillon, Etape::Cibles), | |
| 205 | + erreurs: Erreurs::default(), | |
| 206 | + }; | |
| 207 | + page( | |
| 208 | + Cadre::new(&session, &brouillon, Some(Etape::Cibles)).await?, | |
| 209 | + "Mode et cibles", | |
| 210 | + "Comment et où installer la plateforme.", | |
| 211 | + form.render()?, | |
| 212 | + ) | |
| 213 | +} | |
| 214 | + | |
| 215 | +pub async fn enregistrer_cibles( | |
| 216 | + State(etat): State<Partage>, | |
| 217 | + entetes: HeaderMap, | |
| 218 | + Query(retour): Query<Retour>, | |
| 219 | + Form(s): Form<SaisieCibles>, | |
| 220 | +) -> Result<Response, AppError> { | |
| 221 | + let (mut brouillon, secrets) = charger(&etat)?; | |
| 222 | + if let Some(r) = acces_etape(&brouillon, Etape::Cibles, &entetes) { | |
| 223 | + return Ok(r); | |
| 224 | + } | |
| 225 | + // M1 : seul le mode natif sur ce serveur est disponible (Compose et multi-hôtes : M2). | |
| 226 | + let mut erreurs = Erreurs::default(); | |
| 227 | + if s.mode.as_deref() != Some("native") { | |
| 228 | + erreurs.ajouter("mode", "Seule l'installation en paquets natifs est disponible pour l'instant."); | |
| 229 | + } | |
| 230 | + if s.topologie.as_deref() != Some("local") { | |
| 231 | + erreurs.ajouter("topologie", "Seule l'installation sur ce serveur est disponible pour l'instant."); | |
| 232 | + } | |
| 233 | + if erreurs.bloquantes() { | |
| 234 | + let form = FormCibles { | |
| 235 | + action: action(Etape::Cibles, &retour), | |
| 236 | + precedent: precedente(&brouillon, Etape::Cibles), | |
| 237 | + erreurs, | |
| 238 | + }; | |
| 239 | + return Ok(invalide(form.render()?)); | |
| 240 | + } | |
| 241 | + brouillon.enregistrer_deploiement(Deploiement { | |
| 242 | + mode: Mode::Native, | |
| 243 | + topologie: Topologie::Local, | |
| 244 | + hotes: vec![], | |
| 245 | + }); | |
| 246 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 247 | + Ok(apres_validation(&brouillon, Etape::Cibles, &retour, &entetes)) | |
| 248 | +} | |
| 249 | + | |
| 250 | +// ================================ E-004 Composants ===================================== | |
| 251 | + | |
| 252 | +struct GroupeVue { | |
| 253 | + libelle: &'static str, | |
| 254 | + composants: Vec<ComposantVue>, | |
| 255 | +} | |
| 256 | + | |
| 257 | +struct ComposantVue { | |
| 258 | + cle: String, | |
| 259 | + nom: &'static str, | |
| 260 | + description: &'static str, | |
| 261 | + coche: bool, | |
| 262 | + verrouille: bool, | |
| 263 | + jalon: Option<&'static str>, | |
| 264 | + requis_par: String, | |
| 265 | +} | |
| 266 | + | |
| 267 | +#[derive(Template)] | |
| 268 | +#[template(path = "assistant/composants.html")] | |
| 269 | +struct FormComposants { | |
| 270 | + action: String, | |
| 271 | + precedent: &'static str, | |
| 272 | + groupes: Vec<GroupeVue>, | |
| 273 | + ram_mo: u32, | |
| 274 | + disque_go: u32, | |
| 275 | + erreurs: Vec<String>, | |
| 276 | +} | |
| 277 | + | |
| 278 | +impl FormComposants { | |
| 279 | + fn new( | |
| 280 | + brouillon: &Brouillon, | |
| 281 | + retour: &Retour, | |
| 282 | + selection: &BTreeSet<ComposantId>, | |
| 283 | + erreurs: Vec<String>, | |
| 284 | + ) -> Self { | |
| 285 | + let resolution = catalogue::resoudre(selection).ok(); | |
| 286 | + let choisis = resolution.as_ref().map_or_else(|| selection.clone(), |r| r.composants.clone()); | |
| 287 | + let mut groupes: Vec<GroupeVue> = Vec::new(); | |
| 288 | + for c in catalogue::CATALOGUE { | |
| 289 | + let requis: Vec<&str> = resolution | |
| 290 | + .as_ref() | |
| 291 | + .and_then(|r| r.requis_par.get(&c.id)) | |
| 292 | + .map(|ids| ids.iter().map(|id| catalogue::composant(*id).nom).collect()) | |
| 293 | + .unwrap_or_default(); | |
| 294 | + let vue = ComposantVue { | |
| 295 | + cle: catalogue::cle(c.id), | |
| 296 | + nom: c.nom, | |
| 297 | + description: c.description, | |
| 298 | + coche: choisis.contains(&c.id), | |
| 299 | + verrouille: c.verrouille || !requis.is_empty(), | |
| 300 | + jalon: match c.disponibilite { | |
| 301 | + Disponibilite::Disponible => None, | |
| 302 | + Disponibilite::Jalon(j) => Some(j), | |
| 303 | + }, | |
| 304 | + requis_par: requis.join(", "), | |
| 305 | + }; | |
| 306 | + match groupes.iter_mut().find(|g| g.libelle == c.groupe.libelle()) { | |
| 307 | + Some(groupe) => groupe.composants.push(vue), | |
| 308 | + None => groupes.push(GroupeVue { libelle: c.groupe.libelle(), composants: vec![vue] }), | |
| 309 | + } | |
| 310 | + } | |
| 311 | + let (ram_mo, disque_go) = catalogue::ressources(&choisis); | |
| 312 | + Self { | |
| 313 | + action: action(Etape::Composants, retour), | |
| 314 | + precedent: precedente(brouillon, Etape::Composants), | |
| 315 | + groupes, | |
| 316 | + ram_mo, | |
| 317 | + disque_go, | |
| 318 | + erreurs, | |
| 319 | + } | |
| 320 | + } | |
| 321 | +} | |
| 322 | + | |
| 323 | +/// Composants cochés dans un formulaire (`composants=a&composants=b`). | |
| 324 | +fn selection(form: &RawForm) -> BTreeSet<ComposantId> { | |
| 325 | + form_urlencoded::parse(&form.0) | |
| 326 | + .filter(|(cle, _)| cle == "composants") | |
| 327 | + .filter_map(|(_, valeur)| serde_norway::from_str::<ComposantId>(&valeur).ok()) | |
| 328 | + .collect() | |
| 329 | +} | |
| 330 | + | |
| 331 | +pub async fn composants( | |
| 332 | + State(etat): State<Partage>, | |
| 333 | + session: Session, | |
| 334 | + entetes: HeaderMap, | |
| 335 | + Query(retour): Query<Retour>, | |
| 336 | +) -> Result<Response, AppError> { | |
| 337 | + let (brouillon, _) = charger(&etat)?; | |
| 338 | + if let Some(r) = acces_etape(&brouillon, Etape::Composants, &entetes) { | |
| 339 | + return Ok(r); | |
| 340 | + } | |
| 341 | + let selection = brouillon.composants.clone().unwrap_or_else(catalogue::selection_par_defaut); | |
| 342 | + page( | |
| 343 | + Cadre::new(&session, &brouillon, Some(Etape::Composants)).await?, | |
| 344 | + "Composants", | |
| 345 | + "Choisissez les briques à installer. Les dépendances sont ajoutées automatiquement.", | |
| 346 | + FormComposants::new(&brouillon, &retour, &selection, vec![]).render()?, | |
| 347 | + ) | |
| 348 | +} | |
| 349 | + | |
| 350 | +/// Recalcul des dépendances et des ressources à chaque changement (E-004). | |
| 351 | +pub async fn resolution( | |
| 352 | + State(etat): State<Partage>, | |
| 353 | + Query(retour): Query<Retour>, | |
| 354 | + form: RawForm, | |
| 355 | +) -> Result<Html<String>, AppError> { | |
| 356 | + let (brouillon, _) = charger(&etat)?; | |
| 357 | + Ok(Html(FormComposants::new(&brouillon, &retour, &selection(&form), vec![]).render()?)) | |
| 358 | +} | |
| 359 | + | |
| 360 | +pub async fn enregistrer_composants( | |
| 361 | + State(etat): State<Partage>, | |
| 362 | + entetes: HeaderMap, | |
| 363 | + Query(retour): Query<Retour>, | |
| 364 | + form: RawForm, | |
| 365 | +) -> Result<Response, AppError> { | |
| 366 | + let (mut brouillon, secrets) = charger(&etat)?; | |
| 367 | + if let Some(r) = acces_etape(&brouillon, Etape::Composants, &entetes) { | |
| 368 | + return Ok(r); | |
| 369 | + } | |
| 370 | + let choix = selection(&form); | |
| 371 | + match catalogue::resoudre(&choix) { | |
| 372 | + Err(constats) => { | |
| 373 | + let erreurs = constats.into_iter().map(|c| c.message).collect(); | |
| 374 | + Ok(invalide(FormComposants::new(&brouillon, &retour, &choix, erreurs).render()?)) | |
| 375 | + } | |
| 376 | + Ok(resolution) => { | |
| 377 | + brouillon.enregistrer_composants(resolution.composants); | |
| 378 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 379 | + Ok(apres_validation(&brouillon, Etape::Composants, &retour, &entetes)) | |
| 380 | + } | |
| 381 | + } | |
| 382 | +} | |
| 383 | + | |
| 384 | +// ================================ E-005 Sécurité ======================================= | |
| 385 | + | |
| 386 | +struct ServiceVue { | |
| 387 | + cle: &'static str, | |
| 388 | + libelle: &'static str, | |
| 389 | + nom: String, | |
| 390 | +} | |
| 391 | + | |
| 392 | +#[derive(Template)] | |
| 393 | +#[template(path = "assistant/securite.html")] | |
| 394 | +struct FormSecurite { | |
| 395 | + action: String, | |
| 396 | + precedent: &'static str, | |
| 397 | + services: Vec<ServiceVue>, | |
| 398 | + preset: String, | |
| 399 | + champs: Vec<ChampNombre>, | |
| 400 | + erreurs: Erreurs, | |
| 401 | +} | |
| 402 | + | |
| 403 | +/// Champ numérique de la politique de mots de passe. | |
| 404 | +struct ChampNombre { | |
| 405 | + cle: &'static str, | |
| 406 | + libelle: &'static str, | |
| 407 | + valeur: u16, | |
| 408 | + aide: &'static str, | |
| 409 | +} | |
| 410 | + | |
| 411 | +fn champs_politique(mdp: &PolitiqueMdp) -> Vec<ChampNombre> { | |
| 412 | + let champ = |cle, libelle, valeur, aide| ChampNombre { cle, libelle, valeur, aide }; | |
| 413 | + vec![ | |
| 414 | + champ("longueur_min", "Longueur minimale", mdp.longueur_min.into(), "8 à 128 caractères"), | |
| 415 | + champ( | |
| 416 | + "classes_min", | |
| 417 | + "Types de caractères exigés", | |
| 418 | + mdp.classes_min.into(), | |
| 419 | + "0 à 4 parmi minuscules, majuscules, chiffres, symboles", | |
| 420 | + ), | |
| 421 | + champ("historique", "Anciens mots de passe refusés", mdp.historique.into(), "0 à 24"), | |
| 422 | + champ( | |
| 423 | + "expiration_jours", | |
| 424 | + "Expiration (jours)", | |
| 425 | + mdp.expiration_jours, | |
| 426 | + "0 = jamais (recommandé par l'ANSSI)", | |
| 427 | + ), | |
| 428 | + champ("echecs_max", "Échecs avant verrouillage", mdp.echecs_max.into(), "3 à 50"), | |
| 429 | + champ( | |
| 430 | + "verrouillage_minutes", | |
| 431 | + "Durée du verrouillage (minutes)", | |
| 432 | + mdp.verrouillage_minutes, | |
| 433 | + "0 = déverrouillage par le support", | |
| 434 | + ), | |
| 435 | + ] | |
| 436 | +} | |
| 437 | + | |
| 438 | +fn libelle_service(service: Service) -> &'static str { | |
| 439 | + match service { | |
| 440 | + Service::Annuaire => "Annuaire (LDAPS)", | |
| 441 | + Service::Mdp => "Self Service Password", | |
| 442 | + Service::Pages => "White Pages", | |
| 443 | + Service::Support => "Service Desk", | |
| 444 | + Service::Auth => "Portail d'authentification", | |
| 445 | + Service::Supervision => "Supervision", | |
| 446 | + Service::Vuln => "Analyse des vulnérabilités", | |
| 447 | + Service::Console => "Console d'administration", | |
| 448 | + } | |
| 449 | +} | |
| 450 | + | |
| 451 | +fn nom_preset(mdp: &PolitiqueMdp) -> &'static str { | |
| 452 | + if *mdp == PolitiqueMdp::anssi() { | |
| 453 | + "anssi" | |
| 454 | + } else if *mdp == PolitiqueMdp::renforcee() { | |
| 455 | + "renforcee" | |
| 456 | + } else { | |
| 457 | + "personnalisee" | |
| 458 | + } | |
| 459 | +} | |
| 460 | + | |
| 461 | +fn services_vue(brouillon: &Brouillon, saisis: &BTreeMap<Service, String>) -> Vec<ServiceVue> { | |
| 462 | + let domaine = brouillon.organisation.as_ref().map_or("", |o| o.domaine.as_str()); | |
| 463 | + let composants = brouillon.composants.clone().unwrap_or_default(); | |
| 464 | + catalogue::services(&composants) | |
| 465 | + .into_iter() | |
| 466 | + .map(|s| ServiceVue { | |
| 467 | + cle: s.prefixe(), | |
| 468 | + libelle: libelle_service(s), | |
| 469 | + nom: saisis.get(&s).cloned().unwrap_or_else(|| format!("{}.{domaine}", s.prefixe())), | |
| 470 | + }) | |
| 471 | + .collect() | |
| 472 | +} | |
| 473 | + | |
| 474 | +pub async fn securite( | |
| 475 | + State(etat): State<Partage>, | |
| 476 | + session: Session, | |
| 477 | + entetes: HeaderMap, | |
| 478 | + Query(retour): Query<Retour>, | |
| 479 | +) -> Result<Response, AppError> { | |
| 480 | + let (brouillon, _) = charger(&etat)?; | |
| 481 | + if let Some(r) = acces_etape(&brouillon, Etape::Securite, &entetes) { | |
| 482 | + return Ok(r); | |
| 483 | + } | |
| 484 | + let existant = brouillon.securite.clone(); | |
| 485 | + let mdp = existant.as_ref().map_or_else(PolitiqueMdp::anssi, |s| s.mdp); | |
| 486 | + let form = FormSecurite { | |
| 487 | + action: action(Etape::Securite, &retour), | |
| 488 | + precedent: precedente(&brouillon, Etape::Securite), | |
| 489 | + services: services_vue(&brouillon, &existant.map(|s| s.services).unwrap_or_default()), | |
| 490 | + preset: nom_preset(&mdp).to_owned(), | |
| 491 | + champs: champs_politique(&mdp), | |
| 492 | + erreurs: Erreurs::default(), | |
| 493 | + }; | |
| 494 | + page( | |
| 495 | + Cadre::new(&session, &brouillon, Some(Etape::Securite)).await?, | |
| 496 | + "Sécurité", | |
| 497 | + "Noms des services, certificats et politique de mots de passe.", | |
| 498 | + form.render()?, | |
| 499 | + ) | |
| 500 | +} | |
| 501 | + | |
| 502 | +pub async fn enregistrer_securite( | |
| 503 | + State(etat): State<Partage>, | |
| 504 | + entetes: HeaderMap, | |
| 505 | + Query(retour): Query<Retour>, | |
| 506 | + Form(saisie): Form<BTreeMap<String, String>>, | |
| 507 | +) -> Result<Response, AppError> { | |
| 508 | + let (mut brouillon, secrets) = charger(&etat)?; | |
| 509 | + if let Some(r) = acces_etape(&brouillon, Etape::Securite, &entetes) { | |
| 510 | + return Ok(r); | |
| 511 | + } | |
| 512 | + let champ = |nom: &str| saisie.get(nom).map(|v| v.trim().to_owned()).unwrap_or_default(); | |
| 513 | + let composants = brouillon.composants.clone().unwrap_or_default(); | |
| 514 | + let services: BTreeMap<Service, String> = catalogue::services(&composants) | |
| 515 | + .into_iter() | |
| 516 | + .map(|s| (s, validation::fqdn(&champ(s.prefixe())).unwrap_or_else(|_| champ(s.prefixe())))) | |
| 517 | + .collect(); | |
| 518 | + | |
| 519 | + let mut erreurs = Erreurs::default(); | |
| 520 | + let preset = champ("preset"); | |
| 521 | + let mdp = match preset.as_str() { | |
| 522 | + "anssi" => PolitiqueMdp::anssi(), | |
| 523 | + "renforcee" => PolitiqueMdp::renforcee(), | |
| 524 | + _ => { | |
| 525 | + let mut nombre = |nom: &str| -> u16 { | |
| 526 | + champ(nom).parse().unwrap_or_else(|_| { | |
| 527 | + erreurs.ajouter(nom, "Saisissez un nombre entier."); | |
| 528 | + 0 | |
| 529 | + }) | |
| 530 | + }; | |
| 531 | + PolitiqueMdp { | |
| 532 | + longueur_min: nombre("longueur_min").min(255) as u8, | |
| 533 | + classes_min: nombre("classes_min").min(255) as u8, | |
| 534 | + historique: nombre("historique").min(255) as u8, | |
| 535 | + expiration_jours: nombre("expiration_jours"), | |
| 536 | + echecs_max: nombre("echecs_max").min(255) as u8, | |
| 537 | + verrouillage_minutes: nombre("verrouillage_minutes"), | |
| 538 | + } | |
| 539 | + } | |
| 540 | + }; | |
| 541 | + if champ("tls") != "interne" { | |
| 542 | + erreurs.ajouter("tls", "Seule l'autorité de certification interne est disponible pour l'instant."); | |
| 543 | + } | |
| 544 | + let securite = Securite { | |
| 545 | + services, | |
| 546 | + tls: Tls { mode: TlsMode::Interne, acme_email: None }, | |
| 547 | + mdp, | |
| 548 | + mfa: brouillon.securite.as_ref().map_or_else(Mfa::default, |s| s.mfa.clone()), | |
| 549 | + }; | |
| 550 | + let domaine = brouillon.organisation.as_ref().map_or(String::new(), |o| o.domaine.clone()); | |
| 551 | + let mut constats = securite.mdp.valider(); | |
| 552 | + constats.extend(securite.tls.valider()); | |
| 553 | + constats.extend(crate::config::valider_services(&securite.services, &composants, &domaine)); | |
| 554 | + for constat in constats { | |
| 555 | + if constat.gravite == crate::config::Gravite::Erreur { | |
| 556 | + let champ = constat.chemin.rsplit('.').next().unwrap_or_default().to_owned(); | |
| 557 | + erreurs.ajouter(&champ, constat.message); | |
| 558 | + } | |
| 559 | + } | |
| 560 | + if erreurs.bloquantes() { | |
| 561 | + let form = FormSecurite { | |
| 562 | + action: action(Etape::Securite, &retour), | |
| 563 | + precedent: precedente(&brouillon, Etape::Securite), | |
| 564 | + services: services_vue(&brouillon, &securite.services), | |
| 565 | + preset, | |
| 566 | + champs: champs_politique(&securite.mdp), | |
| 567 | + erreurs, | |
| 568 | + }; | |
| 569 | + return Ok(invalide(form.render()?)); | |
| 570 | + } | |
| 571 | + brouillon.enregistrer_securite(securite); | |
| 572 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 573 | + Ok(apres_validation(&brouillon, Etape::Securite, &retour, &entetes)) | |
| 574 | +} | |
| 575 | + | |
| 576 | +// ================================ E-007 Comptes ======================================== | |
| 577 | + | |
| 578 | +#[derive(Template)] | |
| 579 | +#[template(path = "assistant/comptes.html")] | |
| 580 | +struct FormComptes { | |
| 581 | + action: String, | |
| 582 | + precedent: &'static str, | |
| 583 | + base_dn: String, | |
| 584 | + urgence_defini: bool, | |
| 585 | + admin_defini: bool, | |
| 586 | + messagerie: bool, | |
| 587 | + identite: Vec<ChampTexte>, | |
| 588 | + regles: Vec<validation::Regle>, | |
| 589 | + erreurs: Erreurs, | |
| 590 | +} | |
| 591 | + | |
| 592 | +/// Champ texte de l'identité du premier administrateur. | |
| 593 | +struct ChampTexte { | |
| 594 | + cle: &'static str, | |
| 595 | + libelle: &'static str, | |
| 596 | + valeur: String, | |
| 597 | + aide: &'static str, | |
| 598 | + type_html: &'static str, | |
| 599 | +} | |
| 600 | + | |
| 601 | +fn identite(prenom: String, nom: String, uid: String, email: String) -> Vec<ChampTexte> { | |
| 602 | + vec![ | |
| 603 | + ChampTexte { cle: "prenom", libelle: "Prénom", valeur: prenom, aide: "", type_html: "text" }, | |
| 604 | + ChampTexte { cle: "nom", libelle: "Nom", valeur: nom, aide: "", type_html: "text" }, | |
| 605 | + ChampTexte { | |
| 606 | + cle: "uid", | |
| 607 | + libelle: "Identifiant", | |
| 608 | + valeur: uid, | |
| 609 | + aide: "Par exemple jean.dupont", | |
| 610 | + type_html: "text", | |
| 611 | + }, | |
| 612 | + ChampTexte { cle: "email", libelle: "Adresse e-mail", valeur: email, aide: "", type_html: "email" }, | |
| 613 | + ] | |
| 614 | +} | |
| 615 | + | |
| 616 | +#[derive(Template)] | |
| 617 | +#[template(path = "assistant/comptes_urgence.html")] | |
| 618 | +struct UrgenceGeneree { | |
| 619 | + valeur: String, | |
| 620 | +} | |
| 621 | + | |
| 622 | +#[derive(Template)] | |
| 623 | +#[template(path = "assistant/comptes_regles.html")] | |
| 624 | +struct ReglesVue { | |
| 625 | + regles: Vec<validation::Regle>, | |
| 626 | +} | |
| 627 | + | |
| 628 | +#[derive(Deserialize)] | |
| 629 | +pub struct SaisieComptes { | |
| 630 | + #[serde(default)] | |
| 631 | + urgence: String, | |
| 632 | + urgence_genere: Option<String>, | |
| 633 | + uid: String, | |
| 634 | + prenom: String, | |
| 635 | + nom: String, | |
| 636 | + email: String, | |
| 637 | + mode_mdp: Option<String>, | |
| 638 | + #[serde(default)] | |
| 639 | + mot_de_passe: String, | |
| 640 | + #[serde(default)] | |
| 641 | + confirmation: String, | |
| 642 | +} | |
| 643 | + | |
| 644 | +/// Longueur minimale du mot de passe d'urgence (E-007 : plus strict que la politique). | |
| 645 | +const LONGUEUR_URGENCE: usize = 20; | |
| 646 | + | |
| 647 | +fn politique(brouillon: &Brouillon) -> PolitiqueMdp { | |
| 648 | + brouillon.securite.as_ref().map_or_else(PolitiqueMdp::anssi, |s| s.mdp) | |
| 649 | +} | |
| 650 | + | |
| 651 | +fn regles(brouillon: &Brouillon, mdp: &str, uid: &str, prenom: &str, nom: &str) -> Vec<validation::Regle> { | |
| 652 | + validation::regles_mot_de_passe(mdp, &politique(brouillon), &[uid, prenom, nom]) | |
| 653 | +} | |
| 654 | + | |
| 655 | +pub async fn comptes( | |
| 656 | + State(etat): State<Partage>, | |
| 657 | + session: Session, | |
| 658 | + entetes: HeaderMap, | |
| 659 | + Query(retour): Query<Retour>, | |
| 660 | +) -> Result<Response, AppError> { | |
| 661 | + let (brouillon, secrets) = charger(&etat)?; | |
| 662 | + if let Some(r) = acces_etape(&brouillon, Etape::Comptes, &entetes) { | |
| 663 | + return Ok(r); | |
| 664 | + } | |
| 665 | + let a = brouillon.admin_initial.clone(); | |
| 666 | + let (uid, prenom, nom, email) = a.map_or_else(Default::default, |a| (a.uid, a.prenom, a.nom, a.email)); | |
| 667 | + let form = FormComptes { | |
| 668 | + action: action(Etape::Comptes, &retour), | |
| 669 | + precedent: precedente(&brouillon, Etape::Comptes), | |
| 670 | + base_dn: brouillon.organisation.as_ref().map_or(String::new(), |o| o.base_dn.clone()), | |
| 671 | + urgence_defini: secrets.ldap_admin_mot_de_passe.is_some(), | |
| 672 | + admin_defini: secrets.admin_initial_mot_de_passe.is_some(), | |
| 673 | + messagerie: brouillon.smtp.is_some(), | |
| 674 | + regles: regles(&brouillon, "", &uid, &prenom, &nom), | |
| 675 | + identite: identite(prenom, nom, uid, email), | |
| 676 | + erreurs: Erreurs::default(), | |
| 677 | + }; | |
| 678 | + page( | |
| 679 | + Cadre::new(&session, &brouillon, Some(Etape::Comptes)).await?, | |
| 680 | + "Comptes", | |
| 681 | + "Le compte d'urgence de l'annuaire et le premier administrateur.", | |
| 682 | + form.render()?, | |
| 683 | + ) | |
| 684 | +} | |
| 685 | + | |
| 686 | +pub async fn enregistrer_comptes( | |
| 687 | + State(etat): State<Partage>, | |
| 688 | + entetes: HeaderMap, | |
| 689 | + Query(retour): Query<Retour>, | |
| 690 | + Form(s): Form<SaisieComptes>, | |
| 691 | +) -> Result<Response, AppError> { | |
| 692 | + let (mut brouillon, mut secrets) = charger(&etat)?; | |
| 693 | + if let Some(r) = acces_etape(&brouillon, Etape::Comptes, &entetes) { | |
| 694 | + return Ok(r); | |
| 695 | + } | |
| 696 | + let admin = AdminInitial { | |
| 697 | + uid: s.uid.trim().to_owned(), | |
| 698 | + prenom: s.prenom.trim().to_owned(), | |
| 699 | + nom: s.nom.trim().to_owned(), | |
| 700 | + email: validation::email(&s.email).unwrap_or_else(|_| s.email.trim().to_owned()), | |
| 701 | + mode_mdp: if s.mode_mdp.as_deref() == Some("lien") { ModeMdp::Lien } else { ModeMdp::Saisir }, | |
| 702 | + }; | |
| 703 | + let mut erreurs = Erreurs::depuis(admin.valider()); | |
| 704 | + | |
| 705 | + if s.urgence.is_empty() { | |
| 706 | + if secrets.ldap_admin_mot_de_passe.is_none() { | |
| 707 | + erreurs.ajouter("urgence", "Le mot de passe du compte d'urgence est obligatoire."); | |
| 708 | + } | |
| 709 | + } else if s.urgence.chars().count() < LONGUEUR_URGENCE { | |
| 710 | + erreurs.ajouter("urgence", format!("{LONGUEUR_URGENCE} caractères minimum pour ce compte.")); | |
| 711 | + } | |
| 712 | + | |
| 713 | + if admin.mode_mdp == ModeMdp::Lien && brouillon.smtp.is_none() { | |
| 714 | + erreurs.ajouter("mode_mdp", "L'envoi d'un lien exige une messagerie : saisissez le mot de passe."); | |
| 715 | + } | |
| 716 | + let regles_saisies = regles(&brouillon, &s.mot_de_passe, &admin.uid, &admin.prenom, &admin.nom); | |
| 717 | + if admin.mode_mdp == ModeMdp::Saisir { | |
| 718 | + if s.mot_de_passe.is_empty() { | |
| 719 | + if secrets.admin_initial_mot_de_passe.is_none() { | |
| 720 | + erreurs.ajouter("mot_de_passe", "Le mot de passe est obligatoire."); | |
| 721 | + } | |
| 722 | + } else if let Some(regle) = regles_saisies.iter().find(|r| !r.respectee) { | |
| 723 | + erreurs | |
| 724 | + .ajouter("mot_de_passe", format!("Règle non respectée : {}.", regle.libelle.to_lowercase())); | |
| 725 | + } else if s.mot_de_passe != s.confirmation { | |
| 726 | + erreurs.ajouter("confirmation", "Les deux saisies doivent être identiques."); | |
| 727 | + } | |
| 728 | + } | |
| 729 | + | |
| 730 | + if erreurs.bloquantes() { | |
| 731 | + let form = FormComptes { | |
| 732 | + action: action(Etape::Comptes, &retour), | |
| 733 | + precedent: precedente(&brouillon, Etape::Comptes), | |
| 734 | + base_dn: brouillon.organisation.as_ref().map_or(String::new(), |o| o.base_dn.clone()), | |
| 735 | + urgence_defini: secrets.ldap_admin_mot_de_passe.is_some(), | |
| 736 | + admin_defini: secrets.admin_initial_mot_de_passe.is_some(), | |
| 737 | + messagerie: brouillon.smtp.is_some(), | |
| 738 | + regles: regles_saisies, | |
| 739 | + identite: identite(s.prenom, s.nom, s.uid, s.email), | |
| 740 | + erreurs, | |
| 741 | + }; | |
| 742 | + return Ok(invalide(form.render()?)); | |
| 743 | + } | |
| 744 | + if !s.urgence.is_empty() { | |
| 745 | + secrets.ldap_admin_mot_de_passe = Some(Secret::new(s.urgence)); | |
| 746 | + secrets.ldap_admin_genere = s.urgence_genere.as_deref() == Some("1"); | |
| 747 | + } | |
| 748 | + if admin.mode_mdp == ModeMdp::Saisir && !s.mot_de_passe.is_empty() { | |
| 749 | + secrets.admin_initial_mot_de_passe = Some(Secret::new(s.mot_de_passe)); | |
| 750 | + } | |
| 751 | + brouillon.enregistrer_admin_initial(admin); | |
| 752 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 753 | + Ok(apres_validation(&brouillon, Etape::Comptes, &retour, &entetes)) | |
| 754 | +} | |
| 755 | + | |
| 756 | +/// Génère un mot de passe d'urgence (32 caractères), affiché une fois dans le champ. | |
| 757 | +pub async fn generer_urgence() -> Result<Html<String>, AppError> { | |
| 758 | + Ok(Html(UrgenceGeneree { valeur: Secret::generer(32).exposer().to_owned() }.render()?)) | |
| 759 | +} | |
| 760 | + | |
| 761 | +#[derive(Deserialize)] | |
| 762 | +pub struct SaisieRegles { | |
| 763 | + #[serde(default)] | |
| 764 | + mot_de_passe: String, | |
| 765 | + #[serde(default)] | |
| 766 | + uid: String, | |
| 767 | + #[serde(default)] | |
| 768 | + prenom: String, | |
| 769 | + #[serde(default)] | |
| 770 | + nom: String, | |
| 771 | +} | |
| 772 | + | |
| 773 | +/// Règles de la politique, cochées en direct pendant la saisie. | |
| 774 | +pub async fn verifier_regles( | |
| 775 | + State(etat): State<Partage>, | |
| 776 | + Form(s): Form<SaisieRegles>, | |
| 777 | +) -> Result<Html<String>, AppError> { | |
| 778 | + let (brouillon, _) = charger(&etat)?; | |
| 779 | + Ok(Html(ReglesVue { regles: regles(&brouillon, &s.mot_de_passe, &s.uid, &s.prenom, &s.nom) }.render()?)) | |
| 780 | +} | |
| 781 | + | |
| 782 | +// ================================ E-008 Télémétrie ===================================== | |
| 783 | + | |
| 784 | +#[derive(Template)] | |
| 785 | +#[template(path = "assistant/telemetrie.html")] | |
| 786 | +struct FormTelemetrie { | |
| 787 | + action: String, | |
| 788 | + precedent: &'static str, | |
| 789 | + active: bool, | |
| 790 | + apercu: String, | |
| 791 | +} | |
| 792 | + | |
| 793 | +fn apercu(etat: &Partage, brouillon: &Brouillon) -> Result<String, AppError> { | |
| 794 | + let id = telemetrie::identifiant_instance(&etat.parametres.etat)?; | |
| 795 | + let composants: Vec<ComposantId> = brouillon.composants.clone().unwrap_or_default().into_iter().collect(); | |
| 796 | + let os = telemetrie::systeme(&std::fs::read_to_string("/etc/os-release").unwrap_or_default()); | |
| 797 | + let rapport = telemetrie::rapport(&id, "native", &composants, 1, 1, &os); | |
| 798 | + Ok(serde_json::to_string_pretty(&rapport).unwrap_or_default()) | |
| 799 | +} | |
| 800 | + | |
| 801 | +pub async fn telemetrie( | |
| 802 | + State(etat): State<Partage>, | |
| 803 | + session: Session, | |
| 804 | + entetes: HeaderMap, | |
| 805 | + Query(retour): Query<Retour>, | |
| 806 | +) -> Result<Response, AppError> { | |
| 807 | + let (brouillon, _) = charger(&etat)?; | |
| 808 | + if let Some(r) = acces_etape(&brouillon, Etape::Telemetrie, &entetes) { | |
| 809 | + return Ok(r); | |
| 810 | + } | |
| 811 | + let form = FormTelemetrie { | |
| 812 | + action: action(Etape::Telemetrie, &retour), | |
| 813 | + precedent: precedente(&brouillon, Etape::Telemetrie), | |
| 814 | + active: brouillon.exploitation.as_ref().is_some_and(|e| e.telemetrie.active), | |
| 815 | + apercu: apercu(&etat, &brouillon)?, | |
| 816 | + }; | |
| 817 | + page( | |
| 818 | + Cadre::new(&session, &brouillon, Some(Etape::Telemetrie)).await?, | |
| 819 | + "Supervision et télémétrie", | |
| 820 | + "Ce qui reste sur vos serveurs, et ce que vous acceptez éventuellement de partager.", | |
| 821 | + form.render()?, | |
| 822 | + ) | |
| 823 | +} | |
| 824 | + | |
| 825 | +#[derive(Deserialize)] | |
| 826 | +pub struct SaisieTelemetrie { | |
| 827 | + telemetrie: Option<String>, | |
| 828 | +} | |
| 829 | + | |
| 830 | +pub async fn enregistrer_telemetrie( | |
| 831 | + State(etat): State<Partage>, | |
| 832 | + entetes: HeaderMap, | |
| 833 | + Query(retour): Query<Retour>, | |
| 834 | + Form(s): Form<SaisieTelemetrie>, | |
| 835 | +) -> Result<Response, AppError> { | |
| 836 | + let (mut brouillon, secrets) = charger(&etat)?; | |
| 837 | + if let Some(r) = acces_etape(&brouillon, Etape::Telemetrie, &entetes) { | |
| 838 | + return Ok(r); | |
| 839 | + } | |
| 840 | + let mut exploitation: Exploitation = brouillon.exploitation.clone().unwrap_or_default(); | |
| 841 | + exploitation.telemetrie.active = s.telemetrie.is_some(); | |
| 842 | + brouillon.enregistrer_exploitation(exploitation); | |
| 843 | + etat.depot.sauver(&brouillon, &secrets)?; | |
| 844 | + Ok(apres_validation(&brouillon, Etape::Telemetrie, &retour, &entetes).into_response()) | |
| 845 | +} |
A
installer/src/assistant/installation.rs
+647
-0
@@ -0,0 +1,647 @@
| 1 | +//! E-010 Récapitulatif, E-011 Installation en cours, E-012 Résultat. | |
| 2 | + | |
| 3 | +use std::{ | |
| 4 | + convert::Infallible, | |
| 5 | + path::{Path, PathBuf}, | |
| 6 | + time::{Duration, SystemTime, UNIX_EPOCH}, | |
| 7 | +}; | |
| 8 | + | |
| 9 | +use askama::Template; | |
| 10 | +use axum::{ | |
| 11 | + Form, | |
| 12 | + extract::State, | |
| 13 | + http::{HeaderMap, HeaderValue, StatusCode, header}, | |
| 14 | + response::{ | |
| 15 | + Html, IntoResponse, Response, | |
| 16 | + sse::{Event, KeepAlive, Sse}, | |
| 17 | + }, | |
| 18 | +}; | |
| 19 | +use serde::Deserialize; | |
| 20 | +use tokio_stream::{Stream, StreamExt, wrappers::BroadcastStream}; | |
| 21 | +use tower_sessions::Session; | |
| 22 | + | |
| 23 | +use super::{ | |
| 24 | + Partage, SESSION_LANCEUR, | |
| 25 | + commun::{Cadre, URL_RECAPITULATIF, charger}, | |
| 26 | + rediriger_vers, | |
| 27 | +}; | |
| 28 | +use crate::{ | |
| 29 | + brouillon::{Brouillon, Etape, ecrire_0600}, | |
| 30 | + config::{Gravite, ModeMdp, OpenIamConfig, Secrets, Service}, | |
| 31 | + errors::{AppError, notify}, | |
| 32 | + pages::Layout, | |
| 33 | + prerequis::{self, Controle}, | |
| 34 | + runner::{self, EtatPhase, Evenement, StatutExecution}, | |
| 35 | +}; | |
| 36 | + | |
| 37 | +/// Validité d'une vérification préalable réussie (E-010). | |
| 38 | +const VALIDITE_VERIFICATION: u64 = 15 * 60; | |
| 39 | +const SESSION_VERIFICATION: &str = "verification"; | |
| 40 | +/// Fichier, dans le répertoire d'état, qui mémorise le chemin du fichier récapitulatif. | |
| 41 | +const CHEMIN_RECAPITULATIF: &str = "recapitulatif.chemin"; | |
| 42 | +const CLE_SAUVEGARDE: &str = "/etc/open-iam/sauvegarde/age.key"; | |
| 43 | +const CA_INTERNE: &str = "/etc/open-iam/pki/ca.crt"; | |
| 44 | + | |
| 45 | +fn maintenant() -> u64 { | |
| 46 | + SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Configuration complète et secrets requis présents, sinon la liste des manques. | |
| 50 | +fn pret(brouillon: &Brouillon, secrets: &Secrets) -> Result<OpenIamConfig, Vec<String>> { | |
| 51 | + let config = brouillon.config().map_err(|c| c.into_iter().map(|c| c.message).collect::<Vec<_>>())?; | |
| 52 | + let mut manques = Vec::new(); | |
| 53 | + if secrets.ldap_admin_mot_de_passe.is_none() { | |
| 54 | + manques.push("Le mot de passe du compte d'urgence n'est pas défini (étape Comptes).".to_owned()); | |
| 55 | + } | |
| 56 | + if config.admin_initial.mode_mdp == ModeMdp::Saisir && secrets.admin_initial_mot_de_passe.is_none() { | |
| 57 | + manques | |
| 58 | + .push("Le mot de passe du premier administrateur n'est pas défini (étape Comptes).".to_owned()); | |
| 59 | + } | |
| 60 | + if manques.is_empty() { Ok(config) } else { Err(manques) } | |
| 61 | +} | |
| 62 | + | |
| 63 | +// ================================ E-010 Récapitulatif ================================== | |
| 64 | + | |
| 65 | +struct Carte { | |
| 66 | + titre: &'static str, | |
| 67 | + url: String, | |
| 68 | + lignes: Vec<(&'static str, String)>, | |
| 69 | +} | |
| 70 | + | |
| 71 | +#[derive(Template)] | |
| 72 | +#[template(path = "assistant/recapitulatif.html")] | |
| 73 | +struct Recapitulatif { | |
| 74 | + layout: Layout, | |
| 75 | + etapes: Vec<super::commun::EtapeVue>, | |
| 76 | + courante: usize, | |
| 77 | + organisation: Option<String>, | |
| 78 | + cartes: Vec<Carte>, | |
| 79 | + avertissements: Vec<String>, | |
| 80 | + phases: Vec<&'static str>, | |
| 81 | + verification: Option<Verification>, | |
| 82 | +} | |
| 83 | + | |
| 84 | +#[derive(Template)] | |
| 85 | +#[template(path = "assistant/verification.html")] | |
| 86 | +struct Verification { | |
| 87 | + controles: Vec<Controle>, | |
| 88 | + manques: Vec<String>, | |
| 89 | + reussie: bool, | |
| 90 | +} | |
| 91 | + | |
| 92 | +fn cartes(config: &OpenIamConfig, secrets: &Secrets) -> Vec<Carte> { | |
| 93 | + let modifier = |e: Etape| format!("{}?retour=recapitulatif", e.url()); | |
| 94 | + let defini = |present: bool| if present { "Défini ✓".to_owned() } else { "À saisir".to_owned() }; | |
| 95 | + let o = &config.organisation; | |
| 96 | + let m = &config.mdp; | |
| 97 | + vec![ | |
| 98 | + Carte { | |
| 99 | + titre: "Organisation", | |
| 100 | + url: modifier(Etape::Organisation), | |
| 101 | + lignes: vec![ | |
| 102 | + ("Nom", o.nom.clone()), | |
| 103 | + ("Domaine", o.domaine.clone()), | |
| 104 | + ("Base de l'annuaire", o.base_dn.clone()), | |
| 105 | + ("Fuseau horaire", o.fuseau.clone()), | |
| 106 | + ], | |
| 107 | + }, | |
| 108 | + Carte { | |
| 109 | + titre: "Mode et cibles", | |
| 110 | + url: modifier(Etape::Cibles), | |
| 111 | + lignes: vec![("Mode", "Paquets natifs".into()), ("Serveur", "Ce serveur".into())], | |
| 112 | + }, | |
| 113 | + Carte { | |
| 114 | + titre: "Composants", | |
| 115 | + url: modifier(Etape::Composants), | |
| 116 | + lignes: config | |
| 117 | + .composants | |
| 118 | + .iter() | |
| 119 | + .map(|id| ("Composant", crate::catalogue::composant(*id).nom.to_owned())) | |
| 120 | + .collect(), | |
| 121 | + }, | |
| 122 | + Carte { | |
| 123 | + titre: "Sécurité", | |
| 124 | + url: modifier(Etape::Securite), | |
| 125 | + lignes: config | |
| 126 | + .services | |
| 127 | + .iter() | |
| 128 | + .map(|(s, nom)| (if *s == Service::Annuaire { "Annuaire" } else { "Service" }, nom.clone())) | |
| 129 | + .chain([ | |
| 130 | + ("Certificats", "Autorité interne".into()), | |
| 131 | + ( | |
| 132 | + "Mots de passe", | |
| 133 | + format!( | |
| 134 | + "{} caractères, {} types, {} échecs avant verrouillage", | |
| 135 | + m.longueur_min, m.classes_min, m.echecs_max | |
| 136 | + ), | |
| 137 | + ), | |
| 138 | + ]) | |
| 139 | + .collect(), | |
| 140 | + }, | |
| 141 | + Carte { | |
| 142 | + titre: "Comptes", | |
| 143 | + url: modifier(Etape::Comptes), | |
| 144 | + lignes: vec![ | |
| 145 | + ("Compte d'urgence", format!("cn=admin,{}", o.base_dn)), | |
| 146 | + ("Mot de passe d'urgence", defini(secrets.ldap_admin_mot_de_passe.is_some())), | |
| 147 | + ( | |
| 148 | + "Premier administrateur", | |
| 149 | + format!("{} ({})", config.admin_initial.uid, config.admin_initial.email), | |
| 150 | + ), | |
| 151 | + ("Son mot de passe", defini(secrets.admin_initial_mot_de_passe.is_some())), | |
| 152 | + ], | |
| 153 | + }, | |
| 154 | + Carte { | |
| 155 | + titre: "Télémétrie", | |
| 156 | + url: modifier(Etape::Telemetrie), | |
| 157 | + lignes: vec![( | |
| 158 | + "Rapport anonyme", | |
| 159 | + if config.telemetrie.active { "Activé".into() } else { "Désactivé".into() }, | |
| 160 | + )], | |
| 161 | + }, | |
| 162 | + ] | |
| 163 | +} | |
| 164 | + | |
| 165 | +fn avertissements(config: &OpenIamConfig, secrets: &Secrets) -> Vec<String> { | |
| 166 | + let mut liste: Vec<String> = config | |
| 167 | + .valider() | |
| 168 | + .into_iter() | |
| 169 | + .filter(|c| c.gravite == Gravite::Avertissement) | |
| 170 | + .map(|c| c.message) | |
| 171 | + .collect(); | |
| 172 | + liste.push("Autorité interne : les postes et applications devront faire confiance à son certificat, téléchargeable en fin d'installation.".into()); | |
| 173 | + if config.telemetrie.active { | |
| 174 | + liste.push( | |
| 175 | + "La télémétrie produit est activée : un rapport anonyme sera envoyé chaque semaine.".into(), | |
| 176 | + ); | |
| 177 | + } | |
| 178 | + if secrets.ldap_admin_genere { | |
| 179 | + liste.push("Le mot de passe d'urgence a été généré : il sera affiché une fois en fin d'installation et écrit dans le fichier récapitulatif.".into()); | |
| 180 | + } | |
| 181 | + liste | |
| 182 | +} | |
| 183 | + | |
| 184 | +pub async fn recapitulatif( | |
| 185 | + State(etat): State<Partage>, | |
| 186 | + session: Session, | |
| 187 | + entetes: HeaderMap, | |
| 188 | +) -> Result<Response, AppError> { | |
| 189 | + let (brouillon, secrets) = charger(&etat)?; | |
| 190 | + if let Some(etape) = brouillon.etape_courante() { | |
| 191 | + return Ok(rediriger_vers(&entetes, etape.url(), StatusCode::SEE_OTHER)); | |
| 192 | + } | |
| 193 | + let config = match brouillon.config() { | |
| 194 | + Ok(config) => config, | |
| 195 | + Err(_) => return Ok(rediriger_vers(&entetes, Etape::Organisation.url(), StatusCode::SEE_OTHER)), | |
| 196 | + }; | |
| 197 | + let Cadre { layout, etapes, courante, organisation } = Cadre::new(&session, &brouillon, None).await?; | |
| 198 | + let page = Recapitulatif { | |
| 199 | + layout, | |
| 200 | + etapes, | |
| 201 | + courante, | |
| 202 | + organisation, | |
| 203 | + cartes: cartes(&config, &secrets), | |
| 204 | + avertissements: avertissements(&config, &secrets), | |
| 205 | + phases: runner::phases(&config).into_iter().map(|(_, libelle)| libelle).collect(), | |
| 206 | + verification: None, | |
| 207 | + }; | |
| 208 | + Ok(Html(page.render()?).into_response()) | |
| 209 | +} | |
| 210 | + | |
| 211 | +pub async fn telecharger_config(State(etat): State<Partage>) -> Result<Response, AppError> { | |
| 212 | + let (brouillon, _) = charger(&etat)?; | |
| 213 | + let config = brouillon.config().map_err(|_| AppError::Io(std::io::ErrorKind::NotFound.into()))?; | |
| 214 | + let disposition = format!("attachment; filename=\"openiam-{}.yaml\"", config.organisation.domaine); | |
| 215 | + Ok(( | |
| 216 | + [ | |
| 217 | + (header::CONTENT_TYPE, "application/yaml; charset=utf-8".to_owned()), | |
| 218 | + (header::CONTENT_DISPOSITION, disposition), | |
| 219 | + ], | |
| 220 | + config.vers_yaml(), | |
| 221 | + ) | |
| 222 | + .into_response()) | |
| 223 | +} | |
| 224 | + | |
| 225 | +/// Vérification préalable (E-010) : prérequis du serveur, configuration et secrets complets. | |
| 226 | +pub async fn verification(State(etat): State<Partage>, session: Session) -> Result<Html<String>, AppError> { | |
| 227 | + let (brouillon, secrets) = charger(&etat)?; | |
| 228 | + let controles = prerequis::verifier(etat.parametres.prerequis_simules).await; | |
| 229 | + let manques = pret(&brouillon, &secrets).err().unwrap_or_default(); | |
| 230 | + let reussie = !prerequis::bloquant(&controles) && manques.is_empty(); | |
| 231 | + if reussie { | |
| 232 | + session.insert(SESSION_VERIFICATION, maintenant()).await?; | |
| 233 | + } else { | |
| 234 | + session.remove::<u64>(SESSION_VERIFICATION).await?; | |
| 235 | + } | |
| 236 | + Ok(Html(Verification { controles, manques, reussie }.render()?)) | |
| 237 | +} | |
| 238 | + | |
| 239 | +// ================================ Lancement ============================================ | |
| 240 | + | |
| 241 | +pub async fn lancer( | |
| 242 | + State(etat): State<Partage>, | |
| 243 | + session: Session, | |
| 244 | + entetes: HeaderMap, | |
| 245 | +) -> Result<Response, AppError> { | |
| 246 | + let conflit = |message: &str| (StatusCode::CONFLICT, notify("error", message)).into_response(); | |
| 247 | + let verifiee = session.get::<u64>(SESSION_VERIFICATION).await?; | |
| 248 | + if !verifiee.is_some_and(|t| maintenant().saturating_sub(t) <= VALIDITE_VERIFICATION) { | |
| 249 | + return Ok(conflit("Faites d'abord la vérification préalable (valable 15 minutes).")); | |
| 250 | + } | |
| 251 | + let (brouillon, secrets) = charger(&etat)?; | |
| 252 | + let config = match pret(&brouillon, &secrets) { | |
| 253 | + Ok(config) => config, | |
| 254 | + Err(manques) => return Ok(conflit(&manques.join(" "))), | |
| 255 | + }; | |
| 256 | + let finalisation = Finalisation { | |
| 257 | + etat: etat.parametres.etat.clone(), | |
| 258 | + dossier: etat.parametres.dossier_recapitulatif.clone(), | |
| 259 | + config: config.clone(), | |
| 260 | + secrets: secrets.clone(), | |
| 261 | + }; | |
| 262 | + match etat.runner.lancer(&config, &secrets, move |execution| finalisation.executer(execution)).await { | |
| 263 | + Ok(_) => { | |
| 264 | + session.insert(SESSION_LANCEUR, true).await?; | |
| 265 | + Ok(rediriger_vers(&entetes, "/install/execution", StatusCode::NO_CONTENT)) | |
| 266 | + } | |
| 267 | + Err(crate::runner::ErreurRunner::Occupe) => Ok(conflit("Une installation est déjà en cours.")), | |
| 268 | + Err(e) => Err(e.into()), | |
| 269 | + } | |
| 270 | +} | |
| 271 | + | |
| 272 | +/// Actions de fin d'installation réussie (D-013) : fichier récapitulatif, puis verrou. | |
| 273 | +struct Finalisation { | |
| 274 | + etat: PathBuf, | |
| 275 | + dossier: PathBuf, | |
| 276 | + config: OpenIamConfig, | |
| 277 | + secrets: Secrets, | |
| 278 | +} | |
| 279 | + | |
| 280 | +impl Finalisation { | |
| 281 | + fn executer(&self, _execution: &Path) -> Result<(), String> { | |
| 282 | + use std::os::unix::fs::PermissionsExt; | |
| 283 | + std::fs::create_dir_all(&self.dossier).map_err(|e| e.to_string())?; | |
| 284 | + std::fs::set_permissions(&self.dossier, std::fs::Permissions::from_mode(0o700)) | |
| 285 | + .map_err(|e| e.to_string())?; | |
| 286 | + let date = jiff::Zoned::now(); | |
| 287 | + let fichier = self.dossier.join(format!( | |
| 288 | + "open-iam-{}-{}.txt", | |
| 289 | + self.config.organisation.domaine, | |
| 290 | + date.strftime("%Y%m%d-%H%M") | |
| 291 | + )); | |
| 292 | + ecrire_0600(&fichier, &self.contenu(&date.strftime("%d/%m/%Y à %H:%M").to_string())) | |
| 293 | + .map_err(|e| e.to_string())?; | |
| 294 | + ecrire_0600(&self.etat.join(CHEMIN_RECAPITULATIF), &fichier.display().to_string()) | |
| 295 | + .map_err(|e| e.to_string())?; | |
| 296 | + std::fs::write(self.etat.join("openiam.yaml"), self.config.vers_yaml()).map_err(|e| e.to_string())?; | |
| 297 | + std::fs::write(self.etat.join(crate::etat::VERROU), date.to_string()).map_err(|e| e.to_string()) | |
| 298 | + } | |
| 299 | + | |
| 300 | + fn contenu(&self, date: &str) -> String { | |
| 301 | + let c = &self.config; | |
| 302 | + let secret = | |
| 303 | + |s: &Option<crate::config::Secret>| s.as_ref().map_or("(non défini)", |s| s.exposer()).to_owned(); | |
| 304 | + let cle = std::fs::read_to_string(CLE_SAUVEGARDE).unwrap_or_else(|_| { | |
| 305 | + "(non disponible : les sauvegardes ne sont pas installées sur ce serveur)".into() | |
| 306 | + }); | |
| 307 | + let services: String = | |
| 308 | + c.services.iter().map(|(s, nom)| format!(" {:<12} ldaps://{nom}\n", format!("{s:?}"))).collect(); | |
| 309 | + format!( | |
| 310 | + "Open IAM — récapitulatif de l'installation\n\ | |
| 311 | + Organisation : {org}\nDate : {date}\n\n\ | |
| 312 | + ATTENTION : ce fichier contient des mots de passe et la clé des sauvegardes.\n\ | |
| 313 | + Copiez-le en lieu sûr (coffre de mots de passe), puis supprimez-le de ce serveur.\n\n\ | |
| 314 | + SERVICES\n{services}\n\ | |
| 315 | + COMPTES\n Compte d'urgence de l'annuaire : cn=admin,{base}\n Mot de passe : {urgence}\n\ | |
| 316 | + \n Premier administrateur : uid={uid},ou=users,{base}\n Mot de passe : {admin}\n\n\ | |
| 317 | + SAUVEGARDES\n Clé de déchiffrement (age) — indispensable pour restaurer :\n{cle}\n\ | |
| 318 | + CONFIGURATION (openiam.yaml, sans secret)\n{yaml}", | |
| 319 | + org = c.organisation.nom, | |
| 320 | + base = c.organisation.base_dn, | |
| 321 | + urgence = secret(&self.secrets.ldap_admin_mot_de_passe), | |
| 322 | + uid = c.admin_initial.uid, | |
| 323 | + admin = secret(&self.secrets.admin_initial_mot_de_passe), | |
| 324 | + yaml = c.vers_yaml(), | |
| 325 | + ) | |
| 326 | + } | |
| 327 | +} | |
| 328 | + | |
| 329 | +// ================================ E-011 Installation en cours ========================== | |
| 330 | + | |
| 331 | +#[derive(Template)] | |
| 332 | +#[template(path = "assistant/execution.html")] | |
| 333 | +struct Execution { | |
| 334 | + layout: Layout, | |
| 335 | + phases: String, | |
| 336 | + progression: ProgressionVue, | |
| 337 | + lignes: String, | |
| 338 | + fin: Option<String>, | |
| 339 | + en_cours: bool, | |
| 340 | +} | |
| 341 | + | |
| 342 | +#[derive(Template)] | |
| 343 | +#[template(path = "assistant/execution_phases.html")] | |
| 344 | +struct PhasesVue { | |
| 345 | + phases: Vec<PhaseVue>, | |
| 346 | +} | |
| 347 | + | |
| 348 | +struct PhaseVue { | |
| 349 | + libelle: String, | |
| 350 | + code: &'static str, | |
| 351 | + texte: &'static str, | |
| 352 | +} | |
| 353 | + | |
| 354 | +impl PhasesVue { | |
| 355 | + fn new(phases: &[(String, EtatPhase)]) -> Self { | |
| 356 | + Self { | |
| 357 | + phases: phases | |
| 358 | + .iter() | |
| 359 | + .map(|(libelle, etat)| { | |
| 360 | + let (code, texte) = badge_phase(etat); | |
| 361 | + PhaseVue { libelle: libelle.clone(), code, texte } | |
| 362 | + }) | |
| 363 | + .collect(), | |
| 364 | + } | |
| 365 | + } | |
| 366 | +} | |
| 367 | + | |
| 368 | +#[derive(Template)] | |
| 369 | +#[template(path = "assistant/execution_progression.html")] | |
| 370 | +struct ProgressionVue { | |
| 371 | + faites: u32, | |
| 372 | + total: u32, | |
| 373 | + pourcentage: u32, | |
| 374 | +} | |
| 375 | + | |
| 376 | +impl ProgressionVue { | |
| 377 | + fn new(faites: u32, total: u32, fini: bool) -> Self { | |
| 378 | + let pourcentage = if fini { 100 } else { (faites * 100).checked_div(total).unwrap_or(0).min(99) }; | |
| 379 | + Self { faites, total, pourcentage } | |
| 380 | + } | |
| 381 | +} | |
| 382 | + | |
| 383 | +#[derive(Template)] | |
| 384 | +#[template(path = "assistant/execution_ligne.html")] | |
| 385 | +struct LigneVue<'a> { | |
| 386 | + evenement: &'a Evenement, | |
| 387 | +} | |
| 388 | + | |
| 389 | +#[derive(Template)] | |
| 390 | +#[template(path = "assistant/execution_fin.html")] | |
| 391 | +struct FinVue { | |
| 392 | + statut: StatutExecution, | |
| 393 | + message: Option<String>, | |
| 394 | +} | |
| 395 | + | |
| 396 | +fn badge_phase(etat: &EtatPhase) -> (&'static str, &'static str) { | |
| 397 | + match etat { | |
| 398 | + EtatPhase::AVenir => ("inactif", "à venir"), | |
| 399 | + EtatPhase::EnCours => ("en-cours", "en cours"), | |
| 400 | + EtatPhase::Ok => ("ok", "terminée"), | |
| 401 | + EtatPhase::Echec => ("erreur", "échec"), | |
| 402 | + } | |
| 403 | +} | |
| 404 | + | |
| 405 | +pub async fn execution( | |
| 406 | + State(etat): State<Partage>, | |
| 407 | + session: Session, | |
| 408 | + entetes: HeaderMap, | |
| 409 | +) -> Result<Response, AppError> { | |
| 410 | + let Some(derniere) = etat.runner.derniere() else { | |
| 411 | + return Ok(rediriger_vers(&entetes, URL_RECAPITULATIF, StatusCode::SEE_OTHER)); | |
| 412 | + }; | |
| 413 | + let evenements = etat.runner.historique(&derniere.id, 0)?; | |
| 414 | + let mut lignes = String::new(); | |
| 415 | + let (mut faites, mut total, mut fin) = (0, 0, None); | |
| 416 | + for (_, evenement) in &evenements { | |
| 417 | + match evenement { | |
| 418 | + Evenement::Ligne { .. } | Evenement::Brut { .. } => { | |
| 419 | + lignes.push_str(&LigneVue { evenement }.render()?) | |
| 420 | + } | |
| 421 | + Evenement::Progression { faites: f, total: t } => (faites, total) = (*f, *t), | |
| 422 | + Evenement::Fin { statut, message } => { | |
| 423 | + fin = Some(FinVue { statut: *statut, message: message.clone() }.render()?) | |
| 424 | + } | |
| 425 | + Evenement::Phase { .. } => {} | |
| 426 | + } | |
| 427 | + } | |
| 428 | + let en_cours = derniere.statut == StatutExecution::EnCours; | |
| 429 | + let page = Execution { | |
| 430 | + layout: Layout::new(&session).await?, | |
| 431 | + progression: ProgressionVue::new(faites, total, derniere.statut == StatutExecution::Reussie), | |
| 432 | + phases: PhasesVue::new(&derniere.phases).render()?, | |
| 433 | + lignes, | |
| 434 | + fin, | |
| 435 | + en_cours, | |
| 436 | + }; | |
| 437 | + Ok(Html(page.render()?).into_response()) | |
| 438 | +} | |
| 439 | + | |
| 440 | +/// Flux SSE (E-011) : rejoue le journal après `Last-Event-ID`, puis suit l'exécution en cours. | |
| 441 | +pub async fn flux( | |
| 442 | + State(etat): State<Partage>, | |
| 443 | + entetes: HeaderMap, | |
| 444 | +) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, AppError> { | |
| 445 | + let depuis: u64 = | |
| 446 | + entetes.get("last-event-id").and_then(|v| v.to_str().ok()).and_then(|v| v.parse().ok()).unwrap_or(0); | |
| 447 | + let derniere = etat.runner.derniere(); | |
| 448 | + let id = derniere.as_ref().map(|d| d.id.clone()).unwrap_or_default(); | |
| 449 | + // Abonnement avant la lecture du journal : aucun événement ne peut tomber entre les deux. | |
| 450 | + let abonnement = | |
| 451 | + (etat.runner.id_en_cours().as_deref() == Some(id.as_str())).then(|| etat.runner.abonner()).flatten(); | |
| 452 | + let historique = if id.is_empty() { Vec::new() } else { etat.runner.historique(&id, depuis)? }; | |
| 453 | + let deja_vu = historique.last().map_or(depuis, |(n, _)| *n); | |
| 454 | + let etat_phases = etat.clone(); | |
| 455 | + let id_phases = id.clone(); | |
| 456 | + | |
| 457 | + // Le flux direct se termine de lui-même : à la fin de l'exécution, le runner relâche l'émetteur. | |
| 458 | + let direct: std::pin::Pin<Box<dyn Stream<Item = (u64, Evenement)> + Send>> = match abonnement { | |
| 459 | + Some(recepteur) => Box::pin( | |
| 460 | + BroadcastStream::new(recepteur).filter_map(Result::ok).filter(move |(n, _)| *n > deja_vu), | |
| 461 | + ), | |
| 462 | + None => Box::pin(tokio_stream::empty()), | |
| 463 | + }; | |
| 464 | + let flux = tokio_stream::iter(historique) | |
| 465 | + .chain(direct) | |
| 466 | + .map(move |(n, evenement)| Ok(evenement_sse(&etat_phases, &id_phases, n, &evenement))); | |
| 467 | + Ok(Sse::new(flux).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))) | |
| 468 | +} | |
| 469 | + | |
| 470 | +fn evenement_sse(etat: &Partage, id: &str, n: u64, evenement: &Evenement) -> Event { | |
| 471 | + let (nom, donnees) = match evenement { | |
| 472 | + Evenement::Ligne { .. } | Evenement::Brut { .. } => { | |
| 473 | + ("ligne", LigneVue { evenement }.render().unwrap_or_default()) | |
| 474 | + } | |
| 475 | + Evenement::Progression { faites, total } => { | |
| 476 | + ("progression", ProgressionVue::new(*faites, *total, false).render().unwrap_or_default()) | |
| 477 | + } | |
| 478 | + Evenement::Phase { .. } => { | |
| 479 | + let phases = etat.runner.derniere().filter(|d| d.id == id).map(|d| d.phases).unwrap_or_default(); | |
| 480 | + ("phases", PhasesVue::new(&phases).render().unwrap_or_default()) | |
| 481 | + } | |
| 482 | + Evenement::Fin { statut, message } => { | |
| 483 | + ("fin", FinVue { statut: *statut, message: message.clone() }.render().unwrap_or_default()) | |
| 484 | + } | |
| 485 | + }; | |
| 486 | + Event::default().id(n.to_string()).event(nom).data(donnees) | |
| 487 | +} | |
| 488 | + | |
| 489 | +pub async fn interrompre(State(etat): State<Partage>) -> Result<Response, AppError> { | |
| 490 | + match etat.runner.interrompre() { | |
| 491 | + Ok(()) => { | |
| 492 | + Ok((StatusCode::ACCEPTED, notify("info", "Interruption demandée : fin de la tâche en cours…")) | |
| 493 | + .into_response()) | |
| 494 | + } | |
| 495 | + Err(_) => { | |
| 496 | + Ok((StatusCode::CONFLICT, notify("error", "Aucune installation en cours.")).into_response()) | |
| 497 | + } | |
| 498 | + } | |
| 499 | +} | |
| 500 | + | |
| 501 | +pub async fn journal(State(etat): State<Partage>) -> Result<Response, AppError> { | |
| 502 | + let Some(derniere) = etat.runner.derniere() else { | |
| 503 | + return Ok(StatusCode::NOT_FOUND.into_response()); | |
| 504 | + }; | |
| 505 | + let texte = etat.runner.journal_texte(&derniere.id)?; | |
| 506 | + Ok(( | |
| 507 | + [ | |
| 508 | + (header::CONTENT_TYPE, "text/plain; charset=utf-8".to_owned()), | |
| 509 | + (header::CONTENT_DISPOSITION, format!("attachment; filename=\"open-iam-{}.log\"", derniere.id)), | |
| 510 | + ], | |
| 511 | + texte, | |
| 512 | + ) | |
| 513 | + .into_response()) | |
| 514 | +} | |
| 515 | + | |
| 516 | +/// Après la fin réussie : passage à E-012. | |
| 517 | +pub async fn suite(State(etat): State<Partage>, entetes: HeaderMap) -> Response { | |
| 518 | + let reussie = etat.runner.derniere().is_some_and(|d| d.statut == StatutExecution::Reussie); | |
| 519 | + rediriger_vers( | |
| 520 | + &entetes, | |
| 521 | + if reussie { "/install/resultat" } else { "/install/execution" }, | |
| 522 | + StatusCode::NO_CONTENT, | |
| 523 | + ) | |
| 524 | +} | |
| 525 | + | |
| 526 | +// ================================ E-012 Résultat ======================================= | |
| 527 | + | |
| 528 | +struct ServiceSante { | |
| 529 | + libelle: &'static str, | |
| 530 | + adresse: String, | |
| 531 | + ok: bool, | |
| 532 | +} | |
| 533 | + | |
| 534 | +#[derive(Template)] | |
| 535 | +#[template(path = "assistant/resultat.html")] | |
| 536 | +struct Resultat { | |
| 537 | + layout: Layout, | |
| 538 | + duree: String, | |
| 539 | + services: Vec<ServiceSante>, | |
| 540 | + urgence: Option<String>, | |
| 541 | + recapitulatif: String, | |
| 542 | + ca: bool, | |
| 543 | +} | |
| 544 | + | |
| 545 | +async fn repond(nom: &str, port: u16) -> bool { | |
| 546 | + matches!( | |
| 547 | + tokio::time::timeout(Duration::from_secs(2), tokio::net::TcpStream::connect((nom, port))).await, | |
| 548 | + Ok(Ok(_)) | |
| 549 | + ) | |
| 550 | +} | |
| 551 | + | |
| 552 | +pub async fn resultat( | |
| 553 | + State(etat): State<Partage>, | |
| 554 | + session: Session, | |
| 555 | + entetes: HeaderMap, | |
| 556 | +) -> Result<Response, AppError> { | |
| 557 | + let Some(derniere) = etat.runner.derniere().filter(|d| d.statut == StatutExecution::Reussie) else { | |
| 558 | + return Ok(rediriger_vers(&entetes, "/install/execution", StatusCode::SEE_OTHER)); | |
| 559 | + }; | |
| 560 | + let (brouillon, secrets) = charger(&etat)?; | |
| 561 | + let config = brouillon.config().ok(); | |
| 562 | + let mut services = Vec::new(); | |
| 563 | + for (service, nom) in config.as_ref().map(|c| c.services.clone()).unwrap_or_default() { | |
| 564 | + if service == Service::Annuaire { | |
| 565 | + services.push(ServiceSante { | |
| 566 | + libelle: "Annuaire (LDAPS)", | |
| 567 | + adresse: format!("ldaps://{nom}"), | |
| 568 | + ok: repond(&nom, 636).await, | |
| 569 | + }); | |
| 570 | + } | |
| 571 | + } | |
| 572 | + let duree = match ( | |
| 573 | + jiff::Timestamp::strptime("%Y-%m-%dT%H:%M:%S%:z", &derniere.debut), | |
| 574 | + derniere.fin.as_deref().map(|f| jiff::Timestamp::strptime("%Y-%m-%dT%H:%M:%S%:z", f)), | |
| 575 | + ) { | |
| 576 | + (Ok(debut), Some(Ok(fin))) => { | |
| 577 | + let secondes = fin.as_second() - debut.as_second(); | |
| 578 | + format!("{} min {:02} s", secondes / 60, secondes % 60) | |
| 579 | + } | |
| 580 | + _ => String::new(), | |
| 581 | + }; | |
| 582 | + let page = Resultat { | |
| 583 | + layout: Layout::new(&session).await?, | |
| 584 | + duree, | |
| 585 | + services, | |
| 586 | + urgence: secrets | |
| 587 | + .ldap_admin_genere | |
| 588 | + .then(|| secrets.ldap_admin_mot_de_passe.map(|s| s.exposer().to_owned())) | |
| 589 | + .flatten(), | |
| 590 | + recapitulatif: std::fs::read_to_string(etat.parametres.etat.join(CHEMIN_RECAPITULATIF)) | |
| 591 | + .unwrap_or_default(), | |
| 592 | + ca: Path::new(CA_INTERNE).is_file(), | |
| 593 | + }; | |
| 594 | + let mut res = Html(page.render()?).into_response(); | |
| 595 | + res.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); | |
| 596 | + Ok(res) | |
| 597 | +} | |
| 598 | + | |
| 599 | +pub async fn telecharger_recapitulatif(State(etat): State<Partage>) -> Result<Response, AppError> { | |
| 600 | + let chemin = std::fs::read_to_string(etat.parametres.etat.join(CHEMIN_RECAPITULATIF))?; | |
| 601 | + let contenu = std::fs::read_to_string(chemin.trim())?; | |
| 602 | + Ok(( | |
| 603 | + [ | |
| 604 | + (header::CONTENT_TYPE, "text/plain; charset=utf-8"), | |
| 605 | + (header::CONTENT_DISPOSITION, "attachment; filename=\"open-iam-recapitulatif.txt\""), | |
| 606 | + (header::CACHE_CONTROL, "no-store"), | |
| 607 | + ], | |
| 608 | + contenu, | |
| 609 | + ) | |
| 610 | + .into_response()) | |
| 611 | +} | |
| 612 | + | |
| 613 | +pub async fn telecharger_ca() -> Result<Response, AppError> { | |
| 614 | + let ca = std::fs::read(CA_INTERNE)?; | |
| 615 | + Ok(( | |
| 616 | + [ | |
| 617 | + (header::CONTENT_TYPE, "application/x-x509-ca-cert"), | |
| 618 | + (header::CONTENT_DISPOSITION, "attachment; filename=\"open-iam-ca.crt\""), | |
| 619 | + ], | |
| 620 | + ca, | |
| 621 | + ) | |
| 622 | + .into_response()) | |
| 623 | +} | |
| 624 | + | |
| 625 | +#[derive(Deserialize)] | |
| 626 | +pub struct Terminer { | |
| 627 | + conserve: Option<String>, | |
| 628 | +} | |
| 629 | + | |
| 630 | +/// Fin de l'assistant : purge du brouillon et de ses secrets, la session perd son accès au résultat. | |
| 631 | +pub async fn terminer( | |
| 632 | + State(etat): State<Partage>, | |
| 633 | + session: Session, | |
| 634 | + entetes: HeaderMap, | |
| 635 | + Form(saisie): Form<Terminer>, | |
| 636 | +) -> Result<Response, AppError> { | |
| 637 | + if saisie.conserve.is_none() { | |
| 638 | + return Ok(( | |
| 639 | + StatusCode::UNPROCESSABLE_ENTITY, | |
| 640 | + notify("error", "Confirmez d'abord avoir conservé les identifiants en lieu sûr."), | |
| 641 | + ) | |
| 642 | + .into_response()); | |
| 643 | + } | |
| 644 | + etat.depot.supprimer()?; | |
| 645 | + session.remove::<bool>(SESSION_LANCEUR).await?; | |
| 646 | + Ok(rediriger_vers(&entetes, "/verrouille", StatusCode::NO_CONTENT)) | |
| 647 | +} |
A
installer/src/assistant/mod.rs
+111
-0
@@ -0,0 +1,111 @@
| 1 | +//! Assistant d'installation (/install, E-000 à E-012). | |
| 2 | + | |
| 3 | +mod acces; | |
| 4 | +mod bienvenue; | |
| 5 | +pub mod commun; | |
| 6 | +mod etapes; | |
| 7 | +mod installation; | |
| 8 | + | |
| 9 | +use std::sync::Arc; | |
| 10 | + | |
| 11 | +use axum::{ | |
| 12 | + Router, | |
| 13 | + extract::{Request, State}, | |
| 14 | + http::{HeaderMap, HeaderValue, StatusCode}, | |
| 15 | + middleware::{self, Next}, | |
| 16 | + response::{IntoResponse, Redirect, Response}, | |
| 17 | + routing::{delete, get, post}, | |
| 18 | +}; | |
| 19 | +use tower_sessions::Session; | |
| 20 | + | |
| 21 | +use crate::etat::Etat; | |
| 22 | + | |
| 23 | +pub type Partage = Arc<Etat>; | |
| 24 | + | |
| 25 | +/// Clé de session posée après un accès par jeton réussi. | |
| 26 | +const SESSION_ASSISTANT: &str = "assistant"; | |
| 27 | +/// Clé de session de qui a lancé l'installation : seule cette session voit E-012 après le verrou. | |
| 28 | +const SESSION_LANCEUR: &str = "lanceur"; | |
| 29 | + | |
| 30 | +/// Écrans encore accessibles à la session qui a lancé l'installation, une fois le verrou posé. | |
| 31 | +const APRES_VERROU: [&str; 6] = | |
| 32 | + ["/resultat", "/terminer", "/execution", "/execution/flux", "/execution/journal.txt", "/execution/suite"]; | |
| 33 | + | |
| 34 | +pub fn routes(etat: Partage) -> Router { | |
| 35 | + // Toute l'arborescence /install est gardée, y compris les adresses inconnues. | |
| 36 | + let protegees = Router::new() | |
| 37 | + .route("/", get(bienvenue::page)) | |
| 38 | + .route("/prerequis", get(bienvenue::controles)) | |
| 39 | + .route("/prerequis/ansible", post(bienvenue::installer_ansible)) | |
| 40 | + .route("/commencer", post(bienvenue::commencer)) | |
| 41 | + .route("/brouillon", delete(bienvenue::supprimer)) | |
| 42 | + .route("/import", post(bienvenue::importer)) | |
| 43 | + .route("/organisation", get(etapes::organisation).post(etapes::enregistrer_organisation)) | |
| 44 | + .route("/organisation/champ/domaine", post(etapes::valider_domaine)) | |
| 45 | + .route("/cibles", get(etapes::cibles).post(etapes::enregistrer_cibles)) | |
| 46 | + .route("/composants", get(etapes::composants).post(etapes::enregistrer_composants)) | |
| 47 | + .route("/composants/resolution", post(etapes::resolution)) | |
| 48 | + .route("/securite", get(etapes::securite).post(etapes::enregistrer_securite)) | |
| 49 | + .route("/comptes", get(etapes::comptes).post(etapes::enregistrer_comptes)) | |
| 50 | + .route("/comptes/generer", post(etapes::generer_urgence)) | |
| 51 | + .route("/comptes/regles", post(etapes::verifier_regles)) | |
| 52 | + .route("/telemetrie", get(etapes::telemetrie).post(etapes::enregistrer_telemetrie)) | |
| 53 | + .route("/recapitulatif", get(installation::recapitulatif)) | |
| 54 | + .route("/openiam.yaml", get(installation::telecharger_config)) | |
| 55 | + .route("/verification", post(installation::verification)) | |
| 56 | + .route("/execution", get(installation::execution).post(installation::lancer)) | |
| 57 | + .route("/execution/flux", get(installation::flux)) | |
| 58 | + .route("/execution/interrompre", post(installation::interrompre)) | |
| 59 | + .route("/execution/journal.txt", get(installation::journal)) | |
| 60 | + .route("/execution/suite", get(installation::suite)) | |
| 61 | + .route("/resultat", get(installation::resultat)) | |
| 62 | + .route("/resultat/recapitulatif.txt", get(installation::telecharger_recapitulatif)) | |
| 63 | + .route("/resultat/ca.crt", get(installation::telecharger_ca)) | |
| 64 | + .route("/terminer", post(installation::terminer)) | |
| 65 | + .fallback(crate::errors::not_found) | |
| 66 | + .layer(middleware::from_fn_with_state(etat.clone(), garde)); | |
| 67 | + Router::new() | |
| 68 | + .route("/", get(|| async { Redirect::to("/install") })) | |
| 69 | + .route("/acces", get(acces::page).post(acces::valider)) | |
| 70 | + .route("/verrouille", get(acces::verrouille)) | |
| 71 | + .nest("/install", protegees) | |
| 72 | + .with_state(etat) | |
| 73 | +} | |
| 74 | + | |
| 75 | +/// Requête émise par HTMX ? | |
| 76 | +pub fn est_htmx(entetes: &HeaderMap) -> bool { | |
| 77 | + entetes.contains_key("hx-request") | |
| 78 | +} | |
| 79 | + | |
| 80 | +/// Redirection adaptée : `HX-Redirect` pour HTMX, 303 sinon. | |
| 81 | +pub fn rediriger(entetes: &HeaderMap, cible: &'static str, statut_htmx: StatusCode) -> Response { | |
| 82 | + rediriger_vers(entetes, cible, statut_htmx) | |
| 83 | +} | |
| 84 | + | |
| 85 | +pub fn rediriger_vers(entetes: &HeaderMap, cible: &str, statut_htmx: StatusCode) -> Response { | |
| 86 | + if est_htmx(entetes) { | |
| 87 | + let mut res = statut_htmx.into_response(); | |
| 88 | + if let Ok(valeur) = HeaderValue::from_str(cible) { | |
| 89 | + res.headers_mut().insert("hx-redirect", valeur); | |
| 90 | + } | |
| 91 | + res | |
| 92 | + } else { | |
| 93 | + Redirect::to(cible).into_response() | |
| 94 | + } | |
| 95 | +} | |
| 96 | + | |
| 97 | +/// Garde des écrans de l'assistant : verrouillé après installation, sinon jeton exigé. | |
| 98 | +async fn garde(State(etat): State<Partage>, session: Session, req: Request, next: Next) -> Response { | |
| 99 | + if etat.installe() { | |
| 100 | + let chemin = req.uri().path().trim_start_matches("/install"); | |
| 101 | + let lanceur = session.get::<bool>(SESSION_LANCEUR).await.ok().flatten().unwrap_or(false); | |
| 102 | + let autorise = lanceur && (APRES_VERROU.contains(&chemin) || chemin.starts_with("/resultat/")); | |
| 103 | + if !autorise { | |
| 104 | + return rediriger(req.headers(), "/verrouille", StatusCode::SEE_OTHER); | |
| 105 | + } | |
| 106 | + } | |
| 107 | + if !session.get::<bool>(SESSION_ASSISTANT).await.ok().flatten().unwrap_or(false) { | |
| 108 | + return rediriger(req.headers(), "/acces", StatusCode::UNAUTHORIZED); | |
| 109 | + } | |
| 110 | + next.run(req).await | |
| 111 | +} |
A
installer/src/brouillon.rs
+586
-0
@@ -0,0 +1,586 @@
| 1 | +//! Brouillon de l'assistant (OI-022) : sections saisies, état des étapes et persistance. | |
| 2 | +//! Le brouillon survit à un redémarrage de l'installeur ; les secrets sont stockés à part, | |
| 3 | +//! en 0600 (IHM_MAP.md § Parcours de l'assistant). | |
| 4 | + | |
| 5 | +use std::{ | |
| 6 | + collections::BTreeSet, | |
| 7 | + fs, | |
| 8 | + io::Write, | |
| 9 | + path::{Path, PathBuf}, | |
| 10 | +}; | |
| 11 | + | |
| 12 | +use serde::{Deserialize, Serialize}; | |
| 13 | + | |
| 14 | +use crate::{ | |
| 15 | + catalogue::{self, ComposantId}, | |
| 16 | + config::{ | |
| 17 | + AdminInitial, Constat, Deploiement, Mfa, OpenIamConfig, Organisation, PolitiqueMdp, Secrets, Service, | |
| 18 | + Smtp, Supervision, Telemetrie, Tls, | |
| 19 | + }, | |
| 20 | +}; | |
| 21 | + | |
| 22 | +/// Étapes de l'assistant, dans l'ordre du stepper (C-011). | |
| 23 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] | |
| 24 | +#[serde(rename_all = "snake_case")] | |
| 25 | +pub enum Etape { | |
| 26 | + Organisation, | |
| 27 | + Cibles, | |
| 28 | + Composants, | |
| 29 | + Securite, | |
| 30 | + Messagerie, | |
| 31 | + Comptes, | |
| 32 | + Telemetrie, | |
| 33 | + Parametres, | |
| 34 | +} | |
| 35 | + | |
| 36 | +impl Etape { | |
| 37 | + pub const TOUTES: [Etape; 8] = [ | |
| 38 | + Etape::Organisation, | |
| 39 | + Etape::Cibles, | |
| 40 | + Etape::Composants, | |
| 41 | + Etape::Securite, | |
| 42 | + Etape::Messagerie, | |
| 43 | + Etape::Comptes, | |
| 44 | + Etape::Telemetrie, | |
| 45 | + Etape::Parametres, | |
| 46 | + ]; | |
| 47 | + | |
| 48 | + pub fn libelle(self) -> &'static str { | |
| 49 | + match self { | |
| 50 | + Etape::Organisation => "Organisation", | |
| 51 | + Etape::Cibles => "Mode et cibles", | |
| 52 | + Etape::Composants => "Composants", | |
| 53 | + Etape::Securite => "Sécurité", | |
| 54 | + Etape::Messagerie => "Messagerie", | |
| 55 | + Etape::Comptes => "Comptes", | |
| 56 | + Etape::Telemetrie => "Supervision et télémétrie", | |
| 57 | + Etape::Parametres => "Paramètres des composants", | |
| 58 | + } | |
| 59 | + } | |
| 60 | + | |
| 61 | + pub fn url(self) -> &'static str { | |
| 62 | + match self { | |
| 63 | + Etape::Organisation => "/install/organisation", | |
| 64 | + Etape::Cibles => "/install/cibles", | |
| 65 | + Etape::Composants => "/install/composants", | |
| 66 | + Etape::Securite => "/install/securite", | |
| 67 | + Etape::Messagerie => "/install/messagerie", | |
| 68 | + Etape::Comptes => "/install/comptes", | |
| 69 | + Etape::Telemetrie => "/install/telemetrie", | |
| 70 | + Etape::Parametres => "/install/parametres", | |
| 71 | + } | |
| 72 | + } | |
| 73 | +} | |
| 74 | + | |
| 75 | +/// État affiché d'une étape (C-011). | |
| 76 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 77 | +pub enum EtatEtape { | |
| 78 | + AFaire, | |
| 79 | + EnCours, | |
| 80 | + Validee, | |
| 81 | + ARevoir, | |
| 82 | + Sautee, | |
| 83 | +} | |
| 84 | + | |
| 85 | +impl EtatEtape { | |
| 86 | + /// Valeur utilisée par le gabarit du stepper. | |
| 87 | + pub fn code(self) -> &'static str { | |
| 88 | + match self { | |
| 89 | + Self::AFaire => "a-faire", | |
| 90 | + Self::EnCours => "en-cours", | |
| 91 | + Self::Validee => "validee", | |
| 92 | + Self::ARevoir => "a-revoir", | |
| 93 | + Self::Sautee => "sautee", | |
| 94 | + } | |
| 95 | + } | |
| 96 | +} | |
| 97 | + | |
| 98 | +/// Section E-005. | |
| 99 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 100 | +#[serde(deny_unknown_fields)] | |
| 101 | +pub struct Securite { | |
| 102 | + pub services: std::collections::BTreeMap<Service, String>, | |
| 103 | + pub tls: Tls, | |
| 104 | + pub mdp: PolitiqueMdp, | |
| 105 | + pub mfa: Mfa, | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// Section E-008. | |
| 109 | +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] | |
| 110 | +#[serde(deny_unknown_fields)] | |
| 111 | +pub struct Exploitation { | |
| 112 | + pub supervision: Supervision, | |
| 113 | + pub telemetrie: Telemetrie, | |
| 114 | +} | |
| 115 | + | |
| 116 | +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] | |
| 117 | +#[serde(deny_unknown_fields)] | |
| 118 | +pub struct Brouillon { | |
| 119 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 120 | + pub organisation: Option<Organisation>, | |
| 121 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 122 | + pub deploiement: Option<Deploiement>, | |
| 123 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 124 | + pub composants: Option<BTreeSet<ComposantId>>, | |
| 125 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 126 | + pub securite: Option<Securite>, | |
| 127 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 128 | + pub smtp: Option<Smtp>, | |
| 129 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 130 | + pub admin_initial: Option<AdminInitial>, | |
| 131 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 132 | + pub exploitation: Option<Exploitation>, | |
| 133 | + #[serde(default)] | |
| 134 | + pub validees: BTreeSet<Etape>, | |
| 135 | + #[serde(default)] | |
| 136 | + pub a_revoir: BTreeSet<Etape>, | |
| 137 | +} | |
| 138 | + | |
| 139 | +impl Brouillon { | |
| 140 | + /// L'étape s'applique-t-elle aux choix actuels ? (sinon elle est « sautée ») | |
| 141 | + pub fn applicable(&self, etape: Etape) -> bool { | |
| 142 | + let composants = self.composants.as_ref(); | |
| 143 | + match etape { | |
| 144 | + Etape::Messagerie => composants.is_some_and(catalogue::envoie_mail), | |
| 145 | + Etape::Parametres => { | |
| 146 | + composants.is_some_and(|c| c.iter().any(|id| catalogue::composant(*id).a_parametres)) | |
| 147 | + } | |
| 148 | + _ => true, | |
| 149 | + } | |
| 150 | + } | |
| 151 | + | |
| 152 | + /// Validée et pas à revoir. | |
| 153 | + fn complete(&self, etape: Etape) -> bool { | |
| 154 | + self.validees.contains(&etape) && !self.a_revoir.contains(&etape) | |
| 155 | + } | |
| 156 | + | |
| 157 | + /// Première étape applicable jamais validée (affichée « en cours »). | |
| 158 | + fn premiere_a_faire(&self) -> Option<Etape> { | |
| 159 | + Etape::TOUTES | |
| 160 | + .into_iter() | |
| 161 | + .find(|e| self.applicable(*e) && !self.validees.contains(e) && !self.a_revoir.contains(e)) | |
| 162 | + } | |
| 163 | + | |
| 164 | + /// État de chaque étape, dans l'ordre. | |
| 165 | + pub fn etats(&self) -> Vec<(Etape, EtatEtape)> { | |
| 166 | + let en_cours = self.premiere_a_faire(); | |
| 167 | + Etape::TOUTES | |
| 168 | + .into_iter() | |
| 169 | + .map(|e| { | |
| 170 | + let etat = if !self.applicable(e) { | |
| 171 | + EtatEtape::Sautee | |
| 172 | + } else if self.a_revoir.contains(&e) { | |
| 173 | + EtatEtape::ARevoir | |
| 174 | + } else if self.validees.contains(&e) { | |
| 175 | + EtatEtape::Validee | |
| 176 | + } else if Some(e) == en_cours { | |
| 177 | + EtatEtape::EnCours | |
| 178 | + } else { | |
| 179 | + EtatEtape::AFaire | |
| 180 | + }; | |
| 181 | + (e, etat) | |
| 182 | + }) | |
| 183 | + .collect() | |
| 184 | + } | |
| 185 | + | |
| 186 | + /// Première étape à compléter (à revoir ou à faire), ou `None` si tout est validé. | |
| 187 | + pub fn etape_courante(&self) -> Option<Etape> { | |
| 188 | + Etape::TOUTES.into_iter().find(|e| self.applicable(*e) && !self.complete(*e)) | |
| 189 | + } | |
| 190 | + | |
| 191 | + /// Une étape est accessible si elle est applicable et déjà validée, à revoir ou en cours. | |
| 192 | + pub fn peut_acceder(&self, etape: Etape) -> bool { | |
| 193 | + self.applicable(etape) | |
| 194 | + && (self.validees.contains(&etape) | |
| 195 | + || self.a_revoir.contains(&etape) | |
| 196 | + || self.premiere_a_faire() == Some(etape)) | |
| 197 | + } | |
| 198 | + | |
| 199 | + /// Étape à afficher après validation de `etape` : la prochaine incomplète, sinon la | |
| 200 | + /// première incomplète avant elle, sinon `None` (récapitulatif). | |
| 201 | + pub fn suivante(&self, etape: Etape) -> Option<Etape> { | |
| 202 | + Etape::TOUTES | |
| 203 | + .into_iter() | |
| 204 | + .find(|e| *e > etape && self.applicable(*e) && !self.complete(*e)) | |
| 205 | + .or_else(|| self.etape_courante()) | |
| 206 | + } | |
| 207 | + | |
| 208 | + fn valider_etape(&mut self, etape: Etape) { | |
| 209 | + self.validees.insert(etape); | |
| 210 | + self.a_revoir.remove(&etape); | |
| 211 | + } | |
| 212 | + | |
| 213 | + fn revoir_si_validee(&mut self, etape: Etape) { | |
| 214 | + if self.validees.contains(&etape) { | |
| 215 | + self.a_revoir.insert(etape); | |
| 216 | + } | |
| 217 | + } | |
| 218 | + | |
| 219 | + pub fn enregistrer_organisation(&mut self, organisation: Organisation) { | |
| 220 | + let domaine_change = self.organisation.as_ref().is_some_and(|o| o.domaine != organisation.domaine); | |
| 221 | + self.organisation = Some(organisation); | |
| 222 | + self.valider_etape(Etape::Organisation); | |
| 223 | + if domaine_change { | |
| 224 | + self.revoir_si_validee(Etape::Securite); | |
| 225 | + } | |
| 226 | + } | |
| 227 | + | |
| 228 | + pub fn enregistrer_deploiement(&mut self, deploiement: Deploiement) { | |
| 229 | + self.deploiement = Some(deploiement); | |
| 230 | + self.valider_etape(Etape::Cibles); | |
| 231 | + } | |
| 232 | + | |
| 233 | + pub fn enregistrer_composants(&mut self, composants: BTreeSet<ComposantId>) { | |
| 234 | + let change = self.composants.as_ref().is_some_and(|c| *c != composants); | |
| 235 | + self.composants = Some(composants); | |
| 236 | + self.valider_etape(Etape::Composants); | |
| 237 | + if change { | |
| 238 | + self.revoir_si_validee(Etape::Securite); | |
| 239 | + if self.deploiement.as_ref().is_some_and(|d| d.topologie == crate::config::Topologie::Multi) { | |
| 240 | + self.revoir_si_validee(Etape::Cibles); | |
| 241 | + } | |
| 242 | + } | |
| 243 | + } | |
| 244 | + | |
| 245 | + pub fn enregistrer_securite(&mut self, securite: Securite) { | |
| 246 | + self.securite = Some(securite); | |
| 247 | + self.valider_etape(Etape::Securite); | |
| 248 | + } | |
| 249 | + | |
| 250 | + pub fn enregistrer_smtp(&mut self, smtp: Smtp) { | |
| 251 | + self.smtp = Some(smtp); | |
| 252 | + self.valider_etape(Etape::Messagerie); | |
| 253 | + } | |
| 254 | + | |
| 255 | + pub fn enregistrer_admin_initial(&mut self, admin: AdminInitial) { | |
| 256 | + self.admin_initial = Some(admin); | |
| 257 | + self.valider_etape(Etape::Comptes); | |
| 258 | + } | |
| 259 | + | |
| 260 | + pub fn enregistrer_exploitation(&mut self, exploitation: Exploitation) { | |
| 261 | + self.exploitation = Some(exploitation); | |
| 262 | + self.valider_etape(Etape::Telemetrie); | |
| 263 | + } | |
| 264 | + | |
| 265 | + /// Reprend une configuration importée (E-001) : toutes ses étapes sont validées. | |
| 266 | + pub fn depuis_config(config: OpenIamConfig) -> Self { | |
| 267 | + Self { | |
| 268 | + organisation: Some(config.organisation), | |
| 269 | + deploiement: Some(config.deploiement), | |
| 270 | + composants: Some(config.composants), | |
| 271 | + securite: Some(Securite { | |
| 272 | + services: config.services, | |
| 273 | + tls: config.tls, | |
| 274 | + mdp: config.mdp, | |
| 275 | + mfa: config.mfa, | |
| 276 | + }), | |
| 277 | + smtp: config.smtp, | |
| 278 | + admin_initial: Some(config.admin_initial), | |
| 279 | + exploitation: Some(Exploitation { | |
| 280 | + supervision: config.supervision, | |
| 281 | + telemetrie: config.telemetrie, | |
| 282 | + }), | |
| 283 | + validees: Etape::TOUTES.into(), | |
| 284 | + a_revoir: BTreeSet::new(), | |
| 285 | + } | |
| 286 | + } | |
| 287 | + | |
| 288 | + /// Configuration complète si toutes les étapes applicables sont validées et cohérentes. | |
| 289 | + pub fn config(&self) -> Result<OpenIamConfig, Vec<Constat>> { | |
| 290 | + let incompletes: Vec<Constat> = Etape::TOUTES | |
| 291 | + .into_iter() | |
| 292 | + .filter(|e| self.applicable(*e) && !self.complete(*e)) | |
| 293 | + .map(|e| Constat::erreur(chemin_section(e), format!("Étape « {} » à compléter.", e.libelle()))) | |
| 294 | + .collect(); | |
| 295 | + if !incompletes.is_empty() { | |
| 296 | + return Err(incompletes); | |
| 297 | + } | |
| 298 | + let manquant = |e: Etape| vec![Constat::erreur(chemin_section(e), "Section absente du brouillon.")]; | |
| 299 | + let securite = self.securite.clone().ok_or_else(|| manquant(Etape::Securite))?; | |
| 300 | + let exploitation = self.exploitation.clone().unwrap_or_default(); | |
| 301 | + let config = OpenIamConfig { | |
| 302 | + organisation: self.organisation.clone().ok_or_else(|| manquant(Etape::Organisation))?, | |
| 303 | + deploiement: self.deploiement.clone().ok_or_else(|| manquant(Etape::Cibles))?, | |
| 304 | + composants: self.composants.clone().ok_or_else(|| manquant(Etape::Composants))?, | |
| 305 | + services: securite.services, | |
| 306 | + tls: securite.tls, | |
| 307 | + mdp: securite.mdp, | |
| 308 | + mfa: securite.mfa, | |
| 309 | + smtp: if self.applicable(Etape::Messagerie) { self.smtp.clone() } else { None }, | |
| 310 | + admin_initial: self.admin_initial.clone().ok_or_else(|| manquant(Etape::Comptes))?, | |
| 311 | + supervision: exploitation.supervision, | |
| 312 | + telemetrie: exploitation.telemetrie, | |
| 313 | + }; | |
| 314 | + let erreurs: Vec<Constat> = | |
| 315 | + config.valider().into_iter().filter(|c| c.gravite == crate::config::Gravite::Erreur).collect(); | |
| 316 | + if erreurs.is_empty() { Ok(config) } else { Err(erreurs) } | |
| 317 | + } | |
| 318 | +} | |
| 319 | + | |
| 320 | +/// Chemin `openiam.yaml` de la section saisie par une étape. | |
| 321 | +fn chemin_section(etape: Etape) -> &'static str { | |
| 322 | + match etape { | |
| 323 | + Etape::Organisation => "organisation", | |
| 324 | + Etape::Cibles => "deploiement", | |
| 325 | + Etape::Composants => "composants", | |
| 326 | + Etape::Securite => "services", | |
| 327 | + Etape::Messagerie => "smtp", | |
| 328 | + Etape::Comptes => "admin_initial", | |
| 329 | + Etape::Telemetrie => "telemetrie", | |
| 330 | + Etape::Parametres => "composants_parametres", | |
| 331 | + } | |
| 332 | +} | |
| 333 | + | |
| 334 | +/// Persistance du brouillon dans le répertoire d'état de l'installeur. | |
| 335 | +pub struct Depot { | |
| 336 | + racine: PathBuf, | |
| 337 | +} | |
| 338 | + | |
| 339 | +#[derive(Debug, thiserror::Error)] | |
| 340 | +pub enum ErreurDepot { | |
| 341 | + #[error("accès au brouillon : {0}")] | |
| 342 | + Io(#[from] std::io::Error), | |
| 343 | + #[error("brouillon illisible : {0}")] | |
| 344 | + Yaml(#[from] serde_norway::Error), | |
| 345 | +} | |
| 346 | + | |
| 347 | +impl Depot { | |
| 348 | + pub const BROUILLON: &'static str = "draft.yaml"; | |
| 349 | + pub const SECRETS: &'static str = "draft-secrets.yaml"; | |
| 350 | + | |
| 351 | + /// Crée le répertoire d'état (0700) s'il n'existe pas. | |
| 352 | + pub fn ouvrir(racine: impl Into<PathBuf>) -> Result<Self, ErreurDepot> { | |
| 353 | + use std::os::unix::fs::PermissionsExt; | |
| 354 | + let racine = racine.into(); | |
| 355 | + fs::create_dir_all(&racine)?; | |
| 356 | + fs::set_permissions(&racine, fs::Permissions::from_mode(0o700))?; | |
| 357 | + Ok(Self { racine }) | |
| 358 | + } | |
| 359 | + | |
| 360 | + pub fn racine(&self) -> &Path { | |
| 361 | + &self.racine | |
| 362 | + } | |
| 363 | + | |
| 364 | + /// Brouillon et secrets enregistrés, ou `None` s'il n'y a pas de brouillon. | |
| 365 | + pub fn charger(&self) -> Result<Option<(Brouillon, Secrets)>, ErreurDepot> { | |
| 366 | + let Some(brouillon) = lire(&self.racine.join(Self::BROUILLON))? else { | |
| 367 | + return Ok(None); | |
| 368 | + }; | |
| 369 | + let secrets = lire(&self.racine.join(Self::SECRETS))?.unwrap_or_default(); | |
| 370 | + Ok(Some((brouillon, secrets))) | |
| 371 | + } | |
| 372 | + | |
| 373 | + /// Écriture atomique (fichier temporaire puis renommage), fichiers en 0600. | |
| 374 | + pub fn sauver(&self, brouillon: &Brouillon, secrets: &Secrets) -> Result<(), ErreurDepot> { | |
| 375 | + ecrire_0600(&self.racine.join(Self::SECRETS), &serde_norway::to_string(secrets)?)?; | |
| 376 | + ecrire_0600(&self.racine.join(Self::BROUILLON), &serde_norway::to_string(brouillon)?)?; | |
| 377 | + Ok(()) | |
| 378 | + } | |
| 379 | + | |
| 380 | + pub fn supprimer(&self) -> Result<(), ErreurDepot> { | |
| 381 | + for nom in [Self::BROUILLON, Self::SECRETS] { | |
| 382 | + match fs::remove_file(self.racine.join(nom)) { | |
| 383 | + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()), | |
| 384 | + _ => {} | |
| 385 | + } | |
| 386 | + } | |
| 387 | + Ok(()) | |
| 388 | + } | |
| 389 | + | |
| 390 | + /// Date de dernière modification du brouillon (carte « reprendre » de E-001). | |
| 391 | + pub fn modifie_le(&self) -> Option<std::time::SystemTime> { | |
| 392 | + fs::metadata(self.racine.join(Self::BROUILLON)).and_then(|m| m.modified()).ok() | |
| 393 | + } | |
| 394 | +} | |
| 395 | + | |
| 396 | +/// Lit un fichier YAML, `None` s'il n'existe pas. | |
| 397 | +fn lire<T: serde::de::DeserializeOwned>(chemin: &Path) -> Result<Option<T>, ErreurDepot> { | |
| 398 | + match fs::read_to_string(chemin) { | |
| 399 | + Ok(texte) => Ok(Some(serde_norway::from_str(&texte)?)), | |
| 400 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), | |
| 401 | + Err(e) => Err(e.into()), | |
| 402 | + } | |
| 403 | +} | |
| 404 | + | |
| 405 | +/// Écrit `contenu` en 0600 via un fichier temporaire renommé (pas de fichier à moitié écrit). | |
| 406 | +pub(crate) fn ecrire_0600(chemin: &Path, contenu: &str) -> std::io::Result<()> { | |
| 407 | + use std::os::unix::fs::OpenOptionsExt; | |
| 408 | + let temporaire = chemin.with_extension("tmp"); | |
| 409 | + let mut fichier = | |
| 410 | + fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&temporaire)?; | |
| 411 | + fichier.write_all(contenu.as_bytes())?; | |
| 412 | + fichier.sync_all()?; | |
| 413 | + fs::rename(&temporaire, chemin) | |
| 414 | +} | |
| 415 | + | |
| 416 | +#[cfg(test)] | |
| 417 | +mod tests { | |
| 418 | + use std::os::unix::fs::PermissionsExt; | |
| 419 | + | |
| 420 | + use super::*; | |
| 421 | + use crate::config::{Secret, tests::exemple}; | |
| 422 | + | |
| 423 | + fn securite() -> Securite { | |
| 424 | + let c = exemple(); | |
| 425 | + Securite { services: c.services, tls: c.tls, mdp: c.mdp, mfa: c.mfa } | |
| 426 | + } | |
| 427 | + | |
| 428 | + /// Brouillon dont les étapes jusqu'à `derniere` incluse sont validées. | |
| 429 | + fn rempli_jusqu_a(derniere: Etape) -> Brouillon { | |
| 430 | + let c = exemple(); | |
| 431 | + let mut b = Brouillon::default(); | |
| 432 | + for etape in Etape::TOUTES.into_iter().filter(|e| *e <= derniere) { | |
| 433 | + match etape { | |
| 434 | + Etape::Organisation => b.enregistrer_organisation(c.organisation.clone()), | |
| 435 | + Etape::Cibles => b.enregistrer_deploiement(c.deploiement.clone()), | |
| 436 | + Etape::Composants => b.enregistrer_composants(c.composants.clone()), | |
| 437 | + Etape::Securite => b.enregistrer_securite(securite()), | |
| 438 | + Etape::Messagerie | Etape::Parametres => {} | |
| 439 | + Etape::Comptes => b.enregistrer_admin_initial(c.admin_initial.clone()), | |
| 440 | + Etape::Telemetrie => b.enregistrer_exploitation(Exploitation::default()), | |
| 441 | + } | |
| 442 | + } | |
| 443 | + b | |
| 444 | + } | |
| 445 | + | |
| 446 | + fn etat(b: &Brouillon, etape: Etape) -> EtatEtape { | |
| 447 | + b.etats().into_iter().find(|(e, _)| *e == etape).unwrap().1 | |
| 448 | + } | |
| 449 | + | |
| 450 | + #[test] | |
| 451 | + fn un_brouillon_neuf_commence_a_l_organisation() { | |
| 452 | + let b = Brouillon::default(); | |
| 453 | + assert_eq!(b.etape_courante(), Some(Etape::Organisation)); | |
| 454 | + assert_eq!(etat(&b, Etape::Organisation), EtatEtape::EnCours); | |
| 455 | + assert_eq!(etat(&b, Etape::Cibles), EtatEtape::AFaire); | |
| 456 | + assert!(b.peut_acceder(Etape::Organisation)); | |
| 457 | + assert!(!b.peut_acceder(Etape::Cibles), "pas de saut en avant"); | |
| 458 | + } | |
| 459 | + | |
| 460 | + #[test] | |
| 461 | + fn valider_une_etape_fait_avancer() { | |
| 462 | + let b = rempli_jusqu_a(Etape::Organisation); | |
| 463 | + assert_eq!(etat(&b, Etape::Organisation), EtatEtape::Validee); | |
| 464 | + assert_eq!(b.etape_courante(), Some(Etape::Cibles)); | |
| 465 | + assert_eq!(b.suivante(Etape::Organisation), Some(Etape::Cibles)); | |
| 466 | + assert!(b.peut_acceder(Etape::Organisation), "retour sur une étape validée"); | |
| 467 | + } | |
| 468 | + | |
| 469 | + #[test] | |
| 470 | + fn la_messagerie_et_les_parametres_sont_sautes_si_aucun_composant_n_en_a_besoin() { | |
| 471 | + let b = rempli_jusqu_a(Etape::Securite); | |
| 472 | + assert_eq!(etat(&b, Etape::Messagerie), EtatEtape::Sautee); | |
| 473 | + assert_eq!(etat(&b, Etape::Parametres), EtatEtape::Sautee); | |
| 474 | + assert_eq!(b.suivante(Etape::Securite), Some(Etape::Comptes)); | |
| 475 | + assert!(!b.peut_acceder(Etape::Messagerie)); | |
| 476 | + } | |
| 477 | + | |
| 478 | + #[test] | |
| 479 | + fn le_parcours_complet_mene_au_recapitulatif() { | |
| 480 | + let b = rempli_jusqu_a(Etape::Telemetrie); | |
| 481 | + assert_eq!(b.etape_courante(), None); | |
| 482 | + assert_eq!(b.suivante(Etape::Telemetrie), None); | |
| 483 | + let config = b.config().unwrap(); | |
| 484 | + assert_eq!(config.organisation, exemple().organisation); | |
| 485 | + assert_eq!(config.composants, exemple().composants); | |
| 486 | + } | |
| 487 | + | |
| 488 | + #[test] | |
| 489 | + fn un_brouillon_incomplet_ne_produit_pas_de_configuration() { | |
| 490 | + let erreurs = rempli_jusqu_a(Etape::Securite).config().unwrap_err(); | |
| 491 | + assert!(erreurs.iter().any(|c| c.chemin == "admin_initial"), "{erreurs:?}"); | |
| 492 | + } | |
| 493 | + | |
| 494 | + #[test] | |
| 495 | + fn changer_les_composants_rend_la_messagerie_et_la_securite_a_revoir() { | |
| 496 | + let mut b = rempli_jusqu_a(Etape::Telemetrie); | |
| 497 | + let mut composants = exemple().composants; | |
| 498 | + composants.insert(ComposantId::Ssp); | |
| 499 | + b.enregistrer_composants(composants); | |
| 500 | + | |
| 501 | + assert_eq!(etat(&b, Etape::Securite), EtatEtape::ARevoir); | |
| 502 | + assert_eq!(etat(&b, Etape::Messagerie), EtatEtape::EnCours, "désormais applicable et vide"); | |
| 503 | + assert_eq!(b.etape_courante(), Some(Etape::Securite)); | |
| 504 | + assert!(b.config().is_err(), "récapitulatif bloqué tant qu'une étape est à revoir"); | |
| 505 | + } | |
| 506 | + | |
| 507 | + #[test] | |
| 508 | + fn reenregistrer_les_memes_composants_n_invalide_rien() { | |
| 509 | + let mut b = rempli_jusqu_a(Etape::Telemetrie); | |
| 510 | + b.enregistrer_composants(exemple().composants); | |
| 511 | + assert_eq!(b.etape_courante(), None); | |
| 512 | + } | |
| 513 | + | |
| 514 | + #[test] | |
| 515 | + fn changer_le_domaine_rend_la_securite_a_revoir() { | |
| 516 | + let mut b = rempli_jusqu_a(Etape::Telemetrie); | |
| 517 | + let mut organisation = exemple().organisation; | |
| 518 | + organisation.domaine = "autre.fr".into(); | |
| 519 | + b.enregistrer_organisation(organisation); | |
| 520 | + assert_eq!(etat(&b, Etape::Securite), EtatEtape::ARevoir); | |
| 521 | + assert!(b.peut_acceder(Etape::Securite)); | |
| 522 | + } | |
| 523 | + | |
| 524 | + #[test] | |
| 525 | + fn valider_une_etape_a_revoir_la_remet_en_validee() { | |
| 526 | + let mut b = rempli_jusqu_a(Etape::Telemetrie); | |
| 527 | + let mut organisation = exemple().organisation; | |
| 528 | + organisation.domaine = "autre.fr".into(); | |
| 529 | + b.enregistrer_organisation(organisation); | |
| 530 | + b.enregistrer_securite(securite()); | |
| 531 | + assert_eq!(etat(&b, Etape::Securite), EtatEtape::Validee); | |
| 532 | + } | |
| 533 | + | |
| 534 | + #[test] | |
| 535 | + fn une_configuration_importee_valide_toutes_les_etapes() { | |
| 536 | + let b = Brouillon::depuis_config(exemple()); | |
| 537 | + assert_eq!(b.etape_courante(), None); | |
| 538 | + assert_eq!(b.config().unwrap(), exemple()); | |
| 539 | + } | |
| 540 | + | |
| 541 | + #[test] | |
| 542 | + fn le_brouillon_survit_a_un_redemarrage() { | |
| 543 | + let dossier = tempfile::tempdir().unwrap(); | |
| 544 | + let racine = dossier.path().join("etat"); | |
| 545 | + let secrets = Secrets { | |
| 546 | + ldap_admin_mot_de_passe: Some(Secret::new("Urgence-0123456789!")), | |
| 547 | + ..Default::default() | |
| 548 | + }; | |
| 549 | + let b = rempli_jusqu_a(Etape::Securite); | |
| 550 | + | |
| 551 | + Depot::ouvrir(&racine).unwrap().sauver(&b, &secrets).unwrap(); | |
| 552 | + let (relu, secrets_relus) = Depot::ouvrir(&racine).unwrap().charger().unwrap().unwrap(); | |
| 553 | + assert_eq!(relu, b); | |
| 554 | + assert_eq!(secrets_relus, secrets); | |
| 555 | + } | |
| 556 | + | |
| 557 | + #[test] | |
| 558 | + fn les_fichiers_d_etat_sont_proteges_et_les_secrets_separes() { | |
| 559 | + let dossier = tempfile::tempdir().unwrap(); | |
| 560 | + let racine = dossier.path().join("etat"); | |
| 561 | + let depot = Depot::ouvrir(&racine).unwrap(); | |
| 562 | + let secrets = Secrets { | |
| 563 | + ldap_admin_mot_de_passe: Some(Secret::new("Urgence-0123456789!")), | |
| 564 | + ..Default::default() | |
| 565 | + }; | |
| 566 | + depot.sauver(&rempli_jusqu_a(Etape::Organisation), &secrets).unwrap(); | |
| 567 | + | |
| 568 | + let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777; | |
| 569 | + assert_eq!(mode(&racine), 0o700); | |
| 570 | + assert_eq!(mode(&racine.join(Depot::BROUILLON)), 0o600); | |
| 571 | + assert_eq!(mode(&racine.join(Depot::SECRETS)), 0o600); | |
| 572 | + assert!(!fs::read_to_string(racine.join(Depot::BROUILLON)).unwrap().contains("Urgence")); | |
| 573 | + } | |
| 574 | + | |
| 575 | + #[test] | |
| 576 | + fn sans_brouillon_charger_renvoie_rien_et_supprimer_efface_tout() { | |
| 577 | + let dossier = tempfile::tempdir().unwrap(); | |
| 578 | + let depot = Depot::ouvrir(dossier.path().join("etat")).unwrap(); | |
| 579 | + assert!(depot.charger().unwrap().is_none()); | |
| 580 | + | |
| 581 | + depot.sauver(&Brouillon::default(), &Secrets::default()).unwrap(); | |
| 582 | + depot.supprimer().unwrap(); | |
| 583 | + assert!(depot.charger().unwrap().is_none()); | |
| 584 | + assert!(!depot.racine().join(Depot::SECRETS).exists()); | |
| 585 | + } | |
| 586 | +} |
A
installer/src/catalogue.rs
+442
-0
@@ -0,0 +1,442 @@
| 1 | +//! Catalogue des composants installables (OI-021, fiche E-004) : source unique des | |
| 2 | +//! dépendances, des rôles d'hôte, des services exposés et des ressources estimées. | |
| 3 | + | |
| 4 | +use std::collections::{BTreeMap, BTreeSet}; | |
| 5 | + | |
| 6 | +use serde::{Deserialize, Serialize}; | |
| 7 | + | |
| 8 | +use crate::config::{Constat, Service}; | |
| 9 | + | |
| 10 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] | |
| 11 | +#[serde(rename_all = "snake_case")] | |
| 12 | +pub enum ComposantId { | |
| 13 | + Openldap, | |
| 14 | + Ssp, | |
| 15 | + WhitePages, | |
| 16 | + ServiceDesk, | |
| 17 | + Lemonldap, | |
| 18 | + LscAd, | |
| 19 | + Sssd, | |
| 20 | + Samba, | |
| 21 | + Replication, | |
| 22 | + Supervision, | |
| 23 | + DependencyTrack, | |
| 24 | + Sauvegarde, | |
| 25 | +} | |
| 26 | + | |
| 27 | +/// Rôle qu'un hôte doit porter pour recevoir un composant (E-003). | |
| 28 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] | |
| 29 | +#[serde(rename_all = "lowercase")] | |
| 30 | +pub enum RoleHote { | |
| 31 | + Annuaire, | |
| 32 | + Sso, | |
| 33 | + Outils, | |
| 34 | + Supervision, | |
| 35 | + Samba, | |
| 36 | +} | |
| 37 | + | |
| 38 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] | |
| 39 | +pub enum Groupe { | |
| 40 | + Socle, | |
| 41 | + LibreService, | |
| 42 | + SsoMfa, | |
| 43 | + Migration, | |
| 44 | + Postes, | |
| 45 | + HauteDisponibilite, | |
| 46 | + Exploitation, | |
| 47 | +} | |
| 48 | + | |
| 49 | +impl Groupe { | |
| 50 | + pub fn libelle(self) -> &'static str { | |
| 51 | + match self { | |
| 52 | + Self::Socle => "Socle", | |
| 53 | + Self::LibreService => "Libre-service", | |
| 54 | + Self::SsoMfa => "SSO et double authentification", | |
| 55 | + Self::Migration => "Migration", | |
| 56 | + Self::Postes => "Postes de travail", | |
| 57 | + Self::HauteDisponibilite => "Haute disponibilité", | |
| 58 | + Self::Exploitation => "Exploitation", | |
| 59 | + } | |
| 60 | + } | |
| 61 | +} | |
| 62 | + | |
| 63 | +/// Un composant n'est sélectionnable que si son déploiement est implémenté. | |
| 64 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 65 | +pub enum Disponibilite { | |
| 66 | + Disponible, | |
| 67 | + /// Jalon du backlog qui le livrera (ex. `"M2"`). | |
| 68 | + Jalon(&'static str), | |
| 69 | +} | |
| 70 | + | |
| 71 | +#[derive(Debug)] | |
| 72 | +pub struct Composant { | |
| 73 | + pub id: ComposantId, | |
| 74 | + pub groupe: Groupe, | |
| 75 | + pub nom: &'static str, | |
| 76 | + pub description: &'static str, | |
| 77 | + pub disponibilite: Disponibilite, | |
| 78 | + pub par_defaut: bool, | |
| 79 | + /// Toujours installé : case cochée et non modifiable. | |
| 80 | + pub verrouille: bool, | |
| 81 | + pub dependances: &'static [ComposantId], | |
| 82 | + pub role_hote: RoleHote, | |
| 83 | + pub envoie_mail: bool, | |
| 84 | + /// Possède un sous-écran de paramètres (E-009). | |
| 85 | + pub a_parametres: bool, | |
| 86 | + pub services: &'static [Service], | |
| 87 | + pub ram_mo: u32, | |
| 88 | + pub disque_go: u32, | |
| 89 | +} | |
| 90 | + | |
| 91 | +use ComposantId as C; | |
| 92 | +use Disponibilite::{Disponible, Jalon}; | |
| 93 | + | |
| 94 | +pub const CATALOGUE: &[Composant] = &[ | |
| 95 | + Composant { | |
| 96 | + id: C::Openldap, | |
| 97 | + groupe: Groupe::Socle, | |
| 98 | + nom: "Annuaire OpenLDAP (LTB)", | |
| 99 | + description: "L'annuaire de référence : comptes, groupes et politique de mots de passe.", | |
| 100 | + disponibilite: Disponible, | |
| 101 | + par_defaut: true, | |
| 102 | + verrouille: true, | |
| 103 | + dependances: &[], | |
| 104 | + role_hote: RoleHote::Annuaire, | |
| 105 | + envoie_mail: false, | |
| 106 | + a_parametres: false, | |
| 107 | + services: &[Service::Annuaire], | |
| 108 | + ram_mo: 512, | |
| 109 | + disque_go: 5, | |
| 110 | + }, | |
| 111 | + Composant { | |
| 112 | + id: C::Ssp, | |
| 113 | + groupe: Groupe::LibreService, | |
| 114 | + nom: "Self Service Password", | |
| 115 | + description: "Les utilisateurs changent ou réinitialisent eux-mêmes leur mot de passe.", | |
| 116 | + disponibilite: Jalon("M2"), | |
| 117 | + par_defaut: true, | |
| 118 | + verrouille: false, | |
| 119 | + dependances: &[C::Openldap], | |
| 120 | + role_hote: RoleHote::Outils, | |
| 121 | + envoie_mail: true, | |
| 122 | + a_parametres: false, | |
| 123 | + services: &[Service::Mdp], | |
| 124 | + ram_mo: 128, | |
| 125 | + disque_go: 1, | |
| 126 | + }, | |
| 127 | + Composant { | |
| 128 | + id: C::WhitePages, | |
| 129 | + groupe: Groupe::LibreService, | |
| 130 | + nom: "White Pages", | |
| 131 | + description: "Annuaire consultable : recherche de collègues, trombinoscope.", | |
| 132 | + disponibilite: Jalon("M2"), | |
| 133 | + par_defaut: true, | |
| 134 | + verrouille: false, | |
| 135 | + dependances: &[C::Openldap], | |
| 136 | + role_hote: RoleHote::Outils, | |
| 137 | + envoie_mail: false, | |
| 138 | + a_parametres: false, | |
| 139 | + services: &[Service::Pages], | |
| 140 | + ram_mo: 128, | |
| 141 | + disque_go: 1, | |
| 142 | + }, | |
| 143 | + Composant { | |
| 144 | + id: C::ServiceDesk, | |
| 145 | + groupe: Groupe::LibreService, | |
| 146 | + nom: "Service Desk", | |
| 147 | + description: "Outil du support : déverrouiller un compte, réinitialiser un mot de passe.", | |
| 148 | + disponibilite: Jalon("M2"), | |
| 149 | + par_defaut: true, | |
| 150 | + verrouille: false, | |
| 151 | + dependances: &[C::Openldap], | |
| 152 | + role_hote: RoleHote::Outils, | |
| 153 | + envoie_mail: true, | |
| 154 | + a_parametres: false, | |
| 155 | + services: &[Service::Support], | |
| 156 | + ram_mo: 128, | |
| 157 | + disque_go: 1, | |
| 158 | + }, | |
| 159 | + Composant { | |
| 160 | + id: C::Lemonldap, | |
| 161 | + groupe: Groupe::SsoMfa, | |
| 162 | + nom: "LemonLDAP::NG", | |
| 163 | + description: "Authentification unique (OIDC, SAML, CAS) et double authentification.", | |
| 164 | + disponibilite: Jalon("M4"), | |
| 165 | + par_defaut: false, | |
| 166 | + verrouille: false, | |
| 167 | + dependances: &[C::Openldap], | |
| 168 | + role_hote: RoleHote::Sso, | |
| 169 | + envoie_mail: true, | |
| 170 | + a_parametres: false, | |
| 171 | + services: &[Service::Auth], | |
| 172 | + ram_mo: 512, | |
| 173 | + disque_go: 2, | |
| 174 | + }, | |
| 175 | + Composant { | |
| 176 | + id: C::LscAd, | |
| 177 | + groupe: Groupe::Migration, | |
| 178 | + nom: "Synchronisation Active Directory (LSC)", | |
| 179 | + description: "Importe et synchronise un ou plusieurs Active Directory.", | |
| 180 | + disponibilite: Jalon("M5"), | |
| 181 | + par_defaut: false, | |
| 182 | + verrouille: false, | |
| 183 | + dependances: &[C::Openldap], | |
| 184 | + role_hote: RoleHote::Annuaire, | |
| 185 | + envoie_mail: false, | |
| 186 | + a_parametres: true, | |
| 187 | + services: &[], | |
| 188 | + ram_mo: 512, | |
| 189 | + disque_go: 1, | |
| 190 | + }, | |
| 191 | + Composant { | |
| 192 | + id: C::Sssd, | |
| 193 | + groupe: Groupe::Postes, | |
| 194 | + nom: "Postes Linux (SSSD)", | |
| 195 | + description: "Connexion aux postes et serveurs Linux avec les comptes de l'annuaire.", | |
| 196 | + disponibilite: Jalon("M6"), | |
| 197 | + par_defaut: false, | |
| 198 | + verrouille: false, | |
| 199 | + dependances: &[C::Openldap], | |
| 200 | + role_hote: RoleHote::Annuaire, | |
| 201 | + envoie_mail: false, | |
| 202 | + a_parametres: true, | |
| 203 | + services: &[], | |
| 204 | + ram_mo: 0, | |
| 205 | + disque_go: 0, | |
| 206 | + }, | |
| 207 | + Composant { | |
| 208 | + id: C::Samba, | |
| 209 | + groupe: Groupe::Postes, | |
| 210 | + nom: "Postes Windows (Samba AD)", | |
| 211 | + description: "Jonction de postes Windows à un domaine alimenté par l'annuaire.", | |
| 212 | + disponibilite: Jalon("M6"), | |
| 213 | + par_defaut: false, | |
| 214 | + verrouille: false, | |
| 215 | + dependances: &[C::Openldap], | |
| 216 | + role_hote: RoleHote::Samba, | |
| 217 | + envoie_mail: false, | |
| 218 | + a_parametres: true, | |
| 219 | + services: &[], | |
| 220 | + ram_mo: 1024, | |
| 221 | + disque_go: 5, | |
| 222 | + }, | |
| 223 | + Composant { | |
| 224 | + id: C::Replication, | |
| 225 | + groupe: Groupe::HauteDisponibilite, | |
| 226 | + nom: "Réplication multi-maître", | |
| 227 | + description: "Plusieurs serveurs d'annuaire synchronisés : l'annuaire reste disponible si l'un tombe.", | |
| 228 | + disponibilite: Jalon("M7"), | |
| 229 | + par_defaut: false, | |
| 230 | + verrouille: false, | |
| 231 | + dependances: &[C::Openldap], | |
| 232 | + role_hote: RoleHote::Annuaire, | |
| 233 | + envoie_mail: false, | |
| 234 | + a_parametres: true, | |
| 235 | + services: &[], | |
| 236 | + ram_mo: 0, | |
| 237 | + disque_go: 0, | |
| 238 | + }, | |
| 239 | + Composant { | |
| 240 | + id: C::Supervision, | |
| 241 | + groupe: Groupe::Exploitation, | |
| 242 | + nom: "Supervision (Prometheus, Loki, Grafana)", | |
| 243 | + description: "Tableaux de bord, journaux centralisés et alertes, sur vos serveurs.", | |
| 244 | + disponibilite: Jalon("M2"), | |
| 245 | + par_defaut: true, | |
| 246 | + verrouille: false, | |
| 247 | + dependances: &[], | |
| 248 | + role_hote: RoleHote::Supervision, | |
| 249 | + envoie_mail: true, | |
| 250 | + a_parametres: false, | |
| 251 | + services: &[Service::Supervision], | |
| 252 | + ram_mo: 1536, | |
| 253 | + disque_go: 20, | |
| 254 | + }, | |
| 255 | + Composant { | |
| 256 | + id: C::DependencyTrack, | |
| 257 | + groupe: Groupe::Exploitation, | |
| 258 | + nom: "Analyse des vulnérabilités (Dependency-Track)", | |
| 259 | + description: "Suit les vulnérabilités connues des logiciels installés.", | |
| 260 | + disponibilite: Jalon("M3"), | |
| 261 | + par_defaut: false, | |
| 262 | + verrouille: false, | |
| 263 | + dependances: &[], | |
| 264 | + role_hote: RoleHote::Supervision, | |
| 265 | + envoie_mail: true, | |
| 266 | + a_parametres: false, | |
| 267 | + services: &[Service::Vuln], | |
| 268 | + ram_mo: 4096, | |
| 269 | + disque_go: 10, | |
| 270 | + }, | |
| 271 | + Composant { | |
| 272 | + id: C::Sauvegarde, | |
| 273 | + groupe: Groupe::Exploitation, | |
| 274 | + nom: "Sauvegardes chiffrées", | |
| 275 | + description: "Sauvegarde quotidienne chiffrée de l'annuaire, avec test de restauration.", | |
| 276 | + disponibilite: Disponible, | |
| 277 | + par_defaut: true, | |
| 278 | + verrouille: true, | |
| 279 | + dependances: &[C::Openldap], | |
| 280 | + role_hote: RoleHote::Annuaire, | |
| 281 | + envoie_mail: false, | |
| 282 | + a_parametres: false, | |
| 283 | + services: &[], | |
| 284 | + ram_mo: 0, | |
| 285 | + disque_go: 5, | |
| 286 | + }, | |
| 287 | +]; | |
| 288 | + | |
| 289 | +pub fn composant(id: ComposantId) -> &'static Composant { | |
| 290 | + CATALOGUE.iter().find(|c| c.id == id).expect("tout ComposantId figure au catalogue") | |
| 291 | +} | |
| 292 | + | |
| 293 | +/// Sélection par défaut proposée en E-004 : composants disponibles cochés par défaut. | |
| 294 | +pub fn selection_par_defaut() -> BTreeSet<ComposantId> { | |
| 295 | + CATALOGUE.iter().filter(|c| c.par_defaut && c.disponibilite == Disponible).map(|c| c.id).collect() | |
| 296 | +} | |
| 297 | + | |
| 298 | +/// Résultat de la résolution des dépendances. | |
| 299 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 300 | +pub struct Resolution { | |
| 301 | + pub composants: BTreeSet<ComposantId>, | |
| 302 | + /// Pour chaque composant ajouté ou verrouillé par dépendance : les composants qui l'exigent. | |
| 303 | + pub requis_par: BTreeMap<ComposantId, BTreeSet<ComposantId>>, | |
| 304 | +} | |
| 305 | + | |
| 306 | +/// Complète la sélection par les composants verrouillés et la fermeture transitive des | |
| 307 | +/// dépendances. Refuse les composants qui ne sont pas encore disponibles. | |
| 308 | +pub fn resoudre(selection: &BTreeSet<ComposantId>) -> Result<Resolution, Vec<Constat>> { | |
| 309 | + let indisponibles: Vec<Constat> = selection | |
| 310 | + .iter() | |
| 311 | + .filter_map(|id| match composant(*id).disponibilite { | |
| 312 | + Disponible => None, | |
| 313 | + Jalon(jalon) => Some(Constat::erreur( | |
| 314 | + format!("composants.{}", cle(*id)), | |
| 315 | + format!( | |
| 316 | + "« {} » n'est pas encore disponible : il arrive au jalon {jalon}.", | |
| 317 | + composant(*id).nom | |
| 318 | + ), | |
| 319 | + )), | |
| 320 | + }) | |
| 321 | + .collect(); | |
| 322 | + if !indisponibles.is_empty() { | |
| 323 | + return Err(indisponibles); | |
| 324 | + } | |
| 325 | + | |
| 326 | + let mut composants: BTreeSet<ComposantId> = | |
| 327 | + selection.iter().copied().chain(CATALOGUE.iter().filter(|c| c.verrouille).map(|c| c.id)).collect(); | |
| 328 | + let mut requis_par: BTreeMap<ComposantId, BTreeSet<ComposantId>> = BTreeMap::new(); | |
| 329 | + let mut a_traiter: Vec<ComposantId> = composants.iter().copied().collect(); | |
| 330 | + while let Some(id) = a_traiter.pop() { | |
| 331 | + for dependance in composant(id).dependances { | |
| 332 | + requis_par.entry(*dependance).or_default().insert(id); | |
| 333 | + if composants.insert(*dependance) { | |
| 334 | + a_traiter.push(*dependance); | |
| 335 | + } | |
| 336 | + } | |
| 337 | + } | |
| 338 | + Ok(Resolution { composants, requis_par }) | |
| 339 | +} | |
| 340 | + | |
| 341 | +/// Clé `openiam.yaml` d'un composant (ex. `white_pages`). | |
| 342 | +pub fn cle(id: ComposantId) -> String { | |
| 343 | + serde_norway::to_string(&id).expect("sérialisation d'une énumération").trim().to_owned() | |
| 344 | +} | |
| 345 | + | |
| 346 | +/// Rôles d'hôte nécessaires pour installer ces composants. | |
| 347 | +pub fn roles_requis(composants: &BTreeSet<ComposantId>) -> BTreeSet<RoleHote> { | |
| 348 | + composants.iter().map(|id| composant(*id).role_hote).collect() | |
| 349 | +} | |
| 350 | + | |
| 351 | +/// Services exposés par ces composants (noms DNS à définir en E-005). | |
| 352 | +pub fn services(composants: &BTreeSet<ComposantId>) -> BTreeSet<Service> { | |
| 353 | + composants.iter().flat_map(|id| composant(*id).services.iter().copied()).collect() | |
| 354 | +} | |
| 355 | + | |
| 356 | +/// Un composant choisi envoie-t-il des e-mails (condition d'affichage de E-006) ? | |
| 357 | +pub fn envoie_mail(composants: &BTreeSet<ComposantId>) -> bool { | |
| 358 | + composants.iter().any(|id| composant(*id).envoie_mail) | |
| 359 | +} | |
| 360 | + | |
| 361 | +/// Ressources estimées (RAM en Mo, disque en Go), socle système inclus. | |
| 362 | +pub fn ressources(composants: &BTreeSet<ComposantId>) -> (u32, u32) { | |
| 363 | + /// Système, Ansible, installeur et journaux. | |
| 364 | + const SOCLE: (u32, u32) = (512, 5); | |
| 365 | + composants | |
| 366 | + .iter() | |
| 367 | + .map(|id| composant(*id)) | |
| 368 | + .fold(SOCLE, |(ram, disque), c| (ram + c.ram_mo, disque + c.disque_go)) | |
| 369 | +} | |
| 370 | + | |
| 371 | +#[cfg(test)] | |
| 372 | +mod tests { | |
| 373 | + use super::*; | |
| 374 | + | |
| 375 | + fn ensemble(ids: &[ComposantId]) -> BTreeSet<ComposantId> { | |
| 376 | + ids.iter().copied().collect() | |
| 377 | + } | |
| 378 | + | |
| 379 | + #[test] | |
| 380 | + fn chaque_composant_figure_une_seule_fois_au_catalogue() { | |
| 381 | + let ids: BTreeSet<_> = CATALOGUE.iter().map(|c| c.id).collect(); | |
| 382 | + assert_eq!(ids.len(), CATALOGUE.len()); | |
| 383 | + } | |
| 384 | + | |
| 385 | + #[test] | |
| 386 | + fn les_dependances_pointent_vers_des_composants_du_catalogue_sans_cycle() { | |
| 387 | + for c in CATALOGUE { | |
| 388 | + for d in c.dependances { | |
| 389 | + assert_ne!(*d, c.id, "{:?} dépend de lui-même", c.id); | |
| 390 | + assert!(composant(*d).dependances.iter().all(|dd| *dd != c.id), "cycle {:?} ↔ {d:?}", c.id); | |
| 391 | + } | |
| 392 | + } | |
| 393 | + } | |
| 394 | + | |
| 395 | + #[test] | |
| 396 | + fn la_selection_vide_contient_les_composants_verrouilles() { | |
| 397 | + let r = resoudre(&BTreeSet::new()).unwrap(); | |
| 398 | + assert_eq!(r.composants, ensemble(&[C::Openldap, C::Sauvegarde])); | |
| 399 | + } | |
| 400 | + | |
| 401 | + #[test] | |
| 402 | + fn la_sauvegarde_est_marquee_comme_requerant_l_annuaire() { | |
| 403 | + let r = resoudre(&BTreeSet::new()).unwrap(); | |
| 404 | + assert_eq!(r.requis_par[&C::Openldap], ensemble(&[C::Sauvegarde])); | |
| 405 | + } | |
| 406 | + | |
| 407 | + #[test] | |
| 408 | + fn un_composant_pas_encore_disponible_est_refuse_avec_son_jalon() { | |
| 409 | + let erreurs = resoudre(&ensemble(&[C::Ssp])).unwrap_err(); | |
| 410 | + assert_eq!(erreurs.len(), 1); | |
| 411 | + assert_eq!(erreurs[0].chemin, "composants.ssp"); | |
| 412 | + assert!(erreurs[0].message.contains("M2"), "{}", erreurs[0].message); | |
| 413 | + } | |
| 414 | + | |
| 415 | + #[test] | |
| 416 | + fn la_selection_par_defaut_ne_propose_que_des_composants_disponibles() { | |
| 417 | + assert_eq!(selection_par_defaut(), ensemble(&[C::Openldap, C::Sauvegarde])); | |
| 418 | + assert!(resoudre(&selection_par_defaut()).is_ok()); | |
| 419 | + } | |
| 420 | + | |
| 421 | + #[test] | |
| 422 | + fn les_roles_et_services_derivent_des_composants() { | |
| 423 | + let tous_l1 = ensemble(&[C::Openldap, C::Ssp, C::Supervision]); | |
| 424 | + assert_eq!( | |
| 425 | + roles_requis(&tous_l1), | |
| 426 | + [RoleHote::Annuaire, RoleHote::Outils, RoleHote::Supervision].into() | |
| 427 | + ); | |
| 428 | + assert_eq!(services(&tous_l1), [Service::Annuaire, Service::Mdp, Service::Supervision].into()); | |
| 429 | + } | |
| 430 | + | |
| 431 | + #[test] | |
| 432 | + fn la_messagerie_n_est_requise_que_si_un_composant_envoie_des_e_mails() { | |
| 433 | + assert!(!envoie_mail(&ensemble(&[C::Openldap, C::Sauvegarde]))); | |
| 434 | + assert!(envoie_mail(&ensemble(&[C::Openldap, C::Ssp]))); | |
| 435 | + } | |
| 436 | + | |
| 437 | + #[test] | |
| 438 | + fn les_ressources_incluent_le_socle_systeme() { | |
| 439 | + let (ram, disque) = ressources(&ensemble(&[C::Openldap, C::Sauvegarde])); | |
| 440 | + assert_eq!((ram, disque), (512 + 512, 5 + 5 + 5)); | |
| 441 | + } | |
| 442 | +} |
A
installer/src/config/ansible.rs
+59
-0
@@ -0,0 +1,59 @@
| 1 | +//! Traduction de la configuration en variables Ansible (`group_vars/all.yml`) et en | |
| 2 | +//! fichier de secrets (`secrets.yml`, ensuite chiffré par ansible-vault). | |
| 3 | +//! Préfixe des variables : `oiam_`. | |
| 4 | + | |
| 5 | +use serde::Serialize; | |
| 6 | +use serde_norway::{Mapping, Value}; | |
| 7 | + | |
| 8 | +use super::{OpenIamConfig, Secrets}; | |
| 9 | +use crate::catalogue; | |
| 10 | + | |
| 11 | +/// Noms de code des dépôts LTB par distribution (plan M1, Q-03). | |
| 12 | +const OS_CODENAMES: [(&str, &str); 2] = [("debian", "trixie"), ("ubuntu", "resolute")]; | |
| 13 | + | |
| 14 | +/// Variables non secrètes transmises à tous les hôtes. | |
| 15 | +pub fn group_vars(config: &OpenIamConfig) -> String { | |
| 16 | + let composants: Vec<String> = config.composants.iter().map(|id| catalogue::cle(*id)).collect(); | |
| 17 | + let vars = mapping([ | |
| 18 | + ("oiam_organisation", Value::from(config.organisation.nom.as_str())), | |
| 19 | + ("oiam_domaine", Value::from(config.organisation.domaine.as_str())), | |
| 20 | + ("oiam_base_dn", Value::from(config.organisation.base_dn.as_str())), | |
| 21 | + ("oiam_langue", valeur(config.organisation.langue)), | |
| 22 | + ("oiam_fuseau", Value::from(config.organisation.fuseau.as_str())), | |
| 23 | + ("oiam_mode", valeur(config.deploiement.mode)), | |
| 24 | + ("oiam_composants", valeur(composants)), | |
| 25 | + ("oiam_services", valeur(&config.services)), | |
| 26 | + ("oiam_tls_mode", valeur(config.tls.mode)), | |
| 27 | + ("oiam_acme_email", valeur(&config.tls.acme_email)), | |
| 28 | + ("oiam_mdp", valeur(config.mdp)), | |
| 29 | + ("oiam_mfa", valeur(&config.mfa)), | |
| 30 | + ("oiam_smtp", valeur(&config.smtp)), | |
| 31 | + ("oiam_admin_initial", valeur(&config.admin_initial)), | |
| 32 | + ("oiam_supervision", valeur(&config.supervision)), | |
| 33 | + ("oiam_os_codenames", mapping(OS_CODENAMES.map(|(os, nom)| (os, Value::from(nom))))), | |
| 34 | + ]); | |
| 35 | + serde_norway::to_string(&vars).expect("sérialisation YAML") | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// Variables secrètes (texte clair : à chiffrer avant écriture sur disque). | |
| 39 | +pub fn secrets_vars(secrets: &Secrets) -> String { | |
| 40 | + let paires = [ | |
| 41 | + ("oiam_ldap_admin_mot_de_passe", &secrets.ldap_admin_mot_de_passe), | |
| 42 | + ("oiam_admin_initial_mot_de_passe", &secrets.admin_initial_mot_de_passe), | |
| 43 | + ("oiam_smtp_mot_de_passe", &secrets.smtp_mot_de_passe), | |
| 44 | + ]; | |
| 45 | + let vars = mapping( | |
| 46 | + paires | |
| 47 | + .into_iter() | |
| 48 | + .filter_map(|(nom, secret)| secret.as_ref().map(|s| (nom, Value::from(s.exposer())))), | |
| 49 | + ); | |
| 50 | + serde_norway::to_string(&vars).expect("sérialisation YAML") | |
| 51 | +} | |
| 52 | + | |
| 53 | +fn valeur(v: impl Serialize) -> Value { | |
| 54 | + serde_norway::to_value(v).expect("sérialisation YAML") | |
| 55 | +} | |
| 56 | + | |
| 57 | +fn mapping(paires: impl IntoIterator<Item = (&'static str, Value)>) -> Value { | |
| 58 | + Value::Mapping(paires.into_iter().map(|(k, v)| (Value::from(k), v)).collect::<Mapping>()) | |
| 59 | +} |
A
installer/src/config/mod.rs
+609
-0
@@ -0,0 +1,609 @@
| 1 | +//! Modèle de configuration `openiam.yaml` (OI-020) : source unique de ce que l'assistant | |
| 2 | +//! collecte et de ce qu'Ansible reçoit. Les secrets sont dans [`Secrets`], jamais ici. | |
| 3 | + | |
| 4 | +pub mod ansible; | |
| 5 | +pub mod secrets; | |
| 6 | +pub mod validation; | |
| 7 | + | |
| 8 | +use std::collections::{BTreeMap, BTreeSet}; | |
| 9 | + | |
| 10 | +use serde::{Deserialize, Serialize}; | |
| 11 | + | |
| 12 | +use crate::catalogue::{self, ComposantId}; | |
| 13 | +pub use secrets::{Secret, Secrets}; | |
| 14 | + | |
| 15 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 16 | +#[serde(deny_unknown_fields)] | |
| 17 | +pub struct OpenIamConfig { | |
| 18 | + pub organisation: Organisation, | |
| 19 | + pub deploiement: Deploiement, | |
| 20 | + pub composants: BTreeSet<ComposantId>, | |
| 21 | + pub services: BTreeMap<Service, String>, | |
| 22 | + pub tls: Tls, | |
| 23 | + pub mdp: PolitiqueMdp, | |
| 24 | + #[serde(default)] | |
| 25 | + pub mfa: Mfa, | |
| 26 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 27 | + pub smtp: Option<Smtp>, | |
| 28 | + pub admin_initial: AdminInitial, | |
| 29 | + #[serde(default)] | |
| 30 | + pub supervision: Supervision, | |
| 31 | + #[serde(default)] | |
| 32 | + pub telemetrie: Telemetrie, | |
| 33 | +} | |
| 34 | + | |
| 35 | +// --- E-002 Organisation --------------------------------------------------------------- | |
| 36 | + | |
| 37 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 38 | +#[serde(deny_unknown_fields)] | |
| 39 | +pub struct Organisation { | |
| 40 | + pub nom: String, | |
| 41 | + pub domaine: String, | |
| 42 | + pub base_dn: String, | |
| 43 | + pub langue: Langue, | |
| 44 | + pub fuseau: String, | |
| 45 | +} | |
| 46 | + | |
| 47 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 48 | +#[serde(rename_all = "lowercase")] | |
| 49 | +pub enum Langue { | |
| 50 | + #[default] | |
| 51 | + Fr, | |
| 52 | + En, | |
| 53 | +} | |
| 54 | + | |
| 55 | +// --- E-003 Mode et cibles ------------------------------------------------------------- | |
| 56 | + | |
| 57 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 58 | +#[serde(deny_unknown_fields)] | |
| 59 | +pub struct Deploiement { | |
| 60 | + pub mode: Mode, | |
| 61 | + pub topologie: Topologie, | |
| 62 | + #[serde(default, skip_serializing_if = "Vec::is_empty")] | |
| 63 | + pub hotes: Vec<Hote>, | |
| 64 | +} | |
| 65 | + | |
| 66 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 67 | +#[serde(rename_all = "lowercase")] | |
| 68 | +pub enum Mode { | |
| 69 | + #[default] | |
| 70 | + Native, | |
| 71 | + Compose, | |
| 72 | +} | |
| 73 | + | |
| 74 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 75 | +#[serde(rename_all = "lowercase")] | |
| 76 | +pub enum Topologie { | |
| 77 | + #[default] | |
| 78 | + Local, | |
| 79 | + Multi, | |
| 80 | +} | |
| 81 | + | |
| 82 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 83 | +#[serde(deny_unknown_fields)] | |
| 84 | +pub struct Hote { | |
| 85 | + pub nom: String, | |
| 86 | + pub adresse: String, | |
| 87 | + #[serde(default = "port_ssh")] | |
| 88 | + pub port: u16, | |
| 89 | + #[serde(default = "utilisateur_root")] | |
| 90 | + pub utilisateur: String, | |
| 91 | + pub roles: BTreeSet<catalogue::RoleHote>, | |
| 92 | +} | |
| 93 | + | |
| 94 | +fn port_ssh() -> u16 { | |
| 95 | + 22 | |
| 96 | +} | |
| 97 | + | |
| 98 | +fn utilisateur_root() -> String { | |
| 99 | + "root".to_owned() | |
| 100 | +} | |
| 101 | + | |
| 102 | +// --- E-005 Sécurité ------------------------------------------------------------------- | |
| 103 | + | |
| 104 | +/// Services exposés, chacun sous un nom DNS (`services.<cle>`). | |
| 105 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] | |
| 106 | +#[serde(rename_all = "kebab-case")] | |
| 107 | +pub enum Service { | |
| 108 | + Annuaire, | |
| 109 | + Mdp, | |
| 110 | + Pages, | |
| 111 | + Support, | |
| 112 | + Auth, | |
| 113 | + Supervision, | |
| 114 | + Vuln, | |
| 115 | + Console, | |
| 116 | +} | |
| 117 | + | |
| 118 | +impl Service { | |
| 119 | + /// Sous-domaine proposé par défaut (E-005). | |
| 120 | + pub fn prefixe(self) -> &'static str { | |
| 121 | + match self { | |
| 122 | + Self::Annuaire => "annuaire", | |
| 123 | + Self::Mdp => "mdp", | |
| 124 | + Self::Pages => "pages", | |
| 125 | + Self::Support => "support", | |
| 126 | + Self::Auth => "auth", | |
| 127 | + Self::Supervision => "supervision", | |
| 128 | + Self::Vuln => "vuln", | |
| 129 | + Self::Console => "console", | |
| 130 | + } | |
| 131 | + } | |
| 132 | +} | |
| 133 | + | |
| 134 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 135 | +#[serde(deny_unknown_fields)] | |
| 136 | +pub struct Tls { | |
| 137 | + pub mode: TlsMode, | |
| 138 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 139 | + pub acme_email: Option<String>, | |
| 140 | +} | |
| 141 | + | |
| 142 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 143 | +#[serde(rename_all = "lowercase")] | |
| 144 | +pub enum TlsMode { | |
| 145 | + #[default] | |
| 146 | + Interne, | |
| 147 | + Acme, | |
| 148 | + Fourni, | |
| 149 | +} | |
| 150 | + | |
| 151 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| 152 | +#[serde(deny_unknown_fields)] | |
| 153 | +pub struct PolitiqueMdp { | |
| 154 | + pub longueur_min: u8, | |
| 155 | + pub classes_min: u8, | |
| 156 | + pub historique: u8, | |
| 157 | + pub expiration_jours: u16, | |
| 158 | + pub echecs_max: u8, | |
| 159 | + pub verrouillage_minutes: u16, | |
| 160 | +} | |
| 161 | + | |
| 162 | +impl PolitiqueMdp { | |
| 163 | + /// Préréglage par défaut (D-010), d'après les recommandations de l'ANSSI. | |
| 164 | + pub fn anssi() -> Self { | |
| 165 | + Self { | |
| 166 | + longueur_min: 12, | |
| 167 | + classes_min: 3, | |
| 168 | + historique: 5, | |
| 169 | + expiration_jours: 0, | |
| 170 | + echecs_max: 10, | |
| 171 | + verrouillage_minutes: 15, | |
| 172 | + } | |
| 173 | + } | |
| 174 | + | |
| 175 | + pub fn renforcee() -> Self { | |
| 176 | + Self { | |
| 177 | + longueur_min: 16, | |
| 178 | + classes_min: 4, | |
| 179 | + historique: 10, | |
| 180 | + expiration_jours: 0, | |
| 181 | + echecs_max: 5, | |
| 182 | + verrouillage_minutes: 30, | |
| 183 | + } | |
| 184 | + } | |
| 185 | +} | |
| 186 | + | |
| 187 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 188 | +#[serde(deny_unknown_fields)] | |
| 189 | +pub struct Mfa { | |
| 190 | + pub exigence: ExigenceMfa, | |
| 191 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 192 | + pub groupe: Option<String>, | |
| 193 | + /// D-012 : 2FA des administrateurs, cochée par défaut. | |
| 194 | + pub admins: bool, | |
| 195 | +} | |
| 196 | + | |
| 197 | +impl Default for Mfa { | |
| 198 | + fn default() -> Self { | |
| 199 | + Self { exigence: ExigenceMfa::Tous, groupe: None, admins: true } | |
| 200 | + } | |
| 201 | +} | |
| 202 | + | |
| 203 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 204 | +#[serde(rename_all = "lowercase")] | |
| 205 | +pub enum ExigenceMfa { | |
| 206 | + #[default] | |
| 207 | + Tous, | |
| 208 | + Groupe, | |
| 209 | + Facultative, | |
| 210 | +} | |
| 211 | + | |
| 212 | +// --- E-006 Messagerie ----------------------------------------------------------------- | |
| 213 | + | |
| 214 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 215 | +#[serde(deny_unknown_fields)] | |
| 216 | +pub struct Smtp { | |
| 217 | + pub hote: String, | |
| 218 | + pub port: u16, | |
| 219 | + pub chiffrement: Chiffrement, | |
| 220 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 221 | + pub utilisateur: Option<String>, | |
| 222 | + pub expediteur: String, | |
| 223 | + pub nom: String, | |
| 224 | +} | |
| 225 | + | |
| 226 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 227 | +#[serde(rename_all = "lowercase")] | |
| 228 | +pub enum Chiffrement { | |
| 229 | + #[default] | |
| 230 | + Starttls, | |
| 231 | + Tls, | |
| 232 | + Aucun, | |
| 233 | +} | |
| 234 | + | |
| 235 | +// --- E-007 Comptes -------------------------------------------------------------------- | |
| 236 | + | |
| 237 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 238 | +#[serde(deny_unknown_fields)] | |
| 239 | +pub struct AdminInitial { | |
| 240 | + pub uid: String, | |
| 241 | + pub prenom: String, | |
| 242 | + pub nom: String, | |
| 243 | + pub email: String, | |
| 244 | + pub mode_mdp: ModeMdp, | |
| 245 | +} | |
| 246 | + | |
| 247 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] | |
| 248 | +#[serde(rename_all = "lowercase")] | |
| 249 | +pub enum ModeMdp { | |
| 250 | + #[default] | |
| 251 | + Saisir, | |
| 252 | + Lien, | |
| 253 | +} | |
| 254 | + | |
| 255 | +// --- E-008 Supervision et télémétrie -------------------------------------------------- | |
| 256 | + | |
| 257 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 258 | +#[serde(deny_unknown_fields)] | |
| 259 | +pub struct Supervision { | |
| 260 | + pub retention_metriques_jours: u16, | |
| 261 | + pub retention_journaux_jours: u16, | |
| 262 | + #[serde(default, skip_serializing_if = "Vec::is_empty")] | |
| 263 | + pub alertes_emails: Vec<String>, | |
| 264 | +} | |
| 265 | + | |
| 266 | +impl Default for Supervision { | |
| 267 | + fn default() -> Self { | |
| 268 | + Self { retention_metriques_jours: 30, retention_journaux_jours: 90, alertes_emails: Vec::new() } | |
| 269 | + } | |
| 270 | +} | |
| 271 | + | |
| 272 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 273 | +#[serde(deny_unknown_fields)] | |
| 274 | +pub struct Telemetrie { | |
| 275 | + /// D-005 : désactivée par défaut, jamais pré-activée. | |
| 276 | + pub active: bool, | |
| 277 | + pub url: String, | |
| 278 | +} | |
| 279 | + | |
| 280 | +/// Collecteur officiel : pas encore en place (Q-02). Aucun envoi n'est implémenté en M1. | |
| 281 | +pub const URL_TELEMETRIE: &str = "https://telemetrie.open-iam.invalid/v1/rapports"; | |
| 282 | + | |
| 283 | +impl Default for Telemetrie { | |
| 284 | + fn default() -> Self { | |
| 285 | + Self { active: false, url: URL_TELEMETRIE.to_owned() } | |
| 286 | + } | |
| 287 | +} | |
| 288 | + | |
| 289 | +// --- Erreurs de validation ------------------------------------------------------------ | |
| 290 | + | |
| 291 | +/// Erreur ou avertissement rattaché à un chemin `openiam.yaml` (ex. `organisation.domaine`). | |
| 292 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 293 | +pub struct Constat { | |
| 294 | + pub chemin: String, | |
| 295 | + pub message: String, | |
| 296 | + pub gravite: Gravite, | |
| 297 | +} | |
| 298 | + | |
| 299 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 300 | +pub enum Gravite { | |
| 301 | + Erreur, | |
| 302 | + Avertissement, | |
| 303 | +} | |
| 304 | + | |
| 305 | +impl Constat { | |
| 306 | + pub fn erreur(chemin: impl Into<String>, message: impl Into<String>) -> Self { | |
| 307 | + Self { chemin: chemin.into(), message: message.into(), gravite: Gravite::Erreur } | |
| 308 | + } | |
| 309 | + | |
| 310 | + pub fn avertissement(chemin: impl Into<String>, message: impl Into<String>) -> Self { | |
| 311 | + Self { chemin: chemin.into(), message: message.into(), gravite: Gravite::Avertissement } | |
| 312 | + } | |
| 313 | +} | |
| 314 | + | |
| 315 | +#[derive(Debug, thiserror::Error)] | |
| 316 | +pub enum ErreurChargement { | |
| 317 | + #[error("openiam.yaml illisible : {0}")] | |
| 318 | + Yaml(#[from] serde_norway::Error), | |
| 319 | + #[error( | |
| 320 | + "openiam.yaml ne doit pas contenir de secret (`{0}`) : les mots de passe se saisissent dans l'assistant" | |
| 321 | + )] | |
| 322 | + SecretPresent(String), | |
| 323 | +} | |
| 324 | + | |
| 325 | +impl OpenIamConfig { | |
| 326 | + /// Lit un `openiam.yaml` (import E-001). Refuse tout champ de secret. | |
| 327 | + pub fn depuis_yaml(texte: &str) -> Result<Self, ErreurChargement> { | |
| 328 | + let brut: serde_norway::Value = serde_norway::from_str(texte)?; | |
| 329 | + if let Some(champ) = champ_secret(&brut) { | |
| 330 | + return Err(ErreurChargement::SecretPresent(champ)); | |
| 331 | + } | |
| 332 | + let mut config: Self = serde_norway::from_value(brut)?; | |
| 333 | + config.telemetrie.active = false; | |
| 334 | + Ok(config) | |
| 335 | + } | |
| 336 | + | |
| 337 | + pub fn vers_yaml(&self) -> String { | |
| 338 | + serde_norway::to_string(self).expect("sérialisation YAML") | |
| 339 | + } | |
| 340 | + | |
| 341 | + /// Validation complète : règles de chaque section et cohérence entre sections. | |
| 342 | + pub fn valider(&self) -> Vec<Constat> { | |
| 343 | + self.valider_avec(std::path::Path::new(ZONEINFO)) | |
| 344 | + } | |
| 345 | + | |
| 346 | + pub fn valider_avec(&self, zoneinfo: &std::path::Path) -> Vec<Constat> { | |
| 347 | + let mut constats = Vec::new(); | |
| 348 | + constats.extend(self.organisation.valider(zoneinfo)); | |
| 349 | + constats.extend(self.deploiement.valider(&self.composants)); | |
| 350 | + if let Err(erreurs) = catalogue::resoudre(&self.composants) { | |
| 351 | + constats.extend(erreurs); | |
| 352 | + } | |
| 353 | + constats.extend(valider_services(&self.services, &self.composants, &self.organisation.domaine)); | |
| 354 | + constats.extend(self.tls.valider()); | |
| 355 | + constats.extend(self.mdp.valider()); | |
| 356 | + constats.extend(self.mfa.valider()); | |
| 357 | + let messagerie_requise = | |
| 358 | + catalogue::envoie_mail(&self.composants) || self.admin_initial.mode_mdp == ModeMdp::Lien; | |
| 359 | + match &self.smtp { | |
| 360 | + Some(smtp) => constats.extend(smtp.valider()), | |
| 361 | + None if messagerie_requise => constats.push(Constat::erreur( | |
| 362 | + "smtp", | |
| 363 | + "Un serveur de messagerie est nécessaire : un composant choisi envoie des e-mails, ou le mot de passe de l'administrateur est envoyé par lien.", | |
| 364 | + )), | |
| 365 | + None => {} | |
| 366 | + } | |
| 367 | + constats.extend(self.admin_initial.valider()); | |
| 368 | + constats.extend(self.supervision.valider()); | |
| 369 | + constats.extend(self.telemetrie.valider()); | |
| 370 | + constats | |
| 371 | + } | |
| 372 | +} | |
| 373 | + | |
| 374 | +/// Fuseaux horaires du système (paquet tzdata). | |
| 375 | +pub const ZONEINFO: &str = "/usr/share/zoneinfo"; | |
| 376 | + | |
| 377 | +/// Premier champ, à toute profondeur, dont le nom désigne un secret. | |
| 378 | +fn champ_secret(valeur: &serde_norway::Value) -> Option<String> { | |
| 379 | + match valeur { | |
| 380 | + serde_norway::Value::Mapping(map) => map.iter().find_map(|(cle, v)| { | |
| 381 | + let nom = cle.as_str().unwrap_or_default(); | |
| 382 | + if secrets::CHAMPS_SECRETS.iter().any(|s| nom.to_lowercase().contains(s)) { | |
| 383 | + Some(nom.to_owned()) | |
| 384 | + } else { | |
| 385 | + champ_secret(v) | |
| 386 | + } | |
| 387 | + }), | |
| 388 | + serde_norway::Value::Sequence(seq) => seq.iter().find_map(champ_secret), | |
| 389 | + serde_norway::Value::Tagged(t) => champ_secret(&t.value), | |
| 390 | + _ => None, | |
| 391 | + } | |
| 392 | +} | |
| 393 | + | |
| 394 | +/// Ajoute un constat d'erreur si le validateur refuse la valeur. | |
| 395 | +fn verifier(constats: &mut Vec<Constat>, chemin: &str, resultat: validation::Resultat) { | |
| 396 | + if let Err(message) = resultat { | |
| 397 | + constats.push(Constat::erreur(chemin, message)); | |
| 398 | + } | |
| 399 | +} | |
| 400 | + | |
| 401 | +/// Ajoute une erreur si `valeur` sort de `min..=max`. | |
| 402 | +fn borne(constats: &mut Vec<Constat>, chemin: &str, valeur: u16, min: u16, max: u16) { | |
| 403 | + if !(min..=max).contains(&valeur) { | |
| 404 | + constats.push(Constat::erreur(chemin, format!("Valeur attendue entre {min} et {max}."))); | |
| 405 | + } | |
| 406 | +} | |
| 407 | + | |
| 408 | +impl Organisation { | |
| 409 | + pub fn valider(&self, zoneinfo: &std::path::Path) -> Vec<Constat> { | |
| 410 | + let mut c = Vec::new(); | |
| 411 | + verifier(&mut c, "organisation.nom", validation::texte(&self.nom, 2, 100)); | |
| 412 | + verifier(&mut c, "organisation.domaine", validation::fqdn(&self.domaine)); | |
| 413 | + if self.domaine.ends_with(".local") { | |
| 414 | + c.push(Constat::avertissement( | |
| 415 | + "organisation.domaine", | |
| 416 | + "Le suffixe .local est réservé à la découverte réseau (mDNS) et peut provoquer des conflits : préférez un domaine que vous possédez.", | |
| 417 | + )); | |
| 418 | + } | |
| 419 | + verifier(&mut c, "organisation.base_dn", validation::base_dn(&self.base_dn)); | |
| 420 | + verifier(&mut c, "organisation.fuseau", validation::fuseau(&self.fuseau, zoneinfo)); | |
| 421 | + c | |
| 422 | + } | |
| 423 | +} | |
| 424 | + | |
| 425 | +impl Deploiement { | |
| 426 | + pub fn valider(&self, composants: &BTreeSet<ComposantId>) -> Vec<Constat> { | |
| 427 | + let mut c = Vec::new(); | |
| 428 | + if self.mode == Mode::Compose && self.topologie == Topologie::Multi { | |
| 429 | + c.push(Constat::erreur( | |
| 430 | + "deploiement.topologie", | |
| 431 | + "Le mode Docker Compose s'installe sur un seul serveur : choisissez « Tout sur ce serveur » ou le mode natif.", | |
| 432 | + )); | |
| 433 | + } | |
| 434 | + if self.topologie == Topologie::Multi { | |
| 435 | + for (i, hote) in self.hotes.iter().enumerate() { | |
| 436 | + verifier(&mut c, &format!("deploiement.hotes[{i}].nom"), validation::fqdn(&hote.nom)); | |
| 437 | + if hote.adresse.trim().parse::<std::net::IpAddr>().is_err() { | |
| 438 | + verifier( | |
| 439 | + &mut c, | |
| 440 | + &format!("deploiement.hotes[{i}].adresse"), | |
| 441 | + validation::fqdn(&hote.adresse), | |
| 442 | + ); | |
| 443 | + } | |
| 444 | + if hote.port == 0 { | |
| 445 | + c.push(Constat::erreur(format!("deploiement.hotes[{i}].port"), "Port SSH invalide.")); | |
| 446 | + } | |
| 447 | + } | |
| 448 | + let attribues: BTreeSet<_> = self.hotes.iter().flat_map(|h| h.roles.iter().copied()).collect(); | |
| 449 | + let manquants: Vec<String> = catalogue::roles_requis(composants) | |
| 450 | + .into_iter() | |
| 451 | + .filter(|role| !attribues.contains(role)) | |
| 452 | + .map(|role| format!("{role:?}").to_lowercase()) | |
| 453 | + .collect(); | |
| 454 | + if self.hotes.is_empty() { | |
| 455 | + c.push(Constat::erreur("deploiement.hotes", "Ajoutez au moins un serveur.")); | |
| 456 | + } else if !manquants.is_empty() { | |
| 457 | + c.push(Constat::erreur( | |
| 458 | + "deploiement.hotes", | |
| 459 | + format!("Aucun serveur ne porte le ou les rôles : {}.", manquants.join(", ")), | |
| 460 | + )); | |
| 461 | + } | |
| 462 | + } | |
| 463 | + c | |
| 464 | + } | |
| 465 | +} | |
| 466 | + | |
| 467 | +pub fn valider_services( | |
| 468 | + services: &BTreeMap<Service, String>, | |
| 469 | + composants: &BTreeSet<ComposantId>, | |
| 470 | + domaine: &str, | |
| 471 | +) -> Vec<Constat> { | |
| 472 | + let mut c = Vec::new(); | |
| 473 | + let mut vus = BTreeSet::new(); | |
| 474 | + for service in catalogue::services(composants) { | |
| 475 | + let chemin = format!("services.{}", service.prefixe()); | |
| 476 | + match services.get(&service) { | |
| 477 | + None => c.push(Constat::erreur(&chemin, "Indiquez le nom de ce service.")), | |
| 478 | + Some(nom) => match validation::fqdn(nom) { | |
| 479 | + Err(message) => c.push(Constat::erreur(&chemin, message)), | |
| 480 | + Ok(nom) if !vus.insert(nom.clone()) => c.push(Constat::erreur( | |
| 481 | + &chemin, | |
| 482 | + format!("« {nom} » est déjà utilisé par un autre service."), | |
| 483 | + )), | |
| 484 | + Ok(nom) if !nom.ends_with(&format!(".{domaine}")) => c.push(Constat::avertissement( | |
| 485 | + &chemin, | |
| 486 | + format!("« {nom} » n'est pas sous le domaine {domaine} : vérifiez que c'est voulu."), | |
| 487 | + )), | |
| 488 | + Ok(_) => {} | |
| 489 | + }, | |
| 490 | + } | |
| 491 | + } | |
| 492 | + c | |
| 493 | +} | |
| 494 | + | |
| 495 | +impl Tls { | |
| 496 | + pub fn valider(&self) -> Vec<Constat> { | |
| 497 | + let mut c = Vec::new(); | |
| 498 | + if self.mode == TlsMode::Acme { | |
| 499 | + match &self.acme_email { | |
| 500 | + Some(email) => verifier(&mut c, "tls.acme_email", validation::email(email)), | |
| 501 | + None => c.push(Constat::erreur( | |
| 502 | + "tls.acme_email", | |
| 503 | + "Let's Encrypt exige une adresse e-mail de contact.", | |
| 504 | + )), | |
| 505 | + } | |
| 506 | + } | |
| 507 | + c | |
| 508 | + } | |
| 509 | +} | |
| 510 | + | |
| 511 | +impl PolitiqueMdp { | |
| 512 | + pub fn valider(&self) -> Vec<Constat> { | |
| 513 | + let mut c = Vec::new(); | |
| 514 | + borne(&mut c, "mdp.longueur_min", self.longueur_min.into(), 8, 128); | |
| 515 | + borne(&mut c, "mdp.classes_min", self.classes_min.into(), 0, 4); | |
| 516 | + borne(&mut c, "mdp.historique", self.historique.into(), 0, 24); | |
| 517 | + borne(&mut c, "mdp.expiration_jours", self.expiration_jours, 0, 730); | |
| 518 | + if (1..=90).contains(&self.expiration_jours) { | |
| 519 | + c.push(Constat::avertissement( | |
| 520 | + "mdp.expiration_jours", | |
| 521 | + "Une expiration fréquente pousse à choisir des mots de passe faibles ; l'ANSSI la déconseille.", | |
| 522 | + )); | |
| 523 | + } | |
| 524 | + borne(&mut c, "mdp.echecs_max", self.echecs_max.into(), 3, 50); | |
| 525 | + borne(&mut c, "mdp.verrouillage_minutes", self.verrouillage_minutes, 0, 1440); | |
| 526 | + c | |
| 527 | + } | |
| 528 | +} | |
| 529 | + | |
| 530 | +impl Mfa { | |
| 531 | + pub fn valider(&self) -> Vec<Constat> { | |
| 532 | + let mut c = Vec::new(); | |
| 533 | + if self.exigence == ExigenceMfa::Groupe { | |
| 534 | + match &self.groupe { | |
| 535 | + Some(groupe) => verifier(&mut c, "mfa.groupe", validation::uid(groupe)), | |
| 536 | + None => c.push(Constat::erreur( | |
| 537 | + "mfa.groupe", | |
| 538 | + "Indiquez le groupe soumis à la double authentification.", | |
| 539 | + )), | |
| 540 | + } | |
| 541 | + } | |
| 542 | + if !self.admins { | |
| 543 | + c.push(Constat::avertissement( | |
| 544 | + "mfa.admins", | |
| 545 | + "Les administrateurs pourront se connecter sans double authentification.", | |
| 546 | + )); | |
| 547 | + } | |
| 548 | + c | |
| 549 | + } | |
| 550 | +} | |
| 551 | + | |
| 552 | +impl Smtp { | |
| 553 | + pub fn valider(&self) -> Vec<Constat> { | |
| 554 | + let mut c = Vec::new(); | |
| 555 | + if self.hote.trim().parse::<std::net::IpAddr>().is_err() { | |
| 556 | + verifier(&mut c, "smtp.hote", validation::fqdn(&self.hote)); | |
| 557 | + } | |
| 558 | + if self.port == 0 { | |
| 559 | + c.push(Constat::erreur("smtp.port", "Port invalide.")); | |
| 560 | + } | |
| 561 | + if self.chiffrement == Chiffrement::Aucun { | |
| 562 | + c.push(Constat::avertissement( | |
| 563 | + "smtp.chiffrement", | |
| 564 | + "Les liens de réinitialisation circuleront en clair : réservez ce choix à un relais local.", | |
| 565 | + )); | |
| 566 | + } | |
| 567 | + verifier(&mut c, "smtp.expediteur", validation::email(&self.expediteur)); | |
| 568 | + verifier(&mut c, "smtp.nom", validation::texte(&self.nom, 1, 100)); | |
| 569 | + c | |
| 570 | + } | |
| 571 | +} | |
| 572 | + | |
| 573 | +impl AdminInitial { | |
| 574 | + pub fn valider(&self) -> Vec<Constat> { | |
| 575 | + let mut c = Vec::new(); | |
| 576 | + verifier(&mut c, "admin_initial.uid", validation::uid(&self.uid)); | |
| 577 | + verifier(&mut c, "admin_initial.prenom", validation::texte(&self.prenom, 1, 64)); | |
| 578 | + verifier(&mut c, "admin_initial.nom", validation::texte(&self.nom, 1, 64)); | |
| 579 | + verifier(&mut c, "admin_initial.email", validation::email(&self.email)); | |
| 580 | + c | |
| 581 | + } | |
| 582 | +} | |
| 583 | + | |
| 584 | +impl Supervision { | |
| 585 | + pub fn valider(&self) -> Vec<Constat> { | |
| 586 | + let mut c = Vec::new(); | |
| 587 | + borne(&mut c, "supervision.retention_metriques_jours", self.retention_metriques_jours, 7, 400); | |
| 588 | + borne(&mut c, "supervision.retention_journaux_jours", self.retention_journaux_jours, 7, 400); | |
| 589 | + if let Some(Err(message)) = | |
| 590 | + self.alertes_emails.iter().map(|e| validation::email(e)).find(Result::is_err) | |
| 591 | + { | |
| 592 | + c.push(Constat::erreur("supervision.alertes_emails", message)); | |
| 593 | + } | |
| 594 | + c | |
| 595 | + } | |
| 596 | +} | |
| 597 | + | |
| 598 | +impl Telemetrie { | |
| 599 | + pub fn valider(&self) -> Vec<Constat> { | |
| 600 | + if self.url.starts_with("https://") { | |
| 601 | + vec![] | |
| 602 | + } else { | |
| 603 | + vec![Constat::erreur("telemetrie.url", "L'adresse du collecteur doit commencer par https://.")] | |
| 604 | + } | |
| 605 | + } | |
| 606 | +} | |
| 607 | + | |
| 608 | +#[cfg(test)] | |
| 609 | +pub(crate) mod tests; |
A
installer/src/config/secrets.rs
+92
-0
@@ -0,0 +1,92 @@
| 1 | +//! Secrets de l'installation. Ils ne sont jamais écrits dans `openiam.yaml`, jamais | |
| 2 | +//! affichés par `Debug` et jamais renvoyés au navigateur (CONVENTIONS.md § Sécurité). | |
| 3 | + | |
| 4 | +use std::fmt; | |
| 5 | + | |
| 6 | +use serde::{Deserialize, Serialize}; | |
| 7 | + | |
| 8 | +/// Valeur secrète : `Debug` masque la valeur ; seul [`Secret::exposer`] la révèle. | |
| 9 | +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 10 | +#[serde(transparent)] | |
| 11 | +pub struct Secret(String); | |
| 12 | + | |
| 13 | +impl Secret { | |
| 14 | + pub fn new(valeur: impl Into<String>) -> Self { | |
| 15 | + Self(valeur.into()) | |
| 16 | + } | |
| 17 | + | |
| 18 | + /// Mot de passe aléatoire de `longueur` caractères, garanti avec les 4 classes | |
| 19 | + /// (minuscule, majuscule, chiffre, symbole), sans caractères ambigus. | |
| 20 | + pub fn generer(longueur: usize) -> Self { | |
| 21 | + use rand::seq::{IndexedRandom, SliceRandom}; | |
| 22 | + const CLASSES: [&[u8]; 4] = | |
| 23 | + [b"abcdefghijkmnopqrstuvwxyz", b"ABCDEFGHJKLMNPQRSTUVWXYZ", b"23456789", b"!#%+-.:=?@_"]; | |
| 24 | + let tous: Vec<u8> = CLASSES.concat(); | |
| 25 | + let mut rng = rand::rng(); | |
| 26 | + let mut octets: Vec<u8> = | |
| 27 | + CLASSES.iter().map(|classe| *classe.choose(&mut rng).expect("classe non vide")).collect(); | |
| 28 | + while octets.len() < longueur.max(CLASSES.len()) { | |
| 29 | + octets.push(*tous.choose(&mut rng).expect("alphabet non vide")); | |
| 30 | + } | |
| 31 | + octets.shuffle(&mut rng); | |
| 32 | + Self(String::from_utf8(octets).expect("alphabet ASCII")) | |
| 33 | + } | |
| 34 | + | |
| 35 | + pub fn exposer(&self) -> &str { | |
| 36 | + &self.0 | |
| 37 | + } | |
| 38 | +} | |
| 39 | + | |
| 40 | +impl fmt::Debug for Secret { | |
| 41 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 42 | + f.write_str("Secret(***)") | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// Secrets collectés par l'assistant (`draft-secrets.yaml`, 0600). | |
| 47 | +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] | |
| 48 | +#[serde(deny_unknown_fields)] | |
| 49 | +pub struct Secrets { | |
| 50 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 51 | + pub ldap_admin_mot_de_passe: Option<Secret>, | |
| 52 | + /// Le mot de passe d'urgence a-t-il été généré par l'installeur (affiché en E-012) ? | |
| 53 | + #[serde(default)] | |
| 54 | + pub ldap_admin_genere: bool, | |
| 55 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 56 | + pub admin_initial_mot_de_passe: Option<Secret>, | |
| 57 | + #[serde(default, skip_serializing_if = "Option::is_none")] | |
| 58 | + pub smtp_mot_de_passe: Option<Secret>, | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// Noms de champs qui désignent un secret : refusés à l'import d'un `openiam.yaml`. | |
| 62 | +pub const CHAMPS_SECRETS: &[&str] = &["mot_de_passe", "password", "secret", "token"]; | |
| 63 | + | |
| 64 | +#[cfg(test)] | |
| 65 | +mod tests { | |
| 66 | + use super::*; | |
| 67 | + | |
| 68 | + #[test] | |
| 69 | + fn debug_ne_revele_jamais_la_valeur() { | |
| 70 | + let s = Secrets { ldap_admin_mot_de_passe: Some(Secret::new("tres-secret")), ..Default::default() }; | |
| 71 | + assert!(!format!("{s:?}").contains("tres-secret")); | |
| 72 | + } | |
| 73 | + | |
| 74 | + #[test] | |
| 75 | + fn un_secret_genere_a_la_longueur_et_les_quatre_classes() { | |
| 76 | + for _ in 0..50 { | |
| 77 | + let s = Secret::generer(32); | |
| 78 | + let v = s.exposer(); | |
| 79 | + assert_eq!(v.chars().count(), 32); | |
| 80 | + assert!(v.chars().any(|c| c.is_ascii_lowercase())); | |
| 81 | + assert!(v.chars().any(|c| c.is_ascii_uppercase())); | |
| 82 | + assert!(v.chars().any(|c| c.is_ascii_digit())); | |
| 83 | + assert!(v.chars().any(|c| !c.is_ascii_alphanumeric())); | |
| 84 | + assert!(!v.chars().any(|c| "0O1lI|'\"\\` ".contains(c)), "{v}"); | |
| 85 | + } | |
| 86 | + } | |
| 87 | + | |
| 88 | + #[test] | |
| 89 | + fn deux_secrets_generes_different() { | |
| 90 | + assert_ne!(Secret::generer(32), Secret::generer(32)); | |
| 91 | + } | |
| 92 | +} |
A
installer/src/config/tests.rs
+310
-0
@@ -0,0 +1,310 @@
| 1 | +use super::*; | |
| 2 | +use crate::catalogue::RoleHote; | |
| 3 | + | |
| 4 | +/// Configuration complète et valide (installation locale du socle M1). | |
| 5 | +pub(crate) fn exemple() -> OpenIamConfig { | |
| 6 | + OpenIamConfig { | |
| 7 | + organisation: Organisation { | |
| 8 | + nom: "Mairie d'Exemple".into(), | |
| 9 | + domaine: "exemple.fr".into(), | |
| 10 | + base_dn: "dc=exemple,dc=fr".into(), | |
| 11 | + langue: Langue::Fr, | |
| 12 | + fuseau: "Europe/Paris".into(), | |
| 13 | + }, | |
| 14 | + deploiement: Deploiement { mode: Mode::Native, topologie: Topologie::Local, hotes: vec![] }, | |
| 15 | + composants: [ComposantId::Openldap, ComposantId::Sauvegarde].into(), | |
| 16 | + services: [(Service::Annuaire, "annuaire.exemple.fr".to_owned())].into(), | |
| 17 | + tls: Tls { mode: TlsMode::Interne, acme_email: None }, | |
| 18 | + mdp: PolitiqueMdp::anssi(), | |
| 19 | + mfa: Mfa::default(), | |
| 20 | + smtp: None, | |
| 21 | + admin_initial: AdminInitial { | |
| 22 | + uid: "jean.dupont".into(), | |
| 23 | + prenom: "Jean".into(), | |
| 24 | + nom: "Dupont".into(), | |
| 25 | + email: "jean.dupont@exemple.fr".into(), | |
| 26 | + mode_mdp: ModeMdp::Saisir, | |
| 27 | + }, | |
| 28 | + supervision: Supervision::default(), | |
| 29 | + telemetrie: Telemetrie::default(), | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +fn smtp() -> Smtp { | |
| 34 | + Smtp { | |
| 35 | + hote: "smtp.exemple.fr".into(), | |
| 36 | + port: 587, | |
| 37 | + chiffrement: Chiffrement::Starttls, | |
| 38 | + utilisateur: None, | |
| 39 | + expediteur: "noreply@exemple.fr".into(), | |
| 40 | + nom: "Mairie d'Exemple".into(), | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +fn erreurs(config: &OpenIamConfig) -> Vec<String> { | |
| 45 | + config.valider().into_iter().filter(|c| c.gravite == Gravite::Erreur).map(|c| c.chemin).collect() | |
| 46 | +} | |
| 47 | + | |
| 48 | +fn avertissements(config: &OpenIamConfig) -> Vec<String> { | |
| 49 | + config.valider().into_iter().filter(|c| c.gravite == Gravite::Avertissement).map(|c| c.chemin).collect() | |
| 50 | +} | |
| 51 | + | |
| 52 | +#[test] | |
| 53 | +fn l_exemple_est_valide_sans_avertissement() { | |
| 54 | + assert_eq!(exemple().valider(), vec![]); | |
| 55 | +} | |
| 56 | + | |
| 57 | +#[test] | |
| 58 | +fn l_aller_retour_yaml_est_sans_perte() { | |
| 59 | + let mut config = exemple(); | |
| 60 | + config.smtp = Some(smtp()); | |
| 61 | + config.deploiement.hotes.push(Hote { | |
| 62 | + nom: "srv1.exemple.fr".into(), | |
| 63 | + adresse: "10.0.0.1".into(), | |
| 64 | + port: 22, | |
| 65 | + utilisateur: "root".into(), | |
| 66 | + roles: [RoleHote::Annuaire].into(), | |
| 67 | + }); | |
| 68 | + let yaml = config.vers_yaml(); | |
| 69 | + assert_eq!(OpenIamConfig::depuis_yaml(&yaml).unwrap(), config); | |
| 70 | +} | |
| 71 | + | |
| 72 | +#[test] | |
| 73 | +fn le_yaml_suit_les_cles_des_fiches() { | |
| 74 | + let yaml = exemple().vers_yaml(); | |
| 75 | + for cle in [ | |
| 76 | + "organisation:", | |
| 77 | + " domaine: exemple.fr", | |
| 78 | + " base_dn: dc=exemple,dc=fr", | |
| 79 | + "composants:", | |
| 80 | + "- openldap", | |
| 81 | + "services:", | |
| 82 | + " annuaire: annuaire.exemple.fr", | |
| 83 | + "telemetrie:", | |
| 84 | + " active: false", | |
| 85 | + ] { | |
| 86 | + assert!(yaml.contains(cle), "« {cle} » absent :\n{yaml}"); | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +#[test] | |
| 91 | +fn l_import_refuse_un_secret() { | |
| 92 | + let yaml = exemple().vers_yaml().replace("smtp:", "") + "smtp_mot_de_passe: x\n"; | |
| 93 | + let err = OpenIamConfig::depuis_yaml(&yaml).unwrap_err(); | |
| 94 | + assert!( | |
| 95 | + matches!(err, ErreurChargement::SecretPresent(ref champ) if champ == "smtp_mot_de_passe"), | |
| 96 | + "{err}" | |
| 97 | + ); | |
| 98 | + | |
| 99 | + let yaml = exemple().vers_yaml().replace(" uid: jean.dupont", " uid: jean.dupont\n password: x"); | |
| 100 | + assert!(matches!(OpenIamConfig::depuis_yaml(&yaml), Err(ErreurChargement::SecretPresent(_)))); | |
| 101 | +} | |
| 102 | + | |
| 103 | +#[test] | |
| 104 | +fn l_import_refuse_un_champ_inconnu() { | |
| 105 | + let yaml = exemple().vers_yaml().replace(" langue: fr", " langue: fr\n couleur: bleu"); | |
| 106 | + assert!(matches!(OpenIamConfig::depuis_yaml(&yaml), Err(ErreurChargement::Yaml(_)))); | |
| 107 | +} | |
| 108 | + | |
| 109 | +#[test] | |
| 110 | +fn l_import_ne_preactive_jamais_la_telemetrie() { | |
| 111 | + let yaml = exemple().vers_yaml().replace(" active: false", " active: true"); | |
| 112 | + assert!(!OpenIamConfig::depuis_yaml(&yaml).unwrap().telemetrie.active); | |
| 113 | +} | |
| 114 | + | |
| 115 | +#[test] | |
| 116 | +fn les_champs_de_l_organisation_sont_valides() { | |
| 117 | + let mut c = exemple(); | |
| 118 | + c.organisation.domaine = "localhost".into(); | |
| 119 | + c.organisation.base_dn = "o=x,c=fr".into(); | |
| 120 | + c.organisation.nom = "X".into(); | |
| 121 | + c.organisation.fuseau = "Europe/Lune".into(); | |
| 122 | + assert_eq!( | |
| 123 | + erreurs(&c), | |
| 124 | + ["organisation.nom", "organisation.domaine", "organisation.base_dn", "organisation.fuseau"] | |
| 125 | + ); | |
| 126 | +} | |
| 127 | + | |
| 128 | +#[test] | |
| 129 | +fn un_domaine_local_donne_un_avertissement() { | |
| 130 | + let mut c = exemple(); | |
| 131 | + c.organisation.domaine = "mairie.local".into(); | |
| 132 | + c.organisation.base_dn = "dc=mairie,dc=local".into(); | |
| 133 | + c.services.insert(Service::Annuaire, "annuaire.mairie.local".into()); | |
| 134 | + assert_eq!(avertissements(&c), ["organisation.domaine"]); | |
| 135 | +} | |
| 136 | + | |
| 137 | +#[test] | |
| 138 | +fn un_composant_indisponible_est_une_erreur() { | |
| 139 | + let mut c = exemple(); | |
| 140 | + c.composants.insert(ComposantId::Ssp); | |
| 141 | + c.services.insert(Service::Mdp, "mdp.exemple.fr".into()); | |
| 142 | + c.smtp = Some(smtp()); | |
| 143 | + assert!(erreurs(&c).contains(&"composants.ssp".to_owned())); | |
| 144 | +} | |
| 145 | + | |
| 146 | +#[test] | |
| 147 | +fn chaque_service_expose_a_un_nom_unique_et_valide() { | |
| 148 | + let mut c = exemple(); | |
| 149 | + c.services.clear(); | |
| 150 | + assert_eq!(erreurs(&c), ["services.annuaire"]); | |
| 151 | + | |
| 152 | + c.services.insert(Service::Annuaire, "pas un nom".into()); | |
| 153 | + assert_eq!(erreurs(&c), ["services.annuaire"]); | |
| 154 | + | |
| 155 | + c.services.insert(Service::Annuaire, "ldap.autre-domaine.fr".into()); | |
| 156 | + assert_eq!(avertissements(&c), ["services.annuaire"]); | |
| 157 | +} | |
| 158 | + | |
| 159 | +#[test] | |
| 160 | +fn compose_impose_un_seul_hote() { | |
| 161 | + let mut c = exemple(); | |
| 162 | + c.deploiement.mode = Mode::Compose; | |
| 163 | + c.deploiement.topologie = Topologie::Multi; | |
| 164 | + assert!(erreurs(&c).contains(&"deploiement.topologie".to_owned())); | |
| 165 | +} | |
| 166 | + | |
| 167 | +#[test] | |
| 168 | +fn en_multi_hotes_chaque_role_requis_est_attribue() { | |
| 169 | + let mut c = exemple(); | |
| 170 | + c.deploiement.topologie = Topologie::Multi; | |
| 171 | + assert_eq!(erreurs(&c), ["deploiement.hotes"]); | |
| 172 | + | |
| 173 | + c.deploiement.hotes.push(Hote { | |
| 174 | + nom: "srv1.exemple.fr".into(), | |
| 175 | + adresse: "10.0.0.1".into(), | |
| 176 | + port: 22, | |
| 177 | + utilisateur: "root".into(), | |
| 178 | + roles: [RoleHote::Outils].into(), | |
| 179 | + }); | |
| 180 | + assert_eq!(erreurs(&c), ["deploiement.hotes"], "rôle annuaire manquant"); | |
| 181 | + | |
| 182 | + c.deploiement.hotes[0].roles.insert(RoleHote::Annuaire); | |
| 183 | + assert_eq!(erreurs(&c), Vec::<String>::new()); | |
| 184 | +} | |
| 185 | + | |
| 186 | +#[test] | |
| 187 | +fn acme_exige_un_e_mail() { | |
| 188 | + let mut c = exemple(); | |
| 189 | + c.tls.mode = TlsMode::Acme; | |
| 190 | + assert_eq!(erreurs(&c), ["tls.acme_email"]); | |
| 191 | + c.tls.acme_email = Some("admin@exemple.fr".into()); | |
| 192 | + assert_eq!(erreurs(&c), Vec::<String>::new()); | |
| 193 | +} | |
| 194 | + | |
| 195 | +#[test] | |
| 196 | +fn la_politique_de_mots_de_passe_est_bornee() { | |
| 197 | + let mut c = exemple(); | |
| 198 | + c.mdp = PolitiqueMdp { | |
| 199 | + longueur_min: 7, | |
| 200 | + classes_min: 5, | |
| 201 | + historique: 25, | |
| 202 | + expiration_jours: 731, | |
| 203 | + echecs_max: 2, | |
| 204 | + verrouillage_minutes: 1441, | |
| 205 | + }; | |
| 206 | + assert_eq!( | |
| 207 | + erreurs(&c), | |
| 208 | + [ | |
| 209 | + "mdp.longueur_min", | |
| 210 | + "mdp.classes_min", | |
| 211 | + "mdp.historique", | |
| 212 | + "mdp.expiration_jours", | |
| 213 | + "mdp.echecs_max", | |
| 214 | + "mdp.verrouillage_minutes" | |
| 215 | + ] | |
| 216 | + ); | |
| 217 | +} | |
| 218 | + | |
| 219 | +#[test] | |
| 220 | +fn une_expiration_courte_est_deconseillee() { | |
| 221 | + let mut c = exemple(); | |
| 222 | + c.mdp.expiration_jours = 60; | |
| 223 | + assert_eq!(avertissements(&c), ["mdp.expiration_jours"]); | |
| 224 | +} | |
| 225 | + | |
| 226 | +#[test] | |
| 227 | +fn la_messagerie_est_exigee_si_un_composant_envoie_des_e_mails_ou_si_le_mot_de_passe_est_envoye_par_lien() { | |
| 228 | + let mut c = exemple(); | |
| 229 | + c.admin_initial.mode_mdp = ModeMdp::Lien; | |
| 230 | + assert_eq!(erreurs(&c), ["smtp"]); | |
| 231 | + c.smtp = Some(smtp()); | |
| 232 | + assert_eq!(erreurs(&c), Vec::<String>::new()); | |
| 233 | +} | |
| 234 | + | |
| 235 | +#[test] | |
| 236 | +fn une_messagerie_sans_chiffrement_donne_un_avertissement() { | |
| 237 | + let mut c = exemple(); | |
| 238 | + c.smtp = Some(Smtp { chiffrement: Chiffrement::Aucun, port: 25, ..smtp() }); | |
| 239 | + assert_eq!(avertissements(&c), ["smtp.chiffrement"]); | |
| 240 | +} | |
| 241 | + | |
| 242 | +#[test] | |
| 243 | +fn les_champs_de_la_messagerie_sont_valides() { | |
| 244 | + let mut c = exemple(); | |
| 245 | + c.smtp = Some(Smtp { hote: "".into(), port: 0, expediteur: "x".into(), nom: "".into(), ..smtp() }); | |
| 246 | + assert_eq!(erreurs(&c), ["smtp.hote", "smtp.port", "smtp.expediteur", "smtp.nom"]); | |
| 247 | +} | |
| 248 | + | |
| 249 | +#[test] | |
| 250 | +fn le_premier_administrateur_est_valide() { | |
| 251 | + let mut c = exemple(); | |
| 252 | + c.admin_initial.uid = "Jean".into(); | |
| 253 | + c.admin_initial.email = "jean".into(); | |
| 254 | + c.admin_initial.prenom = "".into(); | |
| 255 | + assert_eq!(erreurs(&c), ["admin_initial.uid", "admin_initial.prenom", "admin_initial.email"]); | |
| 256 | +} | |
| 257 | + | |
| 258 | +#[test] | |
| 259 | +fn la_2fa_par_groupe_exige_un_nom_de_groupe_et_la_desactiver_pour_les_admins_avertit() { | |
| 260 | + let mut c = exemple(); | |
| 261 | + c.mfa = Mfa { exigence: ExigenceMfa::Groupe, groupe: None, admins: false }; | |
| 262 | + assert_eq!(erreurs(&c), ["mfa.groupe"]); | |
| 263 | + assert_eq!(avertissements(&c), ["mfa.admins"]); | |
| 264 | +} | |
| 265 | + | |
| 266 | +#[test] | |
| 267 | +fn la_telemetrie_exige_https_et_les_alertes_des_e_mails_valides() { | |
| 268 | + let mut c = exemple(); | |
| 269 | + c.telemetrie.url = "http://collecte.exemple.fr".into(); | |
| 270 | + c.supervision.alertes_emails = vec!["pas-un-email".into()]; | |
| 271 | + c.supervision.retention_journaux_jours = 2; | |
| 272 | + assert_eq!( | |
| 273 | + erreurs(&c), | |
| 274 | + ["supervision.retention_journaux_jours", "supervision.alertes_emails", "telemetrie.url"] | |
| 275 | + ); | |
| 276 | +} | |
| 277 | + | |
| 278 | +#[test] | |
| 279 | +fn les_group_vars_portent_les_valeurs_utiles_aux_roles() { | |
| 280 | + let vars: serde_norway::Value = serde_norway::from_str(&ansible::group_vars(&exemple())).unwrap(); | |
| 281 | + assert_eq!(vars["oiam_base_dn"], "dc=exemple,dc=fr"); | |
| 282 | + assert_eq!(vars["oiam_domaine"], "exemple.fr"); | |
| 283 | + assert_eq!(vars["oiam_organisation"], "Mairie d'Exemple"); | |
| 284 | + assert_eq!(vars["oiam_fuseau"], "Europe/Paris"); | |
| 285 | + assert_eq!(vars["oiam_composants"][0], "openldap"); | |
| 286 | + assert_eq!(vars["oiam_services"]["annuaire"], "annuaire.exemple.fr"); | |
| 287 | + assert_eq!(vars["oiam_tls_mode"], "interne"); | |
| 288 | + assert_eq!(vars["oiam_mdp"]["longueur_min"], 12); | |
| 289 | + assert_eq!(vars["oiam_admin_initial"]["uid"], "jean.dupont"); | |
| 290 | + assert_eq!(vars["oiam_os_codenames"]["debian"], "trixie"); | |
| 291 | +} | |
| 292 | + | |
| 293 | +#[test] | |
| 294 | +fn les_group_vars_ne_contiennent_aucun_secret() { | |
| 295 | + let yaml = ansible::group_vars(&exemple()); | |
| 296 | + assert!(!yaml.contains("mot_de_passe")); | |
| 297 | +} | |
| 298 | + | |
| 299 | +#[test] | |
| 300 | +fn les_secrets_vars_portent_les_secrets() { | |
| 301 | + let secrets = Secrets { | |
| 302 | + ldap_admin_mot_de_passe: Some(Secret::new("Urgence-123456789!")), | |
| 303 | + admin_initial_mot_de_passe: Some(Secret::new("Admin-123456!")), | |
| 304 | + ..Default::default() | |
| 305 | + }; | |
| 306 | + let vars: serde_norway::Value = serde_norway::from_str(&ansible::secrets_vars(&secrets)).unwrap(); | |
| 307 | + assert_eq!(vars["oiam_ldap_admin_mot_de_passe"], "Urgence-123456789!"); | |
| 308 | + assert_eq!(vars["oiam_admin_initial_mot_de_passe"], "Admin-123456!"); | |
| 309 | + assert!(vars.get("oiam_smtp_mot_de_passe").is_none()); | |
| 310 | +} |
A
installer/src/config/validation.rs
+283
-0
@@ -0,0 +1,283 @@
| 1 | +//! Validateurs de champs (règles des fiches E-002 à E-008). Chaque validateur renvoie la | |
| 2 | +//! valeur normalisée, ou un message d'erreur qui dit quoi corriger (charte § Ton rédactionnel). | |
| 3 | + | |
| 4 | +use std::path::Path; | |
| 5 | + | |
| 6 | +use super::PolitiqueMdp; | |
| 7 | + | |
| 8 | +pub type Resultat = Result<String, String>; | |
| 9 | + | |
| 10 | +/// Nom de domaine complet : minuscules, au moins deux labels, IDN converti en punycode. | |
| 11 | +pub fn fqdn(saisie: &str) -> Resultat { | |
| 12 | + let saisie = saisie.trim().trim_end_matches('.'); | |
| 13 | + if saisie.is_empty() { | |
| 14 | + return Err("Le domaine est obligatoire.".into()); | |
| 15 | + } | |
| 16 | + let ascii = idna::domain_to_ascii(saisie) | |
| 17 | + .map_err(|_| format!("« {saisie} » n'est pas un nom de domaine valide."))?; | |
| 18 | + if !ascii.contains('.') { | |
| 19 | + return Err("Le domaine doit contenir au moins un point, par exemple exemple.fr.".into()); | |
| 20 | + } | |
| 21 | + if ascii.len() > 253 { | |
| 22 | + return Err("Le domaine ne doit pas dépasser 253 caractères.".into()); | |
| 23 | + } | |
| 24 | + for label in ascii.split('.') { | |
| 25 | + if label.is_empty() { | |
| 26 | + return Err("Le domaine contient deux points consécutifs.".into()); | |
| 27 | + } | |
| 28 | + if label.len() > 63 { | |
| 29 | + return Err(format!("Chaque partie du domaine est limitée à 63 caractères (« {label} »).")); | |
| 30 | + } | |
| 31 | + if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { | |
| 32 | + return Err(format!( | |
| 33 | + "« {label} » contient des caractères non autorisés : lettres, chiffres et tirets uniquement." | |
| 34 | + )); | |
| 35 | + } | |
| 36 | + if label.starts_with('-') || label.ends_with('-') { | |
| 37 | + return Err(format!("« {label} » ne doit ni commencer ni finir par un tiret.")); | |
| 38 | + } | |
| 39 | + } | |
| 40 | + Ok(ascii) | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// Base DN dérivée d'un domaine : `exemple.fr` → `dc=exemple,dc=fr`. | |
| 44 | +pub fn dn_depuis_domaine(domaine: &str) -> String { | |
| 45 | + domaine.split('.').map(|label| format!("dc={label}")).collect::<Vec<_>>().join(",") | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// Base de l'annuaire : DN composé uniquement de `dc=`, `o=` et `ou=`. | |
| 49 | +pub fn base_dn(saisie: &str) -> Resultat { | |
| 50 | + let saisie = saisie.trim(); | |
| 51 | + if saisie.is_empty() { | |
| 52 | + return Err("La base de l'annuaire est obligatoire.".into()); | |
| 53 | + } | |
| 54 | + let mut composants = Vec::new(); | |
| 55 | + for rdn in saisie.split(',') { | |
| 56 | + let Some((attribut, valeur)) = rdn.split_once('=') else { | |
| 57 | + return Err(format!( | |
| 58 | + "« {} » n'est pas de la forme attribut=valeur, par exemple dc=exemple.", | |
| 59 | + rdn.trim() | |
| 60 | + )); | |
| 61 | + }; | |
| 62 | + let attribut = attribut.trim().to_lowercase(); | |
| 63 | + let valeur = valeur.trim(); | |
| 64 | + if !matches!(attribut.as_str(), "dc" | "o" | "ou") { | |
| 65 | + return Err(format!("« {attribut}= » n'est pas accepté : utilisez dc=, o= ou ou=.")); | |
| 66 | + } | |
| 67 | + if valeur.is_empty() | |
| 68 | + || !valeur.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == ' ') | |
| 69 | + { | |
| 70 | + return Err(format!("La valeur « {valeur} » est vide ou contient des caractères spéciaux.")); | |
| 71 | + } | |
| 72 | + composants.push(format!("{attribut}={valeur}")); | |
| 73 | + } | |
| 74 | + Ok(composants.join(",")) | |
| 75 | +} | |
| 76 | + | |
| 77 | +pub fn email(saisie: &str) -> Resultat { | |
| 78 | + let saisie = saisie.trim(); | |
| 79 | + let erreur = | |
| 80 | + || format!("« {saisie} » n'est pas une adresse e-mail valide, par exemple prenom.nom@exemple.fr."); | |
| 81 | + let (local, domaine) = saisie.rsplit_once('@').ok_or_else(erreur)?; | |
| 82 | + if local.is_empty() || local.len() > 64 || local.chars().any(|c| c.is_whitespace() || c == '@') { | |
| 83 | + return Err(erreur()); | |
| 84 | + } | |
| 85 | + let domaine = fqdn(domaine).map_err(|_| erreur())?; | |
| 86 | + Ok(format!("{local}@{domaine}")) | |
| 87 | +} | |
| 88 | + | |
| 89 | +/// Identifiant de connexion (`uid`). | |
| 90 | +pub fn uid(saisie: &str) -> Resultat { | |
| 91 | + let saisie = saisie.trim(); | |
| 92 | + let mut chars = saisie.chars(); | |
| 93 | + let premier_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase()); | |
| 94 | + let reste_ok = | |
| 95 | + chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-')); | |
| 96 | + if premier_ok && reste_ok && (2..=64).contains(&saisie.len()) { | |
| 97 | + Ok(saisie.to_owned()) | |
| 98 | + } else { | |
| 99 | + Err("L'identifiant fait 2 à 64 caractères : une lettre minuscule, puis des minuscules, chiffres, « . », « _ » ou « - ».".into()) | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +/// Fuseau horaire IANA, vérifié dans `racine_zoneinfo` (normalement `/usr/share/zoneinfo`). | |
| 104 | +pub fn fuseau(saisie: &str, racine_zoneinfo: &Path) -> Resultat { | |
| 105 | + let saisie = saisie.trim(); | |
| 106 | + let forme_ok = !saisie.is_empty() | |
| 107 | + && saisie.split('/').all(|p| { | |
| 108 | + !p.is_empty() | |
| 109 | + && p != "." | |
| 110 | + && p != ".." | |
| 111 | + && p.chars().all(|c| c.is_ascii_alphanumeric() || "_+-".contains(c)) | |
| 112 | + }); | |
| 113 | + if forme_ok && racine_zoneinfo.join(saisie).is_file() { | |
| 114 | + Ok(saisie.to_owned()) | |
| 115 | + } else { | |
| 116 | + Err(format!("« {saisie} » n'est pas un fuseau horaire connu, par exemple Europe/Paris.")) | |
| 117 | + } | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// Texte libre borné (nom, prénom…), espaces de début et de fin retirés. | |
| 121 | +pub fn texte(saisie: &str, min: usize, max: usize) -> Resultat { | |
| 122 | + let saisie = saisie.trim(); | |
| 123 | + let longueur = saisie.chars().count(); | |
| 124 | + if longueur < min { | |
| 125 | + Err(if min <= 1 { "Ce champ est obligatoire.".into() } else { format!("{min} caractères minimum.") }) | |
| 126 | + } else if longueur > max { | |
| 127 | + Err(format!("{max} caractères maximum.")) | |
| 128 | + } else { | |
| 129 | + Ok(saisie.to_owned()) | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// Une règle de la politique de mots de passe et si la saisie la respecte (affichage E-007). | |
| 134 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 135 | +pub struct Regle { | |
| 136 | + pub libelle: String, | |
| 137 | + pub respectee: bool, | |
| 138 | +} | |
| 139 | + | |
| 140 | +/// Évalue un mot de passe contre la politique. `interdits` : identifiant, nom… qui ne | |
| 141 | +/// doivent pas apparaître dans le mot de passe (insensible à la casse, 3 caractères minimum). | |
| 142 | +pub fn regles_mot_de_passe(mdp: &str, politique: &PolitiqueMdp, interdits: &[&str]) -> Vec<Regle> { | |
| 143 | + let classes = [ | |
| 144 | + mdp.chars().any(|c| c.is_lowercase()), | |
| 145 | + mdp.chars().any(|c| c.is_uppercase()), | |
| 146 | + mdp.chars().any(|c| c.is_ascii_digit()), | |
| 147 | + mdp.chars().any(|c| !c.is_alphanumeric()), | |
| 148 | + ] | |
| 149 | + .into_iter() | |
| 150 | + .filter(|presente| *presente) | |
| 151 | + .count(); | |
| 152 | + let minuscule = mdp.to_lowercase(); | |
| 153 | + let contient_interdit = | |
| 154 | + interdits.iter().filter(|i| i.chars().count() >= 3).any(|i| minuscule.contains(&i.to_lowercase())); | |
| 155 | + | |
| 156 | + let mut regles = vec![Regle { | |
| 157 | + libelle: format!("Au moins {} caractères", politique.longueur_min), | |
| 158 | + respectee: mdp.chars().count() >= usize::from(politique.longueur_min), | |
| 159 | + }]; | |
| 160 | + if politique.classes_min > 0 { | |
| 161 | + regles.push(Regle { | |
| 162 | + libelle: format!( | |
| 163 | + "Au moins {} types de caractères parmi minuscules, majuscules, chiffres et symboles", | |
| 164 | + politique.classes_min | |
| 165 | + ), | |
| 166 | + respectee: classes >= usize::from(politique.classes_min), | |
| 167 | + }); | |
| 168 | + } | |
| 169 | + regles.push(Regle { | |
| 170 | + libelle: "Ne contient ni l'identifiant ni le nom".into(), | |
| 171 | + respectee: !contient_interdit, | |
| 172 | + }); | |
| 173 | + regles | |
| 174 | +} | |
| 175 | + | |
| 176 | +#[cfg(test)] | |
| 177 | +mod tests { | |
| 178 | + use super::*; | |
| 179 | + | |
| 180 | + #[test] | |
| 181 | + fn un_domaine_est_normalise_en_minuscules() { | |
| 182 | + assert_eq!(fqdn(" Exemple.FR ").unwrap(), "exemple.fr"); | |
| 183 | + assert_eq!(fqdn("annuaire.mairie-x.fr").unwrap(), "annuaire.mairie-x.fr"); | |
| 184 | + } | |
| 185 | + | |
| 186 | + #[test] | |
| 187 | + fn un_domaine_idn_est_converti_en_punycode() { | |
| 188 | + assert_eq!(fqdn("hôpital.fr").unwrap(), "xn--hpital-ixa.fr"); | |
| 189 | + } | |
| 190 | + | |
| 191 | + #[test] | |
| 192 | + fn les_domaines_invalides_sont_refuses_avec_une_explication() { | |
| 193 | + assert!(fqdn("").unwrap_err().contains("obligatoire")); | |
| 194 | + assert!(fqdn("localhost").unwrap_err().contains("au moins un point")); | |
| 195 | + assert!(fqdn("-exemple.fr").is_err()); | |
| 196 | + assert!(fqdn("exemple-.fr").is_err()); | |
| 197 | + assert!(fqdn("exe mple.fr").is_err()); | |
| 198 | + assert!(fqdn("exemple..fr").is_err()); | |
| 199 | + assert!(fqdn(&format!("{}.fr", "a".repeat(64))).unwrap_err().contains("63")); | |
| 200 | + } | |
| 201 | + | |
| 202 | + #[test] | |
| 203 | + fn la_base_dn_se_deduit_du_domaine() { | |
| 204 | + assert_eq!(dn_depuis_domaine("exemple.fr"), "dc=exemple,dc=fr"); | |
| 205 | + assert_eq!(dn_depuis_domaine("a.b.exemple.fr"), "dc=a,dc=b,dc=exemple,dc=fr"); | |
| 206 | + } | |
| 207 | + | |
| 208 | + #[test] | |
| 209 | + fn une_base_dn_personnalisee_est_validee() { | |
| 210 | + assert_eq!(base_dn("dc=exemple, DC=fr").unwrap(), "dc=exemple,dc=fr"); | |
| 211 | + assert!(base_dn("o=Mairie,c=fr").unwrap_err().contains("dc=")); | |
| 212 | + assert_eq!(base_dn("ou=iam,o=mairie").unwrap(), "ou=iam,o=mairie"); | |
| 213 | + assert!(base_dn("").is_err()); | |
| 214 | + assert!(base_dn("dc=").is_err()); | |
| 215 | + assert!(base_dn("exemple.fr").is_err()); | |
| 216 | + assert!(base_dn("dc=ex,mple,dc=fr").is_err()); | |
| 217 | + } | |
| 218 | + | |
| 219 | + #[test] | |
| 220 | + fn les_e_mails_sont_valides_simplement() { | |
| 221 | + assert_eq!(email(" Jean.Dupont@Exemple.fr ").unwrap(), "Jean.Dupont@exemple.fr"); | |
| 222 | + assert!(email("jean").is_err()); | |
| 223 | + assert!(email("jean@").is_err()); | |
| 224 | + assert!(email("@exemple.fr").is_err()); | |
| 225 | + assert!(email("jean@localhost").is_err()); | |
| 226 | + assert!(email("jean dupont@exemple.fr").is_err()); | |
| 227 | + } | |
| 228 | + | |
| 229 | + #[test] | |
| 230 | + fn les_identifiants_suivent_le_motif_de_e_007() { | |
| 231 | + assert_eq!(uid("jean.dupont").unwrap(), "jean.dupont"); | |
| 232 | + assert!(uid("Jean").is_err()); | |
| 233 | + assert!(uid("1jean").is_err()); | |
| 234 | + assert!(uid("j").is_err()); | |
| 235 | + assert!(uid("jean dupont").is_err()); | |
| 236 | + assert!(uid(&format!("j{}", "a".repeat(64))).is_err()); | |
| 237 | + } | |
| 238 | + | |
| 239 | + #[test] | |
| 240 | + fn un_fuseau_doit_exister_dans_zoneinfo() { | |
| 241 | + let racine = tempfile::tempdir().unwrap(); | |
| 242 | + std::fs::create_dir_all(racine.path().join("Europe")).unwrap(); | |
| 243 | + std::fs::write(racine.path().join("Europe/Paris"), b"TZif").unwrap(); | |
| 244 | + assert_eq!(fuseau("Europe/Paris", racine.path()).unwrap(), "Europe/Paris"); | |
| 245 | + assert!(fuseau("Europe/Lune", racine.path()).is_err()); | |
| 246 | + assert!(fuseau("../etc/passwd", racine.path()).is_err()); | |
| 247 | + assert!(fuseau("", racine.path()).is_err()); | |
| 248 | + } | |
| 249 | + | |
| 250 | + #[test] | |
| 251 | + fn un_texte_est_borne() { | |
| 252 | + assert_eq!(texte(" Mairie de X ", 2, 100).unwrap(), "Mairie de X"); | |
| 253 | + assert!(texte("M", 2, 100).is_err()); | |
| 254 | + assert!(texte(&"x".repeat(101), 2, 100).is_err()); | |
| 255 | + } | |
| 256 | + | |
| 257 | + fn anssi() -> PolitiqueMdp { | |
| 258 | + PolitiqueMdp::anssi() | |
| 259 | + } | |
| 260 | + | |
| 261 | + #[test] | |
| 262 | + fn un_mot_de_passe_conforme_respecte_toutes_les_regles() { | |
| 263 | + let regles = regles_mot_de_passe("Cheval-Batterie-42", &anssi(), &["jean.dupont", "Dupont"]); | |
| 264 | + assert!(regles.iter().all(|r| r.respectee), "{regles:?}"); | |
| 265 | + } | |
| 266 | + | |
| 267 | + #[test] | |
| 268 | + fn les_regles_non_respectees_sont_signalees_une_par_une() { | |
| 269 | + let regles = regles_mot_de_passe("court", &anssi(), &[]); | |
| 270 | + let echecs: Vec<_> = regles.iter().filter(|r| !r.respectee).map(|r| r.libelle.as_str()).collect(); | |
| 271 | + assert_eq!(echecs.len(), 2, "{echecs:?}"); | |
| 272 | + assert!(echecs.iter().any(|l| l.contains("12 caractères"))); | |
| 273 | + assert!(echecs.iter().any(|l| l.contains("3 types"))); | |
| 274 | + } | |
| 275 | + | |
| 276 | + #[test] | |
| 277 | + fn un_mot_de_passe_ne_contient_ni_l_identifiant_ni_le_nom() { | |
| 278 | + let regles = regles_mot_de_passe("Jean.Dupont-2026!", &anssi(), &["jean.dupont", "Dupont"]); | |
| 279 | + assert!(regles.iter().any(|r| !r.respectee && r.libelle.contains("identifiant"))); | |
| 280 | + let regles = regles_mot_de_passe("Xyz-Abcdefgh-1", &anssi(), &["Al"]); | |
| 281 | + assert!(regles.iter().all(|r| r.respectee), "les noms de moins de 3 caractères sont ignorés"); | |
| 282 | + } | |
| 283 | +} |
M
installer/src/errors.rs
+6
-0
@@ -15,6 +15,12 @@ pub enum AppError {
| 15 | 15 | Session(#[from] tower_sessions::session::Error), |
| 16 | 16 | #[error("gabarit : {0}")] |
| 17 | 17 | Template(#[from] askama::Error), |
| 18 | + #[error("brouillon : {0}")] | |
| 19 | + Depot(#[from] crate::brouillon::ErreurDepot), | |
| 20 | + #[error("exécution : {0}")] | |
| 21 | + Runner(#[from] crate::runner::ErreurRunner), | |
| 22 | + #[error("fichier : {0}")] | |
| 23 | + Io(#[from] std::io::Error), | |
| 18 | 24 | #[cfg(debug_assertions)] |
| 19 | 25 | #[error("erreur volontaire de démonstration")] |
| 20 | 26 | Demo, |
A
installer/src/etat.rs
+85
-0
@@ -0,0 +1,85 @@
| 1 | +//! État partagé de l'application : paramètres, brouillon, runner et limitation des | |
| 2 | +//! tentatives d'accès. | |
| 3 | + | |
| 4 | +use std::{ | |
| 5 | + path::PathBuf, | |
| 6 | + sync::{Arc, Mutex}, | |
| 7 | + time::{Duration, Instant}, | |
| 8 | +}; | |
| 9 | + | |
| 10 | +use crate::{ | |
| 11 | + brouillon::{Depot, ErreurDepot}, | |
| 12 | + runner::{ErreurRunner, Outils, Runner}, | |
| 13 | +}; | |
| 14 | + | |
| 15 | +#[derive(Debug, Clone)] | |
| 16 | +pub struct Parametres { | |
| 17 | + /// Répertoire d'état (`/var/lib/open-iam`). | |
| 18 | + pub etat: PathBuf, | |
| 19 | + /// Fuseaux horaires du système. | |
| 20 | + pub zoneinfo: PathBuf, | |
| 21 | + pub outils: Outils, | |
| 22 | + /// Où écrire le fichier récapitulatif de fin d'installation (D-013 : `~/open-iam`). | |
| 23 | + pub dossier_recapitulatif: PathBuf, | |
| 24 | + /// Tests uniquement : prérequis de E-001 tous satisfaits sans sonder le système. | |
| 25 | + pub prerequis_simules: bool, | |
| 26 | +} | |
| 27 | + | |
| 28 | +impl Parametres { | |
| 29 | + pub fn production(etat: PathBuf) -> Self { | |
| 30 | + let maison = std::env::var_os("HOME").map_or_else(|| PathBuf::from("/root"), PathBuf::from); | |
| 31 | + Self { | |
| 32 | + etat, | |
| 33 | + zoneinfo: crate::config::ZONEINFO.into(), | |
| 34 | + outils: Outils::default(), | |
| 35 | + dossier_recapitulatif: maison.join("open-iam"), | |
| 36 | + prerequis_simules: false, | |
| 37 | + } | |
| 38 | + } | |
| 39 | +} | |
| 40 | + | |
| 41 | +#[derive(Debug, thiserror::Error)] | |
| 42 | +pub enum ErreurEtat { | |
| 43 | + #[error(transparent)] | |
| 44 | + Depot(#[from] ErreurDepot), | |
| 45 | + #[error(transparent)] | |
| 46 | + Runner(#[from] ErreurRunner), | |
| 47 | +} | |
| 48 | + | |
| 49 | +pub struct Etat { | |
| 50 | + pub parametres: Parametres, | |
| 51 | + pub depot: Depot, | |
| 52 | + pub runner: Runner, | |
| 53 | + /// Horodatage des échecs récents d'accès par jeton (E-000 : 5 par minute au plus). | |
| 54 | + echecs_acces: Mutex<Vec<Instant>>, | |
| 55 | +} | |
| 56 | + | |
| 57 | +pub const ECHECS_ACCES_MAX: usize = 5; | |
| 58 | +pub const FENETRE_ECHECS: Duration = Duration::from_secs(60); | |
| 59 | + | |
| 60 | +impl Etat { | |
| 61 | + pub fn ouvrir(parametres: Parametres) -> Result<Arc<Self>, ErreurEtat> { | |
| 62 | + let depot = Depot::ouvrir(¶metres.etat)?; | |
| 63 | + let runner = Runner::new(¶metres.etat, parametres.outils.clone())?; | |
| 64 | + Ok(Arc::new(Self { parametres, depot, runner, echecs_acces: Mutex::default() })) | |
| 65 | + } | |
| 66 | + | |
| 67 | + /// La plateforme est-elle installée ? (verrou créé à la fin d'une installation réussie) | |
| 68 | + pub fn installe(&self) -> bool { | |
| 69 | + self.parametres.etat.join(VERROU).exists() | |
| 70 | + } | |
| 71 | + | |
| 72 | + /// Secondes d'attente avant une nouvelle tentative, si la limite est atteinte. | |
| 73 | + pub fn attente_acces(&self) -> Option<u64> { | |
| 74 | + let mut echecs = self.echecs_acces.lock().expect("verrou des échecs"); | |
| 75 | + echecs.retain(|t| t.elapsed() < FENETRE_ECHECS); | |
| 76 | + (echecs.len() >= ECHECS_ACCES_MAX) | |
| 77 | + .then(|| (FENETRE_ECHECS.saturating_sub(echecs[0].elapsed())).as_secs().max(1)) | |
| 78 | + } | |
| 79 | + | |
| 80 | + pub fn noter_echec_acces(&self) { | |
| 81 | + self.echecs_acces.lock().expect("verrou des échecs").push(Instant::now()); | |
| 82 | + } | |
| 83 | +} | |
| 84 | + | |
| 85 | +pub const VERROU: &str = "installed.lock"; |
M
installer/src/lib.rs
+13
-2
@@ -1,10 +1,21 @@
| 1 | +pub mod acces; | |
| 1 | 2 | pub mod assets; |
| 3 | +pub mod assistant; | |
| 4 | +pub mod brouillon; | |
| 5 | +pub mod catalogue; | |
| 6 | +pub mod config; | |
| 2 | 7 | pub mod design_tokens; |
| 3 | 8 | #[cfg(debug_assertions)] |
| 4 | 9 | mod dev; |
| 5 | 10 | pub mod errors; |
| 11 | +pub mod etat; | |
| 6 | 12 | pub mod pages; |
| 13 | +pub mod prerequis; | |
| 14 | +pub mod runner; | |
| 7 | 15 | pub mod security; |
| 16 | +pub mod telemetrie; | |
| 17 | + | |
| 18 | +use std::sync::Arc; | |
| 8 | 19 | |
| 9 | 20 | use axum::{Router, middleware, routing::get}; |
| 10 | 21 | use tower_sessions::{ |
@@ -13,7 +24,7 @@ use tower_sessions::{
| 13 | 24 | }; |
| 14 | 25 | |
| 15 | 26 | /// Application complète. Les sessions sont en mémoire : un redémarrage les invalide (E-000). |
| 16 | -pub fn app() -> Router { | |
| 27 | +pub fn app(etat: Arc<etat::Etat>) -> Router { | |
| 17 | 28 | let sessions = SessionManagerLayer::new(MemoryStore::default()) |
| 18 | 29 | .with_name("oiam_session") |
| 19 | 30 | .with_http_only(true) |
@@ -22,7 +33,7 @@ pub fn app() -> Router {
| 22 | 33 | .with_secure(false) |
| 23 | 34 | .with_expiry(Expiry::OnInactivity(Duration::hours(8))); |
| 24 | 35 | |
| 25 | - let router = Router::new().route("/", get(pages::accueil)).route("/static/{*path}", get(assets::serve)); | |
| 36 | + let router = Router::new().route("/static/{*path}", get(assets::serve)).merge(assistant::routes(etat)); | |
| 26 | 37 | #[cfg(debug_assertions)] |
| 27 | 38 | let router = router.merge(dev::routes()); |
| 28 | 39 |
M
installer/src/main.rs
+76
-7
@@ -1,33 +1,66 @@
| 1 | -use std::{net::SocketAddr, process::ExitCode}; | |
| 1 | +use std::{net::SocketAddr, path::PathBuf, process::ExitCode}; | |
| 2 | 2 | |
| 3 | -use clap::Parser; | |
| 4 | -use open_iam_installer::app; | |
| 3 | +use clap::{Parser, Subcommand}; | |
| 4 | +use open_iam_installer::{ | |
| 5 | + acces, app, | |
| 6 | + etat::{Etat, Parametres}, | |
| 7 | +}; | |
| 5 | 8 | use tokio::net::TcpListener; |
| 6 | 9 | |
| 7 | 10 | /// Installeur et console d'administration Open IAM. |
| 8 | 11 | #[derive(Parser)] |
| 9 | 12 | #[command(version)] |
| 10 | 13 | struct Args { |
| 14 | + /// Répertoire d'état (brouillon, exécutions, verrou d'installation). | |
| 15 | + #[arg(long, global = true, default_value = "/var/lib/open-iam")] | |
| 16 | + etat: PathBuf, | |
| 17 | + #[command(subcommand)] | |
| 18 | + commande: Option<Commande>, | |
| 11 | 19 | /// Adresse d'écoute. Limitée au loopback tant que TLS n'est pas disponible (OI-023) : |
| 12 | 20 | /// depuis un poste distant, passez par un tunnel SSH (`ssh -L 7070:127.0.0.1:7070 serveur`). |
| 13 | 21 | #[arg(long, default_value = "127.0.0.1:7070")] |
| 14 | 22 | listen: SocketAddr, |
| 15 | 23 | } |
| 16 | 24 | |
| 25 | +#[derive(Subcommand)] | |
| 26 | +enum Commande { | |
| 27 | + /// Émet un nouveau jeton d'accès à l'assistant (l'installeur peut tourner en parallèle). | |
| 28 | + NouveauJeton, | |
| 29 | +} | |
| 30 | + | |
| 17 | 31 | #[tokio::main] |
| 18 | 32 | async fn main() -> ExitCode { |
| 19 | 33 | tracing_subscriber::fmt().init(); |
| 20 | 34 | let args = Args::parse(); |
| 21 | 35 | |
| 36 | + if let Some(Commande::NouveauJeton) = args.commande { | |
| 37 | + return match acces::generer(&args.etat) { | |
| 38 | + Ok(jeton) => { | |
| 39 | + afficher_acces(&args.listen, &jeton); | |
| 40 | + ExitCode::SUCCESS | |
| 41 | + } | |
| 42 | + Err(err) => { | |
| 43 | + eprintln!("Impossible d'écrire le jeton dans {} : {err}", args.etat.display()); | |
| 44 | + ExitCode::FAILURE | |
| 45 | + } | |
| 46 | + }; | |
| 47 | + } | |
| 48 | + | |
| 22 | 49 | if !args.listen.ip().is_loopback() { |
| 23 | 50 | eprintln!( |
| 24 | - "Refusé : l'écoute sur {} exposerait l'installeur sans TLS. \ | |
| 25 | - Utilisez 127.0.0.1 et un tunnel SSH.", | |
| 51 | + "Refusé : l'écoute sur {} exposerait l'installeur sans TLS. Utilisez 127.0.0.1 et un tunnel SSH.", | |
| 26 | 52 | args.listen |
| 27 | 53 | ); |
| 28 | 54 | return ExitCode::FAILURE; |
| 29 | 55 | } |
| 30 | 56 | |
| 57 | + let etat = match Etat::ouvrir(parametres(&args)) { | |
| 58 | + Ok(etat) => etat, | |
| 59 | + Err(err) => { | |
| 60 | + eprintln!("Impossible d'ouvrir le répertoire d'état {} : {err}", args.etat.display()); | |
| 61 | + return ExitCode::FAILURE; | |
| 62 | + } | |
| 63 | + }; | |
| 31 | 64 | let listener = match TcpListener::bind(args.listen).await { |
| 32 | 65 | Ok(listener) => listener, |
| 33 | 66 | Err(err) => { |
@@ -35,12 +68,22 @@ async fn main() -> ExitCode {
| 35 | 68 | return ExitCode::FAILURE; |
| 36 | 69 | } |
| 37 | 70 | }; |
| 38 | - println!("Open IAM — installeur disponible sur http://{}/", args.listen); | |
| 71 | + if etat.installe() { | |
| 72 | + println!("Open IAM est déjà installé : l'assistant est verrouillé. http://{}/", args.listen); | |
| 73 | + } else { | |
| 74 | + match acces::generer(&args.etat) { | |
| 75 | + Ok(jeton) => afficher_acces(&args.listen, &jeton), | |
| 76 | + Err(err) => { | |
| 77 | + eprintln!("Impossible d'émettre le jeton d'accès : {err}"); | |
| 78 | + return ExitCode::FAILURE; | |
| 79 | + } | |
| 80 | + } | |
| 81 | + } | |
| 39 | 82 | |
| 40 | 83 | let shutdown = async { |
| 41 | 84 | let _ = tokio::signal::ctrl_c().await; |
| 42 | 85 | }; |
| 43 | - match axum::serve(listener, app()).with_graceful_shutdown(shutdown).await { | |
| 86 | + match axum::serve(listener, app(etat)).with_graceful_shutdown(shutdown).await { | |
| 44 | 87 | Ok(()) => ExitCode::SUCCESS, |
| 45 | 88 | Err(err) => { |
| 46 | 89 | eprintln!("Erreur du serveur : {err}"); |
@@ -48,3 +91,29 @@ async fn main() -> ExitCode {
| 48 | 91 | } |
| 49 | 92 | } |
| 50 | 93 | } |
| 94 | + | |
| 95 | +fn parametres(args: &Args) -> Parametres { | |
| 96 | + #[allow(unused_mut)] | |
| 97 | + let mut parametres = Parametres::production(args.etat.clone()); | |
| 98 | + // Compilation de développement uniquement : parcourir l'assistant sur un poste sans rien | |
| 99 | + // y installer (tests/navigateur). Absent des binaires de production. | |
| 100 | + #[cfg(debug_assertions)] | |
| 101 | + { | |
| 102 | + if std::env::var_os("OIAM_DEV_PREREQUIS_SIMULES").is_some() { | |
| 103 | + parametres.prerequis_simules = true; | |
| 104 | + } | |
| 105 | + if let Some(chemin) = std::env::var_os("OIAM_DEV_ANSIBLE_PLAYBOOK") { | |
| 106 | + parametres.outils.ansible_playbook = chemin.into(); | |
| 107 | + } | |
| 108 | + if let Some(chemin) = std::env::var_os("OIAM_DEV_ANSIBLE_VAULT") { | |
| 109 | + parametres.outils.ansible_vault = chemin.into(); | |
| 110 | + } | |
| 111 | + } | |
| 112 | + parametres | |
| 113 | +} | |
| 114 | + | |
| 115 | +fn afficher_acces(listen: &SocketAddr, jeton: &str) { | |
| 116 | + println!("Open IAM — ouvrez cette adresse (valable 30 minutes, usage unique) :"); | |
| 117 | + println!(" http://{listen}/acces?jeton={jeton}"); | |
| 118 | + println!("Depuis votre poste : ssh -L {port}:127.0.0.1:{port} <serveur>", port = listen.port()); | |
| 119 | +} |
M
installer/src/pages.rs
+0
-12
@@ -1,7 +1,5 @@
| 1 | 1 | //! Données communes des gabarits et pages de l'application. |
| 2 | 2 | |
| 3 | -use askama::Template; | |
| 4 | -use axum::response::Html; | |
| 5 | 3 | use tower_sessions::Session; |
| 6 | 4 | |
| 7 | 5 | use crate::{errors::AppError, security::csrf_token}; |
@@ -34,13 +32,3 @@ impl Layout {
| 34 | 32 | HTMX_CONFIG |
| 35 | 33 | } |
| 36 | 34 | } |
| 37 | - | |
| 38 | -#[derive(Template)] | |
| 39 | -#[template(path = "pages/accueil.html")] | |
| 40 | -struct Accueil { | |
| 41 | - layout: Layout, | |
| 42 | -} | |
| 43 | - | |
| 44 | -pub async fn accueil(session: Session) -> Result<Html<String>, AppError> { | |
| 45 | - Ok(Html(Accueil { layout: Layout::new(&session).await? }.render()?)) | |
| 46 | -} |
A
installer/src/prerequis.rs
+341
-0
@@ -0,0 +1,341 @@
| 1 | +//! Prérequis de E-001 : chaque contrôle est une fonction pure sur la sortie d'une commande | |
| 2 | +//! système (testable), la collecte des sorties est faite par [`verifier`]. | |
| 3 | + | |
| 4 | +use std::{net::SocketAddr, time::Duration}; | |
| 5 | + | |
| 6 | +use tokio::{net::TcpStream, process::Command, time::timeout}; | |
| 7 | + | |
| 8 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 9 | +pub enum Niveau { | |
| 10 | + Ok, | |
| 11 | + Avertissement, | |
| 12 | + Bloquant, | |
| 13 | +} | |
| 14 | + | |
| 15 | +impl Niveau { | |
| 16 | + /// État du badge C-008. | |
| 17 | + pub fn badge(self) -> &'static str { | |
| 18 | + match self { | |
| 19 | + Self::Ok => "ok", | |
| 20 | + Self::Avertissement => "avertissement", | |
| 21 | + Self::Bloquant => "erreur", | |
| 22 | + } | |
| 23 | + } | |
| 24 | +} | |
| 25 | + | |
| 26 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 27 | +pub struct Controle { | |
| 28 | + pub cle: &'static str, | |
| 29 | + pub libelle: &'static str, | |
| 30 | + pub niveau: Niveau, | |
| 31 | + pub detail: String, | |
| 32 | +} | |
| 33 | + | |
| 34 | +impl Controle { | |
| 35 | + fn new(cle: &'static str, libelle: &'static str, niveau: Niveau, detail: impl Into<String>) -> Self { | |
| 36 | + Self { cle, libelle, niveau, detail: detail.into() } | |
| 37 | + } | |
| 38 | +} | |
| 39 | + | |
| 40 | +/// Distributions supportées (Q-03). | |
| 41 | +pub const SYSTEMES: [(&str, &str, &str); 2] = | |
| 42 | + [("debian", "trixie", "Debian 13"), ("ubuntu", "resolute", "Ubuntu 26.04 LTS")]; | |
| 43 | + | |
| 44 | +pub fn systeme(os_release: &str) -> Controle { | |
| 45 | + let valeur = |cle: &str| { | |
| 46 | + os_release | |
| 47 | + .lines() | |
| 48 | + .find_map(|l| l.strip_prefix(&format!("{cle}="))) | |
| 49 | + .map(|v| v.trim_matches('"').to_owned()) | |
| 50 | + .unwrap_or_default() | |
| 51 | + }; | |
| 52 | + let (id, nom_code, joli) = (valeur("ID"), valeur("VERSION_CODENAME"), valeur("PRETTY_NAME")); | |
| 53 | + let supportes = SYSTEMES.iter().map(|(_, _, nom)| *nom).collect::<Vec<_>>().join(" ou "); | |
| 54 | + if SYSTEMES.iter().any(|(i, c, _)| *i == id && *c == nom_code) { | |
| 55 | + Controle::new("systeme", "Système d'exploitation", Niveau::Ok, joli) | |
| 56 | + } else { | |
| 57 | + Controle::new( | |
| 58 | + "systeme", | |
| 59 | + "Système d'exploitation", | |
| 60 | + Niveau::Bloquant, | |
| 61 | + format!( | |
| 62 | + "{} n'est pas supporté : installez {supportes}.", | |
| 63 | + if joli.is_empty() { "Ce système" } else { &joli } | |
| 64 | + ), | |
| 65 | + ) | |
| 66 | + } | |
| 67 | +} | |
| 68 | + | |
| 69 | +pub fn administrateur(uid: u32) -> Controle { | |
| 70 | + if uid == 0 { | |
| 71 | + Controle::new("root", "Droits d'administration", Niveau::Ok, "L'installeur s'exécute en root.") | |
| 72 | + } else { | |
| 73 | + Controle::new( | |
| 74 | + "root", | |
| 75 | + "Droits d'administration", | |
| 76 | + Niveau::Bloquant, | |
| 77 | + "Relancez l'installeur en root : sudo open-iam-installer", | |
| 78 | + ) | |
| 79 | + } | |
| 80 | +} | |
| 81 | + | |
| 82 | +/// `version` : première ligne de `ansible-playbook --version`, ou `None` s'il est absent. | |
| 83 | +pub fn ansible(version: Option<&str>) -> Controle { | |
| 84 | + let libelle = "Ansible"; | |
| 85 | + let Some(ligne) = version else { | |
| 86 | + return Controle::new("ansible", libelle, Niveau::Bloquant, "Ansible n'est pas installé."); | |
| 87 | + }; | |
| 88 | + let numero = ligne.split(['[', ']']).nth(1).unwrap_or(ligne).trim().replace("core ", ""); | |
| 89 | + let mut parties = numero.split('.').map(|p| p.parse::<u32>().unwrap_or(0)); | |
| 90 | + let (majeur, mineur) = (parties.next().unwrap_or(0), parties.next().unwrap_or(0)); | |
| 91 | + if (majeur, mineur) >= (2, 16) { | |
| 92 | + Controle::new("ansible", libelle, Niveau::Ok, format!("ansible-core {numero}")) | |
| 93 | + } else { | |
| 94 | + Controle::new( | |
| 95 | + "ansible", | |
| 96 | + libelle, | |
| 97 | + Niveau::Bloquant, | |
| 98 | + format!("ansible-core {numero} est trop ancien : la version 2.16 au moins est requise."), | |
| 99 | + ) | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +/// Ansible est installé mais `ansible-playbook --version` échoue : on montre son erreur. | |
| 104 | +pub fn ansible_defaillant(erreur: &str) -> Controle { | |
| 105 | + let derniere = erreur.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("erreur inconnue").trim(); | |
| 106 | + Controle::new( | |
| 107 | + "ansible", | |
| 108 | + "Ansible", | |
| 109 | + Niveau::Bloquant, | |
| 110 | + format!("Ansible est installé mais ne démarre pas : {derniere}"), | |
| 111 | + ) | |
| 112 | +} | |
| 113 | + | |
| 114 | +/// `octets_libres` : espace disponible sur /var. | |
| 115 | +pub fn espace(octets_libres: u64) -> Controle { | |
| 116 | + let go = octets_libres / 1_000_000_000; | |
| 117 | + let (niveau, detail) = match go { | |
| 118 | + 0..5 => (Niveau::Bloquant, format!("{go} Go libres sur /var : 5 Go au minimum sont nécessaires.")), | |
| 119 | + 5..20 => (Niveau::Avertissement, format!("{go} Go libres sur /var : 20 Go sont recommandés.")), | |
| 120 | + _ => (Niveau::Ok, format!("{go} Go libres sur /var.")), | |
| 121 | + }; | |
| 122 | + Controle::new("espace", "Espace disque", niveau, detail) | |
| 123 | +} | |
| 124 | + | |
| 125 | +/// `ss` : sortie de `ss -ltnpH`. Les ports occupés ne bloquent pas (un service existant peut | |
| 126 | +/// être volontaire), mais le processus en cause est indiqué. | |
| 127 | +pub fn ports(ss: &str, attendus: &[u16]) -> Controle { | |
| 128 | + let occupes: Vec<String> = attendus | |
| 129 | + .iter() | |
| 130 | + .filter_map(|port| { | |
| 131 | + ss.lines() | |
| 132 | + .find(|l| l.split_whitespace().nth(3).is_some_and(|a| a.ends_with(&format!(":{port}")))) | |
| 133 | + .map(|l| { | |
| 134 | + let processus = | |
| 135 | + l.split("((\"").nth(1).and_then(|p| p.split('"').next()).unwrap_or("inconnu"); | |
| 136 | + format!("{port} ({processus})") | |
| 137 | + }) | |
| 138 | + }) | |
| 139 | + .collect(); | |
| 140 | + if occupes.is_empty() { | |
| 141 | + Controle::new("ports", "Ports réseau", Niveau::Ok, "Les ports nécessaires sont libres.") | |
| 142 | + } else { | |
| 143 | + Controle::new( | |
| 144 | + "ports", | |
| 145 | + "Ports réseau", | |
| 146 | + Niveau::Avertissement, | |
| 147 | + format!("Ports déjà utilisés : {}. Arrêtez ces services avant d'installer.", occupes.join(", ")), | |
| 148 | + ) | |
| 149 | + } | |
| 150 | +} | |
| 151 | + | |
| 152 | +/// `injoignables` : dépôts dont le port 443 n'a pas répondu. | |
| 153 | +pub fn depots(injoignables: &[&str]) -> Controle { | |
| 154 | + if injoignables.is_empty() { | |
| 155 | + Controle::new("depots", "Accès aux dépôts de paquets", Niveau::Ok, "Les dépôts répondent.") | |
| 156 | + } else { | |
| 157 | + Controle::new( | |
| 158 | + "depots", | |
| 159 | + "Accès aux dépôts de paquets", | |
| 160 | + Niveau::Avertissement, | |
| 161 | + format!( | |
| 162 | + "Injoignables : {}. Une installation hors ligne exige un miroir local (voir la documentation).", | |
| 163 | + injoignables.join(", ") | |
| 164 | + ), | |
| 165 | + ) | |
| 166 | + } | |
| 167 | +} | |
| 168 | + | |
| 169 | +/// `synchronisee` : sortie de `timedatectl show -p NTPSynchronized --value`. | |
| 170 | +pub fn horloge(synchronisee: Option<&str>) -> Controle { | |
| 171 | + if synchronisee.map(str::trim) == Some("yes") { | |
| 172 | + Controle::new("horloge", "Horloge", Niveau::Ok, "Horloge synchronisée.") | |
| 173 | + } else { | |
| 174 | + Controle::new( | |
| 175 | + "horloge", | |
| 176 | + "Horloge", | |
| 177 | + Niveau::Avertissement, | |
| 178 | + "L'horloge n'est pas synchronisée : les certificats et la double authentification en dépendent. L'installation activera la synchronisation.", | |
| 179 | + ) | |
| 180 | + } | |
| 181 | +} | |
| 182 | + | |
| 183 | +pub const DEPOTS: [&str; 3] = ["ltb-project.org", "deb.debian.org", "archive.ubuntu.com"]; | |
| 184 | +pub const PORTS: [u16; 2] = [389, 636]; | |
| 185 | + | |
| 186 | +/// Collecte les informations du système et applique les contrôles. | |
| 187 | +pub async fn verifier(simules: bool) -> Vec<Controle> { | |
| 188 | + if simules { | |
| 189 | + return vec![ | |
| 190 | + systeme("ID=debian\nVERSION_CODENAME=trixie\nPRETTY_NAME=\"Debian GNU/Linux 13 (trixie)\""), | |
| 191 | + administrateur(0), | |
| 192 | + ansible(Some("ansible-playbook [core 2.19.4]")), | |
| 193 | + espace(50_000_000_000), | |
| 194 | + ports("", &PORTS), | |
| 195 | + depots(&[]), | |
| 196 | + horloge(Some("yes")), | |
| 197 | + ]; | |
| 198 | + } | |
| 199 | + let os_release = tokio::fs::read_to_string("/etc/os-release").await.unwrap_or_default(); | |
| 200 | + let uid = sortie("id", &["-u"]).await.and_then(|s| s.trim().parse().ok()).unwrap_or(u32::MAX); | |
| 201 | + let controle_ansible = match executer("ansible-playbook", &["--version"]).await { | |
| 202 | + None => ansible(None), | |
| 203 | + Some(Ok(version)) => ansible(version.lines().next()), | |
| 204 | + Some(Err(erreur)) => ansible_defaillant(&erreur), | |
| 205 | + }; | |
| 206 | + let libre = sortie("df", &["--output=avail", "-B1", "/var"]) | |
| 207 | + .await | |
| 208 | + .and_then(|s| s.lines().nth(1).and_then(|l| l.trim().parse().ok())) | |
| 209 | + .unwrap_or(0); | |
| 210 | + let ss = sortie("ss", &["-ltnpH"]).await.unwrap_or_default(); | |
| 211 | + let mut injoignables = Vec::new(); | |
| 212 | + for depot in DEPOTS { | |
| 213 | + if !joignable(depot).await { | |
| 214 | + injoignables.push(depot); | |
| 215 | + } | |
| 216 | + } | |
| 217 | + let ntp = sortie("timedatectl", &["show", "-p", "NTPSynchronized", "--value"]).await; | |
| 218 | + vec![ | |
| 219 | + systeme(&os_release), | |
| 220 | + administrateur(uid), | |
| 221 | + controle_ansible, | |
| 222 | + espace(libre), | |
| 223 | + ports(&ss, &PORTS), | |
| 224 | + depots(&injoignables), | |
| 225 | + horloge(ntp.as_deref()), | |
| 226 | + ] | |
| 227 | +} | |
| 228 | + | |
| 229 | +pub fn bloquant(controles: &[Controle]) -> bool { | |
| 230 | + controles.iter().any(|c| c.niveau == Niveau::Bloquant) | |
| 231 | +} | |
| 232 | + | |
| 233 | +async fn sortie(programme: &str, arguments: &[&str]) -> Option<String> { | |
| 234 | + executer(programme, arguments).await.and_then(Result::ok) | |
| 235 | +} | |
| 236 | + | |
| 237 | +/// `None` si le programme est introuvable, sinon sa sortie standard ou, en cas d'échec, son | |
| 238 | +/// erreur. Locale fixe : sorties analysables et Ansible indépendant de la locale du système. | |
| 239 | +async fn executer(programme: &str, arguments: &[&str]) -> Option<Result<String, String>> { | |
| 240 | + let resultat = Command::new(programme).args(arguments).envs(crate::runner::LOCALE).output().await.ok()?; | |
| 241 | + Some(if resultat.status.success() { | |
| 242 | + Ok(String::from_utf8_lossy(&resultat.stdout).into_owned()) | |
| 243 | + } else { | |
| 244 | + Err(format!( | |
| 245 | + "{}{}", | |
| 246 | + String::from_utf8_lossy(&resultat.stdout), | |
| 247 | + String::from_utf8_lossy(&resultat.stderr) | |
| 248 | + )) | |
| 249 | + }) | |
| 250 | +} | |
| 251 | + | |
| 252 | +async fn joignable(hote: &str) -> bool { | |
| 253 | + let Ok(Ok(mut adresses)) = timeout(Duration::from_secs(3), tokio::net::lookup_host((hote, 443))).await | |
| 254 | + else { | |
| 255 | + return false; | |
| 256 | + }; | |
| 257 | + let Some(adresse): Option<SocketAddr> = adresses.next() else { return false }; | |
| 258 | + matches!(timeout(Duration::from_secs(3), TcpStream::connect(adresse)).await, Ok(Ok(_))) | |
| 259 | +} | |
| 260 | + | |
| 261 | +/// Installe ansible-core depuis les dépôts de la distribution (bouton de E-001). | |
| 262 | +pub async fn installer_ansible() -> Result<(), String> { | |
| 263 | + let resultat = Command::new("apt-get") | |
| 264 | + .args(["install", "-y", "--no-install-recommends", "ansible-core"]) | |
| 265 | + .env("DEBIAN_FRONTEND", "noninteractive") | |
| 266 | + .envs(crate::runner::LOCALE) | |
| 267 | + .output() | |
| 268 | + .await | |
| 269 | + .map_err(|e| e.to_string())?; | |
| 270 | + if resultat.status.success() { | |
| 271 | + Ok(()) | |
| 272 | + } else { | |
| 273 | + Err(String::from_utf8_lossy(&resultat.stderr).lines().last().unwrap_or("échec d'apt-get").to_owned()) | |
| 274 | + } | |
| 275 | +} | |
| 276 | + | |
| 277 | +#[cfg(test)] | |
| 278 | +mod tests { | |
| 279 | + use super::*; | |
| 280 | + | |
| 281 | + #[test] | |
| 282 | + fn debian_13_et_ubuntu_26_04_sont_supportes() { | |
| 283 | + assert_eq!( | |
| 284 | + systeme("ID=debian\nVERSION_CODENAME=trixie\nPRETTY_NAME=\"Debian 13\"").niveau, | |
| 285 | + Niveau::Ok | |
| 286 | + ); | |
| 287 | + assert_eq!(systeme("ID=ubuntu\nVERSION_CODENAME=resolute\n").niveau, Niveau::Ok); | |
| 288 | + let refus = systeme("ID=debian\nVERSION_CODENAME=bookworm\nPRETTY_NAME=\"Debian GNU/Linux 12\""); | |
| 289 | + assert_eq!(refus.niveau, Niveau::Bloquant); | |
| 290 | + assert!(refus.detail.contains("Debian GNU/Linux 12"), "{}", refus.detail); | |
| 291 | + assert!(refus.detail.contains("Debian 13 ou Ubuntu 26.04"), "{}", refus.detail); | |
| 292 | + } | |
| 293 | + | |
| 294 | + #[test] | |
| 295 | + fn root_est_exige() { | |
| 296 | + assert_eq!(administrateur(0).niveau, Niveau::Ok); | |
| 297 | + assert_eq!(administrateur(1000).niveau, Niveau::Bloquant); | |
| 298 | + } | |
| 299 | + | |
| 300 | + #[test] | |
| 301 | + fn ansible_2_16_au_moins() { | |
| 302 | + assert_eq!(ansible(Some("ansible-playbook [core 2.19.4]")).niveau, Niveau::Ok); | |
| 303 | + assert_eq!(ansible(Some("ansible-playbook [core 2.16.0]")).niveau, Niveau::Ok); | |
| 304 | + assert_eq!(ansible(Some("ansible-playbook [core 2.14.3]")).niveau, Niveau::Bloquant); | |
| 305 | + assert_eq!(ansible(None).niveau, Niveau::Bloquant); | |
| 306 | + } | |
| 307 | + | |
| 308 | + #[test] | |
| 309 | + fn un_ansible_qui_ne_demarre_pas_affiche_son_erreur() { | |
| 310 | + let c = ansible_defaillant( | |
| 311 | + "ERROR: Ansible could not initialize the preferred locale: unsupported locale setting\n", | |
| 312 | + ); | |
| 313 | + assert_eq!(c.niveau, Niveau::Bloquant); | |
| 314 | + assert!(c.detail.contains("ne démarre pas"), "{}", c.detail); | |
| 315 | + assert!(c.detail.contains("unsupported locale setting"), "{}", c.detail); | |
| 316 | + } | |
| 317 | + | |
| 318 | + #[test] | |
| 319 | + fn l_espace_disque_a_deux_seuils() { | |
| 320 | + assert_eq!(espace(4_000_000_000).niveau, Niveau::Bloquant); | |
| 321 | + assert_eq!(espace(10_000_000_000).niveau, Niveau::Avertissement); | |
| 322 | + assert_eq!(espace(30_000_000_000).niveau, Niveau::Ok); | |
| 323 | + } | |
| 324 | + | |
| 325 | + #[test] | |
| 326 | + fn un_port_occupe_indique_le_processus() { | |
| 327 | + let ss = "LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:((\"sshd\",pid=1,fd=3))\n\ | |
| 328 | + LISTEN 0 128 0.0.0.0:389 0.0.0.0:* users:((\"slapd\",pid=42,fd=8))\n"; | |
| 329 | + let c = ports(ss, &PORTS); | |
| 330 | + assert_eq!(c.niveau, Niveau::Avertissement); | |
| 331 | + assert!(c.detail.contains("389 (slapd)"), "{}", c.detail); | |
| 332 | + assert_eq!(ports("LISTEN 0 128 0.0.0.0:22 0.0.0.0:*\n", &PORTS).niveau, Niveau::Ok); | |
| 333 | + } | |
| 334 | + | |
| 335 | + #[test] | |
| 336 | + fn les_depots_et_l_horloge_ne_bloquent_pas() { | |
| 337 | + assert_eq!(depots(&["ltb-project.org"]).niveau, Niveau::Avertissement); | |
| 338 | + assert_eq!(horloge(Some("no")).niveau, Niveau::Avertissement); | |
| 339 | + assert_eq!(horloge(Some("yes\n")).niveau, Niveau::Ok); | |
| 340 | + } | |
| 341 | +} |
A
installer/src/runner.rs
+619
-0
@@ -0,0 +1,619 @@
| 1 | +//! Exécution d'Ansible (OI-036) : préparation de l'arborescence et de l'inventaire, | |
| 2 | +//! lancement d'`ansible-playbook`, traduction de sa sortie en événements, journal sur | |
| 3 | +//! disque (reprise après reconnexion ou redémarrage) et diffusion en direct (E-011). | |
| 4 | + | |
| 5 | +use std::{ | |
| 6 | + fs, | |
| 7 | + io::Write, | |
| 8 | + path::{Path, PathBuf}, | |
| 9 | + process::Stdio, | |
| 10 | + sync::{ | |
| 11 | + Arc, Mutex, | |
| 12 | + atomic::{AtomicBool, Ordering}, | |
| 13 | + }, | |
| 14 | +}; | |
| 15 | + | |
| 16 | +use rust_embed::Embed; | |
| 17 | +use serde::{Deserialize, Serialize}; | |
| 18 | +use tokio::{ | |
| 19 | + io::{AsyncBufReadExt, BufReader}, | |
| 20 | + process::Command, | |
| 21 | + sync::{broadcast, mpsc}, | |
| 22 | +}; | |
| 23 | + | |
| 24 | +use crate::{ | |
| 25 | + brouillon::ecrire_0600, | |
| 26 | + catalogue::ComposantId, | |
| 27 | + config::{OpenIamConfig, Secret, Secrets, TlsMode, ansible}, | |
| 28 | +}; | |
| 29 | + | |
| 30 | +/// Playbooks et rôles embarqués dans le binaire (plan M1 § Architecture). | |
| 31 | +#[derive(Embed)] | |
| 32 | +#[folder = "../ansible/"] | |
| 33 | +#[exclude = "molecule/*"] | |
| 34 | +#[exclude = "inventories/*"] | |
| 35 | +#[exclude = ".ansible-lint"] | |
| 36 | +#[exclude = "*.retry"] | |
| 37 | +#[exclude = "*__pycache__*"] | |
| 38 | +struct Playbooks; | |
| 39 | + | |
| 40 | +/// Programmes externes utilisés (remplacés par des faux dans les tests). | |
| 41 | +#[derive(Debug, Clone)] | |
| 42 | +pub struct Outils { | |
| 43 | + pub ansible_playbook: PathBuf, | |
| 44 | + pub ansible_vault: PathBuf, | |
| 45 | + /// Variables d'environnement supplémentaires transmises à ansible-playbook. | |
| 46 | + pub environnement: Vec<(String, String)>, | |
| 47 | +} | |
| 48 | + | |
| 49 | +impl Default for Outils { | |
| 50 | + fn default() -> Self { | |
| 51 | + Self { | |
| 52 | + ansible_playbook: "ansible-playbook".into(), | |
| 53 | + ansible_vault: "ansible-vault".into(), | |
| 54 | + environnement: Vec::new(), | |
| 55 | + } | |
| 56 | + } | |
| 57 | +} | |
| 58 | + | |
| 59 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| 60 | +#[serde(rename_all = "snake_case")] | |
| 61 | +pub enum StatutExecution { | |
| 62 | + EnCours, | |
| 63 | + Reussie, | |
| 64 | + Echouee, | |
| 65 | + Interrompue, | |
| 66 | +} | |
| 67 | + | |
| 68 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| 69 | +#[serde(rename_all = "snake_case")] | |
| 70 | +pub enum EtatPhase { | |
| 71 | + AVenir, | |
| 72 | + EnCours, | |
| 73 | + Ok, | |
| 74 | + Echec, | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// Événement d'une exécution, numéroté dans le journal (identifiant SSE). | |
| 78 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | |
| 79 | +#[serde(tag = "type", rename_all = "snake_case")] | |
| 80 | +pub enum Evenement { | |
| 81 | + Phase { phase: String, etat: EtatPhase }, | |
| 82 | + Progression { faites: u32, total: u32 }, | |
| 83 | + Ligne { heure: String, hote: String, phase: String, tache: String, statut: String, message: String }, | |
| 84 | + Brut { texte: String }, | |
| 85 | + Fin { statut: StatutExecution, message: Option<String> }, | |
| 86 | +} | |
| 87 | + | |
| 88 | +/// État d'une exécution (`executions/<id>/etat.json`). | |
| 89 | +#[derive(Debug, Clone, Serialize, Deserialize)] | |
| 90 | +pub struct EtatExecution { | |
| 91 | + pub id: String, | |
| 92 | + pub statut: StatutExecution, | |
| 93 | + pub debut: String, | |
| 94 | + pub fin: Option<String>, | |
| 95 | + pub phases: Vec<(String, EtatPhase)>, | |
| 96 | +} | |
| 97 | + | |
| 98 | +#[derive(Debug, thiserror::Error)] | |
| 99 | +pub enum ErreurRunner { | |
| 100 | + #[error("une installation est déjà en cours")] | |
| 101 | + Occupe, | |
| 102 | + #[error("aucune installation en cours")] | |
| 103 | + Inactif, | |
| 104 | + #[error("exécution inconnue : {0}")] | |
| 105 | + Inconnue(String), | |
| 106 | + #[error("préparation de l'exécution : {0}")] | |
| 107 | + Io(#[from] std::io::Error), | |
| 108 | + #[error("état d'exécution illisible : {0}")] | |
| 109 | + Json(#[from] serde_json::Error), | |
| 110 | + #[error("chiffrement des secrets : {0}")] | |
| 111 | + Coffre(String), | |
| 112 | +} | |
| 113 | + | |
| 114 | +/// Locale des commandes externes : toujours présente sur Debian et Ubuntu, indépendante de | |
| 115 | +/// celle de l'administrateur (une locale non générée empêche Ansible de démarrer). | |
| 116 | +pub const LOCALE: [(&str, &str); 2] = [("LC_ALL", "C.UTF-8"), ("LANG", "C.UTF-8")]; | |
| 117 | + | |
| 118 | +/// Phases affichées en E-011 : rôles de site.yml appliqués, dans l'ordre, avec leur libellé. | |
| 119 | +pub fn phases(config: &OpenIamConfig) -> Vec<(&'static str, &'static str)> { | |
| 120 | + let mut phases = vec![("common", "Préparation du système")]; | |
| 121 | + if config.tls.mode == TlsMode::Interne { | |
| 122 | + phases.push(("pki", "Certificats")); | |
| 123 | + } | |
| 124 | + phases.push(("hardening", "Durcissement")); | |
| 125 | + if config.composants.contains(&ComposantId::Openldap) { | |
| 126 | + phases.push(("openldap_ltb", "Annuaire OpenLDAP")); | |
| 127 | + } | |
| 128 | + if config.composants.contains(&ComposantId::Sauvegarde) { | |
| 129 | + phases.push(("backup", "Sauvegardes")); | |
| 130 | + } | |
| 131 | + phases | |
| 132 | +} | |
| 133 | + | |
| 134 | +struct Actif { | |
| 135 | + id: String, | |
| 136 | + emetteur: broadcast::Sender<(u64, Evenement)>, | |
| 137 | + pid: Option<u32>, | |
| 138 | + interrompu: Arc<AtomicBool>, | |
| 139 | +} | |
| 140 | + | |
| 141 | +pub struct Runner { | |
| 142 | + racine: PathBuf, | |
| 143 | + outils: Outils, | |
| 144 | + actif: Arc<Mutex<Option<Actif>>>, | |
| 145 | +} | |
| 146 | + | |
| 147 | +impl Runner { | |
| 148 | + /// Ouvre le répertoire d'état et marque « interrompue » toute exécution restée « en cours » | |
| 149 | + /// (installeur arrêté pendant une installation). | |
| 150 | + pub fn new(racine: impl Into<PathBuf>, outils: Outils) -> Result<Self, ErreurRunner> { | |
| 151 | + use std::os::unix::fs::PermissionsExt; | |
| 152 | + let racine = racine.into(); | |
| 153 | + fs::create_dir_all(racine.join("executions"))?; | |
| 154 | + fs::set_permissions(&racine, fs::Permissions::from_mode(0o700))?; | |
| 155 | + let runner = Self { racine, outils, actif: Arc::new(Mutex::new(None)) }; | |
| 156 | + for id in runner.identifiants()? { | |
| 157 | + let chemin = runner.dossier_execution(&id).join("etat.json"); | |
| 158 | + if let Ok(mut etat) = lire_etat(&chemin) | |
| 159 | + && etat.statut == StatutExecution::EnCours | |
| 160 | + { | |
| 161 | + etat.statut = StatutExecution::Interrompue; | |
| 162 | + etat.fin = Some(maintenant()); | |
| 163 | + ecrire_etat(&chemin, &etat)?; | |
| 164 | + } | |
| 165 | + } | |
| 166 | + Ok(runner) | |
| 167 | + } | |
| 168 | + | |
| 169 | + pub fn dossier_execution(&self, id: &str) -> PathBuf { | |
| 170 | + self.racine.join("executions").join(id) | |
| 171 | + } | |
| 172 | + | |
| 173 | + fn identifiants(&self) -> Result<Vec<String>, ErreurRunner> { | |
| 174 | + let mut ids: Vec<String> = fs::read_dir(self.racine.join("executions"))? | |
| 175 | + .filter_map(Result::ok) | |
| 176 | + .filter(|e| e.path().join("etat.json").is_file()) | |
| 177 | + .filter_map(|e| e.file_name().into_string().ok()) | |
| 178 | + .collect(); | |
| 179 | + ids.sort(); | |
| 180 | + Ok(ids) | |
| 181 | + } | |
| 182 | + | |
| 183 | + /// État de la dernière exécution, s'il y en a une. | |
| 184 | + pub fn derniere(&self) -> Option<EtatExecution> { | |
| 185 | + let id = self.identifiants().ok()?.pop()?; | |
| 186 | + lire_etat(&self.dossier_execution(&id).join("etat.json")).ok() | |
| 187 | + } | |
| 188 | + | |
| 189 | + pub fn en_cours(&self) -> bool { | |
| 190 | + self.actif.lock().expect("verrou du runner").is_some() | |
| 191 | + } | |
| 192 | + | |
| 193 | + /// Lance une installation. `finaliser` s'exécute après un succès d'Ansible (fichier | |
| 194 | + /// récapitulatif, verrou de l'assistant) ; son échec fait échouer l'exécution. | |
| 195 | + pub async fn lancer<F>( | |
| 196 | + &self, | |
| 197 | + config: &OpenIamConfig, | |
| 198 | + secrets: &Secrets, | |
| 199 | + finaliser: F, | |
| 200 | + ) -> Result<String, ErreurRunner> | |
| 201 | + where | |
| 202 | + F: FnOnce(&Path) -> Result<(), String> + Send + 'static, | |
| 203 | + { | |
| 204 | + let id = { | |
| 205 | + let mut actif = self.actif.lock().expect("verrou du runner"); | |
| 206 | + if actif.is_some() { | |
| 207 | + return Err(ErreurRunner::Occupe); | |
| 208 | + } | |
| 209 | + let id = identifiant(); | |
| 210 | + let (emetteur, _) = broadcast::channel(1024); | |
| 211 | + *actif = Some(Actif { id: id.clone(), emetteur, pid: None, interrompu: Arc::default() }); | |
| 212 | + id | |
| 213 | + }; | |
| 214 | + match self.demarrer(&id, config, secrets, finaliser).await { | |
| 215 | + Ok(()) => Ok(id), | |
| 216 | + Err(erreur) => { | |
| 217 | + *self.actif.lock().expect("verrou du runner") = None; | |
| 218 | + Err(erreur) | |
| 219 | + } | |
| 220 | + } | |
| 221 | + } | |
| 222 | + | |
| 223 | + async fn demarrer<F>( | |
| 224 | + &self, | |
| 225 | + id: &str, | |
| 226 | + config: &OpenIamConfig, | |
| 227 | + secrets: &Secrets, | |
| 228 | + finaliser: F, | |
| 229 | + ) -> Result<(), ErreurRunner> | |
| 230 | + where | |
| 231 | + F: FnOnce(&Path) -> Result<(), String> + Send + 'static, | |
| 232 | + { | |
| 233 | + let dossier = self.dossier_execution(id); | |
| 234 | + let playbooks = dossier.join("ansible"); | |
| 235 | + extraire_playbooks(&playbooks)?; | |
| 236 | + let coffre = self.mot_de_passe_coffre()?; | |
| 237 | + self.preparer_inventaire(&dossier.join("inventaire"), config, secrets, &coffre).await?; | |
| 238 | + | |
| 239 | + let phases = phases(config); | |
| 240 | + let etat = EtatExecution { | |
| 241 | + id: id.to_owned(), | |
| 242 | + statut: StatutExecution::EnCours, | |
| 243 | + debut: maintenant(), | |
| 244 | + fin: None, | |
| 245 | + phases: phases.iter().map(|(_, libelle)| ((*libelle).to_owned(), EtatPhase::AVenir)).collect(), | |
| 246 | + }; | |
| 247 | + ecrire_etat(&dossier.join("etat.json"), &etat)?; | |
| 248 | + | |
| 249 | + let mut commande = Command::new(&self.outils.ansible_playbook); | |
| 250 | + commande | |
| 251 | + .current_dir(&playbooks) | |
| 252 | + .arg("--inventory") | |
| 253 | + .arg(dossier.join("inventaire/hosts.yml")) | |
| 254 | + .arg("--vault-password-file") | |
| 255 | + .arg(&coffre) | |
| 256 | + .arg("site.yml") | |
| 257 | + .env("ANSIBLE_CONFIG", playbooks.join("ansible.cfg")) | |
| 258 | + .env("ANSIBLE_STDOUT_CALLBACK", "open_iam") | |
| 259 | + .env("ANSIBLE_CALLBACK_PLUGINS", playbooks.join("callback_plugins")) | |
| 260 | + .env("ANSIBLE_NOCOLOR", "1") | |
| 261 | + .env("ANSIBLE_FORCE_COLOR", "0") | |
| 262 | + .env("ANSIBLE_RETRY_FILES_ENABLED", "0") | |
| 263 | + .env("PYTHONUNBUFFERED", "1") | |
| 264 | + .envs(LOCALE) | |
| 265 | + .envs(self.outils.environnement.iter().map(|(k, v)| (k, v))) | |
| 266 | + .stdin(Stdio::null()) | |
| 267 | + .stdout(Stdio::piped()) | |
| 268 | + .stderr(Stdio::piped()) | |
| 269 | + // Groupe de processus propre : l'interruption atteint aussi les processus d'Ansible. | |
| 270 | + .process_group(0); | |
| 271 | + let mut enfant = commande.spawn()?; | |
| 272 | + | |
| 273 | + let (emetteur, interrompu) = { | |
| 274 | + let mut actif = self.actif.lock().expect("verrou du runner"); | |
| 275 | + let actif = actif.as_mut().expect("exécution active"); | |
| 276 | + actif.pid = enfant.id(); | |
| 277 | + (actif.emetteur.clone(), actif.interrompu.clone()) | |
| 278 | + }; | |
| 279 | + | |
| 280 | + let (lignes_tx, mut lignes_rx) = mpsc::unbounded_channel::<(bool, String)>(); | |
| 281 | + for (sortie_standard, flux) in [ | |
| 282 | + ( | |
| 283 | + true, | |
| 284 | + Box::new(enfant.stdout.take().expect("stdout")) | |
| 285 | + as Box<dyn tokio::io::AsyncRead + Unpin + Send>, | |
| 286 | + ), | |
| 287 | + (false, Box::new(enfant.stderr.take().expect("stderr"))), | |
| 288 | + ] { | |
| 289 | + let tx = lignes_tx.clone(); | |
| 290 | + tokio::spawn(async move { | |
| 291 | + let mut lignes = BufReader::new(flux).lines(); | |
| 292 | + while let Ok(Some(ligne)) = lignes.next_line().await { | |
| 293 | + let _ = tx.send((sortie_standard, ligne)); | |
| 294 | + } | |
| 295 | + }); | |
| 296 | + } | |
| 297 | + drop(lignes_tx); | |
| 298 | + | |
| 299 | + let mut suivi = Suivi { | |
| 300 | + journal: fs::OpenOptions::new().create(true).append(true).open(dossier.join("journal.jsonl"))?, | |
| 301 | + etat, | |
| 302 | + chemin_etat: dossier.join("etat.json"), | |
| 303 | + suivant: 1, | |
| 304 | + emetteur, | |
| 305 | + masques: masques(secrets), | |
| 306 | + phases, | |
| 307 | + phase_courante: None, | |
| 308 | + faites: 0, | |
| 309 | + total: 0, | |
| 310 | + derniere_erreur: None, | |
| 311 | + }; | |
| 312 | + let actif = self.actif.clone(); | |
| 313 | + tokio::spawn(async move { | |
| 314 | + suivi.emettre(Evenement::Progression { faites: 0, total: 0 }); | |
| 315 | + let attente = enfant.wait(); | |
| 316 | + tokio::pin!(attente); | |
| 317 | + let code = loop { | |
| 318 | + tokio::select! { | |
| 319 | + ligne = lignes_rx.recv() => match ligne { | |
| 320 | + Some((sortie_standard, ligne)) => suivi.traiter(sortie_standard, &ligne), | |
| 321 | + None => break attente.await.map(|s| s.code()).unwrap_or(None), | |
| 322 | + }, | |
| 323 | + statut = &mut attente => break statut.map(|s| s.code()).unwrap_or(None), | |
| 324 | + } | |
| 325 | + }; | |
| 326 | + // Un processus resté vivant peut garder les sorties ouvertes : on ne lit le reste | |
| 327 | + // que pendant un court délai. | |
| 328 | + let _ = tokio::time::timeout(std::time::Duration::from_secs(2), async { | |
| 329 | + while let Some((sortie_standard, ligne)) = lignes_rx.recv().await { | |
| 330 | + suivi.traiter(sortie_standard, &ligne); | |
| 331 | + } | |
| 332 | + }) | |
| 333 | + .await; | |
| 334 | + let (statut, message) = if interrompu.load(Ordering::SeqCst) { | |
| 335 | + (StatutExecution::Interrompue, Some("Installation interrompue à votre demande.".to_owned())) | |
| 336 | + } else if code == Some(0) { | |
| 337 | + match finaliser(&dossier) { | |
| 338 | + Ok(()) => (StatutExecution::Reussie, None), | |
| 339 | + Err(e) => (StatutExecution::Echouee, Some(format!("Finalisation impossible : {e}"))), | |
| 340 | + } | |
| 341 | + } else { | |
| 342 | + let message = suivi.derniere_erreur.clone().unwrap_or_else(|| { | |
| 343 | + format!( | |
| 344 | + "ansible-playbook s'est arrêté avec le code {}.", | |
| 345 | + code.map_or("?".into(), |c| c.to_string()) | |
| 346 | + ) | |
| 347 | + }); | |
| 348 | + (StatutExecution::Echouee, Some(message)) | |
| 349 | + }; | |
| 350 | + suivi.terminer(statut, message); | |
| 351 | + *actif.lock().expect("verrou du runner") = None; | |
| 352 | + }); | |
| 353 | + Ok(()) | |
| 354 | + } | |
| 355 | + | |
| 356 | + /// Mot de passe du coffre ansible-vault (`vault.pass`, 0600), créé au premier usage. | |
| 357 | + fn mot_de_passe_coffre(&self) -> Result<PathBuf, ErreurRunner> { | |
| 358 | + let chemin = self.racine.join("vault.pass"); | |
| 359 | + if !chemin.is_file() { | |
| 360 | + ecrire_0600(&chemin, Secret::generer(48).exposer())?; | |
| 361 | + } | |
| 362 | + Ok(chemin) | |
| 363 | + } | |
| 364 | + | |
| 365 | + async fn preparer_inventaire( | |
| 366 | + &self, | |
| 367 | + dossier: &Path, | |
| 368 | + config: &OpenIamConfig, | |
| 369 | + secrets: &Secrets, | |
| 370 | + coffre: &Path, | |
| 371 | + ) -> Result<(), ErreurRunner> { | |
| 372 | + let vars = dossier.join("group_vars/all"); | |
| 373 | + fs::create_dir_all(&vars)?; | |
| 374 | + // M1 : installation sur ce serveur uniquement. L'installeur s'exécute en root : | |
| 375 | + // pas d'élévation de privilèges (sudo n'est pas forcément installé). | |
| 376 | + fs::write( | |
| 377 | + dossier.join("hosts.yml"), | |
| 378 | + "all:\n hosts:\n localhost:\n ansible_connection: local\n \ | |
| 379 | + ansible_python_interpreter: /usr/bin/python3\n ansible_become: false\n", | |
| 380 | + )?; | |
| 381 | + fs::write(vars.join("config.yml"), ansible::group_vars(config))?; | |
| 382 | + let secrets_yml = vars.join("secrets.yml"); | |
| 383 | + ecrire_0600(&secrets_yml, &ansible::secrets_vars(secrets))?; | |
| 384 | + let sortie = Command::new(&self.outils.ansible_vault) | |
| 385 | + .envs(LOCALE) | |
| 386 | + .arg("encrypt") | |
| 387 | + .arg("--vault-password-file") | |
| 388 | + .arg(coffre) | |
| 389 | + .arg(&secrets_yml) | |
| 390 | + .output() | |
| 391 | + .await | |
| 392 | + .map_err(|e| ErreurRunner::Coffre(e.to_string()))?; | |
| 393 | + if !sortie.status.success() { | |
| 394 | + let _ = fs::remove_file(&secrets_yml); | |
| 395 | + return Err(ErreurRunner::Coffre(String::from_utf8_lossy(&sortie.stderr).into_owned())); | |
| 396 | + } | |
| 397 | + Ok(()) | |
| 398 | + } | |
| 399 | + | |
| 400 | + /// Événements de l'exécution `id` dont l'identifiant dépasse `depuis`. | |
| 401 | + pub fn historique(&self, id: &str, depuis: u64) -> Result<Vec<(u64, Evenement)>, ErreurRunner> { | |
| 402 | + let chemin = self.dossier_execution(id).join("journal.jsonl"); | |
| 403 | + let texte = match fs::read_to_string(&chemin) { | |
| 404 | + Ok(texte) => texte, | |
| 405 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { | |
| 406 | + return if self.dossier_execution(id).is_dir() { | |
| 407 | + Ok(Vec::new()) | |
| 408 | + } else { | |
| 409 | + Err(ErreurRunner::Inconnue(id.to_owned())) | |
| 410 | + }; | |
| 411 | + } | |
| 412 | + Err(e) => return Err(e.into()), | |
| 413 | + }; | |
| 414 | + texte | |
| 415 | + .lines() | |
| 416 | + .filter(|l| !l.is_empty()) | |
| 417 | + .map(|l| serde_json::from_str::<Entree>(l).map(|e| (e.id, e.evenement)).map_err(Into::into)) | |
| 418 | + .filter(|r| r.as_ref().map_or(true, |(n, _)| *n > depuis)) | |
| 419 | + .collect() | |
| 420 | + } | |
| 421 | + | |
| 422 | + /// Abonnement aux événements de l'exécution en cours (à combiner avec [`Runner::historique`] | |
| 423 | + /// en écartant les identifiants déjà reçus). | |
| 424 | + pub fn abonner(&self) -> Option<broadcast::Receiver<(u64, Evenement)>> { | |
| 425 | + self.actif.lock().expect("verrou du runner").as_ref().map(|a| a.emetteur.subscribe()) | |
| 426 | + } | |
| 427 | + | |
| 428 | + pub fn id_en_cours(&self) -> Option<String> { | |
| 429 | + self.actif.lock().expect("verrou du runner").as_ref().map(|a| a.id.clone()) | |
| 430 | + } | |
| 431 | + | |
| 432 | + /// Demande l'arrêt d'ansible-playbook (SIGINT : il termine la tâche en cours). | |
| 433 | + pub fn interrompre(&self) -> Result<(), ErreurRunner> { | |
| 434 | + let actif = self.actif.lock().expect("verrou du runner"); | |
| 435 | + let actif = actif.as_ref().ok_or(ErreurRunner::Inactif)?; | |
| 436 | + actif.interrompu.store(true, Ordering::SeqCst); | |
| 437 | + if let Some(pid) = actif.pid { | |
| 438 | + std::process::Command::new("kill").args(["-INT", "--"]).arg(format!("-{pid}")).status()?; | |
| 439 | + } | |
| 440 | + Ok(()) | |
| 441 | + } | |
| 442 | + | |
| 443 | + /// Journal lisible (téléchargement depuis E-011), secrets déjà masqués. | |
| 444 | + pub fn journal_texte(&self, id: &str) -> Result<String, ErreurRunner> { | |
| 445 | + let mut texte = String::new(); | |
| 446 | + for (_, evenement) in self.historique(id, 0)? { | |
| 447 | + match evenement { | |
| 448 | + Evenement::Ligne { heure, hote, phase, tache, statut, message } => { | |
| 449 | + texte.push_str(&format!("{heure} {hote} {phase} › {tache} [{statut}]")); | |
| 450 | + if !message.is_empty() { | |
| 451 | + texte.push_str(&format!("\n {message}")); | |
| 452 | + } | |
| 453 | + texte.push('\n'); | |
| 454 | + } | |
| 455 | + Evenement::Brut { texte: brut } => texte.push_str(&format!(" {brut}\n")), | |
| 456 | + Evenement::Fin { statut, message } => { | |
| 457 | + texte.push_str(&format!("Fin : {statut:?} {}\n", message.unwrap_or_default())) | |
| 458 | + } | |
| 459 | + Evenement::Phase { .. } | Evenement::Progression { .. } => {} | |
| 460 | + } | |
| 461 | + } | |
| 462 | + Ok(texte) | |
| 463 | + } | |
| 464 | +} | |
| 465 | + | |
| 466 | +#[derive(Serialize, Deserialize)] | |
| 467 | +struct Entree { | |
| 468 | + id: u64, | |
| 469 | + evenement: Evenement, | |
| 470 | +} | |
| 471 | + | |
| 472 | +/// Sortie JSON du callback `ansible/callback_plugins/open_iam.py`. | |
| 473 | +#[derive(Deserialize)] | |
| 474 | +#[serde(tag = "type", rename_all = "snake_case")] | |
| 475 | +enum Sortie { | |
| 476 | + Play { taches: u32 }, | |
| 477 | + Tache { hote: String, role: String, nom: String, statut: String, message: String }, | |
| 478 | + Bilan {}, | |
| 479 | +} | |
| 480 | + | |
| 481 | +struct Suivi { | |
| 482 | + journal: fs::File, | |
| 483 | + etat: EtatExecution, | |
| 484 | + chemin_etat: PathBuf, | |
| 485 | + suivant: u64, | |
| 486 | + emetteur: broadcast::Sender<(u64, Evenement)>, | |
| 487 | + masques: Vec<String>, | |
| 488 | + phases: Vec<(&'static str, &'static str)>, | |
| 489 | + phase_courante: Option<usize>, | |
| 490 | + faites: u32, | |
| 491 | + total: u32, | |
| 492 | + derniere_erreur: Option<String>, | |
| 493 | +} | |
| 494 | + | |
| 495 | +impl Suivi { | |
| 496 | + fn emettre(&mut self, evenement: Evenement) { | |
| 497 | + let id = self.suivant; | |
| 498 | + self.suivant += 1; | |
| 499 | + if let Ok(ligne) = serde_json::to_string(&Entree { id, evenement: evenement.clone() }) { | |
| 500 | + let _ = writeln!(self.journal, "{ligne}"); | |
| 501 | + let _ = self.journal.flush(); | |
| 502 | + } | |
| 503 | + let _ = self.emetteur.send((id, evenement)); | |
| 504 | + } | |
| 505 | + | |
| 506 | + fn masquer(&self, texte: &str) -> String { | |
| 507 | + self.masques.iter().fold(texte.to_owned(), |t, secret| t.replace(secret.as_str(), "••••••")) | |
| 508 | + } | |
| 509 | + | |
| 510 | + fn traiter(&mut self, sortie_standard: bool, ligne: &str) { | |
| 511 | + let ligne = self.masquer(ligne); | |
| 512 | + let sortie = sortie_standard.then(|| serde_json::from_str::<Sortie>(&ligne).ok()).flatten(); | |
| 513 | + match sortie { | |
| 514 | + Some(Sortie::Play { taches }) => { | |
| 515 | + self.total += taches; | |
| 516 | + self.emettre(Evenement::Progression { faites: self.faites, total: self.total }); | |
| 517 | + } | |
| 518 | + Some(Sortie::Tache { hote, role, nom, statut, message }) => { | |
| 519 | + let index = | |
| 520 | + self.phases.iter().position(|(r, _)| *r == role).or(self.phase_courante).unwrap_or(0); | |
| 521 | + self.changer_de_phase(index); | |
| 522 | + let tache = nom.split_once(" : ").map_or(nom.as_str(), |(_, t)| t).to_owned(); | |
| 523 | + let phase = self.phases.get(index).map_or(role.as_str(), |(_, libelle)| libelle).to_owned(); | |
| 524 | + if statut == "failed" || statut == "unreachable" { | |
| 525 | + self.derniere_erreur = Some(format!("{phase} › {tache} ({hote}) : {message}")); | |
| 526 | + self.marquer_phase(index, EtatPhase::Echec); | |
| 527 | + } | |
| 528 | + self.faites += 1; | |
| 529 | + self.emettre(Evenement::Ligne { heure: heure(), hote, phase, tache, statut, message }); | |
| 530 | + let total = self.total.max(self.faites); | |
| 531 | + self.emettre(Evenement::Progression { faites: self.faites, total }); | |
| 532 | + } | |
| 533 | + Some(Sortie::Bilan {}) => {} | |
| 534 | + None if ligne.trim().is_empty() => {} | |
| 535 | + None => self.emettre(Evenement::Brut { texte: ligne }), | |
| 536 | + } | |
| 537 | + } | |
| 538 | + | |
| 539 | + fn changer_de_phase(&mut self, index: usize) { | |
| 540 | + if self.phase_courante == Some(index) { | |
| 541 | + return; | |
| 542 | + } | |
| 543 | + if let Some(precedente) = self.phase_courante | |
| 544 | + && self.etat.phases.get(precedente).is_some_and(|(_, e)| *e == EtatPhase::EnCours) | |
| 545 | + { | |
| 546 | + self.marquer_phase(precedente, EtatPhase::Ok); | |
| 547 | + } | |
| 548 | + self.phase_courante = Some(index); | |
| 549 | + self.marquer_phase(index, EtatPhase::EnCours); | |
| 550 | + } | |
| 551 | + | |
| 552 | + fn marquer_phase(&mut self, index: usize, etat: EtatPhase) { | |
| 553 | + let Some((libelle, actuel)) = self.etat.phases.get_mut(index) else { return }; | |
| 554 | + if *actuel == etat { | |
| 555 | + return; | |
| 556 | + } | |
| 557 | + *actuel = etat; | |
| 558 | + let phase = libelle.clone(); | |
| 559 | + let _ = ecrire_etat(&self.chemin_etat, &self.etat); | |
| 560 | + self.emettre(Evenement::Phase { phase, etat }); | |
| 561 | + } | |
| 562 | + | |
| 563 | + fn terminer(&mut self, statut: StatutExecution, message: Option<String>) { | |
| 564 | + if let Some(index) = self.phase_courante { | |
| 565 | + let etat = if statut == StatutExecution::Reussie { EtatPhase::Ok } else { EtatPhase::Echec }; | |
| 566 | + if self.etat.phases.get(index).is_some_and(|(_, e)| *e == EtatPhase::EnCours) { | |
| 567 | + self.marquer_phase(index, etat); | |
| 568 | + } | |
| 569 | + } | |
| 570 | + self.etat.statut = statut; | |
| 571 | + self.etat.fin = Some(maintenant()); | |
| 572 | + let _ = ecrire_etat(&self.chemin_etat, &self.etat); | |
| 573 | + self.emettre(Evenement::Fin { statut, message }); | |
| 574 | + } | |
| 575 | +} | |
| 576 | + | |
| 577 | +/// Valeurs à masquer dans toute sortie : les secrets de l'installation (4 caractères minimum). | |
| 578 | +fn masques(secrets: &Secrets) -> Vec<String> { | |
| 579 | + [&secrets.ldap_admin_mot_de_passe, &secrets.admin_initial_mot_de_passe, &secrets.smtp_mot_de_passe] | |
| 580 | + .into_iter() | |
| 581 | + .flatten() | |
| 582 | + .map(|s| s.exposer().to_owned()) | |
| 583 | + .filter(|s| s.chars().count() >= 4) | |
| 584 | + .collect() | |
| 585 | +} | |
| 586 | + | |
| 587 | +fn extraire_playbooks(destination: &Path) -> Result<(), ErreurRunner> { | |
| 588 | + for chemin in Playbooks::iter() { | |
| 589 | + let fichier = Playbooks::get(&chemin).expect("fichier listé par l'itérateur"); | |
| 590 | + let cible = destination.join(chemin.as_ref()); | |
| 591 | + if let Some(parent) = cible.parent() { | |
| 592 | + fs::create_dir_all(parent)?; | |
| 593 | + } | |
| 594 | + fs::write(cible, fichier.data)?; | |
| 595 | + } | |
| 596 | + Ok(()) | |
| 597 | +} | |
| 598 | + | |
| 599 | +fn lire_etat(chemin: &Path) -> Result<EtatExecution, ErreurRunner> { | |
| 600 | + Ok(serde_json::from_str(&fs::read_to_string(chemin)?)?) | |
| 601 | +} | |
| 602 | + | |
| 603 | +fn ecrire_etat(chemin: &Path, etat: &EtatExecution) -> Result<(), ErreurRunner> { | |
| 604 | + ecrire_0600(chemin, &serde_json::to_string(etat)?)?; | |
| 605 | + Ok(()) | |
| 606 | +} | |
| 607 | + | |
| 608 | +fn identifiant() -> String { | |
| 609 | + let maintenant = jiff::Zoned::now(); | |
| 610 | + format!("{}-{:03}", maintenant.strftime("%Y%m%d-%H%M%S"), maintenant.subsec_nanosecond() / 1_000_000) | |
| 611 | +} | |
| 612 | + | |
| 613 | +fn maintenant() -> String { | |
| 614 | + jiff::Zoned::now().strftime("%Y-%m-%dT%H:%M:%S%:z").to_string() | |
| 615 | +} | |
| 616 | + | |
| 617 | +fn heure() -> String { | |
| 618 | + jiff::Zoned::now().strftime("%H:%M:%S").to_string() | |
| 619 | +} |
A
installer/src/telemetrie.rs
+93
-0
@@ -0,0 +1,93 @@
| 1 | +//! Rapport de télémétrie produit (D-005, opt-in). En M1, seul l'aperçu existe (E-008) : | |
| 2 | +//! aucun envoi n'est implémenté tant que le collecteur n'existe pas (Q-02). | |
| 3 | +//! Le même code produira le rapport envoyé : l'aperçu est donc exact. | |
| 4 | + | |
| 5 | +use std::path::Path; | |
| 6 | + | |
| 7 | +use serde_json::{Value, json}; | |
| 8 | + | |
| 9 | +use crate::{brouillon::ecrire_0600, catalogue::ComposantId}; | |
| 10 | + | |
| 11 | +/// Identifiant d'instance aléatoire (UUID v4), sans lien avec le serveur, créé au premier usage. | |
| 12 | +pub fn identifiant_instance(etat: &Path) -> std::io::Result<String> { | |
| 13 | + let chemin = etat.join("instance_id"); | |
| 14 | + if let Ok(id) = std::fs::read_to_string(&chemin) { | |
| 15 | + return Ok(id.trim().to_owned()); | |
| 16 | + } | |
| 17 | + let mut octets: [u8; 16] = rand::random(); | |
| 18 | + octets[6] = (octets[6] & 0x0f) | 0x40; | |
| 19 | + octets[8] = (octets[8] & 0x3f) | 0x80; | |
| 20 | + let hex: String = octets.iter().map(|o| format!("{o:02x}")).collect(); | |
| 21 | + let id = format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32]); | |
| 22 | + ecrire_0600(&chemin, &id)?; | |
| 23 | + Ok(id) | |
| 24 | +} | |
| 25 | + | |
| 26 | +/// Famille et version majeure du système, lues dans /etc/os-release (ex. « debian 13 »). | |
| 27 | +pub fn systeme(os_release: &str) -> String { | |
| 28 | + let valeur = |cle: &str| { | |
| 29 | + os_release | |
| 30 | + .lines() | |
| 31 | + .find_map(|l| l.strip_prefix(&format!("{cle}="))) | |
| 32 | + .unwrap_or_default() | |
| 33 | + .trim_matches('"') | |
| 34 | + }; | |
| 35 | + format!("{} {}", valeur("ID"), valeur("VERSION_ID").split('.').next().unwrap_or_default()) | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// Tranche du nombre d'utilisateurs (jamais le nombre exact). | |
| 39 | +pub fn tranche(utilisateurs: usize) -> &'static str { | |
| 40 | + match utilisateurs { | |
| 41 | + 0..50 => "<50", | |
| 42 | + 50..250 => "50-250", | |
| 43 | + 250..1000 => "250-1000", | |
| 44 | + 1000..5000 => "1000-5000", | |
| 45 | + _ => ">5000", | |
| 46 | + } | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Contenu exhaustif du rapport (E-008) : aucune donnée identifiante. | |
| 50 | +pub fn rapport( | |
| 51 | + instance_id: &str, | |
| 52 | + mode: &str, | |
| 53 | + composants: &[ComposantId], | |
| 54 | + nb_hotes: usize, | |
| 55 | + utilisateurs: usize, | |
| 56 | + os: &str, | |
| 57 | +) -> Value { | |
| 58 | + json!({ | |
| 59 | + "instance_id": instance_id, | |
| 60 | + "version": env!("CARGO_PKG_VERSION"), | |
| 61 | + "mode": mode, | |
| 62 | + "composants": composants, | |
| 63 | + "nb_hotes": nb_hotes, | |
| 64 | + "tranche_utilisateurs": tranche(utilisateurs), | |
| 65 | + "os": os, | |
| 66 | + }) | |
| 67 | +} | |
| 68 | + | |
| 69 | +#[cfg(test)] | |
| 70 | +mod tests { | |
| 71 | + use super::*; | |
| 72 | + | |
| 73 | + #[test] | |
| 74 | + fn l_identifiant_est_un_uuid_v4_stable() { | |
| 75 | + let dossier = tempfile::tempdir().unwrap(); | |
| 76 | + let id = identifiant_instance(dossier.path()).unwrap(); | |
| 77 | + assert_eq!(id.len(), 36); | |
| 78 | + assert_eq!(&id[14..15], "4"); | |
| 79 | + assert_eq!(identifiant_instance(dossier.path()).unwrap(), id); | |
| 80 | + } | |
| 81 | + | |
| 82 | + #[test] | |
| 83 | + fn le_rapport_ne_contient_que_les_champs_annonces() { | |
| 84 | + let r = rapport("id", "native", &[ComposantId::Openldap], 1, 12, "debian 13"); | |
| 85 | + let cles: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect(); | |
| 86 | + assert_eq!( | |
| 87 | + cles, | |
| 88 | + ["composants", "instance_id", "mode", "nb_hotes", "os", "tranche_utilisateurs", "version"] | |
| 89 | + ); | |
| 90 | + assert_eq!(r["tranche_utilisateurs"], "<50"); | |
| 91 | + assert_eq!(systeme("ID=debian\nVERSION_ID=\"13\"\n"), "debian 13"); | |
| 92 | + } | |
| 93 | +} |
M
installer/static/app.js
+90
-1
@@ -49,8 +49,13 @@ document.addEventListener("alpine:init", () => {
| 49 | 49 | |
| 50 | 50 | // C-007 Copie du contenu d'un bloc de code. |
| 51 | 51 | Alpine.data("copie", () => ({ |
| 52 | + async copierChamp() { | |
| 53 | + await this.ecrire(this.$refs.contenu.value); | |
| 54 | + }, | |
| 52 | 55 | async copier() { |
| 53 | - const texte = this.$refs.contenu.textContent; | |
| 56 | + await this.ecrire(this.$refs.contenu.textContent); | |
| 57 | + }, | |
| 58 | + async ecrire(texte) { | |
| 54 | 59 | try { |
| 55 | 60 | await navigator.clipboard.writeText(texte); |
| 56 | 61 | notifier("success", "Copié dans le presse-papiers."); |
@@ -60,6 +65,90 @@ document.addEventListener("alpine:init", () => {
| 60 | 65 | }, |
| 61 | 66 | })); |
| 62 | 67 | |
| 68 | + // E-000 Décompte avant une nouvelle tentative d'accès (data-attente en secondes). | |
| 69 | + Alpine.data("decompte", () => ({ | |
| 70 | + restant: 0, | |
| 71 | + init() { | |
| 72 | + this.restant = Number(this.$el.dataset.attente || 0); | |
| 73 | + if (this.restant > 0) { | |
| 74 | + const minuterie = setInterval(() => { | |
| 75 | + this.restant -= 1; | |
| 76 | + if (this.restant <= 0) clearInterval(minuterie); | |
| 77 | + }, 1000); | |
| 78 | + } | |
| 79 | + }, | |
| 80 | + get bloque() { | |
| 81 | + return this.restant > 0; | |
| 82 | + }, | |
| 83 | + })); | |
| 84 | + | |
| 85 | + // E-002 Organisation : base de l'annuaire déduite du domaine et aperçu de l'arborescence. | |
| 86 | + Alpine.data("organisation", () => ({ | |
| 87 | + personnaliser: false, | |
| 88 | + base: "", | |
| 89 | + init() { | |
| 90 | + this.personnaliser = this.$el.querySelector("[name=personnaliser]")?.checked ?? false; | |
| 91 | + this.base = this.$refs.base.value; | |
| 92 | + }, | |
| 93 | + majDomaine(event) { | |
| 94 | + if (this.personnaliser) return; | |
| 95 | + const labels = event.target.value.trim().toLowerCase().replace(/\.$/, "").split(".").filter(Boolean); | |
| 96 | + this.base = labels.map((l) => `dc=${l}`).join(","); | |
| 97 | + this.$refs.base.value = this.base; | |
| 98 | + }, | |
| 99 | + get baseFigee() { | |
| 100 | + return !this.personnaliser; | |
| 101 | + }, | |
| 102 | + get apercu() { | |
| 103 | + const base = this.personnaliser ? this.$refs.base.value : this.base; | |
| 104 | + return `${base || "dc=…"}\n├── ou=users utilisateurs\n├── ou=groups groupes\n├── ou=applications comptes de service\n└── ou=ppolicies politiques de mots de passe`; | |
| 105 | + }, | |
| 106 | + })); | |
| 107 | + | |
| 108 | + // E-005 Politique de mots de passe : un préréglage remplit les champs et les fige. | |
| 109 | + const PRESETS = { | |
| 110 | + anssi: { longueur_min: 12, classes_min: 3, historique: 5, expiration_jours: 0, echecs_max: 10, verrouillage_minutes: 15 }, | |
| 111 | + renforcee: { longueur_min: 16, classes_min: 4, historique: 10, expiration_jours: 0, echecs_max: 5, verrouillage_minutes: 30 }, | |
| 112 | + }; | |
| 113 | + Alpine.data("politique", () => ({ | |
| 114 | + preset: "anssi", | |
| 115 | + init() { | |
| 116 | + this.preset = this.$el.dataset.preset || "anssi"; | |
| 117 | + }, | |
| 118 | + appliquer() { | |
| 119 | + const valeurs = PRESETS[this.preset]; | |
| 120 | + if (!valeurs) return; | |
| 121 | + for (const [cle, valeur] of Object.entries(valeurs)) { | |
| 122 | + if (this.$refs[cle]) this.$refs[cle].value = valeur; | |
| 123 | + } | |
| 124 | + }, | |
| 125 | + get fige() { | |
| 126 | + return this.preset !== "personnalisee"; | |
| 127 | + }, | |
| 128 | + })); | |
| 129 | + | |
| 130 | + // E-011 Journal : défilement automatique, suspendu quand l'utilisateur remonte. | |
| 131 | + Alpine.data("defilement", () => ({ | |
| 132 | + automatique: true, | |
| 133 | + init() { | |
| 134 | + this.$el.scrollTop = this.$el.scrollHeight; | |
| 135 | + }, | |
| 136 | + observer() { | |
| 137 | + const el = this.$el; | |
| 138 | + this.automatique = el.scrollHeight - el.scrollTop - el.clientHeight < 40; | |
| 139 | + }, | |
| 140 | + suivre() { | |
| 141 | + if (this.automatique) this.$el.scrollTop = this.$el.scrollHeight; | |
| 142 | + }, | |
| 143 | + })); | |
| 144 | + | |
| 145 | + // E-011 Barre de progression : largeur posée par le CSSOM (pas de style en ligne, CSP). | |
| 146 | + Alpine.data("largeur", () => ({ | |
| 147 | + init() { | |
| 148 | + this.$el.style.width = `${Number(this.$el.dataset.largeur || 0)}%`; | |
| 149 | + }, | |
| 150 | + })); | |
| 151 | + | |
| 63 | 152 | // C-004 Ouverture d'un <dialog> natif désigné par data-dialogue (fermeture : <form method="dialog">). |
| 64 | 153 | Alpine.data("ouvreDialogue", () => ({ |
| 65 | 154 | ouvrir() { |
A
installer/templates/assistant/acces.html
+16
-0
@@ -0,0 +1,16 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | + | |
| 3 | +{% block title %}Accès à l'installeur{% endblock %} | |
| 4 | + | |
| 5 | +{% block content %} | |
| 6 | +{# E-000 Accès par jeton (design.md : auth-card) #} | |
| 7 | +<div class="mx-auto w-full max-w-card rounded-sm bg-muted p-xl"> | |
| 8 | + <h1 class="text-2xl text-foreground">Accès à l'installeur</h1> | |
| 9 | + <p class="mt-xs text-sm text-muted-foreground">L'installeur modifie ce serveur avec les droits d'administration : son accès est protégé par un jeton à usage unique.</p> | |
| 10 | + <div class="mt-xl">{{ formulaire|safe }}</div> | |
| 11 | + <div class="mt-xl border-l-4 border-l-info bg-info-bg p-md text-sm text-foreground" role="note"> | |
| 12 | + Le jeton est affiché dans le terminal où vous avez lancé l'installeur. Pour en obtenir un nouveau : | |
| 13 | + <code class="font-mono">open-iam-installer nouveau-jeton</code> | |
| 14 | + </div> | |
| 15 | +</div> | |
| 16 | +{% endblock %} |
A
installer/templates/assistant/acces_formulaire.html
+19
-0
@@ -0,0 +1,19 @@
| 1 | +{% import "components/bouton.html" as b %} | |
| 2 | +<form id="form-acces" class="flex flex-col gap-md" hx-post="/acces" hx-target="this" hx-swap="outerHTML" | |
| 3 | + hx-disabled-elt="find button[type=submit]" novalidate x-data="decompte" data-attente="{{ attente.unwrap_or(0) }}"> | |
| 4 | + {% if let Some(erreur) = erreur %} | |
| 5 | + <div class="border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert">{{ erreur }}</div> | |
| 6 | + {% endif %} | |
| 7 | + {% if attente.is_some() %} | |
| 8 | + <p class="text-sm text-error-ink" aria-live="polite">Nouvel essai possible dans <span x-text="restant">{{ attente.unwrap_or(0) }}</span> s.</p> | |
| 9 | + {% endif %} | |
| 10 | + <div class="flex flex-col gap-xs"> | |
| 11 | + <label for="jeton" class="text-sm text-foreground">Jeton d'accès <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 12 | + <input id="jeton" name="jeton" required aria-required="true" autocomplete="off" spellcheck="false" autocapitalize="characters" | |
| 13 | + class="h-10 w-full rounded-xs border border-input bg-background px-sm font-mono text-sm text-foreground" | |
| 14 | + {% if erreur.is_some() %}aria-invalid="true" aria-describedby="erreur-acces"{% endif %}> | |
| 15 | + </div> | |
| 16 | + <div> | |
| 17 | + <button type="submit" class="{% call b::classes("default") %}{% endcall %}" :disabled="bloque" {% if attente.is_some() %}disabled{% endif %}>Accéder</button> | |
| 18 | + </div> | |
| 19 | +</form> |
A
installer/templates/assistant/bienvenue.html
+55
-0
@@ -0,0 +1,55 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | +{% import "components/bouton.html" as b %} | |
| 3 | +{% import "components/modal.html" as modal %} | |
| 4 | + | |
| 5 | +{% block title %}Installer Open IAM{% endblock %} | |
| 6 | + | |
| 7 | +{% block content %} | |
| 8 | +{# E-001 Bienvenue / reprise #} | |
| 9 | +<h1 class="text-3xl text-foreground">Installer Open IAM</h1> | |
| 10 | +<p class="mt-md max-w-3xl text-base text-muted-foreground"> | |
| 11 | + Cet assistant installe sur ce serveur un annuaire OpenLDAP (LDAP Tool Box) durci, avec ses sauvegardes chiffrées. | |
| 12 | + Les outils de libre-service, l'authentification unique et la migration depuis Active Directory arriveront dans les lots suivants. | |
| 13 | +</p> | |
| 14 | + | |
| 15 | +{% if let Some(reprise) = reprise %} | |
| 16 | +<section class="mt-xl rounded-sm border border-card-border bg-background p-xl" aria-labelledby="titre-reprise"> | |
| 17 | + <h2 id="titre-reprise" class="text-md text-title-ink">Installation en préparation pour {{ reprise.organisation }}</h2> | |
| 18 | + <p class="mt-xs text-sm text-muted-foreground">Dernière modification le {{ reprise.modifie_le }}.</p> | |
| 19 | + <div class="mt-md flex flex-wrap gap-sm"> | |
| 20 | + <a href="{{ reprise.url }}" class="{% call b::classes("default") %}{% endcall %}">Reprendre</a> | |
| 21 | + <button type="button" class="{% call b::classes("outline") %}{% endcall %}" | |
| 22 | + x-data="ouvreDialogue" data-dialogue="confirm-recommencer" x-on:click="ouvrir">Recommencer</button> | |
| 23 | + </div> | |
| 24 | + <dialog id="confirm-recommencer" role="alertdialog" aria-labelledby="confirm-recommencer-titre" | |
| 25 | + aria-describedby="confirm-recommencer-texte" class="{% call modal::classes_dialogue() %}{% endcall %}"> | |
| 26 | + {% call modal::entete("confirm-recommencer", "Supprimer le brouillon ?") %}{% endcall %} | |
| 27 | + <p id="confirm-recommencer-texte" class="mt-md text-base text-muted-foreground">Le brouillon sera supprimé, y compris les mots de passe saisis.</p> | |
| 28 | + <div class="mt-xl flex justify-end gap-sm"> | |
| 29 | + <form method="dialog"><button class="{% call b::classes("outline") %}{% endcall %}" autofocus>Annuler</button></form> | |
| 30 | + <button type="button" class="{% call b::classes("destructive") %}{% endcall %}" hx-delete="/install/brouillon" hx-swap="none">Supprimer le brouillon</button> | |
| 31 | + </div> | |
| 32 | + </dialog> | |
| 33 | +</section> | |
| 34 | +{% endif %} | |
| 35 | + | |
| 36 | +<section class="mt-xxl" aria-labelledby="titre-prerequis"> | |
| 37 | + <h2 id="titre-prerequis" class="text-lg text-foreground">Vérification du serveur</h2> | |
| 38 | + <div id="prerequis" class="mt-md" hx-get="/install/prerequis" hx-trigger="load" hx-swap="innerHTML"> | |
| 39 | + <ul class="flex flex-col gap-xs" aria-busy="true" aria-label="Vérification en cours"> | |
| 40 | + {% for _ in 0..7 %}<li class="h-8 animate-pulse rounded-xs bg-muted"></li>{% endfor %} | |
| 41 | + </ul> | |
| 42 | + </div> | |
| 43 | +</section> | |
| 44 | + | |
| 45 | +<section class="mt-xxl rounded-sm bg-muted p-md" aria-labelledby="titre-import"> | |
| 46 | + <h2 id="titre-import" class="text-md text-title-ink">Reprendre une configuration existante</h2> | |
| 47 | + <p class="mt-xs text-sm text-graphite">Importez le fichier openiam.yaml d'une installation précédente : les mots de passe seront à ressaisir.</p> | |
| 48 | + <form class="mt-md flex flex-col gap-sm" hx-post="/install/import" hx-encoding="multipart/form-data" | |
| 49 | + hx-target="#import-resultat" hx-swap="innerHTML" hx-trigger="change"> | |
| 50 | + <label for="fichier" class="text-sm text-foreground">Fichier openiam.yaml</label> | |
| 51 | + <input id="fichier" name="fichier" type="file" accept=".yaml,.yml" class="text-sm text-foreground"> | |
| 52 | + <div id="import-resultat"></div> | |
| 53 | + </form> | |
| 54 | +</section> | |
| 55 | +{% endblock %} |
A
installer/templates/assistant/champ_domaine.html
+1
-0
@@ -0,0 +1 @@
| 1 | +{% include "assistant/champ_domaine_contenu.html" %} |
A
installer/templates/assistant/champ_domaine_contenu.html
+12
-0
@@ -0,0 +1,12 @@
| 1 | +<div id="field-domaine" class="field flex flex-col gap-xs"> | |
| 2 | + <label for="domaine" class="text-sm text-foreground">Domaine DNS <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 3 | + <input id="domaine" name="domaine" value="{{ domaine }}" required aria-required="true" spellcheck="false" autocapitalize="none" | |
| 4 | + hx-post="/install/organisation/champ/domaine" hx-trigger="change" hx-target="#field-domaine" hx-swap="outerHTML" hx-select="#field-domaine" | |
| 5 | + x-on:input="majDomaine" | |
| 6 | + class="h-10 rounded-xs border bg-background px-sm font-mono text-sm text-foreground {% if erreurs.get("domaine").is_some() %}border-error{% else %}border-input{% endif %}" | |
| 7 | + aria-describedby="{% if erreurs.get("domaine").is_some() %}erreur-domaine {% endif %}{% if erreurs.avertissement("domaine").is_some() %}avert-domaine {% endif %}aide-domaine" | |
| 8 | + {% if erreurs.get("domaine").is_some() %}aria-invalid="true"{% endif %}> | |
| 9 | + {% if let Some(e) = erreurs.get("domaine") %}<p id="erreur-domaine" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 10 | + {% if let Some(e) = erreurs.avertissement("domaine") %}<p id="avert-domaine" class="text-sm text-warning">{{ e }}</p>{% endif %} | |
| 11 | + <p id="aide-domaine" class="text-sm text-muted-foreground">Par exemple mairie-exemple.fr</p> | |
| 12 | +</div> |
A
installer/templates/assistant/cibles.html
+24
-0
@@ -0,0 +1,24 @@
| 1 | +{% import "components/actions.html" as a %} | |
| 2 | +{% import "components/option_card.html" as option %} | |
| 3 | +{# E-003 Mode et cibles — M1 : paquets natifs sur ce serveur uniquement #} | |
| 4 | +<form id="form-cibles" class="flex flex-col gap-xl" hx-post="{{ action }}" hx-target="this" hx-swap="outerHTML" | |
| 5 | + hx-disabled-elt="find button[type=submit]" novalidate> | |
| 6 | + {% call a::resume(erreurs.nombre()) %}{% endcall %} | |
| 7 | + <fieldset class="flex flex-col gap-sm"> | |
| 8 | + <legend class="text-lg text-foreground">Mode d'installation</legend> | |
| 9 | + {% if let Some(e) = erreurs.get("mode") %}<p class="text-sm text-error-ink" role="alert">{{ e }}</p>{% endif %} | |
| 10 | + <div class="grid gap-md md:grid-cols-2"> | |
| 11 | + {% call option::option_card("mode", "native", "Paquets natifs", "Recommandé en production : services système, mises à jour par le gestionnaire de paquets.", true, false, "") %}{% endcall %} | |
| 12 | + {% call option::option_card("mode", "compose", "Docker Compose", "Évaluation et petites structures.", false, true, "Disponible au jalon M2") %}{% endcall %} | |
| 13 | + </div> | |
| 14 | + </fieldset> | |
| 15 | + <fieldset class="flex flex-col gap-sm"> | |
| 16 | + <legend class="text-lg text-foreground">Où installer</legend> | |
| 17 | + {% if let Some(e) = erreurs.get("topologie") %}<p class="text-sm text-error-ink" role="alert">{{ e }}</p>{% endif %} | |
| 18 | + <div class="grid gap-md md:grid-cols-2"> | |
| 19 | + {% call option::option_card("topologie", "local", "Tout sur ce serveur", "L'installeur configure la machine sur laquelle il s'exécute.", true, false, "") %}{% endcall %} | |
| 20 | + {% call option::option_card("topologie", "multi", "Plusieurs serveurs", "Répartir l'annuaire et les outils sur plusieurs machines (SSH).", false, true, "Disponible au jalon M2") %}{% endcall %} | |
| 21 | + </div> | |
| 22 | + </fieldset> | |
| 23 | + {% call a::actions(precedent) %}{% endcall %} | |
| 24 | +</form> |
A
installer/templates/assistant/composants.html
+45
-0
@@ -0,0 +1,45 @@
| 1 | +{% import "components/actions.html" as a %} | |
| 2 | +{# E-004 Composants #} | |
| 3 | +<form id="form-composants" class="grid gap-xl lg:grid-cols-3" hx-post="{{ action }}" hx-target="this" hx-swap="outerHTML" | |
| 4 | + hx-disabled-elt="find button[type=submit]" hx-disinherit="hx-disabled-elt hx-target hx-swap" novalidate> | |
| 5 | + <div class="flex flex-col gap-xl lg:col-span-2" hx-post="/install/composants/resolution" hx-trigger="change" hx-target="#form-composants" hx-swap="outerHTML" hx-include="closest form"> | |
| 6 | + {% if !erreurs.is_empty() %} | |
| 7 | + <div class="border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert"> | |
| 8 | + {% for e in erreurs %}<p>{{ e }}</p>{% endfor %} | |
| 9 | + </div> | |
| 10 | + {% endif %} | |
| 11 | + {% for groupe in groupes %} | |
| 12 | + <fieldset class="flex flex-col gap-sm"> | |
| 13 | + <legend class="text-lg text-foreground">{{ groupe.libelle }}</legend> | |
| 14 | + <div class="grid gap-md md:grid-cols-2"> | |
| 15 | + {% for c in groupe.composants %} | |
| 16 | + <label class="relative flex flex-col gap-xs rounded-sm border bg-background p-xl | |
| 17 | + {% if c.jalon.is_some() %}cursor-not-allowed border-dashed border-dashed-border{% else if c.verrouille %}border-transparent p-[23px] ring-2 ring-primary{% else %}cursor-pointer border-card-border has-checked:border-transparent has-checked:p-[23px] has-checked:ring-2 has-checked:ring-primary{% endif %} | |
| 18 | + has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring"> | |
| 19 | + <span class="flex items-start gap-sm"> | |
| 20 | + <input type="checkbox" name="composants" value="{{ c.cle }}"{% if c.jalon.is_some() || c.verrouille %} disabled{% endif %}{% if c.coche %} checked{% endif %} | |
| 21 | + class="mt-xxs size-4 shrink-0 accent-primary" aria-describedby="desc-{{ c.cle }}"> | |
| 22 | + <span class="text-md text-title-ink">{{ c.nom }}</span> | |
| 23 | + </span> | |
| 24 | + <span id="desc-{{ c.cle }}" class="pl-xl text-sm text-muted-foreground">{{ c.description }} | |
| 25 | + {% if let Some(jalon) = c.jalon %}<span class="mt-xxs block text-xs text-warning">Jalon {{ jalon }} — pas encore disponible</span>{% endif %} | |
| 26 | + {% if !c.requis_par.is_empty() %}<span class="mt-xxs block text-xs text-ink-secondary">Requis par : {{ c.requis_par }}</span>{% endif %} | |
| 27 | + {% if c.verrouille && c.requis_par.is_empty() %}<span class="mt-xxs block text-xs text-ink-secondary">Toujours installé</span>{% endif %} | |
| 28 | + </span> | |
| 29 | + </label> | |
| 30 | + {% endfor %} | |
| 31 | + </div> | |
| 32 | + </fieldset> | |
| 33 | + {% endfor %} | |
| 34 | + </div> | |
| 35 | + <aside class="lg:sticky lg:top-20 lg:self-start"> | |
| 36 | + <div class="rounded-sm bg-muted p-md text-sm text-graphite" aria-live="polite"> | |
| 37 | + <h2 class="text-md text-title-ink">Ressources estimées</h2> | |
| 38 | + <dl class="mt-sm grid grid-cols-2 gap-xs"> | |
| 39 | + <dt>Mémoire</dt><dd class="text-right tabular-nums text-foreground">{{ ram_mo }} Mo</dd> | |
| 40 | + <dt>Disque</dt><dd class="text-right tabular-nums text-foreground">{{ disque_go }} Go</dd> | |
| 41 | + </dl> | |
| 42 | + </div> | |
| 43 | + </aside> | |
| 44 | + <div class="lg:col-span-3">{% call a::actions(precedent) %}{% endcall %}</div> | |
| 45 | +</form> |
A
installer/templates/assistant/comptes.html
+47
-0
@@ -0,0 +1,47 @@
| 1 | +{% import "components/actions.html" as a %} | |
| 2 | +{% import "components/bouton.html" as b %} | |
| 3 | +{% import "components/secret.html" as secret %} | |
| 4 | +{# E-007 Comptes #} | |
| 5 | +<form id="form-comptes" class="flex flex-col gap-xxl" hx-post="{{ action }}" hx-target="this" hx-swap="outerHTML" | |
| 6 | + hx-disabled-elt="find button[type=submit]" hx-disinherit="hx-disabled-elt hx-target hx-swap" novalidate> | |
| 7 | + {% call a::resume(erreurs.nombre()) %}{% endcall %} | |
| 8 | + <fieldset class="flex flex-col gap-md"> | |
| 9 | + <legend class="text-lg text-foreground">Compte d'urgence de l'annuaire</legend> | |
| 10 | + <p class="text-sm text-muted-foreground">Super-administrateur technique, réservé aux secours : <code class="rounded-xs bg-muted p-xxs font-mono">cn=admin,{{ base_dn }}</code></p> | |
| 11 | + <div id="bloc-urgence" class="flex flex-col gap-xs"> | |
| 12 | + {% call secret::secret("urgence", "Mot de passe du compte d'urgence", urgence_defini, erreurs.get("urgence"), "20 caractères minimum. Nous vous conseillons de le générer.") %}{% endcall %} | |
| 13 | + <button type="button" class="{% call b::classes("outline") %}{% endcall %} self-start" hx-post="/install/comptes/generer" hx-target="#bloc-urgence" hx-swap="outerHTML">Générer</button> | |
| 14 | + </div> | |
| 15 | + </fieldset> | |
| 16 | + <fieldset class="flex flex-col gap-md"> | |
| 17 | + <legend class="text-lg text-foreground">Premier administrateur</legend> | |
| 18 | + <div class="grid gap-md md:grid-cols-2"> | |
| 19 | + {% for c in identite %} | |
| 20 | + <div class="field flex flex-col gap-xs"> | |
| 21 | + <label for="{{ c.cle }}" class="text-sm text-foreground">{{ c.libelle }} <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 22 | + <input id="{{ c.cle }}" name="{{ c.cle }}" value="{{ c.valeur }}" type="{{ c.type_html }}" spellcheck="false" | |
| 23 | + class="h-10 rounded-xs border bg-background px-sm text-sm text-foreground {% if erreurs.get(c.cle).is_some() %}border-error{% else %}border-input{% endif %}" | |
| 24 | + {% if let Some(e) = erreurs.get(c.cle) %}aria-invalid="true" aria-describedby="erreur-{{ c.cle }}"{% endif %}> | |
| 25 | + {% if let Some(e) = erreurs.get(c.cle) %}<p id="erreur-{{ c.cle }}" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 26 | + {% if !c.aide.is_empty() %}<p class="text-xs text-muted-foreground">{{ c.aide }}</p>{% endif %} | |
| 27 | + </div> | |
| 28 | + {% endfor %} | |
| 29 | + </div> | |
| 30 | + <fieldset class="flex flex-col gap-xs"> | |
| 31 | + <legend class="text-sm text-foreground">Définition du mot de passe</legend> | |
| 32 | + <label class="flex items-center gap-xs text-sm text-foreground"><input type="radio" name="mode_mdp" value="saisir" checked class="accent-primary"> Le saisir maintenant</label> | |
| 33 | + <label class="flex items-center gap-xs text-sm text-muted-foreground"><input type="radio" name="mode_mdp" value="lien"{% if !messagerie %} disabled{% endif %} class="accent-primary" aria-describedby="raison-lien"> Envoyer un lien d'initialisation</label> | |
| 34 | + {% if !messagerie %}<p id="raison-lien" class="pl-xl text-xs text-warning">Indisponible : aucune messagerie n'est configurée.</p>{% endif %} | |
| 35 | + {% if let Some(e) = erreurs.get("mode_mdp") %}<p class="text-sm text-error-ink" role="alert">{{ e }}</p>{% endif %} | |
| 36 | + </fieldset> | |
| 37 | + <div class="grid gap-md md:grid-cols-2" hx-post="/install/comptes/regles" hx-trigger="input from:#mot_de_passe delay:300ms" hx-target="#regles" hx-swap="outerHTML" hx-include="#mot_de_passe, #uid, #prenom, #nom"> | |
| 38 | + {% call secret::secret("mot_de_passe", "Mot de passe", admin_defini, erreurs.get("mot_de_passe"), "Il doit respecter la politique définie à l'étape Sécurité.") %}{% endcall %} | |
| 39 | + {% call secret::secret("confirmation", "Confirmation", admin_defini, erreurs.get("confirmation"), "Saisissez à nouveau le mot de passe.") %}{% endcall %} | |
| 40 | + </div> | |
| 41 | + {% include "assistant/comptes_regles.html" %} | |
| 42 | + </fieldset> | |
| 43 | + <p class="border-l-4 border-l-info bg-info-bg p-md text-sm text-foreground"> | |
| 44 | + Un compte de service en lecture seule sera créé pour chaque application, avec un mot de passe aléatoire. | |
| 45 | + </p> | |
| 46 | + {% call a::actions(precedent) %}{% endcall %} | |
| 47 | +</form> |
A
installer/templates/assistant/comptes_regles.html
+7
-0
@@ -0,0 +1,7 @@
| 1 | +<ul id="regles" class="flex flex-col gap-xxs text-sm" aria-live="polite" aria-label="Règles du mot de passe"> | |
| 2 | + {% for r in regles %} | |
| 3 | + <li class="flex items-center gap-xs {% if r.respectee %}text-success{% else %}text-muted-foreground{% endif %}"> | |
| 4 | + <span aria-hidden="true">{% if r.respectee %}✓{% else %}○{% endif %}</span>{{ r.libelle }}<span class="sr-only">{% if r.respectee %} : respectée{% else %} : non respectée{% endif %}</span> | |
| 5 | + </li> | |
| 6 | + {% endfor %} | |
| 7 | +</ul> |
A
installer/templates/assistant/comptes_urgence.html
+12
-0
@@ -0,0 +1,12 @@
| 1 | +{% import "components/bouton.html" as b %} | |
| 2 | +<div id="bloc-urgence" class="field flex flex-col gap-xs"> | |
| 3 | + <label for="urgence" class="text-sm text-foreground">Mot de passe du compte d'urgence <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 4 | + <div class="flex items-center gap-xs" x-data="copie"> | |
| 5 | + <input id="urgence" name="urgence" type="text" value="{{ valeur }}" readonly autocomplete="off" spellcheck="false" x-ref="contenu" | |
| 6 | + class="h-10 min-w-0 flex-1 rounded-xs border border-input bg-background px-sm font-mono text-sm text-foreground" aria-describedby="aide-urgence"> | |
| 7 | + <button type="button" class="{% call b::classes("icone") %}{% endcall %}" x-on:click="copierChamp" aria-label="Copier le mot de passe"><span aria-hidden="true">⧉</span></button> | |
| 8 | + </div> | |
| 9 | + <input type="hidden" name="urgence_genere" value="1"> | |
| 10 | + <p id="aide-urgence" class="text-sm text-warning">Conservez-le en lieu sûr : il sera aussi écrit dans le fichier récapitulatif de fin d'installation.</p> | |
| 11 | + <button type="button" class="{% call b::classes("outline") %}{% endcall %} self-start" hx-post="/install/comptes/generer" hx-target="#bloc-urgence" hx-swap="outerHTML">Générer un autre</button> | |
| 12 | +</div> |
A
installer/templates/assistant/etape.html
+15
-0
@@ -0,0 +1,15 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | +{% import "components/stepper.html" as stepper %} | |
| 3 | + | |
| 4 | +{% block title %}{{ titre }}{% endblock %} | |
| 5 | + | |
| 6 | +{% block organisation %}{% if let Some(nom) = organisation %}<span class="text-sm text-ink-secondary">· {{ nom }}</span>{% endif %}{% endblock %} | |
| 7 | + | |
| 8 | +{% block stepper %}{% call stepper::stepper(etapes, courante) %}{% endcall %}{% endblock %} | |
| 9 | + | |
| 10 | +{% block content %} | |
| 11 | +<h1 class="text-2xl text-foreground">{{ titre }}</h1> | |
| 12 | +<p class="mt-xs text-sm text-muted-foreground">{{ intro }}</p> | |
| 13 | +<p class="mt-xs text-xs text-muted-foreground"><span class="text-error-ink" aria-hidden="true">*</span> obligatoire</p> | |
| 14 | +<div class="mt-xl">{{ formulaire|safe }}</div> | |
| 15 | +{% endblock %} |
A
installer/templates/assistant/execution.html
+46
-0
@@ -0,0 +1,46 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | +{% import "components/bouton.html" as b %} | |
| 3 | +{% import "components/modal.html" as modal %} | |
| 4 | + | |
| 5 | +{% block title %}Installation en cours{% endblock %} | |
| 6 | + | |
| 7 | +{% block content %} | |
| 8 | +{# E-011 Installation en cours #} | |
| 9 | +<div class="flex flex-col gap-xl" hx-ext="sse" {% if en_cours %}sse-connect="/install/execution/flux" sse-close="fin"{% endif %}> | |
| 10 | + <div class="flex flex-wrap items-start justify-between gap-md"> | |
| 11 | + <div> | |
| 12 | + <h1 class="text-2xl text-foreground">Installation</h1> | |
| 13 | + <p class="mt-xs text-sm text-muted-foreground">Vous pouvez fermer cet onglet : l'installation continue et vous retrouverez l'avancement en revenant.</p> | |
| 14 | + </div> | |
| 15 | + {% if en_cours %} | |
| 16 | + <button type="button" class="{% call b::classes("destructive") %}{% endcall %}" x-data="ouvreDialogue" data-dialogue="confirm-interrompre" x-on:click="ouvrir">Interrompre</button> | |
| 17 | + <dialog id="confirm-interrompre" role="alertdialog" aria-labelledby="confirm-interrompre-titre" aria-describedby="confirm-interrompre-texte" class="{% call modal::classes_dialogue() %}{% endcall %}"> | |
| 18 | + {% call modal::entete("confirm-interrompre", "Interrompre l'installation ?") %}{% endcall %} | |
| 19 | + <p id="confirm-interrompre-texte" class="mt-md text-base text-muted-foreground">L'installation s'arrêtera après la tâche en cours. Le serveur restera dans un état partiel ; une nouvelle exécution le corrigera.</p> | |
| 20 | + <div class="mt-xl flex justify-end gap-sm"> | |
| 21 | + <form method="dialog"><button class="{% call b::classes("outline") %}{% endcall %}" autofocus>Continuer l'installation</button></form> | |
| 22 | + <button type="button" class="{% call b::classes("destructive") %}{% endcall %}" hx-post="/install/execution/interrompre" hx-swap="none">Interrompre</button> | |
| 23 | + </div> | |
| 24 | + </dialog> | |
| 25 | + {% endif %} | |
| 26 | + </div> | |
| 27 | + | |
| 28 | + <div id="progression" sse-swap="progression" hx-swap="outerHTML">{{ progression|safe }}</div> | |
| 29 | + | |
| 30 | + <div class="flex flex-col gap-xl lg:flex-row"> | |
| 31 | + <div class="lg:w-64 lg:shrink-0" sse-swap="phases" hx-target="#phases" hx-swap="outerHTML">{{ phases|safe }}</div> | |
| 32 | + <div class="min-w-0 flex-1"> | |
| 33 | + <div class="flex items-center justify-between gap-sm"> | |
| 34 | + <h2 class="text-lg text-foreground">Journal</h2> | |
| 35 | + <a href="/install/execution/journal.txt" class="text-sm text-primary underline-offset-4 hover:underline">Télécharger le journal</a> | |
| 36 | + </div> | |
| 37 | + <div role="log" aria-label="Journal de l'installation" tabindex="0" x-data="defilement" x-on:htmx:sse-message.window="suivre" x-on:scroll="observer" | |
| 38 | + class="mt-sm h-[60vh] overflow-y-auto bg-log-bg p-md font-mono text-xs text-log-fg"> | |
| 39 | + <ol id="journal" sse-swap="ligne" hx-swap="beforeend">{{ lignes|safe }}</ol> | |
| 40 | + </div> | |
| 41 | + </div> | |
| 42 | + </div> | |
| 43 | + | |
| 44 | + <div id="fin" sse-swap="fin" hx-swap="innerHTML">{% if let Some(fin) = fin %}{{ fin|safe }}{% endif %}</div> | |
| 45 | +</div> | |
| 46 | +{% endblock %} |
A
installer/templates/assistant/execution_fin.html
+25
-0
@@ -0,0 +1,25 @@
| 1 | +{% import "components/bouton.html" as b %} | |
| 2 | +{% match statut %} | |
| 3 | +{% when StatutExecution::Reussie %} | |
| 4 | +<div class="border-l-4 border-l-success bg-success-bg p-md text-sm text-foreground" role="status"> | |
| 5 | + <p>✓ Installation terminée avec succès.</p> | |
| 6 | + <a href="/install/resultat" class="mt-xs inline-block text-primary underline-offset-4 hover:underline">Voir le résultat</a> | |
| 7 | + <span hx-get="/install/execution/suite" hx-trigger="load delay:2s" hx-swap="none"></span> | |
| 8 | +</div> | |
| 9 | +{% when StatutExecution::Echouee %} | |
| 10 | +<div class="border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert"> | |
| 11 | + <p>✕ L'installation a échoué.</p> | |
| 12 | + {% if let Some(m) = message %}<p class="mt-xs whitespace-pre-wrap font-mono text-xs">{{ m }}</p>{% endif %} | |
| 13 | + <p class="mt-xs">Corrigez la cause indiquée, puis relancez : l'installation reprend sans risque, les étapes déjà faites ne sont pas refaites.</p> | |
| 14 | + <div class="mt-md flex flex-wrap gap-sm"> | |
| 15 | + <button type="button" class="{% call b::classes("default") %}{% endcall %}" hx-post="/install/execution" hx-swap="none" hx-disabled-elt="this">Relancer</button> | |
| 16 | + <a href="/install/recapitulatif" class="{% call b::classes("outline") %}{% endcall %}">Modifier la configuration</a> | |
| 17 | + </div> | |
| 18 | +</div> | |
| 19 | +{% when _ %} | |
| 20 | +<div class="border-l-4 border-l-warning bg-warning-bg p-md text-sm text-foreground" role="status"> | |
| 21 | + <p>Installation interrompue.</p> | |
| 22 | + {% if let Some(m) = message %}<p class="mt-xs">{{ m }}</p>{% endif %} | |
| 23 | + <button type="button" class="{% call b::classes("default") %}{% endcall %} mt-md" hx-post="/install/execution" hx-swap="none" hx-disabled-elt="this">Relancer</button> | |
| 24 | +</div> | |
| 25 | +{% endmatch %} |
A
installer/templates/assistant/execution_ligne.html
+9
-0
@@ -0,0 +1,9 @@
| 1 | +{% match evenement %} | |
| 2 | +{% when Evenement::Ligne { heure, hote, phase, tache, statut, message } %} | |
| 3 | +<li class="whitespace-pre-wrap {% if statut == "failed" || statut == "unreachable" %}text-log-failed{% else if statut == "changed" %}text-log-changed{% else if statut == "ok" %}text-log-ok{% endif %}"> | |
| 4 | + <span aria-hidden="true">{% if statut == "failed" || statut == "unreachable" %}✕{% else if statut == "changed" %}~{% else if statut == "skipped" %}–{% else %}✓{% endif %}</span> {{ heure }} {{ phase }} › {{ tache }}{% if statut == "skipped" %} (ignorée){% endif %}{% if !message.is_empty() %} | |
| 5 | + {{ message }}{% endif %}</li> | |
| 6 | +{% when Evenement::Brut { texte } %} | |
| 7 | +<li class="whitespace-pre-wrap text-log-fg/70" data-brut> {{ texte }}</li> | |
| 8 | +{% when _ %} | |
| 9 | +{% endmatch %} |
A
installer/templates/assistant/execution_phases.html
+6
-0
@@ -0,0 +1,6 @@
| 1 | +{% import "components/badge.html" as badge %} | |
| 2 | +<ol id="phases" class="flex flex-col gap-xs" aria-live="polite" aria-label="Étapes de l'installation"> | |
| 3 | + {% for p in phases %} | |
| 4 | + <li class="flex items-center justify-between gap-sm text-sm text-foreground">{{ p.libelle }} {% call badge::badge(p.code, p.texte) %}{% endcall %}</li> | |
| 5 | + {% endfor %} | |
| 6 | +</ol> |
A
installer/templates/assistant/execution_progression.html
+8
-0
@@ -0,0 +1,8 @@
| 1 | +<div id="progression" class="flex flex-col gap-xs"> | |
| 2 | + <div class="h-2 w-full overflow-hidden rounded-full bg-muted" role="progressbar" aria-label="Avancement de l'installation" | |
| 3 | + aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ pourcentage }}"> | |
| 4 | + <progress class="sr-only" max="100" value="{{ pourcentage }}"></progress> | |
| 5 | + <div class="h-full bg-primary transition-all" data-largeur="{{ pourcentage }}" x-data="largeur"></div> | |
| 6 | + </div> | |
| 7 | + <p class="text-xs tabular-nums text-muted-foreground">{{ pourcentage }} % — {{ faites }} tâche(s) sur {{ total }} environ</p> | |
| 8 | +</div> |
A
installer/templates/assistant/import_erreurs.html
+6
-0
@@ -0,0 +1,6 @@
| 1 | +<div class="mt-xs border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert"> | |
| 2 | + <p>Le fichier n'a pas été importé :</p> | |
| 3 | + <ul class="mt-xs list-disc pl-xl"> | |
| 4 | + {% for e in erreurs %}<li class="font-mono text-xs">{{ e }}</li>{% endfor %} | |
| 5 | + </ul> | |
| 6 | +</div> |
A
installer/templates/assistant/lancer.html
+21
-0
@@ -0,0 +1,21 @@
| 1 | +{% import "components/bouton.html" as b %} | |
| 2 | +{% import "components/modal.html" as modal %} | |
| 3 | +<div id="zone-lancer" class="flex flex-col gap-xs"{% if verification.is_some() %} hx-swap-oob="true"{% endif %}> | |
| 4 | + {% if let Some(v) = verification %}{% if v.reussie %} | |
| 5 | + <button type="button" id="lancer" class="{% call b::classes("default") %}{% endcall %} self-start" x-data="ouvreDialogue" data-dialogue="confirm-lancer" x-on:click="ouvrir">Lancer l'installation</button> | |
| 6 | + <dialog id="confirm-lancer" role="alertdialog" aria-labelledby="confirm-lancer-titre" aria-describedby="confirm-lancer-texte" class="{% call modal::classes_dialogue() %}{% endcall %}"> | |
| 7 | + {% call modal::entete("confirm-lancer", "Lancer l'installation ?") %}{% endcall %} | |
| 8 | + <p id="confirm-lancer-texte" class="mt-md text-base text-muted-foreground">Ce serveur va être modifié : installation de paquets, configuration du pare-feu, création de l'annuaire.</p> | |
| 9 | + <div class="mt-xl flex justify-end gap-sm"> | |
| 10 | + <form method="dialog"><button class="{% call b::classes("outline") %}{% endcall %}" autofocus>Annuler</button></form> | |
| 11 | + <button type="button" class="{% call b::classes("default") %}{% endcall %}" hx-post="/install/execution" hx-swap="none" hx-disabled-elt="this">Lancer</button> | |
| 12 | + </div> | |
| 13 | + </dialog> | |
| 14 | + {% else %} | |
| 15 | + <button type="button" id="lancer" class="{% call b::classes("default") %}{% endcall %} self-start" disabled aria-describedby="raison-lancer">Lancer l'installation</button> | |
| 16 | + <p id="raison-lancer" class="text-sm text-muted-foreground">Corrigez les points signalés, puis relancez la vérification.</p> | |
| 17 | + {% endif %}{% else %} | |
| 18 | + <button type="button" id="lancer" class="{% call b::classes("default") %}{% endcall %} self-start" disabled aria-describedby="raison-lancer">Lancer l'installation</button> | |
| 19 | + <p id="raison-lancer" class="text-sm text-muted-foreground">Faites d'abord la vérification préalable (elle reste valable 15 minutes).</p> | |
| 20 | + {% endif %} | |
| 21 | +</div> |
A
installer/templates/assistant/organisation.html
+66
-0
@@ -0,0 +1,66 @@
| 1 | +{% import "components/actions.html" as a %} | |
| 2 | +{# E-002 Organisation #} | |
| 3 | +<form id="form-organisation" class="grid gap-xl lg:grid-cols-3" hx-post="{{ action }}" hx-target="this" hx-swap="outerHTML" | |
| 4 | + hx-disabled-elt="find button[type=submit]" hx-disinherit="hx-disabled-elt hx-target hx-swap" novalidate x-data="organisation"> | |
| 5 | + <div class="flex flex-col gap-md lg:col-span-2"> | |
| 6 | + {% call a::resume(erreurs.nombre()) %}{% endcall %} | |
| 7 | + <div class="field flex flex-col gap-xs"> | |
| 8 | + <label for="nom" class="text-sm text-foreground">Nom de l'organisation <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 9 | + <input id="nom" name="nom" value="{{ nom }}" required aria-required="true" maxlength="100" | |
| 10 | + class="h-10 rounded-xs border bg-background px-sm text-sm text-foreground {% if erreurs.get("nom").is_some() %}border-error{% else %}border-input{% endif %}" | |
| 11 | + {% if let Some(e) = erreurs.get("nom") %}aria-invalid="true" aria-describedby="erreur-nom"{% endif %}> | |
| 12 | + {% if let Some(e) = erreurs.get("nom") %}<p id="erreur-nom" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 13 | + </div> | |
| 14 | + {% include "assistant/champ_domaine_contenu.html" %} | |
| 15 | + <div class="field flex flex-col gap-xs"> | |
| 16 | + <div class="flex items-center justify-between gap-sm"> | |
| 17 | + <label for="base_dn" class="text-sm text-foreground">Base de l'annuaire <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 18 | + <label class="flex items-center gap-xs text-sm text-muted-foreground"> | |
| 19 | + <input type="checkbox" name="personnaliser" value="1" x-model="personnaliser" {% if personnaliser %}checked{% endif %} class="size-4 accent-primary"> | |
| 20 | + Personnaliser | |
| 21 | + </label> | |
| 22 | + </div> | |
| 23 | + <input id="base_dn" name="base_dn" value="{{ base_dn }}" spellcheck="false" x-ref="base" :readonly="baseFigee" {% if !personnaliser %}readonly{% endif %} | |
| 24 | + class="h-10 rounded-xs border bg-background px-sm font-mono text-sm text-foreground read-only:border-transparent read-only:bg-muted read-only:text-muted-foreground {% if erreurs.get("base_dn").is_some() %}border-error{% else %}border-input{% endif %}" | |
| 25 | + aria-describedby="{% if erreurs.get("base_dn").is_some() %}erreur-base_dn {% endif %}aide-base_dn"> | |
| 26 | + {% if let Some(e) = erreurs.get("base_dn") %}<p id="erreur-base_dn" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 27 | + <p id="aide-base_dn" class="text-sm text-muted-foreground">Déduite du domaine. Ne la personnalisez que pour reprendre un annuaire existant.</p> | |
| 28 | + </div> | |
| 29 | + <div class="grid gap-md md:grid-cols-2"> | |
| 30 | + <div class="field flex flex-col gap-xs"> | |
| 31 | + <label for="langue" class="text-sm text-foreground">Langue des portails <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 32 | + <select id="langue" name="langue" class="h-10 rounded-xs border border-input bg-background px-sm text-sm text-foreground"> | |
| 33 | + <option value="fr" {% if langue == "fr" %}selected{% endif %}>Français</option> | |
| 34 | + <option value="en" {% if langue == "en" %}selected{% endif %}>English</option> | |
| 35 | + </select> | |
| 36 | + </div> | |
| 37 | + <div class="field flex flex-col gap-xs"> | |
| 38 | + <label for="fuseau" class="text-sm text-foreground">Fuseau horaire <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 39 | + <input id="fuseau" name="fuseau" value="{{ fuseau }}" list="fuseaux" spellcheck="false" | |
| 40 | + class="h-10 rounded-xs border bg-background px-sm text-sm text-foreground {% if erreurs.get("fuseau").is_some() %}border-error{% else %}border-input{% endif %}" | |
| 41 | + {% if let Some(e) = erreurs.get("fuseau") %}aria-invalid="true" aria-describedby="erreur-fuseau"{% endif %}> | |
| 42 | + <datalist id="fuseaux"> | |
| 43 | + <option value="Europe/Paris"></option><option value="Europe/Brussels"></option><option value="Europe/Zurich"></option> | |
| 44 | + <option value="Europe/Luxembourg"></option><option value="America/Montreal"></option><option value="Indian/Reunion"></option> | |
| 45 | + <option value="America/Guadeloupe"></option><option value="America/Martinique"></option><option value="Pacific/Noumea"></option><option value="UTC"></option> | |
| 46 | + </datalist> | |
| 47 | + {% if let Some(e) = erreurs.get("fuseau") %}<p id="erreur-fuseau" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 48 | + </div> | |
| 49 | + </div> | |
| 50 | + </div> | |
| 51 | + <aside class="flex flex-col gap-md"> | |
| 52 | + <div class="rounded-sm bg-muted p-md"> | |
| 53 | + <h2 class="text-sm text-graphite">Aperçu de l'annuaire</h2> | |
| 54 | + <pre class="mt-xs overflow-x-auto font-mono text-xs text-foreground" tabindex="0" x-text="apercu">{{ base_dn }} | |
| 55 | +├── ou=users utilisateurs | |
| 56 | +├── ou=groups groupes | |
| 57 | +├── ou=applications comptes de service | |
| 58 | +└── ou=ppolicies politiques de mots de passe</pre> | |
| 59 | + </div> | |
| 60 | + <details class="rounded-sm bg-muted p-md text-sm text-graphite"> | |
| 61 | + <summary class="cursor-pointer text-foreground">Pourquoi un domaine ?</summary> | |
| 62 | + <p class="mt-xs">Il sert de base à l'annuaire (dc=exemple,dc=fr) et aux noms des services. Utilisez de préférence un domaine que votre organisation possède ; évitez le suffixe .local.</p> | |
| 63 | + </details> | |
| 64 | + </aside> | |
| 65 | + <div class="lg:col-span-3">{% call a::actions(precedent) %}{% endcall %}</div> | |
| 66 | +</form> |
A
installer/templates/assistant/prerequis.html
+27
-0
@@ -0,0 +1,27 @@
| 1 | +{% import "components/badge.html" as badge %} | |
| 2 | +{% import "components/bouton.html" as b %} | |
| 3 | +<ul class="flex flex-col border-t border-border"> | |
| 4 | + {% for c in controles %} | |
| 5 | + <li class="flex flex-col gap-xxs border-b border-border py-sm" data-controle="{{ c.cle }}"> | |
| 6 | + <div class="flex flex-wrap items-center gap-sm"> | |
| 7 | + {% call badge::badge(c.niveau.badge(), c.libelle) %}{% endcall %} | |
| 8 | + </div> | |
| 9 | + <p class="pl-xs text-sm text-muted-foreground">{{ c.detail }}</p> | |
| 10 | + </li> | |
| 11 | + {% endfor %} | |
| 12 | +</ul> | |
| 13 | +{% if let Some(message) = message %} | |
| 14 | +<div class="mt-md border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert">{{ message }}</div> | |
| 15 | +{% endif %} | |
| 16 | +<div class="mt-xl flex flex-wrap gap-sm"> | |
| 17 | + <button type="button" class="{% call b::classes("outline") %}{% endcall %}" hx-get="/install/prerequis" hx-target="#prerequis" hx-swap="innerHTML">Revérifier</button> | |
| 18 | + {% if ansible_absent %} | |
| 19 | + <button type="button" class="{% call b::classes("outline") %}{% endcall %}" hx-post="/install/prerequis/ansible" hx-target="#prerequis" hx-swap="innerHTML" hx-disabled-elt="this">Installer Ansible</button> | |
| 20 | + {% endif %} | |
| 21 | + {% if bloquant %} | |
| 22 | + <button type="button" class="{% call b::classes("default") %}{% endcall %}" disabled aria-describedby="raison-commencer">Commencer</button> | |
| 23 | + <p id="raison-commencer" class="w-full text-sm text-error-ink">Corrigez d'abord les points bloquants ci-dessus.</p> | |
| 24 | + {% else %} | |
| 25 | + <button type="button" class="{% call b::classes("default") %}{% endcall %}" hx-post="/install/commencer" hx-swap="none">Commencer</button> | |
| 26 | + {% endif %} | |
| 27 | +</div> |
A
installer/templates/assistant/recapitulatif.html
+55
-0
@@ -0,0 +1,55 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | +{% import "components/stepper.html" as stepper %} | |
| 3 | +{% import "components/bouton.html" as b %} | |
| 4 | + | |
| 5 | +{% block title %}Récapitulatif{% endblock %} | |
| 6 | +{% block organisation %}{% if let Some(nom) = organisation %}<span class="text-sm text-ink-secondary">· {{ nom }}</span>{% endif %}{% endblock %} | |
| 7 | +{% block stepper %}{% call stepper::stepper(etapes, courante) %}{% endcall %}{% endblock %} | |
| 8 | + | |
| 9 | +{% block content %} | |
| 10 | +{# E-010 Récapitulatif #} | |
| 11 | +<h1 class="text-2xl text-foreground">Récapitulatif</h1> | |
| 12 | +<p class="mt-xs text-sm text-muted-foreground">Relisez vos choix. L'installation modifiera réellement ce serveur.</p> | |
| 13 | + | |
| 14 | +{% if !avertissements.is_empty() %} | |
| 15 | +<ul class="mt-xl flex flex-col gap-xs"> | |
| 16 | + {% for a in avertissements %}<li class="border-l-4 border-l-warning bg-warning-bg p-md text-sm text-foreground">{{ a }}</li>{% endfor %} | |
| 17 | +</ul> | |
| 18 | +{% endif %} | |
| 19 | + | |
| 20 | +<div class="mt-xl grid gap-md md:grid-cols-2"> | |
| 21 | + {% for carte in cartes %} | |
| 22 | + <section class="border border-border bg-card p-xl" aria-labelledby="carte-{{ loop.index }}"> | |
| 23 | + <div class="flex items-start justify-between gap-sm"> | |
| 24 | + <h2 id="carte-{{ loop.index }}" class="text-md text-title-ink">{{ carte.titre }}</h2> | |
| 25 | + <a href="{{ carte.url }}" class="text-sm text-primary underline-offset-4 hover:underline">Modifier<span class="sr-only"> : {{ carte.titre }}</span></a> | |
| 26 | + </div> | |
| 27 | + <dl class="mt-sm flex flex-col gap-xxs text-sm"> | |
| 28 | + {% for (cle, valeur) in carte.lignes %} | |
| 29 | + <div class="flex flex-wrap gap-x-sm"><dt class="text-muted-foreground">{{ cle }}</dt><dd class="font-mono text-foreground">{{ valeur }}</dd></div> | |
| 30 | + {% endfor %} | |
| 31 | + </dl> | |
| 32 | + </section> | |
| 33 | + {% endfor %} | |
| 34 | +</div> | |
| 35 | + | |
| 36 | +<section class="mt-xxl" aria-labelledby="titre-plan"> | |
| 37 | + <h2 id="titre-plan" class="text-lg text-foreground">Plan d'exécution</h2> | |
| 38 | + <div class="mt-md overflow-x-auto" tabindex="0" aria-label="Plan d'exécution"> | |
| 39 | + <table class="w-full text-sm"> | |
| 40 | + <thead class="bg-muted text-left text-xs text-muted-foreground"><tr><th class="px-md py-sm">Serveur</th><th class="px-md py-sm">Étapes appliquées, dans l'ordre</th></tr></thead> | |
| 41 | + <tbody><tr class="border-b border-border"><td class="px-md py-sm">Ce serveur</td><td class="px-md py-sm">{{ phases|join(" → ") }}</td></tr></tbody> | |
| 42 | + </table> | |
| 43 | + </div> | |
| 44 | +</section> | |
| 45 | + | |
| 46 | +<section class="mt-xxl flex flex-col gap-md" aria-labelledby="titre-verification"> | |
| 47 | + <h2 id="titre-verification" class="text-lg text-foreground">Vérification préalable</h2> | |
| 48 | + <div class="flex flex-wrap gap-sm"> | |
| 49 | + <button type="button" class="{% call b::classes("outline") %}{% endcall %}" hx-post="/install/verification" hx-target="#resultat-verification" hx-swap="innerHTML" hx-disabled-elt="this">Lancer la vérification</button> | |
| 50 | + <a href="/install/openiam.yaml" class="{% call b::classes("outline") %}{% endcall %}">Télécharger openiam.yaml</a> | |
| 51 | + </div> | |
| 52 | + <div id="resultat-verification" aria-live="polite"></div> | |
| 53 | + {% include "assistant/lancer.html" %} | |
| 54 | +</section> | |
| 55 | +{% endblock %} |
A
installer/templates/assistant/resultat.html
+53
-0
@@ -0,0 +1,53 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | +{% import "components/badge.html" as badge %} | |
| 3 | +{% import "components/bouton.html" as b %} | |
| 4 | +{% import "components/code.html" as code %} | |
| 5 | + | |
| 6 | +{% block title %}Installation terminée{% endblock %} | |
| 7 | + | |
| 8 | +{% block content %} | |
| 9 | +{# E-012 Résultat #} | |
| 10 | +<div class="border-l-4 border-l-success bg-success-bg p-md"> | |
| 11 | + <h1 class="text-lg text-foreground">Open IAM est installé</h1> | |
| 12 | + {% if !duree.is_empty() %}<p class="text-sm text-muted-foreground">Durée de l'installation : {{ duree }}.</p>{% endif %} | |
| 13 | +</div> | |
| 14 | + | |
| 15 | +<section class="mt-xxl" aria-labelledby="titre-services"> | |
| 16 | + <h2 id="titre-services" class="text-lg text-foreground">Services</h2> | |
| 17 | + <div class="mt-md overflow-x-auto" tabindex="0" aria-label="Tableau des services"> | |
| 18 | + <table class="w-full text-sm"> | |
| 19 | + <thead class="bg-muted text-left text-xs text-muted-foreground"><tr><th class="px-md py-sm">Service</th><th class="px-md py-sm">Adresse</th><th class="px-md py-sm">État</th></tr></thead> | |
| 20 | + <tbody> | |
| 21 | + {% for s in services %} | |
| 22 | + <tr class="border-b border-border"><td class="px-md py-sm">{{ s.libelle }}</td><td class="px-md py-sm font-mono">{{ s.adresse }}</td> | |
| 23 | + <td class="px-md py-sm">{% if s.ok %}{% call badge::badge("ok", "Répond") %}{% endcall %}{% else %}{% call badge::badge("erreur", "Ne répond pas") %}{% endcall %}{% endif %}</td></tr> | |
| 24 | + {% endfor %} | |
| 25 | + </tbody> | |
| 26 | + </table> | |
| 27 | + </div> | |
| 28 | +</section> | |
| 29 | + | |
| 30 | +<section class="mt-xxl border border-warning bg-warning-bg p-xl" aria-labelledby="titre-identifiants"> | |
| 31 | + <h2 id="titre-identifiants" class="text-lg text-foreground">Identifiants et fichier récapitulatif</h2> | |
| 32 | + {% if let Some(urgence) = urgence %} | |
| 33 | + <p class="mt-sm text-sm text-foreground">Mot de passe généré pour le compte d'urgence de l'annuaire (affiché une seule fois) :</p> | |
| 34 | + <div class="mt-xs">{% call code::code("secret-urgence", urgence, "le mot de passe d'urgence") %}{% endcall %}</div> | |
| 35 | + {% endif %} | |
| 36 | + <p class="mt-md text-sm text-foreground">Le fichier récapitulatif (adresses, mots de passe, clé des sauvegardes, configuration) a été écrit sur le serveur :</p> | |
| 37 | + <div class="mt-xs">{% call code::code("chemin-recapitulatif", recapitulatif, "le chemin du fichier") %}{% endcall %}</div> | |
| 38 | + <p class="mt-xs text-sm text-warning">Il contient des mots de passe : copiez-le en lieu sûr, puis supprimez-le du serveur.</p> | |
| 39 | + <div class="mt-md flex flex-wrap gap-sm"> | |
| 40 | + <a href="/install/resultat/recapitulatif.txt" class="{% call b::classes("outline") %}{% endcall %}">Télécharger le récapitulatif</a> | |
| 41 | + {% if ca %}<a href="/install/resultat/ca.crt" class="{% call b::classes("outline") %}{% endcall %}">Certificat de l'autorité interne</a>{% endif %} | |
| 42 | + </div> | |
| 43 | +</section> | |
| 44 | + | |
| 45 | +<form class="mt-xxl flex flex-col gap-md" hx-post="/install/terminer" hx-swap="none" x-data="{}"> | |
| 46 | + <label class="flex items-start gap-sm text-base text-foreground"> | |
| 47 | + <input type="checkbox" name="conserve" value="on" required class="mt-xxs size-5 shrink-0 accent-primary"> | |
| 48 | + J'ai conservé le fichier récapitulatif et les identifiants en lieu sûr. | |
| 49 | + </label> | |
| 50 | + <button type="submit" class="{% call b::classes("default") %}{% endcall %} self-start">Terminer</button> | |
| 51 | + <p class="text-sm text-muted-foreground">La console d'administration arrive au jalon M3. Après « Terminer », l'assistant est verrouillé.</p> | |
| 52 | +</form> | |
| 53 | +{% endblock %} |
A
installer/templates/assistant/securite.html
+55
-0
@@ -0,0 +1,55 @@
| 1 | +{% import "components/actions.html" as a %} | |
| 2 | +{% import "components/option_card.html" as option %} | |
| 3 | +{# E-005 Sécurité — M1 : autorité interne ; ACME et certificats fournis au jalon M2 #} | |
| 4 | +<form id="form-securite" class="flex flex-col gap-xxl" hx-post="{{ action }}" hx-target="this" hx-swap="outerHTML" | |
| 5 | + hx-disabled-elt="find button[type=submit]" novalidate x-data="politique" data-preset="{{ preset }}"> | |
| 6 | + {% call a::resume(erreurs.nombre()) %}{% endcall %} | |
| 7 | + <fieldset class="flex flex-col gap-md"> | |
| 8 | + <legend class="text-lg text-foreground">Noms des services</legend> | |
| 9 | + {% for s in services %} | |
| 10 | + <div class="field flex flex-col gap-xs"> | |
| 11 | + <label for="{{ s.cle }}" class="text-sm text-foreground">{{ s.libelle }} <span class="text-error-ink" aria-hidden="true">*</span></label> | |
| 12 | + <input id="{{ s.cle }}" name="{{ s.cle }}" value="{{ s.nom }}" spellcheck="false" autocapitalize="none" | |
| 13 | + class="h-10 rounded-xs border bg-background px-sm font-mono text-sm text-foreground {% if erreurs.get(s.cle).is_some() %}border-error{% else %}border-input{% endif %}" | |
| 14 | + {% if let Some(e) = erreurs.get(s.cle) %}aria-invalid="true" aria-describedby="erreur-{{ s.cle }}"{% endif %}> | |
| 15 | + {% if let Some(e) = erreurs.get(s.cle) %}<p id="erreur-{{ s.cle }}" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 16 | + </div> | |
| 17 | + {% endfor %} | |
| 18 | + </fieldset> | |
| 19 | + <fieldset class="flex flex-col gap-sm"> | |
| 20 | + <legend class="text-lg text-foreground">Certificats</legend> | |
| 21 | + {% if let Some(e) = erreurs.get("tls") %}<p class="text-sm text-error-ink" role="alert">{{ e }}</p>{% endif %} | |
| 22 | + <div class="grid gap-md md:grid-cols-3"> | |
| 23 | + {% call option::option_card("tls", "interne", "Autorité interne", "Une autorité de certification propre à votre installation.", true, false, "") %}{% endcall %} | |
| 24 | + {% call option::option_card("tls", "acme", "Let's Encrypt", "Certificats publics renouvelés automatiquement.", false, true, "Disponible au jalon M2") %}{% endcall %} | |
| 25 | + {% call option::option_card("tls", "fourni", "Certificats fournis", "Vos propres certificats.", false, true, "Disponible au jalon M2") %}{% endcall %} | |
| 26 | + </div> | |
| 27 | + <p class="border-l-4 border-l-warning bg-warning-bg p-md text-sm text-foreground"> | |
| 28 | + Les navigateurs et les applications devront faire confiance au certificat de l'autorité interne, téléchargeable en fin d'installation. | |
| 29 | + </p> | |
| 30 | + </fieldset> | |
| 31 | + <fieldset class="flex flex-col gap-md"> | |
| 32 | + <legend class="text-lg text-foreground">Politique de mots de passe</legend> | |
| 33 | + <div class="field flex flex-col gap-xs md:max-w-sm"> | |
| 34 | + <label for="preset" class="text-sm text-foreground">Préréglage</label> | |
| 35 | + <select id="preset" name="preset" x-model="preset" x-on:change="appliquer" class="h-10 rounded-xs border border-input bg-background px-sm text-sm text-foreground"> | |
| 36 | + <option value="anssi" {% if preset == "anssi" %}selected{% endif %}>Recommandations ANSSI (recommandé)</option> | |
| 37 | + <option value="renforcee" {% if preset == "renforcee" %}selected{% endif %}>Renforcée</option> | |
| 38 | + <option value="personnalisee" {% if preset == "personnalisee" %}selected{% endif %}>Personnalisée</option> | |
| 39 | + </select> | |
| 40 | + </div> | |
| 41 | + <div class="grid gap-md md:grid-cols-2 lg:grid-cols-3"> | |
| 42 | + {% for c in champs %} | |
| 43 | + <div class="field flex flex-col gap-xs"> | |
| 44 | + <label for="{{ c.cle }}" class="text-sm text-foreground">{{ c.libelle }}</label> | |
| 45 | + <input id="{{ c.cle }}" name="{{ c.cle }}" type="number" inputmode="numeric" value="{{ c.valeur }}" x-ref="{{ c.cle }}" :readonly="fige"{% if preset != "personnalisee" %} readonly{% endif %} | |
| 46 | + class="h-10 rounded-xs border bg-background px-sm text-sm tabular-nums text-foreground read-only:border-transparent read-only:bg-muted {% if erreurs.get(c.cle).is_some() %}border-error{% else %}border-input{% endif %}" | |
| 47 | + aria-describedby="{% if erreurs.get(c.cle).is_some() %}erreur-{{ c.cle }} {% endif %}aide-{{ c.cle }}"> | |
| 48 | + {% if let Some(e) = erreurs.get(c.cle) %}<p id="erreur-{{ c.cle }}" class="text-sm text-error-ink">{{ e }}</p>{% endif %} | |
| 49 | + <p id="aide-{{ c.cle }}" class="text-xs text-muted-foreground">{{ c.aide }}</p> | |
| 50 | + </div> | |
| 51 | + {% endfor %} | |
| 52 | + </div> | |
| 53 | + </fieldset> | |
| 54 | + {% call a::actions(precedent) %}{% endcall %} | |
| 55 | +</form> |
A
installer/templates/assistant/telemetrie.html
+28
-0
@@ -0,0 +1,28 @@
| 1 | +{% import "components/actions.html" as a %} | |
| 2 | +{# E-008 Supervision et télémétrie — la supervision locale arrive avec son composant (M2) #} | |
| 3 | +<form id="form-telemetrie" class="flex flex-col gap-xl" hx-post="{{ action }}" hx-target="this" hx-swap="outerHTML" | |
| 4 | + hx-disabled-elt="find button[type=submit]" novalidate> | |
| 5 | + <fieldset class="flex flex-col gap-md"> | |
| 6 | + <legend class="text-lg text-foreground">Télémétrie produit</legend> | |
| 7 | + <label class="flex items-start gap-sm text-base text-foreground"> | |
| 8 | + <input type="checkbox" name="telemetrie" value="on"{% if active %} checked{% endif %} class="mt-xxs size-5 shrink-0 accent-primary"> | |
| 9 | + <span>Envoyer chaque semaine un rapport anonyme d'utilisation aux mainteneurs d'Open IAM | |
| 10 | + <span class="block text-sm text-muted-foreground">Facultatif, désactivé par défaut, modifiable plus tard. Aucun envoi n'a lieu pendant l'installation.</span></span> | |
| 11 | + </label> | |
| 12 | + <div class="grid gap-md md:grid-cols-2"> | |
| 13 | + <div class="rounded-sm bg-muted p-md text-sm text-graphite"> | |
| 14 | + <h2 class="text-sm text-title-ink">Envoyé</h2> | |
| 15 | + <ul class="mt-xs list-disc pl-xl"><li>Identifiant d'instance aléatoire</li><li>Version et mode d'installation</li><li>Composants installés, nombre de serveurs</li><li>Tranche du nombre d'utilisateurs</li><li>Famille et version du système</li></ul> | |
| 16 | + </div> | |
| 17 | + <div class="rounded-sm bg-muted p-md text-sm text-graphite"> | |
| 18 | + <h2 class="text-sm text-title-ink">Jamais envoyé</h2> | |
| 19 | + <ul class="mt-xs list-disc pl-xl"><li>Noms, domaine, DN</li><li>Adresses IP et e-mails</li><li>Contenu de l'annuaire</li><li>Journaux</li></ul> | |
| 20 | + </div> | |
| 21 | + </div> | |
| 22 | + <div> | |
| 23 | + <h2 class="text-sm text-foreground">Contenu exact du rapport</h2> | |
| 24 | + <pre class="mt-xs max-h-64 overflow-auto rounded-sm bg-muted p-md font-mono text-xs text-foreground" tabindex="0">{{ apercu }}</pre> | |
| 25 | + </div> | |
| 26 | + </fieldset> | |
| 27 | + {% call a::actions(precedent) %}{% endcall %} | |
| 28 | +</form> |
A
installer/templates/assistant/verification.html
+13
-0
@@ -0,0 +1,13 @@
| 1 | +{% import "components/badge.html" as badge %} | |
| 2 | +<ul class="flex flex-col border-t border-border"> | |
| 3 | + {% for c in controles %} | |
| 4 | + <li class="flex flex-col gap-xxs border-b border-border py-sm"> | |
| 5 | + {% call badge::badge(c.niveau.badge(), c.libelle) %}{% endcall %} | |
| 6 | + <p class="pl-xs text-sm text-muted-foreground">{{ c.detail }}</p> | |
| 7 | + </li> | |
| 8 | + {% endfor %} | |
| 9 | +</ul> | |
| 10 | +{% for m in manques %}<p class="mt-xs border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert">{{ m }}</p>{% endfor %} | |
| 11 | +{% if reussie %}<p class="mt-md text-sm text-success">✓ Vérification réussie : vous pouvez lancer l'installation.</p>{% endif %} | |
| 12 | +{% let verification = Some(self) %} | |
| 13 | +{% include "assistant/lancer.html" %} |
A
installer/templates/assistant/verrouille.html
+18
-0
@@ -0,0 +1,18 @@
| 1 | +{% extends "layouts/assistant.html" %} | |
| 2 | + | |
| 3 | +{% block title %}Plateforme installée{% endblock %} | |
| 4 | + | |
| 5 | +{% block content %} | |
| 6 | +{# E-092 Assistant verrouillé #} | |
| 7 | +<div class="rounded-sm bg-muted p-huge"> | |
| 8 | + <h1 class="text-2xl text-foreground">La plateforme est déjà installée</h1> | |
| 9 | + <p class="mt-md text-base text-muted-foreground"> | |
| 10 | + L'assistant d'installation est verrouillé pour éviter toute réinstallation accidentelle. | |
| 11 | + La console d'administration, qui permettra de faire évoluer la plateforme, arrive au jalon M3. | |
| 12 | + </p> | |
| 13 | + <p class="mt-md text-sm text-muted-foreground"> | |
| 14 | + Le fichier récapitulatif de l'installation (adresses, identifiants générés, configuration) se trouve dans | |
| 15 | + <code class="font-mono">~/open-iam/</code> sur le serveur. | |
| 16 | + </p> | |
| 17 | +</div> | |
| 18 | +{% endblock %} |
A
installer/templates/components/actions.html
+16
-0
@@ -0,0 +1,16 @@
| 1 | +{# C-012 Barre d'actions de l'étape : collée en bas sur mobile (design.md : action-bar). #} | |
| 2 | +{% import "components/bouton.html" as b %} | |
| 3 | +{% macro actions(precedent) %} | |
| 4 | +<div class="sticky bottom-0 -mx-md mt-xxl flex flex-col-reverse gap-sm border-t border-border bg-background p-md shadow-float sm:static sm:mx-0 sm:flex-row sm:justify-end sm:border-0 sm:p-0 sm:shadow-none"> | |
| 5 | + <a href="{{ precedent }}" class="{% call b::classes("outline") %}{% endcall %} w-full sm:w-auto">Précédent</a> | |
| 6 | + <button type="submit" class="{% call b::classes("default") %}{% endcall %} w-full sm:w-auto">Enregistrer et continuer</button> | |
| 7 | +</div> | |
| 8 | +{% endmacro %} | |
| 9 | + | |
| 10 | +{% macro resume(nombre) %} | |
| 11 | +{% if nombre > 0 %} | |
| 12 | +<div class="border-l-4 border-l-error bg-error-bg p-md text-sm text-foreground" role="alert" tabindex="-1" autofocus> | |
| 13 | + {% if nombre == 1 %}Le formulaire contient une erreur{% else %}Le formulaire contient {{ nombre }} erreurs{% endif %} : corrigez les champs signalés. | |
| 14 | +</div> | |
| 15 | +{% endif %} | |
| 16 | +{% endmacro %} |
D
installer/templates/pages/accueil.html
+0
-10
@@ -1,10 +0,0 @@
| 1 | -{% extends "layouts/assistant.html" %} | |
| 2 | - | |
| 3 | -{% block title %}Installer Open IAM{% endblock %} | |
| 4 | - | |
| 5 | -{% block content %} | |
| 6 | -<h1 class="text-3xl text-foreground">Installer Open IAM</h1> | |
| 7 | -<p class="mt-md text-base text-muted-foreground"> | |
| 8 | - L'assistant d'installation arrive au jalon M1. Cette page vérifie le socle : thème, sécurité et notifications. | |
| 9 | -</p> | |
| 10 | -{% endblock %} |
A
installer/tests/acces.rs
+126
-0
@@ -0,0 +1,126 @@
| 1 | +//! OI-023 — E-000 accès par jeton, garde de l'assistant, E-092 assistant verrouillé. | |
| 2 | + | |
| 3 | +mod commun; | |
| 4 | + | |
| 5 | +use axum::http::StatusCode; | |
| 6 | +use commun::*; | |
| 7 | + | |
| 8 | +#[tokio::test] | |
| 9 | +async fn l_assistant_exige_le_jeton() { | |
| 10 | + let banc = banc(); | |
| 11 | + let (res, _) = send(&banc.router, get("/install")).await; | |
| 12 | + assert_eq!(res.status(), StatusCode::SEE_OTHER); | |
| 13 | + assert_eq!(header(&res, "location"), "/acces"); | |
| 14 | +} | |
| 15 | + | |
| 16 | +#[tokio::test] | |
| 17 | +async fn une_requete_htmx_sans_acces_est_redirigee_par_hx_redirect() { | |
| 18 | + let banc = banc(); | |
| 19 | + let mut req = get("/install/organisation"); | |
| 20 | + req.headers_mut().insert("hx-request", "true".parse().unwrap()); | |
| 21 | + let (res, _) = send(&banc.router, req).await; | |
| 22 | + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); | |
| 23 | + assert_eq!(header(&res, "hx-redirect"), "/acces"); | |
| 24 | +} | |
| 25 | + | |
| 26 | +#[tokio::test] | |
| 27 | +async fn l_url_avec_jeton_ouvre_l_assistant_et_retire_le_jeton_de_l_url() { | |
| 28 | + let banc = banc(); | |
| 29 | + let (cookie, _) = session(&banc.router).await; | |
| 30 | + let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 31 | + let (res, _) = send(&banc.router, get_avec(&format!("/acces?jeton={jeton}"), &cookie)).await; | |
| 32 | + assert_eq!(res.status(), StatusCode::SEE_OTHER); | |
| 33 | + assert_eq!(header(&res, "location"), "/install"); | |
| 34 | + let cookie = nouveau_cookie(&res).expect("nouvel identifiant de session après l'accès"); | |
| 35 | + | |
| 36 | + let (res, _) = send(&banc.router, get_avec("/install", &cookie)).await; | |
| 37 | + assert_eq!(res.status(), StatusCode::OK); | |
| 38 | +} | |
| 39 | + | |
| 40 | +#[tokio::test] | |
| 41 | +async fn un_jeton_est_a_usage_unique() { | |
| 42 | + let banc = banc(); | |
| 43 | + let (cookie, _) = session(&banc.router).await; | |
| 44 | + let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 45 | + send(&banc.router, get_avec(&format!("/acces?jeton={jeton}"), &cookie)).await; | |
| 46 | + | |
| 47 | + let (autre, _) = session(&banc.router).await; | |
| 48 | + let (res, body) = send(&banc.router, get_avec(&format!("/acces?jeton={jeton}"), &autre)).await; | |
| 49 | + assert_eq!(res.status(), StatusCode::OK); | |
| 50 | + assert!(body.contains("plus valide"), "{body}"); | |
| 51 | +} | |
| 52 | + | |
| 53 | +#[tokio::test] | |
| 54 | +async fn un_jeton_saisi_invalide_renvoie_422() { | |
| 55 | + let banc = banc(); | |
| 56 | + open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 57 | + let (cookie, csrf) = session(&banc.router).await; | |
| 58 | + let (res, body) = send(&banc.router, post_form("/acces", &cookie, Some(&csrf), "jeton=FAUX")).await; | |
| 59 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 60 | + assert!(body.contains("plus valide")); | |
| 61 | +} | |
| 62 | + | |
| 63 | +#[tokio::test] | |
| 64 | +async fn cinq_echecs_bloquent_les_tentatives() { | |
| 65 | + let banc = banc(); | |
| 66 | + let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 67 | + let (cookie, csrf) = session(&banc.router).await; | |
| 68 | + for _ in 0..5 { | |
| 69 | + send(&banc.router, post_form("/acces", &cookie, Some(&csrf), "jeton=FAUX")).await; | |
| 70 | + } | |
| 71 | + let (res, body) = | |
| 72 | + send(&banc.router, post_form("/acces", &cookie, Some(&csrf), &format!("jeton={jeton}"))).await; | |
| 73 | + assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS); | |
| 74 | + assert!(body.contains("Trop de tentatives")); | |
| 75 | +} | |
| 76 | + | |
| 77 | +#[tokio::test] | |
| 78 | +async fn un_jeton_expire_est_refuse() { | |
| 79 | + let banc = banc(); | |
| 80 | + let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 81 | + open_iam_installer::acces::vieillir(&banc.etat_dir(), 31 * 60).unwrap(); | |
| 82 | + let (cookie, csrf) = session(&banc.router).await; | |
| 83 | + let (res, _) = | |
| 84 | + send(&banc.router, post_form("/acces", &cookie, Some(&csrf), &format!("jeton={jeton}"))).await; | |
| 85 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 86 | +} | |
| 87 | + | |
| 88 | +#[tokio::test] | |
| 89 | +async fn le_fichier_de_jeton_est_protege() { | |
| 90 | + use std::os::unix::fs::PermissionsExt; | |
| 91 | + let banc = banc(); | |
| 92 | + open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 93 | + let mode = std::fs::metadata(banc.etat_dir().join("jeton")).unwrap().permissions().mode() & 0o777; | |
| 94 | + assert_eq!(mode, 0o600); | |
| 95 | +} | |
| 96 | + | |
| 97 | +#[tokio::test] | |
| 98 | +async fn apres_installation_l_assistant_est_verrouille() { | |
| 99 | + let banc = banc(); | |
| 100 | + std::fs::write(banc.etat_dir().join("installed.lock"), "").unwrap(); | |
| 101 | + for chemin in ["/install", "/install/organisation", "/acces"] { | |
| 102 | + let (res, _) = send(&banc.router, get(chemin)).await; | |
| 103 | + assert_eq!(res.status(), StatusCode::SEE_OTHER, "{chemin}"); | |
| 104 | + assert_eq!(header(&res, "location"), "/verrouille", "{chemin}"); | |
| 105 | + } | |
| 106 | + let (res, body) = send(&banc.router, get("/verrouille")).await; | |
| 107 | + assert_eq!(res.status(), StatusCode::OK); | |
| 108 | + assert!(body.contains("déjà installée"), "{body}"); | |
| 109 | +} | |
| 110 | + | |
| 111 | +#[tokio::test] | |
| 112 | +async fn la_racine_mene_a_l_assistant() { | |
| 113 | + let banc = banc(); | |
| 114 | + let (res, _) = send(&banc.router, get("/")).await; | |
| 115 | + assert_eq!(header(&res, "location"), "/install"); | |
| 116 | +} | |
| 117 | + | |
| 118 | +#[tokio::test] | |
| 119 | +async fn l_identifiant_de_session_change_apres_l_acces() { | |
| 120 | + let banc = banc(); | |
| 121 | + let (avant, _) = session(&banc.router).await; | |
| 122 | + let (apres, _) = session_assistant(&banc).await; | |
| 123 | + assert_ne!(avant, apres); | |
| 124 | + let (res, _) = send(&banc.router, get_avec("/install", &avant)).await; | |
| 125 | + assert_eq!(res.status(), StatusCode::SEE_OTHER, "l'ancien identifiant ne donne pas accès"); | |
| 126 | +} |
A
installer/tests/assistant.rs
+391
-0
@@ -0,0 +1,391 @@
| 1 | +//! OI-024 à OI-031 — étapes de l'assistant E-001 à E-008 (E-006 : M2, D-020). | |
| 2 | + | |
| 3 | +mod commun; | |
| 4 | + | |
| 5 | +use axum::{body::Body, http::Request, http::StatusCode}; | |
| 6 | +use commun::*; | |
| 7 | +use open_iam_installer::brouillon::{Depot, Etape}; | |
| 8 | + | |
| 9 | +async fn ouvert() -> (Banc, String, String) { | |
| 10 | + let banc = banc(); | |
| 11 | + let (cookie, csrf) = session_assistant(&banc).await; | |
| 12 | + (banc, cookie, csrf) | |
| 13 | +} | |
| 14 | + | |
| 15 | +async fn poster( | |
| 16 | + banc: &Banc, | |
| 17 | + cookie: &str, | |
| 18 | + csrf: &str, | |
| 19 | + uri: &str, | |
| 20 | + form: &str, | |
| 21 | +) -> (axum::http::Response<Body>, String) { | |
| 22 | + send(&banc.router, post_form(uri, cookie, Some(csrf), form)).await | |
| 23 | +} | |
| 24 | + | |
| 25 | +fn brouillon(banc: &Banc) -> open_iam_installer::brouillon::Brouillon { | |
| 26 | + Depot::ouvrir(banc.etat_dir()).unwrap().charger().unwrap().expect("brouillon").0 | |
| 27 | +} | |
| 28 | + | |
| 29 | +const ORGANISATION: &str = | |
| 30 | + "nom=Mairie+d%27Exemple&domaine=Exemple.FR&base_dn=&langue=fr&fuseau=Europe%2FParis"; | |
| 31 | +const MOT_DE_PASSE: &str = "Cheval-Batterie-42"; | |
| 32 | +const URGENCE: &str = "Urgence-Tres-Longue-2026!"; | |
| 33 | + | |
| 34 | +/// Mène l'assistant jusqu'à l'étape `derniere` incluse. | |
| 35 | +async fn jusqu_a(banc: &Banc, cookie: &str, csrf: &str, derniere: Etape) { | |
| 36 | + let etapes: [(Etape, &str, String); 6] = [ | |
| 37 | + (Etape::Organisation, "/install/organisation", ORGANISATION.into()), | |
| 38 | + (Etape::Cibles, "/install/cibles", "mode=native&topologie=local".into()), | |
| 39 | + (Etape::Composants, "/install/composants", "composants=openldap&composants=sauvegarde".into()), | |
| 40 | + ( | |
| 41 | + Etape::Securite, | |
| 42 | + "/install/securite", | |
| 43 | + "annuaire=annuaire.exemple.fr&tls=interne&preset=anssi&longueur_min=12&classes_min=3&historique=5&expiration_jours=0&echecs_max=10&verrouillage_minutes=15".into(), | |
| 44 | + ), | |
| 45 | + ( | |
| 46 | + Etape::Comptes, | |
| 47 | + "/install/comptes", | |
| 48 | + format!( | |
| 49 | + "urgence={URGENCE}&uid=jean.dupont&prenom=Jean&nom=Dupont&email=jean.dupont%40exemple.fr&mode_mdp=saisir&mot_de_passe={MOT_DE_PASSE}&confirmation={MOT_DE_PASSE}" | |
| 50 | + ), | |
| 51 | + ), | |
| 52 | + (Etape::Telemetrie, "/install/telemetrie", "".into()), | |
| 53 | + ]; | |
| 54 | + poster(banc, cookie, csrf, "/install/commencer", "").await; | |
| 55 | + for (etape, uri, form) in etapes { | |
| 56 | + let (res, body) = poster(banc, cookie, csrf, uri, &form).await; | |
| 57 | + assert_eq!(res.status(), StatusCode::NO_CONTENT, "{uri} : {body}"); | |
| 58 | + if etape == derniere { | |
| 59 | + break; | |
| 60 | + } | |
| 61 | + } | |
| 62 | +} | |
| 63 | + | |
| 64 | +// --- E-001 ------------------------------------------------------------------------------ | |
| 65 | + | |
| 66 | +#[tokio::test] | |
| 67 | +async fn e001_les_prerequis_se_chargent_et_permettent_de_commencer() { | |
| 68 | + let (banc, cookie, _) = ouvert().await; | |
| 69 | + let (_, page) = send(&banc.router, get_avec("/install", &cookie)).await; | |
| 70 | + assert!(page.contains(r#"hx-get="/install/prerequis""#), "{page}"); | |
| 71 | + | |
| 72 | + let (res, fragment) = send(&banc.router, get_avec("/install/prerequis", &cookie)).await; | |
| 73 | + assert_eq!(res.status(), StatusCode::OK); | |
| 74 | + assert_eq!(fragment.matches("data-controle=").count(), 7, "{fragment}"); | |
| 75 | + assert!(fragment.contains("Commencer")); | |
| 76 | + assert!(!fragment.contains("raison-commencer"), "aucun prérequis bloquant : {fragment}"); | |
| 77 | + assert!(fragment.contains(r#"hx-post="/install/commencer""#), "bouton Commencer actif"); | |
| 78 | +} | |
| 79 | + | |
| 80 | +#[tokio::test] | |
| 81 | +async fn e001_commencer_cree_le_brouillon_et_mene_a_l_organisation() { | |
| 82 | + let (banc, cookie, csrf) = ouvert().await; | |
| 83 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/commencer", "").await; | |
| 84 | + assert_eq!(res.status(), StatusCode::NO_CONTENT); | |
| 85 | + assert_eq!(header(&res, "hx-redirect"), "/install/organisation"); | |
| 86 | + assert!(banc.etat_dir().join(Depot::BROUILLON).exists()); | |
| 87 | +} | |
| 88 | + | |
| 89 | +#[tokio::test] | |
| 90 | +async fn e001_un_brouillon_existant_se_reprend_ou_se_supprime() { | |
| 91 | + let (banc, cookie, csrf) = ouvert().await; | |
| 92 | + jusqu_a(&banc, &cookie, &csrf, Etape::Organisation).await; | |
| 93 | + let (_, page) = send(&banc.router, get_avec("/install", &cookie)).await; | |
| 94 | + assert!(page.contains("Mairie d'Exemple") || page.contains("Mairie d'Exemple"), "{page}"); | |
| 95 | + assert!(page.contains(r#"href="/install/cibles""#), "lien Reprendre vers l'étape courante"); | |
| 96 | + | |
| 97 | + let req = Request::delete("/install/brouillon") | |
| 98 | + .header("cookie", &cookie) | |
| 99 | + .header("x-csrf-token", &csrf) | |
| 100 | + .header("hx-request", "true") | |
| 101 | + .body(Body::empty()) | |
| 102 | + .unwrap(); | |
| 103 | + let (res, _) = send(&banc.router, req).await; | |
| 104 | + assert_eq!(res.status(), StatusCode::OK); | |
| 105 | + assert!(!banc.etat_dir().join(Depot::BROUILLON).exists()); | |
| 106 | +} | |
| 107 | + | |
| 108 | +fn import(cookie: &str, csrf: &str, yaml: &str) -> Request<Body> { | |
| 109 | + let corps = format!( | |
| 110 | + "--LIMITE\r\nContent-Disposition: form-data; name=\"fichier\"; filename=\"openiam.yaml\"\r\nContent-Type: application/yaml\r\n\r\n{yaml}\r\n--LIMITE--\r\n" | |
| 111 | + ); | |
| 112 | + Request::post("/install/import") | |
| 113 | + .header("cookie", cookie) | |
| 114 | + .header("x-csrf-token", csrf) | |
| 115 | + .header("hx-request", "true") | |
| 116 | + .header("content-type", "multipart/form-data; boundary=LIMITE") | |
| 117 | + .body(Body::from(corps)) | |
| 118 | + .unwrap() | |
| 119 | +} | |
| 120 | + | |
| 121 | +#[tokio::test] | |
| 122 | +async fn e001_un_import_valide_mene_au_recapitulatif_avec_les_comptes_a_revoir() { | |
| 123 | + let (banc, cookie, csrf) = ouvert().await; | |
| 124 | + let (res, body) = send(&banc.router, import(&cookie, &csrf, include_str!("donnees/openiam.yaml"))).await; | |
| 125 | + assert_eq!(res.status(), StatusCode::NO_CONTENT, "{body}"); | |
| 126 | + assert_eq!(header(&res, "hx-redirect"), "/install/recapitulatif"); | |
| 127 | + let b = brouillon(&banc); | |
| 128 | + assert_eq!(b.etape_courante(), Some(Etape::Comptes), "les mots de passe sont à ressaisir"); | |
| 129 | +} | |
| 130 | + | |
| 131 | +#[tokio::test] | |
| 132 | +async fn e001_un_import_avec_secret_ou_invalide_est_refuse_avec_le_chemin_fautif() { | |
| 133 | + let (banc, cookie, csrf) = ouvert().await; | |
| 134 | + let avec_secret = format!("{}smtp_mot_de_passe: x\n", include_str!("donnees/openiam.yaml")); | |
| 135 | + let (res, body) = send(&banc.router, import(&cookie, &csrf, &avec_secret)).await; | |
| 136 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 137 | + assert!(body.contains("secret"), "{body}"); | |
| 138 | + | |
| 139 | + let invalide = include_str!("donnees/openiam.yaml").replace("domaine: exemple.fr", "domaine: localhost"); | |
| 140 | + let (res, body) = send(&banc.router, import(&cookie, &csrf, &invalide)).await; | |
| 141 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 142 | + assert!(body.contains("organisation.domaine"), "{body}"); | |
| 143 | +} | |
| 144 | + | |
| 145 | +// --- Parcours et stepper ---------------------------------------------------------------- | |
| 146 | + | |
| 147 | +#[tokio::test] | |
| 148 | +async fn on_ne_peut_pas_sauter_une_etape() { | |
| 149 | + let (banc, cookie, csrf) = ouvert().await; | |
| 150 | + poster(&banc, &cookie, &csrf, "/install/commencer", "").await; | |
| 151 | + let (res, _) = send(&banc.router, get_avec("/install/composants", &cookie)).await; | |
| 152 | + assert_eq!(res.status(), StatusCode::SEE_OTHER); | |
| 153 | + assert_eq!(header(&res, "location"), "/install/organisation"); | |
| 154 | +} | |
| 155 | + | |
| 156 | +#[tokio::test] | |
| 157 | +async fn le_stepper_signale_l_etape_courante_et_les_etapes_sautees() { | |
| 158 | + let (banc, cookie, csrf) = ouvert().await; | |
| 159 | + jusqu_a(&banc, &cookie, &csrf, Etape::Composants).await; | |
| 160 | + let (_, page) = send(&banc.router, get_avec("/install/securite", &cookie)).await; | |
| 161 | + assert!(page.contains(r#"aria-current="step""#)); | |
| 162 | + assert!(page.contains("Étape 4 / 9"), "{page}"); | |
| 163 | + assert!(page.contains("(sautée)"), "la messagerie est sautée en M1"); | |
| 164 | +} | |
| 165 | + | |
| 166 | +// --- E-002 ------------------------------------------------------------------------------ | |
| 167 | + | |
| 168 | +#[tokio::test] | |
| 169 | +async fn e002_une_organisation_valide_est_normalisee_et_mene_aux_cibles() { | |
| 170 | + let (banc, cookie, csrf) = ouvert().await; | |
| 171 | + poster(&banc, &cookie, &csrf, "/install/commencer", "").await; | |
| 172 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/organisation", ORGANISATION).await; | |
| 173 | + assert_eq!(header(&res, "hx-redirect"), "/install/cibles"); | |
| 174 | + let organisation = brouillon(&banc).organisation.unwrap(); | |
| 175 | + assert_eq!(organisation.domaine, "exemple.fr"); | |
| 176 | + assert_eq!(organisation.base_dn, "dc=exemple,dc=fr"); | |
| 177 | +} | |
| 178 | + | |
| 179 | +#[tokio::test] | |
| 180 | +async fn e002_une_saisie_invalide_renvoie_les_erreurs_par_champ() { | |
| 181 | + let (banc, cookie, csrf) = ouvert().await; | |
| 182 | + poster(&banc, &cookie, &csrf, "/install/commencer", "").await; | |
| 183 | + let (res, body) = poster( | |
| 184 | + &banc, | |
| 185 | + &cookie, | |
| 186 | + &csrf, | |
| 187 | + "/install/organisation", | |
| 188 | + "nom=X&domaine=localhost&base_dn=&langue=fr&fuseau=Mars", | |
| 189 | + ) | |
| 190 | + .await; | |
| 191 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 192 | + assert!(body.contains(r#"id="form-organisation""#)); | |
| 193 | + for champ in ["nom", "domaine", "fuseau"] { | |
| 194 | + assert!(body.contains(&format!(r#"id="erreur-{champ}""#)), "erreur {champ} absente : {body}"); | |
| 195 | + } | |
| 196 | + assert!(body.contains("au moins un point")); | |
| 197 | + assert!(body.contains("role=\"alert\""), "résumé des erreurs en tête"); | |
| 198 | +} | |
| 199 | + | |
| 200 | +#[tokio::test] | |
| 201 | +async fn e002_la_validation_immediate_du_domaine_avertit_pour_local() { | |
| 202 | + let (banc, cookie, csrf) = ouvert().await; | |
| 203 | + poster(&banc, &cookie, &csrf, "/install/commencer", "").await; | |
| 204 | + let (res, body) = | |
| 205 | + poster(&banc, &cookie, &csrf, "/install/organisation/champ/domaine", "domaine=mairie.local").await; | |
| 206 | + assert_eq!(res.status(), StatusCode::OK); | |
| 207 | + assert!(body.contains(r#"id="field-domaine""#)); | |
| 208 | + assert!(body.contains("mDNS"), "{body}"); | |
| 209 | +} | |
| 210 | + | |
| 211 | +#[tokio::test] | |
| 212 | +async fn e002_changer_le_domaine_rend_la_securite_a_revoir() { | |
| 213 | + let (banc, cookie, csrf) = ouvert().await; | |
| 214 | + jusqu_a(&banc, &cookie, &csrf, Etape::Securite).await; | |
| 215 | + let autre = ORGANISATION.replace("Exemple.FR", "autre.fr"); | |
| 216 | + poster(&banc, &cookie, &csrf, "/install/organisation", &autre).await; | |
| 217 | + assert_eq!(brouillon(&banc).etape_courante(), Some(Etape::Securite)); | |
| 218 | +} | |
| 219 | + | |
| 220 | +// --- E-003 ------------------------------------------------------------------------------ | |
| 221 | + | |
| 222 | +#[tokio::test] | |
| 223 | +async fn e003_seul_le_mode_natif_local_est_disponible_en_m1() { | |
| 224 | + let (banc, cookie, csrf) = ouvert().await; | |
| 225 | + jusqu_a(&banc, &cookie, &csrf, Etape::Organisation).await; | |
| 226 | + let (_, page) = send(&banc.router, get_avec("/install/cibles", &cookie)).await; | |
| 227 | + assert!(page.contains("M2"), "options du jalon M2 annoncées : {page}"); | |
| 228 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/cibles", "mode=compose&topologie=local").await; | |
| 229 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 230 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/cibles", "mode=native&topologie=local").await; | |
| 231 | + assert_eq!(header(&res, "hx-redirect"), "/install/composants"); | |
| 232 | +} | |
| 233 | + | |
| 234 | +// --- E-004 ------------------------------------------------------------------------------ | |
| 235 | + | |
| 236 | +#[tokio::test] | |
| 237 | +async fn e004_les_composants_indisponibles_sont_visibles_mais_non_cochables() { | |
| 238 | + let (banc, cookie, csrf) = ouvert().await; | |
| 239 | + jusqu_a(&banc, &cookie, &csrf, Etape::Cibles).await; | |
| 240 | + let (_, page) = send(&banc.router, get_avec("/install/composants", &cookie)).await; | |
| 241 | + assert!(page.contains("Self Service Password")); | |
| 242 | + assert!(page.contains(r#"value="ssp" disabled"#), "{page}"); | |
| 243 | + assert!(page.contains("Jalon M2")); | |
| 244 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/composants", "composants=ssp").await; | |
| 245 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 246 | +} | |
| 247 | + | |
| 248 | +#[tokio::test] | |
| 249 | +async fn e004_la_resolution_ajoute_les_composants_verrouilles_et_estime_les_ressources() { | |
| 250 | + let (banc, cookie, csrf) = ouvert().await; | |
| 251 | + jusqu_a(&banc, &cookie, &csrf, Etape::Cibles).await; | |
| 252 | + let (res, body) = poster(&banc, &cookie, &csrf, "/install/composants/resolution", "").await; | |
| 253 | + assert_eq!(res.status(), StatusCode::OK); | |
| 254 | + assert!(body.contains("Requis par"), "{body}"); | |
| 255 | + assert!(body.contains("1024 Mo"), "RAM estimée : {body}"); | |
| 256 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/composants", "").await; | |
| 257 | + assert_eq!(header(&res, "hx-redirect"), "/install/securite"); | |
| 258 | + assert_eq!(brouillon(&banc).composants.unwrap().len(), 2); | |
| 259 | +} | |
| 260 | + | |
| 261 | +// --- E-005 ------------------------------------------------------------------------------ | |
| 262 | + | |
| 263 | +#[tokio::test] | |
| 264 | +async fn e005_les_noms_de_services_sont_proposes_depuis_le_domaine() { | |
| 265 | + let (banc, cookie, csrf) = ouvert().await; | |
| 266 | + jusqu_a(&banc, &cookie, &csrf, Etape::Composants).await; | |
| 267 | + let (_, page) = send(&banc.router, get_avec("/install/securite", &cookie)).await; | |
| 268 | + assert!(page.contains(r#"value="annuaire.exemple.fr""#), "{page}"); | |
| 269 | + assert!(page.contains("ANSSI")); | |
| 270 | +} | |
| 271 | + | |
| 272 | +#[tokio::test] | |
| 273 | +async fn e005_une_politique_hors_bornes_est_refusee_et_la_messagerie_est_sautee() { | |
| 274 | + let (banc, cookie, csrf) = ouvert().await; | |
| 275 | + jusqu_a(&banc, &cookie, &csrf, Etape::Composants).await; | |
| 276 | + let invalide = "annuaire=annuaire.exemple.fr&tls=interne&preset=personnalisee&longueur_min=4&classes_min=3&historique=5&expiration_jours=0&echecs_max=10&verrouillage_minutes=15"; | |
| 277 | + let (res, body) = poster(&banc, &cookie, &csrf, "/install/securite", invalide).await; | |
| 278 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 279 | + assert!(body.contains(r#"id="erreur-longueur_min""#), "{body}"); | |
| 280 | + | |
| 281 | + let (res, _) = poster( | |
| 282 | + &banc, | |
| 283 | + &cookie, | |
| 284 | + &csrf, | |
| 285 | + "/install/securite", | |
| 286 | + &invalide.replace("longueur_min=4", "longueur_min=14"), | |
| 287 | + ) | |
| 288 | + .await; | |
| 289 | + assert_eq!(header(&res, "hx-redirect"), "/install/comptes", "la messagerie est sautée"); | |
| 290 | + assert_eq!(brouillon(&banc).securite.unwrap().mdp.longueur_min, 14); | |
| 291 | +} | |
| 292 | + | |
| 293 | +// --- E-007 ------------------------------------------------------------------------------ | |
| 294 | + | |
| 295 | +#[tokio::test] | |
| 296 | +async fn e007_le_mot_de_passe_suit_la_politique_et_la_confirmation() { | |
| 297 | + let (banc, cookie, csrf) = ouvert().await; | |
| 298 | + jusqu_a(&banc, &cookie, &csrf, Etape::Securite).await; | |
| 299 | + let base = format!( | |
| 300 | + "urgence={URGENCE}&uid=jean.dupont&prenom=Jean&nom=Dupont&email=jean.dupont%40exemple.fr&mode_mdp=saisir" | |
| 301 | + ); | |
| 302 | + let (res, body) = poster( | |
| 303 | + &banc, | |
| 304 | + &cookie, | |
| 305 | + &csrf, | |
| 306 | + "/install/comptes", | |
| 307 | + &format!("{base}&mot_de_passe=court&confirmation=court"), | |
| 308 | + ) | |
| 309 | + .await; | |
| 310 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 311 | + assert!(body.contains("12 caractères"), "{body}"); | |
| 312 | + | |
| 313 | + let (res, body) = poster( | |
| 314 | + &banc, | |
| 315 | + &cookie, | |
| 316 | + &csrf, | |
| 317 | + "/install/comptes", | |
| 318 | + &format!("{base}&mot_de_passe={MOT_DE_PASSE}&confirmation=autre"), | |
| 319 | + ) | |
| 320 | + .await; | |
| 321 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 322 | + assert!(body.contains("identiques"), "{body}"); | |
| 323 | + | |
| 324 | + let (res, body) = poster(&banc, &cookie, &csrf, "/install/comptes", &format!("urgence=court&uid=jean.dupont&prenom=Jean&nom=Dupont&email=jean.dupont%40exemple.fr&mode_mdp=saisir&mot_de_passe={MOT_DE_PASSE}&confirmation={MOT_DE_PASSE}")).await; | |
| 325 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 326 | + assert!(body.contains("20 caractères"), "{body}"); | |
| 327 | +} | |
| 328 | + | |
| 329 | +#[tokio::test] | |
| 330 | +async fn e007_les_secrets_sont_enregistres_a_part_et_jamais_reaffiches() { | |
| 331 | + let (banc, cookie, csrf) = ouvert().await; | |
| 332 | + jusqu_a(&banc, &cookie, &csrf, Etape::Comptes).await; | |
| 333 | + let brouillon_yaml = std::fs::read_to_string(banc.etat_dir().join(Depot::BROUILLON)).unwrap(); | |
| 334 | + assert!(!brouillon_yaml.contains(MOT_DE_PASSE)); | |
| 335 | + let secrets = std::fs::read_to_string(banc.etat_dir().join(Depot::SECRETS)).unwrap(); | |
| 336 | + assert!(secrets.contains(MOT_DE_PASSE)); | |
| 337 | + | |
| 338 | + let (_, page) = send(&banc.router, get_avec("/install/comptes", &cookie)).await; | |
| 339 | + assert!(!page.contains(MOT_DE_PASSE) && !page.contains(URGENCE), "secret renvoyé au navigateur"); | |
| 340 | + assert!(page.contains("Défini ✓")); | |
| 341 | + | |
| 342 | + // Champs laissés vides : les secrets enregistrés sont conservés. | |
| 343 | + let (res, body) = poster(&banc, &cookie, &csrf, "/install/comptes", "urgence=&uid=jean.dupont&prenom=Jean&nom=Dupont&email=jean.dupont%40exemple.fr&mode_mdp=saisir&mot_de_passe=&confirmation=").await; | |
| 344 | + assert_eq!(res.status(), StatusCode::NO_CONTENT, "{body}"); | |
| 345 | +} | |
| 346 | + | |
| 347 | +#[tokio::test] | |
| 348 | +async fn e007_le_mot_de_passe_d_urgence_peut_etre_genere() { | |
| 349 | + let (banc, cookie, csrf) = ouvert().await; | |
| 350 | + jusqu_a(&banc, &cookie, &csrf, Etape::Securite).await; | |
| 351 | + let (res, body) = poster(&banc, &cookie, &csrf, "/install/comptes/generer", "").await; | |
| 352 | + assert_eq!(res.status(), StatusCode::OK); | |
| 353 | + assert!(body.contains(r#"name="urgence_genere" value="1""#), "{body}"); | |
| 354 | + let valeur = attribute(&body[body.find("id=\"urgence\"").unwrap() - 200..], "value"); | |
| 355 | + assert_eq!(valeur.chars().count(), 32); | |
| 356 | +} | |
| 357 | + | |
| 358 | +#[tokio::test] | |
| 359 | +async fn e007_l_envoi_d_un_lien_est_indisponible_sans_messagerie() { | |
| 360 | + let (banc, cookie, csrf) = ouvert().await; | |
| 361 | + jusqu_a(&banc, &cookie, &csrf, Etape::Securite).await; | |
| 362 | + let (_, page) = send(&banc.router, get_avec("/install/comptes", &cookie)).await; | |
| 363 | + assert!(page.contains(r#"value="lien" disabled"#), "{page}"); | |
| 364 | +} | |
| 365 | + | |
| 366 | +// --- E-008 ------------------------------------------------------------------------------ | |
| 367 | + | |
| 368 | +#[tokio::test] | |
| 369 | +async fn e008_la_telemetrie_est_desactivee_par_defaut_avec_l_apercu_exact() { | |
| 370 | + let (banc, cookie, csrf) = ouvert().await; | |
| 371 | + jusqu_a(&banc, &cookie, &csrf, Etape::Comptes).await; | |
| 372 | + let (_, page) = send(&banc.router, get_avec("/install/telemetrie", &cookie)).await; | |
| 373 | + assert!(page.contains(r#"name="telemetrie""#)); | |
| 374 | + assert!(!page.contains("checked"), "jamais pré-activée : {page}"); | |
| 375 | + assert!(page.contains("instance_id") && page.contains("tranche_utilisateurs"), "{page}"); | |
| 376 | + assert!(!page.contains("exemple.fr"), "l'aperçu ne contient pas le domaine"); | |
| 377 | + | |
| 378 | + let (res, _) = poster(&banc, &cookie, &csrf, "/install/telemetrie", "telemetrie=on").await; | |
| 379 | + assert_eq!(header(&res, "hx-redirect"), "/install/recapitulatif"); | |
| 380 | + assert!(brouillon(&banc).exploitation.unwrap().telemetrie.active); | |
| 381 | +} | |
| 382 | + | |
| 383 | +#[tokio::test] | |
| 384 | +async fn retour_au_recapitulatif_apres_modification() { | |
| 385 | + let (banc, cookie, csrf) = ouvert().await; | |
| 386 | + jusqu_a(&banc, &cookie, &csrf, Etape::Telemetrie).await; | |
| 387 | + let (res, _) = | |
| 388 | + poster(&banc, &cookie, &csrf, "/install/cibles?retour=recapitulatif", "mode=native&topologie=local") | |
| 389 | + .await; | |
| 390 | + assert_eq!(header(&res, "hx-redirect"), "/install/recapitulatif"); | |
| 391 | +} |
A
installer/tests/commun/mod.rs
+124
-0
@@ -0,0 +1,124 @@
| 1 | +//! Outils partagés des tests d'intégration : application sur un répertoire d'état temporaire, | |
| 2 | +//! session ouverte, envoi de requêtes. | |
| 3 | +#![allow(dead_code)] | |
| 4 | + | |
| 5 | +use std::path::{Path, PathBuf}; | |
| 6 | + | |
| 7 | +use axum::{ | |
| 8 | + Router, | |
| 9 | + body::Body, | |
| 10 | + http::{Request, Response, header}, | |
| 11 | +}; | |
| 12 | +use http_body_util::BodyExt; | |
| 13 | +use open_iam_installer::{ | |
| 14 | + app, | |
| 15 | + etat::{Etat, Parametres}, | |
| 16 | + runner::Outils, | |
| 17 | +}; | |
| 18 | +use tower::ServiceExt; | |
| 19 | + | |
| 20 | +pub struct Banc { | |
| 21 | + pub dossier: tempfile::TempDir, | |
| 22 | + pub router: Router, | |
| 23 | + pub etat: std::sync::Arc<Etat>, | |
| 24 | +} | |
| 25 | + | |
| 26 | +impl Banc { | |
| 27 | + pub fn racine(&self) -> &Path { | |
| 28 | + self.dossier.path() | |
| 29 | + } | |
| 30 | + | |
| 31 | + pub fn etat_dir(&self) -> PathBuf { | |
| 32 | + self.dossier.path().join("etat") | |
| 33 | + } | |
| 34 | +} | |
| 35 | + | |
| 36 | +pub fn faux(nom: &str) -> PathBuf { | |
| 37 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/faux").join(nom) | |
| 38 | +} | |
| 39 | + | |
| 40 | +pub fn banc() -> Banc { | |
| 41 | + banc_avec(Vec::new()) | |
| 42 | +} | |
| 43 | + | |
| 44 | +/// Application dont Ansible est remplacé par les faux de tests/faux (variables du scénario). | |
| 45 | +pub fn banc_avec(environnement: Vec<(String, String)>) -> Banc { | |
| 46 | + let dossier = tempfile::tempdir().unwrap(); | |
| 47 | + let zoneinfo = dossier.path().join("zoneinfo"); | |
| 48 | + std::fs::create_dir_all(zoneinfo.join("Europe")).unwrap(); | |
| 49 | + std::fs::write(zoneinfo.join("Europe/Paris"), b"TZif").unwrap(); | |
| 50 | + let parametres = Parametres { | |
| 51 | + etat: dossier.path().join("etat"), | |
| 52 | + zoneinfo, | |
| 53 | + outils: Outils { | |
| 54 | + ansible_playbook: faux("ansible-playbook"), | |
| 55 | + ansible_vault: faux("ansible-vault"), | |
| 56 | + environnement, | |
| 57 | + }, | |
| 58 | + dossier_recapitulatif: dossier.path().join("home/open-iam"), | |
| 59 | + prerequis_simules: true, | |
| 60 | + }; | |
| 61 | + let etat = Etat::ouvrir(parametres).unwrap(); | |
| 62 | + Banc { router: app(etat.clone()), etat, dossier } | |
| 63 | +} | |
| 64 | + | |
| 65 | +pub async fn send(router: &Router, req: Request<Body>) -> (Response<Body>, String) { | |
| 66 | + let res = router.clone().oneshot(req).await.unwrap(); | |
| 67 | + let (parts, body) = res.into_parts(); | |
| 68 | + let bytes = body.collect().await.unwrap().to_bytes(); | |
| 69 | + (Response::from_parts(parts, Body::empty()), String::from_utf8_lossy(&bytes).into_owned()) | |
| 70 | +} | |
| 71 | + | |
| 72 | +pub fn get(uri: &str) -> Request<Body> { | |
| 73 | + Request::get(uri).body(Body::empty()).unwrap() | |
| 74 | +} | |
| 75 | + | |
| 76 | +pub fn get_avec(uri: &str, cookie: &str) -> Request<Body> { | |
| 77 | + Request::get(uri).header(header::COOKIE, cookie).body(Body::empty()).unwrap() | |
| 78 | +} | |
| 79 | + | |
| 80 | +pub fn header<'a>(res: &'a Response<Body>, name: &str) -> &'a str { | |
| 81 | + res.headers().get(name).map(|v| v.to_str().unwrap()).unwrap_or("") | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// Valeur décodée du premier attribut `name="…"` du HTML. | |
| 85 | +pub fn attribute(html: &str, name: &str) -> String { | |
| 86 | + let marker = format!(" {name}=\""); | |
| 87 | + let start = html.find(&marker).unwrap_or_else(|| panic!("attribut {name} absent")) + marker.len(); | |
| 88 | + let raw = html[start..].split('"').next().unwrap(); | |
| 89 | + raw.replace(""", "\"").replace(""", "\"").replace("'", "'").replace("&", "&") | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// Session anonyme (cookie + jeton CSRF), ouverte sur la page d'accès. | |
| 93 | +pub async fn session(router: &Router) -> (String, String) { | |
| 94 | + let (res, body) = send(router, get("/acces")).await; | |
| 95 | + let cookie = header(&res, "set-cookie").split(';').next().unwrap().to_owned(); | |
| 96 | + let hx_headers: serde_json::Value = serde_json::from_str(&attribute(&body, "hx-headers")).unwrap(); | |
| 97 | + (cookie, hx_headers["X-CSRF-Token"].as_str().unwrap().to_owned()) | |
| 98 | +} | |
| 99 | + | |
| 100 | +/// Session ayant franchi l'accès par jeton (E-000). | |
| 101 | +pub async fn session_assistant(banc: &Banc) -> (String, String) { | |
| 102 | + let (cookie, csrf) = session(&banc.router).await; | |
| 103 | + let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap(); | |
| 104 | + let (res, _) = | |
| 105 | + send(&banc.router, post_form("/acces", &cookie, Some(&csrf), &format!("jeton={jeton}"))).await; | |
| 106 | + assert_eq!(res.status(), 204, "accès refusé"); | |
| 107 | + (nouveau_cookie(&res).unwrap_or(cookie), csrf) | |
| 108 | +} | |
| 109 | + | |
| 110 | +/// Cookie de session renvoyé par une réponse (l'identifiant change après l'accès). | |
| 111 | +pub fn nouveau_cookie(res: &Response<Body>) -> Option<String> { | |
| 112 | + res.headers().get("set-cookie").map(|v| v.to_str().unwrap().split(';').next().unwrap().to_owned()) | |
| 113 | +} | |
| 114 | + | |
| 115 | +pub fn post_form(uri: &str, cookie: &str, token: Option<&str>, form: &str) -> Request<Body> { | |
| 116 | + let mut req = Request::post(uri) | |
| 117 | + .header(header::COOKIE, cookie) | |
| 118 | + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") | |
| 119 | + .header("hx-request", "true"); | |
| 120 | + if let Some(token) = token { | |
| 121 | + req = req.header("x-csrf-token", token); | |
| 122 | + } | |
| 123 | + req.body(Body::from(form.to_owned())).unwrap() | |
| 124 | +} |
M
installer/tests/composants.rs
+7
-2
@@ -4,11 +4,16 @@
| 4 | 4 | |
| 5 | 5 | use axum::{body::Body, http::Request, http::StatusCode}; |
| 6 | 6 | use http_body_util::BodyExt; |
| 7 | -use open_iam_installer::app; | |
| 7 | +mod commun; | |
| 8 | + | |
| 8 | 9 | use tower::ServiceExt; |
| 9 | 10 | |
| 10 | 11 | async fn page() -> String { |
| 11 | - let res = app().oneshot(Request::get("/dev/composants").body(Body::empty()).unwrap()).await.unwrap(); | |
| 12 | + let res = commun::banc() | |
| 13 | + .router | |
| 14 | + .oneshot(Request::get("/dev/composants").body(Body::empty()).unwrap()) | |
| 15 | + .await | |
| 16 | + .unwrap(); | |
| 12 | 17 | assert_eq!(res.status(), StatusCode::OK); |
| 13 | 18 | String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap() |
| 14 | 19 | } |
A
installer/tests/donnees/openiam.yaml
+38
-0
@@ -0,0 +1,38 @@
| 1 | +organisation: | |
| 2 | + nom: Mairie d'Exemple | |
| 3 | + domaine: exemple.fr | |
| 4 | + base_dn: dc=exemple,dc=fr | |
| 5 | + langue: fr | |
| 6 | + fuseau: Europe/Paris | |
| 7 | +deploiement: | |
| 8 | + mode: native | |
| 9 | + topologie: local | |
| 10 | +composants: | |
| 11 | +- openldap | |
| 12 | +- sauvegarde | |
| 13 | +services: | |
| 14 | + annuaire: annuaire.exemple.fr | |
| 15 | +tls: | |
| 16 | + mode: interne | |
| 17 | +mdp: | |
| 18 | + longueur_min: 12 | |
| 19 | + classes_min: 3 | |
| 20 | + historique: 5 | |
| 21 | + expiration_jours: 0 | |
| 22 | + echecs_max: 10 | |
| 23 | + verrouillage_minutes: 15 | |
| 24 | +mfa: | |
| 25 | + exigence: tous | |
| 26 | + admins: true | |
| 27 | +admin_initial: | |
| 28 | + uid: jean.dupont | |
| 29 | + prenom: Jean | |
| 30 | + nom: Dupont | |
| 31 | + email: jean.dupont@exemple.fr | |
| 32 | + mode_mdp: saisir | |
| 33 | +supervision: | |
| 34 | + retention_metriques_jours: 30 | |
| 35 | + retention_journaux_jours: 90 | |
| 36 | +telemetrie: | |
| 37 | + active: false | |
| 38 | + url: https://telemetrie.open-iam.invalid/v1/rapports |
A
installer/tests/faux/ansible-playbook
+42
-0
@@ -0,0 +1,42 @@
| 1 | +#!/bin/bash | |
| 2 | +# Faux ansible-playbook pour les tests du runner : rejoue le scénario OIAM_FAUX_SCENARIO. | |
| 3 | +# reussite : un play, 4 tâches sur 2 rôles, bilan, sortie 0 | |
| 4 | +# echec : la 3e tâche échoue, sortie 2 | |
| 5 | +# secret : écrit OIAM_FAUX_SECRET sur la sortie d'erreur et dans un message, sortie 0 | |
| 6 | +# long : émet une tâche puis attend (pour les tests d'interruption) | |
| 7 | +# Il note ses arguments et l'environnement utile dans $OIAM_FAUX_TRACE. | |
| 8 | +set -u | |
| 9 | +{ | |
| 10 | + printf 'args=%s\n' "$*" | |
| 11 | + printf 'callback=%s\n' "${ANSIBLE_STDOUT_CALLBACK:-}" | |
| 12 | + printf 'cwd=%s\n' "$PWD" | |
| 13 | + printf 'locale=%s\n' "${LC_ALL:-}" | |
| 14 | +} > "${OIAM_FAUX_TRACE:-/dev/null}" | |
| 15 | + | |
| 16 | +tache() { printf '{"type":"tache","hote":"localhost","role":"%s","nom":"%s : %s","statut":"%s","message":"%s"}\n' "$1" "$1" "$2" "$3" "${4:-}"; } | |
| 17 | + | |
| 18 | +echo '{"type":"play","nom":"Socle Open IAM","taches":4}' | |
| 19 | +case "${OIAM_FAUX_SCENARIO:-reussite}" in | |
| 20 | + reussite) | |
| 21 | + tache common "Installer les paquets de base" changed | |
| 22 | + tache common "Régler le fuseau horaire" ok | |
| 23 | + tache openldap_ltb "Installer les paquets OpenLDAP LTB" changed | |
| 24 | + tache openldap_ltb "Démarrer l'annuaire" ok | |
| 25 | + echo '{"type":"bilan","hotes":{"localhost":{"ok":4,"changed":2,"failures":0,"unreachable":0,"skipped":0}}}' | |
| 26 | + exit 0 ;; | |
| 27 | + echec) | |
| 28 | + tache common "Installer les paquets de base" changed | |
| 29 | + tache common "Régler le fuseau horaire" ok | |
| 30 | + tache openldap_ltb "Installer les paquets OpenLDAP LTB" failed "No package matching 'openldap-ltb' is available" | |
| 31 | + echo '{"type":"bilan","hotes":{"localhost":{"ok":2,"changed":1,"failures":1,"unreachable":0,"skipped":0}}}' | |
| 32 | + exit 2 ;; | |
| 33 | + secret) | |
| 34 | + echo "avertissement contenant ${OIAM_FAUX_SECRET}" >&2 | |
| 35 | + tache common "Tâche bavarde" failed "mot de passe ${OIAM_FAUX_SECRET} refusé" | |
| 36 | + exit 0 ;; | |
| 37 | + long) | |
| 38 | + tache common "Installer les paquets de base" changed | |
| 39 | + trap 'echo "interrompu" >&2; exit 130' INT | |
| 40 | + sleep 30 & wait | |
| 41 | + exit 0 ;; | |
| 42 | +esac |
A
installer/tests/faux/ansible-vault
+9
-0
@@ -0,0 +1,9 @@
| 1 | +#!/bin/bash | |
| 2 | +# Faux ansible-vault : « chiffre » en base64 avec l'en-tête vault, pour vérifier qu'aucun | |
| 3 | +# secret n'est écrit en clair. Usage attendu : encrypt --vault-password-file F FICHIER | |
| 4 | +set -eu | |
| 5 | +[[ "$1" == "encrypt" ]] || exit 3 | |
| 6 | +fichier="${*: -1}" | |
| 7 | +[[ -s "$3" ]] || { echo "fichier de mot de passe vide" >&2; exit 4; } | |
| 8 | +contenu="$(base64 -w0 "$fichier")" | |
| 9 | +printf '$ANSIBLE_VAULT;1.1;AES256\n%s\n' "$contenu" > "$fichier" |
A
installer/tests/installation.rs
+253
-0
@@ -0,0 +1,253 @@
| 1 | +//! OI-037 à OI-039 — E-010 récapitulatif, E-011 installation en direct, E-012 résultat et | |
| 2 | +//! verrouillage. Ansible est remplacé par tests/faux/ansible-playbook. | |
| 3 | + | |
| 4 | +mod commun; | |
| 5 | + | |
| 6 | +use std::time::Duration; | |
| 7 | + | |
| 8 | +use axum::http::StatusCode; | |
| 9 | +use commun::*; | |
| 10 | + | |
| 11 | +const URGENCE: &str = "Urgence-Tres-Longue-2026!"; | |
| 12 | +const MOT_DE_PASSE: &str = "Cheval-Batterie-42"; | |
| 13 | + | |
| 14 | +/// Assistant complété jusqu'au récapitulatif, avec le scénario Ansible donné. | |
| 15 | +async fn pret(scenario: &str) -> (Banc, String, String) { | |
| 16 | + pret_avec(scenario, vec![]).await | |
| 17 | +} | |
| 18 | + | |
| 19 | +async fn pret_avec(scenario: &str, mut environnement: Vec<(String, String)>) -> (Banc, String, String) { | |
| 20 | + environnement.push(("OIAM_FAUX_SCENARIO".into(), scenario.into())); | |
| 21 | + let banc = banc_avec(environnement); | |
| 22 | + let (cookie, csrf) = session_assistant(&banc).await; | |
| 23 | + let etapes = [ | |
| 24 | + ("/install/commencer", String::new()), | |
| 25 | + ( | |
| 26 | + "/install/organisation", | |
| 27 | + "nom=Mairie+d%27Exemple&domaine=exemple.fr&base_dn=&langue=fr&fuseau=Europe%2FParis".into(), | |
| 28 | + ), | |
| 29 | + ("/install/cibles", "mode=native&topologie=local".into()), | |
| 30 | + ("/install/composants", String::new()), | |
| 31 | + ("/install/securite", "annuaire=annuaire.exemple.fr&tls=interne&preset=anssi".into()), | |
| 32 | + ( | |
| 33 | + "/install/comptes", | |
| 34 | + format!( | |
| 35 | + "urgence={URGENCE}&urgence_genere=1&uid=jean.dupont&prenom=Jean&nom=Dupont&email=jean.dupont%40exemple.fr&mode_mdp=saisir&mot_de_passe={MOT_DE_PASSE}&confirmation={MOT_DE_PASSE}" | |
| 36 | + ), | |
| 37 | + ), | |
| 38 | + ("/install/telemetrie", String::new()), | |
| 39 | + ]; | |
| 40 | + for (uri, form) in etapes { | |
| 41 | + let (res, body) = send(&banc.router, post_form(uri, &cookie, Some(&csrf), &form)).await; | |
| 42 | + assert_eq!(res.status(), StatusCode::NO_CONTENT, "{uri} : {body}"); | |
| 43 | + } | |
| 44 | + (banc, cookie, csrf) | |
| 45 | +} | |
| 46 | + | |
| 47 | +async fn verifier(banc: &Banc, cookie: &str, csrf: &str) -> String { | |
| 48 | + let (res, body) = send(&banc.router, post_form("/install/verification", cookie, Some(csrf), "")).await; | |
| 49 | + assert_eq!(res.status(), StatusCode::OK, "{body}"); | |
| 50 | + body | |
| 51 | +} | |
| 52 | + | |
| 53 | +async fn lancer(banc: &Banc, cookie: &str, csrf: &str) -> axum::http::Response<axum::body::Body> { | |
| 54 | + send(&banc.router, post_form("/install/execution", cookie, Some(csrf), "")).await.0 | |
| 55 | +} | |
| 56 | + | |
| 57 | +async fn attendre_fin(banc: &Banc) { | |
| 58 | + tokio::time::timeout(Duration::from_secs(20), async { | |
| 59 | + while banc.etat.runner.en_cours() { | |
| 60 | + tokio::time::sleep(Duration::from_millis(50)).await; | |
| 61 | + } | |
| 62 | + }) | |
| 63 | + .await | |
| 64 | + .expect("fin d'exécution"); | |
| 65 | +} | |
| 66 | + | |
| 67 | +// --- E-010 ------------------------------------------------------------------------------ | |
| 68 | + | |
| 69 | +#[tokio::test] | |
| 70 | +async fn e010_le_recapitulatif_exige_un_parcours_complet() { | |
| 71 | + let banc = banc(); | |
| 72 | + let (cookie, csrf) = session_assistant(&banc).await; | |
| 73 | + send(&banc.router, post_form("/install/commencer", &cookie, Some(&csrf), "")).await; | |
| 74 | + let (res, _) = send(&banc.router, get_avec("/install/recapitulatif", &cookie)).await; | |
| 75 | + assert_eq!(res.status(), StatusCode::SEE_OTHER); | |
| 76 | + assert_eq!(header(&res, "location"), "/install/organisation"); | |
| 77 | +} | |
| 78 | + | |
| 79 | +#[tokio::test] | |
| 80 | +async fn e010_le_recapitulatif_resume_sans_secret_et_propose_de_modifier() { | |
| 81 | + let (banc, cookie, _) = pret("reussite").await; | |
| 82 | + let (res, page) = send(&banc.router, get_avec("/install/recapitulatif", &cookie)).await; | |
| 83 | + assert_eq!(res.status(), StatusCode::OK); | |
| 84 | + assert!(page.contains("exemple.fr") && page.contains("jean.dupont"), "{page}"); | |
| 85 | + assert!(page.contains(r#"href="/install/organisation?retour=recapitulatif""#)); | |
| 86 | + assert!(page.contains("Autorité interne"), "avertissement sur l'autorité interne"); | |
| 87 | + assert!(page.contains("Annuaire OpenLDAP"), "plan d'exécution"); | |
| 88 | + assert!(!page.contains(URGENCE) && !page.contains(MOT_DE_PASSE)); | |
| 89 | + assert!(page.contains("Défini ✓")); | |
| 90 | +} | |
| 91 | + | |
| 92 | +#[tokio::test] | |
| 93 | +async fn e010_openiam_yaml_se_telecharge_sans_secret() { | |
| 94 | + let (banc, cookie, _) = pret("reussite").await; | |
| 95 | + let (res, yaml) = send(&banc.router, get_avec("/install/openiam.yaml", &cookie)).await; | |
| 96 | + assert_eq!(res.status(), StatusCode::OK); | |
| 97 | + assert!(header(&res, "content-disposition").contains("openiam-exemple.fr.yaml")); | |
| 98 | + assert!(yaml.contains("domaine: exemple.fr")); | |
| 99 | + assert!(!yaml.contains(URGENCE) && !yaml.contains(MOT_DE_PASSE)); | |
| 100 | +} | |
| 101 | + | |
| 102 | +#[tokio::test] | |
| 103 | +async fn e010_le_lancement_exige_la_verification_prealable() { | |
| 104 | + let (banc, cookie, csrf) = pret("reussite").await; | |
| 105 | + let (_, page) = send(&banc.router, get_avec("/install/recapitulatif", &cookie)).await; | |
| 106 | + assert!(page.contains(r#"id="lancer""#) && page.contains("Faites d'abord la vérification"), "{page}"); | |
| 107 | + let res = lancer(&banc, &cookie, &csrf).await; | |
| 108 | + assert_eq!(res.status(), StatusCode::CONFLICT); | |
| 109 | + | |
| 110 | + let fragment = verifier(&banc, &cookie, &csrf).await; | |
| 111 | + assert!(fragment.contains(r#"hx-swap-oob="true""#), "le bouton est réactivé hors bande : {fragment}"); | |
| 112 | + let res = lancer(&banc, &cookie, &csrf).await; | |
| 113 | + assert_eq!(res.status(), StatusCode::NO_CONTENT); | |
| 114 | + assert_eq!(header(&res, "hx-redirect"), "/install/execution"); | |
| 115 | + attendre_fin(&banc).await; | |
| 116 | +} | |
| 117 | + | |
| 118 | +// --- E-011 ------------------------------------------------------------------------------ | |
| 119 | + | |
| 120 | +#[tokio::test] | |
| 121 | +async fn e011_le_flux_rejoue_les_evenements_et_la_fin() { | |
| 122 | + let (banc, cookie, csrf) = pret("reussite").await; | |
| 123 | + verifier(&banc, &cookie, &csrf).await; | |
| 124 | + lancer(&banc, &cookie, &csrf).await; | |
| 125 | + attendre_fin(&banc).await; | |
| 126 | + | |
| 127 | + let (res, page) = send(&banc.router, get_avec("/install/execution", &cookie)).await; | |
| 128 | + assert_eq!(res.status(), StatusCode::OK); | |
| 129 | + assert!(!page.contains("sse-connect"), "plus de flux une fois l'exécution terminée"); | |
| 130 | + assert!(page.contains(r#"role="log""#)); | |
| 131 | + assert!(page.contains("Annuaire OpenLDAP")); | |
| 132 | + assert!(page.contains("Installer les paquets de base"), "journal rendu côté serveur"); | |
| 133 | + | |
| 134 | + let (res, flux) = send(&banc.router, get_avec("/install/execution/flux", &cookie)).await; | |
| 135 | + assert!(header(&res, "content-type").starts_with("text/event-stream")); | |
| 136 | + assert!(flux.contains("event: ligne"), "{flux}"); | |
| 137 | + assert!(flux.contains("Installer les paquets de base")); | |
| 138 | + assert!(flux.contains("event: fin")); | |
| 139 | + assert!(flux.contains("id: 1")); | |
| 140 | +} | |
| 141 | + | |
| 142 | +#[tokio::test] | |
| 143 | +async fn e011_pendant_l_execution_la_page_suit_le_flux_et_l_interruption_aboutit() { | |
| 144 | + let (banc, cookie, csrf) = pret("long").await; | |
| 145 | + verifier(&banc, &cookie, &csrf).await; | |
| 146 | + lancer(&banc, &cookie, &csrf).await; | |
| 147 | + let (_, page) = send(&banc.router, get_avec("/install/execution", &cookie)).await; | |
| 148 | + assert!(page.contains(r#"sse-connect="/install/execution/flux""#), "{page}"); | |
| 149 | + assert!(page.contains("Interrompre")); | |
| 150 | + let (res, _) = | |
| 151 | + send(&banc.router, post_form("/install/execution/interrompre", &cookie, Some(&csrf), "")).await; | |
| 152 | + assert_eq!(res.status(), StatusCode::ACCEPTED); | |
| 153 | + attendre_fin(&banc).await; | |
| 154 | + let (_, page) = send(&banc.router, get_avec("/install/execution", &cookie)).await; | |
| 155 | + assert!(page.contains("Installation interrompue"), "{page}"); | |
| 156 | + assert!(!banc.etat.installe()); | |
| 157 | +} | |
| 158 | + | |
| 159 | +#[tokio::test] | |
| 160 | +async fn e011_une_reconnexion_reprend_apres_le_dernier_evenement_recu() { | |
| 161 | + let (banc, cookie, csrf) = pret("reussite").await; | |
| 162 | + verifier(&banc, &cookie, &csrf).await; | |
| 163 | + lancer(&banc, &cookie, &csrf).await; | |
| 164 | + attendre_fin(&banc).await; | |
| 165 | + let mut req = get_avec("/install/execution/flux", &cookie); | |
| 166 | + req.headers_mut().insert("last-event-id", "3".parse().unwrap()); | |
| 167 | + let (_, flux) = send(&banc.router, req).await; | |
| 168 | + assert!(!flux.contains("id: 3\n"), "{flux}"); | |
| 169 | + assert!(flux.contains("id: 4\n"), "{flux}"); | |
| 170 | +} | |
| 171 | + | |
| 172 | +#[tokio::test] | |
| 173 | +async fn e011_un_echec_indique_la_tache_et_permet_de_relancer_sans_verrouiller() { | |
| 174 | + let (banc, cookie, csrf) = pret("echec").await; | |
| 175 | + verifier(&banc, &cookie, &csrf).await; | |
| 176 | + lancer(&banc, &cookie, &csrf).await; | |
| 177 | + attendre_fin(&banc).await; | |
| 178 | + let (_, page) = send(&banc.router, get_avec("/install/execution", &cookie)).await; | |
| 179 | + assert!(page.contains("No package matching"), "{page}"); | |
| 180 | + assert!(page.contains("Relancer")); | |
| 181 | + assert!(!banc.etat.installe()); | |
| 182 | +} | |
| 183 | + | |
| 184 | +#[tokio::test] | |
| 185 | +async fn e011_le_journal_se_telecharge_avec_les_secrets_masques() { | |
| 186 | + // Le faux Ansible écrit le mot de passe d'urgence dans sa sortie. | |
| 187 | + let (banc, cookie, csrf) = pret_avec("secret", vec![("OIAM_FAUX_SECRET".into(), URGENCE.into())]).await; | |
| 188 | + verifier(&banc, &cookie, &csrf).await; | |
| 189 | + lancer(&banc, &cookie, &csrf).await; | |
| 190 | + attendre_fin(&banc).await; | |
| 191 | + let (res, journal) = send(&banc.router, get_avec("/install/execution/journal.txt", &cookie)).await; | |
| 192 | + assert_eq!(res.status(), StatusCode::OK); | |
| 193 | + assert!(journal.contains("avertissement contenant"), "{journal}"); | |
| 194 | + assert!(!journal.contains(URGENCE), "{journal}"); | |
| 195 | +} | |
| 196 | + | |
| 197 | +// --- E-012 ------------------------------------------------------------------------------ | |
| 198 | + | |
| 199 | +#[tokio::test] | |
| 200 | +async fn e012_le_succes_ecrit_le_recapitulatif_protege_et_verrouille() { | |
| 201 | + use std::os::unix::fs::PermissionsExt; | |
| 202 | + let (banc, cookie, csrf) = pret("reussite").await; | |
| 203 | + verifier(&banc, &cookie, &csrf).await; | |
| 204 | + lancer(&banc, &cookie, &csrf).await; | |
| 205 | + attendre_fin(&banc).await; | |
| 206 | + | |
| 207 | + assert!(banc.etat.installe(), "verrou créé à la fin du run, sans attendre E-012"); | |
| 208 | + let dossier = banc.racine().join("home/open-iam"); | |
| 209 | + assert_eq!(std::fs::metadata(&dossier).unwrap().permissions().mode() & 0o777, 0o700); | |
| 210 | + let fichier = std::fs::read_dir(&dossier).unwrap().next().unwrap().unwrap().path(); | |
| 211 | + assert!(fichier.file_name().unwrap().to_string_lossy().starts_with("open-iam-exemple.fr-")); | |
| 212 | + assert_eq!(std::fs::metadata(&fichier).unwrap().permissions().mode() & 0o777, 0o600); | |
| 213 | + let contenu = std::fs::read_to_string(&fichier).unwrap(); | |
| 214 | + assert!(contenu.contains(URGENCE), "le mot de passe d'urgence est dans le récapitulatif"); | |
| 215 | + assert!(contenu.contains("ldaps://annuaire.exemple.fr")); | |
| 216 | + assert!(contenu.contains("domaine: exemple.fr"), "openiam.yaml inclus"); | |
| 217 | + | |
| 218 | + let (res, page) = send(&banc.router, get_avec("/install/resultat", &cookie)).await; | |
| 219 | + assert_eq!(res.status(), StatusCode::OK, "la session qui a lancé voit le résultat"); | |
| 220 | + assert!(page.contains(&fichier.display().to_string()), "chemin du fichier affiché"); | |
| 221 | + assert!(page.contains(URGENCE), "secret généré affiché une fois"); | |
| 222 | + assert_eq!(header(&res, "cache-control"), "no-store"); | |
| 223 | +} | |
| 224 | + | |
| 225 | +#[tokio::test] | |
| 226 | +async fn e012_une_autre_session_et_l_apres_terminer_sont_verrouilles() { | |
| 227 | + let (banc, cookie, csrf) = pret("reussite").await; | |
| 228 | + verifier(&banc, &cookie, &csrf).await; | |
| 229 | + lancer(&banc, &cookie, &csrf).await; | |
| 230 | + attendre_fin(&banc).await; | |
| 231 | + | |
| 232 | + let (res, _) = send(&banc.router, get("/verrouille")).await; | |
| 233 | + let autre = nouveau_cookie(&res).expect("session ouverte sur /verrouille"); | |
| 234 | + let (res, _) = send(&banc.router, get_avec("/install/resultat", &autre)).await; | |
| 235 | + assert_eq!(header(&res, "location"), "/verrouille"); | |
| 236 | + | |
| 237 | + let (res, _) = | |
| 238 | + send(&banc.router, post_form("/install/terminer", &cookie, Some(&csrf), "conserve=on")).await; | |
| 239 | + assert_eq!(header(&res, "hx-redirect"), "/verrouille"); | |
| 240 | + let (res, _) = send(&banc.router, get_avec("/install/resultat", &cookie)).await; | |
| 241 | + assert_eq!(header(&res, "location"), "/verrouille"); | |
| 242 | + assert!(!banc.etat_dir().join("draft-secrets.yaml").exists(), "secrets du brouillon purgés"); | |
| 243 | +} | |
| 244 | + | |
| 245 | +#[tokio::test] | |
| 246 | +async fn e012_terminer_exige_d_avoir_conserve_les_identifiants() { | |
| 247 | + let (banc, cookie, csrf) = pret("reussite").await; | |
| 248 | + verifier(&banc, &cookie, &csrf).await; | |
| 249 | + lancer(&banc, &cookie, &csrf).await; | |
| 250 | + attendre_fin(&banc).await; | |
| 251 | + let (res, _) = send(&banc.router, post_form("/install/terminer", &cookie, Some(&csrf), "")).await; | |
| 252 | + assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); | |
| 253 | +} |
A
installer/tests/runner.rs
+254
-0
@@ -0,0 +1,254 @@
| 1 | +//! OI-036 — runner : lancement d'ansible-playbook, événements, journal sur disque, flux, | |
| 2 | +//! verrou d'exécution. Ansible est remplacé par les scripts de tests/faux/. | |
| 3 | + | |
| 4 | +use std::{path::PathBuf, sync::Arc, time::Duration}; | |
| 5 | + | |
| 6 | +use open_iam_installer::{ | |
| 7 | + config::{Secret, Secrets}, | |
| 8 | + runner::{Evenement, Outils, Runner, StatutExecution}, | |
| 9 | +}; | |
| 10 | + | |
| 11 | +fn faux(nom: &str) -> PathBuf { | |
| 12 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/faux").join(nom) | |
| 13 | +} | |
| 14 | + | |
| 15 | +const SECRET: &str = "Urgence-Tres-Secret-2026!"; | |
| 16 | + | |
| 17 | +fn secrets() -> Secrets { | |
| 18 | + Secrets { ldap_admin_mot_de_passe: Some(Secret::new(SECRET)), ..Default::default() } | |
| 19 | +} | |
| 20 | + | |
| 21 | +struct Banc { | |
| 22 | + _dossier: tempfile::TempDir, | |
| 23 | + runner: Arc<Runner>, | |
| 24 | + trace: PathBuf, | |
| 25 | +} | |
| 26 | + | |
| 27 | +fn banc(scenario: &str) -> Banc { | |
| 28 | + let dossier = tempfile::tempdir().unwrap(); | |
| 29 | + let trace = dossier.path().join("trace.txt"); | |
| 30 | + let outils = Outils { | |
| 31 | + ansible_playbook: faux("ansible-playbook"), | |
| 32 | + ansible_vault: faux("ansible-vault"), | |
| 33 | + environnement: vec![ | |
| 34 | + ("OIAM_FAUX_SCENARIO".into(), scenario.into()), | |
| 35 | + ("OIAM_FAUX_TRACE".into(), trace.display().to_string()), | |
| 36 | + ("OIAM_FAUX_SECRET".into(), SECRET.into()), | |
| 37 | + ], | |
| 38 | + }; | |
| 39 | + let runner = Arc::new(Runner::new(dossier.path().join("etat"), outils).unwrap()); | |
| 40 | + Banc { _dossier: dossier, runner, trace } | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// Lance une exécution et attend sa fin ; renvoie tous les événements dans l'ordre. | |
| 44 | +async fn executer(banc: &Banc) -> Vec<(u64, Evenement)> { | |
| 45 | + let config = | |
| 46 | + open_iam_installer::config::OpenIamConfig::depuis_yaml(include_str!("donnees/openiam.yaml")).unwrap(); | |
| 47 | + let id = banc.runner.lancer(&config, &secrets(), |_| Ok(())).await.unwrap(); | |
| 48 | + attendre_fin(&banc.runner, &id).await | |
| 49 | +} | |
| 50 | + | |
| 51 | +async fn attendre_fin(runner: &Runner, id: &str) -> Vec<(u64, Evenement)> { | |
| 52 | + tokio::time::timeout(Duration::from_secs(20), async { | |
| 53 | + loop { | |
| 54 | + let evenements = runner.historique(id, 0).unwrap(); | |
| 55 | + if evenements.iter().any(|(_, e)| matches!(e, Evenement::Fin { .. })) { | |
| 56 | + return evenements; | |
| 57 | + } | |
| 58 | + tokio::time::sleep(Duration::from_millis(50)).await; | |
| 59 | + } | |
| 60 | + }) | |
| 61 | + .await | |
| 62 | + .expect("l'exécution aurait dû se terminer") | |
| 63 | +} | |
| 64 | + | |
| 65 | +fn fin(evenements: &[(u64, Evenement)]) -> &Evenement { | |
| 66 | + &evenements.last().unwrap().1 | |
| 67 | +} | |
| 68 | + | |
| 69 | +#[tokio::test] | |
| 70 | +async fn une_execution_reussie_produit_les_lignes_la_progression_et_la_fin() { | |
| 71 | + let banc = banc("reussite"); | |
| 72 | + let evenements = executer(&banc).await; | |
| 73 | + | |
| 74 | + let lignes: Vec<_> = evenements | |
| 75 | + .iter() | |
| 76 | + .filter_map(|(_, e)| match e { | |
| 77 | + Evenement::Ligne { tache, statut, phase, .. } => { | |
| 78 | + Some((phase.as_str(), tache.as_str(), statut.as_str())) | |
| 79 | + } | |
| 80 | + _ => None, | |
| 81 | + }) | |
| 82 | + .collect(); | |
| 83 | + assert_eq!(lignes.len(), 4); | |
| 84 | + assert_eq!(lignes[0], ("Préparation du système", "Installer les paquets de base", "changed")); | |
| 85 | + assert_eq!(lignes[2].0, "Annuaire OpenLDAP"); | |
| 86 | + | |
| 87 | + let progression = evenements | |
| 88 | + .iter() | |
| 89 | + .rev() | |
| 90 | + .find_map(|(_, e)| match e { | |
| 91 | + Evenement::Progression { faites, total } => Some((*faites, *total)), | |
| 92 | + _ => None, | |
| 93 | + }) | |
| 94 | + .unwrap(); | |
| 95 | + assert_eq!(progression, (4, 4)); | |
| 96 | + assert!(matches!(fin(&evenements), Evenement::Fin { statut: StatutExecution::Reussie, .. })); | |
| 97 | + | |
| 98 | + let ids: Vec<u64> = evenements.iter().map(|(id, _)| *id).collect(); | |
| 99 | + assert!(ids.windows(2).all(|w| w[1] == w[0] + 1), "identifiants consécutifs : {ids:?}"); | |
| 100 | +} | |
| 101 | + | |
| 102 | +#[tokio::test] | |
| 103 | +async fn ansible_est_lance_avec_le_callback_open_iam_et_le_coffre() { | |
| 104 | + let banc = banc("reussite"); | |
| 105 | + executer(&banc).await; | |
| 106 | + let trace = std::fs::read_to_string(&banc.trace).unwrap(); | |
| 107 | + assert!(trace.contains("callback=open_iam"), "{trace}"); | |
| 108 | + assert!(trace.contains("site.yml"), "{trace}"); | |
| 109 | + assert!(trace.contains("--vault-password-file"), "{trace}"); | |
| 110 | + assert!(trace.contains("--inventory"), "{trace}"); | |
| 111 | + assert!(trace.contains("locale=C.UTF-8"), "locale indépendante de celle de l'administrateur : {trace}"); | |
| 112 | +} | |
| 113 | + | |
| 114 | +#[tokio::test] | |
| 115 | +async fn l_arborescence_ansible_et_l_inventaire_local_sont_prepares() { | |
| 116 | + let banc = banc("reussite"); | |
| 117 | + executer(&banc).await; | |
| 118 | + let derniere = banc.runner.derniere().unwrap(); | |
| 119 | + let dossier = banc.runner.dossier_execution(&derniere.id); | |
| 120 | + assert!(dossier.join("ansible/site.yml").is_file()); | |
| 121 | + assert!(dossier.join("ansible/callback_plugins/open_iam.py").is_file()); | |
| 122 | + assert!(dossier.join("ansible/roles/openldap_ltb/tasks/main.yml").is_file()); | |
| 123 | + assert!(!dossier.join("ansible/molecule").exists(), "les scénarios de test ne sont pas embarqués"); | |
| 124 | + | |
| 125 | + let inventaire = std::fs::read_to_string(dossier.join("inventaire/hosts.yml")).unwrap(); | |
| 126 | + assert!(inventaire.contains("ansible_connection: local"), "{inventaire}"); | |
| 127 | + let vars = std::fs::read_to_string(dossier.join("inventaire/group_vars/all/config.yml")).unwrap(); | |
| 128 | + assert!(vars.contains("oiam_base_dn: dc=exemple,dc=fr"), "{vars}"); | |
| 129 | +} | |
| 130 | + | |
| 131 | +#[tokio::test] | |
| 132 | +async fn les_secrets_sont_chiffres_sur_disque() { | |
| 133 | + let banc = banc("reussite"); | |
| 134 | + executer(&banc).await; | |
| 135 | + let derniere = banc.runner.derniere().unwrap(); | |
| 136 | + let chiffre = std::fs::read_to_string( | |
| 137 | + banc.runner.dossier_execution(&derniere.id).join("inventaire/group_vars/all/secrets.yml"), | |
| 138 | + ) | |
| 139 | + .unwrap(); | |
| 140 | + assert!(chiffre.starts_with("$ANSIBLE_VAULT;"), "{chiffre}"); | |
| 141 | + assert!(!chiffre.contains(SECRET)); | |
| 142 | +} | |
| 143 | + | |
| 144 | +#[tokio::test] | |
| 145 | +async fn une_execution_en_echec_indique_la_tache_en_cause() { | |
| 146 | + let banc = banc("echec"); | |
| 147 | + let evenements = executer(&banc).await; | |
| 148 | + match fin(&evenements) { | |
| 149 | + Evenement::Fin { statut: StatutExecution::Echouee, message: Some(message) } => { | |
| 150 | + assert!(message.contains("Installer les paquets OpenLDAP LTB"), "{message}"); | |
| 151 | + assert!(message.contains("No package matching"), "{message}"); | |
| 152 | + } | |
| 153 | + autre => panic!("fin inattendue : {autre:?}"), | |
| 154 | + } | |
| 155 | + assert_eq!(banc.runner.derniere().unwrap().statut, StatutExecution::Echouee); | |
| 156 | +} | |
| 157 | + | |
| 158 | +#[tokio::test] | |
| 159 | +async fn aucun_secret_n_apparait_dans_le_journal_ni_les_evenements() { | |
| 160 | + let banc = banc("secret"); | |
| 161 | + let evenements = executer(&banc).await; | |
| 162 | + let texte = format!("{evenements:?}"); | |
| 163 | + assert!(!texte.contains(SECRET), "{texte}"); | |
| 164 | + assert!(texte.contains("••••••"), "le secret doit être remplacé par un masque"); | |
| 165 | + | |
| 166 | + let derniere = banc.runner.derniere().unwrap(); | |
| 167 | + let journal = banc.runner.journal_texte(&derniere.id).unwrap(); | |
| 168 | + assert!(!journal.contains(SECRET)); | |
| 169 | + assert!(journal.contains("avertissement contenant"), "les lignes brutes sont conservées : {journal}"); | |
| 170 | +} | |
| 171 | + | |
| 172 | +#[tokio::test] | |
| 173 | +async fn une_seconde_execution_simultanee_est_refusee() { | |
| 174 | + let banc = banc("long"); | |
| 175 | + let config = | |
| 176 | + open_iam_installer::config::OpenIamConfig::depuis_yaml(include_str!("donnees/openiam.yaml")).unwrap(); | |
| 177 | + let id = banc.runner.lancer(&config, &secrets(), |_| Ok(())).await.unwrap(); | |
| 178 | + let seconde = banc.runner.lancer(&config, &secrets(), |_| Ok(())).await; | |
| 179 | + assert!(seconde.is_err(), "une exécution est déjà en cours"); | |
| 180 | + banc.runner.interrompre().unwrap(); | |
| 181 | + attendre_fin(&banc.runner, &id).await; | |
| 182 | +} | |
| 183 | + | |
| 184 | +#[tokio::test] | |
| 185 | +async fn l_interruption_termine_l_execution_en_statut_interrompu() { | |
| 186 | + let banc = banc("long"); | |
| 187 | + let config = | |
| 188 | + open_iam_installer::config::OpenIamConfig::depuis_yaml(include_str!("donnees/openiam.yaml")).unwrap(); | |
| 189 | + let id = banc.runner.lancer(&config, &secrets(), |_| Ok(())).await.unwrap(); | |
| 190 | + tokio::time::sleep(Duration::from_millis(300)).await; | |
| 191 | + banc.runner.interrompre().unwrap(); | |
| 192 | + let evenements = attendre_fin(&banc.runner, &id).await; | |
| 193 | + assert!(matches!(fin(&evenements), Evenement::Fin { statut: StatutExecution::Interrompue, .. })); | |
| 194 | +} | |
| 195 | + | |
| 196 | +#[tokio::test] | |
| 197 | +async fn une_reconnexion_rejoue_les_evenements_manquants_sans_doublon() { | |
| 198 | + let banc = banc("reussite"); | |
| 199 | + let evenements = executer(&banc).await; | |
| 200 | + let id = banc.runner.derniere().unwrap().id; | |
| 201 | + let depuis = evenements[2].0; | |
| 202 | + let suite = banc.runner.historique(&id, depuis).unwrap(); | |
| 203 | + assert_eq!(suite.first().unwrap().0, depuis + 1); | |
| 204 | + assert_eq!(suite.len(), evenements.len() - 3); | |
| 205 | +} | |
| 206 | + | |
| 207 | +#[tokio::test] | |
| 208 | +async fn un_abonne_recoit_les_evenements_en_direct() { | |
| 209 | + let banc = banc("long"); | |
| 210 | + let config = | |
| 211 | + open_iam_installer::config::OpenIamConfig::depuis_yaml(include_str!("donnees/openiam.yaml")).unwrap(); | |
| 212 | + let id = banc.runner.lancer(&config, &secrets(), |_| Ok(())).await.unwrap(); | |
| 213 | + let mut flux = banc.runner.abonner().expect("exécution en cours"); | |
| 214 | + banc.runner.interrompre().unwrap(); | |
| 215 | + let recu = tokio::time::timeout(Duration::from_secs(10), async { | |
| 216 | + loop { | |
| 217 | + if let Ok((_, Evenement::Fin { .. })) = flux.recv().await { | |
| 218 | + return true; | |
| 219 | + } | |
| 220 | + } | |
| 221 | + }) | |
| 222 | + .await | |
| 223 | + .unwrap(); | |
| 224 | + assert!(recu); | |
| 225 | + attendre_fin(&banc.runner, &id).await; | |
| 226 | +} | |
| 227 | + | |
| 228 | +#[tokio::test] | |
| 229 | +async fn la_finalisation_n_est_appelee_qu_en_cas_de_succes_et_son_echec_fait_echouer() { | |
| 230 | + let banc = banc("reussite"); | |
| 231 | + let config = | |
| 232 | + open_iam_installer::config::OpenIamConfig::depuis_yaml(include_str!("donnees/openiam.yaml")).unwrap(); | |
| 233 | + let id = banc.runner.lancer(&config, &secrets(), |_| Err("disque plein".into())).await.unwrap(); | |
| 234 | + let evenements = attendre_fin(&banc.runner, &id).await; | |
| 235 | + assert!( | |
| 236 | + matches!(fin(&evenements), Evenement::Fin { statut: StatutExecution::Echouee, message: Some(m) } if m.contains("disque plein")) | |
| 237 | + ); | |
| 238 | +} | |
| 239 | + | |
| 240 | +#[tokio::test] | |
| 241 | +async fn une_execution_orpheline_est_marquee_interrompue_au_redemarrage() { | |
| 242 | + let dossier = tempfile::tempdir().unwrap(); | |
| 243 | + let racine = dossier.path().join("etat"); | |
| 244 | + let orpheline = racine.join("executions/20261101-120000-000"); | |
| 245 | + std::fs::create_dir_all(&orpheline).unwrap(); | |
| 246 | + std::fs::write( | |
| 247 | + orpheline.join("etat.json"), | |
| 248 | + r#"{"id":"20261101-120000-000","statut":"en_cours","debut":"2026-11-01T12:00:00+01:00","fin":null,"phases":[]}"#, | |
| 249 | + ) | |
| 250 | + .unwrap(); | |
| 251 | + let runner = Runner::new(&racine, Outils::default()).unwrap(); | |
| 252 | + let derniere = runner.derniere().unwrap(); | |
| 253 | + assert_eq!(derniere.statut, StatutExecution::Interrompue); | |
| 254 | +} |
M
installer/tests/socle.rs
+25
-17
@@ -7,7 +7,8 @@ use axum::{
| 7 | 7 | http::{Request, Response, StatusCode, header}, |
| 8 | 8 | }; |
| 9 | 9 | use http_body_util::BodyExt; |
| 10 | -use open_iam_installer::app; | |
| 10 | +mod commun; | |
| 11 | + | |
| 11 | 12 | use tower::ServiceExt; |
| 12 | 13 | |
| 13 | 14 | const CSP: &str = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; \ |
@@ -31,7 +32,7 @@ fn header<'a>(res: &'a Response<Body>, name: &str) -> &'a str {
| 31 | 32 | |
| 32 | 33 | /// Ouvre une session : renvoie le cookie et le jeton CSRF lus dans la page d'accueil. |
| 33 | 34 | async fn session(router: &Router) -> (String, String) { |
| 34 | - let (res, body) = send(router, get("/")).await; | |
| 35 | + let (res, body) = send(router, get("/acces")).await; | |
| 35 | 36 | let cookie = header(&res, "set-cookie").split(';').next().unwrap().to_owned(); |
| 36 | 37 | let hx_headers: serde_json::Value = serde_json::from_str(&attribute(&body, "hx-headers")).unwrap(); |
| 37 | 38 | let token = hx_headers["X-CSRF-Token"].as_str().expect("jeton CSRF dans hx-headers").to_owned(); |
@@ -59,8 +60,9 @@ fn post_form(uri: &str, cookie: &str, token: Option<&str>, form: &str) -> Reques
| 59 | 60 | |
| 60 | 61 | #[tokio::test] |
| 61 | 62 | async fn la_page_d_accueil_porte_les_en_tetes_de_securite() { |
| 62 | - let router = app(); | |
| 63 | - let (res, body) = send(&router, get("/")).await; | |
| 63 | + let banc = commun::banc(); | |
| 64 | + let router = banc.router.clone(); | |
| 65 | + let (res, body) = send(&router, get("/acces")).await; | |
| 64 | 66 | |
| 65 | 67 | assert_eq!(res.status(), StatusCode::OK); |
| 66 | 68 | assert_eq!(header(&res, "content-security-policy"), CSP); |
@@ -74,7 +76,7 @@ async fn la_page_d_accueil_porte_les_en_tetes_de_securite() {
| 74 | 76 | |
| 75 | 77 | #[tokio::test] |
| 76 | 78 | async fn la_page_n_a_ni_script_ni_style_en_ligne() { |
| 77 | - let (_, body) = send(&app(), get("/")).await; | |
| 79 | + let (_, body) = send(&commun::banc().router, get("/acces")).await; | |
| 78 | 80 | for (i, _) in body.match_indices("<script") { |
| 79 | 81 | let tag = &body[i..body[i..].find('>').unwrap() + i]; |
| 80 | 82 | assert!(tag.contains(" src=\"/static/"), "script en ligne : {tag}"); |
@@ -86,7 +88,7 @@ async fn la_page_n_a_ni_script_ni_style_en_ligne() {
| 86 | 88 | |
| 87 | 89 | #[tokio::test] |
| 88 | 90 | async fn la_session_utilise_un_cookie_strict_et_httponly() { |
| 89 | - let (res, _) = send(&app(), get("/")).await; | |
| 91 | + let (res, _) = send(&commun::banc().router, get("/acces")).await; | |
| 90 | 92 | let cookie = header(&res, "set-cookie"); |
| 91 | 93 | assert!(cookie.starts_with("oiam_session="), "{cookie}"); |
| 92 | 94 | assert!(cookie.contains("HttpOnly"), "{cookie}"); |
@@ -95,7 +97,7 @@ async fn la_session_utilise_un_cookie_strict_et_httponly() {
| 95 | 97 | |
| 96 | 98 | #[tokio::test] |
| 97 | 99 | async fn la_configuration_htmx_interdit_eval_et_rend_les_422() { |
| 98 | - let (_, body) = send(&app(), get("/")).await; | |
| 100 | + let (_, body) = send(&commun::banc().router, get("/acces")).await; | |
| 99 | 101 | let meta = &body[body.find(r#"<meta name="htmx-config""#).expect("meta htmx-config")..]; |
| 100 | 102 | let json: serde_json::Value = serde_json::from_str(&attribute(meta, "content")).unwrap(); |
| 101 | 103 | assert_eq!(json["allowEval"], false); |
@@ -108,7 +110,8 @@ async fn la_configuration_htmx_interdit_eval_et_rend_les_422() {
| 108 | 110 | |
| 109 | 111 | #[tokio::test] |
| 110 | 112 | async fn un_post_sans_jeton_csrf_est_refuse() { |
| 111 | - let router = app(); | |
| 113 | + let banc = commun::banc(); | |
| 114 | + let router = banc.router.clone(); | |
| 112 | 115 | let (cookie, _) = session(&router).await; |
| 113 | 116 | let (res, _) = send(&router, post_form("/dev/formulaire", &cookie, None, "domaine=a.fr")).await; |
| 114 | 117 | assert_eq!(res.status(), StatusCode::FORBIDDEN); |
@@ -116,7 +119,8 @@ async fn un_post_sans_jeton_csrf_est_refuse() {
| 116 | 119 | |
| 117 | 120 | #[tokio::test] |
| 118 | 121 | async fn un_post_avec_un_mauvais_jeton_csrf_est_refuse() { |
| 119 | - let router = app(); | |
| 122 | + let banc = commun::banc(); | |
| 123 | + let router = banc.router.clone(); | |
| 120 | 124 | let (cookie, _) = session(&router).await; |
| 121 | 125 | let req = post_form("/dev/formulaire", &cookie, Some("faux"), "domaine=a.fr"); |
| 122 | 126 | let (res, _) = send(&router, req).await; |
@@ -126,13 +130,14 @@ async fn un_post_avec_un_mauvais_jeton_csrf_est_refuse() {
| 126 | 130 | #[tokio::test] |
| 127 | 131 | async fn un_post_sans_session_est_refuse() { |
| 128 | 132 | let req = post_form("/dev/formulaire", "oiam_session=inconnue", Some("x"), "domaine=a.fr"); |
| 129 | - let (res, _) = send(&app(), req).await; | |
| 133 | + let (res, _) = send(&commun::banc().router, req).await; | |
| 130 | 134 | assert_eq!(res.status(), StatusCode::FORBIDDEN); |
| 131 | 135 | } |
| 132 | 136 | |
| 133 | 137 | #[tokio::test] |
| 134 | 138 | async fn une_saisie_invalide_renvoie_422_et_le_formulaire_avec_ses_erreurs() { |
| 135 | - let router = app(); | |
| 139 | + let banc = commun::banc(); | |
| 140 | + let router = banc.router.clone(); | |
| 136 | 141 | let (cookie, token) = session(&router).await; |
| 137 | 142 | let req = post_form("/dev/formulaire", &cookie, Some(&token), "domaine=sans-point"); |
| 138 | 143 | let (res, body) = send(&router, req).await; |
@@ -146,7 +151,8 @@ async fn une_saisie_invalide_renvoie_422_et_le_formulaire_avec_ses_erreurs() {
| 146 | 151 | |
| 147 | 152 | #[tokio::test] |
| 148 | 153 | async fn une_saisie_valide_renvoie_204_et_un_toast_de_succes() { |
| 149 | - let router = app(); | |
| 154 | + let banc = commun::banc(); | |
| 155 | + let router = banc.router.clone(); | |
| 150 | 156 | let (cookie, token) = session(&router).await; |
| 151 | 157 | let req = post_form("/dev/formulaire", &cookie, Some(&token), "domaine=exemple.fr"); |
| 152 | 158 | let (res, _) = send(&router, req).await; |
@@ -159,7 +165,7 @@ async fn une_saisie_valide_renvoie_204_et_un_toast_de_succes() {
| 159 | 165 | #[tokio::test] |
| 160 | 166 | async fn une_erreur_serveur_htmx_declenche_un_toast_d_erreur() { |
| 161 | 167 | let req = Request::get("/dev/erreur").header("hx-request", "true").body(Body::empty()).unwrap(); |
| 162 | - let (res, _) = send(&app(), req).await; | |
| 168 | + let (res, _) = send(&commun::banc().router, req).await; | |
| 163 | 169 | assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); |
| 164 | 170 | let trigger: serde_json::Value = serde_json::from_str(header(&res, "hx-trigger")).unwrap(); |
| 165 | 171 | assert_eq!(trigger["notify"]["type"], "error"); |
@@ -167,7 +173,7 @@ async fn une_erreur_serveur_htmx_declenche_un_toast_d_erreur() {
| 167 | 173 | |
| 168 | 174 | #[tokio::test] |
| 169 | 175 | async fn une_erreur_serveur_hors_htmx_affiche_une_page_d_erreur() { |
| 170 | - let (res, body) = send(&app(), get("/dev/erreur")).await; | |
| 176 | + let (res, body) = send(&commun::banc().router, get("/dev/erreur")).await; | |
| 171 | 177 | assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); |
| 172 | 178 | assert!(body.contains("<h1")); |
| 173 | 179 | assert_eq!(header(&res, "content-security-policy"), CSP); |
@@ -175,7 +181,7 @@ async fn une_erreur_serveur_hors_htmx_affiche_une_page_d_erreur() {
| 175 | 181 | |
| 176 | 182 | #[tokio::test] |
| 177 | 183 | async fn une_route_inconnue_renvoie_une_page_404() { |
| 178 | - let (res, body) = send(&app(), get("/inconnue")).await; | |
| 184 | + let (res, body) = send(&commun::banc().router, get("/inconnue")).await; | |
| 179 | 185 | assert_eq!(res.status(), StatusCode::NOT_FOUND); |
| 180 | 186 | assert!(body.contains("<h1")); |
| 181 | 187 | assert_eq!(header(&res, "content-security-policy"), CSP); |
@@ -183,7 +189,8 @@ async fn une_route_inconnue_renvoie_une_page_404() {
| 183 | 189 | |
| 184 | 190 | #[tokio::test] |
| 185 | 191 | async fn les_ressources_statiques_sont_servies_depuis_le_binaire() { |
| 186 | - let router = app(); | |
| 192 | + let banc = commun::banc(); | |
| 193 | + let router = banc.router.clone(); | |
| 187 | 194 | let (res, css) = send(&router, get("/static/app.css")).await; |
| 188 | 195 | assert_eq!(res.status(), StatusCode::OK); |
| 189 | 196 | assert!(header(&res, "content-type").starts_with("text/css")); |
@@ -200,7 +207,8 @@ async fn les_ressources_statiques_sont_servies_depuis_le_binaire() {
| 200 | 207 | |
| 201 | 208 | #[tokio::test] |
| 202 | 209 | async fn les_fichiers_internes_ne_sont_pas_servis() { |
| 203 | - let router = app(); | |
| 210 | + let banc = commun::banc(); | |
| 211 | + let router = banc.router.clone(); | |
| 204 | 212 | for path in ["/static/VENDOR.md", "/static/../Cargo.toml", "/static/inexistant.js"] { |
| 205 | 213 | let (res, _) = send(&router, get(path)).await; |
| 206 | 214 | assert_eq!(res.status(), StatusCode::NOT_FOUND, "{path}"); |
M
scripts/ci.sh
+26
-10
@@ -2,7 +2,7 @@
| 2 | 2 | # Intégration continue locale (OI-008). Échoue au premier contrôle en erreur. |
| 3 | 3 | # GitRust n'a pas encore de CI (Q-01) : un futur runner n'aura qu'à appeler ce script (OI-012). |
| 4 | 4 | # |
| 5 | -# Usage : scripts/ci.sh [--sans-navigateur] | |
| 5 | +# Usage : scripts/ci.sh [--sans-navigateur] [--sans-molecule] (Molecule : ~2 min, Docker requis) | |
| 6 | 6 | # Prérequis : cargo, cargo-deny, tailwindcss v4, shellcheck, scripts/dev-setup.sh (ansible-lint), |
| 7 | 7 | # npm install dans tests/navigateur (vérification navigateur). |
| 8 | 8 | set -euo pipefail |
@@ -10,7 +10,14 @@ racine="$(cd "$(dirname "$0")/.." && pwd)"
| 10 | 10 | cd "$racine" |
| 11 | 11 | |
| 12 | 12 | navigateur=1 |
| 13 | -[[ "${1:-}" == "--sans-navigateur" ]] && navigateur=0 | |
| 13 | +molecule=1 | |
| 14 | +for option in "$@"; do | |
| 15 | + case "$option" in | |
| 16 | + --sans-navigateur) navigateur=0 ;; | |
| 17 | + --sans-molecule) molecule=0 ;; | |
| 18 | + *) echo "Option inconnue : $option" >&2; exit 2 ;; | |
| 19 | + esac | |
| 20 | +done | |
| 14 | 21 | |
| 15 | 22 | etape() { printf '\n\033[1m▶ %s\033[0m\n' "$1"; } |
| 16 | 23 |
@@ -38,21 +45,30 @@ shellcheck scripts/*.sh
| 38 | 45 | echo "scripts conformes" |
| 39 | 46 | |
| 40 | 47 | etape "Ansible (ansible-lint)" |
| 41 | -if compgen -G "ansible/**/*.yml" >/dev/null || compgen -G "ansible/*.yml" >/dev/null; then | |
| 42 | - "$racine/.venv/bin/ansible-lint" ansible/ | |
| 43 | -else | |
| 44 | - echo "aucun fichier Ansible pour l'instant : ignoré" | |
| 48 | +# Lancé depuis ansible/ pour lire ansible/.ansible-lint. | |
| 49 | +(cd ansible && "$racine/.venv/bin/ansible-lint") | |
| 50 | + | |
| 51 | +if (( molecule )); then | |
| 52 | + etape "Ansible : recette du socle sur Debian 13 et Ubuntu 26.04 (molecule test -s socle)" | |
| 53 | + (cd ansible && "$racine/.venv/bin/molecule" test -s socle) | |
| 45 | 54 | fi |
| 46 | 55 | |
| 47 | 56 | if (( navigateur )); then |
| 48 | 57 | etape "Navigateur : accessibilité, CSP, HTMX, Alpine (tests/navigateur)" |
| 49 | 58 | port=17070 |
| 50 | 59 | cargo build --quiet -p open-iam-installer |
| 51 | - target/debug/open-iam-installer --listen "127.0.0.1:$port" >/dev/null 2>&1 & | |
| 60 | + # État et dossier personnel temporaires ; prérequis simulés et faux Ansible : rien n'est installé ici. | |
| 61 | + temporaire="$(mktemp -d)" | |
| 62 | + OIAM_DEV_PREREQUIS_SIMULES=1 \ | |
| 63 | + OIAM_DEV_ANSIBLE_PLAYBOOK="$racine/installer/tests/faux/ansible-playbook" \ | |
| 64 | + OIAM_DEV_ANSIBLE_VAULT="$racine/installer/tests/faux/ansible-vault" \ | |
| 65 | + OIAM_FAUX_SCENARIO=reussite HOME="$temporaire" \ | |
| 66 | + target/debug/open-iam-installer --etat "$temporaire/etat" --listen "127.0.0.1:$port" >/dev/null 2>&1 & | |
| 52 | 67 | serveur=$! |
| 53 | - trap 'kill "$serveur" 2>/dev/null || true' EXIT | |
| 54 | - for _ in $(seq 1 50); do curl -fs -o /dev/null "http://127.0.0.1:$port/" && break; sleep 0.2; done | |
| 55 | - node tests/navigateur/verifier.mjs "http://127.0.0.1:$port" | |
| 68 | + trap 'kill "$serveur" 2>/dev/null || true; rm -r -- "$temporaire"' EXIT | |
| 69 | + for _ in $(seq 1 50); do curl -fs -o /dev/null "http://127.0.0.1:$port/acces" && break; sleep 0.2; done | |
| 70 | + jeton="$(target/debug/open-iam-installer --etat "$temporaire/etat" nouveau-jeton | grep -oE 'jeton=[A-Z2-7]+' | cut -d= -f2)" | |
| 71 | + OIAM_JETON="$jeton" node tests/navigateur/verifier.mjs "http://127.0.0.1:$port" | |
| 56 | 72 | fi |
| 57 | 73 | |
| 58 | 74 | printf '\n\033[1;32m✓ CI locale verte\033[0m\n' |
M
scripts/cible.sh
+10
-5
@@ -10,14 +10,19 @@
| 10 | 10 | # Accès : root@127.0.0.1 port 2222 (debian) ou 2223 (ubuntu), clé tests/cible/.ssh/id_ed25519. |
| 11 | 11 | # Inventaire Ansible correspondant : ansible/inventories/dev/hosts.yml. |
| 12 | 12 | # Les conteneurs tournent en --privileged (systemd, nftables) : réservé à un poste de développement. |
| 13 | +# | |
| 14 | +# Variables : OIAM_CIBLE_PREFIXE (défaut oiam-cible) et OIAM_CIBLE_PORT (défaut 2222, ubuntu = +1) | |
| 15 | +# permettent des cibles séparées, par exemple pour Molecule (ansible/molecule/socle). | |
| 13 | 16 | set -euo pipefail |
| 14 | 17 | racine="$(cd "$(dirname "$0")/.." && pwd)" |
| 15 | 18 | dossier="$racine/tests/cible" |
| 16 | 19 | cle="$dossier/.ssh/id_ed25519" |
| 20 | +prefixe="${OIAM_CIBLE_PREFIXE:-oiam-cible}" | |
| 21 | +port_base="${OIAM_CIBLE_PORT:-2222}" | |
| 17 | 22 | |
| 18 | 23 | image() { case "$1" in debian) echo "debian:trixie" ;; ubuntu) echo "ubuntu:26.04" ;; esac; } |
| 19 | -port() { case "$1" in debian) echo 2222 ;; ubuntu) echo 2223 ;; esac; } | |
| 20 | -nom() { echo "oiam-cible-$1"; } | |
| 24 | +port() { case "$1" in debian) echo "$port_base" ;; ubuntu) echo $((port_base + 1)) ;; esac; } | |
| 25 | +nom() { echo "$prefixe-$1"; } | |
| 21 | 26 | cibles() { |
| 22 | 27 | case "${1:-debian}" in |
| 23 | 28 | debian|ubuntu) echo "$1" ;; |
@@ -42,11 +47,11 @@ demarrer() {
| 42 | 47 | local c="$1" |
| 43 | 48 | if existe "$c"; then echo "$(nom "$c") existe déjà (utilisez reinitialiser pour repartir de zéro)."; return; fi |
| 44 | 49 | cle_ssh |
| 45 | - docker build -q --build-arg "BASE=$(image "$c")" -t "$(nom "$c")" "$dossier" >/dev/null | |
| 50 | + docker build -q --build-arg "BASE=$(image "$c")" -t "oiam-cible-$c" "$dossier" >/dev/null | |
| 46 | 51 | docker run -d --name "$(nom "$c")" --hostname "cible-$c" \ |
| 47 | 52 | --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \ |
| 48 | 53 | --tmpfs /run --tmpfs /run/lock \ |
| 49 | - -p "127.0.0.1:$(port "$c"):22" "$(nom "$c")" >/dev/null | |
| 54 | + -p "127.0.0.1:$(port "$c"):22" "oiam-cible-$c" >/dev/null | |
| 50 | 55 | docker exec "$(nom "$c")" install -d -m 700 /root/.ssh |
| 51 | 56 | docker cp "$cle.pub" "$(nom "$c"):/root/.ssh/authorized_keys" |
| 52 | 57 | docker exec "$(nom "$c")" chown root:root /root/.ssh/authorized_keys |
@@ -86,5 +91,5 @@ case "$commande" in
| 86 | 91 | exec ssh $(ssh_opts "$c") root@127.0.0.1 |
| 87 | 92 | ;; |
| 88 | 93 | statut) statut ;; |
| 89 | - *) sed -n '2,13p' "$0"; exit 2 ;; | |
| 94 | + *) sed -n '2,17p' "$0"; exit 2 ;; | |
| 90 | 95 | esac |
A
tests/e2e/l1-annuaire.sh
+65
-0
@@ -0,0 +1,65 @@
| 1 | +#!/usr/bin/env bash | |
| 2 | +# Recette L1 (OI-040) : installation réelle par l'assistant web, dans une cible vierge. | |
| 3 | +# tests/e2e/l1-annuaire.sh [debian|ubuntu] | |
| 4 | +# Le binaire de production est copié dans la cible et piloté par un navigateur à travers un | |
| 5 | +# tunnel SSH, comme le ferait un administrateur. Puis l'annuaire installé est contrôlé. | |
| 6 | +# Cible conteneur (D-018, D-021) : la recette sur VM réelle (OI-905) reprendra ce script. | |
| 7 | +set -euo pipefail | |
| 8 | +racine="$(cd "$(dirname "$0")/../.." && pwd)" | |
| 9 | +cd "$racine" | |
| 10 | +cible="${1:-debian}" | |
| 11 | +case "$cible" in debian) port=2222 ;; ubuntu) port=2223 ;; *) echo "Cible : debian ou ubuntu" >&2; exit 2 ;; esac | |
| 12 | +tunnel_port=$((17090 + port - 2222)) | |
| 13 | +ssh_opts=(-i tests/cible/.ssh/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR) | |
| 14 | +sur_cible() { ssh "${ssh_opts[@]}" -p "$port" root@127.0.0.1 "$@"; } | |
| 15 | +etape() { printf '\n\033[1m▶ %s\033[0m\n' "$1"; } | |
| 16 | +echecs=0 | |
| 17 | +controle() { # $1 : libellé ; la commande suit | |
| 18 | + local libelle="$1"; shift | |
| 19 | + if "$@" >/dev/null 2>&1; then echo "✓ $libelle"; else echo "✕ $libelle"; echecs=$((echecs + 1)); fi | |
| 20 | +} | |
| 21 | + | |
| 22 | +etape "Cible $cible vierge" | |
| 23 | +scripts/cible.sh reinitialiser "$cible" | |
| 24 | + | |
| 25 | +etape "Binaire de production" | |
| 26 | +cargo build --release --quiet -p open-iam-installer | |
| 27 | +scp "${ssh_opts[@]}" -P "$port" -q target/release/open-iam-installer root@127.0.0.1:/usr/local/bin/open-iam-installer | |
| 28 | + | |
| 29 | +etape "Lancement de l'installeur dans la cible" | |
| 30 | +sur_cible 'setsid nohup /usr/local/bin/open-iam-installer > /var/log/open-iam-installer.log 2>&1 < /dev/null &' | |
| 31 | +for _ in $(seq 1 50); do sur_cible 'ss -ltnH | grep -q "127.0.0.1:7070"' && break; sleep 0.2; done | |
| 32 | +jeton="$(sur_cible /usr/local/bin/open-iam-installer nouveau-jeton | grep -oE 'jeton=[A-Z2-7]+' | cut -d= -f2)" | |
| 33 | +ssh "${ssh_opts[@]}" -p "$port" -N -L "$tunnel_port:127.0.0.1:7070" root@127.0.0.1 & | |
| 34 | +tunnel=$! | |
| 35 | +trap 'kill "$tunnel" 2>/dev/null || true' EXIT | |
| 36 | +sleep 1 | |
| 37 | + | |
| 38 | +etape "Parcours de l'assistant et installation réelle (plusieurs minutes)" | |
| 39 | +OIAM_JETON="$jeton" node tests/navigateur/recette.mjs "http://127.0.0.1:$tunnel_port" || echecs=$((echecs + 1)) | |
| 40 | + | |
| 41 | +etape "Contrôles de l'annuaire installé" | |
| 42 | +admin="uid=jean.dupont,ou=users,dc=exemple,dc=fr" | |
| 43 | +mdp="Cheval-Batterie-42" | |
| 44 | +B=/usr/local/openldap/bin | |
| 45 | +controle "bind LDAPS du premier administrateur" sur_cible "$B/ldapwhoami -x -H ldaps://annuaire.exemple.fr -D '$admin' -w '$mdp'" | |
| 46 | +controle "bind anonyme refusé" sur_cible "! $B/ldapwhoami -x -H ldaps://annuaire.exemple.fr" | |
| 47 | +controle "bind simple sans TLS refusé (code 13)" sur_cible "$B/ldapwhoami -x -H ldap://annuaire.exemple.fr -D '$admin' -w '$mdp'; test \$? -eq 13" | |
| 48 | +controle "memberOf calculé" sur_cible "$B/ldapsearch -LLL -Q -Y EXTERNAL -H ldapi://%2Fvar%2Frun%2Fslapd%2Fldapi -b '$admin' memberOf | grep -q openiam-admins" | |
| 49 | +controle "minuteries de sauvegarde actives" sur_cible "systemctl is-active open-iam-sauvegarde.timer open-iam-test-restauration.timer" | |
| 50 | +controle "sauvegarde puis restauration réussies" sur_cible "/usr/local/sbin/open-iam-sauvegarde && /usr/local/sbin/open-iam-test-restauration" | |
| 51 | +controle "fichier récapitulatif en 0600" sur_cible "test \"\$(stat -c %a /root/open-iam/open-iam-exemple.fr-*.txt)\" = 600" | |
| 52 | +controle "le récapitulatif contient la clé des sauvegardes" sur_cible "grep -q AGE-SECRET-KEY /root/open-iam/open-iam-exemple.fr-*.txt" | |
| 53 | +controle "verrou d'installation posé" sur_cible "test -f /var/lib/open-iam/installed.lock" | |
| 54 | +controle "aucun secret en clair dans les exécutions" sur_cible "! grep -rqF '$mdp' /var/lib/open-iam/executions" | |
| 55 | + | |
| 56 | +etape "Pare-feu, vu depuis l'extérieur de la cible" | |
| 57 | +ip="$(docker container inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "oiam-cible-$cible")" | |
| 58 | +ouvert() { timeout 2 bash -c "exec 3<>/dev/tcp/$ip/$1" 2>/dev/null; } | |
| 59 | +for p in 22 389 636; do controle "port $p ouvert" ouvert "$p"; done | |
| 60 | +for p in 25 80 443 7070 8389; do controle "port $p fermé" bash -c "! (timeout 2 bash -c 'exec 3<>/dev/tcp/$ip/$p' 2>/dev/null)"; done | |
| 61 | + | |
| 62 | +etape "Un second lancement de l'installeur trouve l'assistant verrouillé" | |
| 63 | +controle "message « déjà installé »" sur_cible "timeout 3 /usr/local/bin/open-iam-installer --listen 127.0.0.1:7071 | grep -q 'déjà installé'" | |
| 64 | + | |
| 65 | +if (( echecs == 0 )); then printf '\n\033[1;32m✓ Recette L1 verte sur %s\033[0m\n' "$cible"; else printf '\n\033[1;31m✕ %d échec(s) sur %s\033[0m\n' "$echecs" "$cible"; exit 1; fi |
A
tests/navigateur/parcours.mjs
+97
-0
@@ -0,0 +1,97 @@
| 1 | +// Parcours complet de l'assistant d'installation, partagé par verifier.mjs (Ansible simulé) | |
| 2 | +// et recette.mjs (vraie installation dans une cible). La page doit être ouverte sur | |
| 3 | +// /acces?jeton=… ; le parcours s'arrête sur l'écran « assistant verrouillé ». | |
| 4 | + | |
| 5 | +export async function parcourirAssistant( | |
| 6 | + p, | |
| 7 | + verifier, | |
| 8 | + { controlerA11y = async () => {}, attenteInstallation = 20000, surResultat = async () => {} } = {}, | |
| 9 | +) { | |
| 10 | + const attendreUrl = async (fragment, delai = 10000) => { | |
| 11 | + const atteinte = await p | |
| 12 | + .waitForFunction((f) => location.pathname.endsWith(f), { timeout: delai }, fragment) | |
| 13 | + .then(() => true, () => false); | |
| 14 | + if (!atteinte) { | |
| 15 | + const texte = await p.evaluate(() => document.body.innerText).catch(() => ""); | |
| 16 | + console.error(`Attendu ${fragment}, page actuelle ${p.url()} :\n${texte.slice(0, 1500)}`); | |
| 17 | + } | |
| 18 | + return atteinte; | |
| 19 | + }; | |
| 20 | + const remplir = async (selecteur, valeur) => { | |
| 21 | + await p.$eval(selecteur, (el) => (el.value = "")); | |
| 22 | + await p.type(selecteur, valeur); | |
| 23 | + }; | |
| 24 | + const soumettre = async (suivante) => { | |
| 25 | + await p.click("form button[type=submit]"); | |
| 26 | + verifier(await attendreUrl(suivante), `passage à ${suivante}`); | |
| 27 | + await p.waitForNetworkIdle({ idleTime: 200 }); | |
| 28 | + }; | |
| 29 | + | |
| 30 | + verifier(p.url().endsWith("/install"), "jeton accepté, arrivée sur l'assistant"); | |
| 31 | + await p.waitForSelector('[data-controle="systeme"]', { timeout: 30000 }); | |
| 32 | + if (await p.$('[hx-post="/install/prerequis/ansible"]')) { | |
| 33 | + await p.click('[hx-post="/install/prerequis/ansible"]'); | |
| 34 | + verifier( | |
| 35 | + await p.waitForSelector('[hx-post="/install/commencer"]', { timeout: 300000 }).then(() => true, () => false), | |
| 36 | + "Ansible installé depuis l'assistant", | |
| 37 | + ); | |
| 38 | + } | |
| 39 | + await controlerA11y("E-001 bienvenue"); | |
| 40 | + await p.waitForNetworkIdle({ idleTime: 500 }); | |
| 41 | + await p.click('[hx-post="/install/commencer"]'); | |
| 42 | + if (!(await attendreUrl("/install/organisation"))) return verifier(false, "passage à l'organisation"); | |
| 43 | + await p.waitForNetworkIdle({ idleTime: 200 }); | |
| 44 | + await controlerA11y("E-002 organisation"); | |
| 45 | + await remplir("#nom", "Mairie d'Exemple"); | |
| 46 | + await remplir("#domaine", "Exemple.fr"); | |
| 47 | + verifier((await p.$eval("#base_dn", (el) => el.value)) === "dc=exemple,dc=fr", "base DN déduite du domaine en direct"); | |
| 48 | + await soumettre("/install/cibles"); | |
| 49 | + await controlerA11y("E-003 cibles"); | |
| 50 | + await soumettre("/install/composants"); | |
| 51 | + await controlerA11y("E-004 composants"); | |
| 52 | + await soumettre("/install/securite"); | |
| 53 | + await controlerA11y("E-005 sécurité"); | |
| 54 | + await soumettre("/install/comptes"); | |
| 55 | + await controlerA11y("E-007 comptes"); | |
| 56 | + await p.click('[hx-post="/install/comptes/generer"]'); | |
| 57 | + await p.waitForSelector('input[name="urgence_genere"]'); | |
| 58 | + await remplir("#prenom", "Jean"); | |
| 59 | + await remplir("#nom", "Dupont"); | |
| 60 | + await remplir("#uid", "jean.dupont"); | |
| 61 | + await remplir("#email", "jean.dupont@exemple.fr"); | |
| 62 | + await remplir("#mot_de_passe", "Cheval-Batterie-42"); | |
| 63 | + await remplir("#confirmation", "Cheval-Batterie-42"); | |
| 64 | + await soumettre("/install/telemetrie"); | |
| 65 | + await controlerA11y("E-008 télémétrie"); | |
| 66 | + await soumettre("/install/recapitulatif"); | |
| 67 | + await controlerA11y("E-010 récapitulatif"); | |
| 68 | + await p.click('[hx-post="/install/verification"]'); | |
| 69 | + verifier( | |
| 70 | + await p.waitForSelector("#lancer:not([disabled])", { timeout: 30000 }).then(() => true, () => false), | |
| 71 | + "vérification préalable réussie", | |
| 72 | + ); | |
| 73 | + await p.click("#lancer"); | |
| 74 | + await p.click('#confirm-lancer [hx-post="/install/execution"]'); | |
| 75 | + verifier(await attendreUrl("/install/execution"), "lancement de l'installation"); | |
| 76 | + const fin = await p.waitForSelector("#fin [role=status], #fin [role=alert]", { timeout: attenteInstallation }).then( | |
| 77 | + (el) => el, | |
| 78 | + () => null, | |
| 79 | + ); | |
| 80 | + const reussie = fin && (await fin.evaluate((el) => el.getAttribute("role") === "status")); | |
| 81 | + if (!reussie) { | |
| 82 | + const journal = await p.$eval("#journal", (el) => el.innerText).catch(() => ""); | |
| 83 | + console.error(journal.split("\n").slice(-30).join("\n")); | |
| 84 | + } | |
| 85 | + verifier(reussie, "installation terminée avec succès (flux SSE)"); | |
| 86 | + if (!reussie) return false; | |
| 87 | + await controlerA11y("E-011 exécution"); | |
| 88 | + verifier(await attendreUrl("/install/resultat"), "passage automatique au résultat"); | |
| 89 | + await p.waitForNetworkIdle({ idleTime: 200 }); | |
| 90 | + await controlerA11y("E-012 résultat"); | |
| 91 | + await surResultat(p); | |
| 92 | + await p.click('input[name="conserve"]'); | |
| 93 | + await p.click('form[hx-post="/install/terminer"] button[type=submit]'); | |
| 94 | + verifier(await attendreUrl("/verrouille"), "assistant verrouillé après « Terminer »"); | |
| 95 | + await controlerA11y("E-092 verrouillé"); | |
| 96 | + return true; | |
| 97 | +} |
A
tests/navigateur/recette.mjs
+40
-0
@@ -0,0 +1,40 @@
| 1 | +// Recette OI-040 : parcours de l'assistant contre un installeur réel (tunnel SSH vers une | |
| 2 | +// cible), avec une vraie installation. Lancé par tests/e2e/l1-annuaire.sh. | |
| 3 | +// Usage : OIAM_JETON=… node recette.mjs http://127.0.0.1:17090 | |
| 4 | + | |
| 5 | +import { existsSync } from "node:fs"; | |
| 6 | +import { homedir } from "node:os"; | |
| 7 | +import puppeteer from "puppeteer-core"; | |
| 8 | +import { parcourirAssistant } from "./parcours.mjs"; | |
| 9 | + | |
| 10 | +const base = process.argv[2]; | |
| 11 | +const executablePath = [ | |
| 12 | + process.env.CHROME, | |
| 13 | + `${homedir()}/.cache/ms-playwright/chromium_headless_shell-1248/chrome-headless-shell-linux64/chrome-headless-shell`, | |
| 14 | + "/snap/chromium/current/usr/lib/chromium-browser/chrome", | |
| 15 | +].find((c) => c && existsSync(c)); | |
| 16 | + | |
| 17 | +const echecs = []; | |
| 18 | +const verifier = (condition, message) => { | |
| 19 | + console.log(`${condition ? "✓" : "✕"} ${message}`); | |
| 20 | + if (!condition) echecs.push(message); | |
| 21 | +}; | |
| 22 | + | |
| 23 | +const browser = await puppeteer.launch({ executablePath, headless: true, args: ["--no-sandbox"] }); | |
| 24 | +const page = await browser.newPage(); | |
| 25 | +await page.setViewport({ width: 1280, height: 900 }); | |
| 26 | +page.on("pageerror", (e) => echecs.push(`erreur JS : ${e.message}`)); | |
| 27 | +await page.goto(`${base}/acces?jeton=${process.env.OIAM_JETON}`, { waitUntil: "networkidle0" }); | |
| 28 | + | |
| 29 | +await parcourirAssistant(page, verifier, { | |
| 30 | + attenteInstallation: 20 * 60 * 1000, | |
| 31 | + surResultat: async (p) => { | |
| 32 | + const html = await p.content(); | |
| 33 | + verifier(html.includes("Répond"), "E-012 : l'annuaire répond en LDAPS"); | |
| 34 | + verifier(/\/root\/open-iam\/open-iam-exemple\.fr-\d{8}-\d{4}\.txt/.test(html), "E-012 : chemin du fichier récapitulatif affiché"); | |
| 35 | + }, | |
| 36 | +}); | |
| 37 | + | |
| 38 | +await browser.close(); | |
| 39 | +console.log(echecs.length === 0 ? "\nParcours réel : tout est vert." : `\n${echecs.length} échec(s) : ${echecs.join(" | ")}`); | |
| 40 | +process.exit(echecs.length === 0 ? 0 : 1); |
M
tests/navigateur/verifier.mjs
+18
-1
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from "node:fs";
| 9 | 9 | import { homedir } from "node:os"; |
| 10 | 10 | import { createRequire } from "node:module"; |
| 11 | 11 | import puppeteer from "puppeteer-core"; |
| 12 | +import { parcourirAssistant } from "./parcours.mjs"; | |
| 12 | 13 | |
| 13 | 14 | const base = process.argv[2] ?? "http://127.0.0.1:7070"; |
| 14 | 15 | const axeSource = readFileSync(createRequire(import.meta.url).resolve("axe-core/axe.min.js"), "utf8"); |
@@ -66,7 +67,7 @@ async function axe(page) {
| 66 | 67 | } |
| 67 | 68 | |
| 68 | 69 | // 1. Accessibilité, CSP et erreurs JavaScript, à trois largeurs. |
| 69 | -for (const chemin of ["/", "/dev/composants", "/inconnue"]) { | |
| 70 | +for (const chemin of ["/acces", "/dev/composants", "/inconnue"]) { | |
| 70 | 71 | for (const largeur of [375, 768, 1280]) { |
| 71 | 72 | const { page, problemes } = await ouvrir(chemin, largeur); |
| 72 | 73 | const violations = await axe(page); |
@@ -121,6 +122,22 @@ verifier(
| 121 | 122 | ); |
| 122 | 123 | |
| 123 | 124 | verifier(problemes.length === 0, `aucune erreur pendant les parcours ${problemes.join(" | ")}`); |
| 125 | +await page.close(); | |
| 126 | + | |
| 127 | +// 3. Parcours complet de l'assistant (jeton fourni par scripts/ci.sh, Ansible simulé). | |
| 128 | +if (process.env.OIAM_JETON) { | |
| 129 | + const { page: p, problemes: pb } = await ouvrir(`/acces?jeton=${process.env.OIAM_JETON}`); | |
| 130 | + const controlerA11y = async (nom) => { | |
| 131 | + for (const largeur of [375, 1280]) { | |
| 132 | + await p.setViewport({ width: largeur, height: 900 }); | |
| 133 | + const violations = await axe(p); | |
| 134 | + verifier(violations.length === 0, `axe ${nom} @${largeur}px ${violations.join(" | ")}`); | |
| 135 | + } | |
| 136 | + await p.setViewport({ width: 1280, height: 900 }); | |
| 137 | + }; | |
| 138 | + await parcourirAssistant(p, verifier, { controlerA11y, attenteInstallation: 20000 }); | |
| 139 | + verifier(pb.length === 0, `aucune erreur pendant le parcours de l'assistant ${pb.join(" | ")}`); | |
| 140 | +} | |
| 124 | 141 | |
| 125 | 142 | await browser.close(); |
| 126 | 143 | console.log(echecs.length === 0 ? "\nTout est vert." : `\n${echecs.length} échec(s).`); |
GitRust