diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..dabbbe0c --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,14 @@ +{ + "configurations": [ + { + "name": "Mac", + "includePath": ["/opt/homebrew/include"], + "macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"], + "intelliSenseMode": "macos-clang-x64", + "compilerPath": "/usr/bin/clang", + "cStandard": "c17", + "cppStandard": "c++17" + } + ], + "version": 4 +} diff --git a/.vscode/settings.json b/.vscode/settings.json index ce40d5cf..5b371550 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -23,8 +23,12 @@ "gpgui", "gpservice", "hidpi", + "Ivars", "jnlp", "LOGNAME", + "NSHTTPURL", + "NSURL", + "objc", "oneshot", "openconnect", "pkcs", @@ -55,9 +59,16 @@ "Vite", "vpnc", "vpninfo", + "webbrowser", "wmctrl", "XAUTHORITY", "yuezk" ], "rust-analyzer.cargo.features": "all", + "files.associations": { + "unistd.h": "c", + "utsname.h": "c", + "vpn.h": "c", + "openconnect.h": "c" + }, } diff --git a/Cargo.lock b/Cargo.lock index 851a9182..2c719106 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -135,13 +135,13 @@ checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" [[package]] name = "async-trait" -version = "0.1.83" +version = "0.1.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" +checksum = "3f934833b4b7233644e5848f235df3f57ed8c80f1528a26c3dfa13d2147fa056" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -178,9 +178,13 @@ name = "auth" version = "2.4.0" dependencies = [ "anyhow", + "block2", "gpapi", "html-escape", "log", + "objc2", + "objc2-foundation", + "objc2-web-kit", "open", "regex", "tauri", @@ -416,16 +420,16 @@ dependencies = [ [[package]] name = "cargo_metadata" -version = "0.18.1" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d886547e41f740c616ae73108f6eb70afe6d940c7bc697cb30f13daec073037" +checksum = "8769706aad5d996120af43197bf46ef6ad0fda35216b4505f926a365a232d924" dependencies = [ "camino", "cargo-platform", "semver", "serde", "serde_json", - "thiserror 1.0.69", + "thiserror 2.0.10", ] [[package]] @@ -440,9 +444,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.5" +version = "1.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c31a0499c1dc64f458ad13872de75c0eb7e3fdb0e67964610c914b034fc5956e" +checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7" dependencies = [ "shlex", ] @@ -542,19 +546,29 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.23" +version = "4.5.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" +checksum = "9560b07a799281c7e0958b9296854d6fafd4c5f31444a7e5bb1ad6dde5ccf1bd" dependencies = [ "clap_builder", "clap_derive", ] +[[package]] +name = "clap-verbosity-flag" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2678fade3b77aa3a8ff3aae87e9c008d3fb00473a41c71fbf74e91c8c7b37e84" +dependencies = [ + "clap", + "log", +] + [[package]] name = "clap_builder" -version = "4.5.23" +version = "4.5.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" +checksum = "874e0dd3eb68bf99058751ac9712f622e61e6f393a94f7128fa26e3f02f5c7cd" dependencies = [ "anstream", "anstyle", @@ -564,14 +578,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.18" +version = "4.5.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" +checksum = "54b755194d6389280185988721fffba69495eed5ee9feeee9a599b53db80318c" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -825,7 +839,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" dependencies = [ "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -835,7 +849,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" dependencies = [ "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -859,7 +873,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -870,7 +884,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -899,7 +913,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -956,7 +970,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -979,7 +993,7 @@ checksum = "f2b99bf03862d7f545ebc28ddd33a665b50865f4dfd84031a393823879bd4c54" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -1200,7 +1214,7 @@ checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -1290,7 +1304,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -1544,7 +1558,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -1559,9 +1573,9 @@ dependencies = [ [[package]] name = "glob" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" [[package]] name = "gobject-sys" @@ -1582,8 +1596,11 @@ dependencies = [ "base64 0.22.1", "chacha20poly1305", "clap", + "clap-verbosity-flag", "dns-lookup", + "env_logger", "log", + "log-reload", "md5", "openssl", "pem", @@ -1598,11 +1615,12 @@ dependencies = [ "specta", "tauri", "tempfile", - "thiserror 2.0.9", + "thiserror 2.0.10", "tokio", "url", "urlencoding", "uzers", + "version-compare", "whoami", ] @@ -1616,6 +1634,7 @@ dependencies = [ "compile-time", "env_logger", "gpapi", + "home", "log", "serde_json", "tauri", @@ -1734,7 +1753,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -2091,7 +2110,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -2178,15 +2197,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - [[package]] name = "ipnet" version = "2.10.1" @@ -2399,9 +2409,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.4.14" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "litemap" @@ -2425,6 +2435,16 @@ version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" +[[package]] +name = "log-reload" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e99df759bfe829042ac9ad2d576ad0b3ffb3bad3c1f124dc0094b54441e89999" +dependencies = [ + "log", + "thiserror 1.0.69", +] + [[package]] name = "lzma-sys" version = "0.1.20" @@ -2667,7 +2687,7 @@ dependencies = [ "proc-macro-crate 2.0.2", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -2920,9 +2940,9 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "open" -version = "5.3.1" +version = "5.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ecd52f0b8d15c40ce4820aa251ed5de032e5d91fab27f7db2f40d42a8bdf69c" +checksum = "e2483562e62ea94312f3576a7aca397306df7990b8d89033e18766744377ef95" dependencies = [ "is-wsl", "libc", @@ -2961,7 +2981,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -3080,12 +3100,12 @@ dependencies = [ [[package]] name = "phf" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_macros 0.11.2", - "phf_shared 0.11.2", + "phf_macros 0.11.3", + "phf_shared 0.11.3", ] [[package]] @@ -3130,11 +3150,11 @@ dependencies = [ [[package]] name = "phf_generator" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "phf_shared 0.11.2", + "phf_shared 0.11.3", "rand 0.8.5", ] @@ -3154,15 +3174,15 @@ dependencies = [ [[package]] name = "phf_macros" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" dependencies = [ - "phf_generator 0.11.2", - "phf_shared 0.11.2", + "phf_generator 0.11.3", + "phf_shared 0.11.3", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -3171,7 +3191,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" dependencies = [ - "siphasher", + "siphasher 0.3.11", ] [[package]] @@ -3180,23 +3200,23 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" dependencies = [ - "siphasher", + "siphasher 0.3.11", ] [[package]] name = "phf_shared" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" dependencies = [ - "siphasher", + "siphasher 1.0.1", ] [[package]] name = "pin-project-lite" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "pin-utils" @@ -3338,9 +3358,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] @@ -3517,9 +3537,9 @@ checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "reqwest" -version = "0.12.9" +version = "0.12.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" +checksum = "43e734407157c3c2034e0258f5e4473ddb361b1e85f95a66690d67264d7cd1da" dependencies = [ "base64 0.22.1", "bytes", @@ -3551,6 +3571,7 @@ dependencies = [ "tokio", "tokio-native-tls", "tokio-util", + "tower", "tower-service", "url", "wasm-bindgen", @@ -3598,9 +3619,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.42" +version = "0.38.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" +checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" dependencies = [ "bitflags 2.6.0", "errno", @@ -3650,9 +3671,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" [[package]] name = "ryu" @@ -3702,7 +3723,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -3726,9 +3747,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.13.0" +version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1863fd3768cd83c56a7f60faa4dc0d403f1b6df0a38c3c25f44b7894e45370d5" +checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32" dependencies = [ "core-foundation-sys", "libc", @@ -3765,9 +3786,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.216" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e" +checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" dependencies = [ "serde_derive", ] @@ -3785,13 +3806,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.216" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" +checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -3802,14 +3823,14 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] name = "serde_json" -version = "1.0.134" +version = "1.0.135" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d" +checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9" dependencies = [ "itoa 1.0.14", "memchr", @@ -3845,7 +3866,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -3871,9 +3892,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28bdad6db2b8340e449f7108f020b3b092e8583a9e3fb82713e1d4e71fe817" +checksum = "d6b6f7f2fcb69f747921f79f3926bd1e203fce4fef62c268dd3abfb6d86029aa" dependencies = [ "base64 0.22.1", "chrono", @@ -3889,14 +3910,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d846214a9854ef724f3da161b426242d8de7c1fc7de2f89bb1efcb154dca79d" +checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -4014,6 +4035,12 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + [[package]] name = "slab" version = "0.4.9" @@ -4106,7 +4133,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -4183,9 +4210,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.91" +version = "2.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53cbcb5a243bd33b7858b1d7f4aca2153490815872d86d955d6ea29f743c035" +checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a" dependencies = [ "proc-macro2", "quote", @@ -4209,14 +4236,14 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] name = "sysinfo" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "948512566b1895f93b1592c7574baeb2de842f224f2aab158799ecadb8ebbb46" +checksum = "4fc858248ea01b66f19d8e8a6d55f41deaf91e9d495246fd01368d99935c6c01" dependencies = [ "core-foundation-sys", "libc", @@ -4262,9 +4289,9 @@ dependencies = [ [[package]] name = "tao" -version = "0.30.8" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6682a07cf5bab0b8a2bd20d0a542917ab928b5edb75ebd4eda6b05cbaab872da" +checksum = "3731d04d4ac210cd5f344087733943b9bfb1a32654387dad4d1c70de21aee2c9" dependencies = [ "bitflags 2.6.0", "cocoa", @@ -4277,7 +4304,6 @@ dependencies = [ "gdkwayland-sys", "gdkx11-sys", "gtk", - "instant", "jni", "lazy_static", "libc", @@ -4307,7 +4333,7 @@ checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -4329,9 +4355,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "tauri" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e545de0a2dfe296fa67db208266cd397c5a55ae782da77973ef4c4fac90e9f2c" +checksum = "2e2e3349fbb2be7af9fad1b43d61ac83ba55ab48d47fbe1b2732f0c8211610a9" dependencies = [ "anyhow", "bytes", @@ -4366,7 +4392,7 @@ dependencies = [ "tauri-runtime", "tauri-runtime-wry", "tauri-utils", - "thiserror 2.0.9", + "thiserror 2.0.10", "tokio", "tray-icon", "url", @@ -4379,9 +4405,9 @@ dependencies = [ [[package]] name = "tauri-build" -version = "2.0.3" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd2a4bcfaf5fb9f4be72520eefcb61ae565038f8ccba2a497d8c28f463b8c01" +checksum = "b274ec7239ada504deb615f1c8abd7ba99631e879709e6f10e5d17217058d976" dependencies = [ "anyhow", "cargo_toml", @@ -4401,9 +4427,9 @@ dependencies = [ [[package]] name = "tauri-codegen" -version = "2.0.3" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf79faeecf301d3e969b1fae977039edb77a4c1f25cc0a961be298b54bff97cf" +checksum = "f77894f9ddb5cb6c04fcfe8c8869ebe0aded4dabf19917118d48be4a95599ab5" dependencies = [ "base64 0.22.1", "brotli", @@ -4417,9 +4443,9 @@ dependencies = [ "serde", "serde_json", "sha2", - "syn 2.0.91", + "syn 2.0.95", "tauri-utils", - "thiserror 2.0.9", + "thiserror 2.0.10", "time", "url", "uuid", @@ -4428,23 +4454,23 @@ dependencies = [ [[package]] name = "tauri-macros" -version = "2.0.3" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c52027c8c5afb83166dacddc092ee8fff50772f9646d461d8c33ee887e447a03" +checksum = "3240a5caed760a532e8f687be6f05b2c7d11a1d791fb53ccc08cfeb3e5308736" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", "tauri-codegen", "tauri-utils", ] [[package]] name = "tauri-runtime" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cce18d43f80d4aba3aa8a0c953bbe835f3d0f2370aca75e8dbb14bd4bab27958" +checksum = "2274ef891ccc0a8d318deffa9d70053f947664d12d58b9c0d1ae5e89237e01f7" dependencies = [ "dpi", "gtk", @@ -4454,16 +4480,16 @@ dependencies = [ "serde", "serde_json", "tauri-utils", - "thiserror 2.0.9", + "thiserror 2.0.10", "url", "windows 0.58.0", ] [[package]] name = "tauri-runtime-wry" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f442a38863e10129ffe2cec7bd09c2dcf8a098a3a27801a476a304d5bb991d2" +checksum = "3707b40711d3b9f6519150869e358ffbde7c57567fb9b5a8b51150606939b2a0" dependencies = [ "gtk", "http", @@ -4487,9 +4513,9 @@ dependencies = [ [[package]] name = "tauri-utils" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9271a88f99b4adea0dc71d0baca4505475a0bbd139fb135f62958721aaa8fe54" +checksum = "96fb10e7cc97456b2d5b9c03e335b5de5da982039a303a20d10006885e4523a0" dependencies = [ "brotli", "cargo_metadata", @@ -4503,7 +4529,7 @@ dependencies = [ "kuchikiki", "log", "memchr", - "phf 0.11.2", + "phf 0.11.3", "proc-macro2", "quote", "regex", @@ -4514,7 +4540,7 @@ dependencies = [ "serde_json", "serde_with", "swift-rs", - "thiserror 2.0.9", + "thiserror 2.0.10", "toml 0.8.2", "url", "urlpattern", @@ -4534,12 +4560,13 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.14.0" +version = "3.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" +checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" dependencies = [ "cfg-if", "fastrand", + "getrandom 0.2.15", "once_cell", "rustix", "windows-sys 0.59.0", @@ -4573,11 +4600,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.9" +version = "2.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" +checksum = "a3ac7f54ca534db81081ef1c1e7f6ea8a3ef428d2fc069097c079443d24124d3" dependencies = [ - "thiserror-impl 2.0.9", + "thiserror-impl 2.0.10", ] [[package]] @@ -4588,18 +4615,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] name = "thiserror-impl" -version = "2.0.9" +version = "2.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" +checksum = "9e9465d30713b56a37ede7185763c3492a91be2f5fa68d958c44e41ab9248beb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -4667,9 +4694,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.42.0" +version = "1.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" +checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e" dependencies = [ "backtrace", "bytes", @@ -4685,13 +4712,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -5154,7 +5181,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", "wasm-bindgen-shared", ] @@ -5189,7 +5216,7 @@ checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5287,9 +5314,9 @@ dependencies = [ [[package]] name = "webview2-com" -version = "0.33.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f61ff3d9d0ee4efcb461b14eb3acfda2702d10dc329f339303fc3e57215ae2c" +checksum = "823e7ebcfaea51e78f72c87fc3b65a1e602c321f407a0b36dbb327d7bb7cd921" dependencies = [ "webview2-com-macros", "webview2-com-sys", @@ -5307,14 +5334,14 @@ checksum = "1d228f15bba3b9d56dde8bddbee66fa24545bd17b48d5128ccf4a8742b18e431" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] name = "webview2-com-sys" -version = "0.33.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3a3e2eeb58f82361c93f9777014668eb3d07e7d174ee4c819575a9208011886" +checksum = "7a82bce72db6e5ee83c68b5de1e2cd6ea195b9fbff91cb37df5884cbe3222df4" dependencies = [ "thiserror 1.0.69", "windows 0.58.0", @@ -5451,7 +5478,7 @@ checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -5462,7 +5489,7 @@ checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -5473,7 +5500,7 @@ checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -5484,7 +5511,7 @@ checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -5601,20 +5628,36 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e4c7e8ceaaf9cb7d7507c974735728ab453b67ef8f18febdd7c11fe59dca8b" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + [[package]] name = "windows-version" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6998aa457c9ba8ff2fb9f13e9d2a930dabcea28f1d0ab94d687d8b3654844515" +checksum = "c12476c23a74725c539b24eae8bfc0dac4029c39cdb561d9f23616accd4ae26d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets 0.53.0", ] [[package]] @@ -5635,6 +5678,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -5653,6 +5702,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -5671,12 +5726,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -5695,6 +5762,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -5713,6 +5786,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -5731,6 +5810,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -5749,6 +5834,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + [[package]] name = "winnow" version = "0.5.40" @@ -5788,9 +5879,9 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" [[package]] name = "wry" -version = "0.47.2" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ce51277d65170f6379d8cda935c80e3c2d1f0ff712a123c8bddb11b31a4b73" +checksum = "1e644bf458e27b11b0ecafc9e5633d1304fdae82baca1d42185669752fe6ca4f" dependencies = [ "base64 0.22.1", "block2", @@ -5818,7 +5909,7 @@ dependencies = [ "sha2", "soup3", "tao-macros", - "thiserror 1.0.69", + "thiserror 2.0.10", "url", "webkit2gtk", "webkit2gtk-sys", @@ -5852,9 +5943,9 @@ dependencies = [ [[package]] name = "xattr" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da84f1a25939b27f6820d92aed108f83ff920fdf11a7b19366c27c4cda81d4f" +checksum = "e105d177a3871454f754b33bb0ee637ecaaac997446375fd3e5d43a2ed00c909" dependencies = [ "libc", "linux-raw-sys", @@ -5890,7 +5981,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", "synstructure", ] @@ -5912,7 +6003,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] [[package]] @@ -5932,7 +6023,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", "synstructure", ] @@ -5961,5 +6052,5 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.95", ] diff --git a/Cargo.toml b/Cargo.toml index 6176945d..eb7d2217 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ license = "GPL-3.0" anyhow = "1.0" base64 = "0.22" clap = { version = "4", features = ["derive"] } +clap-verbosity-flag = "3" ctrlc = "3.4" directories = "5.0" dns-lookup = "2.0.4" diff --git a/apps/gpauth/Cargo.toml b/apps/gpauth/Cargo.toml index 3eb3e8dd..853bc0f7 100644 --- a/apps/gpauth/Cargo.toml +++ b/apps/gpauth/Cargo.toml @@ -24,6 +24,9 @@ tokio.workspace = true tempfile.workspace = true compile-time.workspace = true +# Pin the version of home because the latest version requires Rust 1.81 +home = "=0.5.9" + # webview auth dependencies tauri = { workspace = true, optional = true } diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index 939773e2..014875d5 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -1,21 +1,19 @@ -use std::borrow::Cow; - -use auth::{auth_prelogin, Authenticator, BrowserAuthenticator}; +use auth::{auth_prelogin, BrowserAuthenticator}; use clap::Parser; use gpapi::{ auth::{SamlAuthData, SamlAuthResult}, - clap::{args::Os, handle_error, Args}, + clap::{args::Os, handle_error, Args, InfoLevelVerbosity}, gp_params::{ClientOs, GpParams}, utils::{normalize_server, openssl}, GP_USER_AGENT, }; -use log::{info, LevelFilter}; +use log::info; use serde_json::json; use tempfile::NamedTempFile; const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); -#[derive(Parser, Clone)] +#[derive(Parser)] #[command( version = VERSION, author, @@ -33,7 +31,7 @@ const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::dat See 'gpauth -h' for more information. " )] -pub(crate) struct Cli { +struct Cli { #[arg(help = "The portal server to authenticate")] server: String, @@ -75,6 +73,9 @@ pub(crate) struct Cli { #[cfg(feature = "webview-auth")] #[arg(long, help = "Clean the cache of the embedded browser")] pub clean: bool, + + #[command(flatten)] + verbose: InfoLevelVerbosity, } impl Args for Cli { @@ -110,28 +111,26 @@ impl Cli { let openssl_conf = self.prepare_env()?; let server = normalize_server(&self.server)?; - let server: &'static str = Box::leak(server.into_boxed_str()); - let gp_params: &'static GpParams = Box::leak(Box::new(self.build_gp_params())); + let gp_params = self.build_gp_params(); let auth_request = match self.saml_request.as_deref() { - Some(auth_request) => Cow::Borrowed(auth_request), - None => Cow::Owned(auth_prelogin(server, gp_params).await?), + Some(auth_request) => auth_request.to_string(), + None => auth_prelogin(&server, &gp_params).await?, }; - let auth_request: &'static str = Box::leak(auth_request.into_owned().into_boxed_str()); - let authenticator = Authenticator::new(&server, gp_params).with_auth_request(&auth_request); - #[cfg(feature = "webview-auth")] let browser = self .browser .as_deref() - .or_else(|| self.default_browser.then_some("default")); + .or_else(|| self.default_browser.then(|| "default")); #[cfg(not(feature = "webview-auth"))] let browser = self.browser.as_deref().or(Some("default")); - if browser.is_some() { - let auth_result = authenticator.browser_authenticate(browser).await; + if let Some(browser) = browser { + let authenticator = BrowserAuthenticator::new(&auth_request, browser); + let auth_result = authenticator.authenticate().await; + print_auth_result(auth_result); // explicitly drop openssl_conf to avoid the unused variable warning @@ -140,7 +139,7 @@ impl Cli { } #[cfg(feature = "webview-auth")] - crate::webview_auth::authenticate(&self, authenticator, openssl_conf)?; + crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?; Ok(()) } @@ -158,14 +157,16 @@ impl Cli { } } -fn init_logger() { - env_logger::builder().filter_level(LevelFilter::Info).init(); +fn init_logger(cli: &Cli) { + env_logger::builder() + .filter_level(cli.verbose.log_level_filter()) + .init(); } pub async fn run() { let cli = Cli::parse(); - init_logger(); + init_logger(&cli); info!("gpauth started: {}", VERSION); if let Err(err) = cli.run().await { diff --git a/apps/gpauth/src/main.rs b/apps/gpauth/src/main.rs index 29246ad4..393941d6 100644 --- a/apps/gpauth/src/main.rs +++ b/apps/gpauth/src/main.rs @@ -1,6 +1,7 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod cli; + #[cfg(feature = "webview-auth")] mod webview_auth; diff --git a/apps/gpauth/src/webview_auth.rs b/apps/gpauth/src/webview_auth.rs index 61c24060..8325622a 100644 --- a/apps/gpauth/src/webview_auth.rs +++ b/apps/gpauth/src/webview_auth.rs @@ -1,23 +1,28 @@ -use auth::{Authenticator, WebviewAuthenticator}; +use auth::WebviewAuthenticator; +use gpapi::gp_params::GpParams; use log::info; use tauri::RunEvent; use tempfile::NamedTempFile; -use crate::cli::{print_auth_result, Cli}; +use crate::cli::print_auth_result; -pub fn authenticate( - cli: &Cli, - authenticator: Authenticator<'static>, +pub async fn authenticate( + server: String, + gp_params: GpParams, + auth_request: String, + clean: bool, mut openssl_conf: Option, ) -> anyhow::Result<()> { - let authenticator = authenticator.with_clean(cli.clean); - tauri::Builder::default() .setup(move |app| { let app_handle = app.handle().clone(); tauri::async_runtime::spawn(async move { - let auth_result = authenticator.webview_authenticate(&app_handle).await; + let authenticator = WebviewAuthenticator::new(&server, &gp_params) + .with_auth_request(&auth_request) + .with_clean(clean); + + let auth_result = authenticator.authenticate(&app_handle).await; print_auth_result(auth_result); // Ensure the app exits after the authentication process diff --git a/apps/gpclient/src/cli.rs b/apps/gpclient/src/cli.rs index 005373bb..3d832720 100644 --- a/apps/gpclient/src/cli.rs +++ b/apps/gpclient/src/cli.rs @@ -2,10 +2,10 @@ use std::{env::temp_dir, fs::File}; use clap::{Parser, Subcommand}; use gpapi::{ - clap::{handle_error, Args}, + clap::{handle_error, Args, InfoLevelVerbosity}, utils::openssl, }; -use log::{info, LevelFilter}; +use log::info; use tempfile::NamedTempFile; use crate::{ @@ -16,9 +16,10 @@ use crate::{ const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); -pub(crate) struct SharedArgs { +pub(crate) struct SharedArgs<'a> { pub(crate) fix_openssl: bool, pub(crate) ignore_tls_errors: bool, + pub(crate) verbose: &'a InfoLevelVerbosity, } #[derive(Subcommand)] @@ -60,6 +61,9 @@ struct Cli { fix_openssl: bool, #[arg(long, help = "Ignore the TLS errors")] ignore_tls_errors: bool, + + #[command(flatten)] + verbose: InfoLevelVerbosity, } impl Args for Cli { @@ -89,6 +93,7 @@ impl Cli { let shared_args = SharedArgs { fix_openssl: self.fix_openssl, ignore_tls_errors: self.ignore_tls_errors, + verbose: &self.verbose, }; if self.ignore_tls_errors { @@ -103,12 +108,12 @@ impl Cli { } } -fn init_logger(command: &CliCommand) { +fn init_logger(cli: &Cli) { let mut builder = env_logger::builder(); - builder.filter_level(LevelFilter::Info); + builder.filter_level(cli.verbose.log_level_filter()); // Output the log messages to a file if the command is the auth callback - if let CliCommand::LaunchGui(args) = command { + if let CliCommand::LaunchGui(args) = &cli.command { let auth_data = args.auth_data.as_deref().unwrap_or_default(); if !auth_data.is_empty() { if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) { @@ -124,7 +129,7 @@ fn init_logger(command: &CliCommand) { pub(crate) async fn run() { let cli = Cli::parse(); - init_logger(&cli.command); + init_logger(&cli); info!("gpclient started: {}", VERSION); diff --git a/apps/gpclient/src/connect.rs b/apps/gpclient/src/connect.rs index 0a0ed9a4..df7d1603 100644 --- a/apps/gpclient/src/connect.rs +++ b/apps/gpclient/src/connect.rs @@ -5,7 +5,7 @@ use clap::Args; use common::vpn_utils::find_csd_wrapper; use gpapi::{ auth::SamlAuthResult, - clap::args::Os, + clap::{args::Os, ToVerboseArg}, credential::{Credential, PasswordCredential}, error::PortalError, gateway::{gateway_login, GatewayLogin}, @@ -19,7 +19,7 @@ use gpapi::{ GP_USER_AGENT, }; use inquire::{Password, PasswordDisplayMode, Select, Text}; -use log::info; +use log::{info, warn}; use openconnect::Vpn; use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE}; @@ -128,7 +128,7 @@ impl ConnectArgs { pub(crate) struct ConnectHandler<'a> { args: &'a ConnectArgs, - shared_args: &'a SharedArgs, + shared_args: &'a SharedArgs<'a>, latest_key_password: RefCell>, } @@ -203,7 +203,7 @@ impl<'a> ConnectHandler<'a> { return Ok(()); }; - info!("Failed to connect portal with prelogin: {}", err); + warn!("Failed to connect portal with prelogin: {}", err); if err.root_cause().downcast_ref::().is_some() { info!("Trying the gateway authentication workflow..."); self.connect_gateway_with_prelogin(server).await?; @@ -356,6 +356,7 @@ impl<'a> ConnectHandler<'a> { }; let os_version = self.args.os_version(); + let verbose = self.shared_args.verbose.to_verbose_arg(); let auth_launcher = SamlAuthLauncher::new(&self.args.server) .gateway(is_gateway) .saml_request(prelogin.saml_request()) @@ -364,7 +365,8 @@ impl<'a> ConnectHandler<'a> { .os_version(Some(&os_version)) .fix_openssl(self.shared_args.fix_openssl) .ignore_tls_errors(self.shared_args.ignore_tls_errors) - .browser(browser); + .browser(browser) + .verbose(verbose); #[cfg(feature = "webview-auth")] let use_default_browser = prelogin.support_default_browser() && self.args.default_browser; diff --git a/apps/gpgui-helper/src-tauri/Cargo.toml b/apps/gpgui-helper/src-tauri/Cargo.toml index 363d9287..364d2f82 100644 --- a/apps/gpgui-helper/src-tauri/Cargo.toml +++ b/apps/gpgui-helper/src-tauri/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true tauri-build = { version = "2", features = [] } [dependencies] -gpapi = { path = "../../../crates/gpapi", features = ["tauri"] } +gpapi = { path = "../../../crates/gpapi", features = ["tauri", "clap"] } tauri.workspace = true tokio.workspace = true diff --git a/apps/gpgui-helper/src-tauri/src/cli.rs b/apps/gpgui-helper/src-tauri/src/cli.rs index 8a01f558..ed92ffe6 100644 --- a/apps/gpgui-helper/src-tauri/src/cli.rs +++ b/apps/gpgui-helper/src-tauri/src/cli.rs @@ -1,6 +1,9 @@ use clap::Parser; -use gpapi::utils::{base64, env_utils}; -use log::{info, LevelFilter}; +use gpapi::{ + clap::InfoLevelVerbosity, + utils::{base64, env_utils}, +}; +use log::info; use crate::app::App; @@ -15,6 +18,9 @@ struct Cli { #[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")] gui_version: String, + + #[command(flatten)] + verbose: InfoLevelVerbosity, } impl Cli { @@ -41,14 +47,16 @@ impl Cli { } } -fn init_logger() { - env_logger::builder().filter_level(LevelFilter::Info).init(); +fn init_logger(cli: &Cli) { + env_logger::builder() + .filter_level(cli.verbose.log_level_filter()) + .init(); } pub fn run() { let cli = Cli::parse(); - init_logger(); + init_logger(&cli); info!("gpgui-helper started: {}", VERSION); if let Err(e) = cli.run() { diff --git a/apps/gpservice/Cargo.toml b/apps/gpservice/Cargo.toml index 4212f435..fdff7031 100644 --- a/apps/gpservice/Cargo.toml +++ b/apps/gpservice/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true [dependencies] -gpapi = { path = "../../crates/gpapi" } +gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] } openconnect = { path = "../../crates/openconnect" } clap.workspace = true anyhow.workspace = true diff --git a/apps/gpservice/src/cli.rs b/apps/gpservice/src/cli.rs index b379bb62..4fc0f611 100644 --- a/apps/gpservice/src/cli.rs +++ b/apps/gpservice/src/cli.rs @@ -3,13 +3,15 @@ use std::{collections::HashMap, io::Write}; use anyhow::bail; use clap::Parser; +use gpapi::clap::InfoLevelVerbosity; +use gpapi::logger; use gpapi::{ process::gui_launcher::GuiLauncher, service::{request::WsRequest, vpn_state::VpnState}, utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal}, GP_SERVICE_LOCK_FILE, }; -use log::{info, warn, LevelFilter}; +use log::{info, warn}; use tokio::sync::{mpsc, watch}; use crate::{vpn_task::VpnTask, ws_server::WsServer}; @@ -26,10 +28,16 @@ struct Cli { #[cfg(debug_assertions)] #[clap(long)] no_gui: bool, + + #[command(flatten)] + verbose: InfoLevelVerbosity, } impl Cli { - async fn run(&mut self, redaction: Arc) -> anyhow::Result<()> { + async fn run(&mut self) -> anyhow::Result<()> { + let redaction = self.init_logger()?; + info!("gpservice started: {}", VERSION); + let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE)); if lock_file.check_health().await { @@ -92,6 +100,33 @@ impl Cli { Ok(()) } + fn init_logger(&self) -> anyhow::Result> { + let redaction = Arc::new(Redaction::new()); + let redaction_clone = Arc::clone(&redaction); + + let inner_logger = env_logger::builder() + // Set the log level to the Trace level, the logs will be filtered + .filter_level(log::LevelFilter::Trace) + .format(move |buf, record| { + let timestamp = buf.timestamp(); + writeln!( + buf, + "[{} {} {}] {}", + timestamp, + record.level(), + record.module_path().unwrap_or_default(), + redaction_clone.redact_str(&record.args().to_string()) + ) + }) + .build(); + + let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info); + + logger::init_with_logger(level, inner_logger)?; + + Ok(redaction) + } + fn prepare_api_key(&self) -> Vec { #[cfg(debug_assertions)] if self.no_gui { @@ -102,29 +137,6 @@ impl Cli { } } -fn init_logger() -> Arc { - let redaction = Arc::new(Redaction::new()); - let redaction_clone = Arc::clone(&redaction); - // let target = Box::new(File::create("log.txt").expect("Can't create file")); - env_logger::builder() - .filter_level(LevelFilter::Info) - .format(move |buf, record| { - let timestamp = buf.timestamp(); - writeln!( - buf, - "[{} {} {}] {}", - timestamp, - record.level(), - record.module_path().unwrap_or_default(), - redaction_clone.redact_str(&record.args().to_string()) - ) - }) - // .target(env_logger::Target::Pipe(target)) - .init(); - - redaction -} - async fn launch_gui(envs: Option>, api_key: Vec, mut minimized: bool) { loop { let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key) @@ -153,10 +165,7 @@ async fn launch_gui(envs: Option>, api_key: Vec, mut pub async fn run() { let mut cli = Cli::parse(); - let redaction = init_logger(); - info!("gpservice started: {}", VERSION); - - if let Err(e) = cli.run(redaction).await { + if let Err(e) = cli.run().await { eprintln!("Error: {}", e); std::process::exit(1); } diff --git a/apps/gpservice/src/vpn_task.rs b/apps/gpservice/src/vpn_task.rs index 9866f8a0..11577d11 100644 --- a/apps/gpservice/src/vpn_task.rs +++ b/apps/gpservice/src/vpn_task.rs @@ -1,8 +1,11 @@ use std::{sync::Arc, thread}; -use gpapi::service::{ - request::{ConnectRequest, WsRequest}, - vpn_state::VpnState, +use gpapi::{ + logger, + service::{ + request::{ConnectRequest, UpdateLogLevelRequest, WsRequest}, + vpn_state::VpnState, + }, }; use log::{info, warn}; use openconnect::Vpn; @@ -158,5 +161,12 @@ async fn process_ws_req(req: WsRequest, ctx: Arc) { WsRequest::Disconnect(_) => { ctx.disconnect().await; } + WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => { + let level = level.parse().unwrap_or_else(|_| log::Level::Info); + info!("Updating log level to: {}", level); + if let Err(err) = logger::set_max_level(level) { + warn!("Failed to update log level: {}", err); + } + } } } diff --git a/changelog.md b/changelog.md index 297edfc3..8899592e 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,12 @@ # Changelog +## [Unreleased] + +- Fix the issue with OpenSSL < 3.0.4 +- GUI: fix the Wayland compatibility issue +- Support configure the log level +- Log the detailed error message when network error occurs + ## 2.4.0 - 2024-12-26 - Upgrade to Tauri 2.0 diff --git a/crates/auth/Cargo.toml b/crates/auth/Cargo.toml index 9e640f2b..21e456ac 100644 --- a/crates/auth/Cargo.toml +++ b/crates/auth/Cargo.toml @@ -31,6 +31,12 @@ html-escape = { version = "0.2.13", optional = true } [target.'cfg(not(target_os = "macos"))'.dependencies] webkit2gtk = { version = "2", optional = true } +[target.'cfg(target_os = "macos")'.dependencies] +block2 = { version = "0.5", optional = true } +objc2 = { version = "0.5", optional = true } +objc2-foundation = { version = "0.2", optional = true } +objc2-web-kit = { version = "0.2", optional = true } + [features] browser-auth = [ "dep:webbrowser", @@ -40,10 +46,14 @@ browser-auth = [ "dep:uuid", ] webview-auth = [ + "gpapi/tauri", "dep:tauri", "dep:regex", "dep:tokio-util", "dep:html-escape", "dep:webkit2gtk", - "gpapi/tauri", + "dep:block2", + "dep:objc2", + "dep:objc2-foundation", + "dep:objc2-web-kit", ] diff --git a/crates/auth/src/authenticator.rs b/crates/auth/src/authenticator.rs deleted file mode 100644 index 200d4fa9..00000000 --- a/crates/auth/src/authenticator.rs +++ /dev/null @@ -1,60 +0,0 @@ -use std::borrow::Cow; - -use anyhow::bail; -use gpapi::{ - gp_params::GpParams, - portal::{prelogin, Prelogin}, -}; - -pub struct Authenticator<'a> { - server: &'a str, - auth_request: Option<&'a str>, - pub(crate) gp_params: &'a GpParams, - - #[cfg(feature = "webview-auth")] - pub(crate) clean: bool, - #[cfg(feature = "webview-auth")] - pub(crate) is_retrying: tokio::sync::RwLock, -} - -impl<'a> Authenticator<'a> { - pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self { - Self { - server, - gp_params, - auth_request: None, - - #[cfg(feature = "webview-auth")] - clean: false, - #[cfg(feature = "webview-auth")] - is_retrying: Default::default(), - } - } - - pub fn with_auth_request(mut self, auth_request: &'a str) -> Self { - if !auth_request.is_empty() { - self.auth_request = Some(auth_request); - } - self - } - - pub(crate) async fn initial_auth_request(&self) -> anyhow::Result> { - if let Some(auth_request) = self.auth_request { - return Ok(Cow::Borrowed(auth_request)); - } - - let auth_request = self.portal_prelogin().await?; - Ok(Cow::Owned(auth_request)) - } - - pub(crate) async fn portal_prelogin(&self) -> anyhow::Result { - auth_prelogin(self.server, self.gp_params).await - } -} - -pub async fn auth_prelogin(server: &str, gp_params: &GpParams) -> anyhow::Result { - match prelogin(server, gp_params).await? { - Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()), - Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"), - } -} diff --git a/crates/auth/src/browser.rs b/crates/auth/src/browser.rs new file mode 100644 index 00000000..f800eb38 --- /dev/null +++ b/crates/auth/src/browser.rs @@ -0,0 +1,4 @@ +mod auth_server; +mod browser_auth; + +pub use browser_auth::BrowserAuthenticator; diff --git a/crates/auth/src/browser_auth/auth_server.rs b/crates/auth/src/browser/auth_server.rs similarity index 100% rename from crates/auth/src/browser_auth/auth_server.rs rename to crates/auth/src/browser/auth_server.rs diff --git a/crates/auth/src/browser_auth/browser_auth_impl.rs b/crates/auth/src/browser/browser_auth.rs similarity index 52% rename from crates/auth/src/browser_auth/browser_auth_impl.rs rename to crates/auth/src/browser/browser_auth.rs index 2d311525..c68e8b9c 100644 --- a/crates/auth/src/browser_auth/browser_auth_impl.rs +++ b/crates/auth/src/browser/browser_auth.rs @@ -4,30 +4,45 @@ use gpapi::{auth::SamlAuthData, GP_CALLBACK_PORT_FILENAME}; use log::info; use tokio::{io::AsyncReadExt, net::TcpListener}; -use super::auth_server::AuthServer; +use crate::browser::auth_server::AuthServer; -pub(super) struct BrowserAuthenticatorImpl<'a> { - auth_request: &'a str, - browser: Option<&'a str>, +pub enum Browser<'a> { + Default, + Chrome, + Firefox, + Other(&'a str), } -impl BrowserAuthenticatorImpl<'_> { - pub fn new(auth_request: &str) -> BrowserAuthenticatorImpl { - BrowserAuthenticatorImpl { - auth_request, - browser: None, +impl<'a> Browser<'a> { + pub fn from_str(browser: &'a str) -> Self { + match browser.to_lowercase().as_str() { + "default" => Browser::Default, + "chrome" => Browser::Chrome, + "firefox" => Browser::Firefox, + _ => Browser::Other(browser), + } + } + + fn as_str(&self) -> &str { + match self { + Browser::Default => "default", + Browser::Chrome => "chrome", + Browser::Firefox => "firefox", + Browser::Other(browser) => browser, } } +} - pub fn new_with_browser<'a>(auth_request: &'a str, browser: &'a str) -> BrowserAuthenticatorImpl<'a> { - let browser = browser.trim(); - BrowserAuthenticatorImpl { +pub struct BrowserAuthenticator<'a> { + auth_request: &'a str, + browser: Browser<'a>, +} + +impl<'a> BrowserAuthenticator<'a> { + pub fn new(auth_request: &'a str, browser: &'a str) -> Self { + Self { auth_request, - browser: if browser.is_empty() || browser == "default" { - None - } else { - Some(browser) - }, + browser: Browser::from_str(browser), } } @@ -40,14 +55,17 @@ impl BrowserAuthenticatorImpl<'_> { auth_server.serve_request(&auth_request); }); - if let Some(browser) = self.browser { - let app = find_browser_path(browser); - - info!("Launching browser: {}", app); - open::with_detached(auth_url, app)?; - } else { - info!("Launching the default browser..."); - webbrowser::open(&auth_url)?; + match self.browser { + Browser::Default => { + info!("Launching the default browser..."); + webbrowser::open(&auth_url)?; + } + _ => { + let app = find_browser_path(&self.browser); + + info!("Launching browser: {}", app); + open::with_detached(auth_url, app)?; + } } info!("Please continue the authentication process in the default browser"); @@ -55,15 +73,18 @@ impl BrowserAuthenticatorImpl<'_> { } } -fn find_browser_path(browser: &str) -> String { - if browser == "chrome" { - which::which("google-chrome-stable") - .or_else(|_| which::which("google-chrome")) - .or_else(|_| which::which("chromium")) - .map(|path| path.to_string_lossy().to_string()) - .unwrap_or_else(|_| browser.to_string()) - } else { - browser.into() +fn find_browser_path(browser: &Browser) -> String { + match browser { + Browser::Chrome => { + const CHROME_VARIANTS: &[&str] = &["google-chrome-stable", "google-chrome", "chromium"]; + + CHROME_VARIANTS + .iter() + .find_map(|&browser_name| which::which(browser_name).ok()) + .map(|path| path.to_string_lossy().to_string()) + .unwrap_or_else(|| browser.as_str().to_string()) + } + _ => browser.as_str().to_string(), } } diff --git a/crates/auth/src/browser_auth.rs b/crates/auth/src/browser_auth.rs deleted file mode 100644 index b8917d60..00000000 --- a/crates/auth/src/browser_auth.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod auth_server; -mod browser_auth_ext; -mod browser_auth_impl; - -pub use browser_auth_ext::BrowserAuthenticator; diff --git a/crates/auth/src/browser_auth/browser_auth_ext.rs b/crates/auth/src/browser_auth/browser_auth_ext.rs deleted file mode 100644 index fe6e8150..00000000 --- a/crates/auth/src/browser_auth/browser_auth_ext.rs +++ /dev/null @@ -1,22 +0,0 @@ -use std::future::Future; - -use gpapi::auth::SamlAuthData; - -use crate::{browser_auth::browser_auth_impl::BrowserAuthenticatorImpl, Authenticator}; - -pub trait BrowserAuthenticator { - fn browser_authenticate(&self, browser: Option<&str>) -> impl Future> + Send; -} - -impl BrowserAuthenticator for Authenticator<'_> { - async fn browser_authenticate(&self, browser: Option<&str>) -> anyhow::Result { - let auth_request = self.initial_auth_request().await?; - let browser_auth = if let Some(browser) = browser { - BrowserAuthenticatorImpl::new_with_browser(&auth_request, browser) - } else { - BrowserAuthenticatorImpl::new(&auth_request) - }; - - browser_auth.authenticate().await - } -} diff --git a/crates/auth/src/lib.rs b/crates/auth/src/lib.rs index ef46475f..165da6da 100644 --- a/crates/auth/src/lib.rs +++ b/crates/auth/src/lib.rs @@ -1,13 +1,23 @@ -mod authenticator; -pub use authenticator::auth_prelogin; -pub use authenticator::Authenticator; +use anyhow::bail; +use gpapi::{ + gp_params::GpParams, + portal::{prelogin, Prelogin}, +}; #[cfg(feature = "browser-auth")] -mod browser_auth; +mod browser; + #[cfg(feature = "browser-auth")] -pub use browser_auth::BrowserAuthenticator; +pub use browser::*; #[cfg(feature = "webview-auth")] -mod webview_auth; +mod webview; #[cfg(feature = "webview-auth")] -pub use webview_auth::WebviewAuthenticator; +pub use webview::*; + +pub async fn auth_prelogin(server: &str, gp_params: &GpParams) -> anyhow::Result { + match prelogin(server, gp_params).await? { + Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()), + Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"), + } +} diff --git a/crates/auth/src/webview.rs b/crates/auth/src/webview.rs new file mode 100644 index 00000000..fc0a97ad --- /dev/null +++ b/crates/auth/src/webview.rs @@ -0,0 +1,8 @@ +mod auth_messenger; +mod webview_auth; + +#[cfg_attr(not(target_os = "macos"), path = "webview/unix.rs")] +#[cfg_attr(target_os = "macos", path = "webview/macos.rs")] +mod platform_impl; + +pub use webview_auth::WebviewAuthenticator; diff --git a/crates/auth/src/webview/auth_messenger.rs b/crates/auth/src/webview/auth_messenger.rs new file mode 100644 index 00000000..5d70f416 --- /dev/null +++ b/crates/auth/src/webview/auth_messenger.rs @@ -0,0 +1,229 @@ +use anyhow::bail; +use gpapi::{auth::SamlAuthData, error::AuthDataParseError}; +use log::{error, info}; +use regex::Regex; +use tokio::sync::{mpsc, RwLock}; +use tokio_util::sync::CancellationToken; + +#[derive(Debug)] +pub(crate) enum AuthDataLocation { + #[cfg(not(target_os = "macos"))] + Headers, + Body, +} + +#[derive(Debug)] +pub(crate) enum AuthError { + /// Failed to load page due to TLS error + #[cfg(not(target_os = "macos"))] + TlsError, + /// 1. Found auth data in headers/body but it's invalid + /// 2. Loaded an empty page, failed to load page. etc. + Invalid(anyhow::Error, AuthDataLocation), + /// No auth data found in headers/body + NotFound(AuthDataLocation), +} + +impl AuthError { + pub fn invalid_from_body(err: anyhow::Error) -> Self { + Self::Invalid(err, AuthDataLocation::Body) + } + + pub fn not_found_in_body() -> Self { + Self::NotFound(AuthDataLocation::Body) + } +} + +#[cfg(not(target_os = "macos"))] +impl AuthError { + pub fn not_found_in_headers() -> Self { + Self::NotFound(AuthDataLocation::Headers) + } +} + +pub(crate) enum AuthEvent { + Data(SamlAuthData, AuthDataLocation), + Error(AuthError), + RaiseWindow, + Close, +} + +pub struct AuthMessenger { + tx: mpsc::UnboundedSender, + rx: RwLock>, + raise_window_cancel_token: RwLock>, +} + +impl AuthMessenger { + pub fn new() -> Self { + let (tx, rx) = mpsc::unbounded_channel(); + + Self { + tx, + rx: RwLock::new(rx), + raise_window_cancel_token: Default::default(), + } + } + + pub async fn subscribe(&self) -> anyhow::Result { + let mut rx = self.rx.write().await; + if let Some(event) = rx.recv().await { + return Ok(event); + } + bail!("Failed to receive auth event"); + } + + pub fn send_auth_event(&self, event: AuthEvent) { + if let Err(event) = self.tx.send(event) { + error!("Failed to send auth event: {}", event); + } + } + + pub fn send_auth_error(&self, err: AuthError) { + self.send_auth_event(AuthEvent::Error(err)); + } + + fn send_auth_data(&self, data: SamlAuthData, location: AuthDataLocation) { + self.send_auth_event(AuthEvent::Data(data, location)); + } + + pub fn schedule_raise_window(&self, delay: u64) { + let Ok(mut guard) = self.raise_window_cancel_token.try_write() else { + return; + }; + + // Return if the previous raise window task is still running + if let Some(token) = guard.as_ref() { + if !token.is_cancelled() { + info!("Raise window task is still running, skipping..."); + return; + } + } + + let cancel_token = CancellationToken::new(); + let cancel_token_clone = cancel_token.clone(); + + *guard = Some(cancel_token_clone); + + let tx = self.tx.clone(); + tokio::spawn(async move { + info!("Displaying the window in {} second(s)...", delay); + + tokio::select! { + _ = tokio::time::sleep(tokio::time::Duration::from_secs(delay)) => { + cancel_token.cancel(); + + if let Err(err) = tx.send(AuthEvent::RaiseWindow) { + error!("Failed to send raise window event: {}", err); + } + } + _ = cancel_token.cancelled() => { + info!("Cancelled raise window task"); + } + } + }); + } + + pub fn cancel_raise_window(&self) { + if let Ok(mut cancel_token) = self.raise_window_cancel_token.try_write() { + if let Some(token) = cancel_token.take() { + token.cancel(); + } + } + } + + pub fn read_from_html(&self, html: &str) { + if html.contains("Temporarily Unavailable") { + return self.send_auth_error(AuthError::invalid_from_body(anyhow::anyhow!("Temporarily Unavailable"))); + } + + let auth_result = SamlAuthData::from_html(html).or_else(|err| { + info!("Read auth data from html failed: {}, extracting gpcallback...", err); + + if let Some(gpcallback) = extract_gpcallback(html) { + info!("Found gpcallback from html..."); + SamlAuthData::from_gpcallback(&gpcallback) + } else { + Err(err) + } + }); + + match auth_result { + Ok(data) => self.send_auth_data(data, AuthDataLocation::Body), + Err(AuthDataParseError::Invalid(err)) => self.send_auth_error(AuthError::invalid_from_body(err)), + Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()), + } + } + + #[cfg(not(target_os = "macos"))] + pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) { + use log::warn; + + let Some(status) = auth_response.get_header("saml-auth-status") else { + return self.send_auth_error(AuthError::not_found_in_headers()); + }; + + // Do not send auth error when reading from headers, as the html body may contain the auth data + if status != "1" { + warn!("Found invalid saml-auth-status in headers: {}", status); + return; + } + + let username = auth_response.get_header("saml-username"); + let prelogin_cookie = auth_response.get_header("prelogin-cookie"); + let portal_userauthcookie = auth_response.get_header("portal-userauthcookie"); + + match SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie) { + Ok(auth_data) => self.send_auth_data(auth_data, AuthDataLocation::Headers), + Err(err) => { + warn!("Failed to read auth data from headers: {}", err); + } + } + } +} + +fn extract_gpcallback(html: &str) -> Option { + let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap(); + re.captures(html) + .and_then(|captures| captures.get(0)) + .map(|m| html_escape::decode_html_entities(m.as_str()).to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extract_gpcallback_some() { + let html = r#" + + + "#; + + assert_eq!( + extract_gpcallback(html).as_deref(), + Some("globalprotectcallback:PGh0bWw+PCEtLSA8c") + ); + } + + #[test] + fn extract_gpcallback_cas() { + let html = r#" + + "#; + + assert_eq!( + extract_gpcallback(html).as_deref(), + Some("globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string") + ); + } + + #[test] + fn extract_gpcallback_none() { + let html = r#" + + "#; + + assert_eq!(extract_gpcallback(html), None); + } +} diff --git a/crates/auth/src/webview/macos.rs b/crates/auth/src/webview/macos.rs new file mode 100644 index 00000000..1c70697e --- /dev/null +++ b/crates/auth/src/webview/macos.rs @@ -0,0 +1,58 @@ +use block2::RcBlock; +use log::warn; +use objc2::runtime::AnyObject; +use objc2_foundation::{NSError, NSString, NSURLRequest, NSURL}; +use objc2_web_kit::WKWebView; +use tauri::webview::PlatformWebview; + +use super::webview_auth::PlatformWebviewExt; + +impl PlatformWebviewExt for PlatformWebview { + fn ignore_tls_errors(&self) -> anyhow::Result<()> { + warn!("Ignoring TLS errors is not supported on macOS"); + Ok(()) + } + + fn load_url(&self, url: &str) -> anyhow::Result<()> { + unsafe { + let wv: &WKWebView = &*self.inner().cast(); + let url = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| anyhow::anyhow!("Invalid URL"))?; + let request = NSURLRequest::requestWithURL(&url); + + wv.loadRequest(&request); + } + + Ok(()) + } + + fn load_html(&self, html: &str) -> anyhow::Result<()> { + unsafe { + let wv: &WKWebView = &*self.inner().cast(); + wv.loadHTMLString_baseURL(&NSString::from_str(html), None); + } + + Ok(()) + } + + fn get_html(&self, callback: Box) + 'static>) { + unsafe { + let wv: &WKWebView = &*self.inner().cast(); + + let js_callback = RcBlock::new(move |body: *mut AnyObject, err: *mut NSError| { + if let Some(err) = err.as_ref() { + let code = err.code(); + let message = err.localizedDescription(); + callback(Err(anyhow::anyhow!("Error {}: {}", code, message))); + } else { + let body: &NSString = &*body.cast(); + callback(Ok(body.to_string())); + } + }); + + wv.evaluateJavaScript_completionHandler( + &NSString::from_str("document.documentElement.outerHTML"), + Some(&js_callback), + ); + } + } +} diff --git a/crates/auth/src/webview/unix.rs b/crates/auth/src/webview/unix.rs new file mode 100644 index 00000000..31af7077 --- /dev/null +++ b/crates/auth/src/webview/unix.rs @@ -0,0 +1,105 @@ +use std::sync::Arc; + +use anyhow::bail; +use gpapi::utils::redact::redact_uri; +use log::warn; +use tauri::webview::PlatformWebview; +use webkit2gtk::{ + gio::Cancellable, glib::GString, LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, + WebsiteDataManagerExt, +}; + +use super::{ + auth_messenger::AuthError, + webview_auth::{GetHeader, PlatformWebviewExt}, +}; + +impl GetHeader for WebResource { + fn get_header(&self, key: &str) -> Option { + self + .response() + .and_then(|response| response.http_headers()) + .and_then(|headers| headers.one(key)) + .map(GString::into) + } +} + +impl PlatformWebviewExt for PlatformWebview { + fn ignore_tls_errors(&self) -> anyhow::Result<()> { + if let Some(manager) = self.inner().website_data_manager() { + manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore); + return Ok(()); + } + bail!("Failed to get website data manager"); + } + + fn load_url(&self, url: &str) -> anyhow::Result<()> { + self.inner().load_uri(url); + Ok(()) + } + + fn load_html(&self, html: &str) -> anyhow::Result<()> { + self.inner().load_html(html, None); + Ok(()) + } + + fn get_html(&self, callback: Box) + 'static>) { + let script = "document.documentElement.outerHTML"; + self + .inner() + .evaluate_javascript(script, None, None, Cancellable::NONE, move |result| match result { + Ok(value) => callback(Ok(value.to_string())), + Err(err) => callback(Err(anyhow::anyhow!(err))), + }); + } +} + +pub trait PlatformWebviewOnResponse { + fn on_response(&self, callback: Box) + 'static>); +} + +impl PlatformWebviewOnResponse for PlatformWebview { + fn on_response(&self, callback: Box) + 'static>) { + let wv = self.inner(); + let callback = Arc::new(callback); + let callback_clone = Arc::clone(&callback); + + wv.connect_load_changed(move |wv, event| { + if event != LoadEvent::Finished { + return; + } + + let Some(web_resource) = wv.main_resource() else { + return; + }; + + let uri = web_resource.uri().unwrap_or("".into()); + if uri.is_empty() { + callback_clone(Err(AuthError::invalid_from_body(anyhow::anyhow!("Empty URI")))); + } else { + callback_clone(Ok(web_resource)); + } + }); + + wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| { + let redacted_uri = redact_uri(uri); + warn!( + "Failed to load uri: {} with error: {}, cert: {}", + redacted_uri, err, cert + ); + + callback(Err(AuthError::TlsError)); + true + }); + + wv.connect_load_failed(move |_wv, _event, uri, err| { + let redacted_uri = redact_uri(uri); + if !uri.starts_with("globalprotectcallback:") { + warn!("Failed to load uri: {} with error: {}", redacted_uri, err); + } + // NOTE: Don't send error here, since load_changed event will be triggered after this + // true to stop other handlers from being invoked for the event. false to propagate the event further. + true + }); + } +} diff --git a/crates/auth/src/webview/webview_auth.rs b/crates/auth/src/webview/webview_auth.rs new file mode 100644 index 00000000..4f1ec717 --- /dev/null +++ b/crates/auth/src/webview/webview_auth.rs @@ -0,0 +1,277 @@ +use std::{sync::Arc, time::Duration}; + +use anyhow::bail; +use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri}; +use log::{info, warn}; +use tauri::{ + webview::{PageLoadEvent, PageLoadPayload}, + AppHandle, WebviewUrl, WebviewWindow, WindowEvent, +}; +use tokio::{sync::oneshot, time}; + +use crate::auth_prelogin; + +use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger}; + +pub trait PlatformWebviewExt { + fn ignore_tls_errors(&self) -> anyhow::Result<()>; + + fn load_url(&self, url: &str) -> anyhow::Result<()>; + + fn load_html(&self, html: &str) -> anyhow::Result<()>; + + fn get_html(&self, callback: Box) + 'static>); + + fn load_auth_request(&self, auth_request: &str) -> anyhow::Result<()> { + if auth_request.starts_with("http") { + info!("Loading auth request as URL: {}", redact_uri(auth_request)); + self.load_url(auth_request) + } else { + info!("Loading auth request as HTML..."); + self.load_html(auth_request) + } + } +} + +#[cfg(not(target_os = "macos"))] +pub trait GetHeader { + fn get_header(&self, key: &str) -> Option; +} + +pub struct WebviewAuthenticator<'a> { + server: &'a str, + gp_params: &'a GpParams, + auth_request: Option<&'a str>, + clean: bool, + + is_retrying: tokio::sync::RwLock, +} + +impl<'a> WebviewAuthenticator<'a> { + pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self { + Self { + server, + gp_params, + auth_request: None, + clean: false, + is_retrying: Default::default(), + } + } + + pub fn with_auth_request(mut self, auth_request: &'a str) -> Self { + self.auth_request = Some(auth_request); + self + } + + pub fn with_clean(mut self, clean: bool) -> Self { + self.clean = clean; + self + } + + pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result { + let auth_messenger = Arc::new(AuthMessenger::new()); + let auth_messenger_clone = Arc::clone(&auth_messenger); + + let on_page_load = move |auth_window: WebviewWindow, event: PageLoadPayload<'_>| { + let auth_messenger_clone = Arc::clone(&auth_messenger_clone); + let redacted_url = redact_uri(event.url().as_str()); + + match event.event() { + PageLoadEvent::Started => { + info!("Started loading page: {}", redacted_url); + auth_messenger_clone.cancel_raise_window(); + } + PageLoadEvent::Finished => { + info!("Finished loading page: {}", redacted_url); + } + } + + // Read auth data from the page no matter whether it's finished loading or not + // Because we found that the finished event may not be triggered in some cases (e.g., on macOS) + let _ = auth_window.with_webview(move |wv| { + wv.get_html(Box::new(move |html| match html { + Ok(html) => auth_messenger_clone.read_from_html(&html), + Err(err) => warn!("Failed to get html: {}", err), + })); + }); + }; + + let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 }; + + let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default()) + .on_page_load(on_page_load) + .title("GlobalProtect Login") + .inner_size(900.0, 650.0 + title_bar_height) + .focused(true) + .visible(false) + .center() + .build()?; + + self + .setup_auth_window(&auth_window, Arc::clone(&auth_messenger)) + .await?; + + loop { + match auth_messenger.subscribe().await? { + AuthEvent::Close => bail!("Authentication cancelled"), + AuthEvent::RaiseWindow => self.raise_window(&auth_window), + #[cfg(not(target_os = "macos"))] + AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError), + AuthEvent::Error(AuthError::NotFound(location)) => { + info!( + "No auth data found in {:?}, it may not be the /SAML20/SP/ACS endpoint", + location + ); + self.handle_not_found(&auth_window, &auth_messenger); + } + AuthEvent::Error(AuthError::Invalid(err, location)) => { + warn!("Got invalid auth data in {:?}: {}", location, err); + self.retry_auth(&auth_window).await; + } + AuthEvent::Data(auth_data, location) => { + info!("Got auth data from {:?}", location); + + auth_window.close()?; + return Ok(auth_data); + } + } + } + } + + async fn setup_auth_window( + &self, + auth_window: &WebviewWindow, + auth_messenger: Arc, + ) -> anyhow::Result<()> { + info!("Setting up auth window..."); + + if self.clean { + info!("Clearing all browsing data..."); + auth_window.clear_all_browsing_data()?; + } + + // Handle window close event + let auth_messenger_clone = Arc::clone(&auth_messenger); + auth_window.on_window_event(move |event| { + if let WindowEvent::CloseRequested { .. } = event { + auth_messenger_clone.send_auth_event(AuthEvent::Close); + } + }); + + // Show the window after 10 seconds, so that the user can see the window if the auth process is stuck + let auth_messenger_clone = Arc::clone(&auth_messenger); + tokio::spawn(async move { + time::sleep(Duration::from_secs(10)).await; + auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow); + }); + + let auth_request = match self.auth_request { + Some(auth_request) => auth_request.to_string(), + None => auth_prelogin(&self.server, &self.gp_params).await?, + }; + + let (tx, rx) = oneshot::channel::>(); + let ignore_tls_errors = self.gp_params.ignore_tls_errors(); + + // Set up webview + auth_window.with_webview(move |wv| { + #[cfg(not(target_os = "macos"))] + { + use super::platform_impl::PlatformWebviewOnResponse; + wv.on_response(Box::new(move |response| match response { + Ok(response) => auth_messenger.read_from_response(&response), + Err(err) => auth_messenger.send_auth_error(err), + })); + } + + let result = || -> anyhow::Result<()> { + if ignore_tls_errors { + wv.ignore_tls_errors()?; + } + + wv.load_auth_request(&auth_request) + }(); + + if let Err(result) = tx.send(result) { + warn!("Failed to send setup auth window result: {:?}", result); + } + })?; + + rx.await??; + info!("Auth window setup completed"); + + Ok(()) + } + + fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc) { + let visible = auth_window.is_visible().unwrap_or(false); + if visible { + return; + } + + auth_messenger.schedule_raise_window(2); + } + + async fn retry_auth(&self, auth_window: &WebviewWindow) { + let mut is_retrying = self.is_retrying.write().await; + if *is_retrying { + info!("Already retrying authentication, skipping..."); + return; + } + + *is_retrying = true; + drop(is_retrying); + + if let Err(err) = self.retry_auth_impl(auth_window).await { + warn!("Failed to retry authentication: {}", err); + } + + *self.is_retrying.write().await = false; + } + + async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> { + info!("Retrying authentication..."); + + auth_window.eval( r#" + var loading = document.createElement("div"); + loading.innerHTML = '
Got invalid token, retrying...
'; + loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;"; + document.body.appendChild(loading); + "#)?; + + let auth_request = auth_prelogin(&self.server, &self.gp_params).await?; + let (tx, rx) = oneshot::channel::>(); + auth_window.with_webview(move |wv| { + let result = wv.load_auth_request(&auth_request); + if let Err(result) = tx.send(result) { + warn!("Failed to send retry auth result: {:?}", result); + } + })?; + + rx.await??; + + Ok(()) + } + + fn raise_window(&self, auth_window: &WebviewWindow) { + let visible = auth_window.is_visible().unwrap_or(false); + if visible { + return; + } + + info!("Raising auth window..."); + + #[cfg(target_os = "macos")] + let result = auth_window.show(); + + #[cfg(not(target_os = "macos"))] + let result = { + use gpapi::utils::window::WindowExt; + auth_window.raise() + }; + + if let Err(err) = result { + warn!("Failed to raise window: {}", err); + } + } +} diff --git a/crates/auth/src/webview_auth.rs b/crates/auth/src/webview_auth.rs deleted file mode 100644 index cc9e2966..00000000 --- a/crates/auth/src/webview_auth.rs +++ /dev/null @@ -1,9 +0,0 @@ -mod auth_messenger; -mod auth_response; -mod auth_settings; -mod webview_auth_ext; - -#[cfg_attr(not(target_os = "macos"), path = "webview_auth/unix.rs")] -mod platform_impl; - -pub use webview_auth_ext::WebviewAuthenticator; diff --git a/crates/auth/src/webview_auth/auth_messenger.rs b/crates/auth/src/webview_auth/auth_messenger.rs deleted file mode 100644 index 29e4da89..00000000 --- a/crates/auth/src/webview_auth/auth_messenger.rs +++ /dev/null @@ -1,108 +0,0 @@ -use anyhow::bail; -use gpapi::auth::SamlAuthData; -use log::{error, info}; -use tokio::sync::{mpsc, RwLock}; -use tokio_util::sync::CancellationToken; - -pub enum AuthError { - /// Failed to load page due to TLS error - TlsError, - /// 1. Found auth data in headers/body but it's invalid - /// 2. Loaded an empty page, failed to load page. etc. - Invalid, - /// No auth data found in headers/body - NotFound, -} - -pub type AuthResult = anyhow::Result; - -pub enum AuthEvent { - Data(SamlAuthData), - Error(AuthError), - RaiseWindow, - Close, -} - -pub struct AuthMessenger { - tx: mpsc::UnboundedSender, - rx: RwLock>, - raise_window_cancel_token: RwLock>, -} - -impl AuthMessenger { - pub fn new() -> Self { - let (tx, rx) = mpsc::unbounded_channel(); - - Self { - tx, - rx: RwLock::new(rx), - raise_window_cancel_token: Default::default(), - } - } - - pub async fn subscribe(&self) -> anyhow::Result { - let mut rx = self.rx.write().await; - if let Some(event) = rx.recv().await { - return Ok(event); - } - bail!("Failed to receive auth event"); - } - - pub fn send_auth_event(&self, event: AuthEvent) { - if let Err(event) = self.tx.send(event) { - error!("Failed to send auth event: {}", event); - } - } - - pub fn send_auth_result(&self, result: AuthResult) { - match result { - Ok(data) => self.send_auth_data(data), - Err(err) => self.send_auth_error(err), - } - } - - pub fn send_auth_error(&self, err: AuthError) { - self.send_auth_event(AuthEvent::Error(err)); - } - - pub fn send_auth_data(&self, data: SamlAuthData) { - self.send_auth_event(AuthEvent::Data(data)); - } - - pub fn schedule_raise_window(&self, delay: u64) { - let cancel_token = CancellationToken::new(); - let cancel_token_clone = cancel_token.clone(); - - if let Ok(mut guard) = self.raise_window_cancel_token.try_write() { - // Cancel the previous raise window task if it exists - if let Some(token) = guard.take() { - token.cancel(); - } - *guard = Some(cancel_token_clone); - } - - let tx = self.tx.clone(); - tokio::spawn(async move { - info!("Displaying the window in {} second(s)...", delay); - - tokio::select! { - _ = tokio::time::sleep(tokio::time::Duration::from_secs(delay)) => { - if let Err(err) = tx.send(AuthEvent::RaiseWindow) { - error!("Failed to send raise window event: {}", err); - } - } - _ = cancel_token.cancelled() => { - info!("Cancelled raise window task"); - } - } - }); - } - - pub fn cancel_raise_window(&self) { - if let Ok(mut cancel_token) = self.raise_window_cancel_token.try_write() { - if let Some(token) = cancel_token.take() { - token.cancel(); - } - } - } -} diff --git a/crates/auth/src/webview_auth/auth_response.rs b/crates/auth/src/webview_auth/auth_response.rs deleted file mode 100644 index 75a5a65b..00000000 --- a/crates/auth/src/webview_auth/auth_response.rs +++ /dev/null @@ -1,152 +0,0 @@ -use std::sync::Arc; - -use gpapi::{ - auth::{AuthDataParseResult, SamlAuthData}, - error::AuthDataParseError, -}; -use log::{info, warn}; -use regex::Regex; - -use crate::webview_auth::auth_messenger::{AuthError, AuthMessenger}; - -/// Trait for handling authentication response -pub trait AuthResponse { - fn get_header(&self, key: &str) -> Option; - fn get_body(&self, cb: F) - where - F: FnOnce(anyhow::Result>) + 'static; - - fn url(&self) -> Option; - - fn is_acs_endpoint(&self) -> bool { - self.url().map_or(false, |url| url.ends_with("/SAML20/SP/ACS")) - } -} - -pub fn read_auth_data(auth_response: &impl AuthResponse, auth_messenger: &Arc) { - let auth_messenger = Arc::clone(auth_messenger); - - match read_from_headers(auth_response) { - Ok(auth_data) => { - info!("Found auth data in headers"); - auth_messenger.send_auth_data(auth_data); - } - Err(header_err) => { - info!("Failed to read auth data from headers: {}", header_err); - - let is_acs_endpoint = auth_response.is_acs_endpoint(); - read_from_body(auth_response, move |auth_result| { - // If the endpoint is `/SAML20/SP/ACS` and no auth data found in body, it should be considered as invalid - let auth_result = auth_result.map_err(move |e| { - info!("Failed to read auth data from body: {}", e); - if is_acs_endpoint || e.is_invalid() || header_err.is_invalid() { - AuthError::Invalid - } else { - AuthError::NotFound - } - }); - - auth_messenger.send_auth_result(auth_result); - }); - } - } -} - -fn read_from_headers(auth_response: &impl AuthResponse) -> AuthDataParseResult { - let Some(status) = auth_response.get_header("saml-auth-status") else { - info!("No SAML auth status found in headers"); - return Err(AuthDataParseError::NotFound); - }; - - if status != "1" { - info!("Found invalid auth status: {}", status); - return Err(AuthDataParseError::Invalid); - } - - let username = auth_response.get_header("saml-username"); - let prelogin_cookie = auth_response.get_header("prelogin-cookie"); - let portal_userauthcookie = auth_response.get_header("portal-userauthcookie"); - - SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(|e| { - warn!("Found invalid auth data: {}", e); - AuthDataParseError::Invalid - }) -} - -fn read_from_body(auth_response: &impl AuthResponse, cb: F) -where - F: FnOnce(AuthDataParseResult) + 'static, -{ - auth_response.get_body(|body| match body { - Ok(body) => { - let html = String::from_utf8_lossy(&body); - cb(read_from_html(&html)) - } - Err(err) => { - info!("Failed to read body: {}", err); - cb(Err(AuthDataParseError::Invalid)) - } - }); -} - -fn read_from_html(html: &str) -> AuthDataParseResult { - if html.contains("Temporarily Unavailable") { - info!("Found 'Temporarily Unavailable' in HTML, auth failed"); - return Err(AuthDataParseError::Invalid); - } - - SamlAuthData::from_html(html).or_else(|err| { - if let Some(gpcallback) = extract_gpcallback(html) { - info!("Found gpcallback from html..."); - SamlAuthData::from_gpcallback(&gpcallback) - } else { - Err(err) - } - }) -} - -fn extract_gpcallback(html: &str) -> Option { - let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap(); - re.captures(html) - .and_then(|captures| captures.get(0)) - .map(|m| html_escape::decode_html_entities(m.as_str()).to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn extract_gpcallback_some() { - let html = r#" - - - "#; - - assert_eq!( - extract_gpcallback(html).as_deref(), - Some("globalprotectcallback:PGh0bWw+PCEtLSA8c") - ); - } - - #[test] - fn extract_gpcallback_cas() { - let html = r#" - - "#; - - assert_eq!( - extract_gpcallback(html).as_deref(), - Some("globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string") - ); - } - - #[test] - fn extract_gpcallback_none() { - let html = r#" - - "#; - - assert_eq!(extract_gpcallback(html), None); - } -} diff --git a/crates/auth/src/webview_auth/auth_settings.rs b/crates/auth/src/webview_auth/auth_settings.rs deleted file mode 100644 index 6adb90e1..00000000 --- a/crates/auth/src/webview_auth/auth_settings.rs +++ /dev/null @@ -1,25 +0,0 @@ -use std::sync::Arc; - -use super::auth_messenger::AuthMessenger; - -pub struct AuthRequest<'a>(&'a str); - -impl<'a> AuthRequest<'a> { - pub fn new(auth_request: &'a str) -> Self { - Self(auth_request) - } - - pub fn is_url(&self) -> bool { - self.0.starts_with("http") - } - - pub fn as_str(&self) -> &str { - self.0 - } -} - -pub struct AuthSettings<'a> { - pub auth_request: AuthRequest<'a>, - pub auth_messenger: Arc, - pub ignore_tls_errors: bool, -} diff --git a/crates/auth/src/webview_auth/unix.rs b/crates/auth/src/webview_auth/unix.rs deleted file mode 100644 index 05ce6555..00000000 --- a/crates/auth/src/webview_auth/unix.rs +++ /dev/null @@ -1,136 +0,0 @@ -use std::sync::Arc; - -use anyhow::bail; -use gpapi::utils::redact::redact_uri; -use log::{info, warn}; -use webkit2gtk::{ - gio::Cancellable, - glib::{GString, TimeSpan}, - LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebView, WebViewExt, WebsiteDataManagerExt, - WebsiteDataManagerExtManual, WebsiteDataTypes, -}; - -use crate::webview_auth::{ - auth_messenger::AuthError, - auth_response::read_auth_data, - auth_settings::{AuthRequest, AuthSettings}, -}; - -use super::auth_response::AuthResponse; - -impl AuthResponse for WebResource { - fn get_header(&self, key: &str) -> Option { - self - .response() - .and_then(|response| response.http_headers()) - .and_then(|headers| headers.one(key)) - .map(GString::into) - } - - fn get_body(&self, cb: F) - where - F: FnOnce(anyhow::Result>) + 'static, - { - let cancellable = Cancellable::NONE; - self.data(cancellable, |data| cb(data.map_err(|e| anyhow::anyhow!(e)))); - } - - fn url(&self) -> Option { - self.uri().map(GString::into) - } -} - -pub fn clear_data(wv: &WebView, cb: F) -where - F: FnOnce(anyhow::Result<()>) + Send + 'static, -{ - let Some(data_manager) = wv.website_data_manager() else { - cb(Err(anyhow::anyhow!("Failed to get website data manager"))); - return; - }; - - data_manager.clear( - WebsiteDataTypes::COOKIES, - TimeSpan(0), - Cancellable::NONE, - move |result| { - cb(result.map_err(|e| anyhow::anyhow!(e))); - }, - ); -} - -pub fn setup_webview(wv: &WebView, auth_settings: AuthSettings) -> anyhow::Result<()> { - let AuthSettings { - auth_request, - auth_messenger, - ignore_tls_errors, - } = auth_settings; - let auth_messenger_clone = Arc::clone(&auth_messenger); - - let Some(data_manager) = wv.website_data_manager() else { - bail!("Failed to get website data manager"); - }; - - if ignore_tls_errors { - data_manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore); - } - - wv.connect_load_changed(move |wv, event| { - if event == LoadEvent::Started { - auth_messenger_clone.cancel_raise_window(); - return; - } - - if event != LoadEvent::Finished { - return; - } - - let Some(main_resource) = wv.main_resource() else { - return; - }; - - let uri = main_resource.uri().unwrap_or("".into()); - if uri.is_empty() { - warn!("Loaded an empty URI"); - auth_messenger_clone.send_auth_error(AuthError::Invalid); - return; - } - - read_auth_data(&main_resource, &auth_messenger_clone); - }); - - wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| { - let redacted_uri = redact_uri(uri); - warn!( - "Failed to load uri: {} with error: {}, cert: {}", - redacted_uri, err, cert - ); - - auth_messenger.send_auth_error(AuthError::TlsError); - true - }); - - wv.connect_load_failed(move |_wv, _event, uri, err| { - let redacted_uri = redact_uri(uri); - if !uri.starts_with("globalprotectcallback:") { - warn!("Failed to load uri: {} with error: {}", redacted_uri, err); - } - // NOTE: Don't send error here, since load_changed event will be triggered after this - // true to stop other handlers from being invoked for the event. false to propagate the event further. - true - }); - - load_auth_request(wv, &auth_request); - - Ok(()) -} - -pub fn load_auth_request(wv: &WebView, auth_request: &AuthRequest) { - if auth_request.is_url() { - info!("Loading auth request as URI..."); - wv.load_uri(auth_request.as_str()); - } else { - info!("Loading auth request as HTML..."); - wv.load_html(auth_request.as_str(), None); - } -} diff --git a/crates/auth/src/webview_auth/webview_auth_ext.rs b/crates/auth/src/webview_auth/webview_auth_ext.rs deleted file mode 100644 index 0b7b7e5f..00000000 --- a/crates/auth/src/webview_auth/webview_auth_ext.rs +++ /dev/null @@ -1,194 +0,0 @@ -use std::{ - future::Future, - sync::Arc, - time::{Duration, Instant}, -}; - -use anyhow::bail; -use gpapi::{auth::SamlAuthData, error::PortalError, utils::window::WindowExt}; -use log::{info, warn}; -use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent}; -use tokio::{sync::oneshot, time}; - -use crate::{ - webview_auth::{ - auth_messenger::{AuthError, AuthEvent, AuthMessenger}, - auth_settings::{AuthRequest, AuthSettings}, - platform_impl, - }, - Authenticator, -}; - -pub trait WebviewAuthenticator { - fn with_clean(self, clean: bool) -> Self; - fn webview_authenticate(&self, app_handle: &AppHandle) -> impl Future> + Send; -} - -impl WebviewAuthenticator for Authenticator<'_> { - fn with_clean(mut self, clean: bool) -> Self { - self.clean = clean; - self - } - - async fn webview_authenticate(&self, app_handle: &AppHandle) -> anyhow::Result { - let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default()) - .title("GlobalProtect Login") - .focused(true) - .visible(false) - .center() - .build()?; - - self.auth_loop(&auth_window).await - } -} - -impl Authenticator<'_> { - async fn auth_loop(&self, auth_window: &WebviewWindow) -> anyhow::Result { - if self.clean { - self.clear_webview_data(&auth_window).await?; - } - - let auth_messenger = self.setup_auth_window(&auth_window).await?; - - loop { - match auth_messenger.subscribe().await? { - AuthEvent::Close => bail!("Authentication cancelled"), - AuthEvent::RaiseWindow => self.raise_window(auth_window), - AuthEvent::Error(AuthError::TlsError) => bail!(PortalError::TlsError), - AuthEvent::Error(AuthError::NotFound) => self.handle_not_found(auth_window, &auth_messenger), - AuthEvent::Error(AuthError::Invalid) => self.retry_auth(auth_window).await, - AuthEvent::Data(auth_data) => { - auth_window.close()?; - return Ok(auth_data); - } - } - } - } - - async fn clear_webview_data(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> { - info!("Clearing webview data..."); - - let (tx, rx) = oneshot::channel::>(); - let now = Instant::now(); - auth_window.with_webview(|webview| { - platform_impl::clear_data(&webview.inner(), |result| { - if let Err(result) = tx.send(result) { - warn!("Failed to send clear data result: {:?}", result); - } - }) - })?; - - rx.await??; - info!("Webview data cleared in {:?}", now.elapsed()); - - Ok(()) - } - - async fn setup_auth_window(&self, auth_window: &WebviewWindow) -> anyhow::Result> { - info!("Setting up auth window..."); - - let auth_messenger = Arc::new(AuthMessenger::new()); - let auth_request = self.initial_auth_request().await?.into_owned(); - let ignore_tls_errors = self.gp_params.ignore_tls_errors(); - - // Handle window close event - let auth_messenger_clone = Arc::clone(&auth_messenger); - auth_window.on_window_event(move |event| { - if let WindowEvent::CloseRequested { .. } = event { - auth_messenger_clone.send_auth_event(AuthEvent::Close); - } - }); - - // Show the window after 10 seconds, so that the user can see the window if the auth process is stuck - let auth_messenger_clone = Arc::clone(&auth_messenger); - tokio::spawn(async move { - time::sleep(Duration::from_secs(10)).await; - auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow); - }); - - // setup webview - let auth_messenger_clone = Arc::clone(&auth_messenger); - let (tx, rx) = oneshot::channel::>(); - - auth_window.with_webview(move |webview| { - let auth_settings = AuthSettings { - auth_request: AuthRequest::new(&auth_request), - auth_messenger: auth_messenger_clone, - ignore_tls_errors, - }; - - let result = platform_impl::setup_webview(&webview.inner(), auth_settings); - if let Err(result) = tx.send(result) { - warn!("Failed to send setup auth window result: {:?}", result); - } - })?; - - rx.await??; - info!("Auth window setup completed"); - - Ok(auth_messenger) - } - - fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc) { - info!("No auth data found, it may not be the /SAML20/SP/ACS endpoint"); - - let visible = auth_window.is_visible().unwrap_or(false); - if visible { - return; - } - - auth_messenger.schedule_raise_window(1); - } - - async fn retry_auth(&self, auth_window: &WebviewWindow) { - let mut is_retrying = self.is_retrying.write().await; - if *is_retrying { - info!("Already retrying authentication, skipping..."); - return; - } - - *is_retrying = true; - drop(is_retrying); - - if let Err(err) = self.retry_auth_impl(auth_window).await { - warn!("Failed to retry authentication: {}", err); - } - - *self.is_retrying.write().await = false; - } - - async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> { - info!("Retrying authentication..."); - - auth_window.eval( r#" - var loading = document.createElement("div"); - loading.innerHTML = '
Got invalid token, retrying...
'; - loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;"; - document.body.appendChild(loading); - "#)?; - - let auth_request = self.portal_prelogin().await?; - let (tx, rx) = oneshot::channel::<()>(); - auth_window.with_webview(move |webview| { - let auth_request = AuthRequest::new(&auth_request); - platform_impl::load_auth_request(&webview.inner(), &auth_request); - - tx.send(()).expect("Failed to send message to the channel") - })?; - - rx.await?; - Ok(()) - } - - fn raise_window(&self, auth_window: &WebviewWindow) { - let visible = auth_window.is_visible().unwrap_or(false); - if visible { - return; - } - - info!("Raising auth window..."); - if let Err(err) = auth_window.raise() { - warn!("Failed to raise window: {}", err); - } - } -} diff --git a/crates/common/src/vpn_utils.rs b/crates/common/src/vpn_utils.rs index 5366154c..229e33ed 100644 --- a/crates/common/src/vpn_utils.rs +++ b/crates/common/src/vpn_utils.rs @@ -2,22 +2,26 @@ use std::{io, path::Path}; use is_executable::IsExecutable; -const VPNC_SCRIPT_LOCATIONS: [&str; 6] = [ +const VPNC_SCRIPT_LOCATIONS: &[&str] = &[ "/usr/local/share/vpnc-scripts/vpnc-script", "/usr/local/sbin/vpnc-script", "/usr/share/vpnc-scripts/vpnc-script", "/usr/sbin/vpnc-script", "/etc/vpnc/vpnc-script", "/etc/openconnect/vpnc-script", + #[cfg(target_os = "macos")] + "/opt/homebrew/etc/vpnc/vpnc-script", ]; -const CSD_WRAPPER_LOCATIONS: [&str; 3] = [ +const CSD_WRAPPER_LOCATIONS: &[&str] = &[ #[cfg(target_arch = "x86_64")] "/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh", #[cfg(target_arch = "aarch64")] "/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh", "/usr/lib/openconnect/hipreport.sh", "/usr/libexec/openconnect/hipreport.sh", + #[cfg(target_os = "macos")] + "/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh", ]; fn find_executable(locations: &[&str]) -> Option { diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 68e3f5df..0b95b970 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -12,6 +12,7 @@ dns-lookup.workspace = true log.workspace = true reqwest.workspace = true openssl.workspace = true +version-compare = "0.2" pem.workspace = true roxmltree.workspace = true serde.workspace = true @@ -33,8 +34,13 @@ sha256.workspace = true tauri = { workspace = true, optional = true } clap = { workspace = true, optional = true } +clap-verbosity-flag = { workspace = true, optional = true } + +env_logger = { workspace = true, optional = true } +log-reload = { version = "0.1", optional = true } [features] tauri = ["dep:tauri"] -clap = ["dep:clap"] +clap = ["dep:clap", "dep:clap-verbosity-flag"] webview-auth = [] +logger = ["dep:env_logger", "dep:log-reload"] diff --git a/crates/gpapi/src/auth.rs b/crates/gpapi/src/auth.rs index dcabde37..aa6e559c 100644 --- a/crates/gpapi/src/auth.rs +++ b/crates/gpapi/src/auth.rs @@ -72,15 +72,12 @@ impl SamlAuthData { let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie"); let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie"); - SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(|e| { - warn!("Failed to parse auth data: {}", e); - AuthDataParseError::Invalid - }) - } - Some(status) => { - warn!("Found invalid auth status: {}", status); - Err(AuthDataParseError::Invalid) + SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid) } + Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!( + "SAML auth status: {}", + status + ))), None => Err(AuthDataParseError::NotFound), } } @@ -100,7 +97,7 @@ impl SamlAuthData { let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| { warn!("Failed to parse token auth data: {}", e); warn!("Auth data: {}", auth_data); - AuthDataParseError::Invalid + AuthDataParseError::Invalid(anyhow::anyhow!(e)) })?; return Ok(auth_data); @@ -108,7 +105,7 @@ impl SamlAuthData { let auth_data = decode_to_string(auth_data).map_err(|e| { warn!("Failed to decode SAML auth data: {}", e); - AuthDataParseError::Invalid + AuthDataParseError::Invalid(anyhow::anyhow!(e)) })?; let auth_data = Self::from_html(&auth_data)?; @@ -128,7 +125,7 @@ impl SamlAuthData { } } -pub fn parse_xml_tag(html: &str, tag: &str) -> Option { +fn parse_xml_tag(html: &str, tag: &str) -> Option { let re = Regex::new(&format!("<{}>(.*)", tag, tag)).unwrap(); re.captures(html) .and_then(|captures| captures.get(1)) diff --git a/crates/gpapi/src/clap/mod.rs b/crates/gpapi/src/clap/mod.rs index 74bc6e36..62ca9e9c 100644 --- a/crates/gpapi/src/clap/mod.rs +++ b/crates/gpapi/src/clap/mod.rs @@ -1,3 +1,6 @@ +use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter}; +use log::Level; + use crate::error::PortalError; pub mod args; @@ -8,7 +11,7 @@ pub trait Args { } pub fn handle_error(err: anyhow::Error, args: &impl Args) { - eprintln!("\nError: {}", err); + eprintln!("\nError: {:?}", err); let Some(err) = err.downcast_ref::() else { return; @@ -26,3 +29,53 @@ pub fn handle_error(err: anyhow::Error, args: &impl Args) { eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" ")); } } + +#[derive(Debug)] +pub struct InfoLevel; + +pub type InfoLevelVerbosity = Verbosity; + +impl LogLevel for InfoLevel { + fn default_filter() -> VerbosityFilter { + VerbosityFilter::Info + } + + fn verbose_help() -> Option<&'static str> { + Some("Enable verbose output, -v for debug, -vv for trace") + } + + fn quiet_help() -> Option<&'static str> { + Some("Decrease logging verbosity, -q for warnings, -qq for errors") + } +} + +pub trait ToVerboseArg { + fn to_verbose_arg(&self) -> Option<&'static str>; +} + +/// Convert the verbosity to the CLI argument value +/// The default verbosity is `Info`, which means no argument is needed +impl ToVerboseArg for InfoLevelVerbosity { + fn to_verbose_arg(&self) -> Option<&'static str> { + match self.filter() { + VerbosityFilter::Off => Some("-qqq"), + VerbosityFilter::Error => Some("-qq"), + VerbosityFilter::Warn => Some("-q"), + VerbosityFilter::Info => None, + VerbosityFilter::Debug => Some("-v"), + VerbosityFilter::Trace => Some("-vv"), + } + } +} + +impl ToVerboseArg for Level { + fn to_verbose_arg(&self) -> Option<&'static str> { + match self { + Level::Error => Some("-qq"), + Level::Warn => Some("-q"), + Level::Info => None, + Level::Debug => Some("-v"), + Level::Trace => Some("-vv"), + } + } +} diff --git a/crates/gpapi/src/error.rs b/crates/gpapi/src/error.rs index 6af70850..505177c5 100644 --- a/crates/gpapi/src/error.rs +++ b/crates/gpapi/src/error.rs @@ -4,10 +4,13 @@ use thiserror::Error; pub enum PortalError { #[error("Prelogin error: {0}")] PreloginError(String), + #[error("Portal config error: {0}")] ConfigError(String), - #[error("Network error: {0}")] + + #[error(transparent)] NetworkError(#[from] reqwest::Error), + #[error("TLS error")] TlsError, } @@ -26,12 +29,12 @@ impl PortalError { pub enum AuthDataParseError { #[error("No auth data found")] NotFound, - #[error("Invalid auth data")] - Invalid, + #[error(transparent)] + Invalid(#[from] anyhow::Error), } impl AuthDataParseError { pub fn is_invalid(&self) -> bool { - matches!(self, AuthDataParseError::Invalid) + matches!(self, AuthDataParseError::Invalid(_)) } } diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index d99c0e9e..a0f78549 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -31,12 +31,10 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam info!("Perform gateway login, user_agent: {}", gp_params.user_agent()); - let res = client - .post(&login_url) - .form(¶ms) - .send() - .await - .map_err(|e| anyhow::anyhow!(PortalError::NetworkError(e)))?; + let res = client.post(&login_url).form(¶ms).send().await.map_err(|e| { + warn!("Network error: {:?}", e); + anyhow::anyhow!(PortalError::NetworkError(e)) + })?; let res = parse_gp_response(res).await.map_err(|err| { warn!("{err}"); diff --git a/crates/gpapi/src/gp_params.rs b/crates/gpapi/src/gp_params.rs index f72eba3b..a595b5ff 100644 --- a/crates/gpapi/src/gp_params.rs +++ b/crates/gpapi/src/gp_params.rs @@ -9,9 +9,10 @@ use crate::{utils::request::create_identity, GP_USER_AGENT}; #[derive(Debug, Serialize, Deserialize, Clone, Type, Default)] pub enum ClientOs { - #[default] + #[cfg_attr(not(target_os = "macos"), default)] Linux, Windows, + #[cfg_attr(target_os = "macos", default)] Mac, } diff --git a/crates/gpapi/src/lib.rs b/crates/gpapi/src/lib.rs index 663eb24e..7b085eb4 100644 --- a/crates/gpapi/src/lib.rs +++ b/crates/gpapi/src/lib.rs @@ -8,6 +8,9 @@ pub mod process; pub mod service; pub mod utils; +#[cfg(feature = "logger")] +pub mod logger; + #[cfg(feature = "clap")] pub mod clap; diff --git a/crates/gpapi/src/logger.rs b/crates/gpapi/src/logger.rs new file mode 100644 index 00000000..c94a44e2 --- /dev/null +++ b/crates/gpapi/src/logger.rs @@ -0,0 +1,49 @@ +use std::sync::OnceLock; + +use anyhow::bail; +use env_logger::Logger; +use log::Level; +use log_reload::{ReloadHandle, ReloadLog}; + +static LOG_HANDLE: OnceLock>> = OnceLock::new(); + +pub fn init(level: Level) -> anyhow::Result<()> { + // Initialize the env_logger and global max level to trace, the logs will be + // filtered by the outer logger + let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build(); + init_with_logger(level, logger)?; + + Ok(()) +} + +pub fn init_with_logger(level: Level, logger: Logger) -> anyhow::Result<()> { + if let Some(_) = LOG_HANDLE.get() { + bail!("Logger already initialized") + } else { + log::set_max_level(log::LevelFilter::Trace); + + // Create a new logger that will filter the logs based on the max level + let level_filter_logger = log_reload::LevelFilter::new(level, logger); + + let reload_log = ReloadLog::new(level_filter_logger); + let handle = reload_log.handle(); + + // Register the logger to be used by the log crate + log::set_boxed_logger(Box::new(reload_log))?; + LOG_HANDLE + .set(handle) + .map_err(|_| anyhow::anyhow!("Failed to set the logger"))?; + } + + Ok(()) +} + +pub fn set_max_level(level: Level) -> anyhow::Result<()> { + let Some(handle) = LOG_HANDLE.get() else { + bail!("Logger not initialized") + }; + + handle + .modify(|logger| logger.set_level(level)) + .map_err(|e| anyhow::anyhow!(e)) +} diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 9be4c765..5b72da01 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -1,6 +1,6 @@ use anyhow::bail; use dns_lookup::lookup_addr; -use log::{debug, info, warn}; +use log::{info, warn}; use reqwest::{Client, StatusCode}; use roxmltree::{Document, Node}; use serde::Serialize; @@ -111,12 +111,10 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent()); - let res = client - .post(&url) - .form(¶ms) - .send() - .await - .map_err(|e| anyhow::anyhow!(PortalError::NetworkError(e)))?; + let res = client.post(&url).form(¶ms).send().await.map_err(|e| { + warn!("Network error: {:?}", e); + anyhow::anyhow!(PortalError::NetworkError(e)) + })?; let res_xml = parse_gp_response(res).await.or_else(|err| { if err.status == StatusCode::NOT_FOUND { @@ -135,8 +133,6 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara bail!(PortalError::ConfigError("Empty portal config response".to_string())) } - debug!("Portal config response: {}", res_xml); - let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?; let root = doc.root(); diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index b4076d95..9d52189d 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -116,12 +116,10 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result { #[cfg(feature = "webview-auth")] default_browser: bool, browser: Option<&'a str>, + verbose: Option<&'a str>, } impl<'a> SamlAuthLauncher<'a> { @@ -43,6 +44,7 @@ impl<'a> SamlAuthLauncher<'a> { #[cfg(feature = "webview-auth")] default_browser: false, browser: None, + verbose: None, } } @@ -104,6 +106,11 @@ impl<'a> SamlAuthLauncher<'a> { self } + pub fn verbose(mut self, verbose: Option<&'a str>) -> Self { + self.verbose = verbose; + self + } + /// Launch the authenticator binary as the current user or SUDO_USER if available. pub async fn launch(self) -> anyhow::Result { let mut auth_cmd = Command::new(GP_AUTH_BINARY); @@ -156,6 +163,10 @@ impl<'a> SamlAuthLauncher<'a> { auth_cmd.arg("--browser").arg(browser); } + if let Some(verbose) = self.verbose { + auth_cmd.arg(verbose); + } + let mut non_root_cmd = auth_cmd.into_non_root()?; let output = non_root_cmd .kill_on_drop(true) diff --git a/crates/gpapi/src/process/service_launcher.rs b/crates/gpapi/src/process/service_launcher.rs index 05bca37f..aada481b 100644 --- a/crates/gpapi/src/process/service_launcher.rs +++ b/crates/gpapi/src/process/service_launcher.rs @@ -10,26 +10,28 @@ use crate::GP_SERVICE_BINARY; use super::command_traits::CommandExt; -pub struct ServiceLauncher { +pub struct ServiceLauncher<'a> { program: PathBuf, minimized: bool, env_file: Option, log_file: Option, + verbose: Option<&'a str> } -impl Default for ServiceLauncher { +impl Default for ServiceLauncher<'_> { fn default() -> Self { Self::new() } } -impl ServiceLauncher { +impl<'a> ServiceLauncher<'a> { pub fn new() -> Self { Self { program: GP_SERVICE_BINARY.into(), minimized: false, env_file: None, log_file: None, + verbose: None } } @@ -48,6 +50,11 @@ impl ServiceLauncher { self } + pub fn verbose(mut self, verbose: Option<&'a str>) -> Self { + self.verbose = verbose; + self + } + pub async fn launch(&self) -> anyhow::Result { let mut cmd = Command::new_pkexec(&self.program); @@ -59,6 +66,10 @@ impl ServiceLauncher { cmd.arg("--env-file").arg(env_file); } + if let Some(verbose) = self.verbose { + cmd.arg(verbose); + } + if let Some(log_file) = &self.log_file { let log_file = File::create(log_file)?; let stdio = Stdio::from(log_file); diff --git a/crates/gpapi/src/service/request.rs b/crates/gpapi/src/service/request.rs index 96b0a698..abf28129 100644 --- a/crates/gpapi/src/service/request.rs +++ b/crates/gpapi/src/service/request.rs @@ -206,11 +206,15 @@ impl ConnectRequest { #[derive(Debug, Deserialize, Serialize, Type)] pub struct DisconnectRequest; +#[derive(Debug, Deserialize, Serialize)] +pub struct UpdateLogLevelRequest(pub String); + /// Requests that can be sent to the service #[derive(Debug, Deserialize, Serialize)] pub enum WsRequest { Connect(Box), Disconnect(DisconnectRequest), + UpdateLogLevel(UpdateLogLevelRequest), } #[derive(Debug, Deserialize, Serialize)] diff --git a/crates/gpapi/src/utils/env_utils.rs b/crates/gpapi/src/utils/env_utils.rs index 70524d14..11ce6331 100644 --- a/crates/gpapi/src/utils/env_utils.rs +++ b/crates/gpapi/src/utils/env_utils.rs @@ -42,8 +42,8 @@ pub fn patch_gui_runtime_env(hidpi: bool) { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1"); // Workaround for https://github.com/tauri-apps/tao/issues/929 - let desktop = env::var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_lowercase(); - if desktop.contains("gnome") { + let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland"; + if is_wayland { env::set_var("GDK_BACKEND", "x11"); } diff --git a/crates/gpapi/src/utils/openssl.rs b/crates/gpapi/src/utils/openssl.rs index 56af8a32..b076e15b 100644 --- a/crates/gpapi/src/utils/openssl.rs +++ b/crates/gpapi/src/utils/openssl.rs @@ -1,9 +1,12 @@ use std::path::Path; +use log::{info, warn}; +use regex::Regex; use tempfile::NamedTempFile; +use version_compare::{compare_to, Cmp}; pub fn openssl_conf() -> String { - let option = "UnsafeLegacyServerConnect"; + let option = get_openssl_option(); format!( "openssl_conf = openssl_init @@ -47,3 +50,58 @@ pub fn fix_openssl_env() -> anyhow::Result { Ok(openssl_conf) } + +// See: https://stackoverflow.com/questions/75763525/curl-35-error0a000152ssl-routinesunsafe-legacy-renegotiation-disabled +fn get_openssl_option() -> &'static str { + let version_str = openssl::version::version(); + let default_option = "UnsafeLegacyServerConnect"; + + let Some(version) = extract_openssl_version(version_str) else { + warn!("Failed to extract OpenSSL version from '{}'", version_str); + return default_option; + }; + + let older_than_3_0_4 = match compare_to(version, "3.0.4", Cmp::Lt) { + Ok(result) => result, + Err(_) => { + warn!("Failed to compare OpenSSL version: {}", version); + return default_option; + } + }; + + if older_than_3_0_4 { + info!("Using 'UnsafeLegacyRenegotiation' option"); + "UnsafeLegacyRenegotiation" + } else { + info!("Using 'UnsafeLegacyServerConnect' option"); + default_option + } +} + +fn extract_openssl_version(version: &str) -> Option<&str> { + let re = Regex::new(r"OpenSSL (\d+\.\d+\.\d+[^\s]*)").unwrap(); + re.captures(version).and_then(|caps| caps.get(1)).map(|m| m.as_str()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_extract_version() { + let input = "OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)"; + assert_eq!(extract_openssl_version(input), Some("3.4.0")); + } + + #[test] + fn test_different_format() { + let input = "OpenSSL 1.1.1t 7 Feb 2023"; + assert_eq!(extract_openssl_version(input), Some("1.1.1t")); + } + + #[test] + fn test_invalid_input() { + let input = "Invalid string without version"; + assert_eq!(extract_openssl_version(input), None); + } +} diff --git a/crates/openconnect/build.rs b/crates/openconnect/build.rs index 0220ce09..bfba3a04 100644 --- a/crates/openconnect/build.rs +++ b/crates/openconnect/build.rs @@ -1,9 +1,14 @@ fn main() { // Link to the native openconnect library println!("cargo:rustc-link-lib=openconnect"); + println!("cargo:rustc-link-search=/opt/homebrew/lib"); // Homebrew path println!("cargo:rerun-if-changed=src/ffi/vpn.c"); println!("cargo:rerun-if-changed=src/ffi/vpn.h"); // Compile the vpn.c file - cc::Build::new().file("src/ffi/vpn.c").include("src/ffi").compile("vpn"); + cc::Build::new() + .file("src/ffi/vpn.c") + .include("src/ffi") + .include("/opt/homebrew/include") // Homebrew path + .compile("vpn"); } diff --git a/packaging/rpm/globalprotect-openconnect.spec.in b/packaging/rpm/globalprotect-openconnect.spec.in index 978796a2..3b341415 100644 --- a/packaging/rpm/globalprotect-openconnect.spec.in +++ b/packaging/rpm/globalprotect-openconnect.spec.in @@ -14,12 +14,17 @@ BuildRequires: cargo BuildRequires: jq BuildRequires: pkg-config BuildRequires: openconnect-devel -BuildRequires: openssl-devel +BuildRequires: (openssl-devel or libopenssl-devel) BuildRequires: wget BuildRequires: file BuildRequires: perl -BuildRequires: (webkit2gtk4.1-devel or webkit2gtk3-soup2-devel) +%if 0%{?suse_version} +BuildRequires: webkit2gtk3-devel +%else +BuildRequires: webkit2gtk4.1-devel +%endif + BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1) BuildRequires: (librsvg2-devel or librsvg-devel)