diff --git a/docs/cli-fresh-host.md b/docs/cli-fresh-host.md index bb86322b..bf120d1e 100644 --- a/docs/cli-fresh-host.md +++ b/docs/cli-fresh-host.md @@ -155,8 +155,7 @@ Example intent: {"name": "OWNER/REPO", "merge_policy": "human", "allow_workflow_edits": false} ], "providers": [{"id": "codex", "kind": "browser"}], - "smoke_target": "scratch", - "codex_parallel_auth": true + "smoke_target": "scratch" } ``` diff --git a/docs/factory-runtime-reference.md b/docs/factory-runtime-reference.md index e74c0463..3865ca00 100644 --- a/docs/factory-runtime-reference.md +++ b/docs/factory-runtime-reference.md @@ -131,9 +131,9 @@ are serialized per reference and saved using compare-and-swap before teardown; API-key and long-lived-token jobs retain full configured concurrency. Refreshed credentials never replace a newer manual login or mutate an external imported login file. -Set `codex_parallel_auth: true` in runtime settings (`runtime.json` domain) to share an existing ChatGPT -subscription across Codex workers. The controller gives each worker an access-only -`chatgptAuthTokens` snapshot, without the refresh token. It checks that the access +Codex workers share an existing ChatGPT subscription in parallel. The controller +gives each worker an access-only `chatgptAuthTokens` snapshot; the refresh token +never enters a worker container. It checks that the access token lasts beyond the job deadline plus five minutes. When needed, the pinned Codex app-server renews the login under the installation credential lock, in a bounded container with no repository, no model turn, and a private durable auth diff --git a/docs/installation.md b/docs/installation.md index e89f0fb9..e8d5efe9 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -296,9 +296,8 @@ watching after 15 minutes without cancelling the saved operation. Refreshable account logins have one active writer per credential reference. Forge saves refreshed credentials before removing the runner and refuses stale writes after a newer login. API-key and long-lived-token jobs can use the full configured -parallel capacity. For parallel Codex jobs with an existing ChatGPT subscription, -set `codex_parallel_auth: true` in `runtime.json` and run a scoped Codex setup -check. The controller owns refresh; workers get access-only snapshots. See the +parallel capacity, and so can Codex jobs on an existing ChatGPT subscription: the +controller owns refresh, and workers get access-only snapshots. See the [runtime guide](factory-runtime.md) for lifecycle and recovery details. Losing a refresh during a crash can still require another login; cleanup and other available harnesses continue independently. diff --git a/docs/operator-sign-in.md b/docs/operator-sign-in.md index 0b830d90..70ee5284 100644 --- a/docs/operator-sign-in.md +++ b/docs/operator-sign-in.md @@ -11,7 +11,8 @@ Forge App, uses that App for GitHub sign-in fallback, and links the installing operator's observed Tailscale identity to their authorized GitHub ID. In Tailscale mode, the UI accepts identity only through its trusted local Serve -proxy. The API checks the UI's upstream secret and the stored operator link; +proxy: the loopback connection must be owned by root, as `tailscaled` is, so +another local account cannot present the identity header. The API checks the UI's upstream secret and the stored operator link; client-supplied identity headers and tagged devices do not authorize an operator. GitHub sign-in remains available when the Tailscale identity is absent or unlinked. The service account and local proxy remain trusted administrative boundaries. diff --git a/forge/factory/config.py b/forge/factory/config.py index 7ab6c5e3..1de4f320 100644 --- a/forge/factory/config.py +++ b/forge/factory/config.py @@ -40,7 +40,6 @@ # Issue conversations only: a faster model per provider, e.g. {"claude": "claude-haiku-4-5"}. # Null keeps each pool entry's own model. Pipeline roles never use it. 'discussion_model': None, - 'codex_parallel_auth': False, 'ready_label': 'ready', 'hold_labels': ['hold', 'blocked'], 'merge_method': 'squash', } @@ -53,7 +52,14 @@ def validate(value): return _validate(value, manifests()) +# Retired: Codex workers always receive an access-only snapshot. Stored +# settings and launch snapshots may still carry it. +RETIRED = ('codex_parallel_auth',) + + def _validate(value, installed): + if isinstance(value, dict): + value = {key: item for key, item in value.items() if key not in RETIRED} if not isinstance(value, dict) or set(value) - set(DEFAULT): raise ValueError('Unknown runtime settings') config = deepcopy({**DEFAULT, **value}) @@ -85,7 +91,7 @@ def _validate(value, installed): if config['provider_ready'] is not None and (not isinstance(config['provider_ready'], list) or any(not isinstance(v, str) or v not in ids for v in config['provider_ready'])): raise ValueError('Verified provider entries must belong to the configured pool') - for key in ('enabled', 'merge_enabled', 'human_required', 'codex_parallel_auth'): + for key in ('enabled', 'merge_enabled', 'human_required'): if type(config[key]) is not bool: raise ValueError(key + ' must be boolean') for key, low, high in [('cycle_budget_seconds', 15, 300), ('cycle_seconds', 5, 3600), ('grace_seconds', 1, 60), diff --git a/forge/factory/runner.py b/forge/factory/runner.py index c0e6138c..b245047c 100644 --- a/forge/factory/runner.py +++ b/forge/factory/runner.py @@ -75,6 +75,8 @@ def scrub(text, secrets=()): text = re.sub(r'\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{16,})\b', '[REDACTED]', text) # Login files carry OAuth access/refresh tokens as JWTs. text = re.sub(r'\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b', '[REDACTED]', text) + # Refresh tokens are often opaque; redact any value labelled as one. + text = re.sub(r'''(refresh[_-]?token\\?["']?\s*[:=]\s*\\?["']?)[^\s"'\\,;&}]+''', r'\1[REDACTED]', text, flags=re.IGNORECASE) return text @@ -411,14 +413,17 @@ def _prepare_credentials(self, job, *, bundles=()): raise RunnerUnavailable('Provider authentication file is unavailable') try: raw = auth_path.read_bytes() - credentials['FORGE_HARNESS_AUTH'] = json.loads(raw) - if self.config.get('provider', 'codex') == 'codex' and self.config.get('codex_parallel_auth'): + if self.config.get('provider', 'codex') == 'codex': + # Workers run untrusted repository code: they receive access + # that outlives their deadline, never the refresh token. from .codex_auth import snapshot, renew_in_container root = self.environ.get('FORGE_CREDENTIAL_ROOT') if not root: - raise ValueError('Shared login must be installation-owned') + raise ValueError('Codex login must be installation-owned') credentials['FORGE_HARNESS_AUTH'] = snapshot(root, auth_ref, job['deadline'], lambda directory, **kwargs: renew_in_container(self, directory, **kwargs)) + else: + credentials['FORGE_HARNESS_AUTH'] = json.loads(raw) credentials['FORGE_AUTH_DIGEST'] = hashlib.sha256(raw).hexdigest() except (RunnerError, OSError, ValueError, KeyError): raise RunnerUnavailable('Provider authentication file could not be loaded or renewed') from None @@ -452,9 +457,6 @@ def _send_credentials(self, job, current, credentials, *, bundles=()): self.call(['cp', '-a', '-', current['id'] + ':/work/'], input=content.getvalue()) def refresh_auth(self, current): - if self.config.get('provider', 'codex') == 'codex' and self.config.get('codex_parallel_auth'): - # Access-only workers cannot write back into the managed login. - return 'controller_managed' ref, root = self.config.get('provider_auth_file_env'), self.environ.get('FORGE_CREDENTIAL_ROOT') if not ref or not root: return 'not_managed' @@ -475,8 +477,9 @@ def read(path): if self.config.get('provider', 'codex') == 'codex': from .codex_auth import renewable if renewable(json.loads(value)): - # An access-only worker copy (e.g. launched while parallel auth was on) - # must never replace the managed login it was cut from. + # A worker's access-only copy must never replace the managed + # login it was cut from. Only a full login, from a worker + # launched before snapshots were the only path, is saved. return 'access_only' return 'saved' if Credentials(root).refresh(ref, expected, value) else 'superseded' except (RunnerError, OSError, ValueError, tarfile.TarError, UnicodeError): diff --git a/forge/installation_apps.py b/forge/installation_apps.py index 3559b16a..8664dcb4 100644 --- a/forge/installation_apps.py +++ b/forge/installation_apps.py @@ -34,14 +34,16 @@ def call(self, action, binding, **parameters): from .operator_auth import configuration from .app_access import missing_app_permissions from .sqlite_identity import identity_effect_lock - fields(binding, ('setup_id', 'owner', 'operators', 'origin', 'codex_parallel_auth', 'workflow_edits', 'repositories')) + # Older clients still send the retired `codex_parallel_auth` choice. + binding = {key: value for key, value in binding.items() if key != 'codex_parallel_auth'} if isinstance(binding, dict) else binding + fields(binding, ('setup_id', 'owner', 'operators', 'origin', 'workflow_edits', 'repositories')) require(isinstance(binding['setup_id'], str) and re.fullmatch('[a-f0-9]{32}', binding['setup_id'])) fields(binding['owner'], ('id', 'login', 'type')) owner = binding['owner'] require(type(owner['id']) is int and owner['id'] > 0 and owner['type'] in ('User', 'Organization') and isinstance(owner['login'], str) and re.fullmatch('[A-Za-z0-9-]{1,39}', owner['login'])) configuration(binding['origin'], 'validation', 'a' * 40, binding['operators']) - require(type(binding['codex_parallel_auth']) is bool and type(binding['workflow_edits']) is bool) + require(type(binding['workflow_edits']) is bool) require(isinstance(binding['repositories'], list) and 1 <= len(binding['repositories']) <= 25) from forge_client.contracts import repository for target in binding['repositories']: repository(target) @@ -121,9 +123,6 @@ def call(self, action, binding, **parameters): current.pop('challenge', None) current.update(checks={}, error=None) self.identity(binding) - runtime = self.setup.runtime() - runtime['codex_parallel_auth'] = binding['codex_parallel_auth'] - self.setup.save_runtime(runtime, active=False) if action == 'refresh': fields(parameters, ()) self.identity(binding) diff --git a/forge/store/executions.py b/forge/store/executions.py index 2d7bd800..1cff65b9 100644 --- a/forge/store/executions.py +++ b/forge/store/executions.py @@ -73,7 +73,10 @@ def provider_available(db, provider, provider_id, config, now): return False if not reference: return True - parallel = provider == 'codex' and config.get('codex_parallel_auth') is True + # Codex workers hold access-only snapshots and the controller alone + # refreshes, so they share an account; other refreshable logins do not. + def shared(other_provider): + return provider == 'codex' and other_provider == 'codex' # Every execution domain pins the credential reference before launching. # A legacy unknown lease remains fail closed until verified teardown. for lease_table, runtime_table in (('discussion_leases','discussion_runtime'), ('auxiliary_leases','auxiliary_runtime')): @@ -85,15 +88,13 @@ def provider_available(db, provider, provider_id, config, now): if row[0] is None: return False other = json.loads(row[0]).get('runner_config') or {} - if other.get('provider_auth_file_env') == reference and ( - not parallel or other.get('provider') != 'codex' or other.get('codex_parallel_auth') is not True): + if other.get('provider_auth_file_env') == reference and not shared(other.get('provider')): return False - rows = db.execute('SELECT l.provider,l.runner_config_json FROM job_launches l ' + rows = db.execute('SELECT l.provider FROM job_launches l ' 'JOIN jobs j ON j.id=l.job_id WHERE j.cleanup=0 ' "AND json_extract(l.runner_config_json,'$.provider_auth_file_env')=?", (reference,)) for row in rows: - other = json.loads(row['runner_config_json']) - if not parallel or row['provider'] != 'codex' or other.get('codex_parallel_auth') is not True: + if not shared(row['provider']): return False return True diff --git a/forge_client/install_consent.py b/forge_client/install_consent.py index b9297067..4617d856 100644 --- a/forge_client/install_consent.py +++ b/forge_client/install_consent.py @@ -57,7 +57,6 @@ def __init__(self, installation, selected, *, github, journal=None, convert_app= 'Sign in locally with one of the installation operators.') self.binding = {'setup_id': self.host_state['intent']['id'], 'owner': selected['owner'], 'operators': sorted({row['id'] for row in selected['operators']}), 'origin': self.host_state['origin'], - 'codex_parallel_auth': selected['codex_parallel_auth'], 'workflow_edits': any(row['allow_workflow_edits'] for row in selected['repositories']), 'repositories': [{'id': row['id'], 'name': row['name']} for row in (repositories if repositories is not None else [row['target'] for row in selected['repositories']])]} diff --git a/forge_client/install_interview.py b/forge_client/install_interview.py index 643c330b..7766467a 100644 --- a/forge_client/install_interview.py +++ b/forge_client/install_interview.py @@ -143,7 +143,7 @@ def interview(ssh, github, *, ask=input, tell=None): value = {'version': 1, 'ssh': ssh, 'name': name, 'revision': None, 'host_key': fingerprint, 'hostname': re.sub('[^a-z0-9-]+', '-', name.lower()).strip('-')[:63], 'owner': owner, 'operators': [actor['login']], 'repositories': rows, 'providers': [account], - 'smoke_target': 'scratch', 'codex_parallel_auth': True} + 'smoke_target': 'scratch'} while True: summary(value, tell) selected = choice('Enter to check this plan, or choose a field to edit: ', diff --git a/forge_client/installation.py b/forge_client/installation.py index 2d0c233b..bae53295 100644 --- a/forge_client/installation.py +++ b/forge_client/installation.py @@ -21,14 +21,16 @@ def intent(value, github): value = deepcopy(value) smoke_issue = value.pop('smoke_issue', None) + # Retired: Codex workers always receive access-only snapshots. + value.pop('codex_parallel_auth', None) fields(value, ('version', 'ssh', 'name', 'revision', 'host_key', 'hostname', 'owner', 'operators', - 'repositories', 'providers', 'smoke_target', 'codex_parallel_auth', + 'repositories', 'providers', 'smoke_target', *(['rules_repair'] if 'rules_repair' in value else []))) require(value['version'] == 1 and isinstance(value['ssh'], str), 'invalid_intent') require(isinstance(value['name'], str) and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}', value['name']), 'invalid_intent') require(value['host_key'] is None or isinstance(value['host_key'], str) and re.fullmatch(r'SHA256:[A-Za-z0-9+/]{43}', value['host_key']), 'invalid_host_key') require(isinstance(value['hostname'], str) and re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', value['hostname']), 'invalid_hostname') - require(value.get('rules_repair') in (None, 'apply-if-admin', 'print-commands', 'skip') and type(value['codex_parallel_auth']) is bool, 'invalid_intent') + require(value.get('rules_repair') in (None, 'apply-if-admin', 'print-commands', 'skip'), 'invalid_intent') require(isinstance(value['operators'], list) and 1 <= len(value['operators']) <= 20, 'invalid_intent') require(isinstance(value['repositories'], list) and 1 <= len(value['repositories']) <= 20, 'invalid_intent') require(isinstance(value['providers'], list) and 1 <= len(value['providers']) <= 3, 'invalid_intent') @@ -657,7 +659,7 @@ def schemas(): 'intent_schema': { 'type': 'object', 'additionalProperties': False, 'required': ['version', 'ssh', 'name', 'revision', 'host_key', 'hostname', 'owner', 'operators', - 'repositories', 'providers', 'smoke_target', 'codex_parallel_auth'], + 'repositories', 'providers', 'smoke_target'], 'properties': { 'version': {'const': 1}, 'ssh': {'type': 'string'}, 'name': {'type': 'string'}, 'revision': {'type': ['string', 'null'], 'description': 'Exact commit, or null to resolve the latest prepared release once'}, @@ -674,8 +676,7 @@ def schemas(): 'properties': {'id': {'enum': ['codex', 'claude', 'grok']}, 'kind': {'enum': ['browser', 'api_key', 'token']}}}}, 'smoke_target': {'type': 'string', 'description': 'scratch or a selected OWNER/REPO'}, - 'smoke_issue': {'type': ['integer', 'null'], 'minimum': 1, 'description': 'Optional existing issue in the selected smoke repo; omitted creates a smoke issue'}, - 'codex_parallel_auth': {'type': 'boolean', 'description': 'Allow parallel jobs with the host-managed Codex login'} + 'smoke_issue': {'type': ['integer', 'null'], 'minimum': 1, 'description': 'Optional existing issue in the selected smoke repo; omitted creates a smoke issue'} }}, 'wait': 'Use --json --wait SECONDS to follow server work through handover. Human output returns the web destination after bootstrap. Resume retains the original installation and first-merge timer.', 'secrets': 'Never accepted in the intent. Use forge account login with hidden input or private stdin.'} diff --git a/tests/test_codex_parallel_auth.py b/tests/test_codex_parallel_auth.py index d1ac9a89..a39e0b7d 100644 --- a/tests/test_codex_parallel_auth.py +++ b/tests/test_codex_parallel_auth.py @@ -11,7 +11,7 @@ from forge.credentials import Credentials from forge.factory.codex_auth import snapshot, expires_at, renew_in_container, renewable from forge.factory.config import validate -from forge.factory.runner import ContainerRunner +from forge.factory.runner import ContainerRunner, scrub from forge.settings import write_json @@ -83,8 +83,8 @@ def crash(directory, *, reconcile): self.assertEqual(self.current()['tokens']['refresh_token'], 'rotated-refresh') def test_runner_only_delivers_access_snapshot_to_worker(self): - config = validate({'provider_auth_file_env': REF, 'provider_environment': [], - 'codex_parallel_auth': True}) + # The default configuration: a single Codex run gets the same snapshot. + config = validate({'provider_auth_file_env': REF, 'provider_environment': []}) runner = ContainerRunner(config, environ=self.credentials.environment()) runner.inspect = Mock(return_value={'status': 'created', 'id': 'worker'}) runner.call = Mock() @@ -98,6 +98,18 @@ def test_runner_only_delivers_access_snapshot_to_worker(self): self.assertEqual(delivered['FORGE_HARNESS_AUTH']['tokens']['refresh_token'], '') self.assertNotIn('GH_TOKEN', delivered) self.assertNotIn(b'synthetic-refresh', raw) + self.assertNotIn('synthetic-refresh', json.dumps(runner.call.call_args_list, default=str)) + + def test_retired_parallel_setting_is_accepted_and_ignored(self): + for value in (True, False): + self.assertNotIn('codex_parallel_auth', validate({'codex_parallel_auth': value})) + + def test_scrub_redacts_labelled_refresh_tokens(self): + for text in ('{"refresh_token": "opaque-refresh-value"}', 'refresh_token=opaque-refresh-value&x=1', + '"refreshToken":"opaque-refresh-value"', '{\\"refresh_token\\": \\"opaque-refresh-value\\"}'): + scrubbed = scrub(text) + self.assertNotIn('opaque-refresh-value', scrubbed, text) + self.assertIn('[REDACTED]', scrubbed) def test_reconnect_does_not_restore_old_staged_credentials(self): def crash(directory, *, reconcile): @@ -124,14 +136,9 @@ def test_invalid_expiry_is_never_dispatched(self): self.credentials.put(REF, json.dumps(value), file=True) with self.assertRaises(ValueError): snapshot(self.root, REF, 5000, Mock()) - def test_access_only_workers_never_persist_back_into_login(self): - runner = ContainerRunner(validate({'codex_parallel_auth': True})) - runner.call = Mock(side_effect=AssertionError('must not read worker auth')) - self.assertEqual(runner.refresh_auth({'id': 'worker'}), 'controller_managed') - def test_an_access_only_copy_never_replaces_the_managed_login(self): - # Live incident: parallel auth was switched off while access-only workers ran; - # their copy was saved back and the login could no longer renew. + # Live incident: an access-only copy was saved back and the login + # could no longer renew. import hashlib stored = Path(self.credentials.environment()[REF]).read_bytes() copy = {'auth_mode': 'chatgptAuthTokens', 'tokens': {**login()['tokens'], 'refresh_token': ''}} diff --git a/tests/test_deployments.py b/tests/test_deployments.py index 115ed9a1..1375a1f6 100644 --- a/tests/test_deployments.py +++ b/tests/test_deployments.py @@ -159,7 +159,8 @@ def browser_pool(self): 'provider_ready': ['codex-browser'], 'provider_pool': [ {'id': 'unverified', 'provider': 'codex', 'model': 'ignored', 'provider_environment': ['OPENAI_API_KEY'], 'provider_auth_file_env': None}, - {'id': 'codex-browser', 'provider': 'codex', 'model': 'selected-model', + # Leasing is exclusive for a refreshable non-Codex login. + {'id': 'codex-browser', 'provider': 'claude', 'model': 'selected-model', 'provider_environment': [], 'provider_auth_file_env': 'FORGE_SETUP_CODEX_AUTH'}]} def test_deployment_pins_verified_browser_pool_account_instead_of_default_api_key(self): @@ -596,8 +597,8 @@ def test_a_malformed_workflows_listing_is_recorded_without_its_detail(self): self.assertEqual(self.entry()['error'], 'The repository workflows could not be read') self.assertFalse(self.engine) - def pipeline_job(self, reference, number=3): - """A pipeline worker holding a capacity lease with this coding account.""" + def pipeline_job(self, reference, number=3, provider='claude'): + """A pipeline worker holding a capacity lease with this refreshable coding account.""" with self.database.write() as db: unit_id = unit(db, 7, number, state='building') db.execute("INSERT INTO attempts(id,unit_id,membership_generation,assignment_generation,input_manifest_json,budget_generation,created_at) " @@ -607,8 +608,8 @@ def pipeline_job(self, reference, number=3): (job, unit_id, 'attempt-' + unit_id)) db.execute('INSERT INTO job_leases VALUES(?,?,?,100)', ('build-' + unit_id, job, 'fence-' + job)) db.execute("INSERT INTO job_launches(job_id,slot,execution_fence,branch,publisher,provider,runner_config_json,policy_json,context_json,deadline) " - "VALUES(?,?,?,'forge/work','forge-build[bot]','codex',?,'{}','{}',700)", - (job, 'build-' + unit_id, 'fence-' + job, json.dumps({'provider_auth_file_env': reference}))) + "VALUES(?,?,?,'forge/work','forge-build[bot]',?,?,'{}','{}',700)", + (job, 'build-' + unit_id, 'fence-' + job, provider, json.dumps({'provider_auth_file_env': reference}))) return job def release(self, job): @@ -618,7 +619,7 @@ def release(self, job): db.execute('DELETE FROM job_leases WHERE job_id=?', (job,)) def test_a_rotating_coding_account_is_never_shared_with_a_pipeline_worker(self): - self.config['provider_auth_file_env'] = 'FORGE_HARNESS_AUTH_ONE' + self.config.update(provider='claude', provider_auth_file_env='FORGE_HARNESS_AUTH_ONE') job = self.pipeline_job('FORGE_HARNESS_AUTH_ONE') self.deployments().tick(self.config) self.assertFalse(self.engine) @@ -635,6 +636,12 @@ def test_another_coding_account_is_not_held_by_the_pipeline_worker(self): self.deployments().tick(self.config) self.assertEqual(self.entry()['status'], 'running') + def test_codex_access_snapshots_share_an_account_with_a_pipeline_worker(self): + self.config['provider_auth_file_env'] = 'FORGE_HARNESS_AUTH_ONE' + self.pipeline_job('FORGE_HARNESS_AUTH_ONE', provider='codex') + self.deployments().tick(self.config) + self.assertEqual(self.entry()['status'], 'running') + def test_discussion_leases_hold_only_their_own_account_or_unknown_identity(self): with self.database.write() as db: db.execute("INSERT INTO discussions(id,title,created_at,updated_at) VALUES('discussion','Question',100,100)") @@ -657,7 +664,7 @@ def test_an_api_key_configuration_needs_no_lease(self): def test_a_running_strategist_holds_its_own_coding_account(self): # The strategist's own auxiliary lease carries the account, so a second # deployments store sees it as held until the execution is cleaned. - self.config['provider_auth_file_env'] = 'FORGE_HARNESS_AUTH_ONE' + self.config.update(provider='claude', provider_auth_file_env='FORGE_HARNESS_AUTH_ONE') self.deployments().tick(self.config) self.assertIsNone(self.available_account(self.config)) self.finish() diff --git a/tests/test_install_consent.py b/tests/test_install_consent.py index 11de019a..5446bcff 100644 --- a/tests/test_install_consent.py +++ b/tests/test_install_consent.py @@ -58,7 +58,7 @@ def request(method, path, token, *args): self.host.rpc.side_effect = lambda program, request, **kw: {'ok': True, 'result': self.server.call(request['setup'])} self.installation = SimpleNamespace(journal=self.local, host=self.host, ssh='anvil') self.selected = {'owner': self.owner, 'operators': [{'id': 7, 'login': 'operator'}], - 'codex_parallel_auth': True, 'repositories': [{'target': self.discovered[0], 'allow_workflow_edits': False}]} + 'repositories': [{'target': self.discovered[0], 'allow_workflow_edits': False}]} self.vault = Vault() self.events = [] self.client = self.make_client() @@ -84,7 +84,6 @@ def test_bootstrap_without_identity_then_installed_repo_observation(self): config = OperatorAuth(self.root).config() self.assertEqual(config['operators'], [7]) self.assertEqual(config['client_id'], self.app['client_id']) - self.assertTrue(self.setup.runtime()['codex_parallel_auth']) self.assertFalse(self.setup.runtime()['enabled']) self.installed = True result = self.client.apply() diff --git a/tests/test_store_discussions.py b/tests/test_store_discussions.py index 50d0a7bc..58e8a08d 100644 --- a/tests/test_store_discussions.py +++ b/tests/test_store_discussions.py @@ -235,7 +235,8 @@ def test_worker_result_identity_must_match_assignment(self): self.assertFalse(any(m['role']=='assistant' for m in self.service.view('1:2')['messages'])) def test_rotating_credentials_remain_leased_until_verified_cleanup(self): - self.config['provider_auth_file_env']='CODEX_ACCOUNT' + # Codex accounts are shared; a refreshable Claude login has one writer. + self.config.update(provider='claude',provider_auth_file_env='CLAUDE_ACCOUNT') job=self.start() with self.store.read_snapshot() as db: self.assertFalse(provider_available(db,self.config['provider'],None,self.config,self.now)) diff --git a/tests/test_store_dispatch_controller.py b/tests/test_store_dispatch_controller.py index 649139e5..1237a361 100644 --- a/tests/test_store_dispatch_controller.py +++ b/tests/test_store_dispatch_controller.py @@ -196,9 +196,10 @@ def test_scoped_gate_prevents_preparation_and_removing_hold_allows_dispatch(self self.assertTrue(self.controller.step('u')['reserved']) def test_provider_rotation_and_account_lease_survive_controller_restart(self): - self.config['provider_pool'] = [dict(id='first', provider='codex', model=None, + # A refreshable non-Codex login has one writer per account. + self.config['provider_pool'] = [dict(id='first', provider='claude', model=None, provider_environment=[], provider_auth_file_env='AUTH_ONE'), - dict(id='second', provider='codex', model='second-model', provider_environment=[], provider_auth_file_env='AUTH_TWO')] + dict(id='second', provider='claude', model='second-model', provider_environment=[], provider_auth_file_env='AUTH_TWO')] def prepare(snapshot, role): return PreparedDispatch(BASE, role + '[bot]', deepcopy(self.config)) first = self.driver(prepare).step('u') @@ -212,11 +213,11 @@ def prepare(snapshot, role): self.assertEqual(db.execute("SELECT cursor FROM runtime_controls WHERE name='provider_cursor'").fetchone()[0], '0') def test_transaction_rechecks_account_and_rolls_back_entire_reservation(self): - self.config['provider_auth_file_env'] = 'AUTH_ONE' + self.config.update(provider='claude', provider_auth_file_env='AUTH_ONE') self.prepare = GitHubPrepare(self.github, self.config) first = self.driver().step('u') added = self.admit('v', 2) - launch = replace(Launch('forge/issue-2', 'build[bot]', 'codex', 200, self.config, {})) + launch = replace(Launch('forge/issue-2', 'build[bot]', 'claude', 200, self.config, {})) with self.assertRaisesRegex(TransitionError, 'provider account'): self.life.reserve_job(self.command('v'), 'build', slot='build-2', execution_fence='fence-two', input_manifest={'requirements_revision_id': added['revision_id'], 'base_oid': BASE, 'policy_hash': 'policy'}, @@ -227,23 +228,13 @@ def test_transaction_rechecks_account_and_rolls_back_entire_reservation(self): self.assertEqual(db.execute('SELECT count(*) FROM job_leases').fetchone()[0], 1) self.assertEqual(self.job(first)['cleanup'], 0) - def test_codex_parallel_snapshots_drain_old_refresh_writer(self): + def test_codex_access_snapshots_share_one_account(self): self.config['provider_auth_file_env'] = 'AUTH_ONE' def prepare(snapshot, role): return PreparedDispatch(BASE, role + '[bot]', deepcopy(self.config)) - first = self.driver(prepare).step('u') + self.assertTrue(self.driver(prepare).step('u')['reserved']) self.admit('v', 2) - self.config['codex_parallel_auth'] = True - self.assertEqual(self.driver(prepare).step('v')['reason'], 'provider_unavailable') - job = self.job(first) - self.life.fence_execution(Command('fence', 'test', 'u', job['unit_version']), job['id'], execution_fence=job['execution_fence'], reason='test') - self.now += 1 - self.life.verify_cleanup(self.command(), job['id'], execution_fence=job['execution_fence'], - evidence={'process_stopped': True, 'resources_released': True}) - self.now += 30 self.assertTrue(self.driver(prepare).step('v')['reserved']) - self.admit('w', 3) - self.assertTrue(self.driver(prepare).step('w')['reserved']) def test_provider_cooldown_and_observation_fail_closed(self): with self.store.write() as db: diff --git a/ui/server/utils/proxy.ts b/ui/server/utils/proxy.ts index ee5ad1b5..3430ae2e 100644 --- a/ui/server/utils/proxy.ts +++ b/ui/server/utils/proxy.ts @@ -1,4 +1,6 @@ import type { IncomingMessage } from 'node:http' +import { readFileSync } from 'node:fs' +import { endianness } from 'node:os' import type { H3Event } from 'h3' export const MAX_ACTION_BODY = 262144 export const MAX_RESPONSE_BODY = 1024 * 1024 @@ -81,27 +83,54 @@ export function guardAction({ method, headers, contentLength, publicOrigin }: Gu // Tailscale Serve adds `Tailscale-User-Login` for a tailnet person (never for a // tagged device). It is an identity only when this process received it from -// Serve itself: Serve connects over loopback to the configured HTTPS name. -// Any other path, such as a direct request to the tailnet address, may carry a -// forged header, so nothing is forwarded. The status API trusts only -// `TAILSCALE_UPSTREAM_HEADER`, and `upstreamHeaders` never copies a client's. +// Serve itself: Serve connects over loopback to the configured HTTPS name, and +// on Linux tailscaled runs as root. Any local account can open a loopback +// connection and send the same header, so the connecting socket must also be +// owned by root, read from the kernel's own socket table. Any other path, such +// as a direct request to the tailnet address, may carry a forged header, so +// nothing is forwarded. The status API trusts only `TAILSCALE_UPSTREAM_HEADER`, +// and `upstreamHeaders` never copies a client's. export const TAILSCALE_UPSTREAM_HEADER = 'x-forge-tailscale-user-login' const TAILSCALE_LOGIN = /^[a-z0-9][a-z0-9._%+-]{0,63}@[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)*$/ -function loopback(address: string | undefined): boolean { +export interface PeerSocket { remoteAddress?: string; remotePort?: number; localAddress?: string; localPort?: number } + +// `/proc/net/tcp` prints an IPv4 address as its in-memory 32-bit word and the +// port in host order, both as uppercase hex. +function procEndpoint(address: string | undefined, port: number | undefined): string | undefined { const plain = (address ?? '').startsWith('::ffff:') ? (address ?? '').slice(7) : (address ?? '') - return plain === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(plain) + const parts = plain.split('.').map(Number) + if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return undefined + if (!Number.isInteger(port) || port! <= 0 || port! > 65535) return undefined + const word = endianness() === 'LE' ? parts.reverse() : parts + return (word.map(part => part.toString(16).padStart(2, '0')).join('') + ':' + port!.toString(16).padStart(4, '0')).toUpperCase() +} + +// The owning uid of the other end of a loopback IPv4 connection: its row has +// our peer as local address and us as remote address. Undefined when unknown. +export function loopbackPeerUid(socket: PeerSocket | undefined, read = (path: string) => readFileSync(path, 'utf8')): number | undefined { + const peer = procEndpoint(socket?.remoteAddress, socket?.remotePort) + const self = procEndpoint(socket?.localAddress, socket?.localPort) + if (!peer || !self || !/^127\./.test((socket?.remoteAddress ?? '').replace(/^::ffff:/, ''))) return undefined + let table: string + try { table = read('/proc/net/tcp') } catch { return undefined } + for (const line of table.split('\n').slice(1)) { + const field = line.trim().split(/\s+/) + if (field[1] === peer && field[2] === self && /^\d+$/.test(field[7] ?? '')) return Number(field[7]) + } + return undefined } -export function tailscaleIdentity(headers: Headers, remoteAddress: string | undefined, env: Record): string | undefined { +export function tailscaleIdentity(headers: Headers, socket: PeerSocket | undefined, env: Record, owner = loopbackPeerUid): string | undefined { if (env.NITRO_FORGE_TAILSCALE_IDENTITY !== 'serve') return undefined let origin: URL try { origin = new URL(env.NITRO_FORGE_PUBLIC_ORIGIN ?? '') } catch { return undefined } - if (origin.protocol !== 'https:' || origin.pathname !== '/' || !loopback(remoteAddress)) return undefined + if (origin.protocol !== 'https:' || origin.pathname !== '/') return undefined if ((headers.host ?? '').trim().toLowerCase() !== origin.host.toLowerCase()) return undefined // A repeated header arrives comma-joined; that is never one person. const value = (headers['tailscale-user-login'] ?? '').trim().toLowerCase() if (!value || value.includes(',') || value.startsWith('tagged-devices') || value.length > 320 || !TAILSCALE_LOGIN.test(value)) return undefined + if (owner(socket) !== 0) return undefined return value } @@ -114,7 +143,7 @@ export function requestTailscaleIdentity(event: H3Event, env = process.env): str const headers = Object.fromEntries(Object.entries(req.headers).map(([key, value]) => [key, Array.isArray(value) ? value.join(',') : value])) const inherited = (req as IncomingMessage & { __unenv__?: object }).__unenv__ - const login = tailscaleIdentity(headers, req.socket?.remoteAddress, env) + const login = tailscaleIdentity(headers, req.socket, env) ?? (inherited && requestIdentities.get(inherited)) if (login) requestIdentities.set(event.context, login) return login diff --git a/ui/tests/unit/proxy-lifecycle.test.ts b/ui/tests/unit/proxy-lifecycle.test.ts index 3681f18d..a379834d 100644 --- a/ui/tests/unit/proxy-lifecycle.test.ts +++ b/ui/tests/unit/proxy-lifecycle.test.ts @@ -4,6 +4,16 @@ import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' vi.mock('#app/nuxt', () => ({ useRuntimeConfig: () => ({ forgeApi: 'http://localhost:8788', forgeUpstreamSecretFile: '' }) })) vi.mock('#app/composables/ssr', () => ({ setResponseStatus: vi.fn() })) +const procTable = vi.hoisted(() => [ + ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode', + // Serve's root-owned loopback connection from port 40000 to the UI on 8787. + ' 0: 0100007F:9C40 0100007F:2253 01 00000000:00000000 00:00000000 00000000 0 0 13 1', +].join('\n')) +vi.mock('node:fs', async (original) => { + const fs = await original() + const readFileSync = ((path: unknown, ...rest: unknown[]) => path === '/proc/net/tcp' ? procTable : (fs.readFileSync as any)(path, ...rest)) as typeof fs.readFileSync + return { ...fs, default: { ...fs, readFileSync }, readFileSync } +}) async function middleware() { vi.stubGlobal('defineEventHandler', (handler: unknown) => handler) @@ -59,7 +69,7 @@ describe('proxy server-rendered identity', () => { const page = request() page.path = '/' Object.assign(page.node.req.headers, { host: 'anvil.example.ts.net', 'tailscale-user-login': 'operator@example.com' }) - Object.assign(page.node.req.socket, { remoteAddress: '127.0.0.1' }) + Object.assign(page.node.req.socket, { remoteAddress: '127.0.0.1', remotePort: 40000, localAddress: '127.0.0.1', localPort: 8787 }) vi.stubGlobal('fetch', vi.fn(async () => new Response('{}'))) await handler(page as any) expect(fetch).not.toHaveBeenCalled() diff --git a/ui/tests/unit/proxy.test.ts b/ui/tests/unit/proxy.test.ts index 52e74a59..3ec3f595 100644 --- a/ui/tests/unit/proxy.test.ts +++ b/ui/tests/unit/proxy.test.ts @@ -9,7 +9,7 @@ import { describe, it, expect } from 'vitest' import { PassThrough } from 'node:stream' import type { IncomingMessage } from 'node:http' -import { allowedHosts, guardAction, guardHost, proxyPaths, tailscaleIdentity, TAILSCALE_UPSTREAM_HEADER, upstreamHeaders, readUpstreamSecret, responseHeaders, readCapped, readRequestBody } from '../../server/utils/proxy' +import { allowedHosts, guardAction, guardHost, loopbackPeerUid, proxyPaths, tailscaleIdentity, TAILSCALE_UPSTREAM_HEADER, upstreamHeaders, readUpstreamSecret, responseHeaders, readCapped, readRequestBody } from '../../server/utils/proxy' const base = { method: 'POST', contentLength: 100, headers: { host: '100.64.0.7:8787', origin: 'http://100.64.0.7:8787', 'sec-fetch-site': 'same-origin', @@ -290,23 +290,44 @@ describe('bounded request bodies', () => { describe('Tailscale Serve operator identity', () => { const env = { NITRO_FORGE_TAILSCALE_IDENTITY: 'serve', NITRO_FORGE_PUBLIC_ORIGIN: 'https://forge.example.ts.net' } const serve = { host: 'forge.example.ts.net', 'tailscale-user-login': 'Alice@Example.com' } - it('trusts the login only on the loopback hop from Serve under the public name', () => { - expect(tailscaleIdentity(serve, '127.0.0.1', env)).toBe('alice@example.com') - expect(tailscaleIdentity(serve, '::ffff:127.0.0.1', env)).toBe('alice@example.com') - expect(tailscaleIdentity(serve, '::1', env)).toBe('alice@example.com') + const hop = { remoteAddress: '127.0.0.1', remotePort: 40000, localAddress: '127.0.0.1', localPort: 8787 } + const root = () => 0 + it('trusts the login only on a root-owned loopback hop from Serve under the public name', () => { + expect(tailscaleIdentity(serve, hop, env, root)).toBe('alice@example.com') + expect(tailscaleIdentity(serve, { ...hop, remoteAddress: '::ffff:127.0.0.1' }, env, root)).toBe('alice@example.com') + }) + it('refuses a forged header from another local account on the same loopback hop', () => { + expect(tailscaleIdentity(serve, hop, env, () => 1001)).toBeUndefined() + expect(tailscaleIdentity(serve, hop, env, () => undefined)).toBeUndefined() }) it('refuses a header sent straight to the tailnet address or under another name', () => { - expect(tailscaleIdentity(serve, '100.101.102.103', env)).toBeUndefined() - expect(tailscaleIdentity({ ...serve, host: '100.64.0.7:8787' }, '127.0.0.1', env)).toBeUndefined() + expect(tailscaleIdentity(serve, { ...hop, remoteAddress: '100.101.102.103' }, env)).toBeUndefined() + expect(tailscaleIdentity({ ...serve, host: '100.64.0.7:8787' }, hop, env, root)).toBeUndefined() }) it('is off unless identity mode and an HTTPS origin are configured', () => { - expect(tailscaleIdentity(serve, '127.0.0.1', {})).toBeUndefined() - expect(tailscaleIdentity(serve, '127.0.0.1', { ...env, NITRO_FORGE_TAILSCALE_IDENTITY: '1' })).toBeUndefined() - expect(tailscaleIdentity(serve, '127.0.0.1', { ...env, NITRO_FORGE_PUBLIC_ORIGIN: 'http://forge.example.ts.net' })).toBeUndefined() + expect(tailscaleIdentity(serve, hop, {}, root)).toBeUndefined() + expect(tailscaleIdentity(serve, hop, { ...env, NITRO_FORGE_TAILSCALE_IDENTITY: '1' }, root)).toBeUndefined() + expect(tailscaleIdentity(serve, hop, { ...env, NITRO_FORGE_PUBLIC_ORIGIN: 'http://forge.example.ts.net' }, root)).toBeUndefined() }) it('refuses tagged devices, repeated and malformed logins', () => { for (const login of ['tagged-devices', 'tagged-devices@example.ts.net', 'alice@example.com,mallory@example.com', 'alice', '', 'a b@example.com']) - expect(tailscaleIdentity({ ...serve, 'tailscale-user-login': login }, '127.0.0.1', env)).toBeUndefined() + expect(tailscaleIdentity({ ...serve, 'tailscale-user-login': login }, hop, env, root)).toBeUndefined() + }) + it('reads the connecting socket owner from the kernel socket table', () => { + // Little-endian hosts print 127.0.0.1 as 0100007F; ports 40000 and 8787 are 9C40 and 2253. + const table = [ + ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode', + ' 0: 0100007F:2253 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 11 1', + ' 1: 0100007F:2253 0100007F:9C40 01 00000000:00000000 00:00000000 00000000 1000 0 12 1', + ' 2: 0100007F:9C40 0100007F:2253 01 00000000:00000000 00:00000000 00000000 0 0 13 1', + ' 3: 0100007F:9C41 0100007F:2253 01 00000000:00000000 00:00000000 00000000 1001 0 14 1', + ].join('\n') + const read = (path: string) => { expect(path).toBe('/proc/net/tcp'); return table } + expect(loopbackPeerUid(hop, read)).toBe(0) + expect(loopbackPeerUid({ ...hop, remotePort: 40001 }, read)).toBe(1001) + expect(loopbackPeerUid({ ...hop, remotePort: 40002 }, read)).toBeUndefined() + expect(loopbackPeerUid({ ...hop, remoteAddress: '100.64.0.2' }, read)).toBeUndefined() + expect(loopbackPeerUid(hop, () => { throw new Error('no /proc') })).toBeUndefined() }) it('forwards only the derived identity, never a client-supplied identity header', () => { const spoofed = { host: 'x', 'tailscale-user-login': 'mallory@example.com', [TAILSCALE_UPSTREAM_HEADER]: 'mallory@example.com' } diff --git a/ui/tests/unit/tailnet-ssr.test.ts b/ui/tests/unit/tailnet-ssr.test.ts index d5aea4eb..d058c50b 100644 --- a/ui/tests/unit/tailnet-ssr.test.ts +++ b/ui/tests/unit/tailnet-ssr.test.ts @@ -4,13 +4,23 @@ import { createApp, createEvent, defineEventHandler, fetchWithEvent, toNodeListe import { IncomingMessage, ServerResponse, fetchNodeRequestHandler } from 'node-mock-http' import { createFetch } from 'ofetch' import { requestTailscaleIdentity, upstreamHeaders } from '../../server/utils/proxy' +const procTable = vi.hoisted(() => [ + ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode', + // Serve's root-owned loopback connection from port 40000 to the UI on 8787. + ' 0: 0100007F:9C40 0100007F:2253 01 00000000:00000000 00:00000000 00000000 0 0 13 1', +].join('\n')) +vi.mock('node:fs', async (original) => { + const fs = await original() + const readFileSync = ((path: unknown, ...rest: unknown[]) => path === '/proc/net/tcp' ? procTable : (fs.readFileSync as any)(path, ...rest)) as typeof fs.readFileSync + return { ...fs, default: { ...fs, readFileSync }, readFileSync } +}) const origin = 'anvil.example.ts.net' const env = { NITRO_FORGE_TAILSCALE_IDENTITY: 'serve', NITRO_FORGE_PUBLIC_ORIGIN: 'https://' + origin } function outer(remoteAddress = '127.0.0.1', login = 'operator@example.com') { const req = new IncomingMessage() req.url = '/'; req.headers = { host: origin, 'tailscale-user-login': login } - req.socket.remoteAddress = remoteAddress + Object.assign(req.socket, { remoteAddress, remotePort: 40000, localAddress: '127.0.0.1', localPort: 8787 }) return createEvent(req as any, new ServerResponse(req) as any) } afterEach(() => vi.unstubAllEnvs())