okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
54ef8615b
main
1"""The Terminal finds a cloudflared that the system installed (PATH, /usr/bin, ~/.local/bin, Homebrew, Program Files), checks its 2version, and does not start a second connector next to one that is already running.""" 3 4from __future__import annotations 5 6import os 7import stat 8import sys 9import tempfile 10import unittest 11from pathlib import Path 12from unittest import mock 13 14from strata_cli .launch import access 15 16 17def fake_cloudflared (directory :Path ,version :str = "2026.5.0" ,name :str = "cloudflared" )-> Path : 18path = directory / name 19path .write_text (f'#!/bin/sh\necho "cloudflared version { version } (built 2026-05-12)"\n' ) 20path .chmod (path .stat ().st_mode | stat .S_IXUSR ) 21return path 22 23 24@ unittest . skipIf ( os . name == "nt" , "the fixture is a shell script" ) 25class FindOnPath (unittest .TestCase ): 26def setUp (self ): 27access ._cf_seen .clear () 28self .tmp = tempfile .TemporaryDirectory () 29self .dir = Path (self .tmp .name ) 30 31def tearDown (self ): 32self .tmp .cleanup () 33 34def env (self ,** extra ): 35return mock .patch .dict (os .environ , {"PATH" :str (self .dir / "bin" ),"HOME" :str (self .dir ),** extra },clear = False ) 36 37def test_a_user_local_copy_on_path_is_found_with_its_version (self ): 38 (self .dir / "bin" ).mkdir () 39exe = fake_cloudflared (self .dir / "bin" ) 40with self .env (): 41info = access .cloudflared_info () 42self .assertEqual (info , {"path" :str (exe ),"version" :"2026.5.0" }) 43self .assertEqual (access .find_cloudflared (),str (exe )) 44 45def test_the_local_bin_folder_is_searched_when_path_misses_it (self ): 46 (self .dir / ".local" / "bin" ).mkdir (parents = True ) 47exe = fake_cloudflared (self .dir / ".local" / "bin" ) 48places = access ._cloudflared_places 49with self .env (PATH = str (self .dir / "empty" )),mock .patch .object (Path ,"home" ,return_value = self .dir ),mock .patch .object (access ,"_cloudflared_places" ,# a box with its own system cloudflared (/usr/bin) must not answer first 50lambda : [p for p in places ()if not p .replace ("\\" ,"/" ).startswith (("/usr/" ,"/opt/" ,"/bin/" ))]): 51self .assertEqual (access .find_cloudflared (),str (exe )) 52 53def test_a_too_old_copy_is_passed_over (self ): 54 (self .dir / "bin" ).mkdir () 55fake_cloudflared (self .dir / "bin" ,version = "2021.3.0" ) 56with self .env (),mock .patch .object (Path ,"home" ,return_value = self .dir / "nohome" ): 57places = [p for p in access ._cloudflared_places ()if str (self .dir )in p ] 58with mock .patch .object (access ,"_cloudflared_places" ,return_value = places ): 59self .assertIsNone (access .find_cloudflared ()) 60 61def test_a_file_that_does_not_run_is_passed_over (self ): 62 (self .dir / "bin" ).mkdir () 63bad = self .dir / "bin" / "cloudflared" 64bad .write_text ("#!/bin/sh\nexit 3\n" ) 65bad .chmod (0o755 ) 66with self .env (),mock .patch .object (access ,"_cloudflared_places" ,return_value = [str (bad )]): 67self .assertIsNone (access .find_cloudflared ()) 68 69def test_strata_cloudflared_picks_exactly_that_file (self ): 70exe = fake_cloudflared (self .dir ,version = "2025.1.2" ,name = "mine" ) 71with self .env (STRATA_CLOUDFLARED = str (exe )): 72self .assertEqual (access ._cloudflared_places (), [str (exe )]) 73self .assertEqual (access .cloudflared_info ()["version" ],"2025.1.2" ) 74 75 76class Places (unittest .TestCase ): 77def test_the_usual_places_are_listed (self ): 78with mock .patch .dict (os .environ , {"PATH" :"/opt/x/bin" },clear = False ),mock .patch .object (access ,"WINDOWS" ,False ), \ 79mock .patch .dict (os .environ , {},clear = False ): 80os .environ .pop ("STRATA_CLOUDFLARED" ,None ) 81places = [p .replace ("\\" ,"/" )for p in access ._cloudflared_places ()] 82for want in ("/opt/x/bin/cloudflared" ,"/usr/bin/cloudflared" ,"/usr/local/bin/cloudflared" ,"/opt/homebrew/bin/cloudflared" ): 83self .assertIn (want ,places ) 84self .assertTrue (any (p .endswith (".local/bin/cloudflared" )for p in places )) 85self .assertEqual (len (places ),len (set (places ))) 86 87def test_windows_places_include_program_files (self ): 88env = {"PATH" :"" ,"ProgramFiles" :r"C:\Program Files" ,"ProgramFiles(x86)" :r"C:\Program Files (x86)" } 89with mock .patch .dict (os .environ ,env ,clear = False ),mock .patch .object (access ,"WINDOWS" ,True ): 90os .environ .pop ("STRATA_CLOUDFLARED" ,None ) 91places = access ._cloudflared_places () 92self .assertTrue (any ("Program Files" in p and p .endswith ("cloudflared.exe" )for p in places )) 93 94def test_version_rule (self ): 95self .assertTrue (access ._cf_new_enough ("2026.5.0" )) 96self .assertTrue (access ._cf_new_enough ("2022.1.0" )) 97self .assertFalse (access ._cf_new_enough ("2021.12.2" )) 98self .assertTrue (access ._cf_new_enough ("" )) 99 100 101class OtherTunnels (unittest .TestCase ): 102PS = (" 4242 cloudflared /usr/bin/cloudflared --no-autoupdate tunnel run --token SECRETSECRETSECRETSECRET\n" 103" 77 cloudflared cloudflared tunnel --no-autoupdate --url http://127.0.0.1:8080\n" 104" 90 bash bash -c cloudflared\n 100 sshd sshd\n" ) 105 106def test_every_cloudflared_is_listed_with_its_pid_and_our_own_pid_is_left_out (self ): 107with mock .patch .object (access ,"WINDOWS" ,False ),mock .patch .object (access .subprocess ,"run" ,return_value = mock .Mock (stdout = self .PS )): 108self .assertEqual ([p for p ,_ in access .cloudflared_procs ()], [4242 ,77 ]) 109self .assertEqual ([p for p ,_ in access .cloudflared_procs (exclude = (4242 ,))], [77 ]) 110 111def test_only_a_tunnel_pointing_at_this_servers_port_is_its_own (self ): 112procs = [(4242 ,"cloudflared tunnel run --token X" ), (77 ,"cloudflared tunnel --url http://127.0.0.1:8080" ), (5 ,"cloudflared tunnel --url http://127.0.0.1:18080" )] 113self .assertEqual (access .own_tunnel_pids (procs ,8080 ), [77 ]) 114self .assertEqual (access .own_tunnel_pids (procs ,9999 ), []) 115self .assertEqual (access .other_tunnel_note ([4242 ]),"cloudflared is already running for another tunnel (PID 4242)." ) 116self .assertEqual (access .other_tunnel_note ([1 ,2 ]),"cloudflared is already running for other tunnels (PIDs 1, 2)." ) 117 118def test_the_servers_own_tunnel_already_running_is_not_doubled (self ): 119with mock .patch .object (access ,"find_cloudflared" ,return_value = "/usr/bin/cloudflared" ),mock .patch .object (access ,"tunnel_info" ,return_value = None ), \ 120mock .patch .object (access ,"cloudflared_procs" ,return_value = [(31 ,"cloudflared tunnel --url http://127.0.0.1:8080" )]), \ 121mock .patch .object (access .subprocess ,"Popen" )as popen : 122url ,message = access .start_tunnel ("demo" ,8080 ) 123self .assertIsNone (url ) 124popen .assert_not_called () 125self .assertIn ("already running (PID 31)" ,message ) 126self .assertIn ("did not start a second one" ,message ) 127 128def test_another_tunnel_running_does_not_stop_a_quick_tunnel (self ): 129proc = mock .Mock (pid = 55 ) 130proc .poll .return_value = None 131with tempfile .TemporaryDirectory ()as tmp ,mock .patch .object (access ,"find_cloudflared" ,return_value = "/usr/bin/cloudflared" ), \ 132mock .patch .object (access ,"tunnel_info" ,return_value = None ),mock .patch .object (access ,"stop_tunnel" ), \ 133mock .patch .object (access ,"_state_dir" ,return_value = Path (tmp )), \ 134mock .patch .object (access ,"cloudflared_procs" ,return_value = [(4242 ,"cloudflared tunnel run --token X" )]), \ 135mock .patch .object (access .subprocess ,"Popen" ,side_effect = lambda * a ,** k : (k ["stdout" ].write (b"https://abc-def.trycloudflare.com" ),k ["stdout" ].flush (),proc )[2 ])as popen , \ 136mock .patch ("strata_control.procs.start_token" ,return_value = "t" ),mock .patch ("strata_control.procs.command_line" ,return_value = ["x" ]): 137url ,message = access .start_tunnel ("demo" ,8080 ,wait = 2 ) 138popen .assert_called_once () 139self .assertEqual (url ,"https://abc-def.trycloudflare.com" ) 140self .assertIn ("cloudflared is already running for another tunnel (PID 4242)." ,message ) 141 142def test_a_missing_ps_is_never_a_block (self ): 143with mock .patch .object (access ,"WINDOWS" ,False ),mock .patch .object (access .subprocess ,"run" ,side_effect = FileNotFoundError ): 144self .assertEqual (access .cloudflared_procs (), []) 145 146 147if __name__ == "__main__" : 148unittest .main ()