Skip to content
This repository was archived by the owner on Jun 5, 2025. It is now read-only.

Commit 49fefb0

Browse files
committed
Code cleanup
1 parent 615e5cc commit 49fefb0

File tree

2 files changed

+40
-68
lines changed

2 files changed

+40
-68
lines changed

src/codegate/providers/copilot/mapping.py

Lines changed: 1 addition & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ class CopilotProxyRoute(BaseModel):
1010
class CoPilotMappings(BaseSettings):
1111

1212
# Proxy routes configuration
13+
# This code is to ensure that incoming proxy requests are routed to the correct target
1314
PROXY_ROUTES: List[tuple[str, str]] = [
1415
("/github/login", "https://github.com/login"),
1516
("/api/github/user", "https://api.github.com"),
@@ -30,56 +31,6 @@ class CoPilotMappings(BaseSettings):
3031
("/v1", "https://copilot-proxy.githubusercontent.com/v1"),
3132
]
3233

33-
# Headers configuration
34-
PRESERVED_HEADERS: List[str] = [
35-
'authorization',
36-
'user-agent',
37-
'content-type',
38-
'accept',
39-
'accept-encoding',
40-
'connection',
41-
'x-github-token',
42-
'github-token',
43-
'x-request-id',
44-
'x-github-api-version',
45-
'openai-organization',
46-
'openai-intent',
47-
'openai-model',
48-
'editor-version',
49-
'editor-plugin-version',
50-
'vscode-sessionid',
51-
'vscode-machineid',
52-
]
53-
54-
REMOVED_HEADERS: List[str] = [
55-
'proxy-connection',
56-
'proxy-authenticate',
57-
'proxy-authorization',
58-
'connection',
59-
'keep-alive',
60-
'transfer-encoding',
61-
'te',
62-
'trailer',
63-
'proxy-authenticate',
64-
'upgrade',
65-
'expect',
66-
]
67-
68-
ENDPOINT_HEADERS: Dict[str, Dict[str, str]] = {
69-
'/v1/engines/copilot-codex/completions': {
70-
'Accept': 'application/json',
71-
'Content-Type': 'application/json',
72-
'Editor-Version': 'vscode/1.95.3',
73-
'Editor-Plugin-Version': 'copilot/1.246.0',
74-
'Openai-Organization': 'github-copilot',
75-
'Openai-Intent': 'copilot-ghost',
76-
'User-Agent': 'GithubCopilot/1.246.0',
77-
'Accept-Encoding': 'gzip, deflate, br',
78-
'X-Github-Api-Version': '2022-11-28',
79-
'Host': 'copilot-proxy.githubusercontent.com'
80-
}
81-
}
82-
8334
# Create settings instance
8435
mappings = CoPilotMappings()
8536

src/codegate/providers/copilot/provider.py

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from codegate.config import Config
1010
from codegate.ca.codegate_ca import CertificateAuthority
11-
from codegate.providers.copilot.mapping import VALIDATED_ROUTES
11+
from codegate.providers.copilot.mapping import VALIDATED_ROUTES
1212

1313
logger = structlog.get_logger("codegate")
1414

@@ -59,7 +59,7 @@ def extract_path(self, full_path: str) -> str:
5959
elif full_path.startswith('/'):
6060
return full_path.lstrip('/')
6161
return full_path
62-
62+
6363
def get_headers(self) -> Dict[str, str]:
6464
"""Get request headers as a dictionary"""
6565
logger.debug("Getting headers as dictionary fn: get_headers")
@@ -78,7 +78,7 @@ def get_headers(self) -> Dict[str, str]:
7878
headers_dict[name.strip().lower()] = value.strip()
7979
except ValueError:
8080
continue
81-
81+
8282
return headers_dict
8383
except Exception as e:
8484
logger.error(f"Error getting headers: {e}")
@@ -222,37 +222,58 @@ async def handle_http_request(self):
222222
logger.error(f"Error handling HTTP request: {e}")
223223
self.send_error_response(502, str(e).encode())
224224

225-
def data_received(self, data: bytes):
225+
def _check_buffer_size(self, new_data: bytes) -> bool:
226+
"""Check if adding new data would exceed the maximum buffer size"""
227+
return len(self.buffer) + len(new_data) <= MAX_BUFFER_SIZE
228+
229+
def _handle_parsed_headers(self) -> None:
230+
"""Handle the request based on parsed headers"""
231+
if self.method == 'CONNECT':
232+
logger.debug("Handling CONNECT request")
233+
self.handle_connect()
234+
else:
235+
logger.debug("Handling HTTP request")
236+
asyncio.create_task(self.handle_http_request())
237+
238+
def _forward_data_to_target(self, data: bytes) -> None:
239+
"""Forward data to target if connection is established"""
240+
if self.target_transport and not self.target_transport.is_closing():
241+
self.log_decrypted_data(data, "Client to Server")
242+
self.target_transport.write(data)
243+
244+
def data_received(self, data: bytes) -> None:
245+
"""Handle received data from the client"""
226246
logger.debug(f"Data received from {self.peername} fn: data_received")
227247

228248
try:
229-
if len(self.buffer) + len(data) > MAX_BUFFER_SIZE:
230-
logger.error("Request too large")
249+
# Check buffer size limit
250+
if not self._check_buffer_size(data):
251+
logger.error("Request exceeds maximum buffer size")
231252
self.send_error_response(413, b"Request body too large")
232253
return
233254

255+
# Append new data to buffer
234256
self.buffer.extend(data)
235257

236258
if not self.headers_parsed:
259+
# Try to parse headers
237260
self.headers_parsed = self.parse_headers()
238261
if not self.headers_parsed:
239262
return
240263

241-
if self.method == 'CONNECT':
242-
logger.debug("Handling CONNECT request")
243-
self.handle_connect()
244-
else:
245-
logger.debug("Handling HTTP request")
246-
asyncio.create_task(self.handle_http_request())
247-
elif self.target_transport and not self.target_transport.is_closing():
248-
self.log_decrypted_data(data, "Client to Server")
249-
self.target_transport.write(data)
264+
# Handle the request based on parsed headers
265+
self._handle_parsed_headers()
266+
else:
267+
# Forward data to target if headers are already parsed
268+
self._forward_data_to_target(data)
250269

270+
except asyncio.CancelledError:
271+
logger.warning("Operation cancelled")
272+
raise
251273
except Exception as e:
252-
logger.error(f"Error in data_received: {e}")
274+
logger.error(f"Error processing received data: {e}")
253275
self.send_error_response(502, str(e).encode())
254276

255-
256277
def handle_connect(self):
257278
'''
258279
This where requests are sent directly via the tunnel created during
@@ -294,7 +315,7 @@ def handle_connect(self):
294315
except Exception as e:
295316
logger.error(f"Error handling CONNECT: {e}")
296317
self.send_error_response(502, str(e).encode())
297-
318+
298319
def send_error_response(self, status: int, message: bytes):
299320
logger.debug(f"Sending error response: {status} {message} fn: send_error_response")
300321
response = (

0 commit comments

Comments
 (0)