{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \",\n end_stream=True,\n )\n \n # receive response\n events = h0_transfer(quic_server, h0_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(events[0].headers, [])\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n \n===========unchanged ref 0===========\n at: aioquic.h0.connection\n H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h0\n h0_transfer(quic_sender, h0_receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n "}}},{"rowIdx":3636,"cells":{"path":{"kind":"string","value":"tests.test_h0/H0ConnectionTest.test_headers_only"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H0_ALPN},\n client_options={\"alpn_protocols\": [\"hq-23\"]},\n <2>: server_options={\"alpn_protocols\": H0_ALPN},\n server_options={\"alpn_protocols\": [\"hq-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"hq-23\"]},\n <2> server_options={\"alpn_protocols\": [\"hq-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h0_client = H0Connection(quic_client)\n <5> h0_server = H0Connection(quic_server)\n <6> \n <7> # send request\n <8> stream_id = quic_client.get_next_available_stream_id()\n <9> h0_client.send_headers(\n<10> stream_id=stream_id,\n<11> headers=[\n<12> (b\":method\", b\"HEAD\"),\n<13> (b\":scheme\", b\"https\"),\n<14> (b\":authority\", b\"localhost\"),\n<15> (b\":path\", b\"/\"),\n<16> ],\n<17> end_stream=True,\n<18> )\n<19> \n<20> # receive request\n<21> events = h0_transfer(quic_client, h0_server)\n<22> self.assertEqual(len(events), 2)\n<23> \n<24> self.assertTrue(isinstance(events[0], HeadersReceived))\n<25> self.assertEqual(\n<26> events[0].headers, [(b\":method\", b\"HEAD\"), (b\":path\", b\"/\")]\n<27> )\n<28> self.assertEqual(events[0].stream_id, stream_id)\n<29> self.assertEqual(events[0].stream_ended, False)\n<30> \n<31> self.assertTrue(isinstance(events[1], DataReceived))\n<32> self.assertEqual(events[1].data, b\"\")\n<33> self.assertEqual(events[1].stream_id, stream_id)\n<34> self.assertEqual(events[1].stream_ended, True)\n<35> \n<36> # send response\n<37> h0_server.send_headers(\n<38> stream_id=stream_id,\n<39> headers=[\n<40> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n # offset: 1\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n end_stream=True,\n )\n \n # receive response\n events = h0_transfer(quic_server, h0_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(events[0].headers, [])\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n \n===========unchanged ref 0===========\n at: aioquic.h0.connection\n H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h0\n h0_transfer(quic_sender, h0_receiver)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_connect(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H0_ALPN},\n - client_options={\"alpn_protocols\": [\"hq-23\"]},\n + server_options={\"alpn_protocols\": H0_ALPN},\n - server_options={\"alpn_protocols\": [\"hq-23\"]},\n ) as (quic_client, quic_server):\n h0_client = H0Connection(quic_client)\n h0_server = H0Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h0_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n )\n h0_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n \n # receive request\n events = h0_transfer(quic_client, h0_server)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(\n events[0].headers, [(b\":method\", b\"GET\"), (b\":path\", b\"/\")]\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h0_server.\n===========changed ref 1===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n \n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h0_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n )\n h0_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=True,\n )\n \n # receive response\n events = h0_transfer(quic_server, h0_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(events[0].headers, [])\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n===========changed ref 2===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n "}}},{"rowIdx":3637,"cells":{"path":{"kind":"string","value":"examples.interop/test_http_0"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <3>: configuration.alpn_protocols = H0_ALPN\n configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n <0> if server.path is None:\n <1> return\n <2> \n <3> configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n <4> async with connect(\n <5> server.host,\n <6> server.port,\n <7> configuration=configuration,\n <8> create_protocol=HttpClient,\n <9> ) as protocol:\n<10> protocol = cast(HttpClient, protocol)\n<11> \n<12> # perform HTTP request\n<13> events = await protocol.get(\n<14> \"https://{}:{}{}\".format(server.host, server.port, server.path)\n<15> )\n<16> if events and isinstance(events[0], HeadersReceived):\n<17> server.result |= Result.D\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.h0.connection\n H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ))\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n \n===========unchanged ref 1===========\n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n at: examples.interop\n Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str=\"/\", result: Result=field(default_factory=lambda: Result(0)))\n \n at: examples.interop.Server\n name: str\n \n host: str\n \n port: int = 4433\n \n http3: bool = True\n \n retry_port: Optional[int] = 4434\n \n path: str = \"/\"\n \n result: Result = field(default_factory=lambda: Result(0))\n \n at: http3_client\n HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: http3_client.HttpClient\n get(url: str, headers: Dict={}) -> Deque[H3Event]\n \n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n \n===========changed ref 0===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 1===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 2===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H0_ALPN},\n - client_options={\"alpn_protocols\": [\"hq-23\"]},\n + server_options={\"alpn_protocols\": H0_ALPN},\n - server_options={\"alpn_protocols\": [\"hq-23\"]},\n ) as (quic_client, quic_server):\n h0_client = H0Connection(quic_client)\n h0_server = H0Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h0_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"HEAD\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n end_stream=True,\n )\n \n # receive request\n events = h0_transfer(quic_client, h0_server)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(\n events[0].headers, [(b\":method\", b\"HEAD\"), (b\":path\", b\"/\")]\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h0_server.send_headers(\n stream_id=stream_id,\n headers=[\n \n===========changed ref 3===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n # offset: 1\n # send response\n h0_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n end_stream=True,\n )\n \n # receive response\n events = h0_transfer(quic_server, h0_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(events[0].headers, [])\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n "}}},{"rowIdx":3638,"cells":{"path":{"kind":"string","value":"examples.interop/test_http_3"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <3>: configuration.alpn_protocols = H3_ALPN\n configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n <0> if server.path is None:\n <1> return\n <2> \n <3> configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n <4> async with connect(\n <5> server.host,\n <6> server.port,\n <7> configuration=configuration,\n <8> create_protocol=HttpClient,\n <9> ) as protocol:\n<10> protocol = cast(HttpClient, protocol)\n<11> \n<12> # perform HTTP request\n<13> events = await protocol.get(\n<14> \"https://{}:{}{}\".format(server.host, server.port, server.path)\n<15> )\n<16> if events and isinstance(events[0], HeadersReceived):\n<17> server.result |= Result.D\n<18> server.result |= Result.three\n<19> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n at: aioquic.h3.events\n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ))\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n at: examples.interop\n Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str=\"/\", result: Result=field(default_factory=lambda: Result(0)))\n \n at: examples.interop.Server\n host: str\n \n \n===========unchanged ref 1===========\n port: int = 4433\n \n path: str = \"/\"\n \n at: http3_client\n HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: http3_client.HttpClient\n get(url: str, headers: Dict={}) -> Deque[H3Event]\n \n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n \n===========changed ref 0===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 1===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 2===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 3===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H0_ALPN},\n - client_options={\"alpn_protocols\": [\"hq-23\"]},\n + server_options={\"alpn_protocols\": H0_ALPN},\n - server_options={\"alpn_protocols\": [\"hq-23\"]},\n ) as (quic_client, quic_server):\n h0_client = H0Connection(quic_client)\n h0_server = H0Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h0_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"HEAD\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n end_stream=True,\n )\n \n # receive request\n events = h0_transfer(quic_client, h0_server)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(\n events[0].headers, [(b\":method\", b\"HEAD\"), (b\":path\", b\"/\")]\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h0_server.send_headers(\n stream_id=stream_id,\n headers=[\n \n===========changed ref 4===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n # offset: 1\n # send response\n h0_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n end_stream=True,\n )\n \n # receive response\n events = h0_transfer(quic_server, h0_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(events[0].headers, [])\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n "}}},{"rowIdx":3639,"cells":{"path":{"kind":"string","value":"examples.interop/test_throughput"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":"<15>: configuration.alpn_protocols = H3_ALPN\n configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n<17>: configuration.alpn_protocols = H0_ALPN\n configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_throughput(server: Server, configuration: QuicConfiguration):\n <0> failures = 0\n <1> \n <2> for size in [5000000, 10000000]:\n <3> print(\"Testing %d bytes download\" % size)\n <4> path = \"/%d\" % size\n <5> \n <6> # perform HTTP request over TCP\n <7> start = time.time()\n <8> response = requests.get(\"https://\" + server.host + path, verify=False)\n <9> tcp_octets = len(response.content)\n<10> tcp_elapsed = time.time() - start\n<11> assert tcp_octets == size, \"HTTP/TCP response size mismatch\"\n<12> \n<13> # perform HTTP request over QUIC\n<14> if server.http3:\n<15> configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n<16> else:\n<17> configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n<18> start = time.time()\n<19> async with connect(\n<20> server.host,\n<21> server.port,\n<22> configuration=configuration,\n<23> create_protocol=HttpClient,\n<24> ) as protocol:\n<25> protocol = cast(HttpClient, protocol)\n<26> \n<27> http_events = await protocol.get(\n<28> \"https://{}:{}{}\".format(server.host, server.port, path)\n<29> )\n<30> quic_elapsed = time.time() - start\n<31> quic_octets = 0\n<32> for http_event in http_events:\n<33> if isinstance(http_event, DataReceived):\n<34> quic_octets += len(http_event.data)\n<35> assert quic_octets == size, \"HTTP/QUIC response size mismatch\"\n<36> \n<37> print(\" - HTTP/TCP completed in %.3f s\" % tcp_elapsed)\n<38> print(\" - HTTP/QUIC completed in %.3f s\" % quic_elapsed)\n<39> \n<40> if quic_elapsed > 1.1 * tcp_elapsed:\n<41> failures += 1\n<42> print(\" => FAIL\")\n<43> else:\n<44> print(\" => PASS\")"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.interop\n def test_throughput(server: Server, configuration: QuicConfiguration):\n # offset: 1\n if failures == 0:\n server.result |= Result.T\n \n \n===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.h0.connection\n H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ))\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n \n===========unchanged ref 1===========\n at: examples.interop\n Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str=\"/\", result: Result=field(default_factory=lambda: Result(0)))\n \n at: examples.interop.Server\n host: str\n \n port: int = 4433\n \n http3: bool = True\n \n at: http3_client\n HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: http3_client.HttpClient\n get(url: str, headers: Dict={}) -> Deque[H3Event]\n \n at: requests.api\n get(url: Union[Text, bytes], params: Optional[\n Union[\n SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType],\n Tuple[_ParamsMappingKeyType, _ParamsMappingValueType],\n Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]],\n Union[Text, bytes],\n ]\n ]=..., **kwargs) -> Response\n \n at: requests.models.Response\n __attrs__ = [\n \"_content\",\n \"status_code\",\n \"headers\",\n \"url\",\n \"history\",\n \"encoding\",\n \"reason\",\n \"cookies\",\n \"elapsed\",\n \"request\",\n ]\n \n at: time\n time() -> float\n \n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n \n===========changed ref 0===========\n # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n server.result |= Result.three\n \n===========changed ref 1===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 2===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 3===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 4===========\n # module: tests.test_h0\n class H0ConnectionTest(TestCase):\n def test_headers_only(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H0_ALPN},\n - client_options={\"alpn_protocols\": [\"hq-23\"]},\n + server_options={\"alpn_protocols\": H0_ALPN},\n - server_options={\"alpn_protocols\": [\"hq-23\"]},\n ) as (quic_client, quic_server):\n h0_client = H0Connection(quic_client)\n h0_server = H0Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h0_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"HEAD\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n end_stream=True,\n )\n \n # receive request\n events = h0_transfer(quic_client, h0_server)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], HeadersReceived))\n self.assertEqual(\n events[0].headers, [(b\":method\", b\"HEAD\"), (b\":path\", b\"/\")]\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h0_server.send_headers(\n stream_id=stream_id,\n headers=[\n "}}},{"rowIdx":3640,"cells":{"path":{"kind":"string","value":"examples.interop/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <4>: alpn_protocols=H3_ALPN + H0_ALPN,\n alpn_protocols=[\"h3-23\", \"h3-22\", \"hq-23\", \"hq-22\"],\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def run(servers, tests, quic_log=False, secrets_log_file=None) -> None:\n <0> for server in servers:\n <1> for test_name, test_func in tests:\n <2> print(\"\\n=== %s %s ===\\n\" % (server.name, test_name))\n <3> configuration = QuicConfiguration(\n <4> alpn_protocols=[\"h3-23\", \"h3-22\", \"hq-23\", \"hq-22\"],\n <5> is_client=True,\n <6> quic_logger=QuicLogger(),\n <7> secrets_log_file=secrets_log_file,\n <8> )\n <9> if test_name == \"test_throughput\":\n<10> timeout = 60\n<11> else:\n<12> timeout = 5\n<13> try:\n<14> await asyncio.wait_for(\n<15> test_func(server, configuration), timeout=timeout\n<16> )\n<17> except Exception as exc:\n<18> print(exc)\n<19> \n<20> if quic_log:\n<21> with open(\"%s-%s.qlog\" % (server.name, test_name), \"w\") as logger_fp:\n<22> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4)\n<23> \n<24> print(\"\")\n<25> print_result(server)\n<26> \n<27> # print summary\n<28> if len(servers) > 1:\n<29> print(\"SUMMARY\")\n<30> for server in servers:\n<31> print_result(server)\n<32> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h0.connection\n H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ))\n \n at: aioquic.quic.configuration.QuicConfiguration\n quic_logger: Optional[QuicLogger] = None\n \n at: aioquic.quic.logger\n QuicLogger()\n \n at: aioquic.quic.logger.QuicLogger\n to_dict() -> Dict[str, Any]\n \n at: asyncio.tasks\n wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]\n \n at: examples.interop\n print_result(server: Server) -> None\n \n at: examples.interop.Server\n name: str\n \n \n===========unchanged ref 1===========\n at: json\n dump(obj: Any, fp: IO[str], *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> None\n \n \n===========changed ref 0===========\n # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n server.result |= Result.three\n \n===========changed ref 1===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 2===========\n # module: examples.interop\n def test_throughput(server: Server, configuration: QuicConfiguration):\n failures = 0\n \n for size in [5000000, 10000000]:\n print(\"Testing %d bytes download\" % size)\n path = \"/%d\" % size\n \n # perform HTTP request over TCP\n start = time.time()\n response = requests.get(\"https://\" + server.host + path, verify=False)\n tcp_octets = len(response.content)\n tcp_elapsed = time.time() - start\n assert tcp_octets == size, \"HTTP/TCP response size mismatch\"\n \n # perform HTTP request over QUIC\n if server.http3:\n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n else:\n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n start = time.time()\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n http_events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, path)\n )\n quic_elapsed = time.time() - start\n quic_octets = 0\n for http_event in http_events:\n if isinstance(http_event, DataReceived):\n quic_octets += len(http_event.data)\n assert quic_octets == size, \"HTTP/QUIC response size mismatch\"\n \n print(\" - HTTP/TCP completed in %.3f s\" % tcp_elapsed)\n print(\" - HTTP/QUIC completed in %.3f s\" % quic_elapsed)\n \n if quic_elapsed > 1.1 * tcp_elapsed:\n failures += 1\n print(\" => FAIL\")\n else:\n print(\" => PASS\")\n \n if failures == 0:\n server.result\n===========changed ref 3===========\n # module: examples.interop\n def test_throughput(server: Server, configuration: QuicConfiguration):\n # offset: 1\n print(\" => FAIL\")\n else:\n print(\" => PASS\")\n \n if failures == 0:\n server.result |= Result.T\n \n===========changed ref 4===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 5===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + "}}},{"rowIdx":3641,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_request"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H3_ALPN},\n client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2>: server_options={\"alpn_protocols\": H3_ALPN},\n server_options={\"alpn_protocols\": [\"h3-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_client = H3Connection(quic_client)\n <5> h3_server = H3Connection(quic_server)\n <6> \n <7> # make first request\n <8> self._make_request(h3_client, h3_server)\n <9> \n<10> # make second request\n<11> self._make_request(h3_client, h3_server)\n<12> \n<13> # make third request -> dynamic table\n<14> self._make_request(h3_client, h3_server)\n<15> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3.H3ConnectionTest\n maxDiff = None\n \n _make_request(h3_client, h3_server)\n \n \n===========changed ref 0===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 1===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 2===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 3===========\n # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n server.result |= Result.three\n \n===========changed ref 4===========\n # module: examples.interop\n def run(servers, tests, quic_log=False, secrets_log_file=None) -> None:\n for server in servers:\n for test_name, test_func in tests:\n print(\"\\n=== %s %s ===\\n\" % (server.name, test_name))\n configuration = QuicConfiguration(\n + alpn_protocols=H3_ALPN + H0_ALPN,\n - alpn_protocols=[\"h3-23\", \"h3-22\", \"hq-23\", \"hq-22\"],\n is_client=True,\n quic_logger=QuicLogger(),\n secrets_log_file=secrets_log_file,\n )\n if test_name == \"test_throughput\":\n timeout = 60\n else:\n timeout = 5\n try:\n await asyncio.wait_for(\n test_func(server, configuration), timeout=timeout\n )\n except Exception as exc:\n print(exc)\n \n if quic_log:\n with open(\"%s-%s.qlog\" % (server.name, test_name), \"w\") as logger_fp:\n json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4)\n \n print(\"\")\n print_result(server)\n \n # print summary\n if len(servers) > 1:\n print(\"SUMMARY\")\n for server in servers:\n print_result(server)\n \n===========changed ref 5===========\n # module: examples.interop\n def test_throughput(server: Server, configuration: QuicConfiguration):\n failures = 0\n \n for size in [5000000, 10000000]:\n print(\"Testing %d bytes download\" % size)\n path = \"/%d\" % size\n \n # perform HTTP request over TCP\n start = time.time()\n response = requests.get(\"https://\" + server.host + path, verify=False)\n tcp_octets = len(response.content)\n tcp_elapsed = time.time() - start\n assert tcp_octets == size, \"HTTP/TCP response size mismatch\"\n \n # perform HTTP request over QUIC\n if server.http3:\n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n else:\n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n start = time.time()\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n http_events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, path)\n )\n quic_elapsed = time.time() - start\n quic_octets = 0\n for http_event in http_events:\n if isinstance(http_event, DataReceived):\n quic_octets += len(http_event.data)\n assert quic_octets == size, \"HTTP/QUIC response size mismatch\"\n \n print(\" - HTTP/TCP completed in %.3f s\" % tcp_elapsed)\n print(\" - HTTP/QUIC completed in %.3f s\" % quic_elapsed)\n \n if quic_elapsed > 1.1 * tcp_elapsed:\n failures += 1\n print(\" => FAIL\")\n else:\n print(\" => PASS\")\n \n if failures == 0:\n server.result\n===========changed ref 6===========\n # module: examples.interop\n def test_throughput(server: Server, configuration: QuicConfiguration):\n # offset: 1\n print(\" => FAIL\")\n else:\n print(\" => PASS\")\n \n if failures == 0:\n server.result |= Result.T\n "}}},{"rowIdx":3642,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_request_headers_only"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H3_ALPN},\n client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2>: server_options={\"alpn_protocols\": H3_ALPN},\n server_options={\"alpn_protocols\": [\"h3-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_headers_only(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_client = H3Connection(quic_client)\n <5> h3_server = H3Connection(quic_server)\n <6> \n <7> # send request\n <8> stream_id = quic_client.get_next_available_stream_id()\n <9> h3_client.send_headers(\n<10> stream_id=stream_id,\n<11> headers=[\n<12> (b\":method\", b\"HEAD\"),\n<13> (b\":scheme\", b\"https\"),\n<14> (b\":authority\", b\"localhost\"),\n<15> (b\":path\", b\"/\"),\n<16> (b\"x-foo\", b\"client\"),\n<17> ],\n<18> end_stream=True,\n<19> )\n<20> \n<21> # receive request\n<22> events = h3_transfer(quic_client, h3_server)\n<23> self.assertEqual(\n<24> events,\n<25> [\n<26> HeadersReceived(\n<27> headers=[\n<28> (b\":method\", b\"HEAD\"),\n<29> (b\":scheme\", b\"https\"),\n<30> (b\":authority\", b\"localhost\"),\n<31> (b\":path\", b\"/\"),\n<32> (b\"x-foo\", b\"client\"),\n<33> ],\n<34> stream_id=stream_id,\n<35> stream_ended=True,\n<36> )\n<37> ],\n<38> )\n<39> \n<40> # send response\n<41> h3_server.send_headers(\n<42> stream_id=stream_id,\n<43> headers=[\n<44> (b\":status\", b\"200\"),\n<45> (b\"content-type\", b\"text/html; charset=utf-8\"),\n<46> (b"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_headers_only(self):\n # offset: 1\n ],\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n (b\"x-foo\", b\"server\"),\n ],\n stream_id=stream_id,\n stream_ended=True,\n )\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.events\n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: aioquic.h3.events.HeadersReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n push_id: Optional[int] = None\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # make first request\n self._make_request(h3_client, h3_server)\n \n # make second request\n self._make_request(h3_client, h3_server)\n \n # make third request -> dynamic table\n self._make_request(h3_client, h3_server)\n \n===========changed ref 1===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 2===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 3===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 4===========\n # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n server.result |= Result.three\n \n===========changed ref 5===========\n # module: examples.interop\n def run(servers, tests, quic_log=False, secrets_log_file=None) -> None:\n for server in servers:\n for test_name, test_func in tests:\n print(\"\\n=== %s %s ===\\n\" % (server.name, test_name))\n configuration = QuicConfiguration(\n + alpn_protocols=H3_ALPN + H0_ALPN,\n - alpn_protocols=[\"h3-23\", \"h3-22\", \"hq-23\", \"hq-22\"],\n is_client=True,\n quic_logger=QuicLogger(),\n secrets_log_file=secrets_log_file,\n )\n if test_name == \"test_throughput\":\n timeout = 60\n else:\n timeout = 5\n try:\n await asyncio.wait_for(\n test_func(server, configuration), timeout=timeout\n )\n except Exception as exc:\n print(exc)\n \n if quic_log:\n with open(\"%s-%s.qlog\" % (server.name, test_name), \"w\") as logger_fp:\n json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4)\n \n print(\"\")\n print_result(server)\n \n # print summary\n if len(servers) > 1:\n print(\"SUMMARY\")\n for server in servers:\n print_result(server)\n "}}},{"rowIdx":3643,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_request_with_server_push_max_push_id"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H3_ALPN},\n client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2>: server_options={\"alpn_protocols\": H3_ALPN},\n server_options={\"alpn_protocols\": [\"h3-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_server_push_max_push_id(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_client = H3Connection(quic_client)\n <5> h3_server = H3Connection(quic_server)\n <6> \n <7> # send request\n <8> stream_id = quic_client.get_next_available_stream_id()\n <9> h3_client.send_headers(\n<10> stream_id=stream_id,\n<11> headers=[\n<12> (b\":method\", b\"GET\"),\n<13> (b\":scheme\", b\"https\"),\n<14> (b\":authority\", b\"localhost\"),\n<15> (b\":path\", b\"/\"),\n<16> ],\n<17> end_stream=True,\n<18> )\n<19> \n<20> # receive request\n<21> events = h3_transfer(quic_client, h3_server)\n<22> self.assertEqual(\n<23> events,\n<24> [\n<25> HeadersReceived(\n<26> headers=[\n<27> (b\":method\", b\"GET\"),\n<28> (b\":scheme\", b\"https\"),\n<29> (b\":authority\", b\"localhost\"),\n<30> (b\":path\", b\"/\"),\n<31> ],\n<32> stream_id=stream_id,\n<33> stream_ended=True,\n<34> )\n<35> ],\n<36> )\n<37> \n<38> # send push promises\n<39> for i in range(0, 8):\n<40> h3_server.send_push_promise(\n<41> stream_id=stream_id,\n<42> headers=[\n<43> (b\":method\", b\"GET\"),\n<44> (b\":scheme\", b\"https\"),\n<45> (b\":authority\", b\"localhost\"),\n<46> (b\":path\", \"/"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_server_push_max_push_id(self):\n # offset: 1\n ],\n )\n \n # send one too many\n with self.assertRaises(NoAvailablePushIDError):\n h3_server.send_push_promise(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/8.css\"),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_push_promise(stream_id: int, headers: Headers) -> int\n \n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.events\n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: aioquic.h3.exceptions\n NoAvailablePushIDError(*args: object)\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # make first request\n self._make_request(h3_client, h3_server)\n \n # make second request\n self._make_request(h3_client, h3_server)\n \n # make third request -> dynamic table\n self._make_request(h3_client, h3_server)\n \n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_headers_only(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"HEAD\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n (b\"x-foo\", b\"client\"),\n ],\n end_stream=True,\n )\n \n # receive request\n events = h3_transfer(quic_client, h3_server)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":method\", b\"HEAD\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n (b\"x-foo\", b\"client\"),\n ],\n stream_id=stream_id,\n stream_ended=True,\n )\n ],\n )\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n (b\"x-foo\", b\"\n===========changed ref 2===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_headers_only(self):\n # offset: 1\n b\"content-type\", b\"text/html; charset=utf-8\"),\n (b\"x-foo\", b\"server\"),\n ],\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n (b\"x-foo\", b\"server\"),\n ],\n stream_id=stream_id,\n stream_ended=True,\n )\n ],\n )\n \n===========changed ref 3===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 4===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 5===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 6===========\n # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n server.result |= Result.three\n "}}},{"rowIdx":3644,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_uni_stream_grease"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H3_ALPN},\n client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2>: server_options={\"alpn_protocols\": H3_ALPN},\n server_options={\"alpn_protocols\": [\"h3-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_grease(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_server = H3Connection(quic_server)\n <5> \n <6> quic_client.send_stream_data(\n <7> 14, b\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfeGREASE is the word\"\n <8> )\n <9> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_server_push_max_push_id(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n end_stream=True,\n )\n \n # receive request\n events = h3_transfer(quic_client, h3_server)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n stream_id=stream_id,\n stream_ended=True,\n )\n ],\n )\n \n # send push promises\n for i in range(0, 8):\n h3_server.send_push_promise(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", \"/{}.css\".format(i).\n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_server_push_max_push_id(self):\n # offset: 1\n https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", \"/{}.css\".format(i).encode(\"ascii\")),\n ],\n )\n \n # send one too many\n with self.assertRaises(NoAvailablePushIDError):\n h3_server.send_push_promise(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/8.css\"),\n ],\n )\n \n===========changed ref 2===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # make first request\n self._make_request(h3_client, h3_server)\n \n # make second request\n self._make_request(h3_client, h3_server)\n \n # make third request -> dynamic table\n self._make_request(h3_client, h3_server)\n \n===========changed ref 3===========\n # module: aioquic.h0.connection\n + H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n \n===========changed ref 4===========\n # module: aioquic.h3.connection\n logger = logging.getLogger(\"http3\")\n \n + H3_ALPN = [\"h3-23\", \"h3-22\"]\n + \n===========changed ref 5===========\n # module: examples.interop\n def test_http_0(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H0_ALPN\n - configuration.alpn_protocols = [\"hq-23\", \"hq-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n \n===========changed ref 6===========\n # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n if server.path is None:\n return\n \n + configuration.alpn_protocols = H3_ALPN\n - configuration.alpn_protocols = [\"h3-23\", \"h3-22\"]\n async with connect(\n server.host,\n server.port,\n configuration=configuration,\n create_protocol=HttpClient,\n ) as protocol:\n protocol = cast(HttpClient, protocol)\n \n # perform HTTP request\n events = await protocol.get(\n \"https://{}:{}{}\".format(server.host, server.port, server.path)\n )\n if events and isinstance(events[0], HeadersReceived):\n server.result |= Result.D\n server.result |= Result.three\n "}}},{"rowIdx":3645,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_request_with_trailers"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H3_ALPN},\n client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2>: server_options={\"alpn_protocols\": H3_ALPN},\n server_options={\"alpn_protocols\": [\"h3-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_trailers(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_client = H3Connection(quic_client)\n <5> h3_server = H3Connection(quic_server)\n <6> \n <7> # send request with trailers\n <8> stream_id = quic_client.get_next_available_stream_id()\n <9> h3_client.send_headers(\n<10> stream_id=stream_id,\n<11> headers=[\n<12> (b\":method\", b\"GET\"),\n<13> (b\":scheme\", b\"https\"),\n<14> (b\":authority\", b\"localhost\"),\n<15> (b\":path\", b\"/\"),\n<16> ],\n<17> end_stream=False,\n<18> )\n<19> h3_client.send_headers(\n<20> stream_id=stream_id,\n<21> headers=[(b\"x-some-trailer\", b\"foo\")],\n<22> end_stream=True,\n<23> )\n<24> \n<25> # receive request\n<26> events = h3_transfer(quic_client, h3_server)\n<27> self.assertEqual(\n<28> events,\n<29> [\n<30> HeadersReceived(\n<31> headers=[\n<32> (b\":method\", b\"GET\"),\n<33> (b\":scheme\", b\"https\"),\n<34> (b\":authority\", b\"localhost\"),\n<35> (b\":path\", b\"/\"),\n<36> ],\n<37> stream_id=stream_id,\n<38> stream_ended=False,\n<39> ),\n<40> HeadersReceived(\n<41> headers=[(b\"x-some-trailer\", b\"foo\")],\n<42> stream_id=stream_id,\n<43> stream_ended=True,\n<44> ),\n<45> ]"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_trailers(self):\n # offset: 1\n )\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n end_stream=False,\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=False,\n )\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[(b\"x-some-trailer\", b\"bar\")],\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n stream_id=stream_id,\n stream_ended=False,\n ),\n DataReceived(\n data=b\"hello\",\n stream_id=stream_id,\n stream_ended=False,\n ),\n HeadersReceived(\n headers=[(b\"x-some-trailer\", b\"bar\")],\n stream_id=stream_id,\n stream_ended=True,\n ),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n push_id: Optional[int] = None\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_grease(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_server = H3Connection(quic_server)\n \n quic_client.send_stream_data(\n 14, b\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfeGREASE is the word\"\n )\n self.assertEqual(h3_transfer(quic_client, h3_server), [])\n \n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_server_push_max_push_id(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n end_stream=True,\n )\n \n # receive request\n events = h3_transfer(quic_client, h3_server)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n stream_id=stream_id,\n stream_ended=True,\n )\n ],\n )\n \n # send push promises\n for i in range(0, 8):\n h3_server.send_push_promise(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", \"/{}.css\".format(i).\n===========changed ref 2===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_server_push_max_push_id(self):\n # offset: 1\n https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", \"/{}.css\".format(i).encode(\"ascii\")),\n ],\n )\n \n # send one too many\n with self.assertRaises(NoAvailablePushIDError):\n h3_server.send_push_promise(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/8.css\"),\n ],\n )\n \n===========changed ref 3===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # make first request\n self._make_request(h3_client, h3_server)\n \n # make second request\n self._make_request(h3_client, h3_server)\n \n # make third request -> dynamic table\n self._make_request(h3_client, h3_server)\n "}}},{"rowIdx":3646,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_uni_stream_type"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"755560878bf95fd828557b13ecac8b56af606b59"},"commit_message":{"kind":"string","value":"[http] add H0_ALPN and H3_ALPN definitions"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": H3_ALPN},\n client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2>: server_options={\"alpn_protocols\": H3_ALPN},\n server_options={\"alpn_protocols\": [\"h3-23\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-23\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-23\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_server = H3Connection(quic_server)\n <5> \n <6> # unknown stream type 9\n <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n <8> self.assertEqual(stream_id, 2)\n <9> quic_client.send_stream_data(stream_id, b\"\\x09\")\n<10> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<11> self.assertEqual(list(h3_server._stream.keys()), [2])\n<12> self.assertEqual(h3_server._stream[2].buffer, b\"\")\n<13> self.assertEqual(h3_server._stream[2].stream_type, 9)\n<14> \n<15> # unknown stream type 64, one byte at a time\n<16> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n<17> self.assertEqual(stream_id, 6)\n<18> \n<19> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<20> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<21> self.assertEqual(list(h3_server._stream.keys()), [2, 6])\n<22> self.assertEqual(h3_server._stream[2].buffer, b\"\")\n<23> self.assertEqual(h3_server._stream[2].stream_type, 9)\n<24> self.assertEqual(h3_server._stream[6].buffer, b\"\\x40\")\n<25> self.assertEqual(h3_server._stream[6].stream_type,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n # offset: 1\n \n quic_client.send_stream_data(stream_id, b\"\\x40\")\n self.assertEqual(h3_transfer(quic_client, h3_server), [])\n self.assertEqual(list(h3_server._stream.keys()), [2, 6])\n self.assertEqual(h3_server._stream[2].buffer, b\"\")\n self.assertEqual(h3_server._stream[2].stream_type, 9)\n self.assertEqual(h3_server._stream[6].buffer, b\"\")\n self.assertEqual(h3_server._stream[6].stream_type, 64)\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._stream: Dict[int, H3Stream] = {}\n \n at: aioquic.h3.connection.H3Stream.__init__\n self.buffer = b\"\"\n \n self.stream_type: Optional[int] = None\n \n at: tests.test_connection\n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_grease(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_server = H3Connection(quic_server)\n \n quic_client.send_stream_data(\n 14, b\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfeGREASE is the word\"\n )\n self.assertEqual(h3_transfer(quic_client, h3_server), [])\n \n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_trailers(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": H3_ALPN},\n - client_options={\"alpn_protocols\": [\"h3-23\"]},\n + server_options={\"alpn_protocols\": H3_ALPN},\n - server_options={\"alpn_protocols\": [\"h3-23\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request with trailers\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n end_stream=False,\n )\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[(b\"x-some-trailer\", b\"foo\")],\n end_stream=True,\n )\n \n # receive request\n events = h3_transfer(quic_client, h3_server)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n stream_id=stream_id,\n stream_ended=False,\n ),\n HeadersReceived(\n headers=[(b\"x-some-trailer\", b\"foo\")],\n stream_id=stream_id,\n stream_ended=True,\n ),\n ],\n )\n \n \n===========changed ref 2===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_request_with_trailers(self):\n # offset: 1\n stream_id=stream_id,\n stream_ended=True,\n ),\n ],\n )\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n end_stream=False,\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=False,\n )\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[(b\"x-some-trailer\", b\"bar\")],\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(\n events,\n [\n HeadersReceived(\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n stream_id=stream_id,\n stream_ended=False,\n ),\n DataReceived(\n data=b\"hello\",\n stream_id=stream_id,\n stream_ended=False,\n ),\n HeadersReceived(\n headers=[(b\"x-some-trailer\", b\"bar\")],\n stream_id=stream_id,\n stream_ended=True,\n ),\n ],\n )\n "}}},{"rowIdx":3647,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8db11b954ca3992373a98675e322d8cc9511e1f7"},"commit_message":{"kind":"string","value":"[interop] add a test for QPACK dynamic tables"},"ground_truth":{"kind":"string","value":"<10>: self._decoder_bytes_received = 0\n self._decoder_bytes_sent = 0\n<11>: self._encoder_bytes_received = 0\n self._encoder_bytes_sent = 0\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n <0> self._max_table_capacity = 4096\n <1> self._blocked_streams = 16\n <2> \n <3> self._is_client = quic.configuration.is_client\n <4> self._is_done = False\n <5> self._quic = quic\n <6> self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger\n <7> self._decoder = pylsqpack.Decoder(\n <8> self._max_table_capacity, self._blocked_streams\n <9> )\n<10> self._encoder = pylsqpack.Encoder()\n<11> self._stream: Dict[int, H3Stream] = {}\n<12> \n<13> self._max_push_id: Optional[int] = 8 if self._is_client else None\n<14> self._next_push_id: int = 0\n<15> \n<16> self._local_control_stream_id: Optional[int] = None\n<17> self._local_decoder_stream_id: Optional[int] = None\n<18> self._local_encoder_stream_id: Optional[int] = None\n<19> \n<20> self._peer_control_stream_id: Optional[int] = None\n<21> self._peer_decoder_stream_id: Optional[int] = None\n<22> self._peer_encoder_stream_id: Optional[int] = None\n<23> \n<24> self._init_connection()\n<25> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Stream(stream_id: int)\n \n at: aioquic.h3.connection.H3Connection._decode_headers\n self._decoder_bytes_sent += len(decoder)\n \n at: aioquic.h3.connection.H3Connection._encode_headers\n self._encoder_bytes_sent += len(encoder)\n \n at: aioquic.h3.connection.H3Connection._handle_control_frame\n self._max_push_id = parse_max_push_id(frame_data)\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL)\n \n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.connection.H3Connection._receive_stream_data_uni\n self._peer_control_stream_id = stream.stream_id\n \n self._decoder_bytes_received += len(data)\n \n self._encoder_bytes_received += len(data)\n \n at: aioquic.h3.connection.H3Connection.handle_event\n self._is_done = True\n \n at: aioquic.h3.connection.H3Connection.send_push_promise\n self._next_push_id += 1\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n \n===========unchanged ref 1===========\n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n at: aioquic.quic.connection\n QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._quic_logger: Optional[QuicLoggerTrace] = None\n self._quic_logger = configuration.quic_logger.start_trace(\n is_client=configuration.is_client, odcid=logger_connection_id\n )\n \n at: aioquic.quic.connection.QuicConnection._close_end\n self._quic_logger = None\n \n at: aioquic.quic.logger\n QuicLoggerTrace(*, is_client: bool, odcid: bytes)\n \n at: typing\n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":3648,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._decode_headers"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8db11b954ca3992373a98675e322d8cc9511e1f7"},"commit_message":{"kind":"string","value":"[interop] add a test for QPACK dynamic tables"},"ground_truth":{"kind":"string","value":"<10>: self._decoder_bytes_sent += len(decoder)\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _decode_headers(self, stream_id: int, frame_data: Optional[bytes]) -> Headers:\n <0> \"\"\"\n <1> Decode a HEADERS block and send decoder updates on the decoder stream.\n <2> \n <3> This is called with frame_data=None when a stream becomes unblocked.\n <4> \"\"\"\n <5> try:\n <6> if frame_data is None:\n <7> decoder, headers = self._decoder.resume_header(stream_id)\n <8> else:\n <9> decoder, headers = self._decoder.feed_header(stream_id, frame_data)\n<10> self._quic.send_stream_data(self._local_decoder_stream_id, decoder)\n<11> except pylsqpack.DecompressionFailed as exc:\n<12> raise QpackDecompressionFailed() from exc\n<13> \n<14> return headers\n<15> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.buffer\n encode_uint_var(value: int) -> bytes\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n self._decoder = pylsqpack.Decoder(\n self._max_table_capacity, self._blocked_streams\n )\n \n self._decoder_bytes_sent = 0\n \n at: aioquic.h3.events\n Headers = List[Tuple[bytes, bytes]]\n \n at: aioquic.quic.connection.QuicConnection\n get_next_available_stream_id(is_unidirectional=False) -> int\n \n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 4096\n self._blocked_streams = 16\n \n self._is_client = quic.configuration.is_client\n self._is_done = False\n self._quic = quic\n self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger\n self._decoder = pylsqpack.Decoder(\n self._max_table_capacity, self._blocked_streams\n )\n + self._decoder_bytes_received = 0\n + self._decoder_bytes_sent = 0\n self._encoder = pylsqpack.Encoder()\n + self._encoder_bytes_received = 0\n + self._encoder_bytes_sent = 0\n self._stream: Dict[int, H3Stream] = {}\n \n self._max_push_id: Optional[int] = 8 if self._is_client else None\n self._next_push_id: int = 0\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n \n self._init_connection()\n "}}},{"rowIdx":3649,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._encode_headers"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8db11b954ca3992373a98675e322d8cc9511e1f7"},"commit_message":{"kind":"string","value":"[interop] add a test for QPACK dynamic tables"},"ground_truth":{"kind":"string","value":" <4>: self._encoder_bytes_sent += len(encoder)\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _encode_headers(self, stream_id: int, headers: Headers) -> bytes:\n <0> \"\"\"\n <1> Encode a HEADERS block and send encoder updates on the encoder stream.\n <2> \"\"\"\n <3> encoder, frame_data = self._encoder.encode(stream_id, 0, headers)\n <4> self._quic.send_stream_data(self._local_encoder_stream_id, encoder)\n <5> return frame_data\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection\n QpackDecompressionFailed(reason_phrase: str=\"\")\n \n at: aioquic.h3.connection.H3Connection._decode_headers\n decoder, headers = self._decoder.feed_header(stream_id, frame_data)\n decoder, headers = self._decoder.resume_header(stream_id)\n \n at: aioquic.h3.events\n Headers = List[Tuple[bytes, bytes]]\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _decode_headers(self, stream_id: int, frame_data: Optional[bytes]) -> Headers:\n \"\"\"\n Decode a HEADERS block and send decoder updates on the decoder stream.\n \n This is called with frame_data=None when a stream becomes unblocked.\n \"\"\"\n try:\n if frame_data is None:\n decoder, headers = self._decoder.resume_header(stream_id)\n else:\n decoder, headers = self._decoder.feed_header(stream_id, frame_data)\n + self._decoder_bytes_sent += len(decoder)\n self._quic.send_stream_data(self._local_decoder_stream_id, decoder)\n except pylsqpack.DecompressionFailed as exc:\n raise QpackDecompressionFailed() from exc\n \n return headers\n \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 4096\n self._blocked_streams = 16\n \n self._is_client = quic.configuration.is_client\n self._is_done = False\n self._quic = quic\n self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger\n self._decoder = pylsqpack.Decoder(\n self._max_table_capacity, self._blocked_streams\n )\n + self._decoder_bytes_received = 0\n + self._decoder_bytes_sent = 0\n self._encoder = pylsqpack.Encoder()\n + self._encoder_bytes_received = 0\n + self._encoder_bytes_sent = 0\n self._stream: Dict[int, H3Stream] = {}\n \n self._max_push_id: Optional[int] = 8 if self._is_client else None\n self._next_push_id: int = 0\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n \n self._init_connection()\n "}}},{"rowIdx":3650,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data_uni"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8db11b954ca3992373a98675e322d8cc9511e1f7"},"commit_message":{"kind":"string","value":"[interop] add a test for QPACK dynamic tables"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data_uni(\n self, stream: H3Stream, data: bytes, stream_ended: bool\n ) -> List[H3Event]:\n <0> http_events: List[H3Event] = []\n <1> \n <2> stream.buffer += data\n <3> if stream_ended:\n <4> stream.ended = True\n <5> \n <6> buf = Buffer(data=stream.buffer)\n <7> consumed = 0\n <8> unblocked_streams: Set[int] = set()\n <9> \n<10> while stream.stream_type == StreamType.PUSH or not buf.eof():\n<11> # fetch stream type for unidirectional streams\n<12> if stream.stream_type is None:\n<13> try:\n<14> stream.stream_type = buf.pull_uint_var()\n<15> except BufferReadError:\n<16> break\n<17> consumed = buf.tell()\n<18> \n<19> # check unicity\n<20> if stream.stream_type == StreamType.CONTROL:\n<21> if self._peer_control_stream_id is not None:\n<22> raise StreamCreationError(\"Only one control stream is allowed\")\n<23> self._peer_control_stream_id = stream.stream_id\n<24> elif stream.stream_type == StreamType.QPACK_DECODER:\n<25> if self._peer_decoder_stream_id is not None:\n<26> raise StreamCreationError(\n<27> \"Only one QPACK decoder stream is allowed\"\n<28> )\n<29> self._peer_decoder_stream_id = stream.stream_id\n<30> elif stream.stream_type == StreamType.QPACK_ENCODER:\n<31> if self._peer_encoder_stream_id is not None:\n<32> raise StreamCreationError(\n<33> \"Only one QPACK encoder stream is allowed\"\n<34> )\n<35> self._peer_encoder_stream_id = stream.stream_id\n<36> \n<37> if stream.stream_type == StreamType.CONTROL:\n<38> # fetch next frame\n<39> try:\n<40> frame_type = buf.pull_uint_var()\n<41> frame_length"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data_uni(\n self, stream: H3Stream, data: bytes, stream_ended: bool\n ) -> List[H3Event]:\n # offset: 1\n frame_data = buf.pull_bytes(frame_length)\n except BufferReadError:\n break\n consumed = buf.tell()\n \n self._handle_control_frame(frame_type, frame_data)\n elif stream.stream_type == StreamType.PUSH:\n # fetch push id\n if stream.push_id is None:\n try:\n stream.push_id = buf.pull_uint_var()\n except BufferReadError:\n break\n consumed = buf.tell()\n \n # remove processed data from buffer\n stream.buffer = stream.buffer[consumed:]\n \n return self._receive_request_or_push_data(stream, b\"\", stream_ended)\n elif stream.stream_type == StreamType.QPACK_DECODER:\n # feed unframed data to decoder\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n try:\n self._encoder.feed_decoder(data)\n except pylsqpack.DecoderStreamError as exc:\n raise QpackDecoderStreamError() from exc\n elif stream.stream_type == StreamType.QPACK_ENCODER:\n # feed unframed data to encoder\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n try:\n unblocked_streams.update(self._decoder.feed_encoder(data))\n except pylsqpack.EncoderStreamError as exc:\n raise QpackEncoderStreamError() from exc\n else:\n # unknown stream type, discard data\n buf.seek(buf.capacity)\n consumed = buf.tell()\n \n # remove processed data from buffer\n stream.buffer = stream.buffer[consumed:]\n \n # process unblocked streams\n for stream_id in unblocked_streams\n===========below chunk 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data_uni(\n self, stream: H3Stream, data: bytes, stream_ended: bool\n ) -> List[H3Event]:\n # offset: 2\n stream.buffer = stream.buffer[consumed:]\n \n # process unblocked streams\n for stream_id in unblocked_streams:\n stream = self._stream[stream_id]\n \n # resume headers\n http_events.extend(\n self._handle_request_or_push_frame(\n frame_type=FrameType.HEADERS,\n frame_data=None,\n stream=stream,\n stream_ended=stream.ended and not stream.buffer,\n )\n )\n stream.blocked = False\n stream.blocked_frame_size = None\n \n # resume processing\n if stream.buffer:\n http_events.extend(\n self._receive_request_or_push_data(stream, b\"\", stream.ended)\n )\n \n return http_events\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n seek(pos: int) -> None\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n QpackDecoderStreamError(reason_phrase: str=\"\")\n \n QpackEncoderStreamError(reason_phrase: str=\"\")\n \n StreamCreationError(reason_phrase: str=\"\")\n \n H3Stream(stream_id: int)\n \n at: aioquic.h3.connection.H3Connection\n _handle_control_frame(frame_type: int, frame_data: bytes) -> None\n \n _handle_request_or_push_frame(frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool) -> List[H3Event]\n \n _receive_request_or_push_data(stream: H3Stream, data: bytes, stream_ended: bool) -> List[H3Event]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._decoder = pylsqpack.Decoder(\n self._max_table_capacity, self._blocked_streams\n )\n \n self._decoder_bytes_received = 0\n \n self._encoder = pylsqpack.Encoder()\n \n self._encoder_bytes_received = 0\n \n self._stream: Dict[int, H3Stream] = {}\n \n self._peer_control_stream_id: Optional[int] = None\n \n \n===========unchanged ref 1===========\n self._peer_decoder_stream_id: Optional[int] = None\n \n self._peer_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.connection.H3Connection._receive_request_or_push_data\n http_events: List[H3Event] = []\n \n consumed = buf.tell()\n consumed = 0\n \n at: aioquic.h3.connection.H3Stream.__init__\n self.blocked = False\n \n self.blocked_frame_size: Optional[int] = None\n \n self.buffer = b\"\"\n \n self.ended = False\n \n self.push_id: Optional[int] = None\n \n self.stream_id = stream_id\n \n self.stream_type: Optional[int] = None\n \n at: aioquic.h3.events\n H3Event()\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n Set = _alias(set, 1, inst=False, name='Set')\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _encode_headers(self, stream_id: int, headers: Headers) -> bytes:\n \"\"\"\n Encode a HEADERS block and send encoder updates on the encoder stream.\n \"\"\"\n encoder, frame_data = self._encoder.encode(stream_id, 0, headers)\n + self._encoder_bytes_sent += len(encoder)\n self._quic.send_stream_data(self._local_encoder_stream_id, encoder)\n return frame_data\n \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _decode_headers(self, stream_id: int, frame_data: Optional[bytes]) -> Headers:\n \"\"\"\n Decode a HEADERS block and send decoder updates on the decoder stream.\n \n This is called with frame_data=None when a stream becomes unblocked.\n \"\"\"\n try:\n if frame_data is None:\n decoder, headers = self._decoder.resume_header(stream_id)\n else:\n decoder, headers = self._decoder.feed_header(stream_id, frame_data)\n + self._decoder_bytes_sent += len(decoder)\n self._quic.send_stream_data(self._local_decoder_stream_id, decoder)\n except pylsqpack.DecompressionFailed as exc:\n raise QpackDecompressionFailed() from exc\n \n return headers\n "}}},{"rowIdx":3651,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"116e47ffcc9255f3b715e327834e11fa628352f2"},"commit_message":{"kind":"string","value":"[tls] verify max_early_data value is the expected one"},"ground_truth":{"kind":"string","value":"<13>: self.max_early_data = max_early_data\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n + max_early_data: Optional[int] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.cadata: Optional[bytes] = None\n <3> self.cafile: Optional[str] = None\n <4> self.capath: Optional[str] = None\n <5> self.certificate: Optional[x509.Certificate] = None\n <6> self.certificate_chain: List[x509.Certificate] = []\n <7> self.certificate_private_key: Optional[\n <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <9> ] = None\n<10> self.early_data_accepted = False\n<11> self.handshake_extensions: List[Extension] = []\n<12> self.key_schedule: Optional[KeySchedule] = None\n<13> self.received_extensions: Optional[List[Extension]] = None\n<14> self.session_ticket: Optional[SessionTicket] = None\n<15> self.server_name: Optional[str] = None\n<16> \n<17> # callbacks\n<18> self.alpn_cb: Optional[AlpnHandler] = None\n<19> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<20> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n<21> self.update_traffic_key_cb: Callable[\n<22> [Direction, Epoch, CipherSuite, bytes], None\n<23> ] = lambda d, e, c, s: None\n<24> \n<25> # supported parameters\n<26> self._cipher_suites = [\n<27> CipherSuite.AES_256_GCM_SHA384,\n<28> CipherSuite.AES_128_GCM_SHA256,\n<29> CipherSuite.CHACHA20_POLY1305_SHA256,\n<30> ]\n<31> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n + max_early_data: Optional[int] = None,\n ):\n # offset: 1\n self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Extension = Tuple[int, bytes]\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n AlpnHandler = Callable[[str], None]\n \n \n===========unchanged ref 1===========\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n "}}},{"rowIdx":3652,"cells":{"path":{"kind":"string","value":"aioquic.quic.connection/QuicConnection._initialize"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"116e47ffcc9255f3b715e327834e11fa628352f2"},"commit_message":{"kind":"string","value":"[tls] verify max_early_data value is the expected one"},"ground_truth":{"kind":"string","value":" <1>: self.tls = tls.Context(\n is_client=self._is_client,\n logger=self._logger,\n max_early_data=None if self._is_client else MAX_EARLY_DATA,\n )\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n<28>: if session_ticket.max_early_data_size == MAX_EARLY_DATA:\n if session_ticket.max_early_data_size == 0xFFFFFFFF:\n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n <0> # TLS\n <1> self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n <2> self.tls.alpn_protocols = self._configuration.alpn_protocols\n <3> self.tls.cadata = self._configuration.cadata\n <4> self.tls.cafile = self._configuration.cafile\n <5> self.tls.capath = self._configuration.capath\n <6> self.tls.certificate = self._configuration.certificate\n <7> self.tls.certificate_chain = self._configuration.certificate_chain\n <8> self.tls.certificate_private_key = self._configuration.private_key\n <9> self.tls.handshake_extensions = [\n<10> (\n<11> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n<12> self._serialize_transport_parameters(),\n<13> )\n<14> ]\n<15> self.tls.server_name = self._configuration.server_name\n<16> \n<17> # TLS session resumption\n<18> session_ticket = self._configuration.session_ticket\n<19> if (\n<20> self._is_client\n<21> and session_ticket is not None\n<22> and session_ticket.is_valid\n<23> and session_ticket.server_name == self._configuration.server_name\n<24> ):\n<25> self.tls.session_ticket = self._configuration.session_ticket\n<26> \n<27> # parse saved QUIC transport parameters - for 0-RTT\n<28> if session_ticket.max_early_data_size == 0xFFFFFFFF:\n<29> for ext_type, ext_data in session_ticket.other_extensions:\n<30> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n<31> self._parse_transport_parameters(\n<32> ext_data, from_session_ticket=True\n<33> )\n<34> break\n<35> \n<36> # TLS callbacks\n<37> self.tls.alpn_cb = self._alpn_handler\n<38> if self._session_ticket_fetcher is not None"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 1\n self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n if self._session_ticket_handler is not None:\n self.tls.new_session_ticket_cb = self._session_ticket_handler\n self.tls.update_traffic_key_cb = self._update_traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n self._cryptos[tls.Epoch.INITIAL].setup_initial(\n cid=peer_cid, is_client=self._is_client, version=self._version\n )\n \n self._loss.spaces = list(self._spaces.values())\n self._packet_number = 0\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain\n self.certificate = certificates[0]\n \n self.certificate_chain = certificates[1:]\n \n self.private_key = load_pem_private_key(fp.read(), password=password)\n \n at: aioquic.quic.configuration.QuicConfiguration.load_verify_locations\n self.cafile = cafile\n \n self.capath = capath\n \n self.cadata = cadata\n \n at: aioquic.quic.connection\n MAX_EARLY_DATA = 0xFFFFFFFF\n \n QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str)\n \n at: aioquic.quic.connection.QuicConnection\n _alpn_handler(alpn_protocol: str) -> None\n \n _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None\n \n \n===========unchanged ref 1===========\n _serialize_transport_parameters() -> bytes\n \n _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._logger = QuicConnectionAdapter(\n logger, {\"id\": dump_cid(logger_connection_id)}\n )\n \n self._session_ticket_fetcher = session_ticket_fetcher\n \n self._session_ticket_handler = session_ticket_handler\n \n at: aioquic.quic.crypto\n CryptoPair()\n \n at: aioquic.quic.packet\n QuicErrorCode(x: Union[str, bytes, bytearray], base: int)\n QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.tls\n Epoch()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None)\n \n \n===========unchanged ref 2===========\n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n self.cadata: Optional[bytes] = None\n \n self.cafile: Optional[str] = None\n \n self.capath: Optional[str] = None\n \n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_chain: List[x509.Certificate] = []\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n self.alpn_cb: Optional[AlpnHandler] = None\n \n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n at: aioquic.tls.SessionTicket\n age_add: int\n \n cipher_suite: CipherSuite\n \n not_valid_after: datetime.datetime\n \n not_valid_before: datetime.datetime\n \n resumption_secret: bytes\n \n server_name: str\n \n ticket: bytes\n \n max_early_data_size: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n "}}},{"rowIdx":3653,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.create_server"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"116e47ffcc9255f3b715e327834e11fa628352f2"},"commit_message":{"kind":"string","value":"[tls] verify max_early_data value is the expected one"},"ground_truth":{"kind":"string","value":" <3>: server = Context(is_client=False, max_early_data=0xFFFFFFFF)\n server = Context(is_client=False)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def create_server(self):\n <0> configuration = QuicConfiguration(is_client=False)\n <1> configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n <2> \n <3> server = Context(is_client=False)\n <4> server.certificate = configuration.certificate\n <5> server.certificate_private_key = configuration.private_key\n <6> server.handshake_extensions = [\n <7> (\n <8> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n <9> SERVER_QUIC_TRANSPORT_PARAMETERS,\n<10> )\n<11> ]\n<12> self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO)\n<13> return server\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ))\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain\n self.certificate = certificates[0]\n \n self.private_key = load_pem_private_key(fp.read(), password=password)\n \n at: aioquic.tls\n State()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None)\n \n at: aioquic.tls.Context.__init__\n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: tests.test_tls\n SERVER_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify(\n b\"ff00001104ff000011004500050004801000000006000480100000000700048\"\n b\"010000000040004810000000001000242580002001000000000000000000000\"\n b\"000000000000000800024064000a00010a\"\n )\n \n at: tests.utils\n SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), \"ssl_cert.pem\")\n \n SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), \"ssl_key.pem\")\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n \n===========unchanged ref 2===========\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.quic.connection\n class QuicConnection:\n + def _handle_session_ticket(self, session_ticket: tls.SessionTicket) -> None:\n + if (\n + session_ticket.max_early_data_size is not None\n + and session_ticket.max_early_data_size != MAX_EARLY_DATA\n + ):\n + raise QuicConnectionError(\n + error_code=QuicErrorCode.PROTOCOL_VIOLATION,\n + frame_type=QuicFrameType.CRYPTO,\n + reason_phrase=\"Invalid max_early_data value %s\"\n + % session_ticket.max_early_data_size,\n + )\n + self._session_ticket_handler(session_ticket)\n + \n===========changed ref 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n + def test_connect_with_0rtt_bad_max_early_data(self):\n + client_ticket = None\n + ticket_store = SessionTicketStore()\n + \n + def patch(server):\n + \"\"\"\n + Patch server's TLS initialization to set an invalid\n + max_early_data value.\n + \"\"\"\n + real_initialize = server._initialize\n + \n + def patched_initialize(peer_cid: bytes):\n + real_initialize(peer_cid)\n + server.tls.max_early_data = 12345\n + \n + server._initialize = patched_initialize\n + \n + def save_session_ticket(ticket):\n + nonlocal client_ticket\n + client_ticket = ticket\n + \n + with client_and_server(\n + client_kwargs={\"session_ticket_handler\": save_session_ticket},\n + server_kwargs={\"session_ticket_handler\": ticket_store.add},\n + server_patch=patch,\n + ) as (client, server):\n + # check handshake failed\n + event = client.next_event()\n + self.assertIsNone(event)\n + \n===========changed ref 2===========\n # module: aioquic.quic.connection\n logger = logging.getLogger(\"quic\")\n \n EPOCH_SHORTCUTS = {\n \"I\": tls.Epoch.INITIAL,\n \"Z\": tls.Epoch.ZERO_RTT,\n \"H\": tls.Epoch.HANDSHAKE,\n \"O\": tls.Epoch.ONE_RTT,\n }\n MAX_DATA_WINDOW = 1048576\n + MAX_EARLY_DATA = 0xFFFFFFFF\n SECRETS_LABELS = [\n [\n None,\n \"QUIC_CLIENT_EARLY_TRAFFIC_SECRET\",\n \"QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET\",\n \"QUIC_CLIENT_TRAFFIC_SECRET_0\",\n ],\n [\n None,\n None,\n \"QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET\",\n \"QUIC_SERVER_TRAFFIC_SECRET_0\",\n ],\n ]\n STREAM_FLAGS = 0x07\n \n NetworkAddress = Any\n "}}},{"rowIdx":3654,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_key_share"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88532f3e474c47d017cba524a05b78cdb774d027"},"commit_message":{"kind":"string","value":"[tls] don't croak on unknown TLS parameters"},"ground_truth":{"kind":"string","value":" <0>: group = buf.pull_uint16()\n group = pull_group(buf)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_key_share(buf: Buffer) -> KeyShareEntry:\n <0> group = pull_group(buf)\n <1> data = pull_opaque(buf, 2)\n <2> return (group, data)\n <3> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n push_opaque(buf: Buffer, capacity: int, value: bytes) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n # KeyShareEntry\n \n \n + KeyShareEntry = Tuple[int, bytes]\n - KeyShareEntry = Tuple[Group, bytes]\n \n===========changed ref 1===========\n # module: aioquic.tls\n - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:\n - return SignatureAlgorithm(buf.pull_uint16())\n - \n===========changed ref 2===========\n # module: aioquic.tls\n - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n - return PskKeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 3===========\n # module: aioquic.tls\n - def pull_group(buf: Buffer) -> Group:\n - return Group(buf.pull_uint16())\n - \n===========changed ref 4===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_compression_method(buf: Buffer) -> CompressionMethod:\n - return CompressionMethod(buf.pull_uint8())\n - "}}},{"rowIdx":3655,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_client_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88532f3e474c47d017cba524a05b78cdb774d027"},"commit_message":{"kind":"string","value":"[tls] don't croak on unknown TLS parameters"},"ground_truth":{"kind":"string","value":" <9>: compression_methods=pull_list(buf, 1, buf.pull_uint8),\n compression_methods=pull_list(\n<10>: buf, 1, partial(pull_compression_method, buf)\n<11>: ),\n<29>: hello.signature_algorithms = pull_list(buf, 2, buf.pull_uint16)\n hello.signature_algorithms = pull_list(\n<30>: buf, 2, partial(pull_signature_algorithm, buf)\n<31>: )\n<33>: hello.supported_groups = pull_list(buf, 2, buf.pull_uint16)\n hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n<35>: hello.psk_key_exchange_modes = pull_list(buf, 1, buf.pull_uint8)\n hello.psk_key_exchange_modes = pull_list(\n<36>: buf, 1, partial(pull_psk_key_exchange_mode, buf)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n <0> assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n <1> with pull_block(buf, 3):\n <2> assert buf.pull_uint16() == TLS_VERSION_1_2\n <3> client_random = buf.pull_bytes(32)\n <4> \n <5> hello = ClientHello(\n <6> random=client_random,\n <7> session_id=pull_opaque(buf, 1),\n <8> cipher_suites=pull_list(buf, 2, buf.pull_uint16),\n <9> compression_methods=pull_list(\n<10> buf, 1, partial(pull_compression_method, buf)\n<11> ),\n<12> )\n<13> \n<14> # extensions\n<15> after_psk = False\n<16> \n<17> def pull_extension() -> None:\n<18> # pre_shared_key MUST be last\n<19> nonlocal after_psk\n<20> assert not after_psk\n<21> \n<22> extension_type = buf.pull_uint16()\n<23> extension_length = buf.pull_uint16()\n<24> if extension_type == ExtensionType.KEY_SHARE:\n<25> hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n<26> elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n<27> hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n<28> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n<29> hello.signature_algorithms = pull_list(\n<30> buf, 2, partial(pull_signature_algorithm, buf)\n<31> )\n<32> elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n<33> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n<34> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n<35> hello.psk_key_exchange_modes = pull_list(\n<36> buf, 1, partial(pull_psk_key_exchange_mode, buf)\n "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n # offset: 1\n elif extension_type == ExtensionType.SERVER_NAME:\n with pull_block(buf, 2):\n assert buf.pull_uint8() == 0\n hello.server_name = pull_opaque(buf, 2).decode(\"ascii\")\n elif extension_type == ExtensionType.ALPN:\n hello.alpn_protocols = pull_list(\n buf, 2, partial(pull_alpn_protocol, buf)\n )\n elif extension_type == ExtensionType.EARLY_DATA:\n hello.early_data = True\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = OfferedPsks(\n identities=pull_list(buf, 2, partial(pull_psk_identity, buf)),\n binders=pull_list(buf, 2, partial(pull_psk_binder, buf)),\n )\n after_psk = True\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_bytes(length: int) -> bytes\n \n pull_uint8() -> int\n \n pull_uint16() -> int\n \n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint16(value: int) -> None\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n pull_block(buf: Buffer, capacity: int) -> Generator\n \n push_block(buf: Buffer, capacity: int) -> Generator\n \n pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]\n \n push_list(buf: Buffer, capacity: int, func: Callable[[T], None], values: Sequence[T]) -> None\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n push_opaque(buf: Buffer, capacity: int, value: bytes) -> None\n \n push_extension(buf: Buffer, extension_type: int) -> Generator\n \n pull_key_share(buf: Buffer) -> KeyShareEntry\n \n push_key_share(buf: Buffer, value: KeyShareEntry) -> None\n \n pull_alpn_protocol(buf: Buffer) -> str\n \n pull_psk_identity(buf: Buffer) -> PskIdentity\n \n pull_psk_binder(buf: Buffer) -> bytes\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n \n===========unchanged ref 1===========\n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[int], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[int]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[int]]=None, supported_groups: Optional[List[int]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n at: aioquic.tls.ClientHello\n random: bytes\n \n session_id: bytes\n \n cipher_suites: List[int]\n \n compression_methods: List[int]\n \n alpn_protocols: Optional[List[str]] = None\n \n early_data: bool = False\n \n key_share: Optional[List[KeyShareEntry]] = None\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n psk_key_exchange_modes: Optional[List[int]] = None\n \n server_name: Optional[str] = None\n \n signature_algorithms: Optional[List[int]] = None\n \n supported_groups: Optional[List[int]] = None\n \n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n at: aioquic.tls.OfferedPsks\n identities: List[PskIdentity]\n \n binders: List[bytes]\n \n at: aioquic.tls.pull_client_hello\n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n cipher_suites=pull_list(buf, 2, buf.pull_uint16),\n compression_methods=pull_list(buf, 1, buf.pull_uint8),\n )\n \n \n===========unchanged ref 2===========\n after_psk = False\n \n pull_extension() -> None\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n def pull_key_share(buf: Buffer) -> KeyShareEntry:\n + group = buf.pull_uint16()\n - group = pull_group(buf)\n data = pull_opaque(buf, 2)\n return (group, data)\n \n===========changed ref 1===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[int]\n + compression_methods: List[int]\n - compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[int]] = None\n - psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n + signature_algorithms: Optional[List[int]] = None\n - signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n + supported_groups: Optional[List[int]] = None\n - supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 2===========\n # module: aioquic.tls\n # KeyShareEntry\n \n \n + KeyShareEntry = Tuple[int, bytes]\n - KeyShareEntry = Tuple[Group, bytes]\n \n===========changed ref 3===========\n # module: aioquic.tls\n - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:\n - return SignatureAlgorithm(buf.pull_uint16())\n - \n===========changed ref 4===========\n # module: aioquic.tls\n - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n - return PskKeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 5===========\n # module: aioquic.tls\n - def pull_group(buf: Buffer) -> Group:\n - return Group(buf.pull_uint16())\n - \n===========changed ref 6===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_compression_method(buf: Buffer) -> CompressionMethod:\n - return CompressionMethod(buf.pull_uint8())\n - "}}},{"rowIdx":3656,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_server_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88532f3e474c47d017cba524a05b78cdb774d027"},"commit_message":{"kind":"string","value":"[tls] don't croak on unknown TLS parameters"},"ground_truth":{"kind":"string","value":" <9>: compression_method=buf.pull_uint8(),\n compression_method=pull_compression_method(buf),\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_server_hello(buf: Buffer) -> ServerHello:\n <0> assert buf.pull_uint8() == HandshakeType.SERVER_HELLO\n <1> with pull_block(buf, 3):\n <2> assert buf.pull_uint16() == TLS_VERSION_1_2\n <3> server_random = buf.pull_bytes(32)\n <4> \n <5> hello = ServerHello(\n <6> random=server_random,\n <7> session_id=pull_opaque(buf, 1),\n <8> cipher_suite=buf.pull_uint16(),\n <9> compression_method=pull_compression_method(buf),\n<10> )\n<11> \n<12> # extensions\n<13> def pull_extension() -> None:\n<14> extension_type = buf.pull_uint16()\n<15> extension_length = buf.pull_uint16()\n<16> if extension_type == ExtensionType.SUPPORTED_VERSIONS:\n<17> hello.supported_version = buf.pull_uint16()\n<18> elif extension_type == ExtensionType.KEY_SHARE:\n<19> hello.key_share = pull_key_share(buf)\n<20> elif extension_type == ExtensionType.PRE_SHARED_KEY:\n<21> hello.pre_shared_key = buf.pull_uint16()\n<22> else:\n<23> hello.other_extensions.append(\n<24> (extension_type, buf.pull_bytes(extension_length))\n<25> )\n<26> \n<27> pull_list(buf, 2, pull_extension)\n<28> \n<29> return hello\n<30> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_bytes(length: int) -> bytes\n \n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint16(value: int) -> None\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n push_block(buf: Buffer, capacity: int) -> Generator\n \n pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]\n \n push_opaque(buf: Buffer, capacity: int, value: bytes) -> None\n \n push_extension(buf: Buffer, extension_type: int) -> Generator\n \n push_key_share(buf: Buffer, value: KeyShareEntry) -> None\n \n ServerHello(random: bytes, session_id: bytes, cipher_suite: int, compression_method: int, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n at: aioquic.tls.ServerHello\n random: bytes\n \n session_id: bytes\n \n cipher_suite: int\n \n compression_method: int\n \n key_share: Optional[KeyShareEntry] = None\n \n pre_shared_key: Optional[int] = None\n \n supported_version: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n \n===========unchanged ref 1===========\n at: aioquic.tls.pull_server_hello\n hello = ServerHello(\n random=server_random,\n session_id=pull_opaque(buf, 1),\n cipher_suite=buf.pull_uint16(),\n compression_method=buf.pull_uint8(),\n )\n \n pull_extension() -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ServerHello:\n random: bytes\n session_id: bytes\n cipher_suite: int\n + compression_method: int\n - compression_method: CompressionMethod\n \n # extensions\n key_share: Optional[KeyShareEntry] = None\n pre_shared_key: Optional[int] = None\n supported_version: Optional[int] = None\n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n # KeyShareEntry\n \n \n + KeyShareEntry = Tuple[int, bytes]\n - KeyShareEntry = Tuple[Group, bytes]\n \n===========changed ref 2===========\n # module: aioquic.tls\n def pull_key_share(buf: Buffer) -> KeyShareEntry:\n + group = buf.pull_uint16()\n - group = pull_group(buf)\n data = pull_opaque(buf, 2)\n return (group, data)\n \n===========changed ref 3===========\n # module: aioquic.tls\n - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:\n - return SignatureAlgorithm(buf.pull_uint16())\n - \n===========changed ref 4===========\n # module: aioquic.tls\n - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n - return PskKeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 5===========\n # module: aioquic.tls\n - def pull_group(buf: Buffer) -> Group:\n - return Group(buf.pull_uint16())\n - \n===========changed ref 6===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_compression_method(buf: Buffer) -> CompressionMethod:\n - return CompressionMethod(buf.pull_uint8())\n - \n===========changed ref 7===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[int]\n + compression_methods: List[int]\n - compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[int]] = None\n - psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n + signature_algorithms: Optional[List[int]] = None\n - signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n + supported_groups: Optional[List[int]] = None\n - supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 8===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n client_random = buf.pull_bytes(32)\n \n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n cipher_suites=pull_list(buf, 2, buf.pull_uint16),\n + compression_methods=pull_list(buf, 1, buf.pull_uint8),\n - compression_methods=pull_list(\n - buf, 1, partial(pull_compression_method, buf)\n - ),\n )\n \n # extensions\n after_psk = False\n \n def pull_extension() -> None:\n # pre_shared_key MUST be last\n nonlocal after_psk\n assert not after_psk\n \n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n + hello.signature_algorithms = pull_list(buf, 2, buf.pull_uint16)\n - hello.signature_algorithms = pull_list(\n - buf, 2, partial(pull_signature_algorithm, buf)\n - )\n elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n + hello.supported_groups = pull_list(buf, 2, buf.pull_uint16)\n - hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODE"}}},{"rowIdx":3657,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_certificate_verify"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88532f3e474c47d017cba524a05b78cdb774d027"},"commit_message":{"kind":"string","value":"[tls] don't croak on unknown TLS parameters"},"ground_truth":{"kind":"string","value":" <2>: algorithm = buf.pull_uint16()\n algorithm = pull_signature_algorithm(buf)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_certificate_verify(buf: Buffer) -> CertificateVerify:\n <0> assert buf.pull_uint8() == HandshakeType.CERTIFICATE_VERIFY\n <1> with pull_block(buf, 3):\n <2> algorithm = pull_signature_algorithm(buf)\n <3> signature = pull_opaque(buf, 2)\n <4> \n <5> return CertificateVerify(algorithm=algorithm, signature=signature)\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n push_uint8(value: int) -> None\n \n at: aioquic.tls\n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n Finished(verify_data: bytes=b\"\")\n \n at: aioquic.tls.Finished\n verify_data: bytes = b\"\"\n \n at: aioquic.tls.pull_finished\n finished = Finished()\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class CertificateVerify:\n + algorithm: int\n - algorithm: SignatureAlgorithm\n signature: bytes\n \n===========changed ref 1===========\n # module: aioquic.tls\n @dataclass\n class ServerHello:\n random: bytes\n session_id: bytes\n cipher_suite: int\n + compression_method: int\n - compression_method: CompressionMethod\n \n # extensions\n key_share: Optional[KeyShareEntry] = None\n pre_shared_key: Optional[int] = None\n supported_version: Optional[int] = None\n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n===========changed ref 2===========\n # module: aioquic.tls\n # KeyShareEntry\n \n \n + KeyShareEntry = Tuple[int, bytes]\n - KeyShareEntry = Tuple[Group, bytes]\n \n===========changed ref 3===========\n # module: aioquic.tls\n def pull_key_share(buf: Buffer) -> KeyShareEntry:\n + group = buf.pull_uint16()\n - group = pull_group(buf)\n data = pull_opaque(buf, 2)\n return (group, data)\n \n===========changed ref 4===========\n # module: aioquic.tls\n def pull_server_hello(buf: Buffer) -> ServerHello:\n assert buf.pull_uint8() == HandshakeType.SERVER_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n server_random = buf.pull_bytes(32)\n \n hello = ServerHello(\n random=server_random,\n session_id=pull_opaque(buf, 1),\n cipher_suite=buf.pull_uint16(),\n + compression_method=buf.pull_uint8(),\n - compression_method=pull_compression_method(buf),\n )\n \n # extensions\n def pull_extension() -> None:\n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_version = buf.pull_uint16()\n elif extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_key_share(buf)\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = buf.pull_uint16()\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n \n===========changed ref 5===========\n # module: aioquic.tls\n - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm:\n - return SignatureAlgorithm(buf.pull_uint16())\n - \n===========changed ref 6===========\n # module: aioquic.tls\n - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n - return PskKeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 7===========\n # module: aioquic.tls\n - def pull_group(buf: Buffer) -> Group:\n - return Group(buf.pull_uint16())\n - \n===========changed ref 8===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_compression_method(buf: Buffer) -> CompressionMethod:\n - return CompressionMethod(buf.pull_uint8())\n - \n===========changed ref 9===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[int]\n + compression_methods: List[int]\n - compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[int]] = None\n - psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n + signature_algorithms: Optional[List[int]] = None\n - signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n + supported_groups: Optional[List[int]] = None\n - supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 10===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n client_random = buf.pull_bytes(32)\n \n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n cipher_suites=pull_list(buf, 2, buf.pull_uint16),\n + compression_methods=pull_list(buf, 1, buf.pull_uint8),\n - compression_methods=pull_list(\n - buf, 1, partial(pull_compression_method, buf)\n - ),\n )\n \n # extensions\n after_psk = False\n \n def pull_extension() -> None:\n # pre_shared_key MUST be last\n nonlocal after_psk\n assert not after_psk\n \n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n + hello.signature_algorithms = pull_list(buf, 2, buf.pull_uint16)\n - hello.signature_algorithms = pull_list(\n - buf, 2, partial(pull_signature_algorithm, buf)\n - )\n elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n + hello.supported_groups = pull_list(buf, 2, buf.pull_uint16)\n - hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODE"}}},{"rowIdx":3658,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88532f3e474c47d017cba524a05b78cdb774d027"},"commit_message":{"kind":"string","value":"[tls] don't croak on unknown TLS parameters"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.cadata: Optional[bytes] = None\n <3> self.cafile: Optional[str] = None\n <4> self.capath: Optional[str] = None\n <5> self.certificate: Optional[x509.Certificate] = None\n <6> self.certificate_chain: List[x509.Certificate] = []\n <7> self.certificate_private_key: Optional[\n <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <9> ] = None\n<10> self.early_data_accepted = False\n<11> self.handshake_extensions: List[Extension] = []\n<12> self.key_schedule: Optional[KeySchedule] = None\n<13> self.max_early_data = max_early_data\n<14> self.received_extensions: Optional[List[Extension]] = None\n<15> self.session_ticket: Optional[SessionTicket] = None\n<16> self.server_name: Optional[str] = None\n<17> \n<18> # callbacks\n<19> self.alpn_cb: Optional[AlpnHandler] = None\n<20> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<21> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n<22> self.update_traffic_key_cb: Callable[\n<23> [Direction, Epoch, CipherSuite, bytes], None\n<24> ] = lambda d, e, c, s: None\n<25> \n<26> # supported parameters\n<27> self._cipher_suites = [\n<28> CipherSuite.AES_256_GCM_SHA384,\n<29> CipherSuite.AES_128_GCM_SHA256,\n<30> CipherSuite.CHACHA"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 1\n ]\n self._compression_methods = [CompressionMethod.NULL]\n self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 2\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n AlpnHandler = Callable[[str], None]\n \n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: aioquic.tls.Context\n _client_send_hello(output_buf: Buffer) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n at: aioquic.tls.Context._server_handle_hello\n self.client_random = peer_hello.random\n \n self.session_id = peer_hello.session_id\n \n self._session_resumed = True\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[key_share[0]](), default_backend()\n )\n \n \n===========unchanged ref 2===========\n self._new_session_ticket = NewSessionTicket(\n ticket_lifetime=86400,\n ticket_age_add=struct.unpack(\"I\", os.urandom(4))[0],\n ticket_nonce=b\"\",\n ticket=os.urandom(64),\n max_early_data_size=self.max_early_data,\n )\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: aioquic.tls.Context._setup_traffic_protection\n self._enc_key = key\n \n self._dec_key = key\n \n at: os\n urandom(size: int, /) -> bytes\n \n at: typing\n Callable = _CallableType(collections.abc.Callable, 2)\n \n List = _alias(list, 1, inst=False, name='List')\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class CertificateVerify:\n + algorithm: int\n - algorithm: SignatureAlgorithm\n signature: bytes\n \n===========changed ref 1===========\n # module: aioquic.tls\n def pull_certificate_verify(buf: Buffer) -> CertificateVerify:\n assert buf.pull_uint8() == HandshakeType.CERTIFICATE_VERIFY\n with pull_block(buf, 3):\n + algorithm = buf.pull_uint16()\n - algorithm = pull_signature_algorithm(buf)\n signature = pull_opaque(buf, 2)\n \n return CertificateVerify(algorithm=algorithm, signature=signature)\n "}}},{"rowIdx":3659,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_send_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88532f3e474c47d017cba524a05b78cdb774d027"},"commit_message":{"kind":"string","value":"[tls] don't croak on unknown TLS parameters"},"ground_truth":{"kind":"string","value":" <1>: supported_groups: List[int] = []\n supported_groups: List[Group] = []\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n <0> key_share: List[KeyShareEntry] = []\n <1> supported_groups: List[Group] = []\n <2> \n <3> if Group.SECP256R1 in self._supported_groups:\n <4> self._ec_private_key = ec.generate_private_key(\n <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n <6> )\n <7> key_share.append(encode_public_key(self._ec_private_key.public_key()))\n <8> supported_groups.append(Group.SECP256R1)\n <9> \n<10> if Group.X25519 in self._supported_groups:\n<11> self._x25519_private_key = x25519.X25519PrivateKey.generate()\n<12> key_share.append(encode_public_key(self._x25519_private_key.public_key()))\n<13> supported_groups.append(Group.X25519)\n<14> \n<15> assert len(key_share), \"no key share entries\"\n<16> \n<17> hello = ClientHello(\n<18> random=self.client_random,\n<19> session_id=self.session_id,\n<20> cipher_suites=[int(x) for x in self._cipher_suites],\n<21> compression_methods=self._compression_methods,\n<22> alpn_protocols=self.alpn_protocols,\n<23> key_share=key_share,\n<24> psk_key_exchange_modes=self._psk_key_exchange_modes\n<25> if (self.session_ticket or self.new_session_ticket_cb is not None)\n<26> else None,\n<27> server_name=self.server_name,\n<28> signature_algorithms=self._signature_algorithms,\n<29> supported_groups=supported_groups,\n<30> supported_versions=self._supported_versions,\n<31> other_extensions=self.handshake_extensions,\n<32> )\n<33> \n<34> # PSK\n<35> if self.session_ticket and self.session_ticket"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 1\n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n self._key_schedule_psk.extract(self.session_ticket.resumption_secret)\n binder_key = self._key_schedule_psk.derive_secret(b\"res binder\")\n binder_length = self._key_schedule_psk.algorithm.digest_size\n \n # update hello\n if self.session_ticket.max_early_data_size is not None:\n hello.early_data = True\n hello.pre_shared_key = OfferedPsks(\n identities=[\n (self.session_ticket.ticket, self.session_ticket.obfuscated_age)\n ],\n binders=[bytes(binder_length)],\n )\n \n # serialize hello without binder\n tmp_buf = Buffer(capacity=1024)\n push_client_hello(tmp_buf, hello)\n \n # calculate binder\n hash_offset = tmp_buf.tell() - binder_length - 3\n self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset))\n binder = self._key_schedule_psk.finished_verify_data(binder_key)\n hello.pre_shared_key.binders[0] = binder\n self._key_schedule_psk.update_hash(\n tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder\n )\n \n # calculate early data key\n if hello.early_data:\n early_key = self._key_schedule_psk.derive_secret(b\"c e traffic\")\n self.update_traffic_key_cb(\n Direction.ENCRYPT,\n Epoch.ZERO_RTT,\n self._key_schedule_psk.cipher_suite,\n early_key,\n )\n \n self._key_schedule_proxy = Key\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 2\n schedule_psk.cipher_suite,\n early_key,\n )\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n self._key_schedule_proxy.extract(None)\n \n with push_message(self._key_schedule_proxy, output_buf):\n push_client_hello(output_buf, hello)\n \n self._set_state(State.CLIENT_EXPECT_SERVER_HELLO)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n data_slice(start: int, end: int) -> bytes\n \n tell() -> int\n \n at: aioquic.tls\n AlertHandshakeFailure(*args: object)\n \n AlertIllegalParameter(*args: object)\n \n Direction()\n \n Epoch()\n \n State()\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n push_client_hello(buf: Buffer, hello: ClientHello) -> None\n \n pull_server_hello(buf: Buffer) -> ServerHello\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n negotiate(supported: List[T], offered: Optional[List[Any]], exc: Optional[Alert]=None) -> T\n \n push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator\n \n at: aioquic.tls.ClientHello\n early_data: bool = False\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n at: aioquic.tls.Context\n _set_state(state: State) -> None\n \n at: aioquic.tls.Context.__init__\n self.handshake_extensions: List[Extension] = []\n \n self.key_schedule: Optional[KeySchedule] = None\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n \n===========unchanged ref 1===========\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n \n self._compression_methods: List[int] = [CompressionMethod.NULL]\n \n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n \n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n \n self._supported_versions = [TLS_VERSION_1_3]\n \n self._key_schedule_psk: Optional[KeySchedule] = None\n \n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n \n self._session_resumed = False\n \n at: aioquic.tls.Context._client_handle_hello\n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n supported_groups: List[int] = []\n \n \n===========unchanged ref 2===========\n hello = ClientHello(\n random=self.client_random,\n session_id=self.session_id,\n cipher_suites=[int(x) for x in self._cipher_suites],\n compression_methods=self._compression_methods,\n alpn_protocols=self.alpn_protocols,\n key_share=key_share,\n psk_key_exchange_modes=self._psk_key_exchange_modes\n if (self.session_ticket or self.new_session_ticket_cb is not None)\n else None,\n server_name=self.server_name,\n signature_algorithms=self._signature_algorithms,\n supported_groups=supported_groups,\n supported_versions=self._supported_versions,\n other_extensions=self.handshake_extensions,\n )\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n self._session_resumed = True\n \n at: aioquic.tls.KeySchedule\n finished_verify_data(secret: bytes) -> bytes\n \n derive_secret(label: bytes) -> bytes\n \n extract(key_material: Optional[bytes]=None) -> None\n \n update_hash(data: bytes) -> None\n \n at: aioquic.tls.KeySchedule.__init__\n self.algorithm = cipher_suite_hash(cipher_suite)\n \n self.cipher_suite = cipher_suite\n \n at: aioquic.tls.KeyScheduleProxy\n extract(key_material: Optional[bytes]=None) -> None\n \n select(cipher_suite: CipherSuite) -> KeySchedule\n \n at: aioquic.tls.OfferedPsks\n binders: List[bytes]\n \n at: aioquic.tls.ServerHello\n cipher_suite: int\n \n compression_method: int\n \n pre_shared_key: Optional[int] = None\n \n supported_version: Optional[int] = None\n \n at: aioquic.tls.SessionTicket\n age_add: int\n \n cipher_suite: CipherSuite\n \n "}}},{"rowIdx":3660,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"dd555a0b35af21f4630c30cd8bc9dfb135ebbcde"},"commit_message":{"kind":"string","value":"[tls] enable X25519 if supported"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.cadata: Optional[bytes] = None\n <3> self.cafile: Optional[str] = None\n <4> self.capath: Optional[str] = None\n <5> self.certificate: Optional[x509.Certificate] = None\n <6> self.certificate_chain: List[x509.Certificate] = []\n <7> self.certificate_private_key: Optional[\n <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <9> ] = None\n<10> self.early_data_accepted = False\n<11> self.handshake_extensions: List[Extension] = []\n<12> self.key_schedule: Optional[KeySchedule] = None\n<13> self.max_early_data = max_early_data\n<14> self.received_extensions: Optional[List[Extension]] = None\n<15> self.session_ticket: Optional[SessionTicket] = None\n<16> self.server_name: Optional[str] = None\n<17> \n<18> # callbacks\n<19> self.alpn_cb: Optional[AlpnHandler] = None\n<20> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<21> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n<22> self.update_traffic_key_cb: Callable[\n<23> [Direction, Epoch, CipherSuite, bytes], None\n<24> ] = lambda d, e, c, s: None\n<25> \n<26> # supported parameters\n<27> self._cipher_suites = [\n<28> CipherSuite.AES_256_GCM_SHA384,\n<29> CipherSuite.AES_128_GCM_SHA256,\n<30> CipherSuite.CHACHA"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 1\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 2\n = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Extension = Tuple[int, bytes]\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n AlpnHandler = Callable[[str], None]\n \n \n===========unchanged ref 1===========\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n "}}},{"rowIdx":3661,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest._handshake"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"dd555a0b35af21f4630c30cd8bc9dfb135ebbcde"},"commit_message":{"kind":"string","value":"[tls] enable X25519 if supported"},"ground_truth":{"kind":"string","value":" <6>: self.assertLessEqual(len(server_input), 296)\n self.assertLessEqual(len(server_input), 264)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n <0> # send client hello\n <1> client_buf = create_buffers()\n <2> client.handle_message(b\"\", client_buf)\n <3> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n <4> server_input = merge_buffers(client_buf)\n <5> self.assertGreaterEqual(len(server_input), 213)\n <6> self.assertLessEqual(len(server_input), 264)\n <7> reset_buffers(client_buf)\n <8> \n <9> # handle client hello\n<10> # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n<11> server_buf = create_buffers()\n<12> server.handle_message(server_input, server_buf)\n<13> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED)\n<14> client_input = merge_buffers(server_buf)\n<15> self.assertGreaterEqual(len(client_input), 600)\n<16> self.assertLessEqual(len(client_input), 2316)\n<17> \n<18> reset_buffers(server_buf)\n<19> \n<20> # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n<21> # send finished\n<22> client.handle_message(client_input, client_buf)\n<23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE)\n<24> server_input = merge_buffers(client_buf)\n<25> self.assertEqual(len(server_input), 52)\n<26> reset_buffers(client_buf)\n<27> \n<28> # handle finished\n<29> server.handle_message(server_input, server_buf)\n<30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE)\n<31> client_input = merge_buffers(server_buf)\n<32> self.assertEqual(len(client_input), 0)\n<33> \n<34> # check keys match\n<35> self.assertEqual(client._dec_key, server._enc_"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # offset: 1\n self.assertEqual(client._enc_key, server._dec_key)\n \n # check cipher suite\n self.assertEqual(\n client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n self.assertEqual(\n server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.key_schedule: Optional[KeySchedule] = None\n \n self._enc_key: Optional[bytes] = None\n \n self._dec_key: Optional[bytes] = None\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: aioquic.tls.Context._setup_traffic_protection\n self._enc_key = key\n \n self._dec_key = key\n \n at: aioquic.tls.KeySchedule.__init__\n self.cipher_suite = cipher_suite\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n \n===========unchanged ref 1===========\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertLessEqual(a: Any, b: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n self.alpn_negotiated: Optional[str] = None\n self.alpn_protocols: Optional[List[str]] = None\n self.cadata: Optional[bytes] = None\n self.cafile: Optional[str] = None\n self.capath: Optional[str] = None\n self.certificate: Optional[x509.Certificate] = None\n self.certificate_chain: List[x509.Certificate] = []\n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n self.early_data_accepted = False\n self.handshake_extensions: List[Extension] = []\n self.key_schedule: Optional[KeySchedule] = None\n self.max_early_data = max_early_data\n self.received_extensions: Optional[List[Extension]] = None\n self.session_ticket: Optional[SessionTicket] = None\n self.server_name: Optional[str] = None\n \n # callbacks\n self.alpn_cb: Optional[AlpnHandler] = None\n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL\n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 1\n _POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n + if default_backend().x25519_supported():\n + self._supported_groups.append(Group.X25519)\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 2\n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n "}}},{"rowIdx":3662,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_handshake_with_alpn_fail"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"dd555a0b35af21f4630c30cd8bc9dfb135ebbcde"},"commit_message":{"kind":"string","value":"[tls] enable X25519 if supported"},"ground_truth":{"kind":"string","value":"<11>: self.assertGreaterEqual(len(server_input), 258)\n self.assertEqual(len(server_input), 258)\n<12>: self.assertLessEqual(len(server_input), 296)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_with_alpn_fail(self):\n <0> client = self.create_client()\n <1> client.alpn_protocols = [\"hq-20\"]\n <2> \n <3> server = self.create_server()\n <4> server.alpn_protocols = [\"h3-20\"]\n <5> \n <6> # send client hello\n <7> client_buf = create_buffers()\n <8> client.handle_message(b\"\", client_buf)\n <9> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n<10> server_input = merge_buffers(client_buf)\n<11> self.assertEqual(len(server_input), 258)\n<12> reset_buffers(client_buf)\n<13> \n<14> # handle client hello\n<15> # send server hello, encrypted extensions, certificate, certificate verify, finished\n<16> server_buf = create_buffers()\n<17> with self.assertRaises(tls.AlertHandshakeFailure) as cm:\n<18> server.handle_message(server_input, server_buf)\n<19> self.assertEqual(str(cm.exception), \"No common ALPN protocols\")\n<20> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n AlertHandshakeFailure(*args: object)\n \n State()\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: tests.test_tls.ContextTest\n create_client(cafile=SERVER_CACERTFILE)\n \n create_server()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertLessEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # send client hello\n client_buf = create_buffers()\n client.handle_message(b\"\", client_buf)\n self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n server_input = merge_buffers(client_buf)\n self.assertGreaterEqual(len(server_input), 213)\n + self.assertLessEqual(len(server_input), 296)\n - self.assertLessEqual(len(server_input), 264)\n reset_buffers(client_buf)\n \n # handle client hello\n # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n server_buf = create_buffers()\n server.handle_message(server_input, server_buf)\n self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED)\n client_input = merge_buffers(server_buf)\n self.assertGreaterEqual(len(client_input), 600)\n self.assertLessEqual(len(client_input), 2316)\n \n reset_buffers(server_buf)\n \n # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n # send finished\n client.handle_message(client_input, client_buf)\n self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE)\n server_input = merge_buffers(client_buf)\n self.assertEqual(len(server_input), 52)\n reset_buffers(client_buf)\n \n # handle finished\n server.handle_message(server_input, server_buf)\n self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE)\n client_input = merge_buffers(server_buf)\n self.assertEqual(len(client_input), 0)\n \n # check keys match\n self.assertEqual(client._dec_key, server._enc_key)\n self.assertEqual(client._enc_key, server._\n===========changed ref 1===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # offset: 1\n assertEqual(client._dec_key, server._enc_key)\n self.assertEqual(client._enc_key, server._dec_key)\n \n # check cipher suite\n self.assertEqual(\n client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n self.assertEqual(\n server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n self.alpn_negotiated: Optional[str] = None\n self.alpn_protocols: Optional[List[str]] = None\n self.cadata: Optional[bytes] = None\n self.cafile: Optional[str] = None\n self.capath: Optional[str] = None\n self.certificate: Optional[x509.Certificate] = None\n self.certificate_chain: List[x509.Certificate] = []\n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n self.early_data_accepted = False\n self.handshake_extensions: List[Extension] = []\n self.key_schedule: Optional[KeySchedule] = None\n self.max_early_data = max_early_data\n self.received_extensions: Optional[List[Extension]] = None\n self.session_ticket: Optional[SessionTicket] = None\n self.server_name: Optional[str] = None\n \n # callbacks\n self.alpn_cb: Optional[AlpnHandler] = None\n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL\n===========changed ref 3===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n ):\n # offset: 1\n _POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n + if default_backend().x25519_supported():\n + self._supported_groups.append(Group.X25519)\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n "}}},{"rowIdx":3663,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"4a52a6526e5edad5ca262c7eb66aa723ed38e523"},"commit_message":{"kind":"string","value":"[tls] make it possible to disable certificate verification"},"ground_truth":{"kind":"string","value":"<17>: if verify_mode is not None:\n self.verify_mode = verify_mode\n else:\n self.verify_mode = (\n ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n )\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + verify_mode: Optional[int] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.cadata: Optional[bytes] = None\n <3> self.cafile: Optional[str] = None\n <4> self.capath: Optional[str] = None\n <5> self.certificate: Optional[x509.Certificate] = None\n <6> self.certificate_chain: List[x509.Certificate] = []\n <7> self.certificate_private_key: Optional[\n <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <9> ] = None\n<10> self.early_data_accepted = False\n<11> self.handshake_extensions: List[Extension] = []\n<12> self.key_schedule: Optional[KeySchedule] = None\n<13> self.max_early_data = max_early_data\n<14> self.received_extensions: Optional[List[Extension]] = None\n<15> self.session_ticket: Optional[SessionTicket] = None\n<16> self.server_name: Optional[str] = None\n<17> \n<18> # callbacks\n<19> self.alpn_cb: Optional[AlpnHandler] = None\n<20> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<21> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n<22> self.update_traffic_key_cb: Callable[\n<23> [Direction, Epoch, CipherSuite, bytes], None\n<24> ] = lambda d, e, c, s: None\n<25> \n<26> # supported parameters\n<27> self._cipher_suites = [\n<28> CipherSuite.AES_256_GCM_SHA384,\n<29> CipherSuite.AES_128_G"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + verify_mode: Optional[int] = None,\n ):\n # offset: 1\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n if default_backend().x25519_supported():\n self._supported_groups.append(Group.X25519)\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + verify_mode: Optional[int] = None,\n ):\n # offset: 2\n _private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Extension = Tuple[int, bytes]\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n AlpnHandler = Callable[[str], None]\n \n \n===========unchanged ref 1===========\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n "}}},{"rowIdx":3664,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_handle_certificate_verify"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"4a52a6526e5edad5ca262c7eb66aa723ed38e523"},"commit_message":{"kind":"string","value":"[tls] make it possible to disable certificate verification"},"ground_truth":{"kind":"string","value":"<17>: if self.verify_mode != ssl.CERT_NONE:\n verify_certificate(\n verify_certificate(\n<18>: cadata=self.cadata,\n cadata=self.cadata,\n<19>: cafile=self.cafile,\n cafile=self.cafile,\n<20>: capath=self.capath,\n capath=self.capath,\n<21>: certificate=self._peer_certificate,\n certificate=self._peer_certificate,\n<22>: chain=self._peer_certificate_chain,\n chain=self._peer_certificate_chain,\n<23>: server_name=self.server_name,\n server_name=self.server_name,\n<24>: )\n )\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_handle_certificate_verify(self, input_buf: Buffer) -> None:\n <0> verify = pull_certificate_verify(input_buf)\n <1> \n <2> assert verify.algorithm in self._signature_algorithms\n <3> \n <4> # check signature\n <5> try:\n <6> self._peer_certificate.public_key().verify(\n <7> verify.signature,\n <8> self.key_schedule.certificate_verify_data(\n <9> b\"TLS 1.3, server CertificateVerify\"\n<10> ),\n<11> *signature_algorithm_params(verify.algorithm),\n<12> )\n<13> except InvalidSignature:\n<14> raise AlertDecryptError\n<15> \n<16> # check certificate\n<17> verify_certificate(\n<18> cadata=self.cadata,\n<19> cafile=self.cafile,\n<20> capath=self.capath,\n<21> certificate=self._peer_certificate,\n<22> chain=self._peer_certificate_chain,\n<23> server_name=self.server_name,\n<24> )\n<25> \n<26> self.key_schedule.update_hash(input_buf.data)\n<27> \n<28> self._set_state(State.CLIENT_EXPECT_FINISHED)\n<29> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.tls\n AlertDecryptError(*args: object)\n \n State()\n \n verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None\n \n pull_certificate_verify(buf: Buffer) -> CertificateVerify\n \n signature_algorithm_params(signature_algorithm: int) -> Union[Tuple[ec.ECDSA], Tuple[padding.AsymmetricPadding, hashes.HashAlgorithm]]\n \n at: aioquic.tls.CertificateVerify\n algorithm: int\n \n signature: bytes\n \n at: aioquic.tls.Context\n _set_state(state: State) -> None\n \n at: aioquic.tls.Context.__init__\n self.cadata: Optional[bytes] = None\n \n self.cafile: Optional[str] = None\n \n self.capath: Optional[str] = None\n \n self.key_schedule: Optional[KeySchedule] = None\n \n self.server_name: Optional[str] = None\n \n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n \n self._peer_certificate: Optional[x509.Certificate] = None\n \n self._peer_certificate_chain: List[x509.Certificate] = []\n \n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n \n===========unchanged ref 1===========\n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n at: aioquic.tls.KeySchedule\n certificate_verify_data(context_string: bytes) -> bytes\n \n update_hash(data: bytes) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + verify_mode: Optional[int] = None,\n ):\n self.alpn_negotiated: Optional[str] = None\n self.alpn_protocols: Optional[List[str]] = None\n self.cadata: Optional[bytes] = None\n self.cafile: Optional[str] = None\n self.capath: Optional[str] = None\n self.certificate: Optional[x509.Certificate] = None\n self.certificate_chain: List[x509.Certificate] = []\n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n self.early_data_accepted = False\n self.handshake_extensions: List[Extension] = []\n self.key_schedule: Optional[KeySchedule] = None\n self.max_early_data = max_early_data\n self.received_extensions: Optional[List[Extension]] = None\n self.session_ticket: Optional[SessionTicket] = None\n self.server_name: Optional[str] = None\n + if verify_mode is not None:\n + self.verify_mode = verify_mode\n + else:\n + self.verify_mode = (\n + ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n + )\n \n # callbacks\n self.alpn_cb: Optional[AlpnHandler] = None\n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher\n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + verify_mode: Optional[int] = None,\n ):\n # offset: 1\n Suite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n if default_backend().x25519_supported():\n self._supported_groups.append(Group.X25519)\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_\n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + verify_mode: Optional[int] = None,\n ):\n # offset: 2\n ed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n "}}},{"rowIdx":3665,"cells":{"path":{"kind":"string","value":"aioquic.quic.connection/QuicConnection._initialize"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"4a52a6526e5edad5ca262c7eb66aa723ed38e523"},"commit_message":{"kind":"string","value":"[tls] make it possible to disable certificate verification"},"ground_truth":{"kind":"string","value":" <5>: verify_mode=self._configuration.verify_mode,\n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n <0> # TLS\n <1> self.tls = tls.Context(\n <2> is_client=self._is_client,\n <3> logger=self._logger,\n <4> max_early_data=None if self._is_client else MAX_EARLY_DATA,\n <5> )\n <6> self.tls.alpn_protocols = self._configuration.alpn_protocols\n <7> self.tls.cadata = self._configuration.cadata\n <8> self.tls.cafile = self._configuration.cafile\n <9> self.tls.capath = self._configuration.capath\n<10> self.tls.certificate = self._configuration.certificate\n<11> self.tls.certificate_chain = self._configuration.certificate_chain\n<12> self.tls.certificate_private_key = self._configuration.private_key\n<13> self.tls.handshake_extensions = [\n<14> (\n<15> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n<16> self._serialize_transport_parameters(),\n<17> )\n<18> ]\n<19> self.tls.server_name = self._configuration.server_name\n<20> \n<21> # TLS session resumption\n<22> session_ticket = self._configuration.session_ticket\n<23> if (\n<24> self._is_client\n<25> and session_ticket is not None\n<26> and session_ticket.is_valid\n<27> and session_ticket.server_name == self._configuration.server_name\n<28> ):\n<29> self.tls.session_ticket = self._configuration.session_ticket\n<30> \n<31> # parse saved QUIC transport parameters - for 0-RTT\n<32> if session_ticket.max_early_data_size == MAX_EARLY_DATA:\n<33> for ext_type, ext_data in session_ticket.other_extensions:\n<34> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n<35> self._parse_transport_parameters(\n<36> ext_data, from_session_ticket=True\n<37> )\n<38> break\n<39> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 1\n self.tls.alpn_cb = self._alpn_handler\n if self._session_ticket_fetcher is not None:\n self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n if self._session_ticket_handler is not None:\n self.tls.new_session_ticket_cb = self._handle_session_ticket\n self.tls.update_traffic_key_cb = self._update_traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n self._cryptos[tls.Epoch.INITIAL].setup_initial(\n cid=peer_cid, is_client=self._is_client, version=self._version\n )\n \n self._loss.spaces = list(self._spaces.values())\n self._packet_number = 0\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n verify_mode: Optional[int] = None\n \n at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain\n self.certificate = certificates[0]\n \n self.certificate_chain = certificates[1:]\n \n self.private_key = load_pem_private_key(fp.read(), password=password)\n \n at: aioquic.quic.configuration.QuicConfiguration.load_verify_locations\n self.cafile = cafile\n \n self.capath = capath\n \n self.cadata = cadata\n \n at: aioquic.quic.connection\n MAX_EARLY_DATA = 0xFFFFFFFF\n \n at: aioquic.quic.connection.QuicConnection\n _alpn_handler(alpn_protocol: str) -> None\n \n _handle_session_ticket(session_ticket: tls.SessionTicket) -> None\n \n \n===========unchanged ref 1===========\n _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None\n \n _serialize_transport_parameters() -> bytes\n \n _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n self._version: Optional[int] = None\n \n self._logger = QuicConnectionAdapter(\n logger, {\"id\": dump_cid(logger_connection_id)}\n )\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client,\n quic_logger=self._quic_logger,\n send_probe=self._send_probe,\n )\n \n self._session_ticket_fetcher = session_ticket_fetcher\n \n self._session_ticket_handler = session_ticket_handler\n \n at: aioquic.quic.connection.QuicConnection.connect\n self._version = self._configuration.supported_versions[0]\n \n at: aioquic.quic.connection.QuicConnection.receive_datagram\n self._version = QuicProtocolVersion(header.version)\n self._version = QuicProtocolVersion(max(common))\n \n at: aioquic.quic.crypto\n CryptoPair()\n \n at: aioquic.quic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool, version: int) -> None\n \n at: aioquic.quic.recovery\n QuicPacketSpace()\n \n \n===========unchanged ref 2===========\n at: aioquic.quic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: aioquic.quic.stream\n QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)\n \n at: aioquic.tls\n Epoch()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None)\n \n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n self.cadata: Optional[bytes] = None\n \n self.cafile: Optional[str] = None\n \n self.capath: Optional[str] = None\n \n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_chain: List[x509.Certificate] = []\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n self.alpn_cb: Optional[AlpnHandler] = None\n \n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n at: aioquic.tls.SessionTicket\n age_add: int\n \n "}}},{"rowIdx":3666,"cells":{"path":{"kind":"string","value":"examples.interop/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"4a52a6526e5edad5ca262c7eb66aa723ed38e523"},"commit_message":{"kind":"string","value":"[tls] make it possible to disable certificate verification"},"ground_truth":{"kind":"string","value":" <8>: verify_mode=server.verify_mode,\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def run(servers, tests, quic_log=False, secrets_log_file=None) -> None:\n <0> for server in servers:\n <1> for test_name, test_func in tests:\n <2> print(\"\\n=== %s %s ===\\n\" % (server.name, test_name))\n <3> configuration = QuicConfiguration(\n <4> alpn_protocols=H3_ALPN + H0_ALPN,\n <5> is_client=True,\n <6> quic_logger=QuicLogger(),\n <7> secrets_log_file=secrets_log_file,\n <8> )\n <9> if test_name == \"test_throughput\":\n<10> timeout = 60\n<11> else:\n<12> timeout = 5\n<13> try:\n<14> await asyncio.wait_for(\n<15> test_func(server, configuration), timeout=timeout\n<16> )\n<17> except Exception as exc:\n<18> print(exc)\n<19> \n<20> if quic_log:\n<21> with open(\"%s-%s.qlog\" % (server.name, test_name), \"w\") as logger_fp:\n<22> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4)\n<23> \n<24> print(\"\")\n<25> print_result(server)\n<26> \n<27> # print summary\n<28> if len(servers) > 1:\n<29> print(\"SUMMARY\")\n<30> for server in servers:\n<31> print_result(server)\n<32> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h0.connection\n H0_ALPN = [\"hq-23\", \"hq-22\"]\n \n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n \n===========unchanged ref 1===========\n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n verify_mode: Optional[int] = None\n \n at: aioquic.quic.logger\n QuicLogger()\n \n at: aioquic.quic.logger.QuicLogger\n to_dict() -> Dict[str, Any]\n \n at: asyncio.tasks\n wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]\n \n at: examples.interop\n print_result(server: Server) -> None\n \n at: examples.interop.Server\n name: str\n \n host: str\n \n port: int = 4433\n \n http3: bool = True\n \n retry_port: Optional[int] = 4434\n \n path: str = \"/\"\n \n result: Result = field(default_factory=lambda: Result(0))\n \n verify_mode: Optional[int] = None\n \n at: json\n dump(obj: Any, fp: IO[str], *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.quic.configuration\n @dataclass\n class QuicConfiguration:\n \"\"\"\n A QUIC configuration.\n \"\"\"\n \n alpn_protocols: Optional[List[str]] = None\n \"\"\"\n A list of supported ALPN protocols.\n \"\"\"\n \n connection_id_length: int = 8\n \"\"\"\n The length in bytes of local connection IDs.\n \"\"\"\n \n idle_timeout: float = 60.0\n \"\"\"\n The idle timeout in seconds.\n \n The connection is terminated if nothing is received for the given duration.\n \"\"\"\n \n is_client: bool = True\n \"\"\"\n Whether this is the client side of the QUIC connection.\n \"\"\"\n \n quic_logger: Optional[QuicLogger] = None\n \"\"\"\n The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to.\n \"\"\"\n \n secrets_log_file: TextIO = None\n \"\"\"\n A file-like object in which to log traffic secrets.\n \n This is useful to analyze traffic captures with Wireshark.\n \"\"\"\n \n server_name: Optional[str] = None\n \"\"\"\n The server name to send during the TLS handshake the Server Name Indication.\n \n .. note:: This is only used by clients.\n \"\"\"\n \n session_ticket: Optional[SessionTicket] = None\n \"\"\"\n The TLS session ticket which should be used for session resumption.\n \"\"\"\n \n cadata: Optional[bytes] = None\n cafile: Optional[str] = None\n capath: Optional[str] = None\n certificate: Any = None\n certificate_chain: List[Any] = field(default_factory=list)\n private_key: Any = None\n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n + verify_mode: Optional[int] = None\n \n===========changed ref 1===========\n # module: examples.interop\n @dataclass\n class Server:\n name: str\n host: str\n port: int = 4433\n http3: bool = True\n retry_port: Optional[int] = 4434\n path: str = \"/\"\n result: Result = field(default_factory=lambda: Result(0))\n + verify_mode: Optional[int] = None\n \n===========changed ref 2===========\n # module: examples.interop\n SERVERS = [\n Server(\"aioquic\", \"quic.aiortc.org\", port=443),\n Server(\"ats\", \"quic.ogre.com\"),\n Server(\"f5\", \"f5quic.com\", retry_port=4433),\n Server(\"gquic\", \"quic.rocks\", retry_port=None),\n Server(\"lsquic\", \"http3-test.litespeedtech.com\"),\n + Server(\n + \"msquic\", \"quic.westus.cloudapp.azure.com\", port=443, verify_mode=ssl.CERT_NONE\n - Server(\"msquic\", \"quic.westus.cloudapp.azure.com\", port=443),\n + ),\n Server(\"mvfst\", \"fb.mvfst.net\"),\n Server(\"ngtcp2\", \"nghttp2.org\"),\n Server(\"ngx_quic\", \"cloudflare-quic.com\", port=443, retry_port=443),\n Server(\"pandora\", \"pandora.cm.in.tum.de\"),\n Server(\"picoquic\", \"test.privateoctopus.com\"),\n Server(\"quant\", \"quant.eggert.org\", http3=False),\n Server(\"quic-go\", \"quic.seemann.io\", port=443, retry_port=443),\n Server(\"quiche\", \"quic.tech\", port=8443, retry_port=4433),\n Server(\"quicker\", \"quicker.edm.uhasselt.be\", retry_port=None),\n Server(\"quicly\", \"kazuhooku.com\"),\n Server(\"quinn\", \"ralith.com\"),\n ]\n "}}},{"rowIdx":3667,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <0>: # configuration\n self._alpn_protocols = alpn_protocols\n self._cadata = cadata\n self._cafile = cafile\n self._capath = capath\n self.alpn_negotiated: Optional[str] = None\n <1>: self.alpn_protocols: Optional[List[str]] = None\n <2>: self.cadata: Optional[bytes] = None\n <3>: self.cafile: Optional[str] = None\n <4>: self.capath: Optional[str] = None\n<10>: self.early_data_accepted = False\n<12>: self.key_schedule: Optional[KeySchedule] = None\n<13>: self._max_early_data = max_early_data\n self.max_early_data = max_early_data\n<14>: self.received_extensions: Optional[List[Extension]] = None\n<16>: self._server_name = server_name\n self.server_name: Optional[str] = None\n<18>: self._verify_mode = verify_mode\n self.verify_mode = verify_mode\n<20>: self.verify_mode = (\n<21>: self._verify_mode = ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n<22>: )\n"},"main_code":{"kind":"string","value":" : bool,\n + alpn_protocols: Optional[List[str]] = None,\n + cadata: Optional[bytes] = None,\n + cafile: Optional[str] = None,\n + capath: Optional[str] = None,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + server_name: Optional[str] = None,\n verify_mode: Optional[int] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.cadata: Optional[bytes] = None\n <3> self.cafile: Optional[str] = None\n <4> self.capath: Optional[str] = None\n <5> self.certificate: Optional[x509.Certificate] = None\n <6> self.certificate_chain: List[x509.Certificate] = []\n <7> self.certificate_private_key: Optional[\n <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <9> ] = None\n<10> self.early_data_accepted = False\n<11> self.handshake_extensions: List[Extension] = []\n<12> self.key_schedule: Optional[KeySchedule] = None\n<13> self.max_early_data = max_early_data\n<14> self.received_extensions: Optional[List[Extension]] = None\n<15> self.session_ticket: Optional[SessionTicket] = None\n<16> self.server_name: Optional[str] = None\n<17> if verify_mode is not None:\n<18> self.verify_mode = verify_mode\n<19> else:\n<20> self.verify_mode = (\n<21> ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n<22> )\n<23> \n<24> # callbacks\n<25> self.alpn_cb: Optional[AlpnHandler] = None\n<26> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<27> self.new_session_ticket"},"context":{"kind":"string","value":"===========below chunk 0===========\n alpn_protocols: Optional[List[str]] = None,\n + cadata: Optional[bytes] = None,\n + cafile: Optional[str] = None,\n + capath: Optional[str] = None,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + server_name: Optional[str] = None,\n verify_mode: Optional[int] = None,\n ):\n # offset: 1\n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n if default_backend().x25519_supported():\n self._supported_groups.append(Group.X25519)\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain\n===========below chunk 1===========\n alpn_protocols: Optional[List[str]] = None,\n + cadata: Optional[bytes] = None,\n + cafile: Optional[str] = None,\n + capath: Optional[str] = None,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + server_name: Optional[str] = None,\n verify_mode: Optional[int] = None,\n ):\n # offset: 2\n Ticket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._peer_certificate_chain: List[x509.Certificate] = []\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Extension = Tuple[int, bytes]\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n AlpnHandler = Callable[[str], None]\n \n \n===========unchanged ref 1===========\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n "}}},{"rowIdx":3668,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._build_session_ticket"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":"<19>: server_name=self._server_name,\n server_name=self.server_name,\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n <0> resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n <1> resumption_secret = hkdf_expand_label(\n <2> algorithm=self.key_schedule.algorithm,\n <3> secret=resumption_master_secret,\n <4> label=b\"resumption\",\n <5> hash_value=new_session_ticket.ticket_nonce,\n <6> length=self.key_schedule.algorithm.digest_size,\n <7> )\n <8> \n <9> timestamp = utcnow()\n<10> return SessionTicket(\n<11> age_add=new_session_ticket.ticket_age_add,\n<12> cipher_suite=self.key_schedule.cipher_suite,\n<13> max_early_data_size=new_session_ticket.max_early_data_size,\n<14> not_valid_after=timestamp\n<15> + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n<16> not_valid_before=timestamp,\n<17> other_extensions=self.handshake_extensions,\n<18> resumption_secret=resumption_secret,\n<19> server_name=self.server_name,\n<20> ticket=new_session_ticket.ticket,\n<21> )\n<22> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n utcnow = datetime.datetime.utcnow\n \n hkdf_expand_label(algorithm: hashes.HashAlgorithm, secret: bytes, label: bytes, hash_value: bytes, length: int) -> bytes\n \n NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b\"\", ticket: bytes=b\"\", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n at: aioquic.tls.Context.__init__\n self.handshake_extensions: List[Extension] = []\n \n self.key_schedule: Optional[KeySchedule] = None\n \n self.server_name: Optional[str] = None\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n at: aioquic.tls.KeySchedule\n derive_secret(label: bytes) -> bytes\n \n at: aioquic.tls.KeySchedule.__init__\n self.algorithm = cipher_suite_hash(cipher_suite)\n \n self.cipher_suite = cipher_suite\n \n at: aioquic.tls.NewSessionTicket\n ticket_lifetime: int = 0\n \n ticket_age_add: int = 0\n \n ticket_nonce: bytes = b\"\"\n \n ticket: bytes = b\"\"\n \n \n===========unchanged ref 1===========\n max_early_data_size: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n at: aioquic.tls.SessionTicket\n age_add: int\n \n cipher_suite: CipherSuite\n \n not_valid_after: datetime.datetime\n \n not_valid_before: datetime.datetime\n \n resumption_secret: bytes\n \n server_name: str\n \n ticket: bytes\n \n max_early_data_size: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n at: datetime\n timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)\n \n at: datetime.timedelta\n __slots__ = '_days', '_seconds', '_microseconds', '_hashcode'\n \n __radd__ = __add__\n \n __rmul__ = __mul__\n \n \n===========changed ref 0===========\n : bool,\n + alpn_protocols: Optional[List[str]] = None,\n + cadata: Optional[bytes] = None,\n + cafile: Optional[str] = None,\n + capath: Optional[str] = None,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + server_name: Optional[str] = None,\n verify_mode: Optional[int] = None,\n ):\n + # configuration\n + self._alpn_protocols = alpn_protocols\n + self._cadata = cadata\n + self._cafile = cafile\n + self._capath = capath\n - self.alpn_negotiated: Optional[str] = None\n - self.alpn_protocols: Optional[List[str]] = None\n - self.cadata: Optional[bytes] = None\n - self.cafile: Optional[str] = None\n - self.capath: Optional[str] = None\n self.certificate: Optional[x509.Certificate] = None\n self.certificate_chain: List[x509.Certificate] = []\n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n - self.early_data_accepted = False\n self.handshake_extensions: List[Extension] = []\n - self.key_schedule: Optional[KeySchedule] = None\n + self._max_early_data = max_early_data\n - self.max_early_data = max_early_data\n - self.received_extensions: Optional[List[Extension]] = None\n self.session_ticket: Optional[SessionTicket] = None\n + self._server_name = server_name\n - self.server_name: Optional[str] = None\n if verify_mode is not None:\n + self._verify_mode = verify_mode\n - self.verify_mode = verify_mode\n else:\n - self.\n===========changed ref 1===========\n alpn_protocols: Optional[List[str]] = None,\n + cadata: Optional[bytes] = None,\n + cafile: Optional[str] = None,\n + capath: Optional[str] = None,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n max_early_data: Optional[int] = None,\n + server_name: Optional[str] = None,\n verify_mode: Optional[int] = None,\n ):\n # offset: 1\n self._verify_mode = verify_mode\n - self.verify_mode = verify_mode\n else:\n - self.verify_mode = (\n + self._verify_mode = ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n - ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n - )\n \n # callbacks\n self.alpn_cb: Optional[AlpnHandler] = None\n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods: List[int] = [CompressionMethod.NULL]\n self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA"}}},{"rowIdx":3669,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_send_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":"<22>: alpn_protocols=self._alpn_protocols,\n alpn_protocols=self.alpn_protocols,\n<27>: server_name=self._server_name,\n server_name=self.server_name,\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n <0> key_share: List[KeyShareEntry] = []\n <1> supported_groups: List[int] = []\n <2> \n <3> if Group.SECP256R1 in self._supported_groups:\n <4> self._ec_private_key = ec.generate_private_key(\n <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n <6> )\n <7> key_share.append(encode_public_key(self._ec_private_key.public_key()))\n <8> supported_groups.append(Group.SECP256R1)\n <9> \n<10> if Group.X25519 in self._supported_groups:\n<11> self._x25519_private_key = x25519.X25519PrivateKey.generate()\n<12> key_share.append(encode_public_key(self._x25519_private_key.public_key()))\n<13> supported_groups.append(Group.X25519)\n<14> \n<15> assert len(key_share), \"no key share entries\"\n<16> \n<17> hello = ClientHello(\n<18> random=self.client_random,\n<19> session_id=self.session_id,\n<20> cipher_suites=[int(x) for x in self._cipher_suites],\n<21> compression_methods=self._compression_methods,\n<22> alpn_protocols=self.alpn_protocols,\n<23> key_share=key_share,\n<24> psk_key_exchange_modes=self._psk_key_exchange_modes\n<25> if (self.session_ticket or self.new_session_ticket_cb is not None)\n<26> else None,\n<27> server_name=self.server_name,\n<28> signature_algorithms=self._signature_algorithms,\n<29> supported_groups=supported_groups,\n<30> supported_versions=self._supported_versions,\n<31> other_extensions=self.handshake_extensions,\n<32> )\n<33> \n<34> # PSK\n<35> if self.session_ticket and self.session_ticket"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 1\n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n self._key_schedule_psk.extract(self.session_ticket.resumption_secret)\n binder_key = self._key_schedule_psk.derive_secret(b\"res binder\")\n binder_length = self._key_schedule_psk.algorithm.digest_size\n \n # update hello\n if self.session_ticket.max_early_data_size is not None:\n hello.early_data = True\n hello.pre_shared_key = OfferedPsks(\n identities=[\n (self.session_ticket.ticket, self.session_ticket.obfuscated_age)\n ],\n binders=[bytes(binder_length)],\n )\n \n # serialize hello without binder\n tmp_buf = Buffer(capacity=1024)\n push_client_hello(tmp_buf, hello)\n \n # calculate binder\n hash_offset = tmp_buf.tell() - binder_length - 3\n self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset))\n binder = self._key_schedule_psk.finished_verify_data(binder_key)\n hello.pre_shared_key.binders[0] = binder\n self._key_schedule_psk.update_hash(\n tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder\n )\n \n # calculate early data key\n if hello.early_data:\n early_key = self._key_schedule_psk.derive_secret(b\"c e traffic\")\n self.update_traffic_key_cb(\n Direction.ENCRYPT,\n Epoch.ZERO_RTT,\n self._key_schedule_psk.cipher_suite,\n early_key,\n )\n \n self._key_schedule_proxy = Key\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 2\n schedule_psk.cipher_suite,\n early_key,\n )\n \n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n self._key_schedule_proxy.extract(None)\n \n with push_message(self._key_schedule_proxy, output_buf):\n push_client_hello(output_buf, hello)\n \n self._set_state(State.CLIENT_EXPECT_SERVER_HELLO)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n data_slice(start: int, end: int) -> bytes\n \n tell() -> int\n \n at: aioquic.tls\n Direction()\n \n Epoch()\n \n State()\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n KeyShareEntry = Tuple[int, bytes]\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[int], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[int]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[int]]=None, supported_groups: Optional[List[int]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n push_client_hello(buf: Buffer, hello: ClientHello) -> None\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n GROUP_TO_CURVE: Dict = {\n Group.SECP256R1: ec.SECP256R1,\n Group.SECP384R1: ec.SECP384R1,\n Group.SECP521R1: ec.SECP521R1,\n }\n \n encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry\n \n \n===========unchanged ref 1===========\n push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator\n \n at: aioquic.tls.ClientHello\n random: bytes\n \n session_id: bytes\n \n cipher_suites: List[int]\n \n compression_methods: List[int]\n \n alpn_protocols: Optional[List[str]] = None\n \n early_data: bool = False\n \n key_share: Optional[List[KeyShareEntry]] = None\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n psk_key_exchange_modes: Optional[List[int]] = None\n \n server_name: Optional[str] = None\n \n signature_algorithms: Optional[List[int]] = None\n \n supported_groups: Optional[List[int]] = None\n \n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n at: aioquic.tls.Context\n _set_state(state: State) -> None\n \n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n \n self._compression_methods: List[int] = [CompressionMethod.NULL]\n \n "}}},{"rowIdx":3670,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_handle_certificate_verify"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":"<17>: if self._verify_mode != ssl.CERT_NONE:\n if self.verify_mode != ssl.CERT_NONE:\n<19>: cadata=self._cadata,\n cadata=self.cadata,\n<20>: cafile=self._cafile,\n cafile=self.cafile,\n<21>: capath=self._capath,\n capath=self.capath,\n<24>: server_name=self._server_name,\n server_name=self.server_name,\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_handle_certificate_verify(self, input_buf: Buffer) -> None:\n <0> verify = pull_certificate_verify(input_buf)\n <1> \n <2> assert verify.algorithm in self._signature_algorithms\n <3> \n <4> # check signature\n <5> try:\n <6> self._peer_certificate.public_key().verify(\n <7> verify.signature,\n <8> self.key_schedule.certificate_verify_data(\n <9> b\"TLS 1.3, server CertificateVerify\"\n<10> ),\n<11> *signature_algorithm_params(verify.algorithm),\n<12> )\n<13> except InvalidSignature:\n<14> raise AlertDecryptError\n<15> \n<16> # check certificate\n<17> if self.verify_mode != ssl.CERT_NONE:\n<18> verify_certificate(\n<19> cadata=self.cadata,\n<20> cafile=self.cafile,\n<21> capath=self.capath,\n<22> certificate=self._peer_certificate,\n<23> chain=self._peer_certificate_chain,\n<24> server_name=self.server_name,\n<25> )\n<26> \n<27> self.key_schedule.update_hash(input_buf.data)\n<28> \n<29> self._set_state(State.CLIENT_EXPECT_FINISHED)\n<30> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.tls\n AlertDecryptError(*args: object)\n \n State()\n \n verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None\n \n pull_certificate_verify(buf: Buffer) -> CertificateVerify\n \n signature_algorithm_params(signature_algorithm: int) -> Union[Tuple[ec.ECDSA], Tuple[padding.AsymmetricPadding, hashes.HashAlgorithm]]\n \n at: aioquic.tls.CertificateVerify\n algorithm: int\n \n signature: bytes\n \n at: aioquic.tls.Context\n _set_state(state: State) -> None\n \n at: aioquic.tls.Context.__init__\n self.cadata: Optional[bytes] = None\n \n self.cafile: Optional[str] = None\n \n self.capath: Optional[str] = None\n \n self.key_schedule: Optional[KeySchedule] = None\n \n self.server_name: Optional[str] = None\n \n self.verify_mode = verify_mode\n self.verify_mode = (\n ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE\n )\n \n self._signature_algorithms: List[int] = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n \n self._peer_certificate: Optional[x509.Certificate] = None\n \n self._peer_certificate_chain: List[x509.Certificate] = []\n \n \n===========unchanged ref 1===========\n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n self._peer_certificate_chain = [\n x509.load_der_x509_certificate(\n certificate.certificates[i][0], backend=default_backend()\n )\n for i in range(1, len(certificate.certificates))\n ]\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n at: aioquic.tls.KeySchedule\n certificate_verify_data(context_string: bytes) -> bytes\n \n update_hash(data: bytes) -> None\n \n at: ssl\n CERT_NONE: int\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n \n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n key_share: List[KeyShareEntry] = []\n supported_groups: List[int] = []\n \n if Group.SECP256R1 in self._supported_groups:\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n key_share.append(encode_public_key(self._ec_private_key.public_key()))\n supported_groups.append(Group.SECP256R1)\n \n if Group.X25519 in self._supported_groups:\n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n key_share.append(encode_public_key(self._x25519_private_key.public_key()))\n supported_groups.append(Group.X25519)\n \n assert len(key_share), \"no key share entries\"\n \n hello = ClientHello(\n random=self.client_random,\n session_id=self.session_id,\n cipher_suites=[int(x) for x in self._cipher_suites],\n compression_methods=self._compression_methods,\n + alpn_protocols=self._alpn_protocols,\n - alpn_protocols=self.alpn_protocols,\n key_share=key_share,\n psk_key_exchange_modes=self._psk_key_exchange_modes\n if (self.session_ticket or self.new_session_ticket_cb is not None)\n else None,\n + server_name=self._server_name,\n - server_name=self.server_name,\n signature_algorithms=self._signature_algorithms,\n supported_groups=supported_groups,\n supported_versions=self._supported_versions,\n other_extensions=self.handshake_extensions,\n )\n \n # PSK\n if self.session_ticket and self.session_ticket.is_valid:\n "}}},{"rowIdx":3671,"cells":{"path":{"kind":"string","value":"aioquic.quic.connection/QuicConnection._initialize"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <2>: alpn_protocols=self._configuration.alpn_protocols,\n cadata=self._configuration.cadata,\n cafile=self._configuration.cafile,\n capath=self._configuration.capath,\n <5>: server_name=self._configuration.server_name,\n <7>: self.tls.alpn_protocols = self._configuration.alpn_protocols\n <8>: self.tls.cadata = self._configuration.cadata\n <9>: self.tls.cafile = self._configuration.cafile\n<10>: self.tls.capath = self._configuration.capath\n<20>: self.tls.server_name = self._configuration.server_name\n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n <0> # TLS\n <1> self.tls = tls.Context(\n <2> is_client=self._is_client,\n <3> logger=self._logger,\n <4> max_early_data=None if self._is_client else MAX_EARLY_DATA,\n <5> verify_mode=self._configuration.verify_mode,\n <6> )\n <7> self.tls.alpn_protocols = self._configuration.alpn_protocols\n <8> self.tls.cadata = self._configuration.cadata\n <9> self.tls.cafile = self._configuration.cafile\n<10> self.tls.capath = self._configuration.capath\n<11> self.tls.certificate = self._configuration.certificate\n<12> self.tls.certificate_chain = self._configuration.certificate_chain\n<13> self.tls.certificate_private_key = self._configuration.private_key\n<14> self.tls.handshake_extensions = [\n<15> (\n<16> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n<17> self._serialize_transport_parameters(),\n<18> )\n<19> ]\n<20> self.tls.server_name = self._configuration.server_name\n<21> \n<22> # TLS session resumption\n<23> session_ticket = self._configuration.session_ticket\n<24> if (\n<25> self._is_client\n<26> and session_ticket is not None\n<27> and session_ticket.is_valid\n<28> and session_ticket.server_name == self._configuration.server_name\n<29> ):\n<30> self.tls.session_ticket = self._configuration.session_ticket\n<31> \n<32> # parse saved QUIC transport parameters - for 0-RTT\n<33> if session_ticket.max_early_data_size == MAX_EARLY_DATA:\n<34> for ext_type, ext_data in session_ticket.other_extensions:\n<35> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n<36> self._parse_transport_parameters(\n<37> ext_data, from_"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 1\n )\n break\n \n # TLS callbacks\n self.tls.alpn_cb = self._alpn_handler\n if self._session_ticket_fetcher is not None:\n self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n if self._session_ticket_handler is not None:\n self.tls.new_session_ticket_cb = self._handle_session_ticket\n self.tls.update_traffic_key_cb = self._update_traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n self._cryptos[tls.Epoch.INITIAL].setup_initial(\n cid=peer_cid, is_client=self._is_client, version=self._version\n )\n \n self._loss.spaces = list(self._spaces.values())\n self._packet_number = 0\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n verify_mode: Optional[int] = None\n \n at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain\n self.certificate = certificates[0]\n \n self.certificate_chain = certificates[1:]\n \n self.private_key = load_pem_private_key(fp.read(), password=password)\n \n at: aioquic.quic.configuration.QuicConfiguration.load_verify_locations\n self.cafile = cafile\n \n self.capath = capath\n \n self.cadata = cadata\n \n at: aioquic.quic.connection\n MAX_EARLY_DATA = 0xFFFFFFFF\n \n at: aioquic.quic.connection.QuicConnection\n _alpn_handler(alpn_protocol: str) -> None\n \n _handle_session_ticket(session_ticket: tls.SessionTicket) -> None\n \n \n===========unchanged ref 1===========\n _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None\n \n _serialize_transport_parameters() -> bytes\n \n _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._packet_number = 0\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n self._version: Optional[int] = None\n \n self._logger = QuicConnectionAdapter(\n logger, {\"id\": dump_cid(logger_connection_id)}\n )\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client,\n quic_logger=self._quic_logger,\n send_probe=self._send_probe,\n )\n \n self._session_ticket_fetcher = session_ticket_fetcher\n \n self._session_ticket_handler = session_ticket_handler\n \n at: aioquic.quic.connection.QuicConnection.connect\n self._version = self._configuration.supported_versions[0]\n \n at: aioquic.quic.connection.QuicConnection.datagrams_to_send\n self._packet_number = builder.packet_number\n \n at: aioquic.quic.connection.QuicConnection.receive_datagram\n self._version = QuicProtocolVersion(header.version)\n self._version = QuicProtocolVersion(max(common))\n \n at: aioquic.quic.crypto\n CryptoPair()\n \n \n===========unchanged ref 2===========\n at: aioquic.quic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool, version: int) -> None\n \n at: aioquic.quic.recovery\n QuicPacketSpace()\n \n at: aioquic.quic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: aioquic.quic.stream\n QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)\n \n at: aioquic.tls\n Epoch()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, verify_mode: Optional[int]=None)\n \n at: aioquic.tls.Context.__init__\n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_chain: List[x509.Certificate] = []\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.alpn_cb: Optional[AlpnHandler] = None\n \n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n at: aioquic.tls.SessionTicket\n age_add: int\n \n cipher_suite: CipherSuite\n \n "}}},{"rowIdx":3672,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect_with_0rtt_bad_max_early_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":"<12>: server.tls._max_early_data = 12345\n server.tls.max_early_data = 12345\n"},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_0rtt_bad_max_early_data(self):\n <0> client_ticket = None\n <1> ticket_store = SessionTicketStore()\n <2> \n <3> def patch(server):\n <4> \"\"\"\n <5> Patch server's TLS initialization to set an invalid\n <6> max_early_data value.\n <7> \"\"\"\n <8> real_initialize = server._initialize\n <9> \n<10> def patched_initialize(peer_cid: bytes):\n<11> real_initialize(peer_cid)\n<12> server.tls.max_early_data = 12345\n<13> \n<14> server._initialize = patched_initialize\n<15> \n<16> def save_session_ticket(ticket):\n<17> nonlocal client_ticket\n<18> client_ticket = ticket\n<19> \n<20> with client_and_server(\n<21> client_kwargs={\"session_ticket_handler\": save_session_ticket},\n<22> server_kwargs={\"session_ticket_handler\": ticket_store.add},\n<23> server_patch=patch,\n<24> ) as (client, server):\n<25> # check handshake failed\n<26> event = client.next_event()\n<27> self.assertIsNone(event)\n<28> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: tests.test_connection\n SessionTicketStore()\n \n client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_connection.SessionTicketStore\n add(ticket)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertIsNone(obj: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n \n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def _client_handle_certificate_verify(self, input_buf: Buffer) -> None:\n verify = pull_certificate_verify(input_buf)\n \n assert verify.algorithm in self._signature_algorithms\n \n # check signature\n try:\n self._peer_certificate.public_key().verify(\n verify.signature,\n self.key_schedule.certificate_verify_data(\n b\"TLS 1.3, server CertificateVerify\"\n ),\n *signature_algorithm_params(verify.algorithm),\n )\n except InvalidSignature:\n raise AlertDecryptError\n \n # check certificate\n + if self._verify_mode != ssl.CERT_NONE:\n - if self.verify_mode != ssl.CERT_NONE:\n verify_certificate(\n + cadata=self._cadata,\n - cadata=self.cadata,\n + cafile=self._cafile,\n - cafile=self.cafile,\n + capath=self._capath,\n - capath=self.capath,\n certificate=self._peer_certificate,\n chain=self._peer_certificate_chain,\n + server_name=self._server_name,\n - server_name=self.server_name,\n )\n \n self.key_schedule.update_hash(input_buf.data)\n \n self._set_state(State.CLIENT_EXPECT_FINISHED)\n \n===========changed ref 2===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # TLS\n self.tls = tls.Context(\n + alpn_protocols=self._configuration.alpn_protocols,\n + cadata=self._configuration.cadata,\n + cafile=self._configuration.cafile,\n + capath=self._configuration.capath,\n is_client=self._is_client,\n logger=self._logger,\n max_early_data=None if self._is_client else MAX_EARLY_DATA,\n + server_name=self._configuration.server_name,\n verify_mode=self._configuration.verify_mode,\n )\n - self.tls.alpn_protocols = self._configuration.alpn_protocols\n - self.tls.cadata = self._configuration.cadata\n - self.tls.cafile = self._configuration.cafile\n - self.tls.capath = self._configuration.capath\n self.tls.certificate = self._configuration.certificate\n self.tls.certificate_chain = self._configuration.certificate_chain\n self.tls.certificate_private_key = self._configuration.private_key\n self.tls.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n self._serialize_transport_parameters(),\n )\n ]\n - self.tls.server_name = self._configuration.server_name\n \n # TLS session resumption\n session_ticket = self._configuration.session_ticket\n if (\n self._is_client\n and session_ticket is not None\n and session_ticket.is_valid\n and session_ticket.server_name == self._configuration.server_name\n ):\n self.tls.session_ticket = self._configuration.session_ticket\n \n # parse saved QUIC transport parameters - for 0-RTT\n if session_ticket.max_early_data_size == MAX_EARLY_DATA:\n for ext_type, ext_data in session_ticket.other_extensions\n===========changed ref 3===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 1\n _data_size == MAX_EARLY_DATA:\n for ext_type, ext_data in session_ticket.other_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(\n ext_data, from_session_ticket=True\n )\n break\n \n # TLS callbacks\n self.tls.alpn_cb = self._alpn_handler\n if self._session_ticket_fetcher is not None:\n self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n if self._session_ticket_handler is not None:\n self.tls.new_session_ticket_cb = self._handle_session_ticket\n self.tls.update_traffic_key_cb = self._update_traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n===========changed ref 4===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 2\n self._cryptos[tls.Epoch.INITIAL].setup_initial(\n cid=peer_cid, is_client=self._is_client, version=self._version\n )\n \n self._loss.spaces = list(self._spaces.values())\n self._packet_number = 0\n "}}},{"rowIdx":3673,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.create_client"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <0>: client = Context(\n client = Context(is_client=True)\n <1>: alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True\n )\n client.cafile = cafile\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE):\n - def create_client(self, cafile=SERVER_CACERTFILE):\n <0> client = Context(is_client=True)\n <1> client.cafile = cafile\n <2> client.handshake_extensions = [\n <3> (\n <4> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n <5> CLIENT_QUIC_TRANSPORT_PARAMETERS,\n <6> )\n <7> ]\n <8> self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START)\n <9> return client\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n State()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, verify_mode: Optional[int]=None)\n \n at: aioquic.tls.Context.__init__\n self.cafile: Optional[str] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: tests.test_tls\n CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify(\n b\"ff0000110031000500048010000000060004801000000007000480100000000\"\n b\"4000481000000000100024258000800024064000a00010a\"\n )\n \n at: tests.utils\n SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), \"pycacert.pem\")\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_0rtt_bad_max_early_data(self):\n client_ticket = None\n ticket_store = SessionTicketStore()\n \n def patch(server):\n \"\"\"\n Patch server's TLS initialization to set an invalid\n max_early_data value.\n \"\"\"\n real_initialize = server._initialize\n \n def patched_initialize(peer_cid: bytes):\n real_initialize(peer_cid)\n + server.tls._max_early_data = 12345\n - server.tls.max_early_data = 12345\n \n server._initialize = patched_initialize\n \n def save_session_ticket(ticket):\n nonlocal client_ticket\n client_ticket = ticket\n \n with client_and_server(\n client_kwargs={\"session_ticket_handler\": save_session_ticket},\n server_kwargs={\"session_ticket_handler\": ticket_store.add},\n server_patch=patch,\n ) as (client, server):\n # check handshake failed\n event = client.next_event()\n self.assertIsNone(event)\n \n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _client_handle_certificate_verify(self, input_buf: Buffer) -> None:\n verify = pull_certificate_verify(input_buf)\n \n assert verify.algorithm in self._signature_algorithms\n \n # check signature\n try:\n self._peer_certificate.public_key().verify(\n verify.signature,\n self.key_schedule.certificate_verify_data(\n b\"TLS 1.3, server CertificateVerify\"\n ),\n *signature_algorithm_params(verify.algorithm),\n )\n except InvalidSignature:\n raise AlertDecryptError\n \n # check certificate\n + if self._verify_mode != ssl.CERT_NONE:\n - if self.verify_mode != ssl.CERT_NONE:\n verify_certificate(\n + cadata=self._cadata,\n - cadata=self.cadata,\n + cafile=self._cafile,\n - cafile=self.cafile,\n + capath=self._capath,\n - capath=self.capath,\n certificate=self._peer_certificate,\n chain=self._peer_certificate_chain,\n + server_name=self._server_name,\n - server_name=self.server_name,\n )\n \n self.key_schedule.update_hash(input_buf.data)\n \n self._set_state(State.CLIENT_EXPECT_FINISHED)\n \n===========changed ref 3===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # TLS\n self.tls = tls.Context(\n + alpn_protocols=self._configuration.alpn_protocols,\n + cadata=self._configuration.cadata,\n + cafile=self._configuration.cafile,\n + capath=self._configuration.capath,\n is_client=self._is_client,\n logger=self._logger,\n max_early_data=None if self._is_client else MAX_EARLY_DATA,\n + server_name=self._configuration.server_name,\n verify_mode=self._configuration.verify_mode,\n )\n - self.tls.alpn_protocols = self._configuration.alpn_protocols\n - self.tls.cadata = self._configuration.cadata\n - self.tls.cafile = self._configuration.cafile\n - self.tls.capath = self._configuration.capath\n self.tls.certificate = self._configuration.certificate\n self.tls.certificate_chain = self._configuration.certificate_chain\n self.tls.certificate_private_key = self._configuration.private_key\n self.tls.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n self._serialize_transport_parameters(),\n )\n ]\n - self.tls.server_name = self._configuration.server_name\n \n # TLS session resumption\n session_ticket = self._configuration.session_ticket\n if (\n self._is_client\n and session_ticket is not None\n and session_ticket.is_valid\n and session_ticket.server_name == self._configuration.server_name\n ):\n self.tls.session_ticket = self._configuration.session_ticket\n \n # parse saved QUIC transport parameters - for 0-RTT\n if session_ticket.max_early_data_size == MAX_EARLY_DATA:\n for ext_type, ext_data in session_ticket.other_extensions"}}},{"rowIdx":3674,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.create_server"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <3>: server = Context(\n alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF\n )\n server = Context(is_client=False, max_early_data=0xFFFFFFFF)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_server(self, alpn_protocols=None):\n - def create_server(self):\n <0> configuration = QuicConfiguration(is_client=False)\n <1> configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n <2> \n <3> server = Context(is_client=False, max_early_data=0xFFFFFFFF)\n <4> server.certificate = configuration.certificate\n <5> server.certificate_private_key = configuration.private_key\n <6> server.handshake_extensions = [\n <7> (\n <8> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n <9> SERVER_QUIC_TRANSPORT_PARAMETERS,\n<10> )\n<11> ]\n<12> self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO)\n<13> return server\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n verify_mode: Optional[int] = None\n \n \n===========unchanged ref 1===========\n load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None\n \n at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain\n self.certificate = certificates[0]\n \n self.private_key = load_pem_private_key(fp.read(), password=password)\n \n at: aioquic.tls\n State()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, verify_mode: Optional[int]=None)\n \n at: aioquic.tls.Context.__init__\n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: tests.test_tls\n SERVER_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify(\n b\"ff00001104ff000011004500050004801000000006000480100000000700048\"\n b\"010000000040004810000000001000242580002001000000000000000000000\"\n b\"000000000000000800024064000a00010a\"\n )\n \n at: tests.utils\n SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), \"ssl_cert.pem\")\n \n SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), \"ssl_key.pem\")\n \n \n===========unchanged ref 2===========\n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE):\n - def create_client(self, cafile=SERVER_CACERTFILE):\n + client = Context(\n - client = Context(is_client=True)\n + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True\n + )\n - client.cafile = cafile\n client.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START)\n return client\n \n===========changed ref 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_0rtt_bad_max_early_data(self):\n client_ticket = None\n ticket_store = SessionTicketStore()\n \n def patch(server):\n \"\"\"\n Patch server's TLS initialization to set an invalid\n max_early_data value.\n \"\"\"\n real_initialize = server._initialize\n \n def patched_initialize(peer_cid: bytes):\n real_initialize(peer_cid)\n + server.tls._max_early_data = 12345\n - server.tls.max_early_data = 12345\n \n server._initialize = patched_initialize\n \n def save_session_ticket(ticket):\n nonlocal client_ticket\n client_ticket = ticket\n \n with client_and_server(\n client_kwargs={\"session_ticket_handler\": save_session_ticket},\n server_kwargs={\"session_ticket_handler\": ticket_store.add},\n server_patch=patch,\n ) as (client, server):\n # check handshake failed\n event = client.next_event()\n self.assertIsNone(event)\n \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n "}}},{"rowIdx":3675,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_handshake_ecdsa_secp256r1"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <5>: client = self.create_client(\n client = self.create_client(cafile=None)\n <6>: cadata=server.certificate.public_bytes(serialization.Encoding.PEM),\n client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM)\n <7>: cafile=None,\n )\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_ecdsa_secp256r1(self):\n <0> server = self.create_server()\n <1> server.certificate, server.certificate_private_key = generate_ec_certificate(\n <2> common_name=\"example.com\", curve=ec.SECP256R1\n <3> )\n <4> \n <5> client = self.create_client(cafile=None)\n <6> client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM)\n <7> \n <8> self._handshake(client, server)\n <9> \n<10> # check ALPN matches\n<11> self.assertEqual(client.alpn_negotiated, None)\n<12> self.assertEqual(server.alpn_negotiated, None)\n<13> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls.Context.__init__\n self.alpn_negotiated: Optional[str] = None\n \n self.cadata: Optional[bytes] = None\n \n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n at: aioquic.tls.Context._server_handle_hello\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n at: tests.test_tls.ContextTest\n create_client(cafile=SERVER_CACERTFILE)\n create_client(self, cafile=SERVER_CACERTFILE)\n \n create_server()\n create_server(self)\n \n _handshake(client, server)\n \n at: tests.utils\n generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[])\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE):\n - def create_client(self, cafile=SERVER_CACERTFILE):\n + client = Context(\n - client = Context(is_client=True)\n + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True\n + )\n - client.cafile = cafile\n client.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START)\n return client\n \n===========changed ref 1===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_server(self, alpn_protocols=None):\n - def create_server(self):\n configuration = QuicConfiguration(is_client=False)\n configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n \n + server = Context(\n + alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF\n + )\n - server = Context(is_client=False, max_early_data=0xFFFFFFFF)\n server.certificate = configuration.certificate\n server.certificate_private_key = configuration.private_key\n server.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n SERVER_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO)\n return server\n \n===========changed ref 2===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_0rtt_bad_max_early_data(self):\n client_ticket = None\n ticket_store = SessionTicketStore()\n \n def patch(server):\n \"\"\"\n Patch server's TLS initialization to set an invalid\n max_early_data value.\n \"\"\"\n real_initialize = server._initialize\n \n def patched_initialize(peer_cid: bytes):\n real_initialize(peer_cid)\n + server.tls._max_early_data = 12345\n - server.tls.max_early_data = 12345\n \n server._initialize = patched_initialize\n \n def save_session_ticket(ticket):\n nonlocal client_ticket\n client_ticket = ticket\n \n with client_and_server(\n client_kwargs={\"session_ticket_handler\": save_session_ticket},\n server_kwargs={\"session_ticket_handler\": ticket_store.add},\n server_patch=patch,\n ) as (client, server):\n # check handshake failed\n event = client.next_event()\n self.assertIsNone(event)\n \n===========changed ref 3===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n \n===========changed ref 4===========\n # module: aioquic.tls\n class Context:\n def _client_handle_certificate_verify(self, input_buf: Buffer) -> None:\n verify = pull_certificate_verify(input_buf)\n \n assert verify.algorithm in self._signature_algorithms\n \n # check signature\n try:\n self._peer_certificate.public_key().verify(\n verify.signature,\n self.key_schedule.certificate_verify_data(\n b\"TLS 1.3, server CertificateVerify\"\n ),\n *signature_algorithm_params(verify.algorithm),\n )\n except InvalidSignature:\n raise AlertDecryptError\n \n # check certificate\n + if self._verify_mode != ssl.CERT_NONE:\n - if self.verify_mode != ssl.CERT_NONE:\n verify_certificate(\n + cadata=self._cadata,\n - cadata=self.cadata,\n + cafile=self._cafile,\n - cafile=self.cafile,\n + capath=self._capath,\n - capath=self.capath,\n certificate=self._peer_certificate,\n chain=self._peer_certificate_chain,\n + server_name=self._server_name,\n - server_name=self.server_name,\n )\n \n self.key_schedule.update_hash(input_buf.data)\n \n self._set_state(State.CLIENT_EXPECT_FINISHED)\n "}}},{"rowIdx":3676,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_handshake_with_alpn"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <0>: client = self.create_client()\n <1>: client = self.create_client(alpn_protocols=[\"hq-20\"])\n client.alpn_protocols = [\"hq-20\"]\n <3>: server = self.create_server()\n <4>: server = self.create_server(alpn_protocols=[\"hq-20\", \"h3-20\"])\n server.alpn_protocols = [\"hq-20\", \"h3-20\"]\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_with_alpn(self):\n <0> client = self.create_client()\n <1> client.alpn_protocols = [\"hq-20\"]\n <2> \n <3> server = self.create_server()\n <4> server.alpn_protocols = [\"hq-20\", \"h3-20\"]\n <5> \n <6> self._handshake(client, server)\n <7> \n <8> # check ALPN matches\n <9> self.assertEqual(client.alpn_negotiated, \"hq-20\")\n<10> self.assertEqual(server.alpn_negotiated, \"hq-20\")\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls.Context.__init__\n self.alpn_negotiated: Optional[str] = None\n \n self.alpn_protocols: Optional[List[str]] = None\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n at: aioquic.tls.Context._server_handle_hello\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n at: tests.test_tls.ContextTest\n create_client(cafile=SERVER_CACERTFILE)\n create_client(self, cafile=SERVER_CACERTFILE)\n \n create_server()\n create_server(self)\n \n _handshake(client, server)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE):\n - def create_client(self, cafile=SERVER_CACERTFILE):\n + client = Context(\n - client = Context(is_client=True)\n + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True\n + )\n - client.cafile = cafile\n client.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START)\n return client\n \n===========changed ref 1===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_server(self, alpn_protocols=None):\n - def create_server(self):\n configuration = QuicConfiguration(is_client=False)\n configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n \n + server = Context(\n + alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF\n + )\n - server = Context(is_client=False, max_early_data=0xFFFFFFFF)\n server.certificate = configuration.certificate\n server.certificate_private_key = configuration.private_key\n server.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n SERVER_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO)\n return server\n \n===========changed ref 2===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_ecdsa_secp256r1(self):\n server = self.create_server()\n server.certificate, server.certificate_private_key = generate_ec_certificate(\n common_name=\"example.com\", curve=ec.SECP256R1\n )\n \n + client = self.create_client(\n - client = self.create_client(cafile=None)\n + cadata=server.certificate.public_bytes(serialization.Encoding.PEM),\n - client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM)\n + cafile=None,\n + )\n \n self._handshake(client, server)\n \n # check ALPN matches\n self.assertEqual(client.alpn_negotiated, None)\n self.assertEqual(server.alpn_negotiated, None)\n \n===========changed ref 3===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_0rtt_bad_max_early_data(self):\n client_ticket = None\n ticket_store = SessionTicketStore()\n \n def patch(server):\n \"\"\"\n Patch server's TLS initialization to set an invalid\n max_early_data value.\n \"\"\"\n real_initialize = server._initialize\n \n def patched_initialize(peer_cid: bytes):\n real_initialize(peer_cid)\n + server.tls._max_early_data = 12345\n - server.tls.max_early_data = 12345\n \n server._initialize = patched_initialize\n \n def save_session_ticket(ticket):\n nonlocal client_ticket\n client_ticket = ticket\n \n with client_and_server(\n client_kwargs={\"session_ticket_handler\": save_session_ticket},\n server_kwargs={\"session_ticket_handler\": ticket_store.add},\n server_patch=patch,\n ) as (client, server):\n # check handshake failed\n event = client.next_event()\n self.assertIsNone(event)\n \n===========changed ref 4===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n \n===========changed ref 5===========\n # module: aioquic.tls\n class Context:\n def _client_handle_certificate_verify(self, input_buf: Buffer) -> None:\n verify = pull_certificate_verify(input_buf)\n \n assert verify.algorithm in self._signature_algorithms\n \n # check signature\n try:\n self._peer_certificate.public_key().verify(\n verify.signature,\n self.key_schedule.certificate_verify_data(\n b\"TLS 1.3, server CertificateVerify\"\n ),\n *signature_algorithm_params(verify.algorithm),\n )\n except InvalidSignature:\n raise AlertDecryptError\n \n # check certificate\n + if self._verify_mode != ssl.CERT_NONE:\n - if self.verify_mode != ssl.CERT_NONE:\n verify_certificate(\n + cadata=self._cadata,\n - cadata=self.cadata,\n + cafile=self._cafile,\n - cafile=self.cafile,\n + capath=self._capath,\n - capath=self.capath,\n certificate=self._peer_certificate,\n chain=self._peer_certificate_chain,\n + server_name=self._server_name,\n - server_name=self.server_name,\n )\n \n self.key_schedule.update_hash(input_buf.data)\n \n self._set_state(State.CLIENT_EXPECT_FINISHED)\n "}}},{"rowIdx":3677,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_handshake_with_alpn_fail"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98"},"commit_message":{"kind":"string","value":"[tls] move configuration to keyword arguments"},"ground_truth":{"kind":"string","value":" <0>: client = self.create_client()\n <1>: client = self.create_client(alpn_protocols=[\"hq-20\"])\n client.alpn_protocols = [\"hq-20\"]\n <3>: server = self.create_server()\n <4>: server = self.create_server(alpn_protocols=[\"h3-20\"])\n server.alpn_protocols = [\"h3-20\"]\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_with_alpn_fail(self):\n <0> client = self.create_client()\n <1> client.alpn_protocols = [\"hq-20\"]\n <2> \n <3> server = self.create_server()\n <4> server.alpn_protocols = [\"h3-20\"]\n <5> \n <6> # send client hello\n <7> client_buf = create_buffers()\n <8> client.handle_message(b\"\", client_buf)\n <9> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n<10> server_input = merge_buffers(client_buf)\n<11> self.assertGreaterEqual(len(server_input), 258)\n<12> self.assertLessEqual(len(server_input), 296)\n<13> reset_buffers(client_buf)\n<14> \n<15> # handle client hello\n<16> # send server hello, encrypted extensions, certificate, certificate verify, finished\n<17> server_buf = create_buffers()\n<18> with self.assertRaises(tls.AlertHandshakeFailure) as cm:\n<19> server.handle_message(server_input, server_buf)\n<20> self.assertEqual(str(cm.exception), \"No common ALPN protocols\")\n<21> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n AlertHandshakeFailure(*args: object)\n \n State()\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: tests.test_tls.ContextTest\n create_client(cafile=SERVER_CACERTFILE)\n create_client(self, cafile=SERVER_CACERTFILE)\n \n create_server()\n create_server(self)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertLessEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n at: unittest.case._AssertRaisesContext.__exit__\n self.exception = exc_value.with_traceback(None)\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE):\n - def create_client(self, cafile=SERVER_CACERTFILE):\n + client = Context(\n - client = Context(is_client=True)\n + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True\n + )\n - client.cafile = cafile\n client.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START)\n return client\n \n===========changed ref 1===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n + def create_server(self, alpn_protocols=None):\n - def create_server(self):\n configuration = QuicConfiguration(is_client=False)\n configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n \n + server = Context(\n + alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF\n + )\n - server = Context(is_client=False, max_early_data=0xFFFFFFFF)\n server.certificate = configuration.certificate\n server.certificate_private_key = configuration.private_key\n server.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n SERVER_QUIC_TRANSPORT_PARAMETERS,\n )\n ]\n self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO)\n return server\n \n===========changed ref 2===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_with_alpn(self):\n - client = self.create_client()\n + client = self.create_client(alpn_protocols=[\"hq-20\"])\n - client.alpn_protocols = [\"hq-20\"]\n \n - server = self.create_server()\n + server = self.create_server(alpn_protocols=[\"hq-20\", \"h3-20\"])\n - server.alpn_protocols = [\"hq-20\", \"h3-20\"]\n \n self._handshake(client, server)\n \n # check ALPN matches\n self.assertEqual(client.alpn_negotiated, \"hq-20\")\n self.assertEqual(server.alpn_negotiated, \"hq-20\")\n \n===========changed ref 3===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_ecdsa_secp256r1(self):\n server = self.create_server()\n server.certificate, server.certificate_private_key = generate_ec_certificate(\n common_name=\"example.com\", curve=ec.SECP256R1\n )\n \n + client = self.create_client(\n - client = self.create_client(cafile=None)\n + cadata=server.certificate.public_bytes(serialization.Encoding.PEM),\n - client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM)\n + cafile=None,\n + )\n \n self._handshake(client, server)\n \n # check ALPN matches\n self.assertEqual(client.alpn_negotiated, None)\n self.assertEqual(server.alpn_negotiated, None)\n \n===========changed ref 4===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_0rtt_bad_max_early_data(self):\n client_ticket = None\n ticket_store = SessionTicketStore()\n \n def patch(server):\n \"\"\"\n Patch server's TLS initialization to set an invalid\n max_early_data value.\n \"\"\"\n real_initialize = server._initialize\n \n def patched_initialize(peer_cid: bytes):\n real_initialize(peer_cid)\n + server.tls._max_early_data = 12345\n - server.tls.max_early_data = 12345\n \n server._initialize = patched_initialize\n \n def save_session_ticket(ticket):\n nonlocal client_ticket\n client_ticket = ticket\n \n with client_and_server(\n client_kwargs={\"session_ticket_handler\": save_session_ticket},\n server_kwargs={\"session_ticket_handler\": ticket_store.add},\n server_patch=patch,\n ) as (client, server):\n # check handshake failed\n event = client.next_event()\n self.assertIsNone(event)\n \n===========changed ref 5===========\n # module: aioquic.tls\n class Context:\n def _build_session_ticket(\n self, new_session_ticket: NewSessionTicket\n ) -> SessionTicket:\n resumption_master_secret = self.key_schedule.derive_secret(b\"res master\")\n resumption_secret = hkdf_expand_label(\n algorithm=self.key_schedule.algorithm,\n secret=resumption_master_secret,\n label=b\"resumption\",\n hash_value=new_session_ticket.ticket_nonce,\n length=self.key_schedule.algorithm.digest_size,\n )\n \n timestamp = utcnow()\n return SessionTicket(\n age_add=new_session_ticket.ticket_age_add,\n cipher_suite=self.key_schedule.cipher_suite,\n max_early_data_size=new_session_ticket.max_early_data_size,\n not_valid_after=timestamp\n + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime),\n not_valid_before=timestamp,\n other_extensions=self.handshake_extensions,\n resumption_secret=resumption_secret,\n + server_name=self._server_name,\n - server_name=self.server_name,\n ticket=new_session_ticket.ticket,\n )\n "}}},{"rowIdx":3678,"cells":{"path":{"kind":"string","value":"examples.http3_server/HttpRequestHandler.send"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8c45dc8255673d5fa42194bb42208799d41e4e7e"},"commit_message":{"kind":"string","value":"[examples] fix typing warnings"},"ground_truth":{"kind":"string","value":"<35>: cast(HttpServerProtocol, self.protocol).http_event_received(\n self.protocol.http_event_received(\n"},"main_code":{"kind":"string","value":" # module: examples.http3_server\n class HttpRequestHandler:\n def send(self, message: Dict):\n <0> if message[\"type\"] == \"http.response.start\":\n <1> self.connection.send_headers(\n <2> stream_id=self.stream_id,\n <3> headers=[\n <4> (b\":status\", str(message[\"status\"]).encode(\"ascii\")),\n <5> (b\"server\", b\"aioquic\"),\n <6> (b\"date\", formatdate(time.time(), usegmt=True).encode()),\n <7> ]\n <8> + [(k, v) for k, v in message[\"headers\"]],\n <9> )\n<10> elif message[\"type\"] == \"http.response.body\":\n<11> self.connection.send_data(\n<12> stream_id=self.stream_id,\n<13> data=message.get(\"body\", b\"\"),\n<14> end_stream=not message.get(\"more_body\", False),\n<15> )\n<16> elif message[\"type\"] == \"http.response.push\" and isinstance(\n<17> self.connection, H3Connection\n<18> ):\n<19> request_headers = [\n<20> (b\":method\", b\"GET\"),\n<21> (b\":scheme\", b\"https\"),\n<22> (b\":authority\", self.authority),\n<23> (b\":path\", message[\"path\"].encode(\"utf8\")),\n<24> ] + [(k, v) for k, v in message[\"headers\"]]\n<25> \n<26> # send push promise\n<27> try:\n<28> push_stream_id = self.connection.send_push_promise(\n<29> stream_id=self.stream_id, headers=request_headers\n<30> )\n<31> except NoAvailablePushIDError:\n<32> return\n<33> \n<34> # fake request\n<35> self.protocol.http_event_received(\n<36> HeadersReceived(\n<37> headers=request_headers, stream_ended=True, stream_id=push_stream_id\n<38> )\n<39> )\n<40> self.transmit()\n<41> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h0.connection.H0Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_push_promise(stream_id: int, headers: Headers) -> int\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None\n \n at: aioquic.h3.events\n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n at: aioquic.h3.events.HeadersReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n push_id: Optional[int] = None\n \n at: aioquic.h3.exceptions\n NoAvailablePushIDError(*args: object)\n \n at: email.utils\n formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str\n \n at: examples.http3_server\n HttpServerProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: examples.http3_server.HttpRequestHandler.__init__\n self.authority = authority\n \n self.connection = connection\n \n self.protocol = protocol\n \n self.stream_id = stream_id\n \n self.transmit = transmit\n \n at: examples.http3_server.HttpServerProtocol\n http_event_received(event: H3Event) -> None\n \n at: time\n time() -> float\n \n \n===========unchanged ref 1===========\n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n "}}},{"rowIdx":3679,"cells":{"path":{"kind":"string","value":"examples.interop/test_http_3"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8c45dc8255673d5fa42194bb42208799d41e4e7e"},"commit_message":{"kind":"string","value":"[examples] fix typing warnings"},"ground_truth":{"kind":"string","value":"<25>: http = cast(H3Connection, protocol._http)\n<27>: http._decoder_bytes_received,\n protocol._http._decoder_bytes_received,\n<28>: http._decoder_bytes_sent,\n protocol._http._decoder_bytes_sent,\n<32>: http._encoder_bytes_received,\n protocol._http._encoder_bytes_received,\n<33>: http._encoder_bytes_sent,\n protocol._http._encoder_bytes_sent,\n<36>: http._decoder_bytes_received\n protocol._http._decoder_bytes_received\n<37>: and http._decoder_bytes_sent\n and protocol._http._decoder_bytes_sent\n<38>: and http._encoder_bytes_received\n and protocol._http._encoder_bytes_received\n<39>: and http._encoder_bytes_sent\n and protocol._http._encoder_bytes_sent\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_http_3(server: Server, configuration: QuicConfiguration):\n <0> if server.path is None:\n <1> return\n <2> \n <3> configuration.alpn_protocols = H3_ALPN\n <4> async with connect(\n <5> server.host,\n <6> server.port,\n <7> configuration=configuration,\n <8> create_protocol=HttpClient,\n <9> ) as protocol:\n<10> protocol = cast(HttpClient, protocol)\n<11> \n<12> # perform HTTP request\n<13> events = await protocol.get(\n<14> \"https://{}:{}{}\".format(server.host, server.port, server.path)\n<15> )\n<16> if events and isinstance(events[0], HeadersReceived):\n<17> server.result |= Result.D\n<18> server.result |= Result.three\n<19> \n<20> # perform another HTTP request to use QPACK dynamic tables\n<21> events = await protocol.get(\n<22> \"https://{}:{}{}\".format(server.host, server.port, server.path)\n<23> )\n<24> if events and isinstance(events[0], HeadersReceived):\n<25> protocol._quic._logger.info(\n<26> \"QPACK decoder bytes RX %d TX %d\",\n<27> protocol._http._decoder_bytes_received,\n<28> protocol._http._decoder_bytes_sent,\n<29> )\n<30> protocol._quic._logger.info(\n<31> \"QPACK encoder bytes RX %d TX %d\",\n<32> protocol._http._encoder_bytes_received,\n<33> protocol._http._encoder_bytes_sent,\n<34> )\n<35> if (\n<36> protocol._http._decoder_bytes_received\n<37> and protocol._http._decoder_bytes_sent\n<38> and protocol._http._encoder_bytes_received\n<39> and protocol._http._encoder_bytes_sent\n<40> ):\n<41> server.result |= Result.d\n<42> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._quic = quic\n \n at: aioquic.h3.connection\n H3_ALPN = [\"h3-23\", \"h3-22\"]\n \n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._decoder_bytes_received = 0\n \n self._decoder_bytes_sent = 0\n \n self._encoder_bytes_received = 0\n \n self._encoder_bytes_sent = 0\n \n at: aioquic.h3.connection.H3Connection._decode_headers\n self._decoder_bytes_sent += len(decoder)\n \n at: aioquic.h3.connection.H3Connection._encode_headers\n self._encoder_bytes_sent += len(encoder)\n \n at: aioquic.h3.connection.H3Connection._receive_stream_data_uni\n self._decoder_bytes_received += len(data)\n \n self._encoder_bytes_received += len(data)\n \n at: aioquic.h3.events\n HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None)\n \n \n===========unchanged ref 1===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n verify_mode: Optional[int] = None\n \n \n===========unchanged ref 2===========\n at: aioquic.quic.connection.QuicConnection.__init__\n self._logger = QuicConnectionAdapter(\n logger, {\"id\": dump_cid(logger_connection_id)}\n )\n \n at: examples.interop\n Result()\n \n Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str=\"/\", result: Result=field(default_factory=lambda: Result(0)), verify_mode: Optional[int]=None)\n \n at: examples.interop.Server\n name: str\n \n host: str\n \n port: int = 4433\n \n http3: bool = True\n \n retry_port: Optional[int] = 4434\n \n path: str = \"/\"\n \n result: Result = field(default_factory=lambda: Result(0))\n \n verify_mode: Optional[int] = None\n \n at: http3_client\n HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: http3_client.HttpClient\n get(url: str, headers: Dict={}) -> Deque[H3Event]\n \n at: http3_client.HttpClient.__init__\n self._http = H3Connection(self._quic)\n self._http: Optional[HttpConnection] = None\n self._http = H0Connection(self._quic)\n \n at: logging.LoggerAdapter\n logger: Logger\n \n extra: Mapping[str, Any]\n \n info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n \n===========changed ref 0===========\n # module: examples.http3_server\n class HttpRequestHandler:\n def send(self, message: Dict):\n if message[\"type\"] == \"http.response.start\":\n self.connection.send_headers(\n stream_id=self.stream_id,\n headers=[\n (b\":status\", str(message[\"status\"]).encode(\"ascii\")),\n (b\"server\", b\"aioquic\"),\n (b\"date\", formatdate(time.time(), usegmt=True).encode()),\n ]\n + [(k, v) for k, v in message[\"headers\"]],\n )\n elif message[\"type\"] == \"http.response.body\":\n self.connection.send_data(\n stream_id=self.stream_id,\n data=message.get(\"body\", b\"\"),\n end_stream=not message.get(\"more_body\", False),\n )\n elif message[\"type\"] == \"http.response.push\" and isinstance(\n self.connection, H3Connection\n ):\n request_headers = [\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", self.authority),\n (b\":path\", message[\"path\"].encode(\"utf8\")),\n ] + [(k, v) for k, v in message[\"headers\"]]\n \n # send push promise\n try:\n push_stream_id = self.connection.send_push_promise(\n stream_id=self.stream_id, headers=request_headers\n )\n except NoAvailablePushIDError:\n return\n \n # fake request\n + cast(HttpServerProtocol, self.protocol).http_event_received(\n - self.protocol.http_event_received(\n HeadersReceived(\n headers=request_headers, stream_ended=True, stream_id=push_stream_id\n )\n )\n self.transmit()\n "}}},{"rowIdx":3680,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.protocol/QuicConnectionProtocol.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <3>: self._connected = False\n self._connected_waiter: Optional[asyncio.Future[None]] = None\n self._connected_waiter = loop.create_future()\n"},"main_code":{"kind":"string","value":" # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def __init__(\n self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None\n ):\n <0> loop = asyncio.get_event_loop()\n <1> \n <2> self._closed = asyncio.Event()\n <3> self._connected_waiter = loop.create_future()\n <4> self._loop = loop\n <5> self._ping_waiter: Optional[asyncio.Future[None]] = None\n <6> self._quic = quic\n <7> self._stream_readers: Dict[int, asyncio.StreamReader] = {}\n <8> self._timer: Optional[asyncio.TimerHandle] = None\n <9> self._timer_at: Optional[float] = None\n<10> self._transmit_task: Optional[asyncio.Handle] = None\n<11> self._transport: Optional[asyncio.DatagramTransport] = None\n<12> \n<13> # callbacks\n<14> self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n<15> self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n<16> self._connection_terminated_handler: Callable[[], None] = lambda: None\n<17> if stream_handler is not None:\n<18> self._stream_handler = stream_handler\n<19> else:\n<20> self._stream_handler = lambda r, w: None\n<21> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: _asyncio\n get_event_loop()\n \n at: aioquic.asyncio.protocol\n QuicConnectionIdHandler = Callable[[bytes], None]\n \n QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer\n self._timer = None\n \n self._timer_at = None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol._process_events\n self._connected_waiter = None\n \n self._connected = True\n \n self._ping_waiter = None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol._transmit_soon\n self._transmit_task = self._loop.call_soon(self.transmit)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.ping\n self._ping_waiter = self._loop.create_future()\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.transmit\n self._transmit_task = None\n \n self._timer = self._loop.call_at(timer_at, self._handle_timer)\n self._timer = None\n \n self._timer_at = timer_at\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.wait_connected\n self._connected_waiter = self._loop.create_future()\n \n at: aioquic.quic.connection\n QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: asyncio.events\n Handle(callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...)\n \n \n===========unchanged ref 1===========\n TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...)\n \n get_event_loop() -> AbstractEventLoop\n \n at: asyncio.futures\n Future(*, loop: Optional[AbstractEventLoop]=...)\n Future = _CFuture = _asyncio.Future\n \n at: asyncio.locks\n Event(*, loop: Optional[AbstractEventLoop]=...)\n \n at: asyncio.streams\n StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...)\n \n at: asyncio.transports\n DatagramTransport(extra: Optional[Mapping[Any, Any]]=...)\n \n at: typing\n Callable = _CallableType(collections.abc.Callable, 2)\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":3681,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.protocol/QuicConnectionProtocol.ping"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <3>: assert self._ping_waiter is None, \"already awaiting ping\"\n assert self._ping_waiter is None, \"already await a ping\"\n"},"main_code":{"kind":"string","value":" # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n <0> \"\"\"\n <1> Ping the peer and wait for the response.\n <2> \"\"\"\n <3> assert self._ping_waiter is None, \"already await a ping\"\n <4> self._ping_waiter = self._loop.create_future()\n <5> self._quic.send_ping(id(self._ping_waiter))\n <6> self.transmit()\n <7> await asyncio.shield(self._ping_waiter)\n <8> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n transmit() -> None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._loop = loop\n \n self._ping_waiter: Optional[asyncio.Future[None]] = None\n \n self._quic = quic\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol._process_events\n self._ping_waiter = None\n \n at: aioquic.quic.connection.QuicConnection\n send_ping(uid: int) -> None\n \n at: asyncio.events.AbstractEventLoop\n create_future() -> Future[Any]\n \n \n===========changed ref 0===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def __init__(\n self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None\n ):\n loop = asyncio.get_event_loop()\n \n self._closed = asyncio.Event()\n + self._connected = False\n + self._connected_waiter: Optional[asyncio.Future[None]] = None\n - self._connected_waiter = loop.create_future()\n self._loop = loop\n self._ping_waiter: Optional[asyncio.Future[None]] = None\n self._quic = quic\n self._stream_readers: Dict[int, asyncio.StreamReader] = {}\n self._timer: Optional[asyncio.TimerHandle] = None\n self._timer_at: Optional[float] = None\n self._transmit_task: Optional[asyncio.Handle] = None\n self._transport: Optional[asyncio.DatagramTransport] = None\n \n # callbacks\n self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_terminated_handler: Callable[[], None] = lambda: None\n if stream_handler is not None:\n self._stream_handler = stream_handler\n else:\n self._stream_handler = lambda r, w: None\n "}}},{"rowIdx":3682,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.protocol/QuicConnectionProtocol.wait_connected"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <3>: assert self._connected_waiter is None, \"already awaiting connected\"\n if not self._connected:\n self._connected_waiter = self._loop.create_future()\n await asyncio.shield(self._connected_waiter)\n await asyncio.shield(self._connected_waiter)\n"},"main_code":{"kind":"string","value":" # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def wait_connected(self) -> None:\n <0> \"\"\"\n <1> Wait for the TLS handshake to complete.\n <2> \"\"\"\n <3> await asyncio.shield(self._connected_waiter)\n <4> \n "},"context":{"kind":"string","value":"===========changed ref 0===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n \n===========changed ref 1===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def __init__(\n self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None\n ):\n loop = asyncio.get_event_loop()\n \n self._closed = asyncio.Event()\n + self._connected = False\n + self._connected_waiter: Optional[asyncio.Future[None]] = None\n - self._connected_waiter = loop.create_future()\n self._loop = loop\n self._ping_waiter: Optional[asyncio.Future[None]] = None\n self._quic = quic\n self._stream_readers: Dict[int, asyncio.StreamReader] = {}\n self._timer: Optional[asyncio.TimerHandle] = None\n self._timer_at: Optional[float] = None\n self._transmit_task: Optional[asyncio.Handle] = None\n self._transport: Optional[asyncio.DatagramTransport] = None\n \n # callbacks\n self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_terminated_handler: Callable[[], None] = lambda: None\n if stream_handler is not None:\n self._stream_handler = stream_handler\n else:\n self._stream_handler = lambda r, w: None\n "}}},{"rowIdx":3683,"cells":{"path":{"kind":"string","value":"aioquic.asyncio.protocol/QuicConnectionProtocol._process_events"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <8>: if self._connected_waiter is not None:\n waiter = self._connected_waiter\n self._connected_waiter = None\n if not self._connected_waiter.done():\n <9>: waiter.set_exception(ConnectionError)\n self._connected_waiter.set_exception(ConnectionError)\n<12>: if self._connected_waiter is not None:\n waiter = self._connected_waiter\n self._connected = True\n self._connected_waiter = None\n self._connected_waiter.set_result(None)\n<13>: waiter.set_result(None)\n"},"main_code":{"kind":"string","value":" # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def _process_events(self) -> None:\n <0> event = self._quic.next_event()\n <1> while event is not None:\n <2> if isinstance(event, events.ConnectionIdIssued):\n <3> self._connection_id_issued_handler(event.connection_id)\n <4> elif isinstance(event, events.ConnectionIdRetired):\n <5> self._connection_id_retired_handler(event.connection_id)\n <6> elif isinstance(event, events.ConnectionTerminated):\n <7> self._connection_terminated_handler()\n <8> if not self._connected_waiter.done():\n <9> self._connected_waiter.set_exception(ConnectionError)\n<10> self._closed.set()\n<11> elif isinstance(event, events.HandshakeCompleted):\n<12> self._connected_waiter.set_result(None)\n<13> elif isinstance(event, events.PingAcknowledged):\n<14> waiter = self._ping_waiter\n<15> self._ping_waiter = None\n<16> waiter.set_result(None)\n<17> self.quic_event_received(event)\n<18> event = self._quic.next_event()\n<19> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: _asyncio.Future\n set_exception(exception, /)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n transmit() -> None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._closed = asyncio.Event()\n \n self._connected_waiter: Optional[asyncio.Future[None]] = None\n \n self._quic = quic\n \n self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n \n self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n \n self._connection_terminated_handler: Callable[[], None] = lambda: None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer\n now = max(self._timer_at, self._loop.time())\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.wait_connected\n self._connected_waiter = self._loop.create_future()\n \n at: aioquic.quic.connection.QuicConnection\n handle_timer(now: float) -> None\n \n next_event() -> Optional[events.QuicEvent]\n \n at: aioquic.quic.events\n ConnectionIdIssued(connection_id: bytes)\n \n ConnectionIdRetired(connection_id: bytes)\n \n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: asyncio.futures.Future\n _state = _PENDING\n \n _result = None\n \n _exception = None\n \n _loop = None\n \n _source_traceback = None\n \n _cancel_message = None\n \n _cancelled_exc = None\n \n _asyncio_future_blocking = False\n \n __log_traceback = False\n \n __class_getitem__ = classmethod(GenericAlias)\n \n set_exception(exception: Union[type, BaseException], /) -> None\n \n \n===========unchanged ref 1===========\n __iter__ = __await__ # make compatible with 'yield from'.\n \n at: asyncio.locks.Event\n set() -> None\n \n \n===========changed ref 0===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def wait_connected(self) -> None:\n \"\"\"\n Wait for the TLS handshake to complete.\n \"\"\"\n + assert self._connected_waiter is None, \"already awaiting connected\"\n + if not self._connected:\n + self._connected_waiter = self._loop.create_future()\n + await asyncio.shield(self._connected_waiter)\n - await asyncio.shield(self._connected_waiter)\n \n===========changed ref 1===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n \n===========changed ref 2===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def __init__(\n self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None\n ):\n loop = asyncio.get_event_loop()\n \n self._closed = asyncio.Event()\n + self._connected = False\n + self._connected_waiter: Optional[asyncio.Future[None]] = None\n - self._connected_waiter = loop.create_future()\n self._loop = loop\n self._ping_waiter: Optional[asyncio.Future[None]] = None\n self._quic = quic\n self._stream_readers: Dict[int, asyncio.StreamReader] = {}\n self._timer: Optional[asyncio.TimerHandle] = None\n self._timer_at: Optional[float] = None\n self._transmit_task: Optional[asyncio.Handle] = None\n self._transport: Optional[asyncio.DatagramTransport] = None\n \n # callbacks\n self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_terminated_handler: Callable[[], None] = lambda: None\n if stream_handler is not None:\n self._stream_handler = stream_handler\n else:\n self._stream_handler = lambda r, w: None\n "}}},{"rowIdx":3684,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <0>: server, response = run(\n asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n <1>: )\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n <0> server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n <1> self.assertEqual(response, b\"gnip\")\n <2> server.close()\n <3> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: tests.test_asyncio\n handle_stream(reader, writer)\n \n at: tests.test_asyncio.HighLevelTest.run_server\n configuration = QuicConfiguration(is_client=False)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 2===========\n # module: tests.test_asyncio\n - def run_client(\n - host,\n - port=4433,\n - cadata=None,\n - cafile=SERVER_CACERTFILE,\n - configuration=None,\n - request=b\"ping\",\n - **kwargs\n - ):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=True)\n - configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n - async with connect(host, port, configuration=configuration, **kwargs) as client:\n - reader, writer = await client.create_stream()\n - assert writer.can_write_eof() is True\n - assert writer.get_extra_info(\"stream_id\") == 0\n - \n - writer.write(request)\n - writer.write_eof()\n - \n - return await reader.read()\n - \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 4===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def wait_connected(self) -> None:\n \"\"\"\n Wait for the TLS handshake to complete.\n \"\"\"\n + assert self._connected_waiter is None, \"already awaiting connected\"\n + if not self._connected:\n + self._connected_waiter = self._loop.create_future()\n + await asyncio.shield(self._connected_waiter)\n - await asyncio.shield(self._connected_waiter)\n \n===========changed ref 5===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n \n===========changed ref 6===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def __init__(\n self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None\n ):\n loop = asyncio.get_event_loop()\n \n self._closed = asyncio.Event()\n + self._connected = False\n + self._connected_waiter: Optional[asyncio.Future[None]] = None\n - self._connected_waiter = loop.create_future()\n self._loop = loop\n self._ping_waiter: Optional[asyncio.Future[None]] = None\n self._quic = quic\n self._stream_readers: Dict[int, asyncio.StreamReader] = {}\n self._timer: Optional[asyncio.TimerHandle] = None\n self._timer_at: Optional[float] = None\n self._transmit_task: Optional[asyncio.Handle] = None\n self._transport: Optional[asyncio.DatagramTransport] = None\n \n # callbacks\n self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None\n self._connection_terminated_handler: Callable[[], None] = lambda: None\n if stream_handler is not None:\n self._stream_handler = stream_handler\n else:\n self._stream_handler = lambda r, w: None\n \n===========changed ref 7===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def _process_events(self) -> None:\n event = self._quic.next_event()\n while event is not None:\n if isinstance(event, events.ConnectionIdIssued):\n self._connection_id_issued_handler(event.connection_id)\n elif isinstance(event, events.ConnectionIdRetired):\n self._connection_id_retired_handler(event.connection_id)\n elif isinstance(event, events.ConnectionTerminated):\n self._connection_terminated_handler()\n + if self._connected_waiter is not None:\n + waiter = self._connected_waiter\n + self._connected_waiter = None\n - if not self._connected_waiter.done():\n + waiter.set_exception(ConnectionError)\n - self._connected_waiter.set_exception(ConnectionError)\n self._closed.set()\n elif isinstance(event, events.HandshakeCompleted):\n + if self._connected_waiter is not None:\n + waiter = self._connected_waiter\n + self._connected = True\n + self._connected_waiter = None\n - self._connected_waiter.set_result(None)\n + waiter.set_result(None)\n elif isinstance(event, events.PingAcknowledged):\n waiter = self._ping_waiter\n self._ping_waiter = None\n waiter.set_result(None)\n self.quic_event_received(event)\n event = self._quic.next_event()\n "}}},{"rowIdx":3685,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_ec_certificate"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <4>: self.run_server(\n run_server(\n<11>: self.run_client(\n run_client(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n <0> certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n <1> \n <2> server, response = run(\n <3> asyncio.gather(\n <4> run_server(\n <5> configuration=QuicConfiguration(\n <6> certificate=certificate,\n <7> private_key=private_key,\n <8> is_client=False,\n <9> )\n<10> ),\n<11> run_client(\n<12> \"127.0.0.1\",\n<13> cadata=certificate.public_bytes(serialization.Encoding.PEM),\n<14> cafile=None,\n<15> ),\n<16> )\n<17> )\n<18> \n<19> self.assertEqual(response, b\"gnip\")\n<20> server.close()\n<21> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n connection_id_length: int = 8\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n quic_logger: Optional[QuicLogger] = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n cadata: Optional[bytes] = None\n \n cafile: Optional[str] = None\n \n capath: Optional[str] = None\n \n certificate: Any = None\n \n certificate_chain: List[Any] = field(default_factory=list)\n \n private_key: Any = None\n \n supported_versions: List[int] = field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n )\n \n verify_mode: Optional[int] = None\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.utils\n generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[])\n \n run(coro)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - "}}},{"rowIdx":3686,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_large"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <5>: asyncio.gather(\n self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n <6>: )\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n <0> \"\"\"\n <1> Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n <2> \"\"\"\n <3> data = b\"Z\" * 2097152\n <4> server, response = run(\n <5> asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n <6> )\n <7> self.assertEqual(response, data)\n <8> server.close()\n <9> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_ec_certificate\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n self.run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n self.run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n server, response = run(\n asyncio.gather(\n self.run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n self.run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n - run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n - def run_client(\n - host,\n - port=4433,\n - cadata=None,\n - cafile=SERVER_CACERTFILE,\n - configuration=None,\n - request=b\"ping\",\n - **kwargs\n - ):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=True)\n - configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n - async with connect(host, port, configuration=configuration, **kwargs) as client:\n - reader, writer = await client.create_stream()\n - assert writer.can_write_eof() is True\n - assert writer.get_extra_info(\"stream_id\") == 0\n - \n - writer.write(request)\n - writer.write_eof()\n - \n - return await reader.read()\n - \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 6===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def wait_connected(self) -> None:\n \"\"\"\n Wait for the TLS handshake to complete.\n \"\"\"\n + assert self._connected_waiter is None, \"already awaiting connected\"\n + if not self._connected:\n + self._connected_waiter = self._loop.create_future()\n + await asyncio.shield(self._connected_waiter)\n - await asyncio.shield(self._connected_waiter)\n \n===========changed ref 7===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n "}}},{"rowIdx":3687,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_without_client_configuration"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <4>: server = run(self.run_server())\n server = run(run_server())\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n <0> async def run_client_without_config(host, port=4433):\n <1> async with connect(host, port) as client:\n <2> await client.ping()\n <3> \n <4> server = run(run_server())\n <5> with self.assertRaises(ConnectionError):\n <6> run(run_client_without_config(\"127.0.0.1\"))\n <7> server.close()\n <8> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n - run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n - def run_client(\n - host,\n - port=4433,\n - cadata=None,\n - cafile=SERVER_CACERTFILE,\n - configuration=None,\n - request=b\"ping\",\n - **kwargs\n - ):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=True)\n - configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n - async with connect(host, port, configuration=configuration, **kwargs) as client:\n - reader, writer = await client.create_stream()\n - assert writer.can_write_eof() is True\n - assert writer.get_extra_info(\"stream_id\") == 0\n - \n - writer.write(request)\n - writer.write_eof()\n - \n - return await reader.read()\n - "}}},{"rowIdx":3688,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_writelines"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":"<13>: asyncio.gather(self.run_server(), run_client_writelines(\"127.0.0.1\"))\n asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n <0> async def run_client_writelines(host, port=4433):\n <1> configuration = QuicConfiguration(is_client=True)\n <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n <3> async with connect(host, port, configuration=configuration) as client:\n <4> reader, writer = await client.create_stream()\n <5> assert writer.can_write_eof() is True\n <6> \n <7> writer.writelines([b\"01234567\", b\"89012345\"])\n <8> writer.write_eof()\n <9> \n<10> return await reader.read()\n<11> \n<12> server, response = run(\n<13> asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n<14> )\n<15> self.assertEqual(response, b\"5432109876543210\")\n<16> server.close()\n<17> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]\n \n ping() -> None\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None\n \n at: asyncio.streams.StreamWriter\n can_write_eof() -> bool\n \n at: tests.test_asyncio.HighLevelTest\n run_server(configuration=None)\n \n at: tests.utils\n run(coro)\n \n \n===========unchanged ref 1===========\n SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), \"pycacert.pem\")\n \n at: unittest.case.TestCase\n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n - run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n - def run_client(\n - host,\n - port=4433,\n - cadata=None,\n - cafile=SERVER_CACERTFILE,\n - configuration=None,\n - request=b\"ping\",\n - **kwargs\n - ):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=True)\n - configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n - async with connect(host, port, configuration=configuration, **kwargs) as client:\n - reader, writer = await client.create_stream()\n - assert writer.can_write_eof() is True\n - assert writer.get_extra_info(\"stream_id\") == 0\n - \n - writer.write(request)\n - writer.write_eof()\n - \n - return await reader.read()\n - "}}},{"rowIdx":3689,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":"<13>: self.run_server(\n configuration=server_configuration, stateless_retry=True\n run_server(configuration=server_configuration, stateless_retry=True),\n<14>: ),\n self.run_client(\n run_client(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n <0> \"\"\"\n <1> This test ensures handshake success and stream data is successfully sent\n <2> and received in the presence of packet loss (randomized 25% in each direction).\n <3> \"\"\"\n <4> data = b\"Z\" * 65536\n <5> \n <6> server_configuration = QuicConfiguration(\n <7> idle_timeout=300.0, is_client=False, quic_logger=QuicLogger()\n <8> )\n <9> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n<10> \n<11> server, response = run(\n<12> asyncio.gather(\n<13> run_server(configuration=server_configuration, stateless_retry=True),\n<14> run_client(\n<15> \"127.0.0.1\",\n<16> configuration=QuicConfiguration(\n<17> is_client=True, idle_timeout=300.0, quic_logger=QuicLogger()\n<18> ),\n<19> request=data,\n<20> ),\n<21> )\n<22> )\n<23> self.assertEqual(response, data)\n<24> server.close()\n<25> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None\n \n at: aioquic.quic.logger\n QuicLogger()\n \n at: asyncio.streams.StreamWriter\n writelines(data: Iterable[bytes]) -> None\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio\n sendto_with_loss(self, data, addr=None)\n \n at: tests.test_asyncio.HighLevelTest\n run_server(configuration=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_writelines\n run_client_writelines(host, port=4433)\n \n at: tests.utils\n run(coro)\n \n SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), \"ssl_cert.pem\")\n \n SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), \"ssl_key.pem\")\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n at: unittest.mock\n _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T]\n _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]]\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - "}}},{"rowIdx":3690,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_session_ticket"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":"<10>: self.run_server(session_ticket_handler=store.add),\n run_server(session_ticket_handler=store.add),\n<11>: self.run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n<22>: self.run_server(session_ticket_fetcher=store.pop),\n run_server(session_ticket_fetcher=store.pop),\n<23>: self.run_client(\n run_client(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_session_ticket(self):\n <0> client_ticket = None\n <1> store = SessionTicketStore()\n <2> \n <3> def save_ticket(t):\n <4> nonlocal client_ticket\n <5> client_ticket = t\n <6> \n <7> # first request\n <8> server, response = run(\n <9> asyncio.gather(\n<10> run_server(session_ticket_handler=store.add),\n<11> run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n<12> )\n<13> )\n<14> self.assertEqual(response, b\"gnip\")\n<15> server.close()\n<16> \n<17> self.assertIsNotNone(client_ticket)\n<18> \n<19> # second request\n<20> server, response = run(\n<21> asyncio.gather(\n<22> run_server(session_ticket_fetcher=store.pop),\n<23> run_client(\n<24> \"127.0.0.1\",\n<25> configuration=QuicConfiguration(\n<26> is_client=True, session_ticket=client_ticket\n<27> ),\n<28> ),\n<29> )\n<30> )\n<31> self.assertEqual(response, b\"gnip\")\n<32> server.close()\n<33> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.logger\n QuicLogger()\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio\n SessionTicketStore()\n \n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_packet_loss\n data = b\"Z\" * 65536\n \n server, response = run(\n asyncio.gather(\n self.run_server(\n configuration=server_configuration, stateless_retry=True\n ),\n self.run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True, idle_timeout=300.0, quic_logger=QuicLogger()\n ),\n request=data,\n ),\n )\n )\n \n server, response = run(\n asyncio.gather(\n self.run_server(\n configuration=server_configuration, stateless_retry=True\n ),\n self.run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True, idle_timeout=300.0, quic_logger=QuicLogger()\n ),\n request=data,\n ),\n )\n )\n \n at: tests.test_asyncio.SessionTicketStore\n add(ticket)\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertIsNotNone(obj: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n "}}},{"rowIdx":3691,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_sni"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <0>: server, response = run(\n asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n <1>: )\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n <0> server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n <1> self.assertEqual(response, b\"gnip\")\n <2> server.close()\n <3> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket\n store = SessionTicketStore()\n \n at: tests.test_asyncio.SessionTicketStore\n pop(label)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n - run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n self.assertEqual(response, b\"gnip\")\n server.close()\n "}}},{"rowIdx":3692,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <1>: asyncio.gather(\n self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n <2>: )\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n <0> server, response = run(\n <1> asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n <2> )\n <3> self.assertEqual(response, b\"gnip\")\n <4> server.close()\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket\n client_ticket = None\n \n server, response = run(\n asyncio.gather(\n self.run_server(session_ticket_handler=store.add),\n self.run_client(\"127.0.0.1\", session_ticket_handler=save_ticket),\n )\n )\n server, response = run(\n asyncio.gather(\n self.run_server(session_ticket_fetcher=store.pop),\n self.run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True, session_ticket=client_ticket\n ),\n ),\n )\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n - run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433):\n configuration = QuicConfiguration(is_client=True)\n configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n async with connect(host, port, configuration=configuration) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n server, response = run(\n + asyncio.gather(self.run_server(), run_client_writelines(\"127.0.0.1\"))\n - asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n server.close()\n \n===========changed ref 8===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"socket.socket.sendto\", new_callable=lambda: sendto_with_loss)\n def test_connect_and_serve_with_packet_loss(self, mock_sendto):\n \"\"\"\n This test ensures handshake success and stream data is successfully sent\n and received in the presence of packet loss (randomized 25% in each direction).\n \"\"\"\n data = b\"Z\" * 65536\n \n server_configuration = QuicConfiguration(\n idle_timeout=300.0, is_client=False, quic_logger=QuicLogger()\n )\n server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n + configuration=server_configuration, stateless_retry=True\n - run_server(configuration=server_configuration, stateless_retry=True),\n + ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True, idle_timeout=300.0, quic_logger=QuicLogger()\n ),\n request=data,\n ),\n )\n )\n self.assertEqual(response, data)\n server.close()\n "}}},{"rowIdx":3693,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad_original_connection_id"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":"<10>: server = run(\n self.run_server(create_protocol=create_protocol, stateless_retry=True)\n server = run(run_server(create_protocol=create_protocol, stateless_retry=True))\n<11>: )\n<12>: run(self.run_client(\"127.0.0.1\"))\n run(run_client(\"127.0.0.1\"))\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self):\n <0> \"\"\"\n <1> If the server's transport parameters do not have the correct\n <2> original_connection_id the connection fail.\n <3> \"\"\"\n <4> \n <5> def create_protocol(*args, **kwargs):\n <6> protocol = QuicConnectionProtocol(*args, **kwargs)\n <7> protocol._quic._original_connection_id = None\n <8> return protocol\n <9> \n<10> server = run(run_server(create_protocol=create_protocol, stateless_retry=True))\n<11> with self.assertRaises(ConnectionError):\n<12> run(run_client(\"127.0.0.1\"))\n<13> server.close()\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 1===========\n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n server, response = run(\n + asyncio.gather(\n + self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n - asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n + )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - "}}},{"rowIdx":3694,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <2>: server = run(self.run_server(stateless_retry=True))\n server = run(run_server(stateless_retry=True))\n <5>: self.run_client(\n run_client(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.quic.retry.QuicRetryTokenHandler.validate_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n <0> mock_validate.side_effect = ValueError(\"Decryption failed.\")\n <1> \n <2> server = run(run_server(stateless_retry=True))\n <3> with self.assertRaises(ConnectionError):\n <4> run(\n <5> run_client(\n <6> \"127.0.0.1\",\n <7> configuration=QuicConfiguration(is_client=True, idle_timeout=4.0),\n <8> )\n <9> )\n<10> server.close()\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.protocol\n QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._quic = quic\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._original_connection_id = original_connection_id\n \n at: aioquic.quic.connection.QuicConnection.receive_datagram\n self._original_connection_id = self._peer_cid\n \n at: tests.utils\n run(coro)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n server, response = run(\n + asyncio.gather(\n + self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n - asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n + )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self):\n \"\"\"\n If the server's transport parameters do not have the correct\n original_connection_id the connection fail.\n \"\"\"\n \n def create_protocol(*args, **kwargs):\n protocol = QuicConnectionProtocol(*args, **kwargs)\n protocol._quic._original_connection_id = None\n return protocol\n \n + server = run(\n + self.run_server(create_protocol=create_protocol, stateless_retry=True)\n - server = run(run_server(create_protocol=create_protocol, stateless_retry=True))\n + )\n with self.assertRaises(ConnectionError):\n + run(self.run_client(\"127.0.0.1\"))\n - run(run_client(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"127.0.0.1\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"127.0.0.1\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_large(self):\n \"\"\"\n Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA.\n \"\"\"\n data = b\"Z\" * 2097152\n server, response = run(\n + asyncio.gather(\n + self.run_server(), self.run_client(\"127.0.0.1\", request=data)\n - asyncio.gather(run_server(), run_client(\"127.0.0.1\", request=data))\n + )\n )\n self.assertEqual(response, data)\n server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n - def run_server(configuration=None, **kwargs):\n - if configuration is None:\n - configuration = QuicConfiguration(is_client=False)\n - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n - return await serve(\n - host=\"::\",\n - port=\"4433\",\n - configuration=configuration,\n - stream_handler=handle_stream,\n - **kwargs\n - )\n - \n===========changed ref 8===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_ec_certificate(self):\n certificate, private_key = generate_ec_certificate(common_name=\"localhost\")\n \n server, response = run(\n asyncio.gather(\n + self.run_server(\n - run_server(\n configuration=QuicConfiguration(\n certificate=certificate,\n private_key=private_key,\n is_client=False,\n )\n ),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n cadata=certificate.public_bytes(serialization.Encoding.PEM),\n cafile=None,\n ),\n )\n )\n \n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 9===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_writelines(self):\n async def run_client_writelines(host, port=4433):\n configuration = QuicConfiguration(is_client=True)\n configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n async with connect(host, port, configuration=configuration) as client:\n reader, writer = await client.create_stream()\n assert writer.can_write_eof() is True\n \n writer.writelines([b\"01234567\", b\"89012345\"])\n writer.write_eof()\n \n return await reader.read()\n \n server, response = run(\n + asyncio.gather(self.run_server(), run_client_writelines(\"127.0.0.1\"))\n - asyncio.gather(run_server(), run_client_writelines(\"127.0.0.1\"))\n )\n self.assertEqual(response, b\"5432109876543210\")\n server.close()\n "}}},{"rowIdx":3695,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <2>: self.run_server(),\n run_server(),\n <3>: self.run_client(\n run_client(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n <0> server, response = run(\n <1> asyncio.gather(\n <2> run_server(),\n <3> run_client(\n <4> \"127.0.0.1\",\n <5> configuration=QuicConfiguration(\n <6> is_client=True,\n <7> quic_logger=QuicLogger(),\n <8> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n <9> ),\n<10> ),\n<11> )\n<12> )\n<13> self.assertEqual(response, b\"gnip\")\n<14> server.close()\n<15> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_stateless_retry_bad_original_connection_id\n server = run(\n self.run_server(create_protocol=create_protocol, stateless_retry=True)\n )\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========unchanged ref 1===========\n at: unittest.mock\n _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T]\n _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]]\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.quic.retry.QuicRetryTokenHandler.validate_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(self.run_server(stateless_retry=True))\n - server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(is_client=True, idle_timeout=4.0),\n )\n )\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n server, response = run(\n + asyncio.gather(\n + self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n - asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n + )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self):\n \"\"\"\n If the server's transport parameters do not have the correct\n original_connection_id the connection fail.\n \"\"\"\n \n def create_protocol(*args, **kwargs):\n protocol = QuicConnectionProtocol(*args, **kwargs)\n protocol._quic._original_connection_id = None\n return protocol\n \n + server = run(\n + self.run_server(create_protocol=create_protocol, stateless_retry=True)\n - server = run(run_server(create_protocol=create_protocol, stateless_retry=True))\n + )\n with self.assertRaises(ConnectionError):\n + run(self.run_client(\"127.0.0.1\"))\n - run(run_client(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n "}}},{"rowIdx":3696,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_connect_timeout"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <2>: self.run_client(\n run_client(\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_timeout(self):\n <0> with self.assertRaises(ConnectionError):\n <1> run(\n <2> run_client(\n <3> \"127.0.0.1\",\n <4> port=4400,\n <5> configuration=QuicConfiguration(is_client=True, idle_timeout=5),\n <6> )\n <7> )\n <8> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n run_server(configuration=None)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_stateless_retry_bad\n server = run(self.run_server(stateless_retry=True))\n \n at: tests.utils\n run(coro)\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n server, response = run(\n asyncio.gather(\n + self.run_server(),\n - run_server(),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True,\n quic_logger=QuicLogger(),\n supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n ),\n ),\n )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.quic.retry.QuicRetryTokenHandler.validate_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(self.run_server(stateless_retry=True))\n - server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(is_client=True, idle_timeout=4.0),\n )\n )\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n server, response = run(\n + asyncio.gather(\n + self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n - asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n + )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n "}}},{"rowIdx":3697,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_change_connection_id"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":"<10>: self.run_server(stateless_retry=False),\n run_client_key_update(\"127.0.0.1\"),\n run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_change_connection_id(self):\n <0> async def run_client_key_update(host, port=4433):\n <1> configuration = QuicConfiguration(is_client=True)\n <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n <3> async with connect(host, port, configuration=configuration) as client:\n <4> await client.ping()\n <5> client.change_connection_id()\n <6> await client.ping()\n <7> \n <8> server, _ = run(\n <9> asyncio.gather(\n<10> run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n<11> )\n<12> )\n<13> server.close()\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.logger\n QuicLogger()\n \n at: aioquic.quic.packet\n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: tests.test_asyncio.HighLevelTest\n run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b\"ping\", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds)\n \n at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_version_negotiation\n server, response = run(\n asyncio.gather(\n self.run_server(),\n self.run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True,\n quic_logger=QuicLogger(),\n supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n ),\n ),\n )\n )\n \n server, response = run(\n asyncio.gather(\n self.run_server(),\n self.run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True,\n quic_logger=QuicLogger(),\n supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n ),\n ),\n )\n )\n \n at: tests.utils\n run(coro)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========unchanged ref 1===========\n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_client(\n + self,\n + host,\n + port=4433,\n + cadata=None,\n + cafile=SERVER_CACERTFILE,\n + configuration=None,\n + request=b\"ping\",\n + **kwargs\n + ):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=True)\n + configuration.load_verify_locations(cadata=cadata, cafile=cafile)\n + async with connect(host, port, configuration=configuration, **kwargs) as client:\n + # waiting for connected when connected returns immediately\n + await client.wait_connected()\n + \n + reader, writer = await client.create_stream()\n + self.assertEqual(writer.can_write_eof(), True)\n + self.assertEqual(writer.get_extra_info(\"stream_id\"), 0)\n + \n + writer.write(request)\n + writer.write_eof()\n + \n + response = await reader.read()\n + \n + # waiting for closed when closed returns immediately\n + await client.wait_closed()\n + \n + return response\n + \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_timeout(self):\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n port=4400,\n configuration=QuicConfiguration(is_client=True, idle_timeout=5),\n )\n )\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n server, response = run(\n asyncio.gather(\n + self.run_server(),\n - run_server(),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True,\n quic_logger=QuicLogger(),\n supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n ),\n ),\n )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.quic.retry.QuicRetryTokenHandler.validate_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(self.run_server(stateless_retry=True))\n - server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(is_client=True, idle_timeout=4.0),\n )\n )\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n server, response = run(\n + asyncio.gather(\n + self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n - asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n + )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self):\n \"\"\"\n If the server's transport parameters do not have the correct\n original_connection_id the connection fail.\n \"\"\"\n \n def create_protocol(*args, **kwargs):\n protocol = QuicConnectionProtocol(*args, **kwargs)\n protocol._quic._original_connection_id = None\n return protocol\n \n + server = run(\n + self.run_server(create_protocol=create_protocol, stateless_retry=True)\n - server = run(run_server(create_protocol=create_protocol, stateless_retry=True))\n + )\n with self.assertRaises(ConnectionError):\n + run(self.run_client(\"127.0.0.1\"))\n - run(run_client(\"127.0.0.1\"))\n server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_without_client_configuration(self):\n async def run_client_without_config(host, port=4433):\n async with connect(host, port) as client:\n await client.ping()\n \n + server = run(self.run_server())\n - server = run(run_server())\n with self.assertRaises(ConnectionError):\n run(run_client_without_config(\"127.0.0.1\"))\n server.close()\n "}}},{"rowIdx":3698,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_key_update"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":"<10>: self.run_server(stateless_retry=False),\n run_client_key_update(\"127.0.0.1\"),\n run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_key_update(self):\n <0> async def run_client_key_update(host, port=4433):\n <1> configuration = QuicConfiguration(is_client=True)\n <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n <3> async with connect(host, port, configuration=configuration) as client:\n <4> await client.ping()\n <5> client.request_key_update()\n <6> await client.ping()\n <7> \n <8> server, _ = run(\n <9> asyncio.gather(\n<10> run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n<11> )\n<12> )\n<13> server.close()\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n change_connection_id() -> None\n \n ping() -> None\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None\n \n \n===========unchanged ref 1===========\n at: asyncio.tasks\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[\n Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]]\n ]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]]\n gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]]\n gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[\n===========unchanged ref 2===========\n at: tests.test_asyncio.HighLevelTest\n run_server(configuration=None)\n \n at: tests.utils\n run(coro)\n \n SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), \"pycacert.pem\")\n \n \n===========changed ref 0===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n + def run_server(self, configuration=None, **kwargs):\n + if configuration is None:\n + configuration = QuicConfiguration(is_client=False)\n + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)\n + return await serve(\n + host=\"::\",\n + port=\"4433\",\n + configuration=configuration,\n + stream_handler=handle_stream,\n + **kwargs\n + )\n + \n===========changed ref 1===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_timeout(self):\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n port=4400,\n configuration=QuicConfiguration(is_client=True, idle_timeout=5),\n )\n )\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n server, response = run(\n asyncio.gather(\n + self.run_server(),\n - run_server(),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True,\n quic_logger=QuicLogger(),\n supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n ),\n ),\n )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.quic.retry.QuicRetryTokenHandler.validate_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(self.run_server(stateless_retry=True))\n - server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(is_client=True, idle_timeout=4.0),\n )\n )\n server.close()\n "}}},{"rowIdx":3699,"cells":{"path":{"kind":"string","value":"tests.test_asyncio/HighLevelTest.test_ping"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1c16a37df2078c8b819b3361da4317fb848d4cfe"},"commit_message":{"kind":"string","value":"[asyncio] create future for wait_connected on demand"},"ground_truth":{"kind":"string","value":" <9>: self.run_server(stateless_retry=False), run_client_ping(\"127.0.0.1\")\n run_server(stateless_retry=False), run_client_ping(\"127.0.0.1\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_ping(self):\n <0> async def run_client_ping(host, port=4433):\n <1> configuration = QuicConfiguration(is_client=True)\n <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n <3> async with connect(host, port, configuration=configuration) as client:\n <4> await client.ping()\n <5> await client.ping()\n <6> \n <7> server, _ = run(\n <8> asyncio.gather(\n <9> run_server(stateless_retry=False), run_client_ping(\"127.0.0.1\")\n<10> )\n<11> )\n<12> server.close()\n<13> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n connect(*args, **kwds)\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n request_key_update() -> None\n \n ping() -> None\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field(\n default_factory=lambda: [\n QuicProtocolVersion.DRAFT_23,\n QuicProtocolVersion.DRAFT_22,\n ]\n ), verify_mode: Optional[int]=None)\n \n at: aioquic.quic.configuration.QuicConfiguration\n load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None\n \n at: tests.test_asyncio.HighLevelTest.test_change_connection_id\n server, _ = run(\n asyncio.gather(\n self.run_server(stateless_retry=False),\n run_client_key_update(\"127.0.0.1\"),\n )\n )\n \n at: tests.utils\n run(coro)\n \n \n===========unchanged ref 1===========\n SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), \"pycacert.pem\")\n \n \n===========changed ref 0===========\n # module: aioquic.asyncio.protocol\n class QuicConnectionProtocol(asyncio.DatagramProtocol):\n def ping(self) -> None:\n \"\"\"\n Ping the peer and wait for the response.\n \"\"\"\n + assert self._ping_waiter is None, \"already awaiting ping\"\n - assert self._ping_waiter is None, \"already await a ping\"\n self._ping_waiter = self._loop.create_future()\n self._quic.send_ping(id(self._ping_waiter))\n self.transmit()\n await asyncio.shield(self._ping_waiter)\n \n===========changed ref 1===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_timeout(self):\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n port=4400,\n configuration=QuicConfiguration(is_client=True, idle_timeout=5),\n )\n )\n \n===========changed ref 2===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_sni(self):\n + server, response = run(\n + asyncio.gather(self.run_server(), self.run_client(\"localhost\"))\n - server, response = run(asyncio.gather(run_server(), run_client(\"localhost\")))\n + )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 3===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_key_update(self):\n async def run_client_key_update(host, port=4433):\n configuration = QuicConfiguration(is_client=True)\n configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n async with connect(host, port, configuration=configuration) as client:\n await client.ping()\n client.request_key_update()\n await client.ping()\n \n server, _ = run(\n asyncio.gather(\n + self.run_server(stateless_retry=False),\n + run_client_key_update(\"127.0.0.1\"),\n - run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n )\n )\n server.close()\n \n===========changed ref 4===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_version_negotiation(self):\n server, response = run(\n asyncio.gather(\n + self.run_server(),\n - run_server(),\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(\n is_client=True,\n quic_logger=QuicLogger(),\n supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23],\n ),\n ),\n )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 5===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n @patch(\"aioquic.quic.retry.QuicRetryTokenHandler.validate_token\")\n def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate):\n mock_validate.side_effect = ValueError(\"Decryption failed.\")\n \n + server = run(self.run_server(stateless_retry=True))\n - server = run(run_server(stateless_retry=True))\n with self.assertRaises(ConnectionError):\n run(\n + self.run_client(\n - run_client(\n \"127.0.0.1\",\n configuration=QuicConfiguration(is_client=True, idle_timeout=4.0),\n )\n )\n server.close()\n \n===========changed ref 6===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_connect_and_serve_with_stateless_retry(self):\n server, response = run(\n + asyncio.gather(\n + self.run_server(stateless_retry=True), self.run_client(\"127.0.0.1\")\n - asyncio.gather(run_server(stateless_retry=True), run_client(\"127.0.0.1\"))\n + )\n )\n self.assertEqual(response, b\"gnip\")\n server.close()\n \n===========changed ref 7===========\n # module: tests.test_asyncio\n class HighLevelTest(TestCase):\n def test_change_connection_id(self):\n async def run_client_key_update(host, port=4433):\n configuration = QuicConfiguration(is_client=True)\n configuration.load_verify_locations(cafile=SERVER_CACERTFILE)\n async with connect(host, port, configuration=configuration) as client:\n await client.ping()\n client.change_connection_id()\n await client.ping()\n \n server, _ = run(\n asyncio.gather(\n + self.run_server(stateless_retry=False),\n + run_client_key_update(\"127.0.0.1\"),\n - run_server(stateless_retry=False), run_client_key_update(\"127.0.0.1\")\n )\n )\n server.close()\n "}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":36,"numItemsPerPage":100,"numTotalItems":7800,"offset":3600,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODA3MTc1Niwic3ViIjoiL2RhdGFzZXRzL2tyYWFsZmFyL0NvZWRpdG9yLXByb2Nlc3NlZC1kZW1vMiIsImV4cCI6MTc1ODA3NTM1NiwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.sMIccv2thC3ipGm0pOW2XcE1R1vBPO6oiZKoKYyxaaO8tBEcVCIENuHgGF6FFbX7c3v7cSRnAxpK9vXHgESKCg","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
examples.http3_client/HttpClient.websocket
Modified
aiortc~aioquic
4a86e356f9392ad0eee7b798aac40556d7b61390
[http3 client] pass URL to websocket() method
<0>:<add> """ <add> Open a WebSocket. <add> """ <add> request = HttpRequest(method="CONNECT", url=URL(url)) <10>:<add> (b":authority", request.url.authority.encode("utf8")), <del> (b":authority", authority.encode("utf8")), <11>:<add> (b":path", request.url.full_path.encode("utf8")), <del> (b":path", path.encode("utf8")), <13>:<add> (b"user-agent", b"aioquic"),
# module: examples.http3_client class HttpClient(QuicConnectionProtocol): - def websocket( - self, authority: str, path: str, subprotocols: List[str] = [] - ) -> WebSocket: + def websocket(self, url: str, subprotocols: List[str] = []) -> WebSocket: <0> stream_id = self._quic.get_next_available_stream_id() <1> websocket = WebSocket( <2> http=self._http, stream_id=stream_id, transmit=self.transmit <3> ) <4> <5> self._websockets[stream_id] = websocket <6> <7> headers = [ <8> (b":method", b"CONNECT"), <9> (b":scheme", b"https"), <10> (b":authority", authority.encode("utf8")), <11> (b":path", path.encode("utf8")), <12> (b":protocol", b"websocket"), <13> (b"sec-websocket-version", b"13"), <14> ] <15> if subprotocols: <16> headers.append( <17> (b"sec-websocket-protocol", ", ".join(subprotocols).encode("utf8")) <18> ) <19> self._http.send_headers(stream_id=stream_id, headers=headers) <20> <21> self.transmit() <22> <23> return websocket <24>
===========unchanged ref 0=========== at: _asyncio.Future set_result(result, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol transmit() -> None quic_event_received(self, event: events.QuicEvent) -> None at: aioquic.h0.connection.H0Connection send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.connection.H3Connection send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events H3Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.quic.events QuicEvent() at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) set_result(result: _T, /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: collections.deque append(x: _T) -> None at: examples.http3_client.HttpClient.__init__ self._http = H3Connection(self._quic) self._http: Optional[HttpConnection] = None self._http = H0Connection(self._quic) self._request_events: Dict[int, Deque[H3Event]] = {} ===========unchanged ref 1=========== self._request_waiter: Dict[int, asyncio.Future[Deque[H3Event]]] = {} self._websockets: Dict[int, WebSocket] = {} at: examples.http3_client.HttpClient.websocket stream_id = self._quic.get_next_available_stream_id() websocket = WebSocket( http=self._http, stream_id=stream_id, transmit=self.transmit ) headers = [ (b":method", b"CONNECT"), (b":scheme", b"https"), (b":authority", request.url.authority.encode("utf8")), (b":path", request.url.full_path.encode("utf8")), (b":protocol", b"websocket"), (b"user-agent", b"aioquic"), (b"sec-websocket-version", b"13"), ] at: examples.http3_client.WebSocket http_event_received(event: H3Event) at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: examples.http3_client class HttpClient(QuicConnectionProtocol): def _request(self, request: HttpRequest): stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", request.method.encode("utf8")), (b":scheme", request.url.scheme.encode("utf8")), + (b":authority", request.url.authority.encode("utf8")), - (b":authority", str(request.url.authority).encode("utf8")), (b":path", request.url.full_path.encode("utf8")), (b"user-agent", b"aioquic"), ] + [ (k.encode("utf8"), v.encode("utf8")) for (k, v) in request.headers.items() ], ) self._http.send_data(stream_id=stream_id, data=request.content, end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter self.transmit() return await asyncio.shield(waiter)
examples.http3_client/run
Modified
aiortc~aioquic
4a86e356f9392ad0eee7b798aac40556d7b61390
[http3 client] pass URL to websocket() method
<13>:<del> path = parsed.path <14>:<del> if parsed.query: <15>:<del> path += "?" + parsed.query <16>:<del> <27>:<del> ws = await client.websocket( <28>:<del> parsed.netloc, path, subprotocols=["chat", "superchat"] <29>:<del> ) <30>:<add> ws = await client.websocket(url, subprotocols=["chat", "superchat"])
# module: examples.http3_client def run(configuration: QuicConfiguration, url: str, data: str) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme in ( <3> "https", <4> "wss", <5> ), "Only https:// or wss:// URLs are supported." <6> if ":" in parsed.netloc: <7> host, port_str = parsed.netloc.split(":") <8> port = int(port_str) <9> else: <10> host = parsed.netloc <11> port = 443 <12> <13> path = parsed.path <14> if parsed.query: <15> path += "?" + parsed.query <16> <17> async with connect( <18> host, <19> port, <20> configuration=configuration, <21> create_protocol=HttpClient, <22> session_ticket_handler=save_session_ticket, <23> ) as client: <24> client = cast(HttpClient, client) <25> <26> if parsed.scheme == "wss": <27> ws = await client.websocket( <28> parsed.netloc, path, subprotocols=["chat", "superchat"] <29> ) <30> <31> # send some messages and receive reply <32> for i in range(2): <33> message = "Hello {}, WebSocket!".format(i) <34> print("> " + message) <35> await ws.send(message) <36> <37> message = await ws.recv() <38> print("< " + message) <39> <40> await ws.close() <41> else: <42> # perform request <43> start = time.time() <44> if data is not None: <45> http_events = await client.post( <46> url, <47> data=data.encode("utf8"), <48> headers={"content-type": "application/x-www-form-urlencoded"}, <49> ) <50> else: <51> http_events = await client.get(url) <52> elapsed = time.time() - start <53> <54> # print speed <55> octets = 0 <56> for http</s>
===========below chunk 0=========== # module: examples.http3_client def run(configuration: QuicConfiguration, url: str, data: str) -> None: # offset: 1 if isinstance(http_event, DataReceived): octets += len(http_event.data) logger.info( "Received %d bytes in %.1f s (%.3f Mbps)" % (octets, elapsed, octets * 8 / elapsed / 1000000) ) # print response for http_event in http_events: if isinstance(http_event, HeadersReceived): headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() elif isinstance(http_event, DataReceived): sys.stdout.buffer.write(http_event.data) sys.stdout.buffer.flush() ===========unchanged ref 0=========== at: _pickle dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: examples.http3_client logger = logging.getLogger("client") HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) save_session_ticket(ticket) at: examples.http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] ===========unchanged ref 1=========== post(url: str, data: bytes, headers: Dict={}) -> Deque[H3Event] websocket(url: str, subprotocols: List[str]=[]) -> WebSocket websocket(self, url: str, subprotocols: List[str]=[]) -> WebSocket at: examples.http3_client.WebSocket close(code=1000, reason="") -> None recv() -> str send(message: str) at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: pickle dump, dumps, load, loads = _dump, _dumps, _load, _loads at: sys stdout: TextIO stderr: TextIO at: time time() -> float at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.IO __slots__ = () flush() -> None at: typing.TextIO __slots__ = () at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: examples.http3_client class HttpClient(QuicConnectionProtocol): - def websocket( - self, authority: str, path: str, subprotocols: List[str] = [] - ) -> WebSocket: + def websocket(self, url: str, subprotocols: List[str] = []) -> WebSocket: + """ + Open a WebSocket. + """ + request = HttpRequest(method="CONNECT", url=URL(url)) stream_id = self._quic.get_next_available_stream_id() websocket = WebSocket( http=self._http, stream_id=stream_id, transmit=self.transmit ) self._websockets[stream_id] = websocket headers = [ (b":method", b"CONNECT"), (b":scheme", b"https"), + (b":authority", request.url.authority.encode("utf8")), - (b":authority", authority.encode("utf8")), + (b":path", request.url.full_path.encode("utf8")), - (b":path", path.encode("utf8")), (b":protocol", b"websocket"), + (b"user-agent", b"aioquic"), (b"sec-websocket-version", b"13"), ] if subprotocols: headers.append( (b"sec-websocket-protocol", ", ".join(subprotocols).encode("utf8")) ) self._http.send_headers(stream_id=stream_id, headers=headers) self.transmit() return websocket ===========changed ref 1=========== # module: examples.http3_client class HttpClient(QuicConnectionProtocol): def _request(self, request: HttpRequest): stream_id = self._quic.get_next_available_stream_id() self._http.send_headers( stream_id=stream_id, headers=[ (b":method", request.method.encode("utf8")), (b":scheme", request.url.scheme.encode("utf8")), + (b":authority", request.url.authority.encode("utf8")), - (b":authority", str(request.url.authority).encode("utf8")), (b":path", request.url.full_path.encode("utf8")), (b"user-agent", b"aioquic"), ] + [ (k.encode("utf8"), v.encode("utf8")) for (k, v) in request.headers.items() ], ) self._http.send_data(stream_id=stream_id, data=request.content, end_stream=True) waiter = self._loop.create_future() self._request_events[stream_id] = deque() self._request_waiter[stream_id] = waiter self.transmit() return await asyncio.shield(waiter)
examples.http3_server/HttpServerProtocol.http_event_received
Modified
aiortc~aioquic
fc7d4612212a33c95e32141b5207657060283623
[http3 server] add "client" to ASGI scope
<26>:<add> # FIXME: add a public API to retrieve peer address <add> client_addr = self._http._quic._network_paths[0].addr <add> client = (client_addr[0], client_addr[1]) <add> <35>:<add> "client": client,
# module: examples.http3_server class HttpServerProtocol(QuicConnectionProtocol): def http_event_received(self, event: H3Event) -> None: <0> if isinstance(event, HeadersReceived) and event.stream_id not in self._handlers: <1> authority = None <2> headers = [] <3> http_version = "0.9" if isinstance(self._http, H0Connection) else "3" <4> raw_path = b"" <5> method = "" <6> protocol = None <7> for header, value in event.headers: <8> if header == b":authority": <9> authority = value <10> headers.append((b"host", value)) <11> elif header == b":method": <12> method = value.decode("utf8") <13> elif header == b":path": <14> raw_path = value <15> elif header == b":protocol": <16> protocol = value.decode("utf8") <17> elif header and not header.startswith(b":"): <18> headers.append((header, value)) <19> <20> if b"?" in raw_path: <21> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <22> else: <23> path_bytes, query_string = raw_path, b"" <24> path = path_bytes.decode("utf8") <25> <26> handler: Handler <27> if method == "CONNECT" and protocol == "websocket": <28> subprotocols: List[str] = [] <29> for header, value in event.headers: <30> if header == b"sec-websocket-protocol": <31> subprotocols = [ <32> x.strip() for x in value.decode("utf8").split(",") <33> ] <34> scope = { <35> "headers": headers, <36> "http_version": http_version, <37> "method": method, <38> "path": path, <39> "query_string": query_string, <40> "raw_path": raw_path, <41> "root_path": "", <42> "scheme": "wss", <43> "subprotocols</s>
===========below chunk 0=========== # module: examples.http3_server class HttpServerProtocol(QuicConnectionProtocol): def http_event_received(self, event: H3Event) -> None: # offset: 1 "type": "websocket", } handler = WebSocketHandler( connection=self._http, scope=scope, stream_id=event.stream_id, transmit=self.transmit, ) else: extensions: Dict[str, Dict] = {} if isinstance(self._http, H3Connection): extensions["http.response.push"] = {} scope = { "extensions": extensions, "headers": headers, "http_version": http_version, "method": method, "path": path, "query_string": query_string, "raw_path": raw_path, "root_path": "", "scheme": "https", "type": "http", } handler = HttpRequestHandler( authority=authority, connection=self._http, protocol=self, scope=scope, stream_ended=event.stream_ended, stream_id=event.stream_id, transmit=self.transmit, ) self._handlers[event.stream_id] = handler asyncio.ensure_future(handler.run_asgi(application)) elif ( isinstance(event, (DataReceived, HeadersReceived)) and event.stream_id in self._handlers ): handler = self._handlers[event.stream_id] handler.http_event_received(event) ===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol transmit() -> None at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection.__init__ self._quic = quic at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: aioquic.h3.events H3Event() HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.quic.connection.QuicConnection.__init__ self._network_paths: List[QuicNetworkPath] = [] at: aioquic.quic.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] at: aioquic.quic.connection.QuicConnection.receive_datagram self._network_paths = [network_path] at: aioquic.quic.connection.QuicNetworkPath addr: NetworkAddress bytes_received: int = 0 bytes_sent: int = 0 is_validated: bool = False local_challenge: Optional[bytes] = None remote_challenge: Optional[bytes] = None at: examples.http3_server HttpRequestHandler(*, authority: bytes, connection: HttpConnection, protocol: QuicConnectionProtocol, scope: Dict, stream_ended: bool, stream_id: int, transmit: Callable[[], None]) WebSocketHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None]) Handler = Union[HttpRequestHandler, WebSocketHandler] application = getattr(module, attr_str) at: examples.http3_server.HttpServerProtocol.__init__ self._handlers: Dict[int, Handler] = {} ===========unchanged ref 1=========== self._http: Optional[HttpConnection] = None at: examples.http3_server.HttpServerProtocol.quic_event_received self._http = H3Connection(self._quic) self._http = H0Connection(self._quic) at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.tls/Context._client_handle_certificate_verify
Modified
aiortc~aioquic
5337baea8eca295aadcdc6c35b1d97f48b429ea2
[tls] verify server certificate dates and subject
<16>:<add> # check certificate <add> verify_certificate(self._peer_certificate, self.server_name) <add>
# module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: <0> verify = pull_certificate_verify(input_buf) <1> <2> assert verify.algorithm in self._signature_algorithms <3> <4> # check signature <5> try: <6> self._peer_certificate.public_key().verify( <7> verify.signature, <8> self.key_schedule.certificate_verify_data( <9> b"TLS 1.3, server CertificateVerify" <10> ), <11> *signature_algorithm_params(verify.algorithm), <12> ) <13> except InvalidSignature: <14> raise AlertDecryptError <15> <16> self.key_schedule.update_hash(input_buf.data) <17> <18> self._set_state(State.CLIENT_EXPECT_FINISHED) <19>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertDecryptError(*args: object) verify_certificate(certificate: x509.Certificate, server_name: Optional[str]) -> None pull_certificate_verify(buf: Buffer) -> CertificateVerify signature_algorithm_params(signature_algorithm: SignatureAlgorithm) -> Union[Tuple[ec.ECDSA], Tuple[padding.AsymmetricPadding, hashes.HashAlgorithm]] at: aioquic.tls.CertificateVerify algorithm: SignatureAlgorithm signature: bytes at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self.server_name: Optional[str] = None self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._peer_certificate: Optional[x509.Certificate] = None at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule certificate_verify_data(context_string: bytes) -> bytes
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<3>:<add> self.certificate_chain: List[x509.Certificate] = []
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.early_data_accepted = False <7> self.handshake_extensions: List[Extension] = [] <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: Optional[List[Extension]] = None <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.alpn_cb: Optional[AlpnHandler] = None <15> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <16> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <17> self.update_traffic_key_cb: Callable[ <18> [Direction, Epoch, CipherSuite, bytes], None <19> ] = lambda d, e, c, s: None <20> <21> # supported parameters <22> self._cipher_suites = [ <23> CipherSuite.AES_256_GCM_SHA384, <24> CipherSuite.AES_128_GCM_SHA256, <25> CipherSuite.CHACHA20_POLY1305_SHA256, <26> ] <27> self._compression_methods = [CompressionMethod.NULL] <28> self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] <29> self._signature_algorithms = [ <30> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <31> SignatureAlgorithm.ECDSA_</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls utcnow = datetime.datetime.utcnow Direction() Epoch() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] KeySchedule(cipher_suite: CipherSuite) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) ===========unchanged ref 1=========== at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self.early_data_accepted = True at: aioquic.tls.SessionTicket age_add: int at: dataclasses field(*, default_factory: Callable[[], _T], init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T field(*, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> Any field(*, default: _T, init: bool=..., repr: bool=..., hash: Optional[bool]=..., compare: bool=..., metadata: Optional[Mapping[str, Any]]=...) -> _T at: datetime datetime() at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' total_seconds() -> float __radd__ = __add__ __rmul__ = __mul__ at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: typing Callable = _CallableType(collections.abc.Callable, 2) Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + def load_pem_private_key( + data: bytes, password: Optional[str] + ) -> Union[dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey]: + """ + Load a PEM-encoded private key. + """ + return serialization.load_pem_private_key( + data, password=password, backend=default_backend() + ) + ===========changed ref 1=========== # module: aioquic.tls + def load_pem_x509_certificates(data: bytes) -> List[x509.Certificate]: + """ + Load a chain of PEM-encoded X509 certificates. + """ + boundary = b"-----END CERTIFICATE-----\n" + certificates = [] + for chunk in data.split(boundary): + if chunk: + certificates.append( + x509.load_pem_x509_certificate( + chunk + boundary, backend=default_backend() + ) + ) + return certificates +
aioquic.quic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<4>:<add> self.tls.certificate_chain = self._configuration.certificate_chain
# module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self._is_client, logger=self._logger) <2> self.tls.alpn_protocols = self._configuration.alpn_protocols <3> self.tls.certificate = self._configuration.certificate <4> self.tls.certificate_private_key = self._configuration.private_key <5> self.tls.handshake_extensions = [ <6> ( <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <8> self._serialize_transport_parameters(), <9> ) <10> ] <11> self.tls.server_name = self._configuration.server_name <12> <13> # TLS session resumption <14> session_ticket = self._configuration.session_ticket <15> if ( <16> self._is_client <17> and session_ticket is not None <18> and session_ticket.is_valid <19> and session_ticket.server_name == self._configuration.server_name <20> ): <21> self.tls.session_ticket = self._configuration.session_ticket <22> <23> # parse saved QUIC transport parameters - for 0-RTT <24> if session_ticket.max_early_data_size == 0xFFFFFFFF: <25> for ext_type, ext_data in session_ticket.other_extensions: <26> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <27> self._parse_transport_parameters( <28> ext_data, from_session_ticket=True <29> ) <30> break <31> <32> # TLS callbacks <33> self.tls.alpn_cb = self._alpn_handler <34> if self._session_ticket_fetcher is not None: <35> self.tls.get_session_ticket_cb = self._session_ticket_fetcher <36> if self._session_ticket_handler is not None: <37> self.tls.new_session_ticket_cb = self._session_ticket_handler <38> self.tls.</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.quic.connection.QuicConnection _alpn_handler(alpn_protocol: str) -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} ===========unchanged ref 1=========== self._packet_number = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._version: Optional[int] = None self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] at: aioquic.quic.connection.QuicConnection.datagrams_to_send self._packet_number = builder.packet_number at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) at: aioquic.quic.crypto CryptoPair() at: aioquic.quic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool, version: int) -> None at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.stream QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========unchanged ref 2=========== Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.tls + def load_pem_private_key( + data: bytes, password: Optional[str] + ) -> Union[dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey]: + """ + Load a PEM-encoded private key. + """ + return serialization.load_pem_private_key( + data, password=password, backend=default_backend() + ) +
tests.test_connection/client_and_server
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<9>:<del> server = QuicConnection( <10>:<add> server_configuration = QuicConfiguration( <del> configuration=QuicConfiguration( <11>:<del> is_client=False, <12>:<del> certificate=SERVER_CERTIFICATE, <13>:<del> private_key=SERVER_PRIVATE_KEY, <14>:<del> quic_logger=QuicLogger(), <15>:<del> **server_options <16>:<del> ), <17>:<del> **server_kwargs <18>:<add> is_client=False, quic_logger=QuicLogger(), **server_options <19>:<add> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <add> <add> server = QuicConnection(configuration=server_configuration, **server_kwargs)
# module: tests.test_connection @contextlib.contextmanager def client_and_server( client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_options={}, server_patch=lambda x: None, transport_options={}, ): <0> client = QuicConnection( <1> configuration=QuicConfiguration( <2> is_client=True, quic_logger=QuicLogger(), **client_options <3> ), <4> **client_kwargs <5> ) <6> client._ack_delay = 0 <7> client_patch(client) <8> <9> server = QuicConnection( <10> configuration=QuicConfiguration( <11> is_client=False, <12> certificate=SERVER_CERTIFICATE, <13> private_key=SERVER_PRIVATE_KEY, <14> quic_logger=QuicLogger(), <15> **server_options <16> ), <17> **server_kwargs <18> ) <19> server._ack_delay = 0 <20> server_patch(server) <21> <22> # perform handshake <23> if handshake: <24> client.connect(SERVER_ADDR, now=time.time()) <25> for i in range(3): <26> roundtrip(client, server) <27> <28> yield client, server <29> <30> # close <31> client.close() <32> server.close() <33>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) ===========unchanged ref 1=========== at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None connect(addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY at: aioquic.quic.logger QuicLogger() at: contextlib contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]] at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) roundtrip(sender, receiver) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: time time() -> float ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_cert_chain( + self, + certfile: PathLike, + keyfile: Optional[PathLike] = None, + password: Optional[str] = None, + ): + """ + Load a private key and the corresponding certificate. + """ + with open(certfile, "rb") as fp: + certificates = load_pem_x509_certificates(fp.read()) + self.certificate = certificates[0] + self.certificate_chain = certificates[1:] + + if keyfile is not None: + with open(keyfile, "rb") as fp: + self.private_key = load_pem_private_key(fp.read(), password=password) + ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. - """ - - certificate: Any = None - """ - The server's TLS certificate. - - See :func:`cryptography.x509.load_pem_x509_certificate`. - - .. note:: This is only used by servers. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. - """ - - private_key: Any = None - """ - The server's TLS private key. - - See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. - - .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] =</s> ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] = field(default_factory=list) + private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 3=========== # module: aioquic.tls + def load_pem_private_key( + data: bytes, password: Optional[str] + ) -> Union[dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey]: + """ + Load a PEM-encoded private key. + """ + return serialization.load_pem_private_key( + data, password=password, backend=default_backend() + ) + ===========changed ref 4=========== # module: aioquic.tls + def load_pem_x509_certificates(data: bytes) -> List[x509.Certificate]: + """ + Load a chain of PEM-encoded X509 certificates. + """ + boundary = b"-----END CERTIFICATE-----\n" + certificates = [] + for chunk in data.split(boundary): + if chunk: + certificates.append( + x509.load_pem_x509_certificate( + chunk + boundary, backend=default_backend() + ) + ) + return certificates +
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<10>:<del> server = QuicConnection( <11>:<del> configuration=QuicConfiguration( <12>:<del> is_client=False, <13>:<del> certificate=SERVER_CERTIFICATE, <14>:<del> private_key=SERVER_PRIVATE_KEY, <15>:<del> ) <16>:<del> ) <17>:<add> server_configuration = QuicConfiguration(is_client=False) <add> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <add> <add> server = QuicConnection(configuration=server_configuration)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): <0> """ <1> Check connection is established even in the client's INITIAL is lost. <2> """ <3> <4> def datagram_sizes(items): <5> return [len(x[0]) for x in items] <6> <7> client = QuicConnection(configuration=QuicConfiguration(is_client=True)) <8> client._ack_delay = 0 <9> <10> server = QuicConnection( <11> configuration=QuicConfiguration( <12> is_client=False, <13> certificate=SERVER_CERTIFICATE, <14> private_key=SERVER_PRIVATE_KEY, <15> ) <16> ) <17> server._ack_delay = 0 <18> <19> # client sends INITIAL <20> now = 0.0 <21> client.connect(SERVER_ADDR, now=now) <22> items = client.datagrams_to_send(now=now) <23> self.assertEqual(datagram_sizes(items), [1280]) <24> self.assertEqual(client.get_timer(), 1.0) <25> <26> # INITIAL is lost <27> now = 1.0 <28> client.handle_timer(now=now) <29> items = client.datagrams_to_send(now=now) <30> self.assertEqual(datagram_sizes(items), [1280]) <31> self.assertEqual(client.get_timer(), 3.0) <32> <33> # server receives INITIAL, sends INITIAL + HANDSHAKE <34> now = 1.1 <35> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <36> items = server.datagrams_to_send(now=now) <37> self.assertEqual(datagram_sizes(items), [1280, 1084]) <38> self.assertEqual(server.get_timer(), 2.1) <39> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <40> self.assertEqual(len(server._loss.spaces[1</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 1 # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 223]) self.assertAlmostEqual(client.get_timer(), 1.825) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) server.receive_datagram(items[1][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [276]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 1) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) now = 1.5 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) </s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) ===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY ===========unchanged ref 1=========== self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_cert_chain( + self, + certfile: PathLike, + keyfile: Optional[PathLike] = None, + password: Optional[str] = None, + ): + """ + Load a private key and the corresponding certificate. + """ + with open(certfile, "rb") as fp: + certificates = load_pem_x509_certificates(fp.read()) + self.certificate = certificates[0] + self.certificate_chain = certificates[1:] + + if keyfile is not None: + with open(keyfile, "rb") as fp: + self.private_key = load_pem_private_key(fp.read(), password=password) +
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<6>:<del> server = QuicConnection( <7>:<del> configuration=QuicConfiguration( <8>:<del> is_client=False, <9>:<del> certificate=SERVER_CERTIFICATE, <10>:<del> private_key=SERVER_PRIVATE_KEY, <11>:<del> ) <12>:<del> ) <13>:<add> server_configuration = QuicConfiguration(is_client=False) <add> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <add> <add> server = QuicConnection(configuration=server_configuration)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client = QuicConnection(configuration=QuicConfiguration(is_client=True)) <4> client._ack_delay = 0 <5> <6> server = QuicConnection( <7> configuration=QuicConfiguration( <8> is_client=False, <9> certificate=SERVER_CERTIFICATE, <10> private_key=SERVER_PRIVATE_KEY, <11> ) <12> ) <13> server._ack_delay = 0 <14> <15> # client sends INITIAL <16> now = 0.0 <17> client.connect(SERVER_ADDR, now=now) <18> items = client.datagrams_to_send(now=now) <19> self.assertEqual(datagram_sizes(items), [1280]) <20> self.assertEqual(client.get_timer(), 1.0) <21> <22> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <23> now = 0.1 <24> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <25> items = server.datagrams_to_send(now=now) <26> self.assertEqual(datagram_sizes(items), [1280, 1084]) <27> self.assertEqual(server.get_timer(), 1.1) <28> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <29> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <30> <31> #  client only receives first datagram and sends ACKS <32> now = 0.2 <33> client.receive_datagram(items[0][0], SERVER_ADDR, now=now) <34> items = client.datagrams_to_send(now=now) <35> self.assertEqual(datagram_sizes(items), [97]) <36> self.assertAlmostEqual(client</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 #  client PTO - padded HANDSHAKE now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 1.25) # server receives padding, discards INITIAL now = 0.725 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 1.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) # ACKs are lost, server retransmits HANDSHAKE now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 905]) self.assertAlmostEqual(server.get_timer(), 3.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s> items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [334]) self.assertAlmostEqual(client.get_timer(), 2.45) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [228]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout ===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY ===========unchanged ref 1=========== self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) SessionTicketStore() client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_2 datagram_sizes(items) client = QuicConnection(configuration=QuicConfiguration(is_client=True)) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
tests.test_tls/ContextTest.create_server
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<0>:<add> configuration = QuicConfiguration(is_client=False) <add> configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <add> <1>:<add> server.certificate = configuration.certificate <add> server.certificate_private_key = configuration.private_key <del> server.certificate = SERVER_CERTIFICATE <2>:<del> server.certificate_private_key = SERVER_PRIVATE_KEY
# module: tests.test_tls class ContextTest(TestCase): def create_server(self): <0> server = Context(is_client=False) <1> server.certificate = SERVER_CERTIFICATE <2> server.certificate_private_key = SERVER_PRIVATE_KEY <3> server.handshake_extensions = [ <4> ( <5> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <6> SERVER_QUIC_TRANSPORT_PARAMETERS, <7> ) <8> ] <9> self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO) <10> return server <11>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.private_key = load_pem_private_key(fp.read(), password=password) ===========unchanged ref 1=========== at: aioquic.tls ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] at: tests.test_tls SERVER_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff00001104ff000011004500050004801000000006000480100000000700048" b"010000000040004810000000001000242580002001000000000000000000000" b"000000000000000800024064000a00010a" ) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_cert_chain( + self, + certfile: PathLike, + keyfile: Optional[PathLike] = None, + password: Optional[str] = None, + ): + """ + Load a private key and the corresponding certificate. + """ + with open(certfile, "rb") as fp: + certificates = load_pem_x509_certificates(fp.read()) + self.certificate = certificates[0] + self.certificate_chain = certificates[1:] + + if keyfile is not None: + with open(keyfile, "rb") as fp: + self.private_key = load_pem_private_key(fp.read(), password=password) + ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. - """ - - certificate: Any = None - """ - The server's TLS certificate. - - See :func:`cryptography.x509.load_pem_x509_certificate`. - - .. note:: This is only used by servers. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. - """ - - private_key: Any = None - """ - The server's TLS private key. - - See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. - - .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] =</s> ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] = field(default_factory=list) + private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 3=========== # module: aioquic.tls + def load_pem_private_key( + data: bytes, password: Optional[str] + ) -> Union[dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey]: + """ + Load a PEM-encoded private key. + """ + return serialization.load_pem_private_key( + data, password=password, backend=default_backend() + ) + ===========changed ref 4=========== # module: aioquic.tls + def load_pem_x509_certificates(data: bytes) -> List[x509.Certificate]: + """ + Load a chain of PEM-encoded X509 certificates. + """ + boundary = b"-----END CERTIFICATE-----\n" + certificates = [] + for chunk in data.split(boundary): + if chunk: + certificates.append( + x509.load_pem_x509_certificate( + chunk + boundary, backend=default_backend() + ) + ) + return certificates +
tests.test_asyncio/run_server
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<1>:<add> configuration = QuicConfiguration(is_client=False) <del> configuration = QuicConfiguration( <2>:<del> certificate=SERVER_CERTIFICATE, <3>:<del> private_key=SERVER_PRIVATE_KEY, <4>:<del> is_client=False, <5>:<del> ) <6>:<add> configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)
# module: tests.test_asyncio def run_server(configuration=None, **kwargs): <0> if configuration is None: <1> configuration = QuicConfiguration( <2> certificate=SERVER_CERTIFICATE, <3> private_key=SERVER_PRIVATE_KEY, <4> is_client=False, <5> ) <6> return await serve( <7> host="::", <8> port="4433", <9> configuration=configuration, <10> stream_handler=handle_stream, <11> **kwargs <12> ) <13>
===========unchanged ref 0=========== at: aioquic.asyncio.server serve(host: str, port: int, *, configuration: QuicConfiguration, create_protocol: Callable=QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: QuicStreamHandler=None) -> QuicServer at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========unchanged ref 1=========== load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) at: tests.test_asyncio handle_stream(reader, writer) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case TestCase(methodName: str=...) ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_cert_chain( + self, + certfile: PathLike, + keyfile: Optional[PathLike] = None, + password: Optional[str] = None, + ): + """ + Load a private key and the corresponding certificate. + """ + with open(certfile, "rb") as fp: + certificates = load_pem_x509_certificates(fp.read()) + self.certificate = certificates[0] + self.certificate_chain = certificates[1:] + + if keyfile is not None: + with open(keyfile, "rb") as fp: + self.private_key = load_pem_private_key(fp.read(), password=password) + ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. - """ - - certificate: Any = None - """ - The server's TLS certificate. - - See :func:`cryptography.x509.load_pem_x509_certificate`. - - .. note:: This is only used by servers. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. - """ - - private_key: Any = None - """ - The server's TLS private key. - - See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. - - .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] =</s> ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] = field(default_factory=list) + private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 3=========== # module: aioquic.tls + def load_pem_private_key( + data: bytes, password: Optional[str] + ) -> Union[dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey]: + """ + Load a PEM-encoded private key. + """ + return serialization.load_pem_private_key( + data, password=password, backend=default_backend() + ) + ===========changed ref 4=========== # module: aioquic.tls + def load_pem_x509_certificates(data: bytes) -> List[x509.Certificate]: + """ + Load a chain of PEM-encoded X509 certificates. + """ + boundary = b"-----END CERTIFICATE-----\n" + certificates = [] + for chunk in data.split(boundary): + if chunk: + certificates.append( + x509.load_pem_x509_certificate( + chunk + boundary, backend=default_backend() + ) + ) + return certificates + ===========changed ref 5=========== # module: tests.utils - SERVER_CERTIFICATE = x509.load_pem_x509_certificate( - load("ssl_cert.pem"), backend=default_backend() - ) - SERVER_PRIVATE_KEY = serialization.load_pem_private_key( - load("ssl_key.pem"), password=None, backend=default_backend() - ) + SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") + SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") if os.environ.get("AIOQUIC_DEBUG"): logging.basicConfig(level=logging.DEBUG)
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss
Modified
aiortc~aioquic
214808c46b6e7dc6833323f9cf1d9d6e61e91096
[config] add QuicConfiguration.load_cert_chain method
<5>:<add> <add> server_configuration = QuicConfiguration( <add> idle_timeout=300.0, is_client=False, quic_logger=QuicLogger() <add> ) <add> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <add> <7>:<del> run_server( <8>:<del> configuration=QuicConfiguration( <9>:<del> certificate=SERVER_CERTIFICATE, <10>:<del> idle_timeout=300.0, <11>:<del> is_client=False, <12>:<del> private_key=SERVER_PRIVATE_KEY, <13>:<del> quic_logger=QuicLogger(), <14>:<del> ), <15>:<del> stateless_retry=True, <16>:<del> ), <17>:<add> run_server(configuration=server_configuration, stateless_retry=True),
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): <0> """ <1> This test ensures handshake success and stream data is successfully sent <2> and received in the presence of packet loss (randomized 25% in each direction). <3> """ <4> data = b"Z" * 65536 <5> server, response = run( <6> asyncio.gather( <7> run_server( <8> configuration=QuicConfiguration( <9> certificate=SERVER_CERTIFICATE, <10> idle_timeout=300.0, <11> is_client=False, <12> private_key=SERVER_PRIVATE_KEY, <13> quic_logger=QuicLogger(), <14> ), <15> stateless_retry=True, <16> ), <17> run_client( <18> "127.0.0.1", <19> configuration=QuicConfiguration( <20> is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() <21> ), <22> request=data, <23> ), <24> ) <25> ) <26> self.assertEqual(response, data) <27> server.close() <28>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) at: aioquic.quic.logger QuicLogger() ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio SessionTicketStore() run_client(host, port=4433, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.utils run(coro) SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio def run_server(configuration=None, **kwargs): if configuration is None: + configuration = QuicConfiguration(is_client=False) - configuration = QuicConfiguration( - certificate=SERVER_CERTIFICATE, - private_key=SERVER_PRIVATE_KEY, - is_client=False, - ) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) return await serve( host="::", port="4433", configuration=configuration, stream_handler=handle_stream, **kwargs ) ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_cert_chain( + self, + certfile: PathLike, + keyfile: Optional[PathLike] = None, + password: Optional[str] = None, + ): + """ + Load a private key and the corresponding certificate. + """ + with open(certfile, "rb") as fp: + certificates = load_pem_x509_certificates(fp.read()) + self.certificate = certificates[0] + self.certificate_chain = certificates[1:] + + if keyfile is not None: + with open(keyfile, "rb") as fp: + self.private_key = load_pem_private_key(fp.read(), password=password) + ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. - """ - - certificate: Any = None - """ - The server's TLS certificate. - - See :func:`cryptography.x509.load_pem_x509_certificate`. - - .. note:: This is only used by servers. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. - """ - - private_key: Any = None - """ - The server's TLS private key. - - See :func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`. - - .. note:: This is only used by servers. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] =</s> ===========changed ref 3=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> used for session resumption. """ + certificate: Any = None + certificate_chain: List[Any] = field(default_factory=list) + private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<2>:<add> self.cadata: Optional[bytes] = None <add> self.cafile: Optional[str] = None <add> self.capath: Optional[str] = None
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_chain: List[x509.Certificate] = [] <4> self.certificate_private_key: Optional[ <5> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <6> ] = None <7> self.early_data_accepted = False <8> self.handshake_extensions: List[Extension] = [] <9> self.key_schedule: Optional[KeySchedule] = None <10> self.received_extensions: Optional[List[Extension]] = None <11> self.session_ticket: Optional[SessionTicket] = None <12> self.server_name: Optional[str] = None <13> <14> # callbacks <15> self.alpn_cb: Optional[AlpnHandler] = None <16> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <17> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <18> self.update_traffic_key_cb: Callable[ <19> [Direction, Epoch, CipherSuite, bytes], None <20> ] = lambda d, e, c, s: None <21> <22> # supported parameters <23> self._cipher_suites = [ <24> CipherSuite.AES_256_GCM_SHA384, <25> CipherSuite.AES_128_GCM_SHA256, <26> CipherSuite.CHACHA20_POLY1305_SHA256, <27> ] <28> self._compression_methods = [CompressionMethod.NULL] <29> self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] <30> self._signature_algorithms = [ <31> SignatureAlgorithm.RSA_</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) AlpnHandler = Callable[[str], None] ===========unchanged ref 1=========== SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) ===========unchanged ref 2=========== self.client_random = peer_hello.random self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self.early_data_accepted = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) self._new_session_ticket = NewSessionTicket( ticket_lifetime=86400, ticket_age_add=struct.unpack("I", os.urandom(4))[0], ticket_nonce=b"", ticket=os.urandom(64), max_early_data_size=0xFFFFFFFF, ) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 1=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" +
aioquic.tls/Context._client_handle_certificate
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<5>:<add> self._peer_certificate_chain = [ <add> x509.load_der_x509_certificate( <add> certificate.certificates[i][0], backend=default_backend() <add> ) <add> for i in range(1, len(certificate.certificates)) <add> ] <add>
# module: aioquic.tls class Context: def _client_handle_certificate(self, input_buf: Buffer) -> None: <0> certificate = pull_certificate(input_buf) <1> <2> self._peer_certificate = x509.load_der_x509_certificate( <3> certificate.certificates[0][0], backend=default_backend() <4> ) <5> self.key_schedule.update_hash(input_buf.data) <6> <7> self._set_state(State.CLIENT_EXPECT_CERTIFICATE_VERIFY) <8>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls State() pull_certificate(buf: Buffer) -> Certificate at: aioquic.tls.Certificate request_context: bytes = b"" certificates: List[CertificateEntry] = field(default_factory=list) at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._peer_certificate: Optional[x509.Certificate] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule update_hash(data: bytes) -> None ===========changed ref 0=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 1=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 2=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 3=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 4=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None + self.cadata: Optional[bytes] = None + self.cafile: Optional[str] = None + self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_</s> ===========changed ref 5=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s>psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None + self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_ ===========changed ref 6=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow
aioquic.tls/Context._client_handle_certificate_verify
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<17>:<add> verify_certificate( <add> cadata=self.cadata, <add> cafile=self.cafile, <add> capath=self.capath, <add> certificate=self._peer_certificate, <add> chain=self._peer_certificate_chain, <add> server_name=self.server_name, <add> ) <del> verify_certificate(self._peer_certificate, self.server_name)
# module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: <0> verify = pull_certificate_verify(input_buf) <1> <2> assert verify.algorithm in self._signature_algorithms <3> <4> # check signature <5> try: <6> self._peer_certificate.public_key().verify( <7> verify.signature, <8> self.key_schedule.certificate_verify_data( <9> b"TLS 1.3, server CertificateVerify" <10> ), <11> *signature_algorithm_params(verify.algorithm), <12> ) <13> except InvalidSignature: <14> raise AlertDecryptError <15> <16> # check certificate <17> verify_certificate(self._peer_certificate, self.server_name) <18> <19> self.key_schedule.update_hash(input_buf.data) <20> <21> self._set_state(State.CLIENT_EXPECT_FINISHED) <22>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertDecryptError(*args: object) State() verify_certificate(certificate: x509.Certificate, server_name: Optional[str]) -> None pull_certificate_verify(buf: Buffer) -> CertificateVerify signature_algorithm_params(signature_algorithm: SignatureAlgorithm) -> Union[Tuple[ec.ECDSA], Tuple[padding.AsymmetricPadding, hashes.HashAlgorithm]] at: aioquic.tls.CertificateVerify algorithm: SignatureAlgorithm signature: bytes at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self.server_name: Optional[str] = None self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._peer_certificate: Optional[x509.Certificate] = None at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule certificate_verify_data(context_string: bytes) -> bytes update_hash(data: bytes) -> None ===========changed ref 0=========== # module: aioquic.tls class Context: def _client_handle_certificate(self, input_buf: Buffer) -> None: certificate = pull_certificate(input_buf) self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) + self._peer_certificate_chain = [ + x509.load_der_x509_certificate( + certificate.certificates[i][0], backend=default_backend() + ) + for i in range(1, len(certificate.certificates)) + ] + self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_CERTIFICATE_VERIFY) ===========changed ref 1=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 2=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 3=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 4=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 5=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None + self.cadata: Optional[bytes] = None + self.cafile: Optional[str] = None + self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_</s> ===========changed ref 6=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s>psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None + self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_
aioquic.quic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<3>:<add> self.tls.cadata = self._configuration.cadata <add> self.tls.cafile = self._configuration.cafile <add> self.tls.capath = self._configuration.capath
# module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self._is_client, logger=self._logger) <2> self.tls.alpn_protocols = self._configuration.alpn_protocols <3> self.tls.certificate = self._configuration.certificate <4> self.tls.certificate_chain = self._configuration.certificate_chain <5> self.tls.certificate_private_key = self._configuration.private_key <6> self.tls.handshake_extensions = [ <7> ( <8> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <9> self._serialize_transport_parameters(), <10> ) <11> ] <12> self.tls.server_name = self._configuration.server_name <13> <14> # TLS session resumption <15> session_ticket = self._configuration.session_ticket <16> if ( <17> self._is_client <18> and session_ticket is not None <19> and session_ticket.is_valid <20> and session_ticket.server_name == self._configuration.server_name <21> ): <22> self.tls.session_ticket = self._configuration.session_ticket <23> <24> # parse saved QUIC transport parameters - for 0-RTT <25> if session_ticket.max_early_data_size == 0xFFFFFFFF: <26> for ext_type, ext_data in session_ticket.other_extensions: <27> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <28> self._parse_transport_parameters( <29> ext_data, from_session_ticket=True <30> ) <31> break <32> <33> # TLS callbacks <34> self.tls.alpn_cb = self._alpn_handler <35> if self._session_ticket_fetcher is not None: <36> self.tls.get_session_ticket_cb = self._session_ticket_fetcher <37> if self._session_ticket_handler is not None: <38> self.tls.new_session_</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.certificate_chain = certificates[1:] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.quic.connection.QuicConnection _alpn_handler(alpn_protocol: str) -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client ===========unchanged ref 1=========== self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._packet_number = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._version: Optional[int] = None self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] at: aioquic.quic.connection.QuicConnection.datagrams_to_send self._packet_number = builder.packet_number at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) at: aioquic.quic.crypto CryptoPair() at: aioquic.quic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool, version: int) -> None at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.stream QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) ===========unchanged ref 2=========== at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 1=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 2=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL +
tests.test_connection/client_and_server
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<0>:<del> client = QuicConnection( <1>:<add> client_configuration = QuicConfiguration( <del> configuration=QuicConfiguration( <2>:<add> is_client=True, quic_logger=QuicLogger(), **client_options <del> is_client=True, quic_logger=QuicLogger(), **client_options <3>:<del> ), <4>:<del> **client_kwargs <6>:<add> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> <add> client = QuicConnection(configuration=client_configuration, **client_kwargs) <12>:<add> server_configuration.load_cert_chain(server_certfile, server_keyfile) <del> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE)
# module: tests.test_connection @contextlib.contextmanager def client_and_server( client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, + server_certfile=SERVER_CERTFILE, + server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}, ): <0> client = QuicConnection( <1> configuration=QuicConfiguration( <2> is_client=True, quic_logger=QuicLogger(), **client_options <3> ), <4> **client_kwargs <5> ) <6> client._ack_delay = 0 <7> client_patch(client) <8> <9> server_configuration = QuicConfiguration( <10> is_client=False, quic_logger=QuicLogger(), **server_options <11> ) <12> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <13> <14> server = QuicConnection(configuration=server_configuration, **server_kwargs) <15> server._ack_delay = 0 <16> server_patch(server) <17> <18> # perform handshake <19> if handshake: <20> client.connect(SERVER_ADDR, now=time.time()) <21> for i in range(3): <22> roundtrip(client, server) <23> <24> yield client, server <25> <26> # close <27> client.close() <28> server.close() <29>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None ===========unchanged ref 1=========== at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None connect(addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY at: aioquic.quic.logger QuicLogger() at: contextlib contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]] at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) roundtrip(sender, receiver) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: time time() -> float ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + cadata: Optional[bytes] = None + cafile: Optional[str] = None + capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 1=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 2=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 3=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 4=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 5=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 6=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<7>:<add> client_configuration = QuicConfiguration(is_client=True) <del> client = QuicConnection(configuration=QuicConfiguration(is_client=True)) <8>:<add> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> <add> client = QuicConnection(configuration=client_configuration)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): <0> """ <1> Check connection is established even in the client's INITIAL is lost. <2> """ <3> <4> def datagram_sizes(items): <5> return [len(x[0]) for x in items] <6> <7> client = QuicConnection(configuration=QuicConfiguration(is_client=True)) <8> client._ack_delay = 0 <9> <10> server_configuration = QuicConfiguration(is_client=False) <11> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <12> <13> server = QuicConnection(configuration=server_configuration) <14> server._ack_delay = 0 <15> <16> # client sends INITIAL <17> now = 0.0 <18> client.connect(SERVER_ADDR, now=now) <19> items = client.datagrams_to_send(now=now) <20> self.assertEqual(datagram_sizes(items), [1280]) <21> self.assertEqual(client.get_timer(), 1.0) <22> <23> # INITIAL is lost <24> now = 1.0 <25> client.handle_timer(now=now) <26> items = client.datagrams_to_send(now=now) <27> self.assertEqual(datagram_sizes(items), [1280]) <28> self.assertEqual(client.get_timer(), 3.0) <29> <30> # server receives INITIAL, sends INITIAL + HANDSHAKE <31> now = 1.1 <32> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <33> items = server.datagrams_to_send(now=now) <34> self.assertEqual(datagram_sizes(items), [1280, 1084]) <35> self.assertEqual(server.get_timer(), 2.1) <36> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <37> self.assertEqual(len(server._loss.spaces[1].</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 1 # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 223]) self.assertAlmostEqual(client.get_timer(), 1.825) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) server.receive_datagram(items[1][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [276]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 1) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) now = 1.5 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) </s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) ===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY ===========unchanged ref 1=========== self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<3>:<add> client_configuration = QuicConfiguration(is_client=True) <del> client = QuicConnection(configuration=QuicConfiguration(is_client=True)) <4>:<add> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> <add> client = QuicConnection(configuration=client_configuration)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client = QuicConnection(configuration=QuicConfiguration(is_client=True)) <4> client._ack_delay = 0 <5> <6> server_configuration = QuicConfiguration(is_client=False) <7> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <8> <9> server = QuicConnection(configuration=server_configuration) <10> server._ack_delay = 0 <11> <12> # client sends INITIAL <13> now = 0.0 <14> client.connect(SERVER_ADDR, now=now) <15> items = client.datagrams_to_send(now=now) <16> self.assertEqual(datagram_sizes(items), [1280]) <17> self.assertEqual(client.get_timer(), 1.0) <18> <19> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <20> now = 0.1 <21> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <22> items = server.datagrams_to_send(now=now) <23> self.assertEqual(datagram_sizes(items), [1280, 1084]) <24> self.assertEqual(server.get_timer(), 1.1) <25> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <26> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <27> <28> #  client only receives first datagram and sends ACKS <29> now = 0.2 <30> client.receive_datagram(items[0][0], SERVER_ADDR, now=now) <31> items = client.datagrams_to_send(now=now) <32> self.assertEqual(datagram_sizes(items), [97]) <33> self.assertAlmostEqual(client.</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 #  client PTO - padded HANDSHAKE now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 1.25) # server receives padding, discards INITIAL now = 0.725 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 1.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) # ACKs are lost, server retransmits HANDSHAKE now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 905]) self.assertAlmostEqual(server.get_timer(), 3.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s> items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [334]) self.assertAlmostEqual(client.get_timer(), 2.45) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [228]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout ===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection connect(addr: NetworkAddress, now: float) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY ===========unchanged ref 1=========== self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
tests.test_tls/ContextTest.create_client
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<1>:<add> client.cafile = cafile
# module: tests.test_tls class ContextTest(TestCase): + def create_client(self, cafile=SERVER_CACERTFILE): - def create_client(self): <0> client = Context(is_client=True) <1> client.handshake_extensions = [ <2> ( <3> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <4> CLIENT_QUIC_TRANSPORT_PARAMETERS, <5> ) <6> ] <7> self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) <8> return client <9>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer seek(pos: int) -> None at: aioquic.tls Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") at: unittest.case TestCase(methodName: str=...) ===========changed ref 0=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 1=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 2=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 3=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_cert_chain(self): + with client_and_server(server_certfile=SERVER_CERTFILE_WITH_CHAIN) as ( + client, + server, + ): + pass + ===========changed ref 5=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 6=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow ===========changed ref 7=========== # module: aioquic.tls class Context: def _client_handle_certificate(self, input_buf: Buffer) -> None: certificate = pull_certificate(input_buf) self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) + self._peer_certificate_chain = [ + x509.load_der_x509_certificate( + certificate.certificates[i][0], backend=default_backend() + ) + for i in range(1, len(certificate.certificates)) + ] + self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_CERTIFICATE_VERIFY) ===========changed ref 8=========== # module: tests.utils + SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") + SERVER_CERTFILE_WITH_CHAIN = os.path.join( + os.path.dirname(__file__), "ssl_cert_with_chain.pem" + ) SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") if os.environ.get("AIOQUIC_DEBUG"): logging.basicConfig(level=logging.DEBUG) ===========changed ref 9=========== # module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: verify = pull_certificate_verify(input_buf) assert verify.algorithm in self._signature_algorithms # check signature try: self._peer_certificate.public_key().verify( verify.signature, self.key_schedule.certificate_verify_data( b"TLS 1.3, server CertificateVerify" ), *signature_algorithm_params(verify.algorithm), ) except InvalidSignature: raise AlertDecryptError # check certificate + verify_certificate( + cadata=self.cadata, + cafile=self.cafile, + capath=self.capath, + certificate=self._peer_certificate, + chain=self._peer_certificate_chain, + server_name=self.server_name, + ) - verify_certificate(self._peer_certificate, self.server_name) self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_FINISHED) ===========changed ref 10=========== # module: tests.test_connection @contextlib.contextmanager def client_and_server( client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, + server_certfile=SERVER_CERTFILE, + server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}, ): - client = QuicConnection( + client_configuration = QuicConfiguration( - configuration=QuicConfiguration( + is_client=True, quic_logger=QuicLogger(), **client_options - is_client=True, quic_logger=QuicLogger(), **client_options - ), - **client_kwargs ) + client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) + + client = QuicConnection(configuration=client_configuration, **client_kwargs) client._ack_delay = 0 client_patch(client) server_configuration = QuicConfiguration( is_client=False, quic_logger=QuicLogger(), **server_options ) + server_configuration.load_cert_chain(server_certfile, server_keyfile) - server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection(configuration=server_configuration, **server_kwargs) server._ack_delay = 0 server_patch(server) # perform handshake if handshake: client.connect(SERVER_ADDR, now=time.time()) for i in range(3): roundtrip(client, server) yield client, server # close client.close() server.close()
tests.test_tls/ContextTest.test_handshake_ecdsa_secp256r1
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<0>:<del> client = self.create_client() <5>:<add> <add> client = self.create_client(cafile=None) <add> client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM)
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): <0> client = self.create_client() <1> server = self.create_server() <2> server.certificate, server.certificate_private_key = generate_ec_certificate( <3> common_name="example.com", curve=ec.SECP256R1 <4> ) <5> <6> self._handshake(client, server) <7> <8> # check ALPN matches <9> self.assertEqual(client.alpn_negotiated, None) <10> self.assertEqual(server.alpn_negotiated, None) <11>
===========unchanged ref 0=========== at: aioquic.tls.Context.__init__ self.alpn_negotiated: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) at: tests.test_tls.ContextTest create_client(cafile=SERVER_CACERTFILE) create_client(self, cafile=SERVER_CACERTFILE) create_server() _handshake(client, server) at: tests.utils generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[]) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, cafile=SERVER_CACERTFILE): - def create_client(self): client = Context(is_client=True) + client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 1=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 2=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 3=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 4=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_cert_chain(self): + with client_and_server(server_certfile=SERVER_CERTFILE_WITH_CHAIN) as ( + client, + server, + ): + pass + ===========changed ref 6=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 7=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow ===========changed ref 8=========== # module: aioquic.tls class Context: def _client_handle_certificate(self, input_buf: Buffer) -> None: certificate = pull_certificate(input_buf) self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) + self._peer_certificate_chain = [ + x509.load_der_x509_certificate( + certificate.certificates[i][0], backend=default_backend() + ) + for i in range(1, len(certificate.certificates)) + ] + self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_CERTIFICATE_VERIFY) ===========changed ref 9=========== # module: tests.utils + SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") + SERVER_CERTFILE_WITH_CHAIN = os.path.join( + os.path.dirname(__file__), "ssl_cert_with_chain.pem" + ) SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") if os.environ.get("AIOQUIC_DEBUG"): logging.basicConfig(level=logging.DEBUG) ===========changed ref 10=========== # module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: verify = pull_certificate_verify(input_buf) assert verify.algorithm in self._signature_algorithms # check signature try: self._peer_certificate.public_key().verify( verify.signature, self.key_schedule.certificate_verify_data( b"TLS 1.3, server CertificateVerify" ), *signature_algorithm_params(verify.algorithm), ) except InvalidSignature: raise AlertDecryptError # check certificate + verify_certificate( + cadata=self.cadata, + cafile=self.cafile, + capath=self.capath, + certificate=self._peer_certificate, + chain=self._peer_certificate_chain, + server_name=self.server_name, + ) - verify_certificate(self._peer_certificate, self.server_name) self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_FINISHED)
tests.test_tls/VerifyCertificateTest.test_verify_dates
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<3>:<add> cadata = certificate.public_bytes(serialization.Encoding.PEM) <10>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="example.com" <del> verify_certificate(certificate, server_name="example.com") <11>:<add> ) <16>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="example.com" <del> verify_certificate(certificate, server_name="example.com") <17>:<add> ) <20>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="example.com" <del> verify_certificate(certificate, server_name="example.com") <21>:<add> ) <28>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="example.com" <del> verify_certificate(certificate, server_name="example.com") <29>:<add> )
# module: tests.test_tls class VerifyCertificateTest(TestCase): def test_verify_dates(self): <0> certificate, _ = generate_ec_certificate( <1> common_name="example.com", curve=ec.SECP256R1 <2> ) <3> <4> #  too early <5> with patch("aioquic.tls.utcnow") as mock_utcnow: <6> mock_utcnow.return_value = ( <7> certificate.not_valid_before - datetime.timedelta(seconds=1) <8> ) <9> with self.assertRaises(tls.AlertCertificateExpired) as cm: <10> verify_certificate(certificate, server_name="example.com") <11> self.assertEqual(str(cm.exception), "Certificate is not valid yet") <12> <13> # valid <14> with patch("aioquic.tls.utcnow") as mock_utcnow: <15> mock_utcnow.return_value = certificate.not_valid_before <16> verify_certificate(certificate, server_name="example.com") <17> <18> with patch("aioquic.tls.utcnow") as mock_utcnow: <19> mock_utcnow.return_value = certificate.not_valid_after <20> verify_certificate(certificate, server_name="example.com") <21> <22> # too late <23> with patch("aioquic.tls.utcnow") as mock_utcnow: <24> mock_utcnow.return_value = certificate.not_valid_after + datetime.timedelta( <25> seconds=1 <26> ) <27> with self.assertRaises(tls.AlertCertificateExpired) as cm: <28> verify_certificate(certificate, server_name="example.com") <29> self.assertEqual(str(cm.exception), "Certificate is no longer valid") <30>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertBadCertificate(*args: object) load_pem_x509_certificates(data: bytes) -> List[x509.Certificate] verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None push_finished(buf: Buffer, finished: Finished) -> None at: aioquic.tls.Finished verify_data: bytes = b"" at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: io.FileIO read(self, size: int=..., /) -> bytes at: tests.test_tls.TlsTest.test_push_finished finished = Finished( verify_data=binascii.unhexlify( "f157923234ff9a4921aadb2e0ec7b1a30fce73fb9ec0c4276f9af268f408ec68" ) ) at: tests.utils load(name) SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: unittest.case TestCase(methodName: str=...) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========unchanged ref 1=========== assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] at: unittest.mock.NonCallableMock.__get_return_value self.return_value = ret ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): - client = self.create_client() server = self.create_server() server.certificate, server.certificate_private_key = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + + client = self.create_client(cafile=None) + client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, None) self.assertEqual(server.alpn_negotiated, None) ===========changed ref 1=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 2=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 3=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 4=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_cert_chain(self): + with client_and_server(server_certfile=SERVER_CERTFILE_WITH_CHAIN) as ( + client, + server, + ): + pass + ===========changed ref 6=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 7=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, cafile=SERVER_CACERTFILE): - def create_client(self): client = Context(is_client=True) + client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 8=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow ===========changed ref 9=========== # module: aioquic.tls class Context: def _client_handle_certificate(self, input_buf: Buffer) -> None: certificate = pull_certificate(input_buf) self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) + self._peer_certificate_chain = [ + x509.load_der_x509_certificate( + certificate.certificates[i][0], backend=default_backend() + ) + for i in range(1, len(certificate.certificates)) + ] + self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_CERTIFICATE_VERIFY)
tests.test_tls/VerifyCertificateTest.test_verify_subject
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<3>:<add> cadata = certificate.public_bytes(serialization.Encoding.PEM) <8>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="example.com" <del> verify_certificate(certificate, server_name="example.com") <9>:<add> ) <12>:<add> verify_certificate( <add> cadata=cadata, <add> certificate=certificate, <add> server_name="test.example.com", <add> ) <del> verify_certificate(certificate, server_name="test.example.com") <19>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="acme.com" <del> verify_certificate(certificate, server_name="acme.com") <20>:<add> )
# module: tests.test_tls class VerifyCertificateTest(TestCase): def test_verify_subject(self): <0> certificate, _ = generate_ec_certificate( <1> common_name="example.com", curve=ec.SECP256R1 <2> ) <3> <4> with patch("aioquic.tls.utcnow") as mock_utcnow: <5> mock_utcnow.return_value = certificate.not_valid_before <6> <7> # valid <8> verify_certificate(certificate, server_name="example.com") <9> <10> # invalid <11> with self.assertRaises(tls.AlertBadCertificate) as cm: <12> verify_certificate(certificate, server_name="test.example.com") <13> self.assertEqual( <14> str(cm.exception), <15> "hostname 'test.example.com' doesn't match 'example.com'", <16> ) <17> <18> with self.assertRaises(tls.AlertBadCertificate) as cm: <19> verify_certificate(certificate, server_name="acme.com") <20> self.assertEqual( <21> str(cm.exception), "hostname 'acme.com' doesn't match 'example.com'" <22> ) <23>
===========unchanged ref 0=========== at: aioquic.tls ffi = binding.ffi AlertBadCertificate(*args: object) verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None at: tests.utils generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[]) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] at: unittest.mock.NonCallableMock.__get_return_value self.return_value = ret ===========changed ref 0=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + def test_verify_certificate_chain(self): + with open(SERVER_CERTFILE, "rb") as fp: + certificate = load_pem_x509_certificates(fp.read())[0] + + with patch("aioquic.tls.utcnow") as mock_utcnow: + mock_utcnow.return_value = certificate.not_valid_before + + # fail + with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate(certificate=certificate, server_name="localhost") + self.assertEqual( + str(cm.exception), "unable to get local issuer certificate" + ) + + # ok + verify_certificate( + cafile=SERVER_CACERTFILE, + certificate=certificate, + server_name="localhost", + ) + ===========changed ref 1=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + def test_verify_certificate_chain_self_signed(self): + certificate, _ = generate_ec_certificate( + common_name="localhost", curve=ec.SECP256R1 + ) + + with patch("aioquic.tls.utcnow") as mock_utcnow: + mock_utcnow.return_value = certificate.not_valid_before + + # fail + with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate(certificate=certificate, server_name="localhost") + self.assertEqual(str(cm.exception), "self signed certificate") + + # ok + verify_certificate( + cadata=certificate.public_bytes(serialization.Encoding.PEM), + certificate=certificate, + server_name="localhost", + ) + ===========changed ref 2=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): def test_verify_dates(self): certificate, _ = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + cadata = certificate.public_bytes(serialization.Encoding.PEM) #  too early with patch("aioquic.tls.utcnow") as mock_utcnow: mock_utcnow.return_value = ( certificate.not_valid_before - datetime.timedelta(seconds=1) ) with self.assertRaises(tls.AlertCertificateExpired) as cm: + verify_certificate( + cadata=cadata, certificate=certificate, server_name="example.com" - verify_certificate(certificate, server_name="example.com") + ) self.assertEqual(str(cm.exception), "Certificate is not valid yet") # valid with patch("aioquic.tls.utcnow") as mock_utcnow: mock_utcnow.return_value = certificate.not_valid_before + verify_certificate( + cadata=cadata, certificate=certificate, server_name="example.com" - verify_certificate(certificate, server_name="example.com") + ) with patch("aioquic.tls.utcnow") as mock_utcnow: mock_utcnow.return_value = certificate.not_valid_after + verify_certificate( + cadata=cadata, certificate=certificate, server_name="example.com" - verify_certificate(certificate, server_name="example.com") + ) # too late with patch("aioquic.tls.utcnow") as mock_utcnow: mock_utcnow.return_value = certificate.not_valid_after + datetime.timedelta( seconds=1 ) with self.assertRaises(tls.AlertCertificateExpired) as cm: + verify_certificate( + cadata=cadata, certificate=</s> ===========changed ref 3=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): def test_verify_dates(self): # offset: 1 <s>ises(tls.AlertCertificateExpired) as cm: + verify_certificate( + cadata=cadata, certificate=certificate, server_name="example.com" - verify_certificate(certificate, server_name="example.com") + ) self.assertEqual(str(cm.exception), "Certificate is no longer valid") ===========changed ref 4=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 5=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 6=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 7=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 8=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): - client = self.create_client() server = self.create_server() server.certificate, server.certificate_private_key = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + + client = self.create_client(cafile=None) + client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, None) self.assertEqual(server.alpn_negotiated, None)
tests.test_tls/VerifyCertificateTest.test_verify_subject_with_subjaltname
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<5>:<add> cadata = certificate.public_bytes(serialization.Encoding.PEM) <10>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="example.com" <del> verify_certificate(certificate, server_name="example.com") <11>:<add> ) <add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="test.example.com" <del> verify_certificate(certificate, server_name="test.example.com") <12>:<add> ) <15>:<add> verify_certificate( <add> cadata=cadata, certificate=certificate, server_name="acme.com" <del> verify_certificate(certificate, server_name="acme.com") <16>:<add> )
# module: tests.test_tls class VerifyCertificateTest(TestCase): def test_verify_subject_with_subjaltname(self): <0> certificate, _ = generate_ec_certificate( <1> alternative_names=["*.example.com", "example.com"], <2> common_name="example.com", <3> curve=ec.SECP256R1, <4> ) <5> <6> with patch("aioquic.tls.utcnow") as mock_utcnow: <7> mock_utcnow.return_value = certificate.not_valid_before <8> <9> # valid <10> verify_certificate(certificate, server_name="example.com") <11> verify_certificate(certificate, server_name="test.example.com") <12> <13> # invalid <14> with self.assertRaises(tls.AlertBadCertificate) as cm: <15> verify_certificate(certificate, server_name="acme.com") <16> self.assertEqual( <17> str(cm.exception), <18> "hostname 'acme.com' doesn't match either of '*.example.com', 'example.com'", <19> ) <20>
===========unchanged ref 0=========== at: aioquic.tls AlertInternalError(*args: object) verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ at: tests.test_tls.VerifyCertificateTest.test_verify_certificate_chain_internal_error certificate, _ = generate_ec_certificate( common_name="localhost", curve=ec.SECP256R1 ) at: tests.utils generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[]) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========unchanged ref 1=========== at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] at: unittest.mock.NonCallableMock.__get_return_value self.return_value = ret ===========changed ref 0=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 1=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + @patch("aioquic.tls.lib.X509_STORE_new") + def test_verify_certificate_chain_internal_error(self, mock_store_new): + mock_store_new.return_value = tls.ffi.NULL + + certificate, _ = generate_ec_certificate( + common_name="localhost", curve=ec.SECP256R1 + ) + + with self.assertRaises(tls.AlertInternalError) as cm: + verify_certificate( + cadata=certificate.public_bytes(serialization.Encoding.PEM), + certificate=certificate, + server_name="localhost", + ) + self.assertEqual(str(cm.exception), "OpenSSL call failed") + ===========changed ref 2=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + def test_verify_certificate_chain_self_signed(self): + certificate, _ = generate_ec_certificate( + common_name="localhost", curve=ec.SECP256R1 + ) + + with patch("aioquic.tls.utcnow") as mock_utcnow: + mock_utcnow.return_value = certificate.not_valid_before + + # fail + with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate(certificate=certificate, server_name="localhost") + self.assertEqual(str(cm.exception), "self signed certificate") + + # ok + verify_certificate( + cadata=certificate.public_bytes(serialization.Encoding.PEM), + certificate=certificate, + server_name="localhost", + ) + ===========changed ref 3=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + def test_verify_certificate_chain(self): + with open(SERVER_CERTFILE, "rb") as fp: + certificate = load_pem_x509_certificates(fp.read())[0] + + with patch("aioquic.tls.utcnow") as mock_utcnow: + mock_utcnow.return_value = certificate.not_valid_before + + # fail + with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate(certificate=certificate, server_name="localhost") + self.assertEqual( + str(cm.exception), "unable to get local issuer certificate" + ) + + # ok + verify_certificate( + cafile=SERVER_CACERTFILE, + certificate=certificate, + server_name="localhost", + ) + ===========changed ref 4=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): def test_verify_subject(self): certificate, _ = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + cadata = certificate.public_bytes(serialization.Encoding.PEM) with patch("aioquic.tls.utcnow") as mock_utcnow: mock_utcnow.return_value = certificate.not_valid_before # valid + verify_certificate( + cadata=cadata, certificate=certificate, server_name="example.com" - verify_certificate(certificate, server_name="example.com") + ) # invalid with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate( + cadata=cadata, + certificate=certificate, + server_name="test.example.com", + ) - verify_certificate(certificate, server_name="test.example.com") self.assertEqual( str(cm.exception), "hostname 'test.example.com' doesn't match 'example.com'", ) with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate( + cadata=cadata, certificate=certificate, server_name="acme.com" - verify_certificate(certificate, server_name="acme.com") + ) self.assertEqual( str(cm.exception), "hostname 'acme.com' doesn't match 'example.com'" )
tests.test_asyncio/run_client
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<0>:<add> if configuration is None: <add> configuration = QuicConfiguration(is_client=True) <add> configuration.load_verify_locations(cadata=cadata, cafile=cafile) <add> async with connect(host, port, configuration=configuration, **kwargs) as client: <del> async with connect(host, port, **kwargs) as client:
# module: tests.test_asyncio + def run_client( + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): - def run_client(host, port=4433, request=b"ping", **kwargs): <0> async with connect(host, port, **kwargs) as client: <1> reader, writer = await client.create_stream() <2> assert writer.can_write_eof() is True <3> assert writer.get_extra_info("stream_id") == 0 <4> <5> writer.write(request) <6> writer.write_eof() <7> <8> return await reader.read() <9>
===========unchanged ref 0=========== at: tests.test_asyncio.SessionTicketStore.__init__ self.tickets = {} at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 1=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 2=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 3=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_cert_chain(self): + with client_and_server(server_certfile=SERVER_CERTFILE_WITH_CHAIN) as ( + client, + server, + ): + pass + ===========changed ref 5=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 6=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, cafile=SERVER_CACERTFILE): - def create_client(self): client = Context(is_client=True) + client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 7=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + @patch("aioquic.tls.lib.X509_STORE_new") + def test_verify_certificate_chain_internal_error(self, mock_store_new): + mock_store_new.return_value = tls.ffi.NULL + + certificate, _ = generate_ec_certificate( + common_name="localhost", curve=ec.SECP256R1 + ) + + with self.assertRaises(tls.AlertInternalError) as cm: + verify_certificate( + cadata=certificate.public_bytes(serialization.Encoding.PEM), + certificate=certificate, + server_name="localhost", + ) + self.assertEqual(str(cm.exception), "OpenSSL call failed") + ===========changed ref 8=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow ===========changed ref 9=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): - client = self.create_client() server = self.create_server() server.certificate, server.certificate_private_key = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + + client = self.create_client(cafile=None) + client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, None) self.assertEqual(server.alpn_negotiated, None) ===========changed ref 10=========== # module: aioquic.tls class Context: def _client_handle_certificate(self, input_buf: Buffer) -> None: certificate = pull_certificate(input_buf) self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) + self._peer_certificate_chain = [ + x509.load_der_x509_certificate( + certificate.certificates[i][0], backend=default_backend() + ) + for i in range(1, len(certificate.certificates)) + ] + self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_CERTIFICATE_VERIFY) ===========changed ref 11=========== # module: tests.utils + SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") + SERVER_CERTFILE_WITH_CHAIN = os.path.join( + os.path.dirname(__file__), "ssl_cert_with_chain.pem" + ) SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") if os.environ.get("AIOQUIC_DEBUG"): logging.basicConfig(level=logging.DEBUG) ===========changed ref 12=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + def test_verify_certificate_chain_self_signed(self): + certificate, _ = generate_ec_certificate( + common_name="localhost", curve=ec.SECP256R1 + ) + + with patch("aioquic.tls.utcnow") as mock_utcnow: + mock_utcnow.return_value = certificate.not_valid_before + + # fail + with self.assertRaises(tls.AlertBadCertificate) as cm: + verify_certificate(certificate=certificate, server_name="localhost") + self.assertEqual(str(cm.exception), "self signed certificate") + + # ok + verify_certificate( + cadata=certificate.public_bytes(serialization.Encoding.PEM), + certificate=certificate, + server_name="localhost", + ) +
tests.test_asyncio/HighLevelTest.test_connect_and_serve_ec_certificate
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<11>:<add> run_client( <del> run_client("127.0.0.1"), <12>:<add> "127.0.0.1", <add> cadata=certificate.public_bytes(serialization.Encoding.PEM), <add> cafile=None, <add> ),
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): <0> certificate, private_key = generate_ec_certificate(common_name="localhost") <1> <2> server, response = run( <3> asyncio.gather( <4> run_server( <5> configuration=QuicConfiguration( <6> certificate=certificate, <7> private_key=private_key, <8> is_client=False, <9> ) <10> ), <11> run_client("127.0.0.1"), <12> ) <13> ) <14> <15> self.assertEqual(response, b"gnip") <16> server.close() <17>
===========unchanged ref 0=========== at: aioquic.asyncio.server serve(host: str, port: int, *, configuration: QuicConfiguration, create_protocol: Callable=QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stateless_retry: bool=False, stream_handler: QuicStreamHandler=None) -> QuicServer at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None ===========unchanged ref 1=========== supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None ===========unchanged ref 2=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 3=========== at: tests.test_asyncio run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) handle_stream(reader, writer) at: tests.utils run(coro) SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case TestCase(methodName: str=...) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio + def run_client( + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): - def run_client(host, port=4433, request=b"ping", **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True assert writer.get_extra_info("stream_id") == 0 writer.write(request) writer.write_eof() return await reader.read()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_writelines
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<1>:<add> configuration = QuicConfiguration(is_client=True) <add> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> async with connect(host, port, configuration=configuration) as client: <del> async with connect(host, port) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): <0> async def run_client_writelines(host, port=4433): <1> async with connect(host, port) as client: <2> reader, writer = await client.create_stream() <3> assert writer.can_write_eof() is True <4> <5> writer.writelines([b"01234567", b"89012345"]) <6> writer.write_eof() <7> <8> return await reader.read() <9> <10> server, response = run( <11> asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) <12> ) <13> self.assertEqual(response, b"5432109876543210") <14> server.close() <15>
===========unchanged ref 0=========== at: tests.test_asyncio run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_ec_certificate certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio + def run_client( + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): - def run_client(host, port=4433, request=b"ping", **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True assert writer.get_extra_info("stream_id") == 0 writer.write(request) writer.write_eof() return await reader.read() ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + run_client( - run_client("127.0.0.1"), + "127.0.0.1", + cadata=certificate.public_bytes(serialization.Encoding.PEM), + cafile=None, + ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 2=========== # module: aioquic.tls + class AlertInternalError(Alert): + description = AlertDescription.internal_error + ===========changed ref 3=========== # module: aioquic.tls + def openssl_decode_string(charp) -> str: + return ffi.string(charp).decode("utf-8") if charp else "" + ===========changed ref 4=========== # module: aioquic.tls + def openssl_encode_path(s: Optional[str]) -> Any: + if s is not None: + return os.fsencode(s) + return ffi.NULL + ===========changed ref 5=========== # module: aioquic.tls + def openssl_assert(ok: bool) -> None: + if not ok: + lib.ERR_clear_error() + raise AlertInternalError("OpenSSL call failed") + ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_cert_chain(self): + with client_and_server(server_certfile=SERVER_CERTFILE_WITH_CHAIN) as ( + client, + server, + ): + pass + ===========changed ref 7=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 8=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, cafile=SERVER_CACERTFILE): - def create_client(self): client = Context(is_client=True) + client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 9=========== # module: tests.test_tls class VerifyCertificateTest(TestCase): + @patch("aioquic.tls.lib.X509_STORE_new") + def test_verify_certificate_chain_internal_error(self, mock_store_new): + mock_store_new.return_value = tls.ffi.NULL + + certificate, _ = generate_ec_certificate( + common_name="localhost", curve=ec.SECP256R1 + ) + + with self.assertRaises(tls.AlertInternalError) as cm: + verify_certificate( + cadata=certificate.public_bytes(serialization.Encoding.PEM), + certificate=certificate, + server_name="localhost", + ) + self.assertEqual(str(cm.exception), "OpenSSL call failed") + ===========changed ref 10=========== # module: aioquic.tls + binding = Binding() + binding.init_static_locks() + ffi = binding.ffi + lib = binding.lib + TLS_VERSION_1_2 = 0x0303 TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A T = TypeVar("T") # facilitate mocking for the test suite utcnow = datetime.datetime.utcnow ===========changed ref 11=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): - client = self.create_client() server = self.create_server() server.certificate, server.certificate_private_key = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + + client = self.create_client(cafile=None) + client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, None) self.assertEqual(server.alpn_negotiated, None)
tests.test_asyncio/HighLevelTest.test_change_connection_id
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<1>:<add> configuration = QuicConfiguration(is_client=True) <add> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> async with connect(host, port, configuration=configuration) as client: <del> async with connect(host, port) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): <0> async def run_client_key_update(host, port=4433): <1> async with connect(host, port) as client: <2> await client.ping() <3> client.change_connection_id() <4> await client.ping() <5> <6> server, _ = run( <7> asyncio.gather( <8> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <9> ) <10> ) <11> server.close() <12>
===========unchanged ref 0=========== at: aioquic.asyncio.server.QuicServer close() at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_stateless_retry_bad server = run(run_server(stateless_retry=True)) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio + def run_client( + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): - def run_client(host, port=4433, request=b"ping", **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True assert writer.get_extra_info("stream_id") == 0 writer.write(request) writer.write_eof() return await reader.read() ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + cadata: Optional[bytes] = None + cafile: Optional[str] = None + capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_without_client_configuration(self): + async def run_client_without_config(host, port=4433): + async with connect(host, port) as client: + await client.ping() + + server = run(run_server()) + with self.assertRaises(ConnectionError): + run(run_client_without_config("127.0.0.1")) + server.close() + ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + run_client( - run_client("127.0.0.1"), + "127.0.0.1", + cadata=certificate.public_bytes(serialization.Encoding.PEM), + cafile=None, + ), ) ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_key_update
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<1>:<add> configuration = QuicConfiguration(is_client=True) <add> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> async with connect(host, port, configuration=configuration) as client: <del> async with connect(host, port) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): <0> async def run_client_key_update(host, port=4433): <1> async with connect(host, port) as client: <2> await client.ping() <3> client.request_key_update() <4> await client.ping() <5> <6> server, _ = run( <7> asyncio.gather( <8> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <9> ) <10> ) <11> server.close() <12>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.logger QuicLogger() at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_version_negotiation server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) ===========unchanged ref 1=========== server, response = run( asyncio.gather( run_server(), run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + cadata: Optional[bytes] = None + cafile: Optional[str] = None + capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): async def run_client_key_update(host, port=4433): + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cafile=SERVER_CACERTFILE) + async with connect(host, port, configuration=configuration) as client: - async with connect(host, port) as client: await client.ping() client.change_connection_id() await client.ping() server, _ = run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_without_client_configuration(self): + async def run_client_without_config(host, port=4433): + async with connect(host, port) as client: + await client.ping() + + server = run(run_server()) + with self.assertRaises(ConnectionError): + run(run_client_without_config("127.0.0.1")) + server.close() + ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + run_client( - run_client("127.0.0.1"), + "127.0.0.1", + cadata=certificate.public_bytes(serialization.Encoding.PEM), + cafile=None, + ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433): + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cafile=SERVER_CACERTFILE) + async with connect(host, port, configuration=configuration) as client: - async with connect(host, port) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close()
tests.test_asyncio/HighLevelTest.test_ping
Modified
aiortc~aioquic
7e03018e4038f7bfa775320f2080395169bce395
[tls] verify peer certificate chain
<1>:<add> configuration = QuicConfiguration(is_client=True) <add> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <add> async with connect(host, port, configuration=configuration) as client: <del> async with connect(host, port) as client:
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_ping(self): <0> async def run_client_ping(host, port=4433): <1> async with connect(host, port) as client: <2> await client.ping() <3> await client.ping() <4> <5> server, _ = run( <6> asyncio.gather( <7> run_server(stateless_retry=False), run_client_ping("127.0.0.1") <8> ) <9> ) <10> server.close() <11>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None at: tests.test_asyncio run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") ===========changed ref 0=========== # module: tests.test_asyncio + def run_client( + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): - def run_client(host, port=4433, request=b"ping", **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: - async with connect(host, port, **kwargs) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True assert writer.get_extra_info("stream_id") == 0 writer.write(request) writer.write_eof() return await reader.read() ===========changed ref 1=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: + def load_verify_locations( + self, + cafile: Optional[str] = None, + capath: Optional[str] = None, + cadata: Optional[bytes] = None, + ) -> None: + """ + Load a set of "certification authority" (CA) certificates used to + validate other peers' certificates. + """ + self.cafile = cafile + self.capath = capath + self.cadata = cadata + ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ + cadata: Optional[bytes] = None + cafile: Optional[str] = None + capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): async def run_client_key_update(host, port=4433): + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cafile=SERVER_CACERTFILE) + async with connect(host, port, configuration=configuration) as client: - async with connect(host, port) as client: await client.ping() client.request_key_update() await client.ping() server, _ = run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): async def run_client_key_update(host, port=4433): + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cafile=SERVER_CACERTFILE) + async with connect(host, port, configuration=configuration) as client: - async with connect(host, port) as client: await client.ping() client.change_connection_id() await client.ping() server, _ = run( asyncio.gather( run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_without_client_configuration(self): + async def run_client_without_config(host, port=4433): + async with connect(host, port) as client: + await client.ping() + + server = run(run_server()) + with self.assertRaises(ConnectionError): + run(run_client_without_config("127.0.0.1")) + server.close() +
aioquic.h3.connection/H3Connection.__init__
Modified
aiortc~aioquic
0fb30257d54adce01e8899ece0d2b062b96a749e
[http3] raise decoder max table size to 4096 bytes
<0>:<add> self._max_table_capacity = 4096 <del> self._max_table_capacity = 0x100 <1>:<add> self._blocked_streams = 16 <del> self._blocked_streams = 0x10
# module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): <0> self._max_table_capacity = 0x100 <1> self._blocked_streams = 0x10 <2> <3> self._is_client = quic.configuration.is_client <4> self._is_done = False <5> self._quic = quic <6> self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger <7> self._decoder = pylsqpack.Decoder( <8> self._max_table_capacity, self._blocked_streams <9> ) <10> self._encoder = pylsqpack.Encoder() <11> self._stream: Dict[int, H3Stream] = {} <12> <13> self._max_push_id: Optional[int] = 8 if self._is_client else None <14> self._next_push_id: int = 0 <15> <16> self._local_control_stream_id: Optional[int] = None <17> self._local_decoder_stream_id: Optional[int] = None <18> self._local_encoder_stream_id: Optional[int] = None <19> <20> self._peer_control_stream_id: Optional[int] = None <21> self._peer_decoder_stream_id: Optional[int] = None <22> self._peer_encoder_stream_id: Optional[int] = None <23> <24> self._init_connection() <25>
===========unchanged ref 0=========== at: aioquic.h3.connection H3Stream(stream_id: int) at: aioquic.h3.connection.H3Connection _init_connection() -> None at: aioquic.h3.connection.H3Connection._handle_control_frame self._max_push_id = parse_max_push_id(frame_data) at: aioquic.h3.connection.H3Connection._init_connection self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL) self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.connection.H3Connection._receive_stream_data_uni self._peer_control_stream_id = stream.stream_id self._peer_decoder_stream_id = stream.stream_id self._peer_encoder_stream_id = stream.stream_id at: aioquic.h3.connection.H3Connection.handle_event self._is_done = True at: aioquic.h3.connection.H3Connection.send_push_promise self._next_push_id += 1 at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None ===========unchanged ref 1=========== certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection.__init__ self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.logger QuicLoggerTrace(*, is_client: bool, odcid: bytes) at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.asyncio.protocol/QuicConnectionProtocol._create_stream
Modified
aiortc~aioquic
05f6df53cb8db42468d7a469305f0f84f97a17b2
[asyncio] pass event loop to StreamWriter
<2>:<add> writer = asyncio.StreamWriter(adapter, None, reader, self._loop) <del> writer = asyncio.StreamWriter(adapter, None, reader, None)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): # private def _create_stream( self, stream_id: int ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: <0> adapter = QuicStreamAdapter(self, stream_id) <1> reader = asyncio.StreamReader() <2> writer = asyncio.StreamWriter(adapter, None, reader, None) <3> self._stream_readers[stream_id] = reader <4> return reader, writer <5>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol QuicStreamAdapter(protocol: QuicConnectionProtocol, stream_id: int) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._stream_readers: Dict[int, asyncio.StreamReader] = {} at: asyncio.streams StreamWriter(transport: transports.BaseTransport, protocol: protocols.BaseProtocol, reader: Optional[StreamReader], loop: events.AbstractEventLoop) StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
aioquic.quic.connection/QuicConnection._parse_transport_parameters
Modified
aiortc~aioquic
417eb53a2e565ff3d17cd9afbefe2e2765d150ff
[qlog] log QUIC transport parameters
<1>:<add> <add> # log event <add> if self._quic_logger is not None and not from_session_ticket: <add> self._quic_logger.log_event( <add> category="transport", <add> event="transport_parameters_update", <add> data={ <add> "owner": "remote", <add> "parameters": self._quic_logger.encode_transport_parameters( <add> quic_transport_parameters <add> ), <add> }, <add> )
# module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: <0> quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) <1> <2> # validate remote parameters <3> if ( <4> self._is_client <5> and not from_session_ticket <6> and ( <7> quic_transport_parameters.original_connection_id <8> != self._original_connection_id <9> ) <10> ): <11> raise QuicConnectionError( <12> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, <13> frame_type=QuicFrameType.CRYPTO, <14> reason_phrase="original_connection_id does not match", <15> ) <16> <17> # store remote parameters <18> if quic_transport_parameters.ack_delay_exponent is not None: <19> self._remote_ack_delay_exponent = self._remote_ack_delay_exponent <20> if quic_transport_parameters.active_connection_id_limit is not None: <21> self._remote_active_connection_id_limit = ( <22> quic_transport_parameters.active_connection_id_limit <23> ) <24> if quic_transport_parameters.idle_timeout is not None: <25> self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0 <26> if quic_transport_parameters.max_ack_delay is not None: <27> self._loss.max_ack_delay = quic_transport_parameters.max_ack_delay / 1000.0 <28> for param in [ <29> "max_data", <30> "max_stream_data_bidi_local", <31> "max_stream_data_bidi_remote", <32> "max_stream_data_uni", <33> "max_streams_bidi", <34> "max_streams_uni", <35> ]: <36> value = getattr(quic_transport_parameters, "initial</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: # offset: 1 if value is not None: setattr(self, "_remote_" + param, value) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.quic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._original_connection_id = original_connection_id self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._remote_ack_delay_exponent = 3 self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid at: aioquic.quic.logger.QuicLoggerTrace encode_transport_parameters(parameters: QuicTransportParameters) -> List[Dict] log_event(*, category: str, event: str, data: Dict) -> None at: aioquic.quic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.quic.packet.QuicTransportParameters original_connection_id: Optional[bytes] = None ===========unchanged ref 1=========== idle_timeout: Optional[int] = None stateless_reset_token: Optional[bytes] = None max_packet_size: Optional[int] = None initial_max_data: Optional[int] = None initial_max_stream_data_bidi_local: Optional[int] = None initial_max_stream_data_bidi_remote: Optional[int] = None initial_max_stream_data_uni: Optional[int] = None initial_max_streams_bidi: Optional[int] = None initial_max_streams_uni: Optional[int] = None ack_delay_exponent: Optional[int] = None max_ack_delay: Optional[int] = None disable_active_migration: Optional[bool] = False preferred_address: Optional[QuicPreferredAddress] = None active_connection_id_limit: Optional[int] = None ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_transport_parameters( + self, parameters: QuicTransportParameters + ) -> List[Dict]: + data = [] + for param_name, param_value in parameters.__dict__.items(): + if isinstance(param_value, bool): + data.append({"name": param_name, "value": param_value}) + elif isinstance(param_value, bytes): + data.append({"name": param_name, "value": hexdump(param_value)}) + elif isinstance(param_value, int): + data.append({"name": param_name, "value": str(param_value)}) + return data +
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
417eb53a2e565ff3d17cd9afbefe2e2765d150ff
[qlog] log QUIC transport parameters
<17>:<add> # log event <add> if self._quic_logger is not None: <add> self._quic_logger.log_event( <add> category="transport", <add> event="transport_parameters_update", <add> data={ <add> "owner": "local", <add> "parameters": self._quic_logger.encode_transport_parameters( <add> quic_transport_parameters <add> ), <add> }, <add> ) <add>
# module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: <0> quic_transport_parameters = QuicTransportParameters( <1> ack_delay_exponent=self._local_ack_delay_exponent, <2> active_connection_id_limit=self._local_active_connection_id_limit, <3> idle_timeout=int(self._configuration.idle_timeout * 1000), <4> initial_max_data=self._local_max_data, <5> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local, <6> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote, <7> initial_max_stream_data_uni=self._local_max_stream_data_uni, <8> initial_max_streams_bidi=self._local_max_streams_bidi, <9> initial_max_streams_uni=self._local_max_streams_uni, <10> max_ack_delay=25, <11> ) <12> if not self._is_client: <13> quic_transport_parameters.original_connection_id = ( <14> self._original_connection_id <15> ) <16> <17> buf = Buffer(capacity=512) <18> push_quic_transport_parameters(buf, quic_transport_parameters) <19> return buf.data <20>
===========unchanged ref 0=========== at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._local_ack_delay_exponent = 3 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.connection.QuicConnection._parse_transport_parameters quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) at: aioquic.quic.connection.QuicConnection._write_connection_limits self._local_max_data *= 2 ===========unchanged ref 1=========== at: aioquic.quic.packet QuicTransportParameters(original_connection_id: Optional[bytes]=None, idle_timeout: Optional[int]=None, stateless_reset_token: Optional[bytes]=None, max_packet_size: Optional[int]=None, initial_max_data: Optional[int]=None, initial_max_stream_data_bidi_local: Optional[int]=None, initial_max_stream_data_bidi_remote: Optional[int]=None, initial_max_stream_data_uni: Optional[int]=None, initial_max_streams_bidi: Optional[int]=None, initial_max_streams_uni: Optional[int]=None, ack_delay_exponent: Optional[int]=None, max_ack_delay: Optional[int]=None, disable_active_migration: Optional[bool]=False, preferred_address: Optional[QuicPreferredAddress]=None, active_connection_id_limit: Optional[int]=None) at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) + + # log event + if self._quic_logger is not None and not from_session_ticket: + self._quic_logger.log_event( + category="transport", + event="transport_parameters_update", + data={ + "owner": "remote", + "parameters": self._quic_logger.encode_transport_parameters( + quic_transport_parameters + ), + }, + ) # validate remote parameters if ( self._is_client and not from_session_ticket and ( quic_transport_parameters.original_connection_id != self._original_connection_id ) ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="original_connection_id does not match", ) # store remote parameters if quic_transport_parameters.ack_delay_exponent is not None: self._remote_ack_delay_exponent = self._remote_ack_delay_exponent if quic_transport_parameters.active_connection_id_limit is not None: self._remote_active_connection_id_limit = ( quic_transport_parameters.active_connection_id_limit ) if quic_transport_parameters.idle_timeout is not None: self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0 if quic_transport_parameters.max_ack_delay is not None: self._loss.max_ack_delay = quic_transport_parameters.max_ack_delay / 1000.0 for param in [ "max_data",</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: # offset: 1 <s> = quic_transport_parameters.max_ack_delay / 1000.0 for param in [ "max_data", "max_stream_data_bidi_local", "max_stream_data_bidi_remote", "max_stream_data_uni", "max_streams_bidi", "max_streams_uni", ]: value = getattr(quic_transport_parameters, "initial_" + param) if value is not None: setattr(self, "_remote_" + param, value) ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_transport_parameters( + self, parameters: QuicTransportParameters + ) -> List[Dict]: + data = [] + for param_name, param_value in parameters.__dict__.items(): + if isinstance(param_value, bool): + data.append({"name": param_name, "value": param_value}) + elif isinstance(param_value, bytes): + data.append({"name": param_name, "value": hexdump(param_value)}) + elif isinstance(param_value, int): + data.append({"name": param_name, "value": str(param_value)}) + return data +
examples.demo/logs
Modified
aiortc~aioquic
c610612b1bd6b087dc33c4a425ea6c1d26da5125
[examples] add link to qvis for QLOG visualization
<1>:<add> Browsable list of QLOG files. <del> Browsable list of logs. <7>:<add> file_url = "https://" + request.headers["host"] + "/logs/" + name <12>:<add> "file_url": file_url, <add> "name": name[:-5], <del> "name": name, <13>:<add> "qvis_url": QVIS_URL + "?" + urlencode({"file": file_url}),
# module: examples.demo @app.route("/logs/?") async def logs(request): <0> """ <1> Browsable list of logs. <2> """ <3> logs = [] <4> for name in os.listdir(LOGS_PATH): <5> if name.endswith(".qlog"): <6> s = os.stat(os.path.join(LOGS_PATH, name)) <7> logs.append( <8> { <9> "date": datetime.datetime.utcfromtimestamp(s.st_mtime).strftime( <10> "%Y-%m-%d %H:%M:%S" <11> ), <12> "name": name, <13> "size": s.st_size, <14> } <15> ) <16> return templates.TemplateResponse( <17> "logs.html", <18> { <19> "logs": sorted(logs, key=lambda x: x["date"], reverse=True), <20> "request": request, <21> }, <22> ) <23>
===========unchanged ref 0=========== at: datetime datetime() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' strftime(fmt: _Text) -> str __str__ = isoformat __radd__ = __add__ at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ utcfromtimestamp(t: float) -> _S __radd__ = __add__ at: examples.demo LOGS_PATH = os.path.join(ROOT, "htdocs", "logs") QVIS_URL = "https://quicvis.edm.uhasselt.be/" templates = Jinja2Templates(directory=os.path.join(ROOT, "templates")) app = Starlette() at: os listdir(path: bytes) -> List[bytes] listdir(path: int) -> List[str] listdir(path: Optional[str]=...) -> List[str] listdir(path: _PathLike[str]) -> List[str] stat(path: _FdOrAnyPath, *, dir_fd: Optional[int]=..., follow_symlinks: bool=...) -> stat_result at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes at: os.stat_result st_mode: int # protection bits, st_ino: int # inode number, st_dev: int # device, st_nlink: int # number of hard links, st_uid: int # user id of owner, st_gid: int # group id of owner, st_size: int # size of file, in bytes, st_atime: float # time of most recent access, st_mtime: float # time of most recent content modification, ===========unchanged ref 1=========== st_ctime: float # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) st_atime_ns: int # time of most recent access, in nanoseconds st_mtime_ns: int # time of most recent content modification in nanoseconds st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds st_reparse_tag: int st_file_attributes: int st_blocks: int # number of blocks allocated for file st_blksize: int # filesystem blocksize st_rdev: int # type of device if an inode device st_flags: int # user defined flags for file st_gen: int # file generation number st_birthtime: int # time of file creation st_rsize: int st_creator: int st_type: int at: urllib.parse urlencode(query: Union[Mapping[Any, Any], Mapping[Any, Sequence[Any]], Sequence[Tuple[Any, Any]], Sequence[Tuple[Any, Sequence[Any]]]], doseq: bool=..., safe: AnyStr=..., encoding: str=..., errors: str=..., quote_via: Callable[[str, AnyStr, str, str], str]=...) -> str ===========changed ref 0=========== # module: examples.demo ROOT = os.path.dirname(__file__) LOGS_PATH = os.path.join(ROOT, "htdocs", "logs") + QVIS_URL = "https://quicvis.edm.uhasselt.be/" templates = Jinja2Templates(directory=os.path.join(ROOT, "templates")) app = Starlette()
tests.test_h0/H0ConnectionTest.test_connect
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H0_ALPN}, <del> client_options={"alpn_protocols": ["hq-23"]}, <2>:<add> server_options={"alpn_protocols": H0_ALPN}, <del> server_options={"alpn_protocols": ["hq-23"]},
# module: tests.test_h0 class H0ConnectionTest(TestCase): def test_connect(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["hq-23"]}, <2> server_options={"alpn_protocols": ["hq-23"]}, <3> ) as (quic_client, quic_server): <4> h0_client = H0Connection(quic_client) <5> h0_server = H0Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h0_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> ) <18> h0_client.send_data(stream_id=stream_id, data=b"", end_stream=True) <19> <20> # receive request <21> events = h0_transfer(quic_client, h0_server) <22> self.assertEqual(len(events), 2) <23> <24> self.assertTrue(isinstance(events[0], HeadersReceived)) <25> self.assertEqual( <26> events[0].headers, [(b":method", b"GET"), (b":path", b"/")] <27> ) <28> self.assertEqual(events[0].stream_id, stream_id) <29> self.assertEqual(events[0].stream_ended, False) <30> <31> self.assertTrue(isinstance(events[1], DataReceived)) <32> self.assertEqual(events[1].data, b"") <33> self.assertEqual(events[1].stream_id, stream_id) <34> self.assertEqual(events[1].stream_ended, True) <35> <36> # send response <37> h0_server.send_</s>
===========below chunk 0=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_connect(self): # offset: 1 stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h0_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) # receive response events = h0_transfer(quic_server, h0_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual(events[0].headers, []) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========unchanged ref 0=========== at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h0 h0_transfer(quic_sender, h0_receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"]
tests.test_h0/H0ConnectionTest.test_headers_only
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H0_ALPN}, <del> client_options={"alpn_protocols": ["hq-23"]}, <2>:<add> server_options={"alpn_protocols": H0_ALPN}, <del> server_options={"alpn_protocols": ["hq-23"]},
# module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["hq-23"]}, <2> server_options={"alpn_protocols": ["hq-23"]}, <3> ) as (quic_client, quic_server): <4> h0_client = H0Connection(quic_client) <5> h0_server = H0Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h0_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"HEAD"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> end_stream=True, <18> ) <19> <20> # receive request <21> events = h0_transfer(quic_client, h0_server) <22> self.assertEqual(len(events), 2) <23> <24> self.assertTrue(isinstance(events[0], HeadersReceived)) <25> self.assertEqual( <26> events[0].headers, [(b":method", b"HEAD"), (b":path", b"/")] <27> ) <28> self.assertEqual(events[0].stream_id, stream_id) <29> self.assertEqual(events[0].stream_ended, False) <30> <31> self.assertTrue(isinstance(events[1], DataReceived)) <32> self.assertEqual(events[1].data, b"") <33> self.assertEqual(events[1].stream_id, stream_id) <34> self.assertEqual(events[1].stream_ended, True) <35> <36> # send response <37> h0_server.send_headers( <38> stream_id=stream_id, <39> headers=[ <40> </s>
===========below chunk 0=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): # offset: 1 (b"content-type", b"text/html; charset=utf-8"), ], end_stream=True, ) # receive response events = h0_transfer(quic_server, h0_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual(events[0].headers, []) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========unchanged ref 0=========== at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h0 h0_transfer(quic_sender, h0_receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_connect(self): with client_and_server( + client_options={"alpn_protocols": H0_ALPN}, - client_options={"alpn_protocols": ["hq-23"]}, + server_options={"alpn_protocols": H0_ALPN}, - server_options={"alpn_protocols": ["hq-23"]}, ) as (quic_client, quic_server): h0_client = H0Connection(quic_client) h0_server = H0Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h0_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], ) h0_client.send_data(stream_id=stream_id, data=b"", end_stream=True) # receive request events = h0_transfer(quic_client, h0_server) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual( events[0].headers, [(b":method", b"GET"), (b":path", b"/")] ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h0_server.</s> ===========changed ref 1=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_connect(self): # offset: 1 <s> self.assertEqual(events[1].stream_ended, True) # send response h0_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h0_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) # receive response events = h0_transfer(quic_server, h0_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual(events[0].headers, []) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========changed ref 2=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"]
examples.interop/test_http_0
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<3>:<add> configuration.alpn_protocols = H0_ALPN <del> configuration.alpn_protocols = ["hq-23", "hq-22"]
# module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): <0> if server.path is None: <1> return <2> <3> configuration.alpn_protocols = ["hq-23", "hq-22"] <4> async with connect( <5> server.host, <6> server.port, <7> configuration=configuration, <8> create_protocol=HttpClient, <9> ) as protocol: <10> protocol = cast(HttpClient, protocol) <11> <12> # perform HTTP request <13> events = await protocol.get( <14> "https://{}:{}{}".format(server.host, server.port, server.path) <15> ) <16> if events and isinstance(events[0], HeadersReceived): <17> server.result |= Result.D <18>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None ===========unchanged ref 1=========== certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: examples.interop Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0))) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) at: http3_client HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========changed ref 0=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 1=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 2=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): with client_and_server( + client_options={"alpn_protocols": H0_ALPN}, - client_options={"alpn_protocols": ["hq-23"]}, + server_options={"alpn_protocols": H0_ALPN}, - server_options={"alpn_protocols": ["hq-23"]}, ) as (quic_client, quic_server): h0_client = H0Connection(quic_client) h0_server = H0Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h0_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"HEAD"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], end_stream=True, ) # receive request events = h0_transfer(quic_client, h0_server) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual( events[0].headers, [(b":method", b"HEAD"), (b":path", b"/")] ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h0_server.send_headers( stream_id=stream_id, headers=[ </s> ===========changed ref 3=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): # offset: 1 <s> # send response h0_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], end_stream=True, ) # receive response events = h0_transfer(quic_server, h0_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual(events[0].headers, []) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True)
examples.interop/test_http_3
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<3>:<add> configuration.alpn_protocols = H3_ALPN <del> configuration.alpn_protocols = ["h3-23", "h3-22"]
# module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): <0> if server.path is None: <1> return <2> <3> configuration.alpn_protocols = ["h3-23", "h3-22"] <4> async with connect( <5> server.host, <6> server.port, <7> configuration=configuration, <8> create_protocol=HttpClient, <9> ) as protocol: <10> protocol = cast(HttpClient, protocol) <11> <12> # perform HTTP request <13> events = await protocol.get( <14> "https://{}:{}{}".format(server.host, server.port, server.path) <15> ) <16> if events and isinstance(events[0], HeadersReceived): <17> server.result |= Result.D <18> server.result |= Result.three <19>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] at: aioquic.h3.events HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None at: examples.interop Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0))) at: examples.interop.Server host: str ===========unchanged ref 1=========== port: int = 4433 path: str = "/" at: http3_client HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========changed ref 0=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 1=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 2=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 3=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): with client_and_server( + client_options={"alpn_protocols": H0_ALPN}, - client_options={"alpn_protocols": ["hq-23"]}, + server_options={"alpn_protocols": H0_ALPN}, - server_options={"alpn_protocols": ["hq-23"]}, ) as (quic_client, quic_server): h0_client = H0Connection(quic_client) h0_server = H0Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h0_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"HEAD"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], end_stream=True, ) # receive request events = h0_transfer(quic_client, h0_server) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual( events[0].headers, [(b":method", b"HEAD"), (b":path", b"/")] ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h0_server.send_headers( stream_id=stream_id, headers=[ </s> ===========changed ref 4=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): # offset: 1 <s> # send response h0_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], end_stream=True, ) # receive response events = h0_transfer(quic_server, h0_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual(events[0].headers, []) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True)
examples.interop/test_throughput
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<15>:<add> configuration.alpn_protocols = H3_ALPN <del> configuration.alpn_protocols = ["h3-23", "h3-22"] <17>:<add> configuration.alpn_protocols = H0_ALPN <del> configuration.alpn_protocols = ["hq-23", "hq-22"]
# module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): <0> failures = 0 <1> <2> for size in [5000000, 10000000]: <3> print("Testing %d bytes download" % size) <4> path = "/%d" % size <5> <6> # perform HTTP request over TCP <7> start = time.time() <8> response = requests.get("https://" + server.host + path, verify=False) <9> tcp_octets = len(response.content) <10> tcp_elapsed = time.time() - start <11> assert tcp_octets == size, "HTTP/TCP response size mismatch" <12> <13> # perform HTTP request over QUIC <14> if server.http3: <15> configuration.alpn_protocols = ["h3-23", "h3-22"] <16> else: <17> configuration.alpn_protocols = ["hq-23", "hq-22"] <18> start = time.time() <19> async with connect( <20> server.host, <21> server.port, <22> configuration=configuration, <23> create_protocol=HttpClient, <24> ) as protocol: <25> protocol = cast(HttpClient, protocol) <26> <27> http_events = await protocol.get( <28> "https://{}:{}{}".format(server.host, server.port, path) <29> ) <30> quic_elapsed = time.time() - start <31> quic_octets = 0 <32> for http_event in http_events: <33> if isinstance(http_event, DataReceived): <34> quic_octets += len(http_event.data) <35> assert quic_octets == size, "HTTP/QUIC response size mismatch" <36> <37> print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) <38> print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) <39> <40> if quic_elapsed > 1.1 * tcp_elapsed: <41> failures += 1 <42> print(" => FAIL") <43> else: <44> print(" => PASS")</s>
===========below chunk 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 if failures == 0: server.result |= Result.T ===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None ===========unchanged ref 1=========== at: examples.interop Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0))) at: examples.interop.Server host: str port: int = 4433 http3: bool = True at: http3_client HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] at: requests.api get(url: Union[Text, bytes], params: Optional[ Union[ SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], Tuple[_ParamsMappingKeyType, _ParamsMappingValueType], Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], Union[Text, bytes], ] ]=..., **kwargs) -> Response at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] at: time time() -> float at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========changed ref 0=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three ===========changed ref 1=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 2=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 3=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 4=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): def test_headers_only(self): with client_and_server( + client_options={"alpn_protocols": H0_ALPN}, - client_options={"alpn_protocols": ["hq-23"]}, + server_options={"alpn_protocols": H0_ALPN}, - server_options={"alpn_protocols": ["hq-23"]}, ) as (quic_client, quic_server): h0_client = H0Connection(quic_client) h0_server = H0Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h0_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"HEAD"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], end_stream=True, ) # receive request events = h0_transfer(quic_client, h0_server) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], HeadersReceived)) self.assertEqual( events[0].headers, [(b":method", b"HEAD"), (b":path", b"/")] ) self.assertEqual(events[0].stream_id, stream_id) self.assertEqual(events[0].stream_ended, False) self.assertTrue(isinstance(events[1], DataReceived)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h0_server.send_headers( stream_id=stream_id, headers=[ </s>
examples.interop/run
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<4>:<add> alpn_protocols=H3_ALPN + H0_ALPN, <del> alpn_protocols=["h3-23", "h3-22", "hq-23", "hq-22"],
# module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: <0> for server in servers: <1> for test_name, test_func in tests: <2> print("\n=== %s %s ===\n" % (server.name, test_name)) <3> configuration = QuicConfiguration( <4> alpn_protocols=["h3-23", "h3-22", "hq-23", "hq-22"], <5> is_client=True, <6> quic_logger=QuicLogger(), <7> secrets_log_file=secrets_log_file, <8> ) <9> if test_name == "test_throughput": <10> timeout = 60 <11> else: <12> timeout = 5 <13> try: <14> await asyncio.wait_for( <15> test_func(server, configuration), timeout=timeout <16> ) <17> except Exception as exc: <18> print(exc) <19> <20> if quic_log: <21> with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: <22> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) <23> <24> print("") <25> print_result(server) <26> <27> # print summary <28> if len(servers) > 1: <29> print("SUMMARY") <30> for server in servers: <31> print_result(server) <32>
===========unchanged ref 0=========== at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration quic_logger: Optional[QuicLogger] = None at: aioquic.quic.logger QuicLogger() at: aioquic.quic.logger.QuicLogger to_dict() -> Dict[str, Any] at: asyncio.tasks wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: examples.interop print_result(server: Server) -> None at: examples.interop.Server name: str ===========unchanged ref 1=========== at: json dump(obj: Any, fp: IO[str], *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> None ===========changed ref 0=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three ===========changed ref 1=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 2=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): failures = 0 for size in [5000000, 10000000]: print("Testing %d bytes download" % size) path = "/%d" % size # perform HTTP request over TCP start = time.time() response = requests.get("https://" + server.host + path, verify=False) tcp_octets = len(response.content) tcp_elapsed = time.time() - start assert tcp_octets == size, "HTTP/TCP response size mismatch" # perform HTTP request over QUIC if server.http3: + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] else: + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] start = time.time() async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) http_events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, path) ) quic_elapsed = time.time() - start quic_octets = 0 for http_event in http_events: if isinstance(http_event, DataReceived): quic_octets += len(http_event.data) assert quic_octets == size, "HTTP/QUIC response size mismatch" print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) if quic_elapsed > 1.1 * tcp_elapsed: failures += 1 print(" => FAIL") else: print(" => PASS") if failures == 0: server.result</s> ===========changed ref 3=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 <s> print(" => FAIL") else: print(" => PASS") if failures == 0: server.result |= Result.T ===========changed ref 4=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 5=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] +
tests.test_h3/H3ConnectionTest.test_request
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H3_ALPN}, <del> client_options={"alpn_protocols": ["h3-23"]}, <2>:<add> server_options={"alpn_protocols": H3_ALPN}, <del> server_options={"alpn_protocols": ["h3-23"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-23"]}, <2> server_options={"alpn_protocols": ["h3-23"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # make first request <8> self._make_request(h3_client, h3_server) <9> <10> # make second request <11> self._make_request(h3_client, h3_server) <12> <13> # make third request -> dynamic table <14> self._make_request(h3_client, h3_server) <15>
===========unchanged ref 0=========== at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3.H3ConnectionTest maxDiff = None _make_request(h3_client, h3_server) ===========changed ref 0=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 1=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 2=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 3=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three ===========changed ref 4=========== # module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: for server in servers: for test_name, test_func in tests: print("\n=== %s %s ===\n" % (server.name, test_name)) configuration = QuicConfiguration( + alpn_protocols=H3_ALPN + H0_ALPN, - alpn_protocols=["h3-23", "h3-22", "hq-23", "hq-22"], is_client=True, quic_logger=QuicLogger(), secrets_log_file=secrets_log_file, ) if test_name == "test_throughput": timeout = 60 else: timeout = 5 try: await asyncio.wait_for( test_func(server, configuration), timeout=timeout ) except Exception as exc: print(exc) if quic_log: with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) print("") print_result(server) # print summary if len(servers) > 1: print("SUMMARY") for server in servers: print_result(server) ===========changed ref 5=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): failures = 0 for size in [5000000, 10000000]: print("Testing %d bytes download" % size) path = "/%d" % size # perform HTTP request over TCP start = time.time() response = requests.get("https://" + server.host + path, verify=False) tcp_octets = len(response.content) tcp_elapsed = time.time() - start assert tcp_octets == size, "HTTP/TCP response size mismatch" # perform HTTP request over QUIC if server.http3: + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] else: + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] start = time.time() async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) http_events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, path) ) quic_elapsed = time.time() - start quic_octets = 0 for http_event in http_events: if isinstance(http_event, DataReceived): quic_octets += len(http_event.data) assert quic_octets == size, "HTTP/QUIC response size mismatch" print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) if quic_elapsed > 1.1 * tcp_elapsed: failures += 1 print(" => FAIL") else: print(" => PASS") if failures == 0: server.result</s> ===========changed ref 6=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 <s> print(" => FAIL") else: print(" => PASS") if failures == 0: server.result |= Result.T
tests.test_h3/H3ConnectionTest.test_request_headers_only
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H3_ALPN}, <del> client_options={"alpn_protocols": ["h3-23"]}, <2>:<add> server_options={"alpn_protocols": H3_ALPN}, <del> server_options={"alpn_protocols": ["h3-23"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_headers_only(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-23"]}, <2> server_options={"alpn_protocols": ["h3-23"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"HEAD"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> (b"x-foo", b"client"), <17> ], <18> end_stream=True, <19> ) <20> <21> # receive request <22> events = h3_transfer(quic_client, h3_server) <23> self.assertEqual( <24> events, <25> [ <26> HeadersReceived( <27> headers=[ <28> (b":method", b"HEAD"), <29> (b":scheme", b"https"), <30> (b":authority", b"localhost"), <31> (b":path", b"/"), <32> (b"x-foo", b"client"), <33> ], <34> stream_id=stream_id, <35> stream_ended=True, <36> ) <37> ], <38> ) <39> <40> # send response <41> h3_server.send_headers( <42> stream_id=stream_id, <43> headers=[ <44> (b":status", b"200"), <45> (b"content-type", b"text/html; charset=utf-8"), <46> (b</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_headers_only(self): # offset: 1 ], end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual( events, [ HeadersReceived( headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), (b"x-foo", b"server"), ], stream_id=stream_id, stream_ended=True, ) ], ) ===========unchanged ref 0=========== at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.h3.events.HeadersReceived headers: Headers stream_id: int stream_ended: bool push_id: Optional[int] = None at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # make first request self._make_request(h3_client, h3_server) # make second request self._make_request(h3_client, h3_server) # make third request -> dynamic table self._make_request(h3_client, h3_server) ===========changed ref 1=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 2=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 3=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 4=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three ===========changed ref 5=========== # module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: for server in servers: for test_name, test_func in tests: print("\n=== %s %s ===\n" % (server.name, test_name)) configuration = QuicConfiguration( + alpn_protocols=H3_ALPN + H0_ALPN, - alpn_protocols=["h3-23", "h3-22", "hq-23", "hq-22"], is_client=True, quic_logger=QuicLogger(), secrets_log_file=secrets_log_file, ) if test_name == "test_throughput": timeout = 60 else: timeout = 5 try: await asyncio.wait_for( test_func(server, configuration), timeout=timeout ) except Exception as exc: print(exc) if quic_log: with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) print("") print_result(server) # print summary if len(servers) > 1: print("SUMMARY") for server in servers: print_result(server)
tests.test_h3/H3ConnectionTest.test_request_with_server_push_max_push_id
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H3_ALPN}, <del> client_options={"alpn_protocols": ["h3-23"]}, <2>:<add> server_options={"alpn_protocols": H3_ALPN}, <del> server_options={"alpn_protocols": ["h3-23"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_server_push_max_push_id(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-23"]}, <2> server_options={"alpn_protocols": ["h3-23"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> end_stream=True, <18> ) <19> <20> # receive request <21> events = h3_transfer(quic_client, h3_server) <22> self.assertEqual( <23> events, <24> [ <25> HeadersReceived( <26> headers=[ <27> (b":method", b"GET"), <28> (b":scheme", b"https"), <29> (b":authority", b"localhost"), <30> (b":path", b"/"), <31> ], <32> stream_id=stream_id, <33> stream_ended=True, <34> ) <35> ], <36> ) <37> <38> # send push promises <39> for i in range(0, 8): <40> h3_server.send_push_promise( <41> stream_id=stream_id, <42> headers=[ <43> (b":method", b"GET"), <44> (b":scheme", b"https"), <45> (b":authority", b"localhost"), <46> (b":path", "/</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_server_push_max_push_id(self): # offset: 1 ], ) # send one too many with self.assertRaises(NoAvailablePushIDError): h3_server.send_push_promise( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/8.css"), ], ) ===========unchanged ref 0=========== at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_push_promise(stream_id: int, headers: Headers) -> int send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.h3.exceptions NoAvailablePushIDError(*args: object) at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # make first request self._make_request(h3_client, h3_server) # make second request self._make_request(h3_client, h3_server) # make third request -> dynamic table self._make_request(h3_client, h3_server) ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_headers_only(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"HEAD"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), (b"x-foo", b"client"), ], end_stream=True, ) # receive request events = h3_transfer(quic_client, h3_server) self.assertEqual( events, [ HeadersReceived( headers=[ (b":method", b"HEAD"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), (b"x-foo", b"client"), ], stream_id=stream_id, stream_ended=True, ) ], ) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), (b"x-foo", b"</s> ===========changed ref 2=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_headers_only(self): # offset: 1 <s>b"content-type", b"text/html; charset=utf-8"), (b"x-foo", b"server"), ], end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual( events, [ HeadersReceived( headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), (b"x-foo", b"server"), ], stream_id=stream_id, stream_ended=True, ) ], ) ===========changed ref 3=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 4=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 5=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 6=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three
tests.test_h3/H3ConnectionTest.test_uni_stream_grease
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H3_ALPN}, <del> client_options={"alpn_protocols": ["h3-23"]}, <2>:<add> server_options={"alpn_protocols": H3_ALPN}, <del> server_options={"alpn_protocols": ["h3-23"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_grease(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-23"]}, <2> server_options={"alpn_protocols": ["h3-23"]}, <3> ) as (quic_client, quic_server): <4> h3_server = H3Connection(quic_server) <5> <6> quic_client.send_stream_data( <7> 14, b"\xff\xff\xff\xff\xff\xff\xff\xfeGREASE is the word" <8> ) <9> self.assertEqual(h3_transfer(quic_client, h3_server), []) <10>
===========unchanged ref 0=========== at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_server_push_max_push_id(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], end_stream=True, ) # receive request events = h3_transfer(quic_client, h3_server) self.assertEqual( events, [ HeadersReceived( headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], stream_id=stream_id, stream_ended=True, ) ], ) # send push promises for i in range(0, 8): h3_server.send_push_promise( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", "/{}.css".format(i).</s> ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_server_push_max_push_id(self): # offset: 1 <s>https"), (b":authority", b"localhost"), (b":path", "/{}.css".format(i).encode("ascii")), ], ) # send one too many with self.assertRaises(NoAvailablePushIDError): h3_server.send_push_promise( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/8.css"), ], ) ===========changed ref 2=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # make first request self._make_request(h3_client, h3_server) # make second request self._make_request(h3_client, h3_server) # make third request -> dynamic table self._make_request(h3_client, h3_server) ===========changed ref 3=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 4=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23", "h3-22"] + ===========changed ref 5=========== # module: examples.interop def test_http_0(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H0_ALPN - configuration.alpn_protocols = ["hq-23", "hq-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D ===========changed ref 6=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): if server.path is None: return + configuration.alpn_protocols = H3_ALPN - configuration.alpn_protocols = ["h3-23", "h3-22"] async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three
tests.test_h3/H3ConnectionTest.test_request_with_trailers
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H3_ALPN}, <del> client_options={"alpn_protocols": ["h3-23"]}, <2>:<add> server_options={"alpn_protocols": H3_ALPN}, <del> server_options={"alpn_protocols": ["h3-23"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_trailers(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-23"]}, <2> server_options={"alpn_protocols": ["h3-23"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request with trailers <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> end_stream=False, <18> ) <19> h3_client.send_headers( <20> stream_id=stream_id, <21> headers=[(b"x-some-trailer", b"foo")], <22> end_stream=True, <23> ) <24> <25> # receive request <26> events = h3_transfer(quic_client, h3_server) <27> self.assertEqual( <28> events, <29> [ <30> HeadersReceived( <31> headers=[ <32> (b":method", b"GET"), <33> (b":scheme", b"https"), <34> (b":authority", b"localhost"), <35> (b":path", b"/"), <36> ], <37> stream_id=stream_id, <38> stream_ended=False, <39> ), <40> HeadersReceived( <41> headers=[(b"x-some-trailer", b"foo")], <42> stream_id=stream_id, <43> stream_ended=True, <44> ), <45> ]</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_trailers(self): # offset: 1 ) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], end_stream=False, ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=False, ) h3_server.send_headers( stream_id=stream_id, headers=[(b"x-some-trailer", b"bar")], end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual( events, [ HeadersReceived( headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], stream_id=stream_id, stream_ended=False, ), DataReceived( data=b"<html><body>hello</body></html>", stream_id=stream_id, stream_ended=False, ), HeadersReceived( headers=[(b"x-some-trailer", b"bar")], stream_id=stream_id, stream_ended=True, ), ], ) ===========unchanged ref 0=========== at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool push_id: Optional[int] = None at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_grease(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_server = H3Connection(quic_server) quic_client.send_stream_data( 14, b"\xff\xff\xff\xff\xff\xff\xff\xfeGREASE is the word" ) self.assertEqual(h3_transfer(quic_client, h3_server), []) ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_server_push_max_push_id(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], end_stream=True, ) # receive request events = h3_transfer(quic_client, h3_server) self.assertEqual( events, [ HeadersReceived( headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], stream_id=stream_id, stream_ended=True, ) ], ) # send push promises for i in range(0, 8): h3_server.send_push_promise( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", "/{}.css".format(i).</s> ===========changed ref 2=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_server_push_max_push_id(self): # offset: 1 <s>https"), (b":authority", b"localhost"), (b":path", "/{}.css".format(i).encode("ascii")), ], ) # send one too many with self.assertRaises(NoAvailablePushIDError): h3_server.send_push_promise( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/8.css"), ], ) ===========changed ref 3=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # make first request self._make_request(h3_client, h3_server) # make second request self._make_request(h3_client, h3_server) # make third request -> dynamic table self._make_request(h3_client, h3_server)
tests.test_h3/H3ConnectionTest.test_uni_stream_type
Modified
aiortc~aioquic
755560878bf95fd828557b13ecac8b56af606b59
[http] add H0_ALPN and H3_ALPN definitions
<1>:<add> client_options={"alpn_protocols": H3_ALPN}, <del> client_options={"alpn_protocols": ["h3-23"]}, <2>:<add> server_options={"alpn_protocols": H3_ALPN}, <del> server_options={"alpn_protocols": ["h3-23"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-23"]}, <2> server_options={"alpn_protocols": ["h3-23"]}, <3> ) as (quic_client, quic_server): <4> h3_server = H3Connection(quic_server) <5> <6> # unknown stream type 9 <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <8> self.assertEqual(stream_id, 2) <9> quic_client.send_stream_data(stream_id, b"\x09") <10> self.assertEqual(h3_transfer(quic_client, h3_server), []) <11> self.assertEqual(list(h3_server._stream.keys()), [2]) <12> self.assertEqual(h3_server._stream[2].buffer, b"") <13> self.assertEqual(h3_server._stream[2].stream_type, 9) <14> <15> # unknown stream type 64, one byte at a time <16> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <17> self.assertEqual(stream_id, 6) <18> <19> quic_client.send_stream_data(stream_id, b"\x40") <20> self.assertEqual(h3_transfer(quic_client, h3_server), []) <21> self.assertEqual(list(h3_server._stream.keys()), [2, 6]) <22> self.assertEqual(h3_server._stream[2].buffer, b"") <23> self.assertEqual(h3_server._stream[2].stream_type, 9) <24> self.assertEqual(h3_server._stream[6].buffer, b"\x40") <25> self.assertEqual(h3_server._stream[6].stream_type,</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): # offset: 1 quic_client.send_stream_data(stream_id, b"\x40") self.assertEqual(h3_transfer(quic_client, h3_server), []) self.assertEqual(list(h3_server._stream.keys()), [2, 6]) self.assertEqual(h3_server._stream[2].buffer, b"") self.assertEqual(h3_server._stream[2].stream_type, 9) self.assertEqual(h3_server._stream[6].buffer, b"") self.assertEqual(h3_server._stream[6].stream_type, 64) ===========unchanged ref 0=========== at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection.__init__ self._stream: Dict[int, H3Stream] = {} at: aioquic.h3.connection.H3Stream.__init__ self.buffer = b"" self.stream_type: Optional[int] = None at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_grease(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_server = H3Connection(quic_server) quic_client.send_stream_data( 14, b"\xff\xff\xff\xff\xff\xff\xff\xfeGREASE is the word" ) self.assertEqual(h3_transfer(quic_client, h3_server), []) ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_trailers(self): with client_and_server( + client_options={"alpn_protocols": H3_ALPN}, - client_options={"alpn_protocols": ["h3-23"]}, + server_options={"alpn_protocols": H3_ALPN}, - server_options={"alpn_protocols": ["h3-23"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request with trailers stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], end_stream=False, ) h3_client.send_headers( stream_id=stream_id, headers=[(b"x-some-trailer", b"foo")], end_stream=True, ) # receive request events = h3_transfer(quic_client, h3_server) self.assertEqual( events, [ HeadersReceived( headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], stream_id=stream_id, stream_ended=False, ), HeadersReceived( headers=[(b"x-some-trailer", b"foo")], stream_id=stream_id, stream_ended=True, ), ], ) </s> ===========changed ref 2=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_request_with_trailers(self): # offset: 1 <s> stream_id=stream_id, stream_ended=True, ), ], ) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], end_stream=False, ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=False, ) h3_server.send_headers( stream_id=stream_id, headers=[(b"x-some-trailer", b"bar")], end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual( events, [ HeadersReceived( headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], stream_id=stream_id, stream_ended=False, ), DataReceived( data=b"<html><body>hello</body></html>", stream_id=stream_id, stream_ended=False, ), HeadersReceived( headers=[(b"x-some-trailer", b"bar")], stream_id=stream_id, stream_ended=True, ), ], )
aioquic.h3.connection/H3Connection.__init__
Modified
aiortc~aioquic
8db11b954ca3992373a98675e322d8cc9511e1f7
[interop] add a test for QPACK dynamic tables
<10>:<add> self._decoder_bytes_received = 0 <add> self._decoder_bytes_sent = 0 <11>:<add> self._encoder_bytes_received = 0 <add> self._encoder_bytes_sent = 0
# module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): <0> self._max_table_capacity = 4096 <1> self._blocked_streams = 16 <2> <3> self._is_client = quic.configuration.is_client <4> self._is_done = False <5> self._quic = quic <6> self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger <7> self._decoder = pylsqpack.Decoder( <8> self._max_table_capacity, self._blocked_streams <9> ) <10> self._encoder = pylsqpack.Encoder() <11> self._stream: Dict[int, H3Stream] = {} <12> <13> self._max_push_id: Optional[int] = 8 if self._is_client else None <14> self._next_push_id: int = 0 <15> <16> self._local_control_stream_id: Optional[int] = None <17> self._local_decoder_stream_id: Optional[int] = None <18> self._local_encoder_stream_id: Optional[int] = None <19> <20> self._peer_control_stream_id: Optional[int] = None <21> self._peer_decoder_stream_id: Optional[int] = None <22> self._peer_encoder_stream_id: Optional[int] = None <23> <24> self._init_connection() <25>
===========unchanged ref 0=========== at: aioquic.h3.connection H3Stream(stream_id: int) at: aioquic.h3.connection.H3Connection._decode_headers self._decoder_bytes_sent += len(decoder) at: aioquic.h3.connection.H3Connection._encode_headers self._encoder_bytes_sent += len(encoder) at: aioquic.h3.connection.H3Connection._handle_control_frame self._max_push_id = parse_max_push_id(frame_data) at: aioquic.h3.connection.H3Connection._init_connection self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL) self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.connection.H3Connection._receive_stream_data_uni self._peer_control_stream_id = stream.stream_id self._decoder_bytes_received += len(data) self._encoder_bytes_received += len(data) at: aioquic.h3.connection.H3Connection.handle_event self._is_done = True at: aioquic.h3.connection.H3Connection.send_push_promise self._next_push_id += 1 at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None ===========unchanged ref 1=========== cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection.__init__ self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.logger QuicLoggerTrace(*, is_client: bool, odcid: bytes) at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.h3.connection/H3Connection._decode_headers
Modified
aiortc~aioquic
8db11b954ca3992373a98675e322d8cc9511e1f7
[interop] add a test for QPACK dynamic tables
<10>:<add> self._decoder_bytes_sent += len(decoder)
# module: aioquic.h3.connection class H3Connection: def _decode_headers(self, stream_id: int, frame_data: Optional[bytes]) -> Headers: <0> """ <1> Decode a HEADERS block and send decoder updates on the decoder stream. <2> <3> This is called with frame_data=None when a stream becomes unblocked. <4> """ <5> try: <6> if frame_data is None: <7> decoder, headers = self._decoder.resume_header(stream_id) <8> else: <9> decoder, headers = self._decoder.feed_header(stream_id, frame_data) <10> self._quic.send_stream_data(self._local_decoder_stream_id, decoder) <11> except pylsqpack.DecompressionFailed as exc: <12> raise QpackDecompressionFailed() from exc <13> <14> return headers <15>
===========unchanged ref 0=========== at: aioquic.buffer encode_uint_var(value: int) -> bytes at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic self._decoder = pylsqpack.Decoder( self._max_table_capacity, self._blocked_streams ) self._decoder_bytes_sent = 0 at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] at: aioquic.quic.connection.QuicConnection get_next_available_stream_id(is_unidirectional=False) -> int send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 4096 self._blocked_streams = 16 self._is_client = quic.configuration.is_client self._is_done = False self._quic = quic self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger self._decoder = pylsqpack.Decoder( self._max_table_capacity, self._blocked_streams ) + self._decoder_bytes_received = 0 + self._decoder_bytes_sent = 0 self._encoder = pylsqpack.Encoder() + self._encoder_bytes_received = 0 + self._encoder_bytes_sent = 0 self._stream: Dict[int, H3Stream] = {} self._max_push_id: Optional[int] = 8 if self._is_client else None self._next_push_id: int = 0 self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None self._init_connection()
aioquic.h3.connection/H3Connection._encode_headers
Modified
aiortc~aioquic
8db11b954ca3992373a98675e322d8cc9511e1f7
[interop] add a test for QPACK dynamic tables
<4>:<add> self._encoder_bytes_sent += len(encoder)
# module: aioquic.h3.connection class H3Connection: def _encode_headers(self, stream_id: int, headers: Headers) -> bytes: <0> """ <1> Encode a HEADERS block and send encoder updates on the encoder stream. <2> """ <3> encoder, frame_data = self._encoder.encode(stream_id, 0, headers) <4> self._quic.send_stream_data(self._local_encoder_stream_id, encoder) <5> return frame_data <6>
===========unchanged ref 0=========== at: aioquic.h3.connection QpackDecompressionFailed(reason_phrase: str="") at: aioquic.h3.connection.H3Connection._decode_headers decoder, headers = self._decoder.feed_header(stream_id, frame_data) decoder, headers = self._decoder.resume_header(stream_id) at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def _decode_headers(self, stream_id: int, frame_data: Optional[bytes]) -> Headers: """ Decode a HEADERS block and send decoder updates on the decoder stream. This is called with frame_data=None when a stream becomes unblocked. """ try: if frame_data is None: decoder, headers = self._decoder.resume_header(stream_id) else: decoder, headers = self._decoder.feed_header(stream_id, frame_data) + self._decoder_bytes_sent += len(decoder) self._quic.send_stream_data(self._local_decoder_stream_id, decoder) except pylsqpack.DecompressionFailed as exc: raise QpackDecompressionFailed() from exc return headers ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 4096 self._blocked_streams = 16 self._is_client = quic.configuration.is_client self._is_done = False self._quic = quic self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger self._decoder = pylsqpack.Decoder( self._max_table_capacity, self._blocked_streams ) + self._decoder_bytes_received = 0 + self._decoder_bytes_sent = 0 self._encoder = pylsqpack.Encoder() + self._encoder_bytes_received = 0 + self._encoder_bytes_sent = 0 self._stream: Dict[int, H3Stream] = {} self._max_push_id: Optional[int] = 8 if self._is_client else None self._next_push_id: int = 0 self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None self._init_connection()
aioquic.h3.connection/H3Connection._receive_stream_data_uni
Modified
aiortc~aioquic
8db11b954ca3992373a98675e322d8cc9511e1f7
[interop] add a test for QPACK dynamic tables
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data_uni( self, stream: H3Stream, data: bytes, stream_ended: bool ) -> List[H3Event]: <0> http_events: List[H3Event] = [] <1> <2> stream.buffer += data <3> if stream_ended: <4> stream.ended = True <5> <6> buf = Buffer(data=stream.buffer) <7> consumed = 0 <8> unblocked_streams: Set[int] = set() <9> <10> while stream.stream_type == StreamType.PUSH or not buf.eof(): <11> # fetch stream type for unidirectional streams <12> if stream.stream_type is None: <13> try: <14> stream.stream_type = buf.pull_uint_var() <15> except BufferReadError: <16> break <17> consumed = buf.tell() <18> <19> # check unicity <20> if stream.stream_type == StreamType.CONTROL: <21> if self._peer_control_stream_id is not None: <22> raise StreamCreationError("Only one control stream is allowed") <23> self._peer_control_stream_id = stream.stream_id <24> elif stream.stream_type == StreamType.QPACK_DECODER: <25> if self._peer_decoder_stream_id is not None: <26> raise StreamCreationError( <27> "Only one QPACK decoder stream is allowed" <28> ) <29> self._peer_decoder_stream_id = stream.stream_id <30> elif stream.stream_type == StreamType.QPACK_ENCODER: <31> if self._peer_encoder_stream_id is not None: <32> raise StreamCreationError( <33> "Only one QPACK encoder stream is allowed" <34> ) <35> self._peer_encoder_stream_id = stream.stream_id <36> <37> if stream.stream_type == StreamType.CONTROL: <38> # fetch next frame <39> try: <40> frame_type = buf.pull_uint_var() <41> frame_length</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_uni( self, stream: H3Stream, data: bytes, stream_ended: bool ) -> List[H3Event]: # offset: 1 frame_data = buf.pull_bytes(frame_length) except BufferReadError: break consumed = buf.tell() self._handle_control_frame(frame_type, frame_data) elif stream.stream_type == StreamType.PUSH: # fetch push id if stream.push_id is None: try: stream.push_id = buf.pull_uint_var() except BufferReadError: break consumed = buf.tell() # remove processed data from buffer stream.buffer = stream.buffer[consumed:] return self._receive_request_or_push_data(stream, b"", stream_ended) elif stream.stream_type == StreamType.QPACK_DECODER: # feed unframed data to decoder data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() try: self._encoder.feed_decoder(data) except pylsqpack.DecoderStreamError as exc: raise QpackDecoderStreamError() from exc elif stream.stream_type == StreamType.QPACK_ENCODER: # feed unframed data to encoder data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() try: unblocked_streams.update(self._decoder.feed_encoder(data)) except pylsqpack.EncoderStreamError as exc: raise QpackEncoderStreamError() from exc else: # unknown stream type, discard data buf.seek(buf.capacity) consumed = buf.tell() # remove processed data from buffer stream.buffer = stream.buffer[consumed:] # process unblocked streams for stream_id in unblocked_streams</s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data_uni( self, stream: H3Stream, data: bytes, stream_ended: bool ) -> List[H3Event]: # offset: 2 <s> stream.buffer = stream.buffer[consumed:] # process unblocked streams for stream_id in unblocked_streams: stream = self._stream[stream_id] # resume headers http_events.extend( self._handle_request_or_push_frame( frame_type=FrameType.HEADERS, frame_data=None, stream=stream, stream_ended=stream.ended and not stream.buffer, ) ) stream.blocked = False stream.blocked_frame_size = None # resume processing if stream.buffer: http_events.extend( self._receive_request_or_push_data(stream, b"", stream.ended) ) return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool seek(pos: int) -> None tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) QpackDecoderStreamError(reason_phrase: str="") QpackEncoderStreamError(reason_phrase: str="") StreamCreationError(reason_phrase: str="") H3Stream(stream_id: int) at: aioquic.h3.connection.H3Connection _handle_control_frame(frame_type: int, frame_data: bytes) -> None _handle_request_or_push_frame(frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool) -> List[H3Event] _receive_request_or_push_data(stream: H3Stream, data: bytes, stream_ended: bool) -> List[H3Event] at: aioquic.h3.connection.H3Connection.__init__ self._decoder = pylsqpack.Decoder( self._max_table_capacity, self._blocked_streams ) self._decoder_bytes_received = 0 self._encoder = pylsqpack.Encoder() self._encoder_bytes_received = 0 self._stream: Dict[int, H3Stream] = {} self._peer_control_stream_id: Optional[int] = None ===========unchanged ref 1=========== self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._receive_request_or_push_data http_events: List[H3Event] = [] consumed = buf.tell() consumed = 0 at: aioquic.h3.connection.H3Stream.__init__ self.blocked = False self.blocked_frame_size: Optional[int] = None self.buffer = b"" self.ended = False self.push_id: Optional[int] = None self.stream_id = stream_id self.stream_type: Optional[int] = None at: aioquic.h3.events H3Event() at: typing List = _alias(list, 1, inst=False, name='List') Set = _alias(set, 1, inst=False, name='Set') ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def _encode_headers(self, stream_id: int, headers: Headers) -> bytes: """ Encode a HEADERS block and send encoder updates on the encoder stream. """ encoder, frame_data = self._encoder.encode(stream_id, 0, headers) + self._encoder_bytes_sent += len(encoder) self._quic.send_stream_data(self._local_encoder_stream_id, encoder) return frame_data ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def _decode_headers(self, stream_id: int, frame_data: Optional[bytes]) -> Headers: """ Decode a HEADERS block and send decoder updates on the decoder stream. This is called with frame_data=None when a stream becomes unblocked. """ try: if frame_data is None: decoder, headers = self._decoder.resume_header(stream_id) else: decoder, headers = self._decoder.feed_header(stream_id, frame_data) + self._decoder_bytes_sent += len(decoder) self._quic.send_stream_data(self._local_decoder_stream_id, decoder) except pylsqpack.DecompressionFailed as exc: raise QpackDecompressionFailed() from exc return headers
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
116e47ffcc9255f3b715e327834e11fa628352f2
[tls] verify max_early_data value is the expected one
<13>:<add> self.max_early_data = max_early_data
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, + max_early_data: Optional[int] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.cadata: Optional[bytes] = None <3> self.cafile: Optional[str] = None <4> self.capath: Optional[str] = None <5> self.certificate: Optional[x509.Certificate] = None <6> self.certificate_chain: List[x509.Certificate] = [] <7> self.certificate_private_key: Optional[ <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <9> ] = None <10> self.early_data_accepted = False <11> self.handshake_extensions: List[Extension] = [] <12> self.key_schedule: Optional[KeySchedule] = None <13> self.received_extensions: Optional[List[Extension]] = None <14> self.session_ticket: Optional[SessionTicket] = None <15> self.server_name: Optional[str] = None <16> <17> # callbacks <18> self.alpn_cb: Optional[AlpnHandler] = None <19> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <20> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <21> self.update_traffic_key_cb: Callable[ <22> [Direction, Epoch, CipherSuite, bytes], None <23> ] = lambda d, e, c, s: None <24> <25> # supported parameters <26> self._cipher_suites = [ <27> CipherSuite.AES_256_GCM_SHA384, <28> CipherSuite.AES_128_GCM_SHA256, <29> CipherSuite.CHACHA20_POLY1305_SHA256, <30> ] <31> </s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, + max_early_data: Optional[int] = None, ): # offset: 1 self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) AlpnHandler = Callable[[str], None] ===========unchanged ref 1=========== SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key
aioquic.quic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
116e47ffcc9255f3b715e327834e11fa628352f2
[tls] verify max_early_data value is the expected one
<1>:<add> self.tls = tls.Context( <add> is_client=self._is_client, <add> logger=self._logger, <add> max_early_data=None if self._is_client else MAX_EARLY_DATA, <add> ) <del> self.tls = tls.Context(is_client=self._is_client, logger=self._logger) <28>:<add> if session_ticket.max_early_data_size == MAX_EARLY_DATA: <del> if session_ticket.max_early_data_size == 0xFFFFFFFF:
# module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self._is_client, logger=self._logger) <2> self.tls.alpn_protocols = self._configuration.alpn_protocols <3> self.tls.cadata = self._configuration.cadata <4> self.tls.cafile = self._configuration.cafile <5> self.tls.capath = self._configuration.capath <6> self.tls.certificate = self._configuration.certificate <7> self.tls.certificate_chain = self._configuration.certificate_chain <8> self.tls.certificate_private_key = self._configuration.private_key <9> self.tls.handshake_extensions = [ <10> ( <11> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <12> self._serialize_transport_parameters(), <13> ) <14> ] <15> self.tls.server_name = self._configuration.server_name <16> <17> # TLS session resumption <18> session_ticket = self._configuration.session_ticket <19> if ( <20> self._is_client <21> and session_ticket is not None <22> and session_ticket.is_valid <23> and session_ticket.server_name == self._configuration.server_name <24> ): <25> self.tls.session_ticket = self._configuration.session_ticket <26> <27> # parse saved QUIC transport parameters - for 0-RTT <28> if session_ticket.max_early_data_size == 0xFFFFFFFF: <29> for ext_type, ext_data in session_ticket.other_extensions: <30> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <31> self._parse_transport_parameters( <32> ext_data, from_session_ticket=True <33> ) <34> break <35> <36> # TLS callbacks <37> self.tls.alpn_cb = self._alpn_handler <38> if self._session_ticket_fetcher is not None</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.certificate_chain = certificates[1:] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.quic.configuration.QuicConfiguration.load_verify_locations self.cafile = cafile self.capath = capath self.cadata = cadata at: aioquic.quic.connection MAX_EARLY_DATA = 0xFFFFFFFF QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.quic.connection.QuicConnection _alpn_handler(alpn_protocol: str) -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None ===========unchanged ref 1=========== _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.quic.crypto CryptoPair() at: aioquic.quic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) ===========unchanged ref 2=========== at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)
tests.test_tls/ContextTest.create_server
Modified
aiortc~aioquic
116e47ffcc9255f3b715e327834e11fa628352f2
[tls] verify max_early_data value is the expected one
<3>:<add> server = Context(is_client=False, max_early_data=0xFFFFFFFF) <del> server = Context(is_client=False)
# module: tests.test_tls class ContextTest(TestCase): def create_server(self): <0> configuration = QuicConfiguration(is_client=False) <1> configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <2> <3> server = Context(is_client=False) <4> server.certificate = configuration.certificate <5> server.certificate_private_key = configuration.private_key <6> server.handshake_extensions = [ <7> ( <8> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <9> SERVER_QUIC_TRANSPORT_PARAMETERS, <10> ) <11> ] <12> self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO) <13> return server <14>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None ===========unchanged ref 1=========== at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.tls State() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls SERVER_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff00001104ff000011004500050004801000000006000480100000000700048" b"010000000040004810000000001000242580002001000000000000000000000" b"000000000000000800024064000a00010a" ) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str ===========unchanged ref 2=========== assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: + def _handle_session_ticket(self, session_ticket: tls.SessionTicket) -> None: + if ( + session_ticket.max_early_data_size is not None + and session_ticket.max_early_data_size != MAX_EARLY_DATA + ): + raise QuicConnectionError( + error_code=QuicErrorCode.PROTOCOL_VIOLATION, + frame_type=QuicFrameType.CRYPTO, + reason_phrase="Invalid max_early_data value %s" + % session_ticket.max_early_data_size, + ) + self._session_ticket_handler(session_ticket) + ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_0rtt_bad_max_early_data(self): + client_ticket = None + ticket_store = SessionTicketStore() + + def patch(server): + """ + Patch server's TLS initialization to set an invalid + max_early_data value. + """ + real_initialize = server._initialize + + def patched_initialize(peer_cid: bytes): + real_initialize(peer_cid) + server.tls.max_early_data = 12345 + + server._initialize = patched_initialize + + def save_session_ticket(ticket): + nonlocal client_ticket + client_ticket = ticket + + with client_and_server( + client_kwargs={"session_ticket_handler": save_session_ticket}, + server_kwargs={"session_ticket_handler": ticket_store.add}, + server_patch=patch, + ) as (client, server): + # check handshake failed + event = client.next_event() + self.assertIsNone(event) + ===========changed ref 2=========== # module: aioquic.quic.connection logger = logging.getLogger("quic") EPOCH_SHORTCUTS = { "I": tls.Epoch.INITIAL, "Z": tls.Epoch.ZERO_RTT, "H": tls.Epoch.HANDSHAKE, "O": tls.Epoch.ONE_RTT, } MAX_DATA_WINDOW = 1048576 + MAX_EARLY_DATA = 0xFFFFFFFF SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any
aioquic.tls/pull_key_share
Modified
aiortc~aioquic
88532f3e474c47d017cba524a05b78cdb774d027
[tls] don't croak on unknown TLS parameters
<0>:<add> group = buf.pull_uint16() <del> group = pull_group(buf)
# module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: <0> group = pull_group(buf) <1> data = pull_opaque(buf, 2) <2> return (group, data) <3>
===========unchanged ref 0=========== at: aioquic.tls push_opaque(buf: Buffer, capacity: int, value: bytes) -> None ===========changed ref 0=========== # module: aioquic.tls # KeyShareEntry + KeyShareEntry = Tuple[int, bytes] - KeyShareEntry = Tuple[Group, bytes] ===========changed ref 1=========== # module: aioquic.tls - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm: - return SignatureAlgorithm(buf.pull_uint16()) - ===========changed ref 2=========== # module: aioquic.tls - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: - return PskKeyExchangeMode(buf.pull_uint8()) - ===========changed ref 3=========== # module: aioquic.tls - def pull_group(buf: Buffer) -> Group: - return Group(buf.pull_uint16()) - ===========changed ref 4=========== # module: aioquic.tls - # INTEGERS - - - def pull_compression_method(buf: Buffer) -> CompressionMethod: - return CompressionMethod(buf.pull_uint8()) -
aioquic.tls/pull_client_hello
Modified
aiortc~aioquic
88532f3e474c47d017cba524a05b78cdb774d027
[tls] don't croak on unknown TLS parameters
<9>:<add> compression_methods=pull_list(buf, 1, buf.pull_uint8), <del> compression_methods=pull_list( <10>:<del> buf, 1, partial(pull_compression_method, buf) <11>:<del> ), <29>:<add> hello.signature_algorithms = pull_list(buf, 2, buf.pull_uint16) <del> hello.signature_algorithms = pull_list( <30>:<del> buf, 2, partial(pull_signature_algorithm, buf) <31>:<del> ) <33>:<add> hello.supported_groups = pull_list(buf, 2, buf.pull_uint16) <del> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) <35>:<add> hello.psk_key_exchange_modes = pull_list(buf, 1, buf.pull_uint8) <del> hello.psk_key_exchange_modes = pull_list( <36>:<del> buf, 1, partial(pull_psk_key_exchange_mode, buf)
# module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: <0> assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO <1> with pull_block(buf, 3): <2> assert buf.pull_uint16() == TLS_VERSION_1_2 <3> client_random = buf.pull_bytes(32) <4> <5> hello = ClientHello( <6> random=client_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suites=pull_list(buf, 2, buf.pull_uint16), <9> compression_methods=pull_list( <10> buf, 1, partial(pull_compression_method, buf) <11> ), <12> ) <13> <14> # extensions <15> after_psk = False <16> <17> def pull_extension() -> None: <18> # pre_shared_key MUST be last <19> nonlocal after_psk <20> assert not after_psk <21> <22> extension_type = buf.pull_uint16() <23> extension_length = buf.pull_uint16() <24> if extension_type == ExtensionType.KEY_SHARE: <25> hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) <26> elif extension_type == ExtensionType.SUPPORTED_VERSIONS: <27> hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) <28> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: <29> hello.signature_algorithms = pull_list( <30> buf, 2, partial(pull_signature_algorithm, buf) <31> ) <32> elif extension_type == ExtensionType.SUPPORTED_GROUPS: <33> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) <34> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: <35> hello.psk_key_exchange_modes = pull_list( <36> buf, 1, partial(pull_psk_key_exchange_mode, buf) </s>
===========below chunk 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert buf.pull_uint8() == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list( buf, 2, partial(pull_alpn_protocol, buf) ) elif extension_type == ExtensionType.EARLY_DATA: hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, partial(pull_psk_identity, buf)), binders=pull_list(buf, 2, partial(pull_psk_binder, buf)), ) after_psk = True else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_bytes(length: int) -> bytes pull_uint8() -> int pull_uint16() -> int push_bytes(value: bytes) -> None push_uint8(value: int) -> None push_uint16(value: int) -> None at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_block(buf: Buffer, capacity: int) -> Generator push_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T] push_list(buf: Buffer, capacity: int, func: Callable[[T], None], values: Sequence[T]) -> None pull_opaque(buf: Buffer, capacity: int) -> bytes push_opaque(buf: Buffer, capacity: int, value: bytes) -> None push_extension(buf: Buffer, extension_type: int) -> Generator pull_key_share(buf: Buffer) -> KeyShareEntry push_key_share(buf: Buffer, value: KeyShareEntry) -> None pull_alpn_protocol(buf: Buffer) -> str pull_psk_identity(buf: Buffer) -> PskIdentity pull_psk_binder(buf: Buffer) -> bytes OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[int], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[int]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[int]]=None, supported_groups: Optional[List[int]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[int] compression_methods: List[int] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[int]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[int]] = None supported_groups: Optional[List[int]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: aioquic.tls.pull_client_hello hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, buf.pull_uint16), compression_methods=pull_list(buf, 1, buf.pull_uint8), ) ===========unchanged ref 2=========== after_psk = False pull_extension() -> None at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() ===========changed ref 0=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: + group = buf.pull_uint16() - group = pull_group(buf) data = pull_opaque(buf, 2) return (group, data) ===========changed ref 1=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[int] + compression_methods: List[int] - compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[int]] = None - psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None + signature_algorithms: Optional[List[int]] = None - signature_algorithms: Optional[List[SignatureAlgorithm]] = None + supported_groups: Optional[List[int]] = None - supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 2=========== # module: aioquic.tls # KeyShareEntry + KeyShareEntry = Tuple[int, bytes] - KeyShareEntry = Tuple[Group, bytes] ===========changed ref 3=========== # module: aioquic.tls - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm: - return SignatureAlgorithm(buf.pull_uint16()) - ===========changed ref 4=========== # module: aioquic.tls - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: - return PskKeyExchangeMode(buf.pull_uint8()) - ===========changed ref 5=========== # module: aioquic.tls - def pull_group(buf: Buffer) -> Group: - return Group(buf.pull_uint16()) - ===========changed ref 6=========== # module: aioquic.tls - # INTEGERS - - - def pull_compression_method(buf: Buffer) -> CompressionMethod: - return CompressionMethod(buf.pull_uint8()) -
aioquic.tls/pull_server_hello
Modified
aiortc~aioquic
88532f3e474c47d017cba524a05b78cdb774d027
[tls] don't croak on unknown TLS parameters
<9>:<add> compression_method=buf.pull_uint8(), <del> compression_method=pull_compression_method(buf),
# module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: <0> assert buf.pull_uint8() == HandshakeType.SERVER_HELLO <1> with pull_block(buf, 3): <2> assert buf.pull_uint16() == TLS_VERSION_1_2 <3> server_random = buf.pull_bytes(32) <4> <5> hello = ServerHello( <6> random=server_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suite=buf.pull_uint16(), <9> compression_method=pull_compression_method(buf), <10> ) <11> <12> # extensions <13> def pull_extension() -> None: <14> extension_type = buf.pull_uint16() <15> extension_length = buf.pull_uint16() <16> if extension_type == ExtensionType.SUPPORTED_VERSIONS: <17> hello.supported_version = buf.pull_uint16() <18> elif extension_type == ExtensionType.KEY_SHARE: <19> hello.key_share = pull_key_share(buf) <20> elif extension_type == ExtensionType.PRE_SHARED_KEY: <21> hello.pre_shared_key = buf.pull_uint16() <22> else: <23> hello.other_extensions.append( <24> (extension_type, buf.pull_bytes(extension_length)) <25> ) <26> <27> pull_list(buf, 2, pull_extension) <28> <29> return hello <30>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_bytes(length: int) -> bytes push_bytes(value: bytes) -> None push_uint8(value: int) -> None push_uint16(value: int) -> None at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) push_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T] push_opaque(buf: Buffer, capacity: int, value: bytes) -> None push_extension(buf: Buffer, extension_type: int) -> Generator push_key_share(buf: Buffer, value: KeyShareEntry) -> None ServerHello(random: bytes, session_id: bytes, cipher_suite: int, compression_method: int, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: int compression_method: int key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========unchanged ref 1=========== at: aioquic.tls.pull_server_hello hello = ServerHello( random=server_random, session_id=pull_opaque(buf, 1), cipher_suite=buf.pull_uint16(), compression_method=buf.pull_uint8(), ) pull_extension() -> None ===========changed ref 0=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes cipher_suite: int + compression_method: int - compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls # KeyShareEntry + KeyShareEntry = Tuple[int, bytes] - KeyShareEntry = Tuple[Group, bytes] ===========changed ref 2=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: + group = buf.pull_uint16() - group = pull_group(buf) data = pull_opaque(buf, 2) return (group, data) ===========changed ref 3=========== # module: aioquic.tls - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm: - return SignatureAlgorithm(buf.pull_uint16()) - ===========changed ref 4=========== # module: aioquic.tls - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: - return PskKeyExchangeMode(buf.pull_uint8()) - ===========changed ref 5=========== # module: aioquic.tls - def pull_group(buf: Buffer) -> Group: - return Group(buf.pull_uint16()) - ===========changed ref 6=========== # module: aioquic.tls - # INTEGERS - - - def pull_compression_method(buf: Buffer) -> CompressionMethod: - return CompressionMethod(buf.pull_uint8()) - ===========changed ref 7=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[int] + compression_methods: List[int] - compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[int]] = None - psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None + signature_algorithms: Optional[List[int]] = None - signature_algorithms: Optional[List[SignatureAlgorithm]] = None + supported_groups: Optional[List[int]] = None - supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 8=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 client_random = buf.pull_bytes(32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, buf.pull_uint16), + compression_methods=pull_list(buf, 1, buf.pull_uint8), - compression_methods=pull_list( - buf, 1, partial(pull_compression_method, buf) - ), ) # extensions after_psk = False def pull_extension() -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: + hello.signature_algorithms = pull_list(buf, 2, buf.pull_uint16) - hello.signature_algorithms = pull_list( - buf, 2, partial(pull_signature_algorithm, buf) - ) elif extension_type == ExtensionType.SUPPORTED_GROUPS: + hello.supported_groups = pull_list(buf, 2, buf.pull_uint16) - hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODE</s>
aioquic.tls/pull_certificate_verify
Modified
aiortc~aioquic
88532f3e474c47d017cba524a05b78cdb774d027
[tls] don't croak on unknown TLS parameters
<2>:<add> algorithm = buf.pull_uint16() <del> algorithm = pull_signature_algorithm(buf)
# module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: <0> assert buf.pull_uint8() == HandshakeType.CERTIFICATE_VERIFY <1> with pull_block(buf, 3): <2> algorithm = pull_signature_algorithm(buf) <3> signature = pull_opaque(buf, 2) <4> <5> return CertificateVerify(algorithm=algorithm, signature=signature) <6>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer push_uint8(value: int) -> None at: aioquic.tls HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_opaque(buf: Buffer, capacity: int) -> bytes Finished(verify_data: bytes=b"") at: aioquic.tls.Finished verify_data: bytes = b"" at: aioquic.tls.pull_finished finished = Finished() ===========changed ref 0=========== # module: aioquic.tls @dataclass class CertificateVerify: + algorithm: int - algorithm: SignatureAlgorithm signature: bytes ===========changed ref 1=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes cipher_suite: int + compression_method: int - compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 2=========== # module: aioquic.tls # KeyShareEntry + KeyShareEntry = Tuple[int, bytes] - KeyShareEntry = Tuple[Group, bytes] ===========changed ref 3=========== # module: aioquic.tls def pull_key_share(buf: Buffer) -> KeyShareEntry: + group = buf.pull_uint16() - group = pull_group(buf) data = pull_opaque(buf, 2) return (group, data) ===========changed ref 4=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert buf.pull_uint8() == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 server_random = buf.pull_bytes(32) hello = ServerHello( random=server_random, session_id=pull_opaque(buf, 1), cipher_suite=buf.pull_uint16(), + compression_method=buf.pull_uint8(), - compression_method=pull_compression_method(buf), ) # extensions def pull_extension() -> None: extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = buf.pull_uint16() elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = buf.pull_uint16() else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========changed ref 5=========== # module: aioquic.tls - def pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm: - return SignatureAlgorithm(buf.pull_uint16()) - ===========changed ref 6=========== # module: aioquic.tls - def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: - return PskKeyExchangeMode(buf.pull_uint8()) - ===========changed ref 7=========== # module: aioquic.tls - def pull_group(buf: Buffer) -> Group: - return Group(buf.pull_uint16()) - ===========changed ref 8=========== # module: aioquic.tls - # INTEGERS - - - def pull_compression_method(buf: Buffer) -> CompressionMethod: - return CompressionMethod(buf.pull_uint8()) - ===========changed ref 9=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[int] + compression_methods: List[int] - compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[int]] = None - psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None + signature_algorithms: Optional[List[int]] = None - signature_algorithms: Optional[List[SignatureAlgorithm]] = None + supported_groups: Optional[List[int]] = None - supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 10=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 client_random = buf.pull_bytes(32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, buf.pull_uint16), + compression_methods=pull_list(buf, 1, buf.pull_uint8), - compression_methods=pull_list( - buf, 1, partial(pull_compression_method, buf) - ), ) # extensions after_psk = False def pull_extension() -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: + hello.signature_algorithms = pull_list(buf, 2, buf.pull_uint16) - hello.signature_algorithms = pull_list( - buf, 2, partial(pull_signature_algorithm, buf) - ) elif extension_type == ExtensionType.SUPPORTED_GROUPS: + hello.supported_groups = pull_list(buf, 2, buf.pull_uint16) - hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODE</s>
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
88532f3e474c47d017cba524a05b78cdb774d027
[tls] don't croak on unknown TLS parameters
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.cadata: Optional[bytes] = None <3> self.cafile: Optional[str] = None <4> self.capath: Optional[str] = None <5> self.certificate: Optional[x509.Certificate] = None <6> self.certificate_chain: List[x509.Certificate] = [] <7> self.certificate_private_key: Optional[ <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <9> ] = None <10> self.early_data_accepted = False <11> self.handshake_extensions: List[Extension] = [] <12> self.key_schedule: Optional[KeySchedule] = None <13> self.max_early_data = max_early_data <14> self.received_extensions: Optional[List[Extension]] = None <15> self.session_ticket: Optional[SessionTicket] = None <16> self.server_name: Optional[str] = None <17> <18> # callbacks <19> self.alpn_cb: Optional[AlpnHandler] = None <20> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <21> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <22> self.update_traffic_key_cb: Callable[ <23> [Direction, Epoch, CipherSuite, bytes], None <24> ] = lambda d, e, c, s: None <25> <26> # supported parameters <27> self._cipher_suites = [ <28> CipherSuite.AES_256_GCM_SHA384, <29> CipherSuite.AES_128_GCM_SHA256, <30> CipherSuite.CHACHA</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 1 ] self._compression_methods = [CompressionMethod.NULL] self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 2 <s> self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context _client_send_hello(output_buf: Buffer) -> None ===========unchanged ref 1=========== at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.client_random = peer_hello.random self.session_id = peer_hello.session_id self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) ===========unchanged ref 2=========== self._new_session_ticket = NewSessionTicket( ticket_lifetime=86400, ticket_age_add=struct.unpack("I", os.urandom(4))[0], ticket_nonce=b"", ticket=os.urandom(64), max_early_data_size=self.max_early_data, ) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.tls @dataclass class CertificateVerify: + algorithm: int - algorithm: SignatureAlgorithm signature: bytes ===========changed ref 1=========== # module: aioquic.tls def pull_certificate_verify(buf: Buffer) -> CertificateVerify: assert buf.pull_uint8() == HandshakeType.CERTIFICATE_VERIFY with pull_block(buf, 3): + algorithm = buf.pull_uint16() - algorithm = pull_signature_algorithm(buf) signature = pull_opaque(buf, 2) return CertificateVerify(algorithm=algorithm, signature=signature)
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
88532f3e474c47d017cba524a05b78cdb774d027
[tls] don't croak on unknown TLS parameters
<1>:<add> supported_groups: List[int] = [] <del> supported_groups: List[Group] = []
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=[int(x) for x in self._cipher_suites], <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_share=key_share, <24> psk_key_exchange_modes=self._psk_key_exchange_modes <25> if (self.session_ticket or self.new_session_ticket_cb is not None) <26> else None, <27> server_name=self.server_name, <28> signature_algorithms=self._signature_algorithms, <29> supported_groups=supported_groups, <30> supported_versions=self._supported_versions, <31> other_extensions=self.handshake_extensions, <32> ) <33> <34> # PSK <35> if self.session_ticket and self.session_ticket</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_psk.extract(self.session_ticket.resumption_secret) binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # update hello if self.session_ticket.max_early_data_size is not None: hello.early_data = True hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) # serialize hello without binder tmp_buf = Buffer(capacity=1024) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) # calculate early data key if hello.early_data: early_key = self._key_schedule_psk.derive_secret(b"c e traffic") self.update_traffic_key_cb( Direction.ENCRYPT, Epoch.ZERO_RTT, self._key_schedule_psk.cipher_suite, early_key, ) self._key_schedule_proxy = Key</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 2 <s>schedule_psk.cipher_suite, early_key, ) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls AlertHandshakeFailure(*args: object) AlertIllegalParameter(*args: object) Direction() Epoch() State() OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) push_client_hello(buf: Buffer, hello: ClientHello) -> None pull_server_hello(buf: Buffer) -> ServerHello KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) negotiate(supported: List[T], offered: Optional[List[Any]], exc: Optional[Alert]=None) -> T push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.ClientHello early_data: bool = False pre_shared_key: Optional[OfferedPsks] = None at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None ===========unchanged ref 1=========== self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._session_resumed = False at: aioquic.tls.Context._client_handle_hello self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello supported_groups: List[int] = [] ===========unchanged ref 2=========== hello = ClientHello( random=self.client_random, session_id=self.session_id, cipher_suites=[int(x) for x in self._cipher_suites], compression_methods=self._compression_methods, alpn_protocols=self.alpn_protocols, key_share=key_share, psk_key_exchange_modes=self._psk_key_exchange_modes if (self.session_ticket or self.new_session_ticket_cb is not None) else None, server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True at: aioquic.tls.KeySchedule finished_verify_data(secret: bytes) -> bytes derive_secret(label: bytes) -> bytes extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.algorithm = cipher_suite_hash(cipher_suite) self.cipher_suite = cipher_suite at: aioquic.tls.KeyScheduleProxy extract(key_material: Optional[bytes]=None) -> None select(cipher_suite: CipherSuite) -> KeySchedule at: aioquic.tls.OfferedPsks binders: List[bytes] at: aioquic.tls.ServerHello cipher_suite: int compression_method: int pre_shared_key: Optional[int] = None supported_version: Optional[int] = None at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
dd555a0b35af21f4630c30cd8bc9dfb135ebbcde
[tls] enable X25519 if supported
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.cadata: Optional[bytes] = None <3> self.cafile: Optional[str] = None <4> self.capath: Optional[str] = None <5> self.certificate: Optional[x509.Certificate] = None <6> self.certificate_chain: List[x509.Certificate] = [] <7> self.certificate_private_key: Optional[ <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <9> ] = None <10> self.early_data_accepted = False <11> self.handshake_extensions: List[Extension] = [] <12> self.key_schedule: Optional[KeySchedule] = None <13> self.max_early_data = max_early_data <14> self.received_extensions: Optional[List[Extension]] = None <15> self.session_ticket: Optional[SessionTicket] = None <16> self.server_name: Optional[str] = None <17> <18> # callbacks <19> self.alpn_cb: Optional[AlpnHandler] = None <20> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <21> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <22> self.update_traffic_key_cb: Callable[ <23> [Direction, Epoch, CipherSuite, bytes], None <24> ] = lambda d, e, c, s: None <25> <26> # supported parameters <27> self._cipher_suites = [ <28> CipherSuite.AES_256_GCM_SHA384, <29> CipherSuite.AES_128_GCM_SHA256, <30> CipherSuite.CHACHA</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 1 ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 2 <s> = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) AlpnHandler = Callable[[str], None] ===========unchanged ref 1=========== SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key
tests.test_tls/ContextTest._handshake
Modified
aiortc~aioquic
dd555a0b35af21f4630c30cd8bc9dfb135ebbcde
[tls] enable X25519 if supported
<6>:<add> self.assertLessEqual(len(server_input), 296) <del> self.assertLessEqual(len(server_input), 264)
# module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): <0> # send client hello <1> client_buf = create_buffers() <2> client.handle_message(b"", client_buf) <3> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <4> server_input = merge_buffers(client_buf) <5> self.assertGreaterEqual(len(server_input), 213) <6> self.assertLessEqual(len(server_input), 264) <7> reset_buffers(client_buf) <8> <9> # handle client hello <10> # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) <11> server_buf = create_buffers() <12> server.handle_message(server_input, server_buf) <13> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <14> client_input = merge_buffers(server_buf) <15> self.assertGreaterEqual(len(client_input), 600) <16> self.assertLessEqual(len(client_input), 2316) <17> <18> reset_buffers(server_buf) <19> <20> # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) <21> # send finished <22> client.handle_message(client_input, client_buf) <23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <24> server_input = merge_buffers(client_buf) <25> self.assertEqual(len(server_input), 52) <26> reset_buffers(client_buf) <27> <28> # handle finished <29> server.handle_message(server_input, server_buf) <30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <31> client_input = merge_buffers(server_buf) <32> self.assertEqual(len(client_input), 0) <33> <34> # check keys match <35> self.assertEqual(client._dec_key, server._enc_</s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # offset: 1 self.assertEqual(client._enc_key, server._dec_key) # check cipher suite self.assertEqual( client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) self.assertEqual( server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) ===========unchanged ref 0=========== at: aioquic.tls State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str ===========unchanged ref 1=========== assertEqual(first: Any, second: Any, msg: Any=...) -> None assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None assertLessEqual(a: Any, b: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.max_early_data = max_early_data self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL</s> ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 1 <s>_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] + if default_backend().x25519_supported(): + self._supported_groups.append(Group.X25519) self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None </s> ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 2 <s> if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
tests.test_tls/ContextTest.test_handshake_with_alpn_fail
Modified
aiortc~aioquic
dd555a0b35af21f4630c30cd8bc9dfb135ebbcde
[tls] enable X25519 if supported
<11>:<add> self.assertGreaterEqual(len(server_input), 258) <del> self.assertEqual(len(server_input), 258) <12>:<add> self.assertLessEqual(len(server_input), 296)
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn_fail(self): <0> client = self.create_client() <1> client.alpn_protocols = ["hq-20"] <2> <3> server = self.create_server() <4> server.alpn_protocols = ["h3-20"] <5> <6> # send client hello <7> client_buf = create_buffers() <8> client.handle_message(b"", client_buf) <9> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <10> server_input = merge_buffers(client_buf) <11> self.assertEqual(len(server_input), 258) <12> reset_buffers(client_buf) <13> <14> # handle client hello <15> # send server hello, encrypted extensions, certificate, certificate verify, finished <16> server_buf = create_buffers() <17> with self.assertRaises(tls.AlertHandshakeFailure) as cm: <18> server.handle_message(server_input, server_buf) <19> self.assertEqual(str(cm.exception), "No common ALPN protocols") <20>
===========unchanged ref 0=========== at: aioquic.tls AlertHandshakeFailure(*args: object) State() at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest create_client(cafile=SERVER_CACERTFILE) create_server() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None assertLessEqual(a: Any, b: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # send client hello client_buf = create_buffers() client.handle_message(b"", client_buf) self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf) self.assertGreaterEqual(len(server_input), 213) + self.assertLessEqual(len(server_input), 296) - self.assertLessEqual(len(server_input), 264) reset_buffers(client_buf) # handle client hello # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) server_buf = create_buffers() server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) client_input = merge_buffers(server_buf) self.assertGreaterEqual(len(client_input), 600) self.assertLessEqual(len(client_input), 2316) reset_buffers(server_buf) # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) # send finished client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 52) reset_buffers(client_buf) # handle finished server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 0) # check keys match self.assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._</s> ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # offset: 1 <s>assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._dec_key) # check cipher suite self.assertEqual( client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) self.assertEqual( server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.max_early_data = max_early_data self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL</s> ===========changed ref 3=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, ): # offset: 1 <s>_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] + if default_backend().x25519_supported(): + self._supported_groups.append(Group.X25519) self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None </s>
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
4a52a6526e5edad5ca262c7eb66aa723ed38e523
[tls] make it possible to disable certificate verification
<17>:<add> if verify_mode is not None: <add> self.verify_mode = verify_mode <add> else: <add> self.verify_mode = ( <add> ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE <add> )
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + verify_mode: Optional[int] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.cadata: Optional[bytes] = None <3> self.cafile: Optional[str] = None <4> self.capath: Optional[str] = None <5> self.certificate: Optional[x509.Certificate] = None <6> self.certificate_chain: List[x509.Certificate] = [] <7> self.certificate_private_key: Optional[ <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <9> ] = None <10> self.early_data_accepted = False <11> self.handshake_extensions: List[Extension] = [] <12> self.key_schedule: Optional[KeySchedule] = None <13> self.max_early_data = max_early_data <14> self.received_extensions: Optional[List[Extension]] = None <15> self.session_ticket: Optional[SessionTicket] = None <16> self.server_name: Optional[str] = None <17> <18> # callbacks <19> self.alpn_cb: Optional[AlpnHandler] = None <20> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <21> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <22> self.update_traffic_key_cb: Callable[ <23> [Direction, Epoch, CipherSuite, bytes], None <24> ] = lambda d, e, c, s: None <25> <26> # supported parameters <27> self._cipher_suites = [ <28> CipherSuite.AES_256_GCM_SHA384, <29> CipherSuite.AES_128_G</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + verify_mode: Optional[int] = None, ): # offset: 1 CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] if default_backend().x25519_supported(): self._supported_groups.append(Group.X25519) self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + verify_mode: Optional[int] = None, ): # offset: 2 <s>_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) AlpnHandler = Callable[[str], None] ===========unchanged ref 1=========== SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key
aioquic.tls/Context._client_handle_certificate_verify
Modified
aiortc~aioquic
4a52a6526e5edad5ca262c7eb66aa723ed38e523
[tls] make it possible to disable certificate verification
<17>:<add> if self.verify_mode != ssl.CERT_NONE: <add> verify_certificate( <del> verify_certificate( <18>:<add> cadata=self.cadata, <del> cadata=self.cadata, <19>:<add> cafile=self.cafile, <del> cafile=self.cafile, <20>:<add> capath=self.capath, <del> capath=self.capath, <21>:<add> certificate=self._peer_certificate, <del> certificate=self._peer_certificate, <22>:<add> chain=self._peer_certificate_chain, <del> chain=self._peer_certificate_chain, <23>:<add> server_name=self.server_name, <del> server_name=self.server_name, <24>:<add> ) <del> )
# module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: <0> verify = pull_certificate_verify(input_buf) <1> <2> assert verify.algorithm in self._signature_algorithms <3> <4> # check signature <5> try: <6> self._peer_certificate.public_key().verify( <7> verify.signature, <8> self.key_schedule.certificate_verify_data( <9> b"TLS 1.3, server CertificateVerify" <10> ), <11> *signature_algorithm_params(verify.algorithm), <12> ) <13> except InvalidSignature: <14> raise AlertDecryptError <15> <16> # check certificate <17> verify_certificate( <18> cadata=self.cadata, <19> cafile=self.cafile, <20> capath=self.capath, <21> certificate=self._peer_certificate, <22> chain=self._peer_certificate_chain, <23> server_name=self.server_name, <24> ) <25> <26> self.key_schedule.update_hash(input_buf.data) <27> <28> self._set_state(State.CLIENT_EXPECT_FINISHED) <29>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertDecryptError(*args: object) State() verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None pull_certificate_verify(buf: Buffer) -> CertificateVerify signature_algorithm_params(signature_algorithm: int) -> Union[Tuple[ec.ECDSA], Tuple[padding.AsymmetricPadding, hashes.HashAlgorithm]] at: aioquic.tls.CertificateVerify algorithm: int signature: bytes at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.key_schedule: Optional[KeySchedule] = None self.server_name: Optional[str] = None self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) ===========unchanged ref 1=========== self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule certificate_verify_data(context_string: bytes) -> bytes update_hash(data: bytes) -> None ===========changed ref 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + verify_mode: Optional[int] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.max_early_data = max_early_data self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None + if verify_mode is not None: + self.verify_mode = verify_mode + else: + self.verify_mode = ( + ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE + ) # callbacks self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher</s> ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + verify_mode: Optional[int] = None, ): # offset: 1 <s>Suite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] if default_backend().x25519_supported(): self._supported_groups.append(Group.X25519) self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_</s> ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + verify_mode: Optional[int] = None, ): # offset: 2 <s>ed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.quic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
4a52a6526e5edad5ca262c7eb66aa723ed38e523
[tls] make it possible to disable certificate verification
<5>:<add> verify_mode=self._configuration.verify_mode,
# module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context( <2> is_client=self._is_client, <3> logger=self._logger, <4> max_early_data=None if self._is_client else MAX_EARLY_DATA, <5> ) <6> self.tls.alpn_protocols = self._configuration.alpn_protocols <7> self.tls.cadata = self._configuration.cadata <8> self.tls.cafile = self._configuration.cafile <9> self.tls.capath = self._configuration.capath <10> self.tls.certificate = self._configuration.certificate <11> self.tls.certificate_chain = self._configuration.certificate_chain <12> self.tls.certificate_private_key = self._configuration.private_key <13> self.tls.handshake_extensions = [ <14> ( <15> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <16> self._serialize_transport_parameters(), <17> ) <18> ] <19> self.tls.server_name = self._configuration.server_name <20> <21> # TLS session resumption <22> session_ticket = self._configuration.session_ticket <23> if ( <24> self._is_client <25> and session_ticket is not None <26> and session_ticket.is_valid <27> and session_ticket.server_name == self._configuration.server_name <28> ): <29> self.tls.session_ticket = self._configuration.session_ticket <30> <31> # parse saved QUIC transport parameters - for 0-RTT <32> if session_ticket.max_early_data_size == MAX_EARLY_DATA: <33> for ext_type, ext_data in session_ticket.other_extensions: <34> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <35> self._parse_transport_parameters( <36> ext_data, from_session_ticket=True <37> ) <38> break <39> </s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 self.tls.alpn_cb = self._alpn_handler if self._session_ticket_fetcher is not None: self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._handle_session_ticket self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.certificate_chain = certificates[1:] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.quic.configuration.QuicConfiguration.load_verify_locations self.cafile = cafile self.capath = capath self.cadata = cadata at: aioquic.quic.connection MAX_EARLY_DATA = 0xFFFFFFFF at: aioquic.quic.connection.QuicConnection _alpn_handler(alpn_protocol: str) -> None _handle_session_ticket(session_ticket: tls.SessionTicket) -> None ===========unchanged ref 1=========== _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._version: Optional[int] = None self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) at: aioquic.quic.crypto CryptoPair() at: aioquic.quic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool, version: int) -> None at: aioquic.quic.recovery QuicPacketSpace() ===========unchanged ref 2=========== at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.stream QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None at: aioquic.tls.SessionTicket age_add: int
examples.interop/run
Modified
aiortc~aioquic
4a52a6526e5edad5ca262c7eb66aa723ed38e523
[tls] make it possible to disable certificate verification
<8>:<add> verify_mode=server.verify_mode,
# module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: <0> for server in servers: <1> for test_name, test_func in tests: <2> print("\n=== %s %s ===\n" % (server.name, test_name)) <3> configuration = QuicConfiguration( <4> alpn_protocols=H3_ALPN + H0_ALPN, <5> is_client=True, <6> quic_logger=QuicLogger(), <7> secrets_log_file=secrets_log_file, <8> ) <9> if test_name == "test_throughput": <10> timeout = 60 <11> else: <12> timeout = 5 <13> try: <14> await asyncio.wait_for( <15> test_func(server, configuration), timeout=timeout <16> ) <17> except Exception as exc: <18> print(exc) <19> <20> if quic_log: <21> with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: <22> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) <23> <24> print("") <25> print_result(server) <26> <27> # print summary <28> if len(servers) > 1: <29> print("SUMMARY") <30> for server in servers: <31> print_result(server) <32>
===========unchanged ref 0=========== at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None ===========unchanged ref 1=========== supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.quic.logger QuicLogger() at: aioquic.quic.logger.QuicLogger to_dict() -> Dict[str, Any] at: asyncio.tasks wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: examples.interop print_result(server: Server) -> None at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) verify_mode: Optional[int] = None at: json dump(obj: Any, fp: IO[str], *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> None ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) + verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop @dataclass class Server: name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) + verify_mode: Optional[int] = None ===========changed ref 2=========== # module: examples.interop SERVERS = [ Server("aioquic", "quic.aiortc.org", port=443), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com"), + Server( + "msquic", "quic.westus.cloudapp.azure.com", port=443, verify_mode=ssl.CERT_NONE - Server("msquic", "quic.westus.cloudapp.azure.com", port=443), + ), Server("mvfst", "fb.mvfst.net"), Server("ngtcp2", "nghttp2.org"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), Server("pandora", "pandora.cm.in.tum.de"), Server("picoquic", "test.privateoctopus.com"), Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=4433), Server("quicker", "quicker.edm.uhasselt.be", retry_port=None), Server("quicly", "kazuhooku.com"), Server("quinn", "ralith.com"), ]
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<0>:<add> # configuration <add> self._alpn_protocols = alpn_protocols <add> self._cadata = cadata <add> self._cafile = cafile <add> self._capath = capath <del> self.alpn_negotiated: Optional[str] = None <1>:<del> self.alpn_protocols: Optional[List[str]] = None <2>:<del> self.cadata: Optional[bytes] = None <3>:<del> self.cafile: Optional[str] = None <4>:<del> self.capath: Optional[str] = None <10>:<del> self.early_data_accepted = False <12>:<del> self.key_schedule: Optional[KeySchedule] = None <13>:<add> self._max_early_data = max_early_data <del> self.max_early_data = max_early_data <14>:<del> self.received_extensions: Optional[List[Extension]] = None <16>:<add> self._server_name = server_name <del> self.server_name: Optional[str] = None <18>:<add> self._verify_mode = verify_mode <del> self.verify_mode = verify_mode <20>:<del> self.verify_mode = ( <21>:<add> self._verify_mode = ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE <del> ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE <22>:<del> )
<s>: bool, + alpn_protocols: Optional[List[str]] = None, + cadata: Optional[bytes] = None, + cafile: Optional[str] = None, + capath: Optional[str] = None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + server_name: Optional[str] = None, verify_mode: Optional[int] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.cadata: Optional[bytes] = None <3> self.cafile: Optional[str] = None <4> self.capath: Optional[str] = None <5> self.certificate: Optional[x509.Certificate] = None <6> self.certificate_chain: List[x509.Certificate] = [] <7> self.certificate_private_key: Optional[ <8> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <9> ] = None <10> self.early_data_accepted = False <11> self.handshake_extensions: List[Extension] = [] <12> self.key_schedule: Optional[KeySchedule] = None <13> self.max_early_data = max_early_data <14> self.received_extensions: Optional[List[Extension]] = None <15> self.session_ticket: Optional[SessionTicket] = None <16> self.server_name: Optional[str] = None <17> if verify_mode is not None: <18> self.verify_mode = verify_mode <19> else: <20> self.verify_mode = ( <21> ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE <22> ) <23> <24> # callbacks <25> self.alpn_cb: Optional[AlpnHandler] = None <26> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <27> self.new_session_ticket</s>
===========below chunk 0=========== <s> alpn_protocols: Optional[List[str]] = None, + cadata: Optional[bytes] = None, + cafile: Optional[str] = None, + capath: Optional[str] = None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + server_name: Optional[str] = None, verify_mode: Optional[int] = None, ): # offset: 1 self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] if default_backend().x25519_supported(): self._supported_groups.append(Group.X25519) self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain</s> ===========below chunk 1=========== <s> alpn_protocols: Optional[List[str]] = None, + cadata: Optional[bytes] = None, + cafile: Optional[str] = None, + capath: Optional[str] = None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + server_name: Optional[str] = None, verify_mode: Optional[int] = None, ): # offset: 2 <s>Ticket] = None self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Extension = Tuple[int, bytes] NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) AlpnHandler = Callable[[str], None] ===========unchanged ref 1=========== SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key
aioquic.tls/Context._build_session_ticket
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<19>:<add> server_name=self._server_name, <del> server_name=self.server_name,
# module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: <0> resumption_master_secret = self.key_schedule.derive_secret(b"res master") <1> resumption_secret = hkdf_expand_label( <2> algorithm=self.key_schedule.algorithm, <3> secret=resumption_master_secret, <4> label=b"resumption", <5> hash_value=new_session_ticket.ticket_nonce, <6> length=self.key_schedule.algorithm.digest_size, <7> ) <8> <9> timestamp = utcnow() <10> return SessionTicket( <11> age_add=new_session_ticket.ticket_age_add, <12> cipher_suite=self.key_schedule.cipher_suite, <13> max_early_data_size=new_session_ticket.max_early_data_size, <14> not_valid_after=timestamp <15> + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), <16> not_valid_before=timestamp, <17> other_extensions=self.handshake_extensions, <18> resumption_secret=resumption_secret, <19> server_name=self.server_name, <20> ticket=new_session_ticket.ticket, <21> ) <22>
===========unchanged ref 0=========== at: aioquic.tls utcnow = datetime.datetime.utcnow hkdf_expand_label(algorithm: hashes.HashAlgorithm, secret: bytes, label: bytes, hash_value: bytes, length: int) -> bytes NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.Context.__init__ self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.server_name: Optional[str] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule derive_secret(label: bytes) -> bytes at: aioquic.tls.KeySchedule.__init__ self.algorithm = cipher_suite_hash(cipher_suite) self.cipher_suite = cipher_suite at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" ===========unchanged ref 1=========== max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ ===========changed ref 0=========== <s>: bool, + alpn_protocols: Optional[List[str]] = None, + cadata: Optional[bytes] = None, + cafile: Optional[str] = None, + capath: Optional[str] = None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + server_name: Optional[str] = None, verify_mode: Optional[int] = None, ): + # configuration + self._alpn_protocols = alpn_protocols + self._cadata = cadata + self._cafile = cafile + self._capath = capath - self.alpn_negotiated: Optional[str] = None - self.alpn_protocols: Optional[List[str]] = None - self.cadata: Optional[bytes] = None - self.cafile: Optional[str] = None - self.capath: Optional[str] = None self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None - self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] - self.key_schedule: Optional[KeySchedule] = None + self._max_early_data = max_early_data - self.max_early_data = max_early_data - self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None + self._server_name = server_name - self.server_name: Optional[str] = None if verify_mode is not None: + self._verify_mode = verify_mode - self.verify_mode = verify_mode else: - self.</s> ===========changed ref 1=========== <s> alpn_protocols: Optional[List[str]] = None, + cadata: Optional[bytes] = None, + cafile: Optional[str] = None, + capath: Optional[str] = None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, max_early_data: Optional[int] = None, + server_name: Optional[str] = None, verify_mode: Optional[int] = None, ): # offset: 1 <s> self._verify_mode = verify_mode - self.verify_mode = verify_mode else: - self.verify_mode = ( + self._verify_mode = ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE - ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE - ) # callbacks self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL] self._psk_key_exchange_modes: List[int] = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA</s>
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<22>:<add> alpn_protocols=self._alpn_protocols, <del> alpn_protocols=self.alpn_protocols, <27>:<add> server_name=self._server_name, <del> server_name=self.server_name,
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[int] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=[int(x) for x in self._cipher_suites], <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_share=key_share, <24> psk_key_exchange_modes=self._psk_key_exchange_modes <25> if (self.session_ticket or self.new_session_ticket_cb is not None) <26> else None, <27> server_name=self.server_name, <28> signature_algorithms=self._signature_algorithms, <29> supported_groups=supported_groups, <30> supported_versions=self._supported_versions, <31> other_extensions=self.handshake_extensions, <32> ) <33> <34> # PSK <35> if self.session_ticket and self.session_ticket</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_psk.extract(self.session_ticket.resumption_secret) binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # update hello if self.session_ticket.max_early_data_size is not None: hello.early_data = True hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) # serialize hello without binder tmp_buf = Buffer(capacity=1024) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) # calculate early data key if hello.early_data: early_key = self._key_schedule_psk.derive_secret(b"c e traffic") self.update_traffic_key_cb( Direction.ENCRYPT, Epoch.ZERO_RTT, self._key_schedule_psk.cipher_suite, early_key, ) self._key_schedule_proxy = Key</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 2 <s>schedule_psk.cipher_suite, early_key, ) self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Direction() Epoch() State() Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyShareEntry = Tuple[int, bytes] OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[int], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[int]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[int]]=None, supported_groups: Optional[List[int]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) GROUP_TO_CURVE: Dict = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry ===========unchanged ref 1=========== push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[int] compression_methods: List[int] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[int]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[int]] = None supported_groups: Optional[List[int]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods: List[int] = [CompressionMethod.NULL]
aioquic.tls/Context._client_handle_certificate_verify
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<17>:<add> if self._verify_mode != ssl.CERT_NONE: <del> if self.verify_mode != ssl.CERT_NONE: <19>:<add> cadata=self._cadata, <del> cadata=self.cadata, <20>:<add> cafile=self._cafile, <del> cafile=self.cafile, <21>:<add> capath=self._capath, <del> capath=self.capath, <24>:<add> server_name=self._server_name, <del> server_name=self.server_name,
# module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: <0> verify = pull_certificate_verify(input_buf) <1> <2> assert verify.algorithm in self._signature_algorithms <3> <4> # check signature <5> try: <6> self._peer_certificate.public_key().verify( <7> verify.signature, <8> self.key_schedule.certificate_verify_data( <9> b"TLS 1.3, server CertificateVerify" <10> ), <11> *signature_algorithm_params(verify.algorithm), <12> ) <13> except InvalidSignature: <14> raise AlertDecryptError <15> <16> # check certificate <17> if self.verify_mode != ssl.CERT_NONE: <18> verify_certificate( <19> cadata=self.cadata, <20> cafile=self.cafile, <21> capath=self.capath, <22> certificate=self._peer_certificate, <23> chain=self._peer_certificate_chain, <24> server_name=self.server_name, <25> ) <26> <27> self.key_schedule.update_hash(input_buf.data) <28> <29> self._set_state(State.CLIENT_EXPECT_FINISHED) <30>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls AlertDecryptError(*args: object) State() verify_certificate(certificate: x509.Certificate, chain: List[x509.Certificate]=[], server_name: Optional[str]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None) -> None pull_certificate_verify(buf: Buffer) -> CertificateVerify signature_algorithm_params(signature_algorithm: int) -> Union[Tuple[ec.ECDSA], Tuple[padding.AsymmetricPadding, hashes.HashAlgorithm]] at: aioquic.tls.CertificateVerify algorithm: int signature: bytes at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.cadata: Optional[bytes] = None self.cafile: Optional[str] = None self.capath: Optional[str] = None self.key_schedule: Optional[KeySchedule] = None self.server_name: Optional[str] = None self.verify_mode = verify_mode self.verify_mode = ( ssl.CERT_REQUIRED if is_client else ssl.CERT_NONE ) self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._peer_certificate: Optional[x509.Certificate] = None self._peer_certificate_chain: List[x509.Certificate] = [] ===========unchanged ref 1=========== at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) self._peer_certificate_chain = [ x509.load_der_x509_certificate( certificate.certificates[i][0], backend=default_backend() ) for i in range(1, len(certificate.certificates)) ] at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule certificate_verify_data(context_string: bytes) -> bytes update_hash(data: bytes) -> None at: ssl CERT_NONE: int ===========changed ref 0=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, ) ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: key_share: List[KeyShareEntry] = [] supported_groups: List[int] = [] if Group.SECP256R1 in self._supported_groups: self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) key_share.append(encode_public_key(self._ec_private_key.public_key())) supported_groups.append(Group.SECP256R1) if Group.X25519 in self._supported_groups: self._x25519_private_key = x25519.X25519PrivateKey.generate() key_share.append(encode_public_key(self._x25519_private_key.public_key())) supported_groups.append(Group.X25519) assert len(key_share), "no key share entries" hello = ClientHello( random=self.client_random, session_id=self.session_id, cipher_suites=[int(x) for x in self._cipher_suites], compression_methods=self._compression_methods, + alpn_protocols=self._alpn_protocols, - alpn_protocols=self.alpn_protocols, key_share=key_share, psk_key_exchange_modes=self._psk_key_exchange_modes if (self.session_ticket or self.new_session_ticket_cb is not None) else None, + server_name=self._server_name, - server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) # PSK if self.session_ticket and self.session_ticket.is_valid: </s>
aioquic.quic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<2>:<add> alpn_protocols=self._configuration.alpn_protocols, <add> cadata=self._configuration.cadata, <add> cafile=self._configuration.cafile, <add> capath=self._configuration.capath, <5>:<add> server_name=self._configuration.server_name, <7>:<del> self.tls.alpn_protocols = self._configuration.alpn_protocols <8>:<del> self.tls.cadata = self._configuration.cadata <9>:<del> self.tls.cafile = self._configuration.cafile <10>:<del> self.tls.capath = self._configuration.capath <20>:<del> self.tls.server_name = self._configuration.server_name
# module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context( <2> is_client=self._is_client, <3> logger=self._logger, <4> max_early_data=None if self._is_client else MAX_EARLY_DATA, <5> verify_mode=self._configuration.verify_mode, <6> ) <7> self.tls.alpn_protocols = self._configuration.alpn_protocols <8> self.tls.cadata = self._configuration.cadata <9> self.tls.cafile = self._configuration.cafile <10> self.tls.capath = self._configuration.capath <11> self.tls.certificate = self._configuration.certificate <12> self.tls.certificate_chain = self._configuration.certificate_chain <13> self.tls.certificate_private_key = self._configuration.private_key <14> self.tls.handshake_extensions = [ <15> ( <16> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <17> self._serialize_transport_parameters(), <18> ) <19> ] <20> self.tls.server_name = self._configuration.server_name <21> <22> # TLS session resumption <23> session_ticket = self._configuration.session_ticket <24> if ( <25> self._is_client <26> and session_ticket is not None <27> and session_ticket.is_valid <28> and session_ticket.server_name == self._configuration.server_name <29> ): <30> self.tls.session_ticket = self._configuration.session_ticket <31> <32> # parse saved QUIC transport parameters - for 0-RTT <33> if session_ticket.max_early_data_size == MAX_EARLY_DATA: <34> for ext_type, ext_data in session_ticket.other_extensions: <35> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <36> self._parse_transport_parameters( <37> ext_data, from_</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 ) break # TLS callbacks self.tls.alpn_cb = self._alpn_handler if self._session_ticket_fetcher is not None: self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._handle_session_ticket self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.certificate_chain = certificates[1:] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.quic.configuration.QuicConfiguration.load_verify_locations self.cafile = cafile self.capath = capath self.cadata = cadata at: aioquic.quic.connection MAX_EARLY_DATA = 0xFFFFFFFF at: aioquic.quic.connection.QuicConnection _alpn_handler(alpn_protocol: str) -> None _handle_session_ticket(session_ticket: tls.SessionTicket) -> None ===========unchanged ref 1=========== _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._packet_number = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._version: Optional[int] = None self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] at: aioquic.quic.connection.QuicConnection.datagrams_to_send self._packet_number = builder.packet_number at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) at: aioquic.quic.crypto CryptoPair() ===========unchanged ref 2=========== at: aioquic.quic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool, version: int) -> None at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.quic.stream QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, verify_mode: Optional[int]=None) at: aioquic.tls.Context.__init__ self.certificate: Optional[x509.Certificate] = None self.certificate_chain: List[x509.Certificate] = [] self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite
tests.test_connection/QuicConnectionTest.test_connect_with_0rtt_bad_max_early_data
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<12>:<add> server.tls._max_early_data = 12345 <del> server.tls.max_early_data = 12345
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_0rtt_bad_max_early_data(self): <0> client_ticket = None <1> ticket_store = SessionTicketStore() <2> <3> def patch(server): <4> """ <5> Patch server's TLS initialization to set an invalid <6> max_early_data value. <7> """ <8> real_initialize = server._initialize <9> <10> def patched_initialize(peer_cid: bytes): <11> real_initialize(peer_cid) <12> server.tls.max_early_data = 12345 <13> <14> server._initialize = patched_initialize <15> <16> def save_session_ticket(ticket): <17> nonlocal client_ticket <18> client_ticket = ticket <19> <20> with client_and_server( <21> client_kwargs={"session_ticket_handler": save_session_ticket}, <22> server_kwargs={"session_ticket_handler": ticket_store.add}, <23> server_patch=patch, <24> ) as (client, server): <25> # check handshake failed <26> event = client.next_event() <27> self.assertIsNone(event) <28>
===========unchanged ref 0=========== at: tests.test_connection SessionTicketStore() client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_connection.SessionTicketStore add(ticket) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertIsNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, ) ===========changed ref 1=========== # module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: verify = pull_certificate_verify(input_buf) assert verify.algorithm in self._signature_algorithms # check signature try: self._peer_certificate.public_key().verify( verify.signature, self.key_schedule.certificate_verify_data( b"TLS 1.3, server CertificateVerify" ), *signature_algorithm_params(verify.algorithm), ) except InvalidSignature: raise AlertDecryptError # check certificate + if self._verify_mode != ssl.CERT_NONE: - if self.verify_mode != ssl.CERT_NONE: verify_certificate( + cadata=self._cadata, - cadata=self.cadata, + cafile=self._cafile, - cafile=self.cafile, + capath=self._capath, - capath=self.capath, certificate=self._peer_certificate, chain=self._peer_certificate_chain, + server_name=self._server_name, - server_name=self.server_name, ) self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_FINISHED) ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context( + alpn_protocols=self._configuration.alpn_protocols, + cadata=self._configuration.cadata, + cafile=self._configuration.cafile, + capath=self._configuration.capath, is_client=self._is_client, logger=self._logger, max_early_data=None if self._is_client else MAX_EARLY_DATA, + server_name=self._configuration.server_name, verify_mode=self._configuration.verify_mode, ) - self.tls.alpn_protocols = self._configuration.alpn_protocols - self.tls.cadata = self._configuration.cadata - self.tls.cafile = self._configuration.cafile - self.tls.capath = self._configuration.capath self.tls.certificate = self._configuration.certificate self.tls.certificate_chain = self._configuration.certificate_chain self.tls.certificate_private_key = self._configuration.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] - self.tls.server_name = self._configuration.server_name # TLS session resumption session_ticket = self._configuration.session_ticket if ( self._is_client and session_ticket is not None and session_ticket.is_valid and session_ticket.server_name == self._configuration.server_name ): self.tls.session_ticket = self._configuration.session_ticket # parse saved QUIC transport parameters - for 0-RTT if session_ticket.max_early_data_size == MAX_EARLY_DATA: for ext_type, ext_data in session_ticket.other_extensions</s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 <s>_data_size == MAX_EARLY_DATA: for ext_type, ext_data in session_ticket.other_extensions: if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: self._parse_transport_parameters( ext_data, from_session_ticket=True ) break # TLS callbacks self.tls.alpn_cb = self._alpn_handler if self._session_ticket_fetcher is not None: self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._handle_session_ticket self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } </s> ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 2 <s> self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0
tests.test_tls/ContextTest.create_client
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<0>:<add> client = Context( <del> client = Context(is_client=True) <1>:<add> alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True <add> ) <del> client.cafile = cafile
# module: tests.test_tls class ContextTest(TestCase): + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): - def create_client(self, cafile=SERVER_CACERTFILE): <0> client = Context(is_client=True) <1> client.cafile = cafile <2> client.handshake_extensions = [ <3> ( <4> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <5> CLIENT_QUIC_TRANSPORT_PARAMETERS, <6> ) <7> ] <8> self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) <9> return client <10>
===========unchanged ref 0=========== at: aioquic.tls State() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, verify_mode: Optional[int]=None) at: aioquic.tls.Context.__init__ self.cafile: Optional[str] = None self.handshake_extensions: List[Extension] = [] self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff0000110031000500048010000000060004801000000007000480100000000" b"4000481000000000100024258000800024064000a00010a" ) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_0rtt_bad_max_early_data(self): client_ticket = None ticket_store = SessionTicketStore() def patch(server): """ Patch server's TLS initialization to set an invalid max_early_data value. """ real_initialize = server._initialize def patched_initialize(peer_cid: bytes): real_initialize(peer_cid) + server.tls._max_early_data = 12345 - server.tls.max_early_data = 12345 server._initialize = patched_initialize def save_session_ticket(ticket): nonlocal client_ticket client_ticket = ticket with client_and_server( client_kwargs={"session_ticket_handler": save_session_ticket}, server_kwargs={"session_ticket_handler": ticket_store.add}, server_patch=patch, ) as (client, server): # check handshake failed event = client.next_event() self.assertIsNone(event) ===========changed ref 1=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, ) ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: verify = pull_certificate_verify(input_buf) assert verify.algorithm in self._signature_algorithms # check signature try: self._peer_certificate.public_key().verify( verify.signature, self.key_schedule.certificate_verify_data( b"TLS 1.3, server CertificateVerify" ), *signature_algorithm_params(verify.algorithm), ) except InvalidSignature: raise AlertDecryptError # check certificate + if self._verify_mode != ssl.CERT_NONE: - if self.verify_mode != ssl.CERT_NONE: verify_certificate( + cadata=self._cadata, - cadata=self.cadata, + cafile=self._cafile, - cafile=self.cafile, + capath=self._capath, - capath=self.capath, certificate=self._peer_certificate, chain=self._peer_certificate_chain, + server_name=self._server_name, - server_name=self.server_name, ) self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_FINISHED) ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context( + alpn_protocols=self._configuration.alpn_protocols, + cadata=self._configuration.cadata, + cafile=self._configuration.cafile, + capath=self._configuration.capath, is_client=self._is_client, logger=self._logger, max_early_data=None if self._is_client else MAX_EARLY_DATA, + server_name=self._configuration.server_name, verify_mode=self._configuration.verify_mode, ) - self.tls.alpn_protocols = self._configuration.alpn_protocols - self.tls.cadata = self._configuration.cadata - self.tls.cafile = self._configuration.cafile - self.tls.capath = self._configuration.capath self.tls.certificate = self._configuration.certificate self.tls.certificate_chain = self._configuration.certificate_chain self.tls.certificate_private_key = self._configuration.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] - self.tls.server_name = self._configuration.server_name # TLS session resumption session_ticket = self._configuration.session_ticket if ( self._is_client and session_ticket is not None and session_ticket.is_valid and session_ticket.server_name == self._configuration.server_name ): self.tls.session_ticket = self._configuration.session_ticket # parse saved QUIC transport parameters - for 0-RTT if session_ticket.max_early_data_size == MAX_EARLY_DATA: for ext_type, ext_data in session_ticket.other_extensions</s>
tests.test_tls/ContextTest.create_server
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<3>:<add> server = Context( <add> alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF <add> ) <del> server = Context(is_client=False, max_early_data=0xFFFFFFFF)
# module: tests.test_tls class ContextTest(TestCase): + def create_server(self, alpn_protocols=None): - def create_server(self): <0> configuration = QuicConfiguration(is_client=False) <1> configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <2> <3> server = Context(is_client=False, max_early_data=0xFFFFFFFF) <4> server.certificate = configuration.certificate <5> server.certificate_private_key = configuration.private_key <6> server.handshake_extensions = [ <7> ( <8> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <9> SERVER_QUIC_TRANSPORT_PARAMETERS, <10> ) <11> ] <12> self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO) <13> return server <14>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None ===========unchanged ref 1=========== load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None at: aioquic.quic.configuration.QuicConfiguration.load_cert_chain self.certificate = certificates[0] self.private_key = load_pem_private_key(fp.read(), password=password) at: aioquic.tls State() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, verify_mode: Optional[int]=None) at: aioquic.tls.Context.__init__ self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._set_state self.state = state at: tests.test_tls SERVER_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff00001104ff000011004500050004801000000006000480100000000700048" b"010000000040004810000000001000242580002001000000000000000000000" b"000000000000000800024064000a00010a" ) at: tests.utils SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") ===========unchanged ref 2=========== at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): - def create_client(self, cafile=SERVER_CACERTFILE): + client = Context( - client = Context(is_client=True) + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True + ) - client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_0rtt_bad_max_early_data(self): client_ticket = None ticket_store = SessionTicketStore() def patch(server): """ Patch server's TLS initialization to set an invalid max_early_data value. """ real_initialize = server._initialize def patched_initialize(peer_cid: bytes): real_initialize(peer_cid) + server.tls._max_early_data = 12345 - server.tls.max_early_data = 12345 server._initialize = patched_initialize def save_session_ticket(ticket): nonlocal client_ticket client_ticket = ticket with client_and_server( client_kwargs={"session_ticket_handler": save_session_ticket}, server_kwargs={"session_ticket_handler": ticket_store.add}, server_patch=patch, ) as (client, server): # check handshake failed event = client.next_event() self.assertIsNone(event) ===========changed ref 2=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, )
tests.test_tls/ContextTest.test_handshake_ecdsa_secp256r1
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<5>:<add> client = self.create_client( <del> client = self.create_client(cafile=None) <6>:<add> cadata=server.certificate.public_bytes(serialization.Encoding.PEM), <del> client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) <7>:<add> cafile=None, <add> )
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): <0> server = self.create_server() <1> server.certificate, server.certificate_private_key = generate_ec_certificate( <2> common_name="example.com", curve=ec.SECP256R1 <3> ) <4> <5> client = self.create_client(cafile=None) <6> client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) <7> <8> self._handshake(client, server) <9> <10> # check ALPN matches <11> self.assertEqual(client.alpn_negotiated, None) <12> self.assertEqual(server.alpn_negotiated, None) <13>
===========unchanged ref 0=========== at: aioquic.tls.Context.__init__ self.alpn_negotiated: Optional[str] = None self.cadata: Optional[bytes] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) at: tests.test_tls.ContextTest create_client(cafile=SERVER_CACERTFILE) create_client(self, cafile=SERVER_CACERTFILE) create_server() create_server(self) _handshake(client, server) at: tests.utils generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[]) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): - def create_client(self, cafile=SERVER_CACERTFILE): + client = Context( - client = Context(is_client=True) + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True + ) - client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): + def create_server(self, alpn_protocols=None): - def create_server(self): configuration = QuicConfiguration(is_client=False) configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + server = Context( + alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF + ) - server = Context(is_client=False, max_early_data=0xFFFFFFFF) server.certificate = configuration.certificate server.certificate_private_key = configuration.private_key server.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, SERVER_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO) return server ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_0rtt_bad_max_early_data(self): client_ticket = None ticket_store = SessionTicketStore() def patch(server): """ Patch server's TLS initialization to set an invalid max_early_data value. """ real_initialize = server._initialize def patched_initialize(peer_cid: bytes): real_initialize(peer_cid) + server.tls._max_early_data = 12345 - server.tls.max_early_data = 12345 server._initialize = patched_initialize def save_session_ticket(ticket): nonlocal client_ticket client_ticket = ticket with client_and_server( client_kwargs={"session_ticket_handler": save_session_ticket}, server_kwargs={"session_ticket_handler": ticket_store.add}, server_patch=patch, ) as (client, server): # check handshake failed event = client.next_event() self.assertIsNone(event) ===========changed ref 3=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, ) ===========changed ref 4=========== # module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: verify = pull_certificate_verify(input_buf) assert verify.algorithm in self._signature_algorithms # check signature try: self._peer_certificate.public_key().verify( verify.signature, self.key_schedule.certificate_verify_data( b"TLS 1.3, server CertificateVerify" ), *signature_algorithm_params(verify.algorithm), ) except InvalidSignature: raise AlertDecryptError # check certificate + if self._verify_mode != ssl.CERT_NONE: - if self.verify_mode != ssl.CERT_NONE: verify_certificate( + cadata=self._cadata, - cadata=self.cadata, + cafile=self._cafile, - cafile=self.cafile, + capath=self._capath, - capath=self.capath, certificate=self._peer_certificate, chain=self._peer_certificate_chain, + server_name=self._server_name, - server_name=self.server_name, ) self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_FINISHED)
tests.test_tls/ContextTest.test_handshake_with_alpn
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<0>:<del> client = self.create_client() <1>:<add> client = self.create_client(alpn_protocols=["hq-20"]) <del> client.alpn_protocols = ["hq-20"] <3>:<del> server = self.create_server() <4>:<add> server = self.create_server(alpn_protocols=["hq-20", "h3-20"]) <del> server.alpn_protocols = ["hq-20", "h3-20"]
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): <0> client = self.create_client() <1> client.alpn_protocols = ["hq-20"] <2> <3> server = self.create_server() <4> server.alpn_protocols = ["hq-20", "h3-20"] <5> <6> self._handshake(client, server) <7> <8> # check ALPN matches <9> self.assertEqual(client.alpn_negotiated, "hq-20") <10> self.assertEqual(server.alpn_negotiated, "hq-20") <11>
===========unchanged ref 0=========== at: aioquic.tls.Context.__init__ self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) at: tests.test_tls.ContextTest create_client(cafile=SERVER_CACERTFILE) create_client(self, cafile=SERVER_CACERTFILE) create_server() create_server(self) _handshake(client, server) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): - def create_client(self, cafile=SERVER_CACERTFILE): + client = Context( - client = Context(is_client=True) + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True + ) - client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): + def create_server(self, alpn_protocols=None): - def create_server(self): configuration = QuicConfiguration(is_client=False) configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + server = Context( + alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF + ) - server = Context(is_client=False, max_early_data=0xFFFFFFFF) server.certificate = configuration.certificate server.certificate_private_key = configuration.private_key server.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, SERVER_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO) return server ===========changed ref 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): server = self.create_server() server.certificate, server.certificate_private_key = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + client = self.create_client( - client = self.create_client(cafile=None) + cadata=server.certificate.public_bytes(serialization.Encoding.PEM), - client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) + cafile=None, + ) self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, None) self.assertEqual(server.alpn_negotiated, None) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_0rtt_bad_max_early_data(self): client_ticket = None ticket_store = SessionTicketStore() def patch(server): """ Patch server's TLS initialization to set an invalid max_early_data value. """ real_initialize = server._initialize def patched_initialize(peer_cid: bytes): real_initialize(peer_cid) + server.tls._max_early_data = 12345 - server.tls.max_early_data = 12345 server._initialize = patched_initialize def save_session_ticket(ticket): nonlocal client_ticket client_ticket = ticket with client_and_server( client_kwargs={"session_ticket_handler": save_session_ticket}, server_kwargs={"session_ticket_handler": ticket_store.add}, server_patch=patch, ) as (client, server): # check handshake failed event = client.next_event() self.assertIsNone(event) ===========changed ref 4=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, ) ===========changed ref 5=========== # module: aioquic.tls class Context: def _client_handle_certificate_verify(self, input_buf: Buffer) -> None: verify = pull_certificate_verify(input_buf) assert verify.algorithm in self._signature_algorithms # check signature try: self._peer_certificate.public_key().verify( verify.signature, self.key_schedule.certificate_verify_data( b"TLS 1.3, server CertificateVerify" ), *signature_algorithm_params(verify.algorithm), ) except InvalidSignature: raise AlertDecryptError # check certificate + if self._verify_mode != ssl.CERT_NONE: - if self.verify_mode != ssl.CERT_NONE: verify_certificate( + cadata=self._cadata, - cadata=self.cadata, + cafile=self._cafile, - cafile=self.cafile, + capath=self._capath, - capath=self.capath, certificate=self._peer_certificate, chain=self._peer_certificate_chain, + server_name=self._server_name, - server_name=self.server_name, ) self.key_schedule.update_hash(input_buf.data) self._set_state(State.CLIENT_EXPECT_FINISHED)
tests.test_tls/ContextTest.test_handshake_with_alpn_fail
Modified
aiortc~aioquic
ee9b855d5bf1d5c47cbc6fb7d57d97e3b73cea98
[tls] move configuration to keyword arguments
<0>:<del> client = self.create_client() <1>:<add> client = self.create_client(alpn_protocols=["hq-20"]) <del> client.alpn_protocols = ["hq-20"] <3>:<del> server = self.create_server() <4>:<add> server = self.create_server(alpn_protocols=["h3-20"]) <del> server.alpn_protocols = ["h3-20"]
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn_fail(self): <0> client = self.create_client() <1> client.alpn_protocols = ["hq-20"] <2> <3> server = self.create_server() <4> server.alpn_protocols = ["h3-20"] <5> <6> # send client hello <7> client_buf = create_buffers() <8> client.handle_message(b"", client_buf) <9> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <10> server_input = merge_buffers(client_buf) <11> self.assertGreaterEqual(len(server_input), 258) <12> self.assertLessEqual(len(server_input), 296) <13> reset_buffers(client_buf) <14> <15> # handle client hello <16> # send server hello, encrypted extensions, certificate, certificate verify, finished <17> server_buf = create_buffers() <18> with self.assertRaises(tls.AlertHandshakeFailure) as cm: <19> server.handle_message(server_input, server_buf) <20> self.assertEqual(str(cm.exception), "No common ALPN protocols") <21>
===========unchanged ref 0=========== at: aioquic.tls AlertHandshakeFailure(*args: object) State() at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest create_client(cafile=SERVER_CACERTFILE) create_client(self, cafile=SERVER_CACERTFILE) create_server() create_server(self) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None assertLessEqual(a: Any, b: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): - def create_client(self, cafile=SERVER_CACERTFILE): + client = Context( - client = Context(is_client=True) + alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True + ) - client.cafile = cafile client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): + def create_server(self, alpn_protocols=None): - def create_server(self): configuration = QuicConfiguration(is_client=False) configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + server = Context( + alpn_protocols=alpn_protocols, is_client=False, max_early_data=0xFFFFFFFF + ) - server = Context(is_client=False, max_early_data=0xFFFFFFFF) server.certificate = configuration.certificate server.certificate_private_key = configuration.private_key server.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, SERVER_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(server.state, State.SERVER_EXPECT_CLIENT_HELLO) return server ===========changed ref 2=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn(self): - client = self.create_client() + client = self.create_client(alpn_protocols=["hq-20"]) - client.alpn_protocols = ["hq-20"] - server = self.create_server() + server = self.create_server(alpn_protocols=["hq-20", "h3-20"]) - server.alpn_protocols = ["hq-20", "h3-20"] self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, "hq-20") self.assertEqual(server.alpn_negotiated, "hq-20") ===========changed ref 3=========== # module: tests.test_tls class ContextTest(TestCase): def test_handshake_ecdsa_secp256r1(self): server = self.create_server() server.certificate, server.certificate_private_key = generate_ec_certificate( common_name="example.com", curve=ec.SECP256R1 ) + client = self.create_client( - client = self.create_client(cafile=None) + cadata=server.certificate.public_bytes(serialization.Encoding.PEM), - client.cadata = server.certificate.public_bytes(serialization.Encoding.PEM) + cafile=None, + ) self._handshake(client, server) # check ALPN matches self.assertEqual(client.alpn_negotiated, None) self.assertEqual(server.alpn_negotiated, None) ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_0rtt_bad_max_early_data(self): client_ticket = None ticket_store = SessionTicketStore() def patch(server): """ Patch server's TLS initialization to set an invalid max_early_data value. """ real_initialize = server._initialize def patched_initialize(peer_cid: bytes): real_initialize(peer_cid) + server.tls._max_early_data = 12345 - server.tls.max_early_data = 12345 server._initialize = patched_initialize def save_session_ticket(ticket): nonlocal client_ticket client_ticket = ticket with client_and_server( client_kwargs={"session_ticket_handler": save_session_ticket}, server_kwargs={"session_ticket_handler": ticket_store.add}, server_patch=patch, ) as (client, server): # check handshake failed event = client.next_event() self.assertIsNone(event) ===========changed ref 5=========== # module: aioquic.tls class Context: def _build_session_ticket( self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, + server_name=self._server_name, - server_name=self.server_name, ticket=new_session_ticket.ticket, )
examples.http3_server/HttpRequestHandler.send
Modified
aiortc~aioquic
8c45dc8255673d5fa42194bb42208799d41e4e7e
[examples] fix typing warnings
<35>:<add> cast(HttpServerProtocol, self.protocol).http_event_received( <del> self.protocol.http_event_received(
# module: examples.http3_server class HttpRequestHandler: def send(self, message: Dict): <0> if message["type"] == "http.response.start": <1> self.connection.send_headers( <2> stream_id=self.stream_id, <3> headers=[ <4> (b":status", str(message["status"]).encode("ascii")), <5> (b"server", b"aioquic"), <6> (b"date", formatdate(time.time(), usegmt=True).encode()), <7> ] <8> + [(k, v) for k, v in message["headers"]], <9> ) <10> elif message["type"] == "http.response.body": <11> self.connection.send_data( <12> stream_id=self.stream_id, <13> data=message.get("body", b""), <14> end_stream=not message.get("more_body", False), <15> ) <16> elif message["type"] == "http.response.push" and isinstance( <17> self.connection, H3Connection <18> ): <19> request_headers = [ <20> (b":method", b"GET"), <21> (b":scheme", b"https"), <22> (b":authority", self.authority), <23> (b":path", message["path"].encode("utf8")), <24> ] + [(k, v) for k, v in message["headers"]] <25> <26> # send push promise <27> try: <28> push_stream_id = self.connection.send_push_promise( <29> stream_id=self.stream_id, headers=request_headers <30> ) <31> except NoAvailablePushIDError: <32> return <33> <34> # fake request <35> self.protocol.http_event_received( <36> HeadersReceived( <37> headers=request_headers, stream_ended=True, stream_id=push_stream_id <38> ) <39> ) <40> self.transmit() <41>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_push_promise(stream_id: int, headers: Headers) -> int send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers, end_stream: bool=False) -> None at: aioquic.h3.events HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.h3.events.HeadersReceived headers: Headers stream_id: int stream_ended: bool push_id: Optional[int] = None at: aioquic.h3.exceptions NoAvailablePushIDError(*args: object) at: email.utils formatdate(timeval: Optional[float]=..., localtime: bool=..., usegmt: bool=...) -> str at: examples.http3_server HttpServerProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: examples.http3_server.HttpRequestHandler.__init__ self.authority = authority self.connection = connection self.protocol = protocol self.stream_id = stream_id self.transmit = transmit at: examples.http3_server.HttpServerProtocol http_event_received(event: H3Event) -> None at: time time() -> float ===========unchanged ref 1=========== at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Dict = _alias(dict, 2, inst=False, name='Dict') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co]
examples.interop/test_http_3
Modified
aiortc~aioquic
8c45dc8255673d5fa42194bb42208799d41e4e7e
[examples] fix typing warnings
<25>:<add> http = cast(H3Connection, protocol._http) <27>:<add> http._decoder_bytes_received, <del> protocol._http._decoder_bytes_received, <28>:<add> http._decoder_bytes_sent, <del> protocol._http._decoder_bytes_sent, <32>:<add> http._encoder_bytes_received, <del> protocol._http._encoder_bytes_received, <33>:<add> http._encoder_bytes_sent, <del> protocol._http._encoder_bytes_sent, <36>:<add> http._decoder_bytes_received <del> protocol._http._decoder_bytes_received <37>:<add> and http._decoder_bytes_sent <del> and protocol._http._decoder_bytes_sent <38>:<add> and http._encoder_bytes_received <del> and protocol._http._encoder_bytes_received <39>:<add> and http._encoder_bytes_sent <del> and protocol._http._encoder_bytes_sent
# module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): <0> if server.path is None: <1> return <2> <3> configuration.alpn_protocols = H3_ALPN <4> async with connect( <5> server.host, <6> server.port, <7> configuration=configuration, <8> create_protocol=HttpClient, <9> ) as protocol: <10> protocol = cast(HttpClient, protocol) <11> <12> # perform HTTP request <13> events = await protocol.get( <14> "https://{}:{}{}".format(server.host, server.port, server.path) <15> ) <16> if events and isinstance(events[0], HeadersReceived): <17> server.result |= Result.D <18> server.result |= Result.three <19> <20> # perform another HTTP request to use QPACK dynamic tables <21> events = await protocol.get( <22> "https://{}:{}{}".format(server.host, server.port, server.path) <23> ) <24> if events and isinstance(events[0], HeadersReceived): <25> protocol._quic._logger.info( <26> "QPACK decoder bytes RX %d TX %d", <27> protocol._http._decoder_bytes_received, <28> protocol._http._decoder_bytes_sent, <29> ) <30> protocol._quic._logger.info( <31> "QPACK encoder bytes RX %d TX %d", <32> protocol._http._encoder_bytes_received, <33> protocol._http._encoder_bytes_sent, <34> ) <35> if ( <36> protocol._http._decoder_bytes_received <37> and protocol._http._decoder_bytes_sent <38> and protocol._http._encoder_bytes_received <39> and protocol._http._encoder_bytes_sent <40> ): <41> server.result |= Result.d <42>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection.__init__ self._decoder_bytes_received = 0 self._decoder_bytes_sent = 0 self._encoder_bytes_received = 0 self._encoder_bytes_sent = 0 at: aioquic.h3.connection.H3Connection._decode_headers self._decoder_bytes_sent += len(decoder) at: aioquic.h3.connection.H3Connection._encode_headers self._encoder_bytes_sent += len(encoder) at: aioquic.h3.connection.H3Connection._receive_stream_data_uni self._decoder_bytes_received += len(data) self._encoder_bytes_received += len(data) at: aioquic.h3.events HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) ===========unchanged ref 1=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None ===========unchanged ref 2=========== at: aioquic.quic.connection.QuicConnection.__init__ self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)), verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) verify_mode: Optional[int] = None at: http3_client HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] at: http3_client.HttpClient.__init__ self._http = H3Connection(self._quic) self._http: Optional[HttpConnection] = None self._http = H0Connection(self._quic) at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========changed ref 0=========== # module: examples.http3_server class HttpRequestHandler: def send(self, message: Dict): if message["type"] == "http.response.start": self.connection.send_headers( stream_id=self.stream_id, headers=[ (b":status", str(message["status"]).encode("ascii")), (b"server", b"aioquic"), (b"date", formatdate(time.time(), usegmt=True).encode()), ] + [(k, v) for k, v in message["headers"]], ) elif message["type"] == "http.response.body": self.connection.send_data( stream_id=self.stream_id, data=message.get("body", b""), end_stream=not message.get("more_body", False), ) elif message["type"] == "http.response.push" and isinstance( self.connection, H3Connection ): request_headers = [ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", self.authority), (b":path", message["path"].encode("utf8")), ] + [(k, v) for k, v in message["headers"]] # send push promise try: push_stream_id = self.connection.send_push_promise( stream_id=self.stream_id, headers=request_headers ) except NoAvailablePushIDError: return # fake request + cast(HttpServerProtocol, self.protocol).http_event_received( - self.protocol.http_event_received( HeadersReceived( headers=request_headers, stream_ended=True, stream_id=push_stream_id ) ) self.transmit()
aioquic.asyncio.protocol/QuicConnectionProtocol.__init__
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<3>:<add> self._connected = False <add> self._connected_waiter: Optional[asyncio.Future[None]] = None <del> self._connected_waiter = loop.create_future()
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): <0> loop = asyncio.get_event_loop() <1> <2> self._closed = asyncio.Event() <3> self._connected_waiter = loop.create_future() <4> self._loop = loop <5> self._ping_waiter: Optional[asyncio.Future[None]] = None <6> self._quic = quic <7> self._stream_readers: Dict[int, asyncio.StreamReader] = {} <8> self._timer: Optional[asyncio.TimerHandle] = None <9> self._timer_at: Optional[float] = None <10> self._transmit_task: Optional[asyncio.Handle] = None <11> self._transport: Optional[asyncio.DatagramTransport] = None <12> <13> # callbacks <14> self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None <15> self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None <16> self._connection_terminated_handler: Callable[[], None] = lambda: None <17> if stream_handler is not None: <18> self._stream_handler = stream_handler <19> else: <20> self._stream_handler = lambda r, w: None <21>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicConnectionIdHandler = Callable[[bytes], None] QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer self._timer = None self._timer_at = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._process_events self._connected_waiter = None self._connected = True self._ping_waiter = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._transmit_soon self._transmit_task = self._loop.call_soon(self.transmit) at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.protocol.QuicConnectionProtocol.ping self._ping_waiter = self._loop.create_future() at: aioquic.asyncio.protocol.QuicConnectionProtocol.transmit self._transmit_task = None self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: aioquic.asyncio.protocol.QuicConnectionProtocol.wait_connected self._connected_waiter = self._loop.create_future() at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: asyncio.events Handle(callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) ===========unchanged ref 1=========== TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: asyncio.streams StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.asyncio.protocol/QuicConnectionProtocol.ping
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<3>:<add> assert self._ping_waiter is None, "already awaiting ping" <del> assert self._ping_waiter is None, "already await a ping"
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: <0> """ <1> Ping the peer and wait for the response. <2> """ <3> assert self._ping_waiter is None, "already await a ping" <4> self._ping_waiter = self._loop.create_future() <5> self._quic.send_ping(id(self._ping_waiter)) <6> self.transmit() <7> await asyncio.shield(self._ping_waiter) <8>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol transmit() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic at: aioquic.asyncio.protocol.QuicConnectionProtocol._process_events self._ping_waiter = None at: aioquic.quic.connection.QuicConnection send_ping(uid: int) -> None at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() + self._connected = False + self._connected_waiter: Optional[asyncio.Future[None]] = None - self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transmit_task: Optional[asyncio.Handle] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.asyncio.protocol/QuicConnectionProtocol.wait_connected
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<3>:<add> assert self._connected_waiter is None, "already awaiting connected" <add> if not self._connected: <add> self._connected_waiter = self._loop.create_future() <add> await asyncio.shield(self._connected_waiter) <del> await asyncio.shield(self._connected_waiter)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def wait_connected(self) -> None: <0> """ <1> Wait for the TLS handshake to complete. <2> """ <3> await asyncio.shield(self._connected_waiter) <4>
===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter) ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() + self._connected = False + self._connected_waiter: Optional[asyncio.Future[None]] = None - self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transmit_task: Optional[asyncio.Handle] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.asyncio.protocol/QuicConnectionProtocol._process_events
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<8>:<add> if self._connected_waiter is not None: <add> waiter = self._connected_waiter <add> self._connected_waiter = None <del> if not self._connected_waiter.done(): <9>:<add> waiter.set_exception(ConnectionError) <del> self._connected_waiter.set_exception(ConnectionError) <12>:<add> if self._connected_waiter is not None: <add> waiter = self._connected_waiter <add> self._connected = True <add> self._connected_waiter = None <del> self._connected_waiter.set_result(None) <13>:<add> waiter.set_result(None)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _process_events(self) -> None: <0> event = self._quic.next_event() <1> while event is not None: <2> if isinstance(event, events.ConnectionIdIssued): <3> self._connection_id_issued_handler(event.connection_id) <4> elif isinstance(event, events.ConnectionIdRetired): <5> self._connection_id_retired_handler(event.connection_id) <6> elif isinstance(event, events.ConnectionTerminated): <7> self._connection_terminated_handler() <8> if not self._connected_waiter.done(): <9> self._connected_waiter.set_exception(ConnectionError) <10> self._closed.set() <11> elif isinstance(event, events.HandshakeCompleted): <12> self._connected_waiter.set_result(None) <13> elif isinstance(event, events.PingAcknowledged): <14> waiter = self._ping_waiter <15> self._ping_waiter = None <16> waiter.set_result(None) <17> self.quic_event_received(event) <18> event = self._quic.next_event() <19>
===========unchanged ref 0=========== at: _asyncio.Future set_exception(exception, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol transmit() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._closed = asyncio.Event() self._connected_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer now = max(self._timer_at, self._loop.time()) at: aioquic.asyncio.protocol.QuicConnectionProtocol.wait_connected self._connected_waiter = self._loop.create_future() at: aioquic.quic.connection.QuicConnection handle_timer(now: float) -> None next_event() -> Optional[events.QuicEvent] at: aioquic.quic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) set_exception(exception: Union[type, BaseException], /) -> None ===========unchanged ref 1=========== __iter__ = __await__ # make compatible with 'yield from'. at: asyncio.locks.Event set() -> None ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def wait_connected(self) -> None: """ Wait for the TLS handshake to complete. """ + assert self._connected_waiter is None, "already awaiting connected" + if not self._connected: + self._connected_waiter = self._loop.create_future() + await asyncio.shield(self._connected_waiter) - await asyncio.shield(self._connected_waiter) ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter) ===========changed ref 2=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() + self._connected = False + self._connected_waiter: Optional[asyncio.Future[None]] = None - self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transmit_task: Optional[asyncio.Handle] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
tests.test_asyncio/HighLevelTest.test_connect_and_serve
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<0>:<add> server, response = run( <add> asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) <del> server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) <1>:<add> )
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): <0> server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) <1> self.assertEqual(response, b"gnip") <2> server.close() <3>
===========unchanged ref 0=========== at: tests.test_asyncio handle_stream(reader, writer) at: tests.test_asyncio.HighLevelTest.run_server configuration = QuicConfiguration(is_client=False) ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 2=========== # module: tests.test_asyncio - def run_client( - host, - port=4433, - cadata=None, - cafile=SERVER_CACERTFILE, - configuration=None, - request=b"ping", - **kwargs - ): - if configuration is None: - configuration = QuicConfiguration(is_client=True) - configuration.load_verify_locations(cadata=cadata, cafile=cafile) - async with connect(host, port, configuration=configuration, **kwargs) as client: - reader, writer = await client.create_stream() - assert writer.can_write_eof() is True - assert writer.get_extra_info("stream_id") == 0 - - writer.write(request) - writer.write_eof() - - return await reader.read() - ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 4=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def wait_connected(self) -> None: """ Wait for the TLS handshake to complete. """ + assert self._connected_waiter is None, "already awaiting connected" + if not self._connected: + self._connected_waiter = self._loop.create_future() + await asyncio.shield(self._connected_waiter) - await asyncio.shield(self._connected_waiter) ===========changed ref 5=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter) ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() + self._connected = False + self._connected_waiter: Optional[asyncio.Future[None]] = None - self._connected_waiter = loop.create_future() self._loop = loop self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transmit_task: Optional[asyncio.Handle] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _process_events(self) -> None: event = self._quic.next_event() while event is not None: if isinstance(event, events.ConnectionIdIssued): self._connection_id_issued_handler(event.connection_id) elif isinstance(event, events.ConnectionIdRetired): self._connection_id_retired_handler(event.connection_id) elif isinstance(event, events.ConnectionTerminated): self._connection_terminated_handler() + if self._connected_waiter is not None: + waiter = self._connected_waiter + self._connected_waiter = None - if not self._connected_waiter.done(): + waiter.set_exception(ConnectionError) - self._connected_waiter.set_exception(ConnectionError) self._closed.set() elif isinstance(event, events.HandshakeCompleted): + if self._connected_waiter is not None: + waiter = self._connected_waiter + self._connected = True + self._connected_waiter = None - self._connected_waiter.set_result(None) + waiter.set_result(None) elif isinstance(event, events.PingAcknowledged): waiter = self._ping_waiter self._ping_waiter = None waiter.set_result(None) self.quic_event_received(event) event = self._quic.next_event()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_ec_certificate
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<4>:<add> self.run_server( <del> run_server( <11>:<add> self.run_client( <del> run_client(
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): <0> certificate, private_key = generate_ec_certificate(common_name="localhost") <1> <2> server, response = run( <3> asyncio.gather( <4> run_server( <5> configuration=QuicConfiguration( <6> certificate=certificate, <7> private_key=private_key, <8> is_client=False, <9> ) <10> ), <11> run_client( <12> "127.0.0.1", <13> cadata=certificate.public_bytes(serialization.Encoding.PEM), <14> cafile=None, <15> ), <16> ) <17> ) <18> <19> self.assertEqual(response, b"gnip") <20> server.close() <21>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.utils generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[]) run(coro) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) -
tests.test_asyncio/HighLevelTest.test_connect_and_serve_large
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<5>:<add> asyncio.gather( <add> self.run_server(), self.run_client("127.0.0.1", request=data) <del> asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) <6>:<add> )
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): <0> """ <1> Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. <2> """ <3> data = b"Z" * 2097152 <4> server, response = run( <5> asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) <6> ) <7> self.assertEqual(response, data) <8> server.close() <9>
===========unchanged ref 0=========== at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_ec_certificate certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( self.run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), self.run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) server, response = run( asyncio.gather( self.run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), self.run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 2=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( + self.run_server( - run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + self.run_client( - run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio - def run_client( - host, - port=4433, - cadata=None, - cafile=SERVER_CACERTFILE, - configuration=None, - request=b"ping", - **kwargs - ): - if configuration is None: - configuration = QuicConfiguration(is_client=True) - configuration.load_verify_locations(cadata=cadata, cafile=cafile) - async with connect(host, port, configuration=configuration, **kwargs) as client: - reader, writer = await client.create_stream() - assert writer.can_write_eof() is True - assert writer.get_extra_info("stream_id") == 0 - - writer.write(request) - writer.write_eof() - - return await reader.read() - ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 6=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def wait_connected(self) -> None: """ Wait for the TLS handshake to complete. """ + assert self._connected_waiter is None, "already awaiting connected" + if not self._connected: + self._connected_waiter = self._loop.create_future() + await asyncio.shield(self._connected_waiter) - await asyncio.shield(self._connected_waiter) ===========changed ref 7=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter)
tests.test_asyncio/HighLevelTest.test_connect_and_serve_without_client_configuration
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<4>:<add> server = run(self.run_server()) <del> server = run(run_server())
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): <0> async def run_client_without_config(host, port=4433): <1> async with connect(host, port) as client: <2> await client.ping() <3> <4> server = run(run_server()) <5> with self.assertRaises(ConnectionError): <6> run(run_client_without_config("127.0.0.1")) <7> server.close() <8>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 4=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( + self.run_server( - run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + self.run_client( - run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 6=========== # module: tests.test_asyncio - def run_client( - host, - port=4433, - cadata=None, - cafile=SERVER_CACERTFILE, - configuration=None, - request=b"ping", - **kwargs - ): - if configuration is None: - configuration = QuicConfiguration(is_client=True) - configuration.load_verify_locations(cadata=cadata, cafile=cafile) - async with connect(host, port, configuration=configuration, **kwargs) as client: - reader, writer = await client.create_stream() - assert writer.can_write_eof() is True - assert writer.get_extra_info("stream_id") == 0 - - writer.write(request) - writer.write_eof() - - return await reader.read() -
tests.test_asyncio/HighLevelTest.test_connect_and_serve_writelines
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<13>:<add> asyncio.gather(self.run_server(), run_client_writelines("127.0.0.1")) <del> asyncio.gather(run_server(), run_client_writelines("127.0.0.1"))
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): <0> async def run_client_writelines(host, port=4433): <1> configuration = QuicConfiguration(is_client=True) <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <3> async with connect(host, port, configuration=configuration) as client: <4> reader, writer = await client.create_stream() <5> assert writer.can_write_eof() is True <6> <7> writer.writelines([b"01234567", b"89012345"]) <8> writer.write_eof() <9> <10> return await reader.read() <11> <12> server, response = run( <13> asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) <14> ) <15> self.assertEqual(response, b"5432109876543210") <16> server.close() <17>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] ping() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None at: asyncio.streams.StreamWriter can_write_eof() -> bool at: tests.test_asyncio.HighLevelTest run_server(configuration=None) at: tests.utils run(coro) ===========unchanged ref 1=========== SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") at: unittest.case.TestCase assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 5=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( + self.run_server( - run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + self.run_client( - run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 7=========== # module: tests.test_asyncio - def run_client( - host, - port=4433, - cadata=None, - cafile=SERVER_CACERTFILE, - configuration=None, - request=b"ping", - **kwargs - ): - if configuration is None: - configuration = QuicConfiguration(is_client=True) - configuration.load_verify_locations(cadata=cadata, cafile=cafile) - async with connect(host, port, configuration=configuration, **kwargs) as client: - reader, writer = await client.create_stream() - assert writer.can_write_eof() is True - assert writer.get_extra_info("stream_id") == 0 - - writer.write(request) - writer.write_eof() - - return await reader.read() -
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_packet_loss
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<13>:<add> self.run_server( <add> configuration=server_configuration, stateless_retry=True <del> run_server(configuration=server_configuration, stateless_retry=True), <14>:<add> ), <add> self.run_client( <del> run_client(
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): <0> """ <1> This test ensures handshake success and stream data is successfully sent <2> and received in the presence of packet loss (randomized 25% in each direction). <3> """ <4> data = b"Z" * 65536 <5> <6> server_configuration = QuicConfiguration( <7> idle_timeout=300.0, is_client=False, quic_logger=QuicLogger() <8> ) <9> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <10> <11> server, response = run( <12> asyncio.gather( <13> run_server(configuration=server_configuration, stateless_retry=True), <14> run_client( <15> "127.0.0.1", <16> configuration=QuicConfiguration( <17> is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() <18> ), <19> request=data, <20> ), <21> ) <22> ) <23> self.assertEqual(response, data) <24> server.close() <25>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration load_cert_chain(certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[str]=None) -> None at: aioquic.quic.logger QuicLogger() at: asyncio.streams.StreamWriter writelines(data: Iterable[bytes]) -> None ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio sendto_with_loss(self, data, addr=None) at: tests.test_asyncio.HighLevelTest run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_writelines run_client_writelines(host, port=4433) at: tests.utils run(coro) SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 4=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) -
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_session_ticket
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<10>:<add> self.run_server(session_ticket_handler=store.add), <del> run_server(session_ticket_handler=store.add), <11>:<add> self.run_client("127.0.0.1", session_ticket_handler=save_ticket), <del> run_client("127.0.0.1", session_ticket_handler=save_ticket), <22>:<add> self.run_server(session_ticket_fetcher=store.pop), <del> run_server(session_ticket_fetcher=store.pop), <23>:<add> self.run_client( <del> run_client(
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_session_ticket(self): <0> client_ticket = None <1> store = SessionTicketStore() <2> <3> def save_ticket(t): <4> nonlocal client_ticket <5> client_ticket = t <6> <7> # first request <8> server, response = run( <9> asyncio.gather( <10> run_server(session_ticket_handler=store.add), <11> run_client("127.0.0.1", session_ticket_handler=save_ticket), <12> ) <13> ) <14> self.assertEqual(response, b"gnip") <15> server.close() <16> <17> self.assertIsNotNone(client_ticket) <18> <19> # second request <20> server, response = run( <21> asyncio.gather( <22> run_server(session_ticket_fetcher=store.pop), <23> run_client( <24> "127.0.0.1", <25> configuration=QuicConfiguration( <26> is_client=True, session_ticket=client_ticket <27> ), <28> ), <29> ) <30> ) <31> self.assertEqual(response, b"gnip") <32> server.close() <33>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.logger QuicLogger() ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio SessionTicketStore() at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_packet_loss data = b"Z" * 65536 server, response = run( asyncio.gather( self.run_server( configuration=server_configuration, stateless_retry=True ), self.run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() ), request=data, ), ) ) server, response = run( asyncio.gather( self.run_server( configuration=server_configuration, stateless_retry=True ), self.run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() ), request=data, ), ) ) at: tests.test_asyncio.SessionTicketStore add(ticket) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNotNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_sni
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<0>:<add> server, response = run( <add> asyncio.gather(self.run_server(), self.run_client("localhost")) <del> server, response = run(asyncio.gather(run_server(), run_client("localhost"))) <1>:<add> )
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): <0> server, response = run(asyncio.gather(run_server(), run_client("localhost"))) <1> self.assertEqual(response, b"gnip") <2> server.close() <3>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket store = SessionTicketStore() at: tests.test_asyncio.SessionTicketStore pop(label) ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 5=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( + self.run_server( - run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + self.run_client( - run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<1>:<add> asyncio.gather( <add> self.run_server(stateless_retry=True), self.run_client("127.0.0.1") <del> asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) <2>:<add> )
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): <0> server, response = run( <1> asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) <2> ) <3> self.assertEqual(response, b"gnip") <4> server.close() <5>
===========unchanged ref 0=========== at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_session_ticket client_ticket = None server, response = run( asyncio.gather( self.run_server(session_ticket_handler=store.add), self.run_client("127.0.0.1", session_ticket_handler=save_ticket), ) ) server, response = run( asyncio.gather( self.run_server(session_ticket_fetcher=store.pop), self.run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, session_ticket=client_ticket ), ), ) ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 5=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( + self.run_server( - run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + self.run_client( - run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( + asyncio.gather(self.run_server(), run_client_writelines("127.0.0.1")) - asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close() ===========changed ref 8=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("socket.socket.sendto", new_callable=lambda: sendto_with_loss) def test_connect_and_serve_with_packet_loss(self, mock_sendto): """ This test ensures handshake success and stream data is successfully sent and received in the presence of packet loss (randomized 25% in each direction). """ data = b"Z" * 65536 server_configuration = QuicConfiguration( idle_timeout=300.0, is_client=False, quic_logger=QuicLogger() ) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server, response = run( asyncio.gather( + self.run_server( + configuration=server_configuration, stateless_retry=True - run_server(configuration=server_configuration, stateless_retry=True), + ), + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, idle_timeout=300.0, quic_logger=QuicLogger() ), request=data, ), ) ) self.assertEqual(response, data) server.close()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad_original_connection_id
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<10>:<add> server = run( <add> self.run_server(create_protocol=create_protocol, stateless_retry=True) <del> server = run(run_server(create_protocol=create_protocol, stateless_retry=True)) <11>:<add> ) <12>:<add> run(self.run_client("127.0.0.1")) <del> run(run_client("127.0.0.1"))
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self): <0> """ <1> If the server's transport parameters do not have the correct <2> original_connection_id the connection fail. <3> """ <4> <5> def create_protocol(*args, **kwargs): <6> protocol = QuicConnectionProtocol(*args, **kwargs) <7> protocol._quic._original_connection_id = None <8> return protocol <9> <10> server = run(run_server(create_protocol=create_protocol, stateless_retry=True)) <11> with self.assertRaises(ConnectionError): <12> run(run_client("127.0.0.1")) <13> server.close() <14>
===========unchanged ref 0=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 1=========== at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 7=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) -
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_stateless_retry_bad
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<2>:<add> server = run(self.run_server(stateless_retry=True)) <del> server = run(run_server(stateless_retry=True)) <5>:<add> self.run_client( <del> run_client(
# module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): <0> mock_validate.side_effect = ValueError("Decryption failed.") <1> <2> server = run(run_server(stateless_retry=True)) <3> with self.assertRaises(ConnectionError): <4> run( <5> run_client( <6> "127.0.0.1", <7> configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), <8> ) <9> ) <10> server.close() <11>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol QuicConnectionProtocol(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.quic.connection.QuicConnection.__init__ self._original_connection_id = original_connection_id at: aioquic.quic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self): """ If the server's transport parameters do not have the correct original_connection_id the connection fail. """ def create_protocol(*args, **kwargs): protocol = QuicConnectionProtocol(*args, **kwargs) protocol._quic._original_connection_id = None return protocol + server = run( + self.run_server(create_protocol=create_protocol, stateless_retry=True) - server = run(run_server(create_protocol=create_protocol, stateless_retry=True)) + ) with self.assertRaises(ConnectionError): + run(self.run_client("127.0.0.1")) - run(run_client("127.0.0.1")) server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("127.0.0.1")) - server, response = run(asyncio.gather(run_server(), run_client("127.0.0.1"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_large(self): """ Transfer enough data to require raising MAX_DATA and MAX_STREAM_DATA. """ data = b"Z" * 2097152 server, response = run( + asyncio.gather( + self.run_server(), self.run_client("127.0.0.1", request=data) - asyncio.gather(run_server(), run_client("127.0.0.1", request=data)) + ) ) self.assertEqual(response, data) server.close() ===========changed ref 7=========== # module: tests.test_asyncio - def run_server(configuration=None, **kwargs): - if configuration is None: - configuration = QuicConfiguration(is_client=False) - configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) - return await serve( - host="::", - port="4433", - configuration=configuration, - stream_handler=handle_stream, - **kwargs - ) - ===========changed ref 8=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_ec_certificate(self): certificate, private_key = generate_ec_certificate(common_name="localhost") server, response = run( asyncio.gather( + self.run_server( - run_server( configuration=QuicConfiguration( certificate=certificate, private_key=private_key, is_client=False, ) ), + self.run_client( - run_client( "127.0.0.1", cadata=certificate.public_bytes(serialization.Encoding.PEM), cafile=None, ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 9=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_writelines(self): async def run_client_writelines(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: reader, writer = await client.create_stream() assert writer.can_write_eof() is True writer.writelines([b"01234567", b"89012345"]) writer.write_eof() return await reader.read() server, response = run( + asyncio.gather(self.run_server(), run_client_writelines("127.0.0.1")) - asyncio.gather(run_server(), run_client_writelines("127.0.0.1")) ) self.assertEqual(response, b"5432109876543210") server.close()
tests.test_asyncio/HighLevelTest.test_connect_and_serve_with_version_negotiation
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<2>:<add> self.run_server(), <del> run_server(), <3>:<add> self.run_client( <del> run_client(
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): <0> server, response = run( <1> asyncio.gather( <2> run_server(), <3> run_client( <4> "127.0.0.1", <5> configuration=QuicConfiguration( <6> is_client=True, <7> quic_logger=QuicLogger(), <8> supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], <9> ), <10> ), <11> ) <12> ) <13> self.assertEqual(response, b"gnip") <14> server.close() <15>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_stateless_retry_bad_original_connection_id server = run( self.run_server(create_protocol=create_protocol, stateless_retry=True) ) at: tests.utils run(coro) at: unittest.case.TestCase assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========unchanged ref 1=========== at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(self.run_server(stateless_retry=True)) - server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), ) ) server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self): """ If the server's transport parameters do not have the correct original_connection_id the connection fail. """ def create_protocol(*args, **kwargs): protocol = QuicConnectionProtocol(*args, **kwargs) protocol._quic._original_connection_id = None return protocol + server = run( + self.run_server(create_protocol=create_protocol, stateless_retry=True) - server = run(run_server(create_protocol=create_protocol, stateless_retry=True)) + ) with self.assertRaises(ConnectionError): + run(self.run_client("127.0.0.1")) - run(run_client("127.0.0.1")) server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close()
tests.test_asyncio/HighLevelTest.test_connect_timeout
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<2>:<add> self.run_client( <del> run_client(
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): <0> with self.assertRaises(ConnectionError): <1> run( <2> run_client( <3> "127.0.0.1", <4> port=4400, <5> configuration=QuicConfiguration(is_client=True, idle_timeout=5), <6> ) <7> ) <8>
===========unchanged ref 0=========== at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_stateless_retry_bad server = run(self.run_server(stateless_retry=True)) at: tests.utils run(coro) ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( + self.run_server(), - run_server(), + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(self.run_server(stateless_retry=True)) - server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), ) ) server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close()
tests.test_asyncio/HighLevelTest.test_change_connection_id
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<10>:<add> self.run_server(stateless_retry=False), <add> run_client_key_update("127.0.0.1"), <del> run_server(stateless_retry=False), run_client_key_update("127.0.0.1")
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): <0> async def run_client_key_update(host, port=4433): <1> configuration = QuicConfiguration(is_client=True) <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <3> async with connect(host, port, configuration=configuration) as client: <4> await client.ping() <5> client.change_connection_id() <6> await client.ping() <7> <8> server, _ = run( <9> asyncio.gather( <10> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <11> ) <12> ) <13> server.close() <14>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLogger() at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_asyncio.HighLevelTest run_client(host, port=4433, cadata=None, cafile=SERVER_CACERTFILE, configuration=None, request=b"ping", *, create_protocol: Optional[Callable]=QuicConnectionProtocol, stream_handler: Optional[QuicStreamHandler]=None, **kwds) at: tests.test_asyncio.HighLevelTest.test_connect_and_serve_with_version_negotiation server, response = run( asyncio.gather( self.run_server(), self.run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) server, response = run( asyncio.gather( self.run_server(), self.run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) at: tests.utils run(coro) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========unchanged ref 1=========== assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_client( + self, + host, + port=4433, + cadata=None, + cafile=SERVER_CACERTFILE, + configuration=None, + request=b"ping", + **kwargs + ): + if configuration is None: + configuration = QuicConfiguration(is_client=True) + configuration.load_verify_locations(cadata=cadata, cafile=cafile) + async with connect(host, port, configuration=configuration, **kwargs) as client: + # waiting for connected when connected returns immediately + await client.wait_connected() + + reader, writer = await client.create_stream() + self.assertEqual(writer.can_write_eof(), True) + self.assertEqual(writer.get_extra_info("stream_id"), 0) + + writer.write(request) + writer.write_eof() + + response = await reader.read() + + # waiting for closed when closed returns immediately + await client.wait_closed() + + return response + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", port=4400, configuration=QuicConfiguration(is_client=True, idle_timeout=5), ) ) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( + self.run_server(), - run_server(), + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(self.run_server(stateless_retry=True)) - server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), ) ) server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self): """ If the server's transport parameters do not have the correct original_connection_id the connection fail. """ def create_protocol(*args, **kwargs): protocol = QuicConnectionProtocol(*args, **kwargs) protocol._quic._original_connection_id = None return protocol + server = run( + self.run_server(create_protocol=create_protocol, stateless_retry=True) - server = run(run_server(create_protocol=create_protocol, stateless_retry=True)) + ) with self.assertRaises(ConnectionError): + run(self.run_client("127.0.0.1")) - run(run_client("127.0.0.1")) server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close()
tests.test_asyncio/HighLevelTest.test_key_update
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<10>:<add> self.run_server(stateless_retry=False), <add> run_client_key_update("127.0.0.1"), <del> run_server(stateless_retry=False), run_client_key_update("127.0.0.1")
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): <0> async def run_client_key_update(host, port=4433): <1> configuration = QuicConfiguration(is_client=True) <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <3> async with connect(host, port, configuration=configuration) as client: <4> await client.ping() <5> client.request_key_update() <6> await client.ping() <7> <8> server, _ = run( <9> asyncio.gather( <10> run_server(stateless_retry=False), run_client_key_update("127.0.0.1") <11> ) <12> ) <13> server.close() <14>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol change_connection_id() -> None ping() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None ===========unchanged ref 1=========== at: asyncio.tasks gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[ Tuple[Union[_T1, BaseException], Union[_T2, BaseException], Union[_T3, BaseException], Union[_T4, BaseException]] ] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], coro_or_future4: _FutureT[_T4], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2, _T3, _T4]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[Tuple[_T1, _T2]] gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: Optional[AbstractEventLoop]=..., return_exceptions: bool=...) -> Future[List[Any]] gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], *, loop: Optional[AbstractEventLoop]=..., return_exceptions: Literal[False]=...) -> Future[</s> ===========unchanged ref 2=========== at: tests.test_asyncio.HighLevelTest run_server(configuration=None) at: tests.utils run(coro) SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", port=4400, configuration=QuicConfiguration(is_client=True, idle_timeout=5), ) ) ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( + self.run_server(), - run_server(), + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(self.run_server(stateless_retry=True)) - server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), ) ) server.close()
tests.test_asyncio/HighLevelTest.test_ping
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<9>:<add> self.run_server(stateless_retry=False), run_client_ping("127.0.0.1") <del> run_server(stateless_retry=False), run_client_ping("127.0.0.1")
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_ping(self): <0> async def run_client_ping(host, port=4433): <1> configuration = QuicConfiguration(is_client=True) <2> configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <3> async with connect(host, port, configuration=configuration) as client: <4> await client.ping() <5> await client.ping() <6> <7> server, _ = run( <8> asyncio.gather( <9> run_server(stateless_retry=False), run_client_ping("127.0.0.1") <10> ) <11> ) <12> server.close() <13>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol request_key_update() -> None ping() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration load_verify_locations(cafile: Optional[str]=None, capath: Optional[str]=None, cadata: Optional[bytes]=None) -> None at: tests.test_asyncio.HighLevelTest.test_change_connection_id server, _ = run( asyncio.gather( self.run_server(stateless_retry=False), run_client_key_update("127.0.0.1"), ) ) at: tests.utils run(coro) ===========unchanged ref 1=========== SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ + assert self._ping_waiter is None, "already awaiting ping" - assert self._ping_waiter is None, "already await a ping" self._ping_waiter = self._loop.create_future() self._quic.send_ping(id(self._ping_waiter)) self.transmit() await asyncio.shield(self._ping_waiter) ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", port=4400, configuration=QuicConfiguration(is_client=True, idle_timeout=5), ) ) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): async def run_client_key_update(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: await client.ping() client.request_key_update() await client.ping() server, _ = run( asyncio.gather( + self.run_server(stateless_retry=False), + run_client_key_update("127.0.0.1"), - run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( + self.run_server(), - run_server(), + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(self.run_server(stateless_retry=True)) - server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), ) ) server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): async def run_client_key_update(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: await client.ping() client.change_connection_id() await client.ping() server, _ = run( asyncio.gather( + self.run_server(stateless_retry=False), + run_client_key_update("127.0.0.1"), - run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close()