From 9374cadd5012bddaec55965287cd3e84e11ca01f Mon Sep 17 00:00:00 2001 From: I515719 Date: Fri, 4 Dec 2026 13:38:06 +0800 Subject: [PATCH] fix: restore SSH key checkout for GitHub repositories --- deploy/infrabox/templates/_helpers.tpl | 3 - deploy/infrabox/values.yaml | 4 - docs/install/configure/github.md | 36 +-- docs/job/git.md | 6 +- infrabox/test/job/test_clone_auth.py | 151 +++++----- infrabox/test/job/test_git_credentials.py | 104 ------- infrabox/test/job/test_git_ssh.py | 112 ++++++++ scripts/infrabox-ssh-key-recovery/README.md | 137 +++++++++ .../infrabox-rotate-ssh.py | 269 ++++++++++++++++++ .../test_rotate_ssh.py | 85 ++++++ src/job/infrabox_job/git_credentials.py | 86 ------ src/job/infrabox_job/git_ssh.py | 58 ++++ src/job/job.py | 52 +--- 13 files changed, 769 insertions(+), 334 deletions(-) delete mode 100644 infrabox/test/job/test_git_credentials.py create mode 100644 infrabox/test/job/test_git_ssh.py create mode 100644 scripts/infrabox-ssh-key-recovery/README.md create mode 100644 scripts/infrabox-ssh-key-recovery/infrabox-rotate-ssh.py create mode 100644 scripts/infrabox-ssh-key-recovery/test_rotate_ssh.py delete mode 100644 src/job/infrabox_job/git_credentials.py create mode 100644 src/job/infrabox_job/git_ssh.py diff --git a/deploy/infrabox/templates/_helpers.tpl b/deploy/infrabox/templates/_helpers.tpl index 4124eb11b..1545d6ee8 100644 --- a/deploy/infrabox/templates/_helpers.tpl +++ b/deploy/infrabox/templates/_helpers.tpl @@ -416,9 +416,6 @@ infrabox-swift-credentials - name: GITHUB_ENABLE_TOKEN_ACCESS value: {{ .Values.github.token_access | quote}} -- - name: GITHUB_TOKEN_REPOSITORIES - value: {{ .Values.github.token_repositories | default list | toJson | quote }} {{ end }} {{ end }} diff --git a/deploy/infrabox/values.yaml b/deploy/infrabox/values.yaml index a12b09a2e..afa198916 100644 --- a/deploy/infrabox/values.yaml +++ b/deploy/infrabox/values.yaml @@ -278,10 +278,6 @@ github: host: github.com token_access: false - # Additional HTTPS repository URLs allowed to use the owner's token for checkout. - # The project's own repository is always allowed; private submodules/git jobs - # in other repositories must be explicitly listed here by an administrator. - token_repositories: [] # General Account configuration diff --git a/docs/install/configure/github.md b/docs/install/configure/github.md index 62fef1ac7..9546e6b24 100644 --- a/docs/install/configure/github.md +++ b/docs/install/configure/github.md @@ -67,25 +67,17 @@ With this only users who belong to at least one of the organization may be able ## Checkout credentials and build access -`github.token_access` defaults to `false`. The project owner's OAuth token still -authenticates platform-managed HTTPS checkout, but is not exported to Docker -build arguments or container environment variables. Setting it to `true` enables -the legacy token export for trusted, non-PR builds; PR builds never receive that -export. Deploy the API update before the runner update: runners deny token export -when the API has not supplied PR metadata. SSH checkout and fallback remain supported. - -HTTPS credentials are scoped to the project's repository. Administrators must -explicitly allow other private repositories needed by submodules or nested git -jobs, using canonical HTTPS URLs on the configured GitHub host: - -```yaml -github: - token_access: false - token_repositories: - - https://github.example.com/team/private-dependency.git -``` - -This deployment-wide list grants checkout access using each project's owner's -token; keep it narrow. Tokens are not stored in source Git configuration or child -job metadata. Existing historical metadata may contain old tokens; revoke and -replace affected OAuth tokens after deploying the fix. +GitHub clone, fetch, nested git jobs and submodules use SSH. HTTP(S) URLs on +the configured GitHub host are converted to SSH. Checkout uses the project's +SSH key (`repository.private_key` or its configured SSH-key secret), and never +falls back to the owner's OAuth token. The public key must be registered with +GitHub and grant access to every required repository; a deploy key only grants +access to its own repository. + +`github.token_access` defaults to `false`. Setting it to `true` exports +`GITHUB_OAUTH_TOKEN` for API calls in trusted, non-PR builds; PR builds never +receive that export. `GITHUB_BASE_URL` contains only the plain HTTPS base URL. +These settings do not affect checkout authentication. + +To repair a missing or revoked deploy key, use the +[SSH key recovery script](../../../scripts/infrabox-ssh-key-recovery/README.md). diff --git a/docs/job/git.md b/docs/job/git.md index f8c592e25..ff403d076 100644 --- a/docs/job/git.md +++ b/docs/job/git.md @@ -8,7 +8,7 @@ An example git job definition: "jobs": [{ "type": "git", "name": "some-external-jobs", - "clone_url": "https://github.com/SAP/infrabox-examples.git", + "clone_url": "git@github.com:SAP/infrabox-examples.git", "commit": "master", "depends_on": [ ... ], "environment": { ... }, @@ -27,3 +27,7 @@ An example git job definition: |depends_on|false|[Dependency Configuration](/docs/job/dependencies.md)|[]|Jobs may have dependencies. You can list all jobs which should finish before the current job may be executed.| |environment|false|[Environment Variables](/docs/job/env_vars.md)|{}|Can be used to set environment variables for the job.| |infrabox_file|false|string|infrabox.json|Path to an `infrabox.json` file in the repo to be used as sub-workflow| + +GitHub repositories use the project SSH key, including nested git jobs and +submodules. Ensure the key has access to each required repository. HTTP(S) URLs +on the configured GitHub host are converted to SSH. diff --git a/infrabox/test/job/test_clone_auth.py b/infrabox/test/job/test_clone_auth.py index 8c5e9f37e..18cf319cf 100644 --- a/infrabox/test/job/test_clone_auth.py +++ b/infrabox/test/job/test_clone_auth.py @@ -1,3 +1,4 @@ +import inspect import os import tempfile import unittest @@ -6,8 +7,7 @@ from job import RunJob from infrabox_job.job import Job -from infrabox_job.process import ApiConsole - +from infrabox_job.process import ApiConsole, Error SSH_URL = 'git@github.example.com:owner/repo.git' HTTPS_URL = 'https://github.example.com/owner/repo.git' @@ -21,7 +21,7 @@ def setUp(self): self.runner = RunJob.__new__(RunJob) self.runner.mount_repo_dir = str(self.destination) self.runner.github_host = 'github.example.com' - self.runner.repository = {'clone_url': HTTPS_URL, 'github_api_token': 'test-token'} + self.runner.repository = {'clone_url': HTTPS_URL, 'github_api_token': 'expired-token'} self.runner.console = Mock(spec=ApiConsole) self.commands = [] self.failed_urls = set() @@ -37,75 +37,86 @@ def execute(command, **kwargs): environment.start() self.addCleanup(environment.stop) - def clone(self, url=SSH_URL, token='test-token', ref=None): - self.runner.clone_repo('commit-sha', url, 'main', ref, False, submodules=False, token=token) + def clone(self, url=SSH_URL, ref=None, submodules=False): + self.runner.clone_repo('commit-sha', url, 'main', ref, False, submodules=submodules) def clones(self): return [(command[-2], options['retry']) for command, options in self.commands if command[:2] == ['git', 'clone']] - def test_token_success_skips_ssh_for_both_ssh_url_formats(self): + def test_clone_interface_has_no_token_argument(self): + self.assertNotIn('token', inspect.signature(self.runner.clone_repo).parameters) + + def test_github_https_clone_and_ref_fetch_use_ssh(self): + self.clone(HTTPS_URL, ref='refs/pull/1/head') + self.assertEqual(self.clones(), [(SSH_URL, True)]) + commands = [command for command, _ in self.commands] + self.assertIn(['git', 'fetch', '--depth=10', SSH_URL, 'refs/pull/1/head'], commands) + self.assertIn(['git', 'config', 'remote.origin.url', SSH_URL], commands) + self.assertNotIn('expired-token', repr(self.commands)) + + def test_legacy_credentialed_github_url_is_normalized_before_execution(self): + self.clone('https://expired-token:x-oauth-basic@github.example.com/owner/repo.git') + self.assertEqual(self.clones(), [(SSH_URL, True)]) + self.assertNotIn('expired-token', repr(self.commands)) + + def test_existing_ssh_url_formats_are_preserved(self): for url in (SSH_URL, 'ssh://git@github.example.com/owner/repo.git'): with self.subTest(url=url): self.commands.clear() - self.clone(url, ref='refs/pull/1/head') - self.assertEqual(self.clones(), [(HTTPS_URL, False)]) - self.assertTrue(any(command == ['git', 'fetch', '--depth=10', HTTPS_URL, - 'refs/pull/1/head'] - for command, _ in self.commands)) - for command, options in self.commands: - self.assertNotIn('test-token', ' '.join(command)) - self.assertEqual(options['env']['INFRABOX_GIT_TOKEN'], 'test-token') - - def test_token_failure_falls_back_to_ssh_without_token_environment(self): - self.failed_urls.add(HTTPS_URL) - self.clone() - self.assertEqual(self.clones(), [(HTTPS_URL, False), (SSH_URL, True)]) - for command, options in self.commands[1:]: - self.assertNotIn('INFRABOX_GIT_TOKEN', options.get('env') or {}) - self.assertIn(['git', 'config', 'remote.origin.url', SSH_URL], - [command for command, _ in self.commands]) - - def test_authentication_failure_never_reaches_checkout(self): - self.failed_urls.update((HTTPS_URL, SSH_URL)) + self.clone(url) + self.assertEqual(self.clones(), [(url, True)]) + + def test_ssh_failure_does_not_fall_back_to_https_or_reach_checkout(self): + self.failed_urls.add(SSH_URL) with self.assertRaisesRegex(RuntimeError, 'authentication failed'): self.clone() - self.assertFalse(any(command[:2] == ['git', 'checkout'] for command, _ in self.commands)) - - def test_missing_token_uses_ssh_directly(self): - self.clone(token=None) self.assertEqual(self.clones(), [(SSH_URL, True)]) - - def test_other_ssh_host_does_not_receive_github_token(self): - url = 'git@other.example.com:owner/repo.git' - self.clone(url) - self.assertEqual(self.clones(), [(url, True)]) + self.assertFalse(any(command[:2] == ['git', 'checkout'] for command, _ in self.commands)) def test_existing_files_are_preserved_when_clone_fails(self): self.destination.mkdir() existing = self.destination / 'user-file' existing.write_text('keep me') - self.failed_urls.update((HTTPS_URL, SSH_URL)) + self.failed_urls.add(SSH_URL) with self.assertRaisesRegex(RuntimeError, 'authentication failed'): self.clone() - self.assertEqual(self.clones(), [(HTTPS_URL, True)]) self.assertEqual(existing.read_text(), 'keep me') - def test_https_url_includes_noninteractive_token_credentials(self): - self.clone('https://github.example.com/owner/repo.git') - self.assertEqual(self.clones(), [(HTTPS_URL, True)]) - self.assertEqual(self.commands[0][1]['env']['INFRABOX_GIT_TOKEN'], 'test-token') - self.assertIn((['git', 'config', 'remote.origin.url', HTTPS_URL]), - [command for command, _ in self.commands]) - self.assertNotIn('test-token', repr([command for command, _ in self.commands])) - - def test_other_https_host_never_receives_owner_credentials(self): - self.clone('https://other.example.com/owner/repo.git') - for command, options in self.commands: - self.assertNotIn('test-token', ' '.join(command)) - self.assertNotIn('INFRABOX_GIT_TOKEN', options.get('env') or {}) - - def test_disabled_access_does_not_export_token_or_configure_global_git(self): + def test_other_hosts_and_gerrit_ssh_ports_are_preserved(self): + for url in ('git@other.example.com:owner/repo.git', + 'ssh://user@gerrit.example.com:29418/project', + 'https://other.example.com/owner/repo.git'): + with self.subTest(url=url): + self.commands.clear() + self.clone(url) + self.assertEqual(self.clones(), [(url, True)]) + self.assertNotIn('expired-token', repr(self.commands)) + + def test_source_checkout_does_not_pass_owner_token(self): + self.runner.job = {'repo': {'clone_url': HTTPS_URL, 'commit': 'commit-sha', 'branch': 'main'}, + 'definition': {}} + with patch.object(self.runner, 'clone_repo') as clone: + self.runner.get_source() + clone.assert_called_once_with('commit-sha', HTTPS_URL, 'main', None, False, submodules=True) + + def test_nested_git_job_does_not_pass_owner_token(self): + data = {'jobs': [{'name': 'nested', 'type': 'git', 'clone_url': HTTPS_URL, 'commit': 'commit-sha'}]} + with patch.object(self.runner, 'clone_repo') as clone, patch('job.find_infrabox_file', return_value=None): + with self.assertRaises(Error): + self.runner.get_job_list(data, self.runner.console, self.runner.repository) + clone.assert_called_once_with('commit-sha', HTTPS_URL, None, None, True, + os.path.join('.infrabox', 'tmp', 'nested')) + + def test_submodules_use_same_ssh_transport_environment(self): + self.clone(HTTPS_URL, submodules=True) + environment = self.commands[0][1]['env'] + self.assertIsNotNone(environment) + for _, options in self.commands: + self.assertEqual(options['env'], environment) + self.assertIn(['git', 'submodule', 'update', '-q'], [c for c, _ in self.commands]) + + def test_disabled_access_does_not_export_api_token_or_change_global_git(self): self.runner.enable_token_access = False self.runner.environment = {} with patch.dict(os.environ, {'INFRABOX_GITHUB_ENABLED': 'true'}): @@ -113,38 +124,34 @@ def test_disabled_access_does_not_export_token_or_configure_global_git(self): self.assertNotIn('GITHUB_OAUTH_TOKEN', self.runner.environment) self.assertEqual(self.runner.environment['GITHUB_BASE_URL'], 'https://github.example.com') self.assertFalse(self.commands) - self.clone() - self.assertEqual(self.clones(), [(HTTPS_URL, False)]) + + def test_api_token_access_does_not_embed_credentials_in_github_url(self): + self.runner.enable_token_access = True + self.runner.environment = {} + with patch.dict(os.environ, {'INFRABOX_GITHUB_ENABLED': 'true'}): + self.runner.config_github() + self.assertEqual(self.runner.environment['GITHUB_BASE_URL'], 'https://github.example.com') + self.assertEqual(self.runner.environment['GITHUB_OAUTH_TOKEN'], 'expired-token') + self.assertFalse(self.commands) def test_token_access_requires_explicit_true(self): for value in ('false', '', '0', 'yes', 'true'): with self.subTest(value=value), patch.dict(os.environ, { - 'INFRABOX_GENERAL_SYSTEM_NAMESPACE': 'test', - 'GITHUB_ENABLE_TOKEN_ACCESS': value}): + 'INFRABOX_GENERAL_SYSTEM_NAMESPACE': 'test', 'GITHUB_ENABLE_TOKEN_ACCESS': value}): self.assertIs(Job().enable_token_access, value == 'true') def test_generated_jobs_do_not_retain_legacy_owner_token(self): - repo = {'clone_url': HTTPS_URL, 'github_api_token': 'test-token'} - data = {'jobs': [{'name': 'test', 'type': 'docker-image'}]} - jobs = self.runner.get_job_list(data, self.runner.console, repo) + repo = {'clone_url': HTTPS_URL, 'github_api_token': 'expired-token'} + jobs = self.runner.get_job_list({'jobs': [{'name': 'test', 'type': 'docker-image'}]}, + self.runner.console, repo) self.assertNotIn('github_api_token', jobs[0]['repo']) - self.assertEqual(repo['github_api_token'], 'test-token') + self.assertEqual(repo['github_api_token'], 'expired-token') def test_uploaded_source_jobs_preserve_absent_repository(self): - data = {'jobs': [{'name': 'test', 'type': 'docker-image'}]} - jobs = self.runner.get_job_list(data, self.runner.console, None) + jobs = self.runner.get_job_list({'jobs': [{'name': 'test', 'type': 'docker-image'}]}, + self.runner.console, None) self.assertIsNone(jobs[0]['repo']) - def test_github_base_url_uses_the_same_token_credentials(self): - self.runner.repository = {'github_api_token': 'test-token'} - self.runner.enable_token_access = True - self.runner.environment = {} - with patch.dict(os.environ, {'INFRABOX_GITHUB_ENABLED': 'true'}): - self.runner.config_github() - self.assertEqual(self.runner.environment['GITHUB_BASE_URL'], - 'https://test-token:x-oauth-basic@github.example.com') - self.assertEqual(self.runner.environment['GITHUB_OAUTH_TOKEN'], 'test-token') - if __name__ == '__main__': unittest.main() diff --git a/infrabox/test/job/test_git_credentials.py b/infrabox/test/job/test_git_credentials.py deleted file mode 100644 index dbb94bc46..000000000 --- a/infrabox/test/job/test_git_credentials.py +++ /dev/null @@ -1,104 +0,0 @@ -import json -import os -import subprocess -import tempfile -import unittest -import sys -import shlex -from pathlib import Path -from unittest.mock import patch - -from infrabox_job.git_credentials import git_environment - - -class GitCredentialsTest(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.home = directory.name - self.environment = patch.dict(os.environ, { - 'HOME': self.home, 'GIT_CONFIG_NOSYSTEM': '1', - 'INFRABOX_GENERAL_DONT_CHECK_CERTIFICATES': 'false', - }) - self.environment.start() - self.addCleanup(self.environment.stop) - - def fill(self, host='github.example.com', path='owner/repo.git', protocol='https', - repositories=None): - env = git_environment('github.example.com', 'test-token', repositories or [ - 'https://github.example.com/owner/repo.git']) - return subprocess.run(['git', 'credential', 'fill'], - input='protocol=%s\nhost=%s\npath=%s\n\n' % (protocol, host, path), - text=True, capture_output=True, env=env, cwd=self.home) - - def test_real_git_authenticates_only_the_allowed_https_repository(self): - for path in ('owner/repo.git', 'owner/repo'): - with self.subTest(path=path): - result = self.fill(path=path) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn('username=test-token\n', result.stdout) - self.assertIn('password=x-oauth-basic\n', result.stdout) - for kwargs in ({'host': 'other.example.com'}, {'protocol': 'http'}, - {'path': 'owner/other.git'}, {'path': 'owner/repo.git/../other'}, - {'host': 'github.example.com.evil.test'}, - {'path': 'owner/repo.git/info/refs'}): - with self.subTest(kwargs=kwargs): - result = self.fill(**kwargs) - self.assertNotEqual(result.returncode, 0) - self.assertNotIn('test-token', result.stdout + result.stderr) - - def test_administrator_can_allow_private_submodule_repository(self): - result = self.fill(path='owner/private-submodule.git', repositories=[ - 'https://github.example.com/owner/repo.git', - 'https://github.example.com/owner/private-submodule.git']) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn('username=test-token', result.stdout) - - def test_git_does_not_store_credentials_or_change_parent_environment(self): - before = dict(os.environ) - env = git_environment('github.example.com', 'test-token', [ - 'https://github.example.com/owner/repo.git']) - result = subprocess.run(['git', 'credential', 'approve'], - input='protocol=https\nhost=github.example.com\n' - 'path=owner/repo.git\nusername=test-token\n' - 'password=x-oauth-basic\n\n', - text=True, capture_output=True, env=env, cwd=self.home) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(dict(os.environ), before) - self.assertEqual(os.listdir(self.home), []) - - def test_authentication_config_is_temporary_and_disables_redirects(self): - env = git_environment('github.example.com', 'test-token', [ - 'https://github.example.com/owner/repo.git']) - result = subprocess.run(['git', 'config', '--get', 'http.followRedirects'], - env=env, text=True, capture_output=True, cwd=self.home) - self.assertEqual(result.stdout.strip(), 'false') - result = subprocess.run(['git', 'config', '--global', '--list'], - text=True, capture_output=True, cwd=self.home) - self.assertNotIn('test-token', result.stdout + result.stderr) - - def test_ssh_submodules_keep_their_transport_without_inheriting_token(self): - script = Path(self.home) / 'ssh-fixture.py' - result_path = Path(self.home) / 'ssh-result.json' - script.write_text('import json, os, pathlib, sys\n' - 'pathlib.Path(sys.argv[1]).write_text(json.dumps({\n' - ' "token_present": "INFRABOX_GIT_TOKEN" in os.environ,\n' - ' "arguments": sys.argv[2:]}))\n' - 'sys.exit(1)\n') - command = ' '.join(shlex.quote(str(item)) for item in (sys.executable, script, result_path)) - with patch.dict(os.environ, {'GIT_SSH_COMMAND': command}): - env = git_environment('github.example.com', 'test-token', [ - 'https://github.example.com/owner/repo.git']) - for host in ('github.example.com', 'other.example.com'): - with self.subTest(host=host): - result_path.unlink(missing_ok=True) - result = subprocess.run(['git', 'ls-remote', 'git@%s:owner/sub.git' % host], - env=env, capture_output=True, text=True, cwd=self.home) - self.assertTrue(result_path.exists(), result.stderr) - payload = json.loads(result_path.read_text()) - self.assertFalse(payload['token_present']) - self.assertIn('git@%s' % host, payload['arguments']) - - -if __name__ == '__main__': - unittest.main() diff --git a/infrabox/test/job/test_git_ssh.py b/infrabox/test/job/test_git_ssh.py new file mode 100644 index 000000000..0984a2798 --- /dev/null +++ b/infrabox/test/job/test_git_ssh.py @@ -0,0 +1,112 @@ +import json +import os +import shlex +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from infrabox_job.git_ssh import github_ssh_url, git_environment, configure_submodule_urls + + +class GitSSHTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.global_config = self.root / 'global-config' + self.global_config.touch() + environment = patch.dict(os.environ, { + 'GIT_CONFIG_NOSYSTEM': '1', 'GIT_CONFIG_GLOBAL': str(self.global_config), + 'GIT_AUTHOR_NAME': 'Test', 'GIT_AUTHOR_EMAIL': 'test@example.com', + 'GIT_COMMITTER_NAME': 'Test', 'GIT_COMMITTER_EMAIL': 'test@example.com', + 'INFRABOX_GENERAL_DONT_CHECK_CERTIFICATES': 'false', + }) + environment.start() + self.addCleanup(environment.stop) + + def git(self, *args, cwd=None, env=None): + result = subprocess.run(['git'] + list(args), cwd=cwd or self.root, + env=env, text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.strip() + + def test_url_conversion_matches_only_configured_github_host(self): + host = 'github.example.com' + for url in ('https://github.example.com/owner/repo.git', + 'http://github.example.com/owner/repo.git', + 'https://expired:x-oauth-basic@GITHUB.EXAMPLE.COM/owner/repo.git'): + self.assertEqual(github_ssh_url(url, host), 'git@github.example.com:owner/repo.git') + for url in ('https://github.example.com.evil.test/owner/repo.git', + 'https://github.example.com@other.example.com/owner/repo.git', + 'ssh://git@github.example.com:2222/owner/repo.git', + 'git@github.example.com:owner/repo.git', + 'ssh://user@gerrit.example.com:29418/project'): + self.assertEqual(github_ssh_url(url, host), url) + self.assertEqual(github_ssh_url('https://other.example.com/repo', ''), + 'https://other.example.com/repo') + + def test_real_git_clone_and_https_submodule_use_ssh(self): + sub = self.root / 'sub-source' + source = self.root / 'source' + for path in (sub, source): + self.git('init', str(path)) + (path / 'content').write_text(path.name) + self.git('add', '.', cwd=path) + self.git('commit', '-m', 'initial', cwd=path) + sub_sha = self.git('rev-parse', 'HEAD', cwd=sub) + (source / '.gitmodules').write_text( + '[submodule "dep"]\n\tpath = dep\n' + '\turl = https://expired-token:x-oauth-basic@GITHUB.EXAMPLE.COM:443/owner/sub.git\n') + self.git('add', '.gitmodules', cwd=source) + self.git('update-index', '--add', '--cacheinfo', '160000,' + sub_sha + ',dep', cwd=source) + self.git('commit', '-m', 'submodule', cwd=source) + log = self.root / 'ssh.jsonl' + script = self.root / 'ssh.py' + script.write_text( + 'import json, os, pathlib, shlex, sys\n' + 'log, source, sub = sys.argv[1:4]\n' + 'args = sys.argv[4:]\n' + 'with open(log, "a") as stream:\n' + ' stream.write(json.dumps(args) + chr(10))\n' + 'assert "git@github.example.com" in args\n' + 'assert "INFRABOX_GIT_TOKEN" not in os.environ\n' + 'repo = shlex.split(args[-1])[1].lstrip("/")\n' + 'target = {"owner/repo.git": source, "owner/sub.git": sub}[repo]\n' + 'os.execvp("git", ["git", "upload-pack", target])\n') + ssh = ' '.join(shlex.quote(str(p)) for p in (sys.executable, script, log, source, sub)) + with patch.dict(os.environ, {'GIT_SSH_COMMAND': ssh, 'GIT_SSH_VARIANT': 'ssh', + 'INFRABOX_GIT_TOKEN': 'expired-token'}): + before = dict(os.environ) + env = git_environment('github.example.com') + self.assertEqual(before, dict(os.environ)) + checkout = self.root / 'checkout' + self.git('clone', '--depth=1', 'https://github.example.com/owner/repo.git', str(checkout), env=env) + configure_submodule_urls(checkout, 'github.example.com', env) + self.git('submodule', 'update', '--init', cwd=checkout, env=env) + self.assertEqual((checkout / 'dep' / 'content').read_text(), 'sub-source') + calls = [json.loads(line) for line in log.read_text().splitlines()] + self.assertTrue(any('owner/repo.git' in args[-1] for args in calls)) + self.assertTrue(any('owner/sub.git' in args[-1] for args in calls)) + self.assertEqual(self.global_config.read_text(), '') + config = self.git('config', '--local', '--list', cwd=checkout) + self.assertNotIn('expired-token', config) + self.assertNotIn('insteadof', config.lower()) + self.assertNotIn('credential.helper', config) + + def test_https_rewrite_is_limited_to_exact_host(self): + env = git_environment('github.example.com') + for url, expected in ( + ('https://github.example.com/owner/repo.git', 'ssh://git@github.example.com/owner/repo.git'), + ('http://github.example.com/owner/repo.git', 'ssh://git@github.example.com/owner/repo.git'), + ('https://github.example.com.evil.test/owner/repo.git', 'https://github.example.com.evil.test/owner/repo.git'), + ('https://other.example.com/owner/repo.git', 'https://other.example.com/owner/repo.git'), + ('ssh://user@gerrit.example.com:29418/project', 'ssh://user@gerrit.example.com:29418/project')): + with self.subTest(url=url): + self.assertEqual(self.git('ls-remote', '--get-url', url, env=env), expected) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/infrabox-ssh-key-recovery/README.md b/scripts/infrabox-ssh-key-recovery/README.md new file mode 100644 index 000000000..88d53dc9b --- /dev/null +++ b/scripts/infrabox-ssh-key-recovery/README.md @@ -0,0 +1,137 @@ +# InfraBox SSH deploy key recovery + +Repair one InfraBox GitHub project's checkout credentials by project name or UUID. +The public key is registered as a read-only GitHub Deploy key named `InfraBox`. +The private key is stored in the existing `repository.private_key` database field. + +## Requirements + +- Local Python 3, `kubectl`, GitHub CLI (`gh`), and `ssh-keygen`. +- Network access to the Kubernetes cluster and configured GitHub Enterprise host. +- A GitHub token that can read the target repository and manage its Deploy keys. + Store only the raw token in the token file. The script supplies it to `gh`; + a separate `gh auth login` is unnecessary. +- Permission to exec into the InfraBox API container. Database operations reuse + the API container's installed libraries and connection configuration. +- For SSH verification, either local Git and SSH, or a running job Pod with + Python 3, Git, and SSH in its `function` container. +- The GitHub SSH host key must already be trusted in the verification environment. + SSH verification uses `StrictHostKeyChecking=yes`. + +## Quick start + +From the InfraBox repository root: + +```sh +cd scripts/infrabox-ssh-key-recovery +``` + +Check a project without making changes: + +```sh +python3 infrabox-rotate-ssh.py dhaas-operator +``` + +A project UUID works in the same position: + +```sh +python3 infrabox-rotate-ssh.py 045480b8-3566-4c3b-adcf-b8d1bc027c44 +``` + +Repair the project and verify SSH clone locally: + +```sh +python3 infrabox-rotate-ssh.py dhaas-operator --apply +``` + +To verify from an existing sleep job Pod instead, find the current Pod name: + +```sh +kubectl --kubeconfig ../../credentials/eu-de-1.yaml get pods -n infrabox-worker +``` + +Replace `SLEEP_POD_NAME` with the running sleep job's Pod name: + +```sh +python3 infrabox-rotate-ssh.py dhaas-operator --apply --probe-pod SLEEP_POD_NAME +``` + +The Pod is only used for a temporary SSH clone check. The script does not change +its normal SSH identity, and removes the temporary private key and checkout. +It does not create the sleep Pod. + +## Configuration + +Credential paths are resolved relative to the InfraBox repository, regardless +of the shell's current directory. + +| Option | Default | +| --- | --- | +| `--github-token-file` | `/credentials/git-token` | +| `--kubeconfig` | `/credentials/eu-de-1.yaml` | +| `--github-host` | `github.wdf.sap.corp` | +| `--system-namespace` | `infrabox-system` | +| `--worker-namespace` | `infrabox-worker` | +| `--api-deployment` | `infrabox-api` (container `api`) | +| `--probe-pod` | Unset: verify locally | + +For example, use another cluster's kubeconfig: + +```sh +python3 infrabox-rotate-ssh.py rms \ + --kubeconfig /absolute/path/to/kubeconfig \ + --github-token-file /absolute/path/to/git-token +``` + +Keep credential files outside version control. This directory contains only +the script, documentation, and tests; generated private keys are temporary. + +## Update behavior + +1. Resolve exactly one GitHub project, confirm its repository identity, and + compare its stored key fingerprint with GitHub Deploy keys. Check mode only + compares configuration; it does not perform a clone. +2. With `--apply`, create a new RSA 3072-bit key pair and register its public key + as a read-only Deploy key. +3. Verify a shallow SSH clone of the repository's default branch. +4. Update `repository.private_key` only if the previous database value has not + changed concurrently, then read back and verify the new fingerprint. + +If the stored key is already registered, `--apply` reports `unchanged`. Use +`--apply --force` only when you intentionally want to replace that key. Existing +Deploy keys are retained so other running jobs can continue using them. + +Successful updates report `result: updated` with the project ID, Deploy key ID, +and public fingerprint. Rerun the affected job afterward: existing Pods retain +their previous credentials. This script does not restart builds automatically. +It does not update Owner OAuth tokens or configure GitHub API authentication. +Projects with a custom Project Secret / SSH Key override are rejected because +that override takes precedence over `repository.private_key`. + +## Failure handling + +- If SSH verification fails, the database is not changed and the script attempts + to remove only the Deploy key it just created. +- A concurrent database change is preserved; the new Deploy key is retained for reconciliation. +- If an update response is lost, the script reads back the fingerprint. If the + database outcome cannot be determined or the old value is still visible, it + retains the new Deploy key and reports its ID: a disconnected update can still + commit later. Re-run check mode and reconcile the fingerprint before deleting it. +- `host_key_verification_failed` means the verification environment does not trust + the GitHub SSH host. Verify the host key through your trusted source and add it + to that environment's `known_hosts` before retrying. +- GitHub `401` / `403` errors require checking the token and repository permissions. +- Pod/database errors require checking cluster access, the selected API container, + project identity, and whether the project has a custom SSH Key override. Raw + database errors are suppressed to avoid disclosing credential-bearing parameters. + +## Local tests + +```sh +python3 test_rotate_ssh.py +python3 infrabox-rotate-ssh.py --help +``` + +The tests cover registered-key preservation, verification-before-update ordering, +failure cleanup, concurrent changes, and uncertain database commit results. They +do not contact GitHub, Kubernetes, or the database. diff --git a/scripts/infrabox-ssh-key-recovery/infrabox-rotate-ssh.py b/scripts/infrabox-ssh-key-recovery/infrabox-rotate-ssh.py new file mode 100644 index 000000000..e7ee84c40 --- /dev/null +++ b/scripts/infrabox-ssh-key-recovery/infrabox-rotate-ssh.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Repair one InfraBox GitHub deploy key, retaining repository.private_key. + +Requires local Python 3, kubectl, gh, ssh-keygen, and access to the API Pod. +Checks only by default. --apply registers a read-only key, verifies SSH clone, +then replaces the private key using a guarded database update. No new API +endpoint is needed. Database connection settings stay inside the API container. +""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[2] + +def fingerprint(public_key): + blob = base64.b64decode(public_key.split()[1], validate=True) + return 'SHA256:' + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip('=') + +def rotate(old, registered, create, verify, update, read, delete): + """Keep active keys, verify before updating, reconcile uncertain commits.""" + if old and old in registered: + return 'unchanged' + new, key_id = create() + try: + verify() + except Exception: + delete(key_id) + raise + try: + update() + if read() != new: + raise RuntimeError('Database fingerprint verification failed') + except Exception: + try: + current = read() + except Exception: + raise RuntimeError('Database outcome unknown; retain new deploy key %s for reconciliation' % key_id) from None + if current != new: + # A disconnected remote update may still be in flight. Reading the + # old committed value does not prove that its transaction rolled back. + raise RuntimeError('Database update not confirmed; retain new deploy key %s for reconciliation' % key_id) from None + return 'updated' + +DB_CODE = r""" +import base64,hashlib,json,sys +from Crypto.PublicKey import RSA +from pyinfraboxutils.db import connect_db + +def run(): + data=json.load(sys.stdin) + conn=connect_db() + try: + cur=conn.cursor() + cur.execute("SET LOCAL statement_timeout = '15s'") + cur.execute("SET LOCAL lock_timeout = '5s'") + query='''SELECT p.id::text,p.name,p.type,r.id::text,r.github_owner,r.name, + r.clone_url,r.private_key,md5(r.private_key),r.github_id + FROM project p JOIN repository r ON r.project_id=p.id + WHERE p.id::text=%s OR p.name=%s''' + if data.get('mode')=='update': + query+=' FOR UPDATE OF r' + cur.execute(query,(data['project'],data['project'])) + rows=cur.fetchall() + if len(rows)!=1: + raise RuntimeError('Project selector must resolve to exactly one repository') + row=rows[0] + if row[2]!='github': + raise RuntimeError('Project must be of type github') + cur.execute('SELECT count(*) FROM sshkey WHERE project_id=%s',(row[0],)) + if cur.fetchone()[0]: + raise RuntimeError('Project has a custom SSH key override; repository.private_key is not effective') + if data.get('mode')=='update': + if row[3]!=data['repository_id'] or row[8]!=data['expected_hash']: + raise RuntimeError('Repository private key changed concurrently') + cur.execute('''UPDATE repository SET private_key=%s + WHERE id=%s AND project_id=%s + AND md5(private_key) IS NOT DISTINCT FROM %s''', + (data['private_key'],row[3],row[0],data['expected_hash'])) + if cur.rowcount!=1: + raise RuntimeError('Guarded update did not update exactly one repository') + conn.commit() + return {'updated':True,'project_id':row[0]} + key_fingerprint=None + if row[7]: + public=RSA.importKey(row[7]).publickey().exportKey('OpenSSH').decode() + blob=base64.b64decode(public.split()[1]) + key_fingerprint='SHA256:'+base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip('=') + return {'project_id':row[0],'project_name':row[1],'repository_id':row[3], + 'owner':row[4],'repository':row[5],'clone_url':row[6], + 'private_key_hash':row[8],'github_id':row[9],'fingerprint':key_fingerprint} + finally: + conn.close() +try: + print(json.dumps(run())) +except Exception as exc: + # Error details/SQL parameters can contain a private key: never print them. + print(json.dumps({'error_type':type(exc).__name__})) + sys.exit(1) +""" + +SSH_CODE = r''' +import json,os,subprocess,sys,tempfile +from pathlib import Path +data=json.load(sys.stdin) +with tempfile.TemporaryDirectory(prefix='infrabox-ssh-probe-') as temp: + key=Path(temp)/'id_rsa' + fd=os.open(str(key),os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) + with os.fdopen(fd,'w') as stream: stream.write(data['private_key']) + env=os.environ.copy() + env.pop('GIT_CONFIG_PARAMETERS',None) + env.pop('GIT_CONFIG_COUNT',None) + env.update(GIT_CONFIG_NOSYSTEM='1',GIT_CONFIG_GLOBAL='/dev/null',GIT_TERMINAL_PROMPT='0') + env['GIT_SSH_COMMAND']='ssh -F /dev/null -i '+str(key)+' -o IdentitiesOnly=yes -o IdentityAgent=none -o BatchMode=yes -o StrictHostKeyChecking=yes -o ConnectTimeout=10' + try: + result=subprocess.run(['git','clone','--depth=1','--no-checkout',data['clone_url'],temp+'/repo'], + input='',env=env,cwd=temp,text=True,capture_output=True,timeout=120) + out={'clone_succeeded':result.returncode==0,'returncode':result.returncode, + 'publickey_denied':'Permission denied (publickey)' in result.stderr, + 'host_key_verification_failed':'Host key verification failed' in result.stderr} + print(json.dumps(out)) + sys.exit(0 if result.returncode==0 else 1) + except subprocess.TimeoutExpired: + print(json.dumps({'clone_succeeded':False,'timeout':True})) + sys.exit(1) +''' + +class Operator: + def __init__(self,args): + self.args=args + self.github_env=os.environ.copy() + token=Path(args.github_token_file).read_text().strip() + if not re.fullmatch(r'[A-Za-z0-9_]+',token): + raise RuntimeError('Token file must contain a single raw GitHub token') + self.github_env.pop('GH_TOKEN',None) + self.github_env['GH_ENTERPRISE_TOKEN']=token + self.github_env['GH_PROMPT_DISABLED']='1' + + def pod(self,namespace,pod,container,script,payload,timeout=45): + command=['kubectl','--kubeconfig',self.args.kubeconfig,'exec','-i','-n',namespace,pod, + '-c',container,'--request-timeout=20s','--','python3','-c',script] + result=subprocess.run(command,input=json.dumps(payload),text=True,capture_output=True,timeout=timeout) + try: + data=json.loads(result.stdout) + except ValueError: + raise RuntimeError('Pod command failed; credential-bearing output suppressed') from None + if result.returncode: + if 'clone_succeeded' in data: + print(json.dumps({'stage':'ssh_probe',**data}),flush=True) + raise RuntimeError('Pod command failed: '+data.get('error_type','SSH verification failed')) + return data + + def database(self,payload): + return self.pod(self.args.system_namespace,'deployment/'+self.args.api_deployment,'api',DB_CODE,payload) + + def github(self,method,path,payload=None): + command=['gh','api','--hostname',self.args.github_host,'--method',method,path] + if payload is not None: + command+=['--input','-'] + result=subprocess.run(command,input=None if payload is None else json.dumps(payload), + env=self.github_env,text=True,capture_output=True,timeout=30) + if result.returncode: + match=re.search(r'HTTP ([0-9]+)',result.stderr) + raise RuntimeError('GitHub request failed: '+(match.group(1) if match else 'transport error')) + return json.loads(result.stdout) if result.stdout.strip() else None + + def run(self): + state=self.database({'project':self.args.project,'mode':'read'}) + owner,repo=state['owner'],state['repository'] + if not all(isinstance(v,str) and re.fullmatch(r'[A-Za-z0-9_.-]+',v) and v not in ('.','..') for v in (owner,repo)): + raise RuntimeError('Invalid repository identity') + expected='git@'+self.args.github_host+':'+owner+'/'+repo+'.git' + allowed={expected,'ssh://git@'+self.args.github_host+'/'+owner+'/'+repo+'.git', + 'https://'+self.args.github_host+'/'+owner+'/'+repo+'.git'} + if state['clone_url'] not in allowed: + raise RuntimeError('Repository clone URL does not match the selected GitHub host and repository') + path='/repos/'+quote(owner,safe='')+'/'+quote(repo,safe='') + info=self.github('GET',path) + if str(info['id'])!=str(state['github_id']): + raise RuntimeError('GitHub repository ID differs from InfraBox') + keys=[] + page=1 + while True: + batch=self.github('GET',path+'/keys?per_page=100&page='+str(page)) + keys+=batch + if len(batch)<100: + break + page+=1 + registered=[fingerprint(k['key']) for k in keys] + print(json.dumps({'project':state['project_name'],'project_id':state['project_id'], + 'repository':owner+'/'+repo,'stored_key_fingerprint':state['fingerprint'], + 'deploy_key_count':len(keys),'stored_key_registered':state['fingerprint'] in registered, + 'mode':'apply' if self.args.apply else 'check'}),flush=True) + if not self.args.apply: + return + if state['fingerprint'] and state['fingerprint'] in registered and not self.args.force: + print(json.dumps({'result':'unchanged','reason':'Stored public key is already registered'})) + return + with tempfile.TemporaryDirectory(prefix='infrabox-rotate-ssh-') as temp: + key=Path(temp)/'id_rsa' + generated=subprocess.run(['ssh-keygen','-q','-t','rsa','-b','3072','-m','PEM', + '-N','','-C','InfraBox '+state['project_name'],'-f',str(key)], + capture_output=True,timeout=25) + if generated.returncode: + raise RuntimeError('SSH key generation failed') + private=key.read_text() + public=Path(str(key)+'.pub').read_text().strip() + new_fingerprint=fingerprint(public) + created_id=None + def create(): + nonlocal created_id + created=self.github('POST',path+'/keys',{'title':'InfraBox','key':public,'read_only':True}) + created_id=created['id'] + print(json.dumps({'stage':'public_key_registered','key_id':created_id,'fingerprint':new_fingerprint}),flush=True) + return new_fingerprint,created_id + def verify(): + payload={'private_key':private,'clone_url':expected} + if self.args.probe_pod: + data=self.pod(self.args.worker_namespace,self.args.probe_pod,'function',SSH_CODE,payload,150) + else: + result=subprocess.run([sys.executable,'-c',SSH_CODE],input=json.dumps(payload), + text=True,capture_output=True,timeout=150) + data=json.loads(result.stdout) + if result.returncode: + raise RuntimeError('Local SSH verification failed; check known_hosts and connectivity') + print(json.dumps({'stage':'ssh_clone_verified',**data}),flush=True) + def update(): + self.database({'project':state['project_id'],'mode':'update','repository_id':state['repository_id'], + 'expected_hash':state['private_key_hash'],'private_key':private}) + def read(): + return self.database({'project':state['project_id'],'mode':'read'})['fingerprint'] + result=rotate(state['fingerprint'],[] if self.args.force else registered,create,verify,update,read, + lambda key_id:self.github('DELETE',path+'/keys/'+str(key_id))) + print(json.dumps({'result':result,'project_id':state['project_id'],'deploy_key_id':created_id, + 'fingerprint':new_fingerprint,'storage':'repository.private_key'}),flush=True) + +def main(): + parser=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project',help='Exact InfraBox project name or UUID') + parser.add_argument('--github-token-file',default=str(ROOT/'credentials/git-token')) + parser.add_argument('--github-host',default='github.wdf.sap.corp') + parser.add_argument('--kubeconfig',default=str(ROOT/'credentials/eu-de-1.yaml')) + parser.add_argument('--system-namespace',default='infrabox-system') + parser.add_argument('--worker-namespace',default='infrabox-worker') + parser.add_argument('--api-deployment',default='infrabox-api') + parser.add_argument('--probe-pod',help='Running sleep job Pod for SSH clone verification; otherwise verify locally') + parser.add_argument('--apply',action='store_true',help='Create, verify, and bind the new key') + parser.add_argument('--force',action='store_true',help='Explicitly rotate even a registered key; older public keys are retained') + args=parser.parse_args() + if not re.fullmatch(r'[A-Za-z0-9.-]+',args.github_host): + parser.error('Invalid GitHub hostname') + try: + Operator(args).run() + except Exception as exc: + # Never print raw subprocess output, private keys, HTTP bodies, or tracebacks. + message=str(exc) if isinstance(exc,RuntimeError) else type(exc).__name__ + print('ERROR: '+message,file=sys.stderr) + return 1 + return 0 + +if __name__=='__main__': + sys.exit(main()) diff --git a/scripts/infrabox-ssh-key-recovery/test_rotate_ssh.py b/scripts/infrabox-ssh-key-recovery/test_rotate_ssh.py new file mode 100644 index 000000000..4fb464d8f --- /dev/null +++ b/scripts/infrabox-ssh-key-recovery/test_rotate_ssh.py @@ -0,0 +1,85 @@ +import importlib.util +from pathlib import Path +import unittest + +MODULE = Path(__file__).with_name('infrabox-rotate-ssh.py') + +class RotationTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if MODULE.exists(): + spec = importlib.util.spec_from_file_location('rotate_ssh', MODULE) + cls.module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(cls.module) + else: + cls.module = None + + def coordinator(self): + self.assertIsNotNone(self.module, 'Rotation implementation is missing') + return self.module.rotate + + def test_healthy_key_does_not_rotate(self): + events = [] + result = self.coordinator()('old', ['old'], lambda: events.append('create'), + lambda: events.append('verify'), lambda: events.append('update'), + lambda: 'old', lambda key: events.append('delete')) + self.assertEqual(result, 'unchanged') + self.assertEqual(events, []) + + def test_verification_failure_does_not_update_database(self): + events = [] + def verify(): + events.append('verify') + raise RuntimeError('SSH rejected') + with self.assertRaises(RuntimeError): + self.coordinator()('old', [], lambda: events.append('create') or ('new', 123), + verify, lambda: events.append('update'), lambda: 'old', + lambda key: events.append(('delete', key))) + self.assertEqual(events, ['create', 'verify', ('delete', 123)]) + + def test_success_verifies_before_database_update(self): + events = [] + result = self.coordinator()('old', [], lambda: events.append('create') or ('new', 123), + lambda: events.append('verify'), lambda: events.append('update'), + lambda: 'new', lambda key: events.append(('delete', key))) + self.assertEqual(result, 'updated') + self.assertEqual(events, ['create', 'verify', 'update']) + + def test_concurrent_update_preserved(self): + removed = [] + def update(): + raise RuntimeError('compare-and-set conflict') + with self.assertRaises(RuntimeError): + self.coordinator()('old', [], lambda: ('new', 123), lambda: None, + update, lambda: 'other', removed.append) + self.assertEqual(removed, []) + + def test_inflight_update_keeps_key_when_readback_still_has_old_value(self): + removed = [] + def update(): + raise TimeoutError('remote transaction may still commit') + with self.assertRaisesRegex(RuntimeError, 'retain new deploy key 123'): + self.coordinator()('old', [], lambda: ('new', 123), lambda: None, + update, lambda: 'old', removed.append) + self.assertEqual(removed, []) + + def test_lost_commit_reply_with_committed_key_is_success(self): + removed = [] + def update(): + raise RuntimeError('connection lost after commit') + result = self.coordinator()('old', [], lambda: ('new', 123), lambda: None, + update, lambda: 'new', removed.append) + self.assertEqual(result, 'updated') + self.assertEqual(removed, []) + + def test_unknown_commit_does_not_revoke_possibly_active_key(self): + removed = [] + def unavailable(): + raise RuntimeError('unavailable') + with self.assertRaises(RuntimeError): + self.coordinator()('old', [], lambda: ('new', 123), lambda: None, + unavailable, unavailable, removed.append) + self.assertEqual(removed, []) + +if __name__ == '__main__': + unittest.main() diff --git a/src/job/infrabox_job/git_credentials.py b/src/job/infrabox_job/git_credentials.py deleted file mode 100644 index c27ca5118..000000000 --- a/src/job/infrabox_job/git_credentials.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Ephemeral, repository-scoped HTTPS credentials for the trusted checkout process.""" -import json -import os -import re -import shlex -import sys -from urllib.parse import urlsplit - - -def github_url(url, host): - for prefix in ('git@%s:' % host, 'ssh://git@%s/' % host): - if host and url.startswith(prefix): - return 'https://%s/%s' % (host, url[len(prefix):]) - parsed = urlsplit(url) - if host and parsed.scheme == 'https' and parsed.netloc.lower() == host.lower(): - return url - return None - - -def repository_path(path): - path = path.strip('/') - if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', path): - return None - if any(part in ('.', '..') for part in path.split('/')): - return None - return path[:-4] if path.endswith('.git') else path - - -def git_environment(host, token, repositories): - allowed = [] - for repository in repositories: - url = github_url(repository, host) if repository else None - if url: - path = repository_path(urlsplit(url).path) - if path: - allowed.append(path) - - env = os.environ.copy() - env.pop('GIT_CONFIG_PARAMETERS', None) - env.update({ - 'INFRABOX_GIT_TOKEN': token or '', - 'INFRABOX_GIT_HOST': host.lower(), - 'INFRABOX_GIT_ALLOWED_PATHS': json.dumps(allowed), - 'GIT_TERMINAL_PROMPT': '0', - 'GIT_ASKPASS': '/bin/false', - 'SSH_ASKPASS': '/bin/false', - }) - # SSH submodules retain their existing transport, without the OAuth token. - ssh = os.environ.get('GIT_SSH_COMMAND') or shlex.quote(os.environ.get('GIT_SSH', 'ssh')) - env['GIT_SSH_COMMAND'] = ('env -u INFRABOX_GIT_TOKEN -u INFRABOX_GIT_HOST ' - '-u INFRABOX_GIT_ALLOWED_PATHS ' + ssh) - env['GIT_SSH_VARIANT'] = os.environ.get('GIT_SSH_VARIANT', 'ssh') - config = [ - ('credential.helper', ''), - ('credential.helper', '!%s %s' % (shlex.quote(sys.executable), shlex.quote(__file__))), - ('credential.useHttpPath', 'true'), - ('http.followRedirects', 'false'), - ('protocol.allow', 'never'), - ('protocol.https.allow', 'always'), - ('protocol.ssh.allow', 'always'), - ] - if os.environ.get('INFRABOX_GENERAL_DONT_CHECK_CERTIFICATES') == 'true': - config.append(('http.sslVerify', 'false')) - env['GIT_CONFIG_COUNT'] = str(len(config)) - for index, (key, value) in enumerate(config): - env['GIT_CONFIG_KEY_%s' % index] = key - env['GIT_CONFIG_VALUE_%s' % index] = value - return env - - -def main(): - # Git invokes helpers for get/store/erase; never persist credentials. - if len(sys.argv) != 2 or sys.argv[1] != 'get': - return - fields = dict(line.rstrip('\n').split('=', 1) for line in sys.stdin if '=' in line) - path = repository_path(fields.get('path', '')) - if (fields.get('protocol') == 'https' - and fields.get('host', '').lower() == os.environ['INFRABOX_GIT_HOST'] - and path in json.loads(os.environ['INFRABOX_GIT_ALLOWED_PATHS'])): - token = os.environ.get('INFRABOX_GIT_TOKEN') - if token and '\n' not in token and '\r' not in token: - print('username=%s\npassword=x-oauth-basic\n' % token) - - -if __name__ == '__main__': - main() diff --git a/src/job/infrabox_job/git_ssh.py b/src/job/infrabox_job/git_ssh.py new file mode 100644 index 000000000..85ca94696 --- /dev/null +++ b/src/job/infrabox_job/git_ssh.py @@ -0,0 +1,58 @@ +"""SSH transport for GitHub checkout, including HTTPS submodule URLs.""" +import os +import subprocess +from urllib.parse import urlsplit + + +def github_ssh_url(url, host): + parsed = urlsplit(url) + if (host and parsed.scheme in ('http', 'https') + and parsed.hostname and parsed.hostname.lower() == host.lower()): + return 'git@%s:%s' % (host, parsed.path.lstrip('/')) + return url + + +def git_environment(host): + env = os.environ.copy() + for name in ('GIT_CONFIG_PARAMETERS', 'INFRABOX_GIT_TOKEN', + 'INFRABOX_GIT_HOST', 'INFRABOX_GIT_ALLOWED_PATHS'): + env.pop(name, None) + env.update(GIT_TERMINAL_PROMPT='0', GIT_ASKPASS='/bin/false', SSH_ASKPASS='/bin/false') + config = [ + ('credential.helper', ''), + ('http.followRedirects', 'false'), + ('protocol.allow', 'never'), + ('protocol.http.allow', 'always'), + ('protocol.https.allow', 'always'), + ('protocol.ssh.allow', 'always'), + ] + if host: + for scheme in ('https', 'http'): + config.append(('url.ssh://git@%s/.insteadOf' % host, '%s://%s/' % (scheme, host))) + if os.environ.get('INFRABOX_GENERAL_DONT_CHECK_CERTIFICATES') == 'true': + config.append(('http.sslVerify', 'false')) + env['GIT_CONFIG_COUNT'] = str(len(config)) + for index, (key, value) in enumerate(config): + env['GIT_CONFIG_KEY_%s' % index] = key + env['GIT_CONFIG_VALUE_%s' % index] = value + return env + + +def configure_submodule_urls(directory, host, env): + """Normalize actual URLs too: Git's insteadOf matching is case-sensitive.""" + if not host or not os.path.isfile(os.path.join(directory, '.gitmodules')): + return + result = subprocess.run( + ['git', 'config', '--file', '.gitmodules', '--null', '--get-regexp', r'^submodule\..*\.url$'], + cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + if result.returncode == 1: + return # No submodule URLs. + if result.returncode: + raise RuntimeError('Could not read submodule URLs') + for record in result.stdout.split('\0'): + if not record: + continue + name, url = record.split('\n', 1) + ssh_url = github_ssh_url(url, host) + if ssh_url != url: + subprocess.check_call(['git', 'config', '--local', name, ssh_url], cwd=directory, env=env) diff --git a/src/job/job.py b/src/job/job.py index b5b8b2446..b407cdfb2 100755 --- a/src/job/job.py +++ b/src/job/job.py @@ -23,7 +23,7 @@ from infrabox_job.stats import StatsCollector from infrabox_job.process import ApiConsole, Failure, Error from infrabox_job.job import Job -from infrabox_job.git_credentials import github_url, git_environment +from infrabox_job.git_ssh import github_ssh_url, git_environment, configure_submodule_urls from infrabox_job import find_infrabox_file from pyinfraboxutils.testresult import Parser as TestresultParser @@ -160,31 +160,15 @@ def get_files_in_dir(self, d, ending=None): return result - def clone_repo(self, commit, clone_url, branch, ref, full_history, sub_path=None, submodules=True, token=None): + def clone_repo(self, commit, clone_url, branch, ref, full_history, sub_path=None, submodules=True): c = self.console mount_repo_dir = self.mount_repo_dir if sub_path: mount_repo_dir = os.path.join(mount_repo_dir, sub_path) - https_url = github_url(clone_url, self.github_host) - git_env = (dict(os.environ, GIT_SSL_NO_VERIFY='true') - if os.environ['INFRABOX_GENERAL_DONT_CHECK_CERTIFICATES'] == 'true' else None) - ssh_env = git_env - ssh_fallback = None - if https_url and token: - if clone_url != https_url: - ssh_fallback = clone_url - clone_url = https_url - # Only deployment administrators can extend the checkout allowlist. - repositories = json.loads(os.environ.get('GITHUB_TOKEN_REPOSITORIES', '[]')) - repositories = [self.repository.get('clone_url')] + repositories - git_env = git_environment(self.github_host, token, repositories) - - # Never remove an existing checkout when retrying with the SSH key. - if ssh_fallback and os.path.lexists(mount_repo_dir): - if os.path.islink(mount_repo_dir) or not os.path.isdir(mount_repo_dir) or os.listdir(mount_repo_dir): - ssh_fallback = None + clone_url = github_ssh_url(clone_url, self.github_host) + git_env = git_environment(self.github_host) cmd = ['git', 'clone'] @@ -195,18 +179,7 @@ def clone_repo(self, commit, clone_url, branch, ref, full_history, sub_path=None cmd += ['--single-branch', '-b', branch] cmd += [clone_url, mount_repo_dir] - try: - c.execute(cmd, show=True, retry=ssh_fallback is None, env=git_env) - except Exception: - if not ssh_fallback: - raise - c.collect('HTTPS clone with GitHub token failed, retrying with SSH key', show=True) - if os.path.isdir(mount_repo_dir): - shutil.rmtree(mount_repo_dir) - clone_url = ssh_fallback - git_env = ssh_env - cmd[-2] = clone_url - c.execute(cmd, show=True, retry=True, env=git_env) + c.execute(cmd, show=True, retry=True, env=git_env) if ref: cmd = ['git', 'fetch'] @@ -233,6 +206,7 @@ def clone_repo(self, commit, clone_url, branch, ref, full_history, sub_path=None c.execute(cmd, cwd=mount_repo_dir, show=True, env=git_env) if submodules: + configure_submodule_urls(mount_repo_dir, self.github_host, git_env) c.execute(['git', 'submodule', 'init', '-q'], cwd=mount_repo_dir, show=True, retry=True, env=git_env) c.execute(['git', 'submodule', 'update', '-q'], cwd=mount_repo_dir, show=True, retry=True, env=git_env) @@ -255,7 +229,6 @@ def get_source(self): repo_clone = def_repo.get('clone', True) repo_submodules = def_repo.get('submodules', True) full_history = def_repo.get('full_history', None) - github_token = self.repository.get('github_api_token', None) if full_history is None: full_history = repo.get('full_history', False) @@ -264,7 +237,7 @@ def get_source(self): if not repo_clone: return - self.clone_repo(commit, clone_url, branch, ref, full_history, submodules=repo_submodules, token=github_token) + self.clone_repo(commit, clone_url, branch, ref, full_history, submodules=repo_submodules) elif self.project['type'] == 'upload': c.collect("Downloading Source") storage_source_zip = os.path.join(self.storage_dir, 'source.zip') @@ -336,10 +309,7 @@ def config_github(self): if token: self.console.collect("GITHUB_OAUTH_TOKEN=********", show=True) - github_url = "https://" + token + ':x-oauth-basic@' + self.github_host - self.console.collect("GITHUB_BASE_URL=" + github_url.replace(token, '********'), show=True) - else: - self.console.collect("GITHUB_BASE_URL=" + github_url, show=True) + self.console.collect("GITHUB_BASE_URL=" + github_url, show=True) if token: self.environment['GITHUB_OAUTH_TOKEN'] = token @@ -1271,8 +1241,8 @@ def get_job_list(self, data, c, repo, parent_name="", continue if job['type'] == "git": - c.header("Clone repo %s" % job['clone_url'], show=True) clone_url = job['clone_url'] + c.header("Clone repo %s" % github_ssh_url(clone_url, self.github_host), show=True) branch = job.get("branch", None) sub_path = os.path.join('.infrabox', 'tmp', job_name) @@ -1280,9 +1250,7 @@ def get_job_list(self, data, c, repo, parent_name="", c.execute(['rm', '-rf', new_repo_path]) os.makedirs(new_repo_path) - github_token = self.repository.get('github_api_token', None) - - self.clone_repo(job['commit'], clone_url, branch, None, True, sub_path, token=github_token) + self.clone_repo(job['commit'], clone_url, branch, None, True, sub_path) c.header("Parsing infrabox file", show=True) ib_file = job.get('infrabox_file', None)