From c8e0fba64ec6a29b7ba324f37e435b3e296db570 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Mon, 19 Oct 2026 09:13:50 +0200 Subject: [PATCH] Support alternate trusted Git host for Edge installation and updates --- ENGINEER_INSTRUCTIONS.md | 18 ++++++++++++++++++ install_iomatex_edge.sh | 9 ++++++--- offline/git_delivery.py | 23 +++++++++++++++-------- offline/stage_versions.py | 11 ++++++----- offline/test_git_delivery.py | 19 +++++++++++++++++++ offline/test_stage_versions.py | 8 ++++++++ 6 files changed, 72 insertions(+), 16 deletions(-) diff --git a/ENGINEER_INSTRUCTIONS.md b/ENGINEER_INSTRUCTIONS.md index ded7f07..7f49fbb 100644 --- a/ENGINEER_INSTRUCTIONS.md +++ b/ENGINEER_INSTRUCTIONS.md @@ -30,6 +30,24 @@ curl --fail --show-error \ ``` `curl` запросит пароль Git пользователя `clone`. Ввод не отображается. + +Если основной домен недоступен, используйте дополнительный адрес: + +```bash +cd /home/iomatex +curl --fail --show-error --connect-timeout 15 --max-time 120 --user clone \ + 'https://git.iomatex.com/api/v1/repos/An-J/Iomatex_OS/raw/install_iomatex_edge.sh?ref=ci-cd' \ + -o install_iomatex_edge.new.sh && +bash -n install_iomatex_edge.new.sh && +sudo bash install_iomatex_edge.new.sh --git-url https://git.iomatex.com/An-J/Iomatex_OS.git +``` + +Используйте актуальный установщик: старые версии принимают только основной домен. +Учётная запись Git та же. Выбранный адрес сохраняется для обновлений Console, +загрузки пакетов и продолжения установки после перезагрузки. Автоматического +переключения между доменами нет. Оба имени ведут на один сервер; при блокировке +его IP потребуется отдельная точка доступа. + Это пароль доступа к репозиторию, а не пароль пользователя Edge. Пароль не нужно добавлять в команду. diff --git a/install_iomatex_edge.sh b/install_iomatex_edge.sh index 4b7722b..ec6775c 100755 --- a/install_iomatex_edge.sh +++ b/install_iomatex_edge.sh @@ -21,7 +21,7 @@ while [[ $# -gt 0 ]]; do *) echo "Unknown argument: $1" >&2; exit 1 ;; esac done -[[ "$GIT_URL" == https://git.it-screen.com/* && "$GIT_URL" != *'@'* && "$GIT_URL" != *'?'* && "$GIT_URL" != *'#'* ]] || { echo 'Only HTTPS repositories on git.it-screen.com are supported' >&2; exit 1; } +[[ ( "$GIT_URL" == https://git.it-screen.com/* || "$GIT_URL" == https://git.iomatex.com/* ) && "$GIT_URL" != *'@'* && "$GIT_URL" != *'?'* && "$GIT_URL" != *'#'* ]] || { echo 'Only HTTPS repositories on git.it-screen.com or git.iomatex.com are supported' >&2; exit 1; } [[ "$GIT_BRANCH" =~ ^[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid branch' >&2; exit 1; } [[ "$CHECKOUT_DIR" == /* && "$CHECKOUT_DIR" != / && "$CHECKOUT_DIR" != /userdata && "$CHECKOUT_DIR" != /opt ]] || { echo 'Use an absolute checkout subdirectory' >&2; exit 1; } # Standalone bootstrap embeds the same lock contract as offline/install-lock.sh. @@ -49,8 +49,11 @@ trap 'rm -rf "$work"' EXIT python3 - "$GIT_URL" "$GIT_BRANCH" "$work/git_delivery.py" <<'PYTHON' import base64, json, os, pathlib, urllib.parse, urllib.request, sys url, branch, destination = sys.argv[1:] -repo = urllib.parse.urlparse(url).path.strip('/').removesuffix('.git') -base = 'https://git.it-screen.com/api/v1/repos/' + repo + '/' +parsed = urllib.parse.urlparse(url) +if parsed.scheme != 'https' or parsed.netloc not in ('git.it-screen.com', 'git.iomatex.com') or parsed.query or parsed.fragment: + raise ValueError('Unsupported Git URL') +repo = parsed.path.strip('/').removesuffix('.git') +base = 'https://' + parsed.netloc + '/api/v1/repos/' + repo + '/' class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): raise RuntimeError('Git download redirect refused') diff --git a/offline/git_delivery.py b/offline/git_delivery.py index 31ceacb..1219a38 100644 --- a/offline/git_delivery.py +++ b/offline/git_delivery.py @@ -27,6 +27,13 @@ import urllib.parse import urllib.request HOST = 'git.it-screen.com' +ALLOWED_HOSTS = (HOST, 'git.iomatex.com') + +def git_host(value=HOST): + if value not in ALLOWED_HOSTS: + raise ValueError('Unsupported Git host') + return value + STATE = Path('/var/lib/iomatex/packages') AUTH = Path('/etc/iomatex/git-credentials.json') CACHE = Path('/userdata/iomatex-apt-cache') @@ -44,7 +51,7 @@ def safe_path(value): def repo_name(url): u = urllib.parse.urlparse(url) - if u.scheme != 'https' or u.netloc != HOST or u.query or u.fragment: + if u.scheme != 'https' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment: raise ValueError('Only HTTPS repositories on our Git are allowed') name = u.path.strip('/').removesuffix('.git') if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name): @@ -58,7 +65,7 @@ def auth_from_env(): return json.loads(AUTH.read_text()) def open_git(repo, endpoint, auth, timeout=120): - url = 'https://' + HOST + '/api/v1/repos/' + repo + '/' + endpoint + url = 'https://' + git_host(auth.get('host', HOST)) + '/api/v1/repos/' + repo + '/' + endpoint token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode() req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token}) return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout) @@ -261,7 +268,7 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None): materialize_file(repo, commit, auth, item, root / 'absent', root) download_snapshot(files, download) write_json(root / '.iomatex-source.json', - {'repo': repo, 'branch': branch, 'commit': commit, 'files': files}) + {'repo': repo, 'host': git_host(auth.get('host', HOST)), 'branch': branch, 'commit': commit, 'files': files}) print('Verifying recovery package catalog...', flush=True) catalog(root) write_json(AUTH, auth, 0o600) @@ -282,7 +289,7 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery dest = requested.resolve() if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink(): raise ValueError('Use a dedicated absolute installer subdirectory') - auth = auth_from_env() + auth = {**auth_from_env(), 'host': git_host(urllib.parse.urlparse(url).netloc)} if commit is None: with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r: commit = json.load(r)['commit']['id'] @@ -318,7 +325,7 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery materialize_file(repo, commit, auth, entry, dest, staged) print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True) download_snapshot(files, download) - source = {'repo': repo, 'commit': commit, 'branch': branch, 'files': files} + source = {'repo': repo, 'host': git_host(auth.get('host', HOST)), 'commit': commit, 'branch': branch, 'files': files} write_json(staged / '.iomatex-source.json', source) # Validate all metadata before replacing an existing installation snapshot. catalog(staged) @@ -397,14 +404,14 @@ def activate(root): platform_check() root = Path(root).resolve() source = json.loads((root / '.iomatex-source.json').read_text()) - repo_name('https://' + HOST + '/' + source['repo']) + repo_name('https://' + git_host(source.get('host', HOST)) + '/' + source['repo']) raw_endpoint('probe', source['commit']) auth_from_env() # fail before modifying APT if reboot credentials are missing text, objects = catalog(root) STATE.mkdir(parents=True, exist_ok=True) (STATE / 'Packages').write_text(text) (STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0)) - write_json(STATE / 'source.json', {'repo':source['repo'], 'commit':source['commit'], 'objects':objects}) + write_json(STATE / 'source.json', {'repo':source['repo'], 'host':git_host(source.get('host', HOST)), 'commit':source['commit'], 'objects':objects}) owner = Path('/usr/local/lib/iomatex') owner.mkdir(parents=True, exist_ok=True) shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py') @@ -446,7 +453,7 @@ def download_object(config, key, dest, auth): digest = hashlib.sha256() size = 0 try: - with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), auth) as response, path.open('wb') as output: + with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), {**auth, 'host': git_host(config.get('host', HOST))}) as response, path.open('wb') as output: while True: chunk = response.read(1024 * 1024) if not chunk: break diff --git a/offline/stage_versions.py b/offline/stage_versions.py index 6326e9a..04eca3e 100644 --- a/offline/stage_versions.py +++ b/offline/stage_versions.py @@ -84,8 +84,9 @@ def record(root, stage): def configure(root): root = Path(root).resolve() source = read_json(root / '.iomatex-source.json') - delivery.repo_name('https://' + delivery.HOST + '/' + source['repo'] + '.git') - next_config = {'checkout': str(root), 'repo': source['repo'], 'branch': source['branch']} + delivery.repo_name('https://' + delivery.git_host(source.get('host', delivery.HOST)) + '/' + source['repo'] + '.git') + next_config = {'checkout': str(root), 'repo': source['repo'], 'branch': source['branch'], + 'host': delivery.git_host(source.get('host', delivery.HOST))} if read_json(CONFIG) != next_config: delivery.write_json(STATE / 'available.json', {}) delivery.write_json(CONFIG, next_config) @@ -97,8 +98,8 @@ def refresh(): phase = 'branch' try: cfg = read_json(CONFIG) - repo = delivery.repo_name('https://' + delivery.HOST + '/' + cfg['repo'] + '.git') - auth = delivery.auth_from_env() + repo = delivery.repo_name('https://' + delivery.git_host(cfg.get('host', delivery.HOST)) + '/' + cfg['repo'] + '.git') + auth = {**delivery.auth_from_env(), 'host': delivery.git_host(cfg.get('host', delivery.HOST))} with delivery.open_git(repo, 'branches/' + urllib.parse.quote(cfg['branch'], safe=''), auth, timeout=15) as response: commit = json.load(response)['commit']['id'] phase = 'catalog' @@ -352,7 +353,7 @@ def install(stage, commit): fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) cfg = read_json(CONFIG) delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'}) - delivery.bootstrap('https://' + delivery.HOST + '/' + cfg['repo'] + '.git', + delivery.bootstrap('https://' + delivery.git_host(cfg.get('host', delivery.HOST)) + '/' + cfg['repo'] + '.git', cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job, preserve_local_changes=True) root = Path(cfg['checkout']) completed = run_stages(root, stages, commit, job, lock.fileno()) diff --git a/offline/test_git_delivery.py b/offline/test_git_delivery.py index 187e597..e7c0191 100644 --- a/offline/test_git_delivery.py +++ b/offline/test_git_delivery.py @@ -11,6 +11,25 @@ sys.path.insert(0, str(Path(__file__).parent)) import git_delivery as d class DeliveryTest(unittest.TestCase): + def test_only_trusted_git_aliases_receive_credentials(self): + for host in d.ALLOWED_HOSTS: + self.assertEqual('An-J/Iomatex_OS', d.repo_name('https://' + host + '/An-J/Iomatex_OS.git')) + with patch.object(d.urllib.request, 'build_opener') as opener: + d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host}) + request = opener.return_value.open.call_args.args[0] + self.assertEqual('https://' + host + '/api/v1/repos/An-J/Iomatex_OS/branches/ci-cd', request.full_url) + for host in ['evil.example', 'git.iomatex.com.evil', 'user@git.iomatex.com', 'git.iomatex.com:443']: + with self.assertRaises(ValueError): + d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host}) + + def test_package_download_uses_persisted_host(self): + data = b'package' + config = {'host': 'git.iomatex.com', 'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40, + 'objects': {'debian/a.deb': {'path': 'third_party/a.deb', 'sha256': hashlib.sha256(data).hexdigest()}}} + with tempfile.TemporaryDirectory() as folder, patch.object(d, 'open_git', return_value=io.BytesIO(data)) as request: + d.download_object(config, 'debian/a.deb', Path(folder)/'a.deb', {'username': 'u', 'password': 'p'}) + self.assertEqual('git.iomatex.com', request.call_args.args[2]['host']) + def test_payloads_excluded_from_edge_snapshot(self): for name in ['third_party/debian/bullseye-arm64/repo/a.deb', 'third_party/zigbee2mqtt/z.tar.gz', 'stage_itscreen/itscreen']: self.assertTrue(d.is_payload(name)) diff --git a/offline/test_stage_versions.py b/offline/test_stage_versions.py index 19389a0..88df4ea 100644 --- a/offline/test_stage_versions.py +++ b/offline/test_stage_versions.py @@ -29,6 +29,14 @@ class StageVersionsTest(unittest.TestCase): versions.delivery.write_json(versions.STATE / 'available.json', self.available) versions.delivery.write_json(versions.CONFIG, {'repo':'An-J/Iomatex_OS', 'branch':'ci-cd', 'checkout':str(root / 'checkout')}) + def test_selected_host_survives_update_configuration(self): + root = Path(self.tmp.name)/'source' + root.mkdir() + versions.delivery.write_json(root/'.iomatex-source.json', { + 'repo': 'An-J/Iomatex_OS', 'branch': 'ci-cd', 'host': 'git.iomatex.com'}) + versions.configure(root) + self.assertEqual('git.iomatex.com', versions.read_json(versions.CONFIG)['host']) + def test_published_catalog_is_accepted_by_legacy_console(self): raw = json.loads((ROOT / 'stage-releases.json').read_text()) # This is the exact set checked by Console 3.1.2's validator.