mirror of
https://github.com/wekan/wekan.git
synced 2026-11-24 09:59:47 -05:00
137 lines
8.5 KiB
Python
137 lines
8.5 KiB
Python
import contextlib
|
|
import hashlib
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
ROOT=Path(__file__).resolve().parent.parent
|
|
spec=importlib.util.spec_from_file_location('risk',ROOT/'releases/risk-audit.py')
|
|
r=importlib.util.module_from_spec(spec);spec.loader.exec_module(r)
|
|
class RiskAudit(unittest.TestCase):
|
|
def setUp(self):
|
|
(ROOT/'.tools/tmp').mkdir(parents=True,exist_ok=True)
|
|
self.tmp=tempfile.TemporaryDirectory(dir=ROOT/'.tools/tmp')
|
|
self.root=Path(self.tmp.name)
|
|
self.file=self.root/'main.js'
|
|
self.file.write_text('console.log("local diagnostics"); fetch("https://service.example/api");')
|
|
self.policy={'roots':['.'],'initialized':True,'files':r.collect(self.root,{'roots':['.']})}
|
|
def tearDown(self):self.tmp.cleanup()
|
|
def test_ordinary_hash_changes_and_local_logging_do_not_block(self):
|
|
self.file.write_text('console.log("more local diagnostics"); fetch("https://service.example/api");')
|
|
r.inspect(self.root,self.policy)
|
|
def test_new_urls_and_keywords_stop_with_evidence(self):
|
|
for text,expected in [('fetch("https://new.example/upload?secret=redacted")','new URL'),('new TelemetryClient()','suspicious keyword')]:
|
|
self.file.write_text(text)
|
|
with self.assertRaisesRegex(ValueError,expected) as result:r.inspect(self.root,self.policy)
|
|
self.assertNotIn('secret=',str(result.exception))
|
|
def test_version_url_allowance_is_limited_to_exact_file_and_host(self):
|
|
self.policy['allowUrlPatternsByFile'] = {'main.js': [r'https://nodejs\.org/dist/v26\.\d+\.\d+/']}
|
|
self.file.write_text('fetch("https://nodejs.org/dist/v26.100.0/")')
|
|
r.inspect(self.root, self.policy)
|
|
(self.root/'other.js').write_text(self.file.read_text())
|
|
with self.assertRaisesRegex(ValueError, 'other.js'): r.inspect(self.root, self.policy)
|
|
(self.root/'other.js').unlink()
|
|
for url in ['https://evil.example/dist/v26.100.0/', 'https://nodejs.org/dist/v26.100.0/?report=1',
|
|
'https://nodejs.org/dist/v27.0.0/']:
|
|
self.file.write_text('fetch("'+url+'")')
|
|
with self.assertRaisesRegex(ValueError, 'new URL'): r.inspect(self.root, self.policy)
|
|
|
|
def test_known_bad_hash_always_blocks_source_or_binary(self):
|
|
self.policy['denyHashes']=[hashlib.sha256(self.file.read_bytes()).hexdigest()]
|
|
with self.assertRaisesRegex(ValueError,'hash'):r.inspect(self.root,self.policy)
|
|
with self.assertRaisesRegex(ValueError,'hash'):r.artifact(self.file,self.policy)
|
|
def test_reviewed_lockfile_funding_urls_are_allowed_only_in_lockfile(self):
|
|
policy = json.loads((ROOT/'releases/risk-baseline.json').read_text())
|
|
self.policy['allowUrlPatternsByFile'] = policy['allowUrlPatternsByFile']
|
|
urls = ['https://github.com/sponsors/csstools',
|
|
'https://github.com/inikulin/parse5?sponsor=1',
|
|
'https://opencollective.com/csstools']
|
|
lock = self.root/'package-lock.json'
|
|
lock.write_text(json.dumps({'packages': {'node_modules/example': {
|
|
'funding': [{'url': url} for url in urls]}}}))
|
|
r.inspect(self.root, self.policy)
|
|
for url in urls:
|
|
with self.subTest(url=url):
|
|
self.file.write_text('fetch("'+url+'")')
|
|
with self.assertRaisesRegex(ValueError, 'main.js: new URL'):
|
|
r.inspect(self.root, self.policy)
|
|
|
|
def test_lockfile_allowances_still_reject_unreviewed_urls_and_keywords(self):
|
|
policy = json.loads((ROOT/'releases/risk-baseline.json').read_text())
|
|
self.policy['allowUrlPatternsByFile'] = policy['allowUrlPatternsByFile']
|
|
lock = self.root/'package-lock.json'
|
|
for url in ['https://github.com/sponsors/unreviewed',
|
|
'https://opencollective.com/unreviewed',
|
|
'https://github.com/inikulin/parse5?sponsor=10',
|
|
'https://github.com/sponsors/csstools?report=1',
|
|
'https://githubXcom/sponsors/csstools',
|
|
'https://opencollective.com.evil.example/csstools',
|
|
'https://new.example/package.tgz']:
|
|
with self.subTest(url=url):
|
|
lock.write_text(json.dumps({'url': url}))
|
|
with self.assertRaisesRegex(ValueError, 'package-lock.json: new URL'):
|
|
r.inspect(self.root, self.policy)
|
|
lock.write_text(json.dumps({'name': 'TelemetryClient',
|
|
'url': 'https://github.com/sponsors/csstools'}))
|
|
with self.assertRaisesRegex(ValueError, 'suspicious keyword'):
|
|
r.inspect(self.root, self.policy)
|
|
|
|
def test_sync_identity_allows_only_the_existing_github_api_origin(self):
|
|
policy = json.loads((ROOT/'releases/risk-baseline.json').read_text())
|
|
self.policy['allowUrlPatternsByFile'] = policy['allowUrlPatternsByFile']
|
|
module = self.root/'models/lib/listSyncSourceIdentity.js'
|
|
module.parent.mkdir(parents=True)
|
|
module.write_text('const base = "https://api.github.com";')
|
|
r.inspect(self.root, self.policy)
|
|
for url in ['https://api.github.com/report', 'https://api.github.com.evil.example']:
|
|
module.write_text('const base = "'+url+'";')
|
|
with self.assertRaisesRegex(ValueError, 'new URL'):
|
|
r.inspect(self.root, self.policy)
|
|
|
|
def test_baselined_keyword_is_not_blanket_for_new_occurrences(self):
|
|
self.file.write_text('/* TelemetryClient compatibility */')
|
|
self.policy['files']=r.collect(self.root,self.policy)
|
|
r.inspect(self.root,self.policy)
|
|
self.file.write_text('/* TelemetryClient compatibility */ new TelemetryClient()')
|
|
with self.assertRaisesRegex(ValueError,'keyword'):r.inspect(self.root,self.policy)
|
|
def test_new_files_are_scanned_and_test_fixtures_are_not_runtime(self):
|
|
(self.root/'tests').mkdir();(self.root/'tests/fixture.js').write_text('new TelemetryClient()')
|
|
r.inspect(self.root,self.policy)
|
|
(self.root/'new.js').write_text('new TelemetryClient()')
|
|
with self.assertRaisesRegex(ValueError,'new.js'):r.inspect(self.root,self.policy)
|
|
def test_artifact_urls_and_telemetry_signatures(self):
|
|
r.artifact(self.file,{'artifactUrls':['https://service.example/api']})
|
|
with self.assertRaisesRegex(ValueError,'New URL'):r.artifact(self.file,{'artifactUrls':[]})
|
|
self.file.write_text('mongosh-telemetry.mongodb.com')
|
|
with self.assertRaisesRegex(ValueError,'Telemetry indicator'):r.artifact(self.file,{})
|
|
def test_cli_exit_code_blocks_findings_but_not_hash_drift(self):
|
|
policy=self.root/'policy.json';policy.write_text(json.dumps(self.policy))
|
|
self.policy['exclude']=['policy.json'];policy.write_text(json.dumps(self.policy))
|
|
for text,code in [('console.log("local logging");',0),('fetch("https://new.example/report")',1)]:
|
|
self.file.write_text(text)
|
|
result=subprocess.run(['python3','-B',str(ROOT/'releases/risk-audit.py'),'--source',str(self.root),'--policy',str(policy)],capture_output=True,text=True)
|
|
self.assertEqual(result.returncode,code,result.stdout+result.stderr)
|
|
|
|
class GeneratedAppTestAssets(unittest.TestCase):
|
|
def test_full_app_test_assets_are_excluded_but_public_source_is_scanned(self):
|
|
(ROOT/'.tools/tmp').mkdir(parents=True,exist_ok=True)
|
|
with tempfile.TemporaryDirectory(dir=ROOT/'.tools/tmp') as directory:
|
|
root=Path(directory)
|
|
for name in ['public/build-assets-app-test','public/build-chunks-app-test',
|
|
'private/build-assets-app-test','private/build-chunks-app-test']:
|
|
asset=root/name/'bundle.js';asset.parent.mkdir(parents=True,exist_ok=True)
|
|
asset.write_text('fetch("https://generated.example"); Sentry.init();')
|
|
source=root/'public/real-source.js';source.write_text('console.log("local");')
|
|
for filename in ['risk-baseline.json','telemetry-source.json']:
|
|
policy={'roots':['public','private'],'exclude':json.loads((ROOT/'releases'/filename).read_text())['exclude']}
|
|
self.assertEqual(list(r.collect(root,policy)),['public/real-source.js'])
|
|
policy['files']=r.collect(root,policy);policy['initialized']=True
|
|
source.write_text('fetch("https://unapproved.example");')
|
|
with self.assertRaises(ValueError):r.inspect(root,policy)
|
|
source.write_text('console.log("local");')
|
|
|
|
if __name__=='__main__':unittest.main()
|