"""Untrusted API/ZIP boundaries and complete source lineage.""" import copy import hashlib import io import json import stat import unittest from unittest import mock import zipfile import urllib.request from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW from gitea_source import GiteaSource, SourceError, NoRedirect, strict_json, unpack_artifact A, B, C = 'a'*40, 'b'*40, 'c'*40 def run(number=8, sha=B): return dict(id=number, run_number=number, run_attempt=1, head_sha=sha, event='push', head_branch='master', path=WORKFLOW, status='completed', conclusion='success', repository={'id':33, 'full_name':REPOSITORY}) def job(r): return dict(id=8, run_id=r['id'], head_sha=r['head_sha'], head_branch='master', run_attempt=1, name='qualify', labels=['nodedc-node22-build'], runner_id=2, runner_name='synology-cms-build', status='completed', conclusion='success', steps=[dict(name=n,status='completed',conclusion='success') for n in ('Check the exact pushed commit','Retain the qualified release in this Gitea run')]) def packed(r, mutate=None, names=None): name='nodedc-dc-cms-release-v1-r'+str(r['id'])+'-'+r['head_sha']+'.tgz' data=b'qualified tgz fixture' receipt=dict(artifact=name,sourceCommit=r['head_sha'],runId=r['id'],runNumber=r['run_number'], deployed=False,sha256=hashlib.sha256(data).hexdigest()) if mutate:mutate(receipt) out=io.BytesIO() with zipfile.ZipFile(out,'w') as z: z.writestr(name,data) z.writestr('release.json',json.dumps(receipt)) for n in names or []:z.writestr(n,b'extra') return out.getvalue() class SourceTests(unittest.TestCase): def setUp(self):self.s=GiteaSource('a'*40,runner_id=2) def test_no_redirects_or_unapproved_routes(self): with self.assertRaises(SourceError):NoRedirect().redirect_request(None,None,302,'',{},'https://other/') for path in ['/../../user','/actions/runs?token=a','//user','/branches/other','/actions/artifacts/1/zip%3f']: with self.subTest(path=path),self.assertRaises(SourceError):self.s.request(path) def test_observed_signed_download_redirect_strips_persistent_token(self): url='https://git.dcserve.ru/api/v1/repos/SILVER/DC_CMS/actions/artifacts/6/zip' target=url+'/raw?sig='+'a'*43+'&expires=1790708000' req=urllib.request.Request(url,headers={'Authorization':'token '+'b'*40}) redirected=NoRedirect().redirect_request(req,None,302,'',{},target) self.assertIsNone(redirected.get_header('Authorization')) self.assertEqual(redirected.full_url,target) for bad in [target.replace('git.dcserve.ru','example.com'),target.replace('/6/','/7/'), target+'&extra=1',target+'&sig='+'c'*43,target.replace('https:','http:')]: with self.subTest(url=bad),self.assertRaises(SourceError):NoRedirect().redirect_request(req,None,302,'',{},bad) with self.assertRaises(SourceError):NoRedirect().redirect_request(redirected,None,302,'',{},target) def test_duplicate_json_keys_and_token_format(self): for value in [b'{"id":1,"id":2}',b'invalid',b'\xff']: with self.assertRaises(SourceError):strict_json(value) for token in ['', 'A'*40,'a'*40+'\n','secret']: with self.assertRaises(SourceError):GiteaSource(token) def test_paginated_complete_unique(self): with mock.patch.object(self.s,'request',side_effect=[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=51,items=[dict(id=51)])]) as get: self.assertEqual(len(self.s.pages('/actions/runs','items')),51) self.assertEqual(get.call_args.args[0],'/actions/runs?page=2&limit=50') def test_partial_changed_and_duplicate_pages_fail(self): scenarios=[ [dict(total_count=2,items=[dict(id=1)])], [dict(total_count=2,items=[dict(id=1),dict(id=1)])], [dict(total_count=True,items=[])], [dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=50,items=[])], ] for pages in scenarios: with self.subTest(pages=len(pages)),mock.patch.object(self.s,'request',side_effect=pages),self.assertRaises(SourceError):self.s.pages('/actions/runs','items') def test_run_nested_repository_identity_not_broken_top_level_field(self): r=run();r['repository_id']=0;self.s.validate_run(r) r['repository']['id']=39 with self.assertRaises(SourceError):self.s.validate_run(r) def test_discovery_rejects_change_between_complete_scans(self): with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[run()],[run(),run(9,C)]]),self.assertRaises(SourceError):self.s.discover() def test_discovery_allows_status_progress_without_loss(self): pending=run();pending.update(status='in_progress',conclusion=None) with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[pending],[run()]]):self.assertEqual(self.s.discover(),[run()]) def test_success_must_have_exact_job_and_steps(self): r=run();row=dict(id=8,number=8,sha=B,attempt=1) with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[job(r)]):self.assertEqual(self.s.successful_run(row),r) for field,value in [('runner_id',1),('runner_id',True),('runner_name','synology-device-core-build'),('labels',['ubuntu-latest']),('steps',[]),('head_sha',A),('conclusion','failure')]: j=job(r);j[field]=value with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[j]),self.assertRaises(SourceError):self.s.successful_run(row) def test_qualification_requires_explicit_registered_runner(self): for invalid in (0, True, -1, '2', 2**53): with self.assertRaises(SourceError):GiteaSource('a'*40,runner_id=invalid) with self.assertRaisesRegex(SourceError, 'registered_runner_identity_required'): GiteaSource('a'*40).successful_run(dict(id=8,number=8,sha=B,attempt=1)) # Registration numbers are allocated by Gitea, never fixed at 1 or 2. source=GiteaSource('a'*40,runner_id=17);j=job(run());j['runner_id']=17 with mock.patch.object(source,'run',return_value=run()),mock.patch.object(source,'pages',return_value=[j]): self.assertEqual(source.successful_run(dict(id=8,number=8,sha=B,attempt=1)),run()) def test_ancestry_proves_both_edges_and_stable_main(self): graph={C:[B],B:[A],A:[]} def get(path): sha=path.rsplit('/',1)[1] return dict(sha=sha,parents=[dict(sha=p) for p in graph[sha]]) with mock.patch.object(self.s,'request',side_effect=get),mock.patch.object(self.s,'main_commit',return_value=C): self.assertEqual(self.s.prove_lineage(A,B),C) with self.assertRaises(SourceError):self.s.prove_lineage(B,A) with self.assertRaises(SourceError):self.s.prove_lineage(B,B) with mock.patch.object(self.s,'ancestor',return_value=True),mock.patch.object(self.s,'main_commit',side_effect=[B,C]),self.assertRaises(SourceError):self.s.prove_lineage(A,B) def test_ancestry_malformed_and_bound(self): with mock.patch.object(self.s,'request',return_value=dict(sha=B,parents=[dict(sha=C)])),self.assertRaisesRegex(SourceError,'ancestry_limit'):self.s.ancestor(A,B,limit=1) with mock.patch.object(self.s,'request',return_value=dict(sha=C,parents=[])),self.assertRaisesRegex(SourceError,'commit_identity'):self.s.ancestor(A,B) def test_zip_requires_exact_receipt_and_only_two_files(self): r=run();receipt,data=unpack_artifact(packed(r),r) self.assertEqual(receipt['sha256'],hashlib.sha256(data).hexdigest()) for change in [lambda d:d.update(sourceCommit=A),lambda d:d.update(deployed=True),lambda d:d.update(sha256='f'*64),lambda d:d.update(extra='value')]: with self.assertRaises(SourceError):unpack_artifact(packed(r,change),r) for name in ['../../script','runtime/token','.DS_Store']: with self.assertRaises(SourceError):unpack_artifact(packed(r,names=[name]),r) with self.assertRaises(SourceError):unpack_artifact(b'bad zip',r) def test_artifact_owner_download_digest_bound_to_run(self): r=run();blob=packed(r) a=dict(id=8,name='dc-cms-release',workflow_run=dict(id=8,repository_id=33,head_sha=B),expired=False,size_in_bytes=len(blob)) with mock.patch.object(self.s,'pages',return_value=[a]),mock.patch.object(self.s,'request',return_value=blob):self.assertEqual(self.s.artifact(r)[0]['sourceCommit'],B) a['workflow_run']['repository_id']=39 with mock.patch.object(self.s,'pages',return_value=[a]),self.assertRaises(SourceError):self.s.artifact(r) if __name__=='__main__':unittest.main()