Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions deploy/infrabox/templates/_helpers.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}

Expand Down
4 changes: 0 additions & 4 deletions deploy/infrabox/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 14 additions & 22 deletions docs/install/configure/github.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
6 changes: 5 additions & 1 deletion docs/job/git.md
Original file line number Diff line number Diff line change
Expand Up @@ -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": { ... },
Expand All @@ -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.
151 changes: 79 additions & 72 deletions infrabox/test/job/test_clone_auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import inspect
import os
import tempfile
import unittest
Expand All @@ -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'
Expand All @@ -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()
Expand All @@ -37,114 +37,121 @@ 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'}):
self.runner.config_github()
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()
Loading
Loading