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: 1 addition & 2 deletions docs/cli-fresh-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
```

Expand Down
6 changes: 3 additions & 3 deletions docs/factory-runtime-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/operator-sign-in.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 8 additions & 2 deletions forge/factory/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
}
Expand All @@ -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})
Expand Down Expand Up @@ -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),
Expand Down
19 changes: 11 additions & 8 deletions forge/factory/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand All @@ -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):
Expand Down
9 changes: 4 additions & 5 deletions forge/installation_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 7 additions & 6 deletions forge/store/executions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')):
Expand All @@ -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

Expand Down
1 change: 0 additions & 1 deletion forge_client/install_consent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']])]}
Expand Down
2 changes: 1 addition & 1 deletion forge_client/install_interview.py
Original file line number Diff line number Diff line change
Expand Up @@ -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: ',
Expand Down
11 changes: 6 additions & 5 deletions forge_client/installation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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'},
Expand All @@ -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.'}
27 changes: 17 additions & 10 deletions tests/test_codex_parallel_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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()
Expand All @@ -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):
Expand All @@ -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': ''}}
Expand Down
Loading
Loading