Support alternate trusted Git host for Edge installation and updates
This commit is contained in:
parent
89d70fc2b4
commit
c8e0fba64e
|
|
@ -30,6 +30,24 @@ curl --fail --show-error \
|
||||||
```
|
```
|
||||||
|
|
||||||
`curl` запросит пароль Git пользователя `clone`. Ввод не отображается.
|
`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.
|
Это пароль доступа к репозиторию, а не пароль пользователя Edge.
|
||||||
Пароль не нужно добавлять в команду.
|
Пароль не нужно добавлять в команду.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ while [[ $# -gt 0 ]]; do
|
||||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
done
|
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; }
|
[[ "$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; }
|
[[ "$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.
|
# 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'
|
python3 - "$GIT_URL" "$GIT_BRANCH" "$work/git_delivery.py" <<'PYTHON'
|
||||||
import base64, json, os, pathlib, urllib.parse, urllib.request, sys
|
import base64, json, os, pathlib, urllib.parse, urllib.request, sys
|
||||||
url, branch, destination = sys.argv[1:]
|
url, branch, destination = sys.argv[1:]
|
||||||
repo = urllib.parse.urlparse(url).path.strip('/').removesuffix('.git')
|
parsed = urllib.parse.urlparse(url)
|
||||||
base = 'https://git.it-screen.com/api/v1/repos/' + repo + '/'
|
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):
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
def redirect_request(self, *args, **kwargs):
|
def redirect_request(self, *args, **kwargs):
|
||||||
raise RuntimeError('Git download redirect refused')
|
raise RuntimeError('Git download redirect refused')
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,13 @@ import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
HOST = 'git.it-screen.com'
|
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')
|
STATE = Path('/var/lib/iomatex/packages')
|
||||||
AUTH = Path('/etc/iomatex/git-credentials.json')
|
AUTH = Path('/etc/iomatex/git-credentials.json')
|
||||||
CACHE = Path('/userdata/iomatex-apt-cache')
|
CACHE = Path('/userdata/iomatex-apt-cache')
|
||||||
|
|
@ -44,7 +51,7 @@ def safe_path(value):
|
||||||
|
|
||||||
def repo_name(url):
|
def repo_name(url):
|
||||||
u = urllib.parse.urlparse(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')
|
raise ValueError('Only HTTPS repositories on our Git are allowed')
|
||||||
name = u.path.strip('/').removesuffix('.git')
|
name = u.path.strip('/').removesuffix('.git')
|
||||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name):
|
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())
|
return json.loads(AUTH.read_text())
|
||||||
|
|
||||||
def open_git(repo, endpoint, auth, timeout=120):
|
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()
|
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
|
||||||
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
|
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
|
||||||
return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
|
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)
|
materialize_file(repo, commit, auth, item, root / 'absent', root)
|
||||||
download_snapshot(files, download)
|
download_snapshot(files, download)
|
||||||
write_json(root / '.iomatex-source.json',
|
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)
|
print('Verifying recovery package catalog...', flush=True)
|
||||||
catalog(root)
|
catalog(root)
|
||||||
write_json(AUTH, auth, 0o600)
|
write_json(AUTH, auth, 0o600)
|
||||||
|
|
@ -282,7 +289,7 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
|
||||||
dest = requested.resolve()
|
dest = requested.resolve()
|
||||||
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
|
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
|
||||||
raise ValueError('Use a dedicated absolute installer subdirectory')
|
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:
|
if commit is None:
|
||||||
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
|
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
|
||||||
commit = json.load(r)['commit']['id']
|
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)
|
materialize_file(repo, commit, auth, entry, dest, staged)
|
||||||
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
|
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
|
||||||
download_snapshot(files, download)
|
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)
|
write_json(staged / '.iomatex-source.json', source)
|
||||||
# Validate all metadata before replacing an existing installation snapshot.
|
# Validate all metadata before replacing an existing installation snapshot.
|
||||||
catalog(staged)
|
catalog(staged)
|
||||||
|
|
@ -397,14 +404,14 @@ def activate(root):
|
||||||
platform_check()
|
platform_check()
|
||||||
root = Path(root).resolve()
|
root = Path(root).resolve()
|
||||||
source = json.loads((root / '.iomatex-source.json').read_text())
|
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'])
|
raw_endpoint('probe', source['commit'])
|
||||||
auth_from_env() # fail before modifying APT if reboot credentials are missing
|
auth_from_env() # fail before modifying APT if reboot credentials are missing
|
||||||
text, objects = catalog(root)
|
text, objects = catalog(root)
|
||||||
STATE.mkdir(parents=True, exist_ok=True)
|
STATE.mkdir(parents=True, exist_ok=True)
|
||||||
(STATE / 'Packages').write_text(text)
|
(STATE / 'Packages').write_text(text)
|
||||||
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
|
(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 = Path('/usr/local/lib/iomatex')
|
||||||
owner.mkdir(parents=True, exist_ok=True)
|
owner.mkdir(parents=True, exist_ok=True)
|
||||||
shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py')
|
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()
|
digest = hashlib.sha256()
|
||||||
size = 0
|
size = 0
|
||||||
try:
|
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:
|
while True:
|
||||||
chunk = response.read(1024 * 1024)
|
chunk = response.read(1024 * 1024)
|
||||||
if not chunk: break
|
if not chunk: break
|
||||||
|
|
|
||||||
|
|
@ -84,8 +84,9 @@ def record(root, stage):
|
||||||
def configure(root):
|
def configure(root):
|
||||||
root = Path(root).resolve()
|
root = Path(root).resolve()
|
||||||
source = read_json(root / '.iomatex-source.json')
|
source = read_json(root / '.iomatex-source.json')
|
||||||
delivery.repo_name('https://' + delivery.HOST + '/' + source['repo'] + '.git')
|
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']}
|
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:
|
if read_json(CONFIG) != next_config:
|
||||||
delivery.write_json(STATE / 'available.json', {})
|
delivery.write_json(STATE / 'available.json', {})
|
||||||
delivery.write_json(CONFIG, next_config)
|
delivery.write_json(CONFIG, next_config)
|
||||||
|
|
@ -97,8 +98,8 @@ def refresh():
|
||||||
phase = 'branch'
|
phase = 'branch'
|
||||||
try:
|
try:
|
||||||
cfg = read_json(CONFIG)
|
cfg = read_json(CONFIG)
|
||||||
repo = delivery.repo_name('https://' + delivery.HOST + '/' + cfg['repo'] + '.git')
|
repo = delivery.repo_name('https://' + delivery.git_host(cfg.get('host', delivery.HOST)) + '/' + cfg['repo'] + '.git')
|
||||||
auth = delivery.auth_from_env()
|
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:
|
with delivery.open_git(repo, 'branches/' + urllib.parse.quote(cfg['branch'], safe=''), auth, timeout=15) as response:
|
||||||
commit = json.load(response)['commit']['id']
|
commit = json.load(response)['commit']['id']
|
||||||
phase = 'catalog'
|
phase = 'catalog'
|
||||||
|
|
@ -352,7 +353,7 @@ def install(stage, commit):
|
||||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
cfg = read_json(CONFIG)
|
cfg = read_json(CONFIG)
|
||||||
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'})
|
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)
|
cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job, preserve_local_changes=True)
|
||||||
root = Path(cfg['checkout'])
|
root = Path(cfg['checkout'])
|
||||||
completed = run_stages(root, stages, commit, job, lock.fileno())
|
completed = run_stages(root, stages, commit, job, lock.fileno())
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,25 @@ sys.path.insert(0, str(Path(__file__).parent))
|
||||||
import git_delivery as d
|
import git_delivery as d
|
||||||
|
|
||||||
class DeliveryTest(unittest.TestCase):
|
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):
|
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']:
|
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))
|
self.assertTrue(d.is_payload(name))
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,14 @@ class StageVersionsTest(unittest.TestCase):
|
||||||
versions.delivery.write_json(versions.STATE / 'available.json', self.available)
|
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')})
|
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):
|
def test_published_catalog_is_accepted_by_legacy_console(self):
|
||||||
raw = json.loads((ROOT / 'stage-releases.json').read_text())
|
raw = json.loads((ROOT / 'stage-releases.json').read_text())
|
||||||
# This is the exact set checked by Console 3.1.2's validator.
|
# This is the exact set checked by Console 3.1.2's validator.
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue