Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🏰 ci: Gate Main Promotions on Approved Dev Commits (#16570)

lia-by-librechat[bot]c60dac37d0a4
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 0000000000..a39dace850
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,5 @@
+# Enable required code-owner reviews in dev/main branch rules to enforce this.
+/.github/CODEOWNERS @danny-avila
+/.github/workflows/ @danny-avila
+/.github/scripts/ @danny-avila
+/.github/MAIN_PROMOTION.md @danny-avila
diff --git a/.github/MAIN_PROMOTION.md b/.github/MAIN_PROMOTION.md
new file mode 100644
index 0000000000..c562757892
--- /dev/null
+++ b/.github/MAIN_PROMOTION.md
@@ -0,0 +1,138 @@
+# Manually Approved Main Promotion
+
+`main` is a release pointer into `dev` history. The **Promote Dev to Main** workflow
+moves that pointer to one approved, fully tested `dev` commit. It creates no merge,
+rebase, squash, or new commit and never force-pushes. It is not an automated merge bot.
+
+## Trust boundary
+
+```text
+maintainer dispatches workflow on main with two exact SHAs
+ -> different environment reviewer approves
+ -> read-only validation of platform protections, actors, refs and full CI
+ -> short-lived App token for this repository, Contents: write only
+ -> repeat all validation, fetch into a bare object store, non-forced push
+ -> verify the new main SHA and revoke the App token
+```
+
+The privileged job runs inline code from the workflow revision on `main`, not a
+script from the candidate branch. It does not check out application source, restore
+caches, download PR artifacts, install packages, or execute repository-local actions.
+The sole action used there is `actions/create-github-app-token`, pinned to a full
+upstream commit SHA. The separate policy-test job has read-only permissions, no App
+credential, no protected environment, and does not persist checkout credentials.
+
+Inputs travel through environment variables and must be complete lowercase SHA-1
+commit IDs before they are used as API or Git arguments. Repository identity, GitHub
+hosts, dispatch event, workflow path and `main` ref are fixed. Both the original actor
+and any rerun actor must have GitHub's `admin` or `maintain` role. API failures,
+incomplete responses, missing CI runs, duplicate/missing jobs and unexpected states
+refuse promotion. There is no bypass or "ignore failures" input.
+
+The CI gate accepts only the latest full `push` or `workflow_dispatch` run on `dev`
+for the exact input SHA, from the repository's existing backend and frontend workflow
+IDs and paths. All build, typecheck, test-shard and circular-dependency jobs must be
+present and successful. Only the PR-only **Codegraph select** job may be skipped.
+An older successful run cannot conceal a newer failed or pending full run. PR checks
+and checks from a different commit do not qualify. This gate does not imply that
+Lighthouse, Playwright or integration lanes that only run on PRs tested the resulting
+post-merge SHA; maintainers still assess those PR results and release readiness.
+
+The candidate must be the current `dev` tip, and the reviewed baseline must still be
+the current `main` tip. `main` must be an ancestor of the candidate. Ref and CI
+validation is repeated after approval and immediately before the push. Concurrency
+serializes promotion runs without cancelling a job mid-push. Git's non-forced server
+update rejects a concurrent change that cannot fast-forward to the candidate. The
+cross-ref check is not an atomic lock on `dev`: if it advances after the final read,
+`main` still receives only the pinned, previously approved SHA, never the new tip.
+
+## Required repository setup (administrator)
+
+This PR adds code, **not** platform protection settings or credentials. Do not place
+the promotion key in repository-wide or organization-wide secrets. Keep it exclusively
+in the protected environment below. A missing environment can be auto-created by
+GitHub without protection; the inline gate refuses that state before minting a token.
+
+1. Protect **both `dev` and `main`** with rulesets/branch protection:
+ - Disallow force pushes and deletions. Require code-owner reviews for workflow,
+ script and CODEOWNERS changes, with stale approvals dismissed and approval of
+ the most recent reviewable push by someone other than its author.
+ - Restrict updates to `main` to release maintainers and the dedicated promotion
+ App. A fast-forward App update is not a PR merge: if a PR-only rule prevents
+ it, decide the narrowly scoped release-App exception explicitly. Never give
+ the App unrestricted bypass of force-push, deletion or other safety rules.
+ - `.github/CODEOWNERS` requests Danny's review of the release control plane;
+ it enforces nothing until the platform requires code-owner review. Add another
+ trusted code owner before Danny-authored control-plane changes can satisfy
+ mandatory code-owner review; the author cannot approve their own PR.
+2. Create an environment named **`main-promotion`**:
+ - Configure trusted **Required reviewers** and enable **Prevent self-review**.
+ Use enough trusted reviewers that someone other than the initiator can approve.
+ - Disable **Allow administrators to bypass configured protection rules**.
+ - Select **Selected branches and tags**. Add exactly one rule: type **Branch**,
+ name **`main`**. No tag rule, wildcard, `dev`, or other branch.
+3. Create a **dedicated GitHub App**, installed only on `LibreChat-AI/LibreChat`, with
+ repository **Contents: read and write** (and GitHub's required metadata access).
+ Do not reuse a PAT or a broad existing App. Do not grant Workflows, Actions,
+ Administration, Secrets or organization permissions.
+4. In that environment only, store:
+ - Variable **`MAIN_PROMOTION_APP_ID`**: the dedicated App's ID.
+ - Secret **`MAIN_PROMOTION_APP_PRIVATE_KEY`**: its private key.
+ The workflow requests a repository-scoped token with only Contents: write. The
+ pinned token action attempts revocation in its post-job step, including failures.
+ An interrupted runner may not execute cleanup; the installation token's short
+ lifetime bounds that residual risk. Do not disable token revocation.
+5. Merge this implementation into **`dev`** after review. Bootstrap it onto `main`
+ once with a separately approved, ordinary exact-SHA fast-forward; `workflow_dispatch`
+ cannot run a new workflow until its definition reaches the default branch.
+ Never bypass failed checks or protections as part of bootstrap. Changes to any
+ `.github/workflows/`, `.github/scripts/` or `.github/CODEOWNERS` file are deliberately
+ excluded from automated promotion, including this workflow's own updates. Those
+ use the separately reviewed manual path, so the App needs no Workflows permission.
+
+A repository administrator and the trusted `main` workflow are the root of trust.
+This is not a defense against a malicious repository administrator or a compromised
+reviewer who knowingly authorizes a malicious release. Nor does it harden the other
+existing publish workflows: an App push to `main` intentionally triggers the existing
+main-push automation, with its own permissions and dependencies. Review that downstream
+publishing surface separately before relying on the release process end to end.
+
+## Promote a normal tested dev commit
+
+1. Run `git ls-remote --heads origin main dev` in your own upstream clone. Review the
+ candidate and both **full** CI runs at the exact `dev` SHA.
+2. If path filters omitted a full run for that SHA, run the existing **Backend Unit
+ Tests** and **Frontend Unit Tests** workflows manually on `dev`, then wait for
+ success. Their new `workflow_dispatch` trigger uses full suites, not PR selection.
+3. Dispatch **Promote Dev to Main** using branch **`main`**. Supply the full `dev` SHA
+ as `dev_sha` and the full current `main` SHA as `expected_main_sha`. Example:
+
+ ```sh
+ gh workflow run promote-main.yml --repo LibreChat-AI/LibreChat --ref main \
+ -f dev_sha=<approved-current-dev-sha> \
+ -f expected_main_sha=<reviewed-current-main-sha>
+ ```
+
+4. A different configured reviewer examines the input SHAs and approves the
+ `main-promotion` environment deployment. The job still revalidates everything.
+5. Read the run summary and confirm `git ls-remote --heads origin main`. Monitor
+ downstream main-push publishing workflows separately. If refs or CI changed,
+ review a fresh dispatch. If the final read failed after a push, inspect the live
+ `main` tip before retrying: the push may have succeeded. Do not force-push.
+
+Rollback of code is a new reviewed revert on `dev`, followed by another approved
+fast-forward. Never move `main` backwards. Promotion adds no merge commit, but any
+merge commits already present in `dev` are preserved as part of its history.
+
+## Local validation
+
+```sh
+python3 -I .github/scripts/test_main_promotion.py
+```
+
+Tests extract and execute the workflow's actual inline policy against controlled
+API responses and exercise real local bare Git repositories. They never use live
+GitHub credentials or update a remote repository. Run the policy-test workflow and
+YAML/action lint before delivery. A production promotion cannot be verified until
+administrator setup and bootstrap are complete; do not report it as deployed merely
+because local tests pass.
diff --git a/.github/scripts/test_main_promotion.py b/.github/scripts/test_main_promotion.py
new file mode 100644
index 0000000000..c9bce8b258
--- /dev/null
+++ b/.github/scripts/test_main_promotion.py
@@ -0,0 +1,450 @@
+"""Exercise the policy embedded in the trusted workflow, using only the stdlib."""
+import copy
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import types
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[2]
+WORKFLOW = ROOT / '.github/workflows/promote-main.yml'
+TEXT = WORKFLOW.read_text()
+MATCH = re.search(r"^ cat > .* <<'PY'\n(.*?)^ PY$", TEXT, re.M | re.S)
+if MATCH is None:
+ raise RuntimeError('Inline production policy was not found')
+SOURCE = '\n'.join(line[10:] for line in MATCH[1].splitlines())
+POLICY = types.ModuleType('promotion_policy')
+exec(compile(SOURCE, str(WORKFLOW), 'exec'), POLICY.__dict__)
+DEV = 'd' * 40
+MAIN = 'a' * 40
+ENV = {
+ 'DEV_SHA': DEV,
+ 'EXPECTED_MAIN_SHA': MAIN,
+ 'GITHUB_REPOSITORY': POLICY.REPO,
+ 'GITHUB_EVENT_NAME': 'workflow_dispatch',
+ 'GITHUB_REF': 'refs/heads/main',
+ 'GITHUB_SERVER_URL': 'https://github.com',
+ 'GITHUB_API_URL': 'https://api.github.com',
+ 'WORKFLOW_REF': POLICY.WORKFLOW,
+ 'WORKFLOW_SHA': MAIN,
+ 'GITHUB_SHA': MAIN,
+ 'GITHUB_ACTOR': 'danny-avila',
+ 'GITHUB_TRIGGERING_ACTOR': 'release-maintainer',
+ 'GH_TOKEN': 'read-only-fixture',
+ 'PROMOTION_TOKEN': 'write-fixture',
+}
+
+
+def fixtures():
+ result = {
+ 'environments/main-promotion': {
+ 'can_admins_bypass': False,
+ 'deployment_branch_policy': {
+ 'protected_branches': False, 'custom_branch_policies': True,
+ },
+ 'protection_rules': [{
+ 'type': 'required_reviewers', 'prevent_self_review': True,
+ 'reviewers': [{'type': 'User', 'reviewer': {'login': 'reviewer'}}],
+ }],
+ },
+ 'environments/main-promotion/deployment-branch-policies?per_page=100': {
+ 'total_count': 1, 'branch_policies': [{'name': 'main', 'type': 'branch'}],
+ },
+ }
+ for actor in ('danny-avila', 'release-maintainer'):
+ result[f'collaborators/{actor}/permission'] = {
+ 'permission': 'admin', 'role_name': 'admin',
+ }
+ for branch, sha in [('main', MAIN), ('dev', DEV)]:
+ result[f'git/ref/heads/{branch}'] = {
+ 'ref': f'refs/heads/{branch}', 'object': {'type': 'commit', 'sha': sha},
+ }
+ for index, (filename, (workflow_id, required)) in enumerate(POLICY.CI.items(), 1):
+ result[f'actions/workflows/{filename}'] = {
+ 'id': workflow_id, 'path': f'.github/workflows/{filename}', 'state': 'active',
+ }
+ run = {
+ 'id': index, 'run_attempt': 2, 'workflow_id': workflow_id,
+ 'path': f'.github/workflows/{filename}', 'event': 'push',
+ 'head_branch': 'dev', 'head_sha': DEV,
+ 'repository': {'full_name': POLICY.REPO},
+ 'status': 'completed', 'conclusion': 'success',
+ }
+ result[f'actions/workflows/{workflow_id}/runs?head_sha={DEV}&per_page=100'] = {
+ 'total_count': 1, 'workflow_runs': [run],
+ }
+ result[f'actions/runs/{index}'] = copy.deepcopy(run)
+ jobs = [{'name': name, 'head_sha': DEV, 'status': 'completed', 'conclusion': 'success'}
+ for name in sorted(required)]
+ jobs.append({'name': 'Codegraph select', 'head_sha': DEV,
+ 'status': 'completed', 'conclusion': 'skipped'})
+ result[f'actions/runs/{index}/attempts/2/jobs?per_page=100'] = {
+ 'total_count': len(jobs), 'jobs': jobs,
+ }
+ return result
+
+
+class PolicyTests(unittest.TestCase):
+ def setUp(self):
+ self.data = fixtures()
+ self.calls = []
+ self.git_calls = []
+ self.scratch = tempfile.TemporaryDirectory(dir=ROOT)
+ self.addCleanup(self.scratch.cleanup)
+ self.addCleanup(patch.stopall)
+ self.env = dict(ENV, RUNNER_TEMP=self.scratch.name,
+ GITHUB_STEP_SUMMARY=str(Path(self.scratch.name) / 'summary'))
+ patch.dict(os.environ, self.env, clear=True).start()
+ patch.object(POLICY, 'api', self.api).start()
+ patch.object(POLICY, 'git', self.git).start()
+
+ def api(self, path):
+ self.calls.append(path)
+ if path not in self.data:
+ raise POLICY.Refused('Missing fixture')
+ return copy.deepcopy(self.data[path])
+
+ def git(self, args, token):
+ self.git_calls.append((args, token))
+ if 'rev-parse' in args:
+ return MAIN if args[-1] == 'refs/heads/main' else DEV
+ return ''
+
+ def refuse(self, operation=POLICY.verify):
+ with self.assertRaises(POLICY.Refused):
+ operation()
+ self.assertFalse(any('push' in args for args, _ in self.git_calls))
+
+ def ci_run(self, index=1):
+ workflow_id = list(POLICY.CI.values())[index - 1][0]
+ return self.data[f'actions/workflows/{workflow_id}/runs?head_sha={DEV}&per_page=100']
+
+ def ci_jobs(self, index=1):
+ return self.data[f'actions/runs/{index}/attempts/2/jobs?per_page=100']
+
+ def test_verified_full_ci_fetches_objects_but_never_pushes(self):
+ self.assertEqual(POLICY.verify()[:2], (DEV, MAIN))
+ self.assertTrue(any('merge-base' in args for args, _ in self.git_calls))
+ self.assertFalse(any('checkout' in args or 'push' in args for args, _ in self.git_calls))
+ self.assertTrue(all(token == ENV['GH_TOKEN'] for _, token in self.git_calls))
+
+ def test_rejects_shell_injection_and_nonexact_hashes(self):
+ for candidate in ('dev', DEV[:7], DEV.upper(), DEV + '\n', '--all',
+ '$(touch release)', DEV + ';echo unsafe', ''):
+ with self.subTest(candidate=candidate), patch.dict(os.environ, DEV_SHA=candidate):
+ self.refuse()
+ self.assertEqual(self.git_calls, [])
+
+ def test_requires_main_dispatch_and_fixed_repository_and_hosts(self):
+ for key, value in {
+ 'GITHUB_REPOSITORY': 'attacker/LibreChat', 'GITHUB_EVENT_NAME': 'pull_request_target',
+ 'GITHUB_REF': 'refs/heads/dev', 'GITHUB_SERVER_URL': 'https://evil.example',
+ 'GITHUB_API_URL': 'https://evil.example', 'WORKFLOW_REF': POLICY.WORKFLOW + '-evil',
+ 'WORKFLOW_SHA': DEV, 'GITHUB_SHA': DEV,
+ }.items():
+ with self.subTest(key=key), patch.dict(os.environ, {key: value}):
+ self.refuse()
+
+ def test_requires_original_and_rerun_actor_authorization(self):
+ for actor in ('danny-avila', 'release-maintainer'):
+ path = f'collaborators/{actor}/permission'
+ original = self.data[path]
+ self.data[path] = {'permission': 'write', 'role_name': 'write'}
+ self.refuse()
+ self.data[path] = original
+
+ def test_maintain_role_is_allowed_but_custom_writer_role_is_not(self):
+ path = 'collaborators/release-maintainer/permission'
+ self.data[path] = {'permission': 'write', 'role_name': 'maintain'}
+ self.assertEqual(POLICY.context(), (DEV, MAIN))
+ self.data[path] = {'permission': 'write', 'role_name': 'publisher'}
+ self.refuse()
+
+ def test_actor_cannot_inject_an_api_path(self):
+ with patch.dict(os.environ, GITHUB_ACTOR='../git/refs'):
+ self.refuse()
+
+ def test_missing_or_unprotected_environment_refuses(self):
+ value = self.data['environments/main-promotion']
+ for key, replacement in [
+ ('can_admins_bypass', True), ('can_admins_bypass', None),
+ ('protection_rules', []), ('deployment_branch_policy', None),
+ ('deployment_branch_policy', {'protected_branches': True, 'custom_branch_policies': False}),
+ ]:
+ with self.subTest(key=key, replacement=replacement):
+ old = value[key]
+ value[key] = replacement
+ self.refuse()
+ value[key] = old
+ del self.data['environments/main-promotion']
+ self.refuse()
+
+ def test_requires_nonself_approval_and_reviewers(self):
+ rule = self.data['environments/main-promotion']['protection_rules'][0]
+ for key, value in [('prevent_self_review', False), ('prevent_self_review', None), ('reviewers', [])]:
+ old = rule[key]
+ rule[key] = value
+ self.refuse()
+ rule[key] = old
+
+ def test_environment_rejects_wildcards_tags_and_extra_branches(self):
+ path = 'environments/main-promotion/deployment-branch-policies?per_page=100'
+ for rows in [[{'name': '*', 'type': 'branch'}], [{'name': 'main', 'type': 'tag'}],
+ [{'name': 'main', 'type': 'branch'}, {'name': 'dev', 'type': 'branch'}], []]:
+ with self.subTest(rows=rows):
+ self.data[path] = {'total_count': len(rows), 'branch_policies': rows}
+ self.refuse()
+
+ def test_drifted_main_or_dev_refuses(self):
+ for branch in ('main', 'dev'):
+ value = self.data[f'git/ref/heads/{branch}']['object']
+ old = value['sha']
+ value['sha'] = 'b' * 40
+ self.refuse()
+ value['sha'] = old
+
+ def test_incomplete_or_oversized_responses_refuse(self):
+ for value in ({'total_count': 2, 'rows': [1]}, {'rows': []},
+ {'total_count': 100, 'rows': list(range(100))}):
+ with self.subTest(value=value.get('total_count')):
+ self.refuse(lambda: POLICY.complete_list(value, 'rows'))
+
+ def test_requires_real_workflow_ids_paths_and_active_state(self):
+ for filename, (workflow_id, _) in POLICY.CI.items():
+ workflow = self.data[f'actions/workflows/{filename}']
+ for key, replacement in [('id', workflow_id + 1), ('path', '.github/workflows/fake.yml'),
+ ('state', 'disabled_manually')]:
+ old = workflow[key]
+ workflow[key] = replacement
+ self.refuse()
+ workflow[key] = old
+
+ def test_only_exact_dev_full_runs_count_not_prs_forks_or_old_commits(self):
+ run = self.ci_run()['workflow_runs'][0]
+ for key, replacement in [('event', 'pull_request'), ('event', 'workflow_run'),
+ ('head_branch', 'topic'), ('head_sha', MAIN),
+ ('repository', {'full_name': 'attacker/LibreChat'})]:
+ old = run[key]
+ run[key] = replacement
+ self.refuse()
+ run[key] = old
+ run['event'] = 'workflow_dispatch'
+ self.data['actions/runs/1']['event'] = 'workflow_dispatch'
+ self.assertEqual(POLICY.verify()[:2], (DEV, MAIN))
+
+ def test_no_workflow_run_means_not_tested(self):
+ self.ci_run().update(total_count=0, workflow_runs=[])
+ self.refuse()
+
+ def test_newer_failed_or_pending_run_cannot_hide_behind_old_success(self):
+ value = self.ci_run()
+ old = copy.deepcopy(value['workflow_runs'][0])
+ for status, conclusion in [('completed', 'failure'), ('in_progress', None),
+ ('completed', 'cancelled'), ('completed', 'skipped')]:
+ value['workflow_runs'] = [old, dict(old, id=100, status=status, conclusion=conclusion)]
+ value['total_count'] = 2
+ self.refuse()
+
+ def test_ci_rerun_during_job_verification_refuses(self):
+ for key, value in [('run_attempt', 3), ('status', 'in_progress'), ('conclusion', 'failure')]:
+ old = self.data['actions/runs/1'][key]
+ self.data['actions/runs/1'][key] = value
+ self.refuse()
+ self.data['actions/runs/1'][key] = old
+
+ def test_every_required_shard_must_exist_and_succeed(self):
+ for index in (1, 2):
+ jobs = self.ci_jobs(index)
+ original = copy.deepcopy(jobs)
+ for name in POLICY.CI[list(POLICY.CI)[index - 1]][1]:
+ with self.subTest(job=name):
+ jobs['jobs'] = [job for job in original['jobs'] if job['name'] != name]
+ jobs['total_count'] = len(jobs['jobs'])
+ self.refuse()
+ jobs.update(original)
+ for conclusion in ('skipped', 'cancelled', 'neutral', 'failure', None):
+ jobs['jobs'][0]['conclusion'] = conclusion
+ self.refuse()
+ jobs.update(original)
+
+ def test_duplicate_incomplete_wrong_sha_and_failed_extra_jobs_refuse(self):
+ jobs = self.ci_jobs()
+ old = copy.deepcopy(jobs)
+ jobs['jobs'].append(copy.deepcopy(jobs['jobs'][0]))
+ jobs['total_count'] += 1
+ self.refuse()
+ jobs.update(copy.deepcopy(old))
+ jobs['jobs'][0]['head_sha'] = MAIN
+ self.refuse()
+ jobs.update(copy.deepcopy(old))
+ jobs['jobs'][0]['status'] = 'in_progress'
+ self.refuse()
+ jobs.update(copy.deepcopy(old))
+ jobs['jobs'].append({'name': 'Additional security test', 'head_sha': DEV,
+ 'status': 'completed', 'conclusion': 'failure'})
+ jobs['total_count'] += 1
+ self.refuse()
+
+ def test_control_plane_changes_refuse_automated_promotion(self):
+ original = self.git
+ def changed(args, token):
+ return '.github/workflows/changed.yml' if 'diff' in args else original(args, token)
+ with patch.object(POLICY, 'git', changed):
+ self.refuse()
+
+ def test_main_or_dev_can_change_during_fetch_without_any_push(self):
+ original = self.git
+ for branch in ('main', 'dev'):
+ def move(args, token):
+ if 'fetch' in args:
+ self.data[f'git/ref/heads/{branch}']['object']['sha'] = 'b' * 40
+ return original(args, token)
+ self.data.update(fixtures())
+ with patch.object(POLICY, 'git', move):
+ self.refuse()
+
+ def test_revalidation_refuses_before_using_write_token(self):
+ self.data['git/ref/heads/dev']['object']['sha'] = MAIN
+ with patch.object(sys, 'argv', ['policy', 'promote']):
+ self.refuse(POLICY.run)
+ self.assertFalse(any(token == ENV['PROMOTION_TOKEN'] for _, token in self.git_calls))
+
+ def test_success_pushes_only_pinned_sha_to_main_without_force(self):
+ original = self.git
+ def push(args, token):
+ if 'push' in args:
+ self.data['git/ref/heads/main']['object']['sha'] = DEV
+ return original(args, token)
+ with patch.object(POLICY, 'git', push), patch.object(sys, 'argv', ['policy', 'promote']):
+ POLICY.run()
+ pushes = [(args, token) for args, token in self.git_calls if 'push' in args]
+ self.assertEqual(len(pushes), 1)
+ self.assertEqual(pushes[0][0][-2:], [POLICY.REMOTE, f'{DEV}:refs/heads/main'])
+ self.assertEqual(pushes[0][1], ENV['PROMOTION_TOKEN'])
+ self.assertFalse(any('force' in arg for arg in pushes[0][0]))
+
+ def test_api_failures_and_malformed_data_fail_closed(self):
+ with patch.object(POLICY, 'api', side_effect=POLICY.Refused('API unavailable')):
+ self.refuse()
+
+ def test_already_current_does_not_push(self):
+ with patch.object(POLICY, 'verify', return_value=(DEV, DEV, [])), \
+ patch.object(POLICY, 'ref', return_value=DEV), \
+ patch.object(sys, 'argv', ['policy', 'promote']):
+ POLICY.run()
+ self.assertEqual(self.git_calls, [])
+ self.assertIn('Already current', Path(self.env['GITHUB_STEP_SUMMARY']).read_text())
+
+ def test_failed_post_push_read_does_not_repeat_the_push(self):
+ original = self.git
+ def push(args, token):
+ result = original(args, token)
+ if 'push' in args:
+ del self.data['git/ref/heads/main']
+ return result
+ with patch.object(POLICY, 'git', push), patch.object(sys, 'argv', ['policy', 'promote']):
+ with self.assertRaises(POLICY.Refused):
+ POLICY.run()
+ self.assertEqual(sum('push' in args for args, _ in self.git_calls), 1)
+
+
+class AdapterTests(unittest.TestCase):
+ def test_api_uses_fixed_host_and_never_prints_raw_errors(self):
+ failed = subprocess.CompletedProcess([], 1, stdout='credential-like diagnostic',
+ stderr='untrusted server error')
+ with patch.object(subprocess, 'run', return_value=failed) as run:
+ with self.assertRaisesRegex(POLICY.Refused, '^GitHub policy read failed'):
+ POLICY.api('git/ref/heads/main')
+ self.assertIn('github.com', run.call_args.args[0])
+ self.assertNotIn('shell', run.call_args.kwargs)
+ for output in ('not-json', ''):
+ with patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, output)):
+ with self.assertRaisesRegex(POLICY.Refused, 'Invalid GitHub response'):
+ POLICY.api('git/ref/heads/main')
+
+ def test_git_credentials_are_not_arguments_or_persisted_config(self):
+ result = subprocess.CompletedProcess([], 0, stdout='ok', stderr='')
+ token = 'synthetic-token'
+ with patch.object(subprocess, 'run', return_value=result) as run, patch('builtins.print'):
+ self.assertEqual(POLICY.git(['push', POLICY.REMOTE, DEV + ':refs/heads/main'], token), 'ok')
+ argv = run.call_args.args[0]
+ self.assertFalse(any(token in arg for arg in argv))
+ self.assertEqual(argv[:3], ['git', '-c', 'core.hooksPath=/dev/null'])
+ env = run.call_args.kwargs['env']
+ self.assertEqual(env['GIT_CONFIG_GLOBAL'], '/dev/null')
+ self.assertEqual(env['GIT_CONFIG_NOSYSTEM'], '1')
+ self.assertEqual(env['GIT_CONFIG_KEY_0'], 'http.https://github.com/.extraheader')
+ self.assertNotIn('shell', run.call_args.kwargs)
+
+
+class GitIntegrationTests(unittest.TestCase):
+ def test_bare_git_fast_forward_preserves_hashes_and_refuses_divergence(self):
+ with tempfile.TemporaryDirectory(dir=ROOT) as directory:
+ env = dict(os.environ, GIT_CONFIG_GLOBAL='/dev/null', GIT_CONFIG_NOSYSTEM='1',
+ GIT_AUTHOR_NAME='test', GIT_AUTHOR_EMAIL='[email protected]',
+ GIT_COMMITTER_NAME='test', GIT_COMMITTER_EMAIL='[email protected]')
+ origin = str(Path(directory) / 'origin.git')
+ local = str(Path(directory) / 'local.git')
+ def git(*args, stdin=None, check=True):
+ return subprocess.run(['git', *args], env=env, input=stdin, capture_output=True,
+ text=True, check=check).stdout.strip()
+ git('init', '--bare', origin)
+ tree = git('--git-dir', origin, 'mktree', stdin='')
+ main = git('--git-dir', origin, 'commit-tree', tree, '-m', 'main')
+ dev = git('--git-dir', origin, 'commit-tree', tree, '-p', main, '-m', 'dev')
+ divergent = git('--git-dir', origin, 'commit-tree', tree, '-p', main, '-m', 'other')
+ git('--git-dir', origin, 'update-ref', 'refs/heads/main', main)
+ git('--git-dir', origin, 'update-ref', 'refs/heads/dev', dev)
+ git('init', '--bare', local)
+ git('--git-dir', local, 'fetch', '--no-tags', origin,
+ '+refs/heads/main:refs/heads/main', '+refs/heads/dev:refs/heads/dev')
+ git('--git-dir', local, 'merge-base', '--is-ancestor', main, dev)
+ git('--git-dir', local, 'push', origin, f'{dev}:refs/heads/main')
+ self.assertEqual(git('--git-dir', origin, 'rev-parse', 'refs/heads/main'), dev)
+ git('--git-dir', origin, 'update-ref', 'refs/heads/main', divergent)
+ refused = subprocess.run(['git', '--git-dir', local, 'push', origin,
+ f'{dev}:refs/heads/main'], env=env, capture_output=True)
+ self.assertNotEqual(refused.returncode, 0)
+ self.assertEqual(git('--git-dir', origin, 'rev-parse', 'refs/heads/main'), divergent)
+
+
+class WorkflowBoundaryTests(unittest.TestCase):
+ def test_write_job_has_no_untrusted_execution_sources(self):
+ self.assertNotRegex(TEXT, r'pull_request_target:|workflow_run:|repository_dispatch:|schedule:')
+ self.assertNotRegex(TEXT, r'uses: (?:\./|actions/(?:checkout|cache|download-artifact|setup-node))')
+ self.assertNotRegex(TEXT, r'\bnpm\s|\bnpx\s|\bpip\s|--force|force-with-lease|shell:\s*python')
+ self.assertIn('permissions: {}', TEXT)
+ self.assertIn('environment: main-promotion', TEXT)
+ self.assertIn('cancel-in-progress: false', TEXT)
+ self.assertIn('permission-contents: write', TEXT)
+ self.assertNotIn('permission-workflows:', TEXT)
+ actions = re.findall(r'uses: ([^\s]+)', TEXT)
+ self.assertEqual(actions, ['actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349'])
+ self.assertNotRegex(SOURCE, r'\beval\(|\bexec\(|shell=True')
+
+ def test_inputs_and_credentials_are_not_interpolated_into_shell_source(self):
+ for block in re.findall(r' run: \|\n(.*?)(?=\n -|\Z)', TEXT, re.S):
+ self.assertNotIn('${{', block)
+ self.assertLess(TEXT.index('python3 -I "$RUNNER_TEMP/main-promotion.py" verify'),
+ TEXT.index('uses: actions/create-github-app-token@'))
+ self.assertNotIn('skip-token-revoke: true', TEXT)
+
+ def test_selected_pr_tests_cannot_masquerade_as_full_ci(self):
+ for filename in POLICY.CI:
+ text = (ROOT / '.github/workflows' / filename).read_text()
+ self.assertIn(' workflow_dispatch:', text)
+ self.assertIn("github.event_name == 'pull_request'", text)
+
+ def test_control_plane_is_code_owned(self):
+ owners = (ROOT / '.github/CODEOWNERS').read_text()
+ for path in ('/.github/CODEOWNERS', '/.github/workflows/', '/.github/scripts/'):
+ self.assertIn(f'{path} @danny-avila', owners)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/.github/workflows/backend-review.yml b/.github/workflows/backend-review.yml
index 82d0088cdc..2845f4c4b2 100644
--- a/.github/workflows/backend-review.yml
+++ b/.github/workflows/backend-review.yml
@@ -24,6 +24,8 @@ on:
- 'config/circular-deps.mjs'
- '.github/workflows/backend-review.yml'
- '!**.md'
+ # Promotion requires full CI at the exact dev SHA, including path-filtered commits.
+ workflow_dispatch:
permissions:
contents: read
diff --git a/.github/workflows/frontend-review.yml b/.github/workflows/frontend-review.yml
index 40ebe5b722..f6b88df7a0 100644
--- a/.github/workflows/frontend-review.yml
+++ b/.github/workflows/frontend-review.yml
@@ -24,6 +24,8 @@ on:
- 'package.json'
- 'package-lock.json'
- '.github/workflows/frontend-review.yml'
+ # Promotion requires full CI at the exact dev SHA, including path-filtered commits.
+ workflow_dispatch:
permissions:
contents: read
diff --git a/.github/workflows/promote-main.yml b/.github/workflows/promote-main.yml
new file mode 100644
index 0000000000..311828b220
--- /dev/null
+++ b/.github/workflows/promote-main.yml
@@ -0,0 +1,275 @@
+name: Promote Dev to Main
+run-name: Promote dev ${{ inputs.dev_sha }} to main
+
+on:
+ workflow_dispatch:
+ inputs:
+ dev_sha:
+ description: 'Approved current dev commit, full lowercase 40-character SHA'
+ type: string
+ required: true
+ expected_main_sha:
+ description: 'Current main commit reviewed as the promotion baseline, full SHA'
+ type: string
+ required: true
+
+permissions: {}
+
+concurrency:
+ group: main-promotion
+ cancel-in-progress: false
+
+jobs:
+ promote:
+ if: >-
+ github.repository == 'LibreChat-AI/LibreChat' &&
+ github.event_name == 'workflow_dispatch' &&
+ github.ref == 'refs/heads/main'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ environment: main-promotion
+ permissions:
+ contents: read
+ actions: read
+ env:
+ GH_HOST: github.com
+ GH_PROMPT_DISABLED: '1'
+ DEV_SHA: ${{ inputs.dev_sha }}
+ EXPECTED_MAIN_SHA: ${{ inputs.expected_main_sha }}
+ WORKFLOW_REF: ${{ github.workflow_ref }}
+ WORKFLOW_SHA: ${{ github.workflow_sha }}
+ steps:
+ # Inline policy comes from the workflow on main. No candidate code, checkout,
+ # artifacts, caches, dependency installs, or repository-local actions run here.
+ - name: Verify protected approval, commit ancestry, and full dev CI
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ cat > "$RUNNER_TEMP/main-promotion.py" <<'PY'
+ import base64
+ import json
+ import os
+ import re
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ REPO = 'LibreChat-AI/LibreChat'
+ REMOTE = 'https://github.com/LibreChat-AI/LibreChat.git'
+ WORKFLOW = REPO + '/.github/workflows/promote-main.yml@refs/heads/main'
+ SHA = re.compile(r'[0-9a-f]{40}')
+ LOGIN = re.compile(r'[A-Za-z0-9][A-Za-z0-9-]{0,38}')
+ CI = {
+ 'backend-review.yml': (59857785, {
+ 'Build packages', 'Circular dependency checks', 'TypeScript type checks',
+ 'Tests: data-provider', 'Tests: data-schemas',
+ *[f'Tests: api (shard {n}/3)' for n in range(1, 4)],
+ *[f'Tests: @librechat/api (shard {n}/4)' for n in range(1, 5)],
+ }),
+ 'frontend-review.yml': (59789527, {
+ 'Build packages', 'Client build recovery regression',
+ 'TypeScript type checks (client)', 'Vite build verification',
+ 'Tests: @librechat/client',
+ *[f'Tests: Ubuntu (shard {n}/2)' for n in range(1, 3)],
+ }),
+ }
+
+ class Refused(Exception):
+ pass
+
+ def require(condition, message):
+ if not condition:
+ raise Refused(message)
+
+ def api(path):
+ result = subprocess.run(
+ ['gh', 'api', '--hostname', 'github.com', '--method', 'GET',
+ '-H', 'Accept: application/vnd.github+json',
+ '-H', 'X-GitHub-Api-Version: 2022-11-28', f'repos/{REPO}/{path}'],
+ capture_output=True, text=True, check=False, timeout=30,
+ )
+ require(result.returncode == 0, 'GitHub policy read failed; refusing promotion')
+ try:
+ return json.loads(result.stdout)
+ except ValueError:
+ raise Refused('Invalid GitHub response; refusing promotion') from None
+
+ def complete_list(value, key):
+ items = value.get(key)
+ require(isinstance(items, list) and value.get('total_count') == len(items)
+ and len(items) < 100, 'Incomplete or oversized policy response')
+ return items
+
+ def ref(branch):
+ value = api(f'git/ref/heads/{branch}')
+ obj = value.get('object', {})
+ require(value.get('ref') == f'refs/heads/{branch}' and obj.get('type') == 'commit'
+ and SHA.fullmatch(obj.get('sha', '')), 'Invalid branch response')
+ return obj['sha']
+
+ def context():
+ dev = os.environ.get('DEV_SHA', '')
+ main = os.environ.get('EXPECTED_MAIN_SHA', '')
+ require(SHA.fullmatch(dev) and SHA.fullmatch(main), 'Supply two full lowercase commit SHAs')
+ require(os.environ.get('GITHUB_REPOSITORY') == REPO
+ and os.environ.get('GITHUB_EVENT_NAME') == 'workflow_dispatch'
+ and os.environ.get('GITHUB_REF') == 'refs/heads/main'
+ and os.environ.get('GITHUB_SERVER_URL') == 'https://github.com'
+ and os.environ.get('GITHUB_API_URL') == 'https://api.github.com'
+ and os.environ.get('WORKFLOW_REF') == WORKFLOW
+ and os.environ.get('WORKFLOW_SHA') == main
+ and os.environ.get('GITHUB_SHA') == main,
+ 'Dispatch the trusted workflow from the current main branch')
+ actors = {os.environ.get('GITHUB_ACTOR', ''),
+ os.environ.get('GITHUB_TRIGGERING_ACTOR', '')}
+ for actor in actors:
+ require(LOGIN.fullmatch(actor), 'Invalid workflow actor')
+ permission = api(f'collaborators/{actor}/permission')
+ require(permission.get('role_name') in ('admin', 'maintain')
+ and permission.get('permission') in ('admin', 'write'),
+ 'Both the initiator and rerun actor must be maintainers')
+ return dev, main
+
+ def approval():
+ value = api('environments/main-promotion')
+ require(value.get('can_admins_bypass') is False, 'Disable administrator approval bypass')
+ require(value.get('deployment_branch_policy') == {
+ 'protected_branches': False, 'custom_branch_policies': True,
+ }, 'Use a main-only environment branch policy')
+ rules = value.get('protection_rules', [])
+ require(any(rule.get('type') == 'required_reviewers'
+ and rule.get('prevent_self_review') is True
+ and bool(rule.get('reviewers')) for rule in rules),
+ 'Configure required reviewers and prevent self-review')
+ policies = complete_list(
+ api('environments/main-promotion/deployment-branch-policies?per_page=100'),
+ 'branch_policies',
+ )
+ require(len(policies) == 1 and policies[0].get('name') == 'main'
+ and policies[0].get('type') == 'branch',
+ 'Only the main branch may access promotion credentials')
+
+ def full_ci(dev):
+ for filename, (workflow_id, required) in CI.items():
+ workflow = api(f'actions/workflows/{filename}')
+ require(workflow.get('id') == workflow_id
+ and workflow.get('path') == f'.github/workflows/{filename}'
+ and workflow.get('state') == 'active', 'Unexpected CI workflow identity')
+ runs = complete_list(api(
+ f'actions/workflows/{workflow_id}/runs?head_sha={dev}&per_page=100'
+ ), 'workflow_runs')
+ eligible = [run for run in runs
+ if run.get('event') in ('push', 'workflow_dispatch')
+ and run.get('head_branch') == 'dev'
+ and run.get('head_sha') == dev
+ and run.get('repository', {}).get('full_name') == REPO]
+ require(bool(eligible), f'Missing full dev CI: {filename}')
+ run = max(eligible, key=lambda item: item['id'])
+ require(run.get('workflow_id') == workflow_id
+ and run.get('path') == f'.github/workflows/{filename}'
+ and run.get('status') == 'completed' and run.get('conclusion') == 'success',
+ f'Latest full dev CI is not successful: {filename}')
+ run_id, attempt = run['id'], run['run_attempt']
+ require(type(run_id) is int and type(attempt) is int and run_id > 0 and attempt > 0,
+ 'Invalid CI run identity')
+ jobs = complete_list(api(
+ f'actions/runs/{run_id}/attempts/{attempt}/jobs?per_page=100'
+ ), 'jobs')
+ names = [job.get('name') for job in jobs]
+ require(len(names) == len(set(names)) and required.issubset(names),
+ f'Missing or duplicate full-suite jobs: {filename}')
+ require(all(job.get('status') == 'completed' and job.get('head_sha') == dev
+ and (job.get('conclusion') == 'success'
+ or (job.get('name') == 'Codegraph select'
+ and job.get('conclusion') == 'skipped')) for job in jobs),
+ f'Failed, skipped, or incomplete full-suite job: {filename}')
+ latest = api(f'actions/runs/{run_id}')
+ require(all(latest.get(key) == run.get(key) for key in (
+ 'id', 'run_attempt', 'head_sha', 'head_branch', 'event',
+ 'workflow_id', 'path', 'status', 'conclusion',
+ )), 'CI changed during verification; wait and dispatch again')
+
+ def git(args, token):
+ # No token in arguments, remote config, files, or output. Ignore global
+ # git config and hooks; only a disposable bare object database is used.
+ header = base64.b64encode(f'x-access-token:{token}'.encode()).decode()
+ print(f'::add-mask::{header}', flush=True)
+ env = dict(os.environ, GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL='/dev/null',
+ GIT_TERMINAL_PROMPT='0', GIT_CONFIG_COUNT='1',
+ GIT_CONFIG_KEY_0='http.https://github.com/.extraheader',
+ GIT_CONFIG_VALUE_0=f'AUTHORIZATION: basic {header}')
+ result = subprocess.run(
+ ['git', '-c', 'core.hooksPath=/dev/null', *args],
+ env=env, capture_output=True, text=True, check=False, timeout=90,
+ )
+ require(result.returncode == 0, 'Git operation refused; do not force or bypass protection')
+ return result.stdout.strip()
+
+ def verify():
+ dev, main = context()
+ approval()
+ require(ref('dev') == dev and ref('main') == main, 'Branch tips changed; dispatch again')
+ full_ci(dev)
+ directory = Path(os.environ['RUNNER_TEMP']) / 'main-promotion.git'
+ token = os.environ['GH_TOKEN']
+ git(['init', '--bare', str(directory)], token)
+ prefix = ['--git-dir', str(directory)]
+ git([*prefix, 'fetch', '--no-tags', REMOTE,
+ '+refs/heads/main:refs/heads/main', '+refs/heads/dev:refs/heads/dev'], token)
+ require(git([*prefix, 'rev-parse', 'refs/heads/main'], token) == main
+ and git([*prefix, 'rev-parse', 'refs/heads/dev'], token) == dev,
+ 'Branch tips changed during fetch; dispatch again')
+ git([*prefix, 'merge-base', '--is-ancestor', main, dev], token)
+ # The App deliberately has no Workflows permission. Updating the
+ # release control plane requires a separately reviewed manual FF.
+ changed = git([*prefix, 'diff', '--name-only', main, dev, '--',
+ '.github/workflows', '.github/scripts', '.github/CODEOWNERS'], token)
+ require(not changed, 'Workflow/control-plane changes require a maintainer-reviewed manual fast-forward')
+ require(ref('dev') == dev and ref('main') == main, 'Branch tips changed after CI verification')
+ return dev, main, prefix
+
+ def run():
+ dev, main, prefix = verify()
+ if sys.argv[1] == 'promote':
+ require(bool(os.environ.get('PROMOTION_TOKEN')), 'No promotion credential')
+ # No force flag. A concurrent non-ancestor main update is rejected
+ # by Git receive-pack; dev can never change the pinned target SHA.
+ if dev != main:
+ git([*prefix, 'push', '--porcelain', REMOTE, f'{dev}:refs/heads/main'],
+ os.environ['PROMOTION_TOKEN'])
+ require(ref('main') == dev, 'Post-push verification failed; inspect main before retrying')
+ outcome = 'Promoted' if dev != main else 'Already current'
+ else:
+ require(sys.argv[1] == 'verify', 'Invalid operation')
+ outcome = 'Verified; main has not been changed'
+ with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as summary:
+ summary.write(f'### {outcome}\n\nMain baseline: `{main}`\n\nApproved dev: `{dev}`\n')
+
+ if __name__ == '__main__':
+ try:
+ run()
+ except Refused as error:
+ print(f'::error::Promotion refused: {error}', file=sys.stderr)
+ sys.exit(1)
+ except (KeyError, TypeError, ValueError, subprocess.TimeoutExpired):
+ print('::error::Invalid or unavailable policy data; refusing promotion.', file=sys.stderr)
+ sys.exit(1)
+ PY
+ python3 -I "$RUNNER_TEMP/main-promotion.py" verify
+
+ - name: Mint a repository-scoped short-lived promotion token
+ id: app
+ uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2
+ with:
+ app-id: ${{ vars.MAIN_PROMOTION_APP_ID }}
+ private-key: ${{ secrets.MAIN_PROMOTION_APP_PRIVATE_KEY }}
+ owner: LibreChat-AI
+ repositories: LibreChat
+ permission-contents: write
+
+ - name: Revalidate and fast-forward only main
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PROMOTION_TOKEN: ${{ steps.app.outputs.token }}
+ run: python3 -I "$RUNNER_TEMP/main-promotion.py" promote
diff --git a/.github/workflows/promotion-tests.yml b/.github/workflows/promotion-tests.yml
new file mode 100644
index 0000000000..5c340c19ac
--- /dev/null
+++ b/.github/workflows/promotion-tests.yml
@@ -0,0 +1,35 @@
+name: Main Promotion Policy Tests
+
+on:
+ pull_request:
+ branches: [dev]
+ paths:
+ - '.github/workflows/promote-main.yml'
+ - '.github/workflows/promotion-tests.yml'
+ - '.github/workflows/backend-review.yml'
+ - '.github/workflows/frontend-review.yml'
+ - '.github/scripts/test_main_promotion.py'
+ - '.github/CODEOWNERS'
+ push:
+ branches: [dev]
+ paths:
+ - '.github/workflows/promote-main.yml'
+ - '.github/workflows/promotion-tests.yml'
+ - '.github/workflows/backend-review.yml'
+ - '.github/workflows/frontend-review.yml'
+ - '.github/scripts/test_main_promotion.py'
+ - '.github/CODEOWNERS'
+
+permissions:
+ contents: read
+
+jobs:
+ policy:
+ name: Main promotion denial and fast-forward tests
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+ with:
+ persist-credentials: false
+ - run: python3 -I .github/scripts/test_main_promotion.py