diff --git a/README.md b/README.md index d19e84c..ec67a9f 100644 --- a/README.md +++ b/README.md @@ -118,10 +118,12 @@ jobs: ``` `allow-terms` is a newline-separated, case-insensitive product-name allowlist. -It does not exempt attribution or private execution paths. The optional -Dependabot exception permits only its exact signoff after GitHub authenticates -the verified bot author and web-flow signer. Policy retains the family owner -identity `10173746+showxu@users.noreply.github.com` and GitHub's web committer. +It does not exempt attribution or private execution paths. The checker recognizes +official documentation references in source and checks the surrounding text for +attribution. The optional Dependabot exception permits only its exact signoff +after GitHub authenticates the verified bot author and web-flow signer. Policy +retains the family owner identity `10173746+showxu@users.noreply.github.com` +and GitHub's web committer. ## Calling Homebrew validation @@ -143,8 +145,16 @@ Use `tap: skill-cli/tap` for the skill-cli tap. `tap` is a required lowercase with a 30-minute timeout. The checkout is temporarily registered under that namespace, and an existing registration fails without being replaced. -Every run executes `brew style` and `brew audit --strict` for each -`Formula/*.rb`. Pull requests compare the base and head through their merge +For Homebrew's [tap trust](https://docs.brew.sh/Tap-Trust), the script grants +`brew trust --formula` only to the enumerated `Formula/*.rb` names, using their +fully qualified namespace. It uses a fresh temporary `XDG_CONFIG_HOME` for all +validation commands, leaving existing user trust and configuration files +unchanged. The trust directory and temporary tap link are removed on success +or failure. No whole-tap permission is granted. This applies to both tap +consumers, the CI fixture and local script invocations. + +After those grants, every run executes `brew style` and `brew audit --strict` +for each `Formula/*.rb`. Pull requests compare the base and head through their merge base, then run `brew install --build-from-source` and `brew test` for changed formulae that still exist. Deletions are skipped. Empty taps succeed with a notice. Auto-update, analytics and installation from the API are disabled. @@ -290,14 +300,16 @@ bash /path/to/github-workflows/scripts/check-homebrew agents-tools/tap bash /path/to/github-workflows/scripts/check-homebrew agents-tools/tap BASE HEAD ``` -The script temporarily registers the tap in Homebrew and removes that link on -exit. Use an unregistered namespace. Source-install runs modify the Homebrew -installation; the unit tests use an isolated recorder instead. The fixture tap +The script temporarily registers the tap in Homebrew and removes that link and +its isolated trust configuration on exit. Use an unregistered namespace. +Source-install runs modify the Homebrew installation; the unit tests use an +isolated recorder instead. The fixture tap contains a checksum-pinned GNU Hello formula. CI calls the reusable Homebrew workflow against it, including source installation when the formula changes in a pull request. Recorder tests cover both namespaces, nested fixture paths, -empty taps, changes/deletions/renames, existing registrations and each failing -Homebrew command. +empty taps, changes/deletions/renames, existing registrations, formula-specific +trust before validation, preservation of user configuration and cleanup after +each failing Homebrew command. macOS runs require Xcode/Swift; Linux fixture runs require Docker. The unit suite validates every package fixture against the schema, exercises compiler diff --git a/fixtures/homebrew/test_homebrew.py b/fixtures/homebrew/test_homebrew.py index 4a65232..4a08e96 100644 --- a/fixtures/homebrew/test_homebrew.py +++ b/fixtures/homebrew/test_homebrew.py @@ -26,6 +26,19 @@ def setUp(self): self.brew_root = self.root / 'brew' self.link = self.brew_root / 'Library/Taps/agents-tools/homebrew-tap' self.log = self.root / 'calls.jsonl' + self.user_config = self.root / 'user-config' + self.user_home = self.root / 'user-home' + for directory in (self.user_config / 'homebrew', self.user_home / '.homebrew'): + directory.mkdir(parents=True) + (directory / 'trust.json').write_text('{"trustedtaps": ["someone/other"]}\n') + (directory / 'brew.env').write_text('# Existing user configuration\n') + self.prior_config = {path: path.read_bytes() for directory in (self.user_config, self.user_home) + for path in directory.rglob('*') if path.is_file()} + self.temporary = self.root / 'temporary files' + self.temporary.mkdir() + self.other_link = self.brew_root / 'Library/Taps/someone/homebrew-other' + self.other_link.mkdir(parents=True) + (self.other_link / 'keep').write_text('unrelated tap\n') binary = self.root / 'bin' binary.mkdir() recorder = binary / 'brew' @@ -38,16 +51,33 @@ def setUp(self): assert link.resolve() == Path.cwd() assert all(os.environ[key] == '1' for key in ( 'HOMEBREW_NO_AUTO_UPDATE', 'HOMEBREW_NO_INSTALL_FROM_API', 'HOMEBREW_NO_ANALYTICS')) + config = Path(os.environ['XDG_CONFIG_HOME']) + assert config.parent == Path(os.environ['TMPDIR']) + assert config.stat().st_mode & 0o777 == 0o700 + store = config / 'homebrew/trust.json' + trust = json.loads(store.read_text()) if store.exists() else {} + if sys.argv[1] == 'trust': + assert sys.argv[2] == '--formula' + for reference in sys.argv[3:]: + trust.setdefault('trustedformulae', []).append(reference) + store.parent.mkdir(parents=True, exist_ok=True) + store.write_text(json.dumps(trust)) + if os.environ.get('FAIL_COMMAND') == 'trust': + break + else: + assert sys.argv[-1] in trust.get('trustedformulae', []) with open(os.environ['BREW_LOG'], 'a') as stream: - stream.write(json.dumps(sys.argv[1:]) + '\\n') + stream.write(json.dumps({'arguments': sys.argv[1:], 'config': str(config), 'trust': trust}) + '\\n') if sys.argv[1] == os.environ.get('FAIL_COMMAND'): sys.exit(1) ''') recorder.chmod(0o755) - self.env = {**os.environ, 'PATH': f'{binary}:{os.environ["PATH"]}', + environment = {key: value for key, value in os.environ.items() if not key.startswith('GIT_')} + self.env = {**environment, 'PATH': f'{binary}:{os.environ["PATH"]}', 'BREW_ROOT': str(self.brew_root), 'BREW_LINK': str(self.link), 'BREW_LOG': str(self.log), 'GIT_CONFIG_GLOBAL': os.devnull, - 'GIT_CONFIG_NOSYSTEM': '1'} + 'GIT_CONFIG_NOSYSTEM': '1', 'HOME': str(self.user_home), + 'XDG_CONFIG_HOME': str(self.user_config), 'TMPDIR': str(self.temporary)} self.git('init', '-q') self.git('config', 'user.name', 'Fixture') self.git('config', 'user.email', 'fixture@example.com') @@ -66,10 +96,19 @@ def run_check(self, *revisions, tap='agents-tools/tap', status=0): result = subprocess.run(['bash', str(SCRIPT), tap, *revisions], cwd=self.tap, env=self.env, text=True, capture_output=True, timeout=30) self.assertEqual(result.returncode, status, result.stdout + result.stderr) - return [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else [] + records = [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else [] + for record in records: + self.assertFalse(Path(record['config']).exists(), 'temporary trust configuration leaked') + self.assertEqual(list(self.temporary.iterdir()), []) + current_config = {path: path.read_bytes() for directory in (self.user_config, self.user_home) + for path in directory.rglob('*') if path.is_file()} + self.assertEqual(current_config, self.prior_config) + self.assertEqual((self.other_link / 'keep').read_text(), 'unrelated tap\n') + return [record['arguments'] for record in records] def validation_calls(self, namespace='agents-tools/tap'): - return [[command, *flags, f'{namespace}/{name}'] + return [['trust', '--formula', f'{namespace}/unchanged', f'{namespace}/workflow-hello']] + [ + [command, *flags, f'{namespace}/{name}'] for name in ('unchanged', 'workflow-hello') for command, flags in (('style', []), ('audit', ['--strict']))] @@ -77,6 +116,31 @@ def test_push_validates_every_formula_and_removes_registration(self): self.assertEqual(self.run_check(), self.validation_calls()) self.assertFalse(self.link.is_symlink()) + def test_trust_grants_only_enumerated_formulae_before_any_validation(self): + (self.tap / 'Casks').mkdir() + (self.tap / 'Casks/unrelated.rb').write_text('# Not a formula\n') + (self.tap / 'cmd').mkdir() + (self.tap / 'cmd/brew-unrelated.rb').write_text('# Not a formula\n') + (self.tap / 'Formula/extra.rb').write_text('# Another audited formula\n') + calls = self.run_check() + expected = {f'agents-tools/tap/{name}' for name in ('extra', 'unchanged', 'workflow-hello')} + self.assertEqual(calls[0][:2], ['trust', '--formula']) + self.assertEqual(set(calls[0][2:]), expected) + records = [json.loads(line) for line in self.log.read_text().splitlines()] + self.assertEqual(len({record['config'] for record in records}), 1) + for record in records: + self.assertEqual(record['trust'], {'trustedformulae': sorted(expected)}) + self.assertEqual({call[-1] for call in calls if call[0] == 'audit'}, expected) + + def test_each_invocation_uses_a_fresh_store_without_xdg_configuration(self): + del self.env['XDG_CONFIG_HOME'] + self.run_check() + first = json.loads(self.log.read_text().splitlines()[0])['config'] + self.log.unlink() + self.run_check() + second = json.loads(self.log.read_text().splitlines()[0])['config'] + self.assertNotEqual(first, second) + def test_second_caller_namespace(self): self.link = self.brew_root / 'Library/Taps/skill-cli/homebrew-tap' self.env['BREW_LINK'] = str(self.link) @@ -119,14 +183,14 @@ def test_nested_tap_uses_relative_diff_paths(self): def test_empty_tap_succeeds_without_brew(self): shutil.rmtree(self.tap / 'Formula') self.assertEqual(self.run_check(), []) - self.assertFalse(self.brew_root.exists()) + self.assertFalse(self.link.exists()) def test_invalid_namespace_or_revisions_fail_before_brew(self): for namespace in ('../tap', 'agents-tools/../../tap', '-bad/tap', 'owner/tap/extra'): with self.subTest(namespace=namespace): self.assertEqual(self.run_check(tap=namespace, status=2), []) self.run_check(self.base, 'missing', status=128) - self.assertFalse(self.brew_root.exists()) + self.assertFalse(self.link.exists()) def test_existing_registration_is_preserved(self): self.link.mkdir(parents=True) @@ -137,7 +201,7 @@ def test_each_brew_failure_propagates_and_cleans_registration(self): with (self.tap / 'Formula/workflow-hello.rb').open('a') as stream: stream.write('# Change\n') head = self.commit() - for command in ('style', 'audit', 'install', 'test'): + for command in ('trust', 'style', 'audit', 'install', 'test'): with self.subTest(command=command): self.log.unlink(missing_ok=True) self.env['FAIL_COMMAND'] = command diff --git a/scripts/check-homebrew b/scripts/check-homebrew index 1c5c7e0..d479e10 100755 --- a/scripts/check-homebrew +++ b/scripts/check-homebrew @@ -32,13 +32,22 @@ if [[ -e "$tap_directory" || -L "$tap_directory" ]]; then echo "Tap already exists: $tap" >&2 exit 1 fi +trust_directory="$(mktemp -d "${TMPDIR:-/tmp}/check-homebrew.XXXXXX")" +trap 'rm -rf -- "$trust_directory"' EXIT mkdir -p "$(dirname "$tap_directory")" ln -s "$PWD" "$tap_directory" -trap 'rm -- "$tap_directory"' EXIT +trap 'rm -rf -- "$trust_directory"; rm -- "$tap_directory"' EXIT +export XDG_CONFIG_HOME="$trust_directory" +references=() for formula in "${formulae[@]}"; do name="${formula##*/}" - reference="$tap/${name%.rb}" + references+=("$tap/${name%.rb}") +done +# Audits may load other formulae in this checkout; grant the enumerated set first. +brew trust --formula "${references[@]}" + +for reference in "${references[@]}"; do brew style "$reference" brew audit --strict "$reference" done diff --git a/scripts/check-policy.py b/scripts/check-policy.py index f1b1ebf..b1b658a 100755 --- a/scripts/check-policy.py +++ b/scripts/check-policy.py @@ -24,10 +24,27 @@ PRIVATE_PATH = re.compile(r"/(?:Users|home)/[^/\s]+/|[.]workspace/") PRODUCT = re.compile(r"\b(ChatGPT|Codex|Cursor|Claude)\b", re.I) PRODUCT_TERMS = frozenset({"chatgpt", "codex", "cursor", "claude"}) -TOOL_ATTRIBUTION = re.compile(r"Generated" r" with|cursor\.com|anthropic\.com|claude\.ai|openai\.com", re.I) +CREDITED_TOOL = r"\b(?:ChatGPT|Codex|Cursor|Claude|OpenAI|Anthropic)\b" +TOOL_CREDIT = re.compile( + r"\b(?:generated by|made with|assisted by|powered by)[ \t]+[*_`]*" + rf"(?:\[[^\]]*{CREDITED_TOOL}[^\]]*\]\(" + rf"|]*>[^<]*{CREDITED_TOOL}[^<]*" + rf"|\[?(?:the[ \t]+)?{CREDITED_TOOL})", + re.I, +) +TOOL_ATTRIBUTION = re.compile( + r"Generated" r" with|" + r"(?"'`)\]]|$)""", + re.I, +) # The agents CLI's committed declaration and lock name agent IDs such as codex; # instruction units under .agent/instructions/ are tracked repository guidance. -AGENT_STATE_FILES = {".agent/agents.json", ".agent/agents.resolved"} +AGENT_STATE_FILES = {".agent/agents.yaml", ".agent/agents.resolved"} AGENT_INSTRUCTIONS = ".agent/instructions/" @@ -44,7 +61,7 @@ def private_execution_file(file): def content_findings(path, number, text, allow_terms): reasons = [] - if TOOL_ATTRIBUTION.search(text): + if TOOL_CREDIT.search(text) or TOOL_ATTRIBUTION.search(DOCUMENTATION_REFERENCE.sub(" ", text)): reasons.append("tool attribution") if PRIVATE_PATH.search(text): reasons.append("private execution path") diff --git a/tests/test_policy.py b/tests/test_policy.py index 45483a9..465b0f7 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -65,6 +65,48 @@ def test_only_added_lines_are_scanned(self): self.assertEqual(len(findings), 3) self.assertTrue(any('b/file:12' in line for line in findings)) + def test_documentation_references_and_dotted_identifiers_are_not_attribution(self): + lines = ( + 'See [plugin packaging](https://developers.openai.com/plugins/build/plugins).', + 'sources: ["https://cursor.com/docs/mcp", "https://docs.cursor.com/en/agent/chat/commands"]', + 'Documented Cursor format (https://cursor.com/docs); upstream source revision unavailable', + 'Generated by the indexer. See **[Cursor](https://cursor.com/docs)**.', + 'See Cursor for settings.', + '#expect(cursor.commands == expected && cursor.components.isEmpty)', + ) + for line in lines: + with self.subTest(line=line): + patch = '@@ -0,0 +1 @@\n+' + line + '\n' + self.assertEqual(policy.added_findings(patch, allow_terms=policy.PRODUCT_TERMS), []) + + def test_documentation_references_preserve_other_findings_on_the_same_line(self): + docs = 'https://cursor.com/docs/mcp' + homepage = 'https://cursor.' 'com/' + private_path = '/' 'Users/fixture/private-checkout' + lines = { + '[Generated' ' with Cursor](' + docs + ')': ['tool attribution'], + 'Generated by ' '[Cursor](' + docs + ')': ['tool attribution'], + 'Generated by ' 'Cursor': ['tool attribution'], + 'Powered by ' '**[Cursor](' + docs + ')**': ['tool attribution'], + 'Made with ' '[the Cursor editor](' + docs + ')': ['tool attribution'], + 'Assisted by ' '[the OpenAI tool](https://developers.openai.com/plugins)': ['tool attribution'], + 'See ' + docs + ' and ' + homepage: ['tool attribution'], + 'See ' + homepage + 'docs-preview': ['tool attribution'], + 'Generated-by: ' + docs: ['forbidden attribution trailer'], + 'See ' + docs + ' in ' + private_path: ['private execution path'], + } + for line, reasons in lines.items(): + with self.subTest(line=line): + patch = '@@ -0,0 +1 @@\n+' + line + '\n' + self.assertEqual( + policy.added_findings(patch, allow_terms=policy.PRODUCT_TERMS), + ['diff:1: ' + reason for reason in reasons], + ) + self.assertEqual( + policy.content_findings('PR title', 1, 'docs: cite ' + docs, frozenset()), + ['PR title:1: unapproved product/tool term: cursor'], + ) + def test_event_ranges_reject_bad_or_unsupported_inputs(self): for event, name in (({}, 'schedule'), ({'deleted': True}, 'push'), ({'before': 'not-a-sha', 'after': 'a' * 40}, 'push')): @@ -81,6 +123,11 @@ def test_dispatch_requires_a_full_nonzero_github_sha(self): class GitRangeTests(unittest.TestCase): def setUp(self): + environment = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + isolation = mock.patch.dict(os.environ, environment, clear=True) + isolation.start() + self.addCleanup(isolation.stop) self.root = ROOT / '.build/test-policy' self.root.mkdir(parents=True) self.addCleanup(shutil.rmtree, self.root) @@ -390,7 +437,14 @@ def test_attributes_cannot_hide_text_or_disable_whitespace_policy(self): def test_agents_instruction_files_are_tracked_and_other_agent_files_stay_private(self): (self.root / '.agent/instructions/shared').mkdir(parents=True) (self.root / '.agent/instructions/shared/route.md').write_text('---\ndescription: Route changes.\n---\n## Route\n') - (self.root / '.agent/agents.json').write_text('{"instructions": {"agents": ["claude-code", "codex"]}}\n') + (self.root / '.agent/agents.yaml').write_text( + 'version: 1\n' + 'components:\n' + ' - kind: instructions\n' + ' sections:\n' + ' - name: shared/route\n' + ' agents: [claude-code, codex, cursor]\n' + ) (self.root / '.agent/agents.resolved').write_text('{"instructions": {"chatgpt": {}}}\n') head = self.commit('docs: declare agent instructions') self.assertEqual(policy.check(self.event(head, 'docs: declare agent instructions'), 'pull_request'), []) @@ -399,7 +453,7 @@ def test_agents_instruction_files_are_tracked_and_other_agent_files_stay_private (self.root / '.agent/cache').mkdir() (self.root / '.agent/cache/state').write_text('state\n') private = ('.agent/instructions/shared/.agent/cache/state', '.agent/instructions/.work' + 'space/notes.md', - '.agent/instructions/PLANS.md', 'plugin/.agent/agents.json', '.agent/agents.json.bak') + '.agent/instructions/PLANS.md', 'plugin/.agent/agents.yaml', '.agent/agents.yaml.bak') for path in private: (self.root / path).parent.mkdir(parents=True, exist_ok=True) (self.root / path).write_text('state\n')