dn-scribe commited on
Commit
fc338d2
·
unverified ·
1 Parent(s): 298adc6

feat: convers ghsa to cve

Browse files
Files changed (5) hide show
  1. .vscode/launch.json +8 -1
  2. README.md +20 -0
  3. app/ghsa2cve.py +15 -0
  4. app/main.py +22 -0
  5. app/utils.py +49 -0
.vscode/launch.json CHANGED
@@ -15,7 +15,14 @@
15
  "jinja": true,
16
  "justMyCode": false,
17
  "console": "internalConsole"
 
 
 
 
 
 
 
 
18
  }
19
  ]
20
  }
21
-
 
15
  "jinja": true,
16
  "justMyCode": false,
17
  "console": "internalConsole"
18
+ },
19
+ {
20
+ "name": "ghsa2cve",
21
+ "request": "launch",
22
+ "type": "debugpy",
23
+ "program": "${workspaceFolder}/app/ghsa2cve.py",
24
+ "args": ["GHSA-222v-cx2c-q2f5"],
25
+ "console": "internalConsole"
26
  }
27
  ]
28
  }
 
README.md CHANGED
@@ -18,9 +18,19 @@ Try it out [here](https://dn-scribe-cas.hf.space/viewer?cve_id=CVE-2024-9900)
18
  - `/healthz` → health check
19
  - `/raw?cve_id=<CVE-ID>&refresh=<true|false>` → Returns raw markdown report content. If the report does not exist, it generates it using OpenAI.
20
  - `/cve_info?cve_id=<CVE-ID>` → Fetches CVE information as JSON with error handling.
 
21
 
22
  Swagger available (on hugging face) [here](https://dn-scribe-cas.hf.space/docs)
23
 
 
 
 
 
 
 
 
 
 
24
  MCP Config for VSCode:
25
  Create a file named `mcp.json` in the `.vscode` folder of your project and add the following content:
26
 
@@ -39,3 +49,13 @@ Create a file named `mcp.json` in the `.vscode` folder of your project and add t
39
  }
40
  }
41
  ```
 
 
 
 
 
 
 
 
 
 
 
18
  - `/healthz` → health check
19
  - `/raw?cve_id=<CVE-ID>&refresh=<true|false>` → Returns raw markdown report content. If the report does not exist, it generates it using OpenAI.
20
  - `/cve_info?cve_id=<CVE-ID>` → Fetches CVE information as JSON with error handling.
21
+ - `/ghsa_to_cve?ghsa_id=<GHSA-ID>` → Converts GHSA ID to CVE ID using OpenAI.
22
 
23
  Swagger available (on hugging face) [here](https://dn-scribe-cas.hf.space/docs)
24
 
25
+ Example of converting GHSA to CVE:
26
+
27
+ ```bash
28
+ curl -X GET "http://127.0.0.1:8000/ghsa_to_cve?ghsa_id=GHSA-832w-fhmw-w4f4" -H "accept: application/json"
29
+
30
+ {"ghsa_id":"GHSA-832w-fhmw-w4f4","cve_id":"CVE-2024-55890"}
31
+ ```
32
+
33
+
34
  MCP Config for VSCode:
35
  Create a file named `mcp.json` in the `.vscode` folder of your project and add the following content:
36
 
 
49
  }
50
  }
51
  ```
52
+
53
+ Function to convert from GHSA to CVE-ID:
54
+
55
+ A function based on OpenAI gpt-4o-mini-search-preview with costs as follows:
56
+
57
+ - 25$ per 1k API calls
58
+ - 0.15$ per 1M input tokens
59
+ - 0.60$ per 1M output tokens
60
+
61
+ Since the whole transaction is about 40 tokens, the real cost is the per-api-call cost.
app/ghsa2cve.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import json
3
+ import asyncio
4
+
5
+ from utils import ghsa_to_cve
6
+
7
+ if __name__ == "__main__":
8
+ import sys
9
+ if len(sys.argv) != 2:
10
+ print("Usage: python ghsa_to_cve.py <GHSA_ID>")
11
+ sys.exit(1)
12
+
13
+ ghsa_id = sys.argv[1]
14
+ cve_id = asyncio.run(ghsa_to_cve(ghsa_id))
15
+ print(f"GHSA ID: {ghsa_id} -> CVE ID: {cve_id}")
app/main.py CHANGED
@@ -23,6 +23,7 @@ from app.utils import (
23
  generate_openai_stream,
24
  generate_openai_json,
25
  get_cve_info,
 
26
  )
27
 
28
  # Configure logging
@@ -203,6 +204,27 @@ async def cve_info(cve_id: str):
203
  raise HTTPException(status_code=500, detail="Internal server error.")
204
 
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  mcp = FastApiMCP(
207
  app,
208
  name="Get CVE Info", # Name for your MCP server
 
23
  generate_openai_stream,
24
  generate_openai_json,
25
  get_cve_info,
26
+ ghsa_to_cve,
27
  )
28
 
29
  # Configure logging
 
204
  raise HTTPException(status_code=500, detail="Internal server error.")
205
 
206
 
207
+ @app.get("/ghsa_to_cve", operation_id="ghsa_to_cve")
208
+ async def ghsa_to_cve_endpoint(ghsa_id: str):
209
+ """
210
+ Endpoint to convert a GHSA ID to a CVE ID.
211
+
212
+ Args:
213
+ ghsa_id (str): The GHSA identifier, e.g., "GHSA-1234-5678-9abc".
214
+
215
+ Returns:
216
+ JSONResponse: The corresponding CVE ID or an error message.
217
+ """
218
+ try:
219
+ cve_id = await ghsa_to_cve(ghsa_id)
220
+ return {"ghsa_id": ghsa_id, "cve_id": cve_id}
221
+ except ValueError as e:
222
+ raise HTTPException(status_code=400, detail=str(e))
223
+ except Exception as e:
224
+ logger.exception(f"Unexpected error while converting GHSA to CVE: {e}")
225
+ raise HTTPException(status_code=500, detail="Internal server error.")
226
+
227
+
228
  mcp = FastApiMCP(
229
  app,
230
  name="Get CVE Info", # Name for your MCP server
app/utils.py CHANGED
@@ -14,6 +14,13 @@ logger = logging.getLogger(__name__)
14
 
15
  logger = logging.getLogger("app.utils")
16
 
 
 
 
 
 
 
 
17
  async def get_cve_info(cve_id: str) -> dict | None:
18
  """
19
  Fetch CVE JSON data from cisagov/vulnrichment repo.
@@ -193,4 +200,46 @@ async def generate_openai_json(cve_id: str):
193
  logger.info(f"OpenAI JSON generated for cve_id={cve_id}, response length={len(text)}")
194
  return text
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
 
14
 
15
  logger = logging.getLogger("app.utils")
16
 
17
+ # Add a helper function to validate CVE-ID
18
+ def validate_cve_id(cve_id: str):
19
+ parts = cve_id.upper().split("-")
20
+ if len(parts) != 3 or not parts[2].isdigit():
21
+ return False
22
+ return True
23
+
24
  async def get_cve_info(cve_id: str) -> dict | None:
25
  """
26
  Fetch CVE JSON data from cisagov/vulnrichment repo.
 
200
  logger.info(f"OpenAI JSON generated for cve_id={cve_id}, response length={len(text)}")
201
  return text
202
 
203
+ async def ghsa_to_cve(ghsa_id: str) -> str:
204
+ """
205
+ Convert a GHSA ID to a CVE ID using OpenAI's API.
206
+
207
+ Args:
208
+ ghsa_id (str): The GHSA identifier, e.g., "GHSA-1234-5678-9abc".
209
+
210
+ Returns:
211
+ str: The corresponding CVE ID or an error message.
212
+ """
213
+ logger.info(f"Converting GHSA ID {ghsa_id} to CVE ID")
214
+ prompt = f"Convert the following GHSA ID to a CVE ID: {ghsa_id}. Return ONLY the CVE ID (or None if not found)."
215
+ model = "gpt-4o-search-preview"
216
+ response = await client.chat.completions.create(
217
+ model=model,
218
+ web_search_options={
219
+ "search_context_size": "low",
220
+ },
221
+ messages=[
222
+ {"role": "user", "content": prompt}
223
+ ],
224
+ )
225
+
226
+ # Log input and output token usage
227
+ logger.info(f"Input tokens: {response.usage.prompt_tokens}, Output tokens: {response.usage.completion_tokens}")
228
+
229
+ cve_id = response.choices[0].message.content
230
+
231
+ if not cve_id.strip():
232
+ logger.error(f"OpenAI returned an empty response for cve_id={cve_id}")
233
+ raise ValueError("OpenAI returned an empty response. Unable to generate JSON.")
234
+
235
+ cve_id = cve_id.rstrip() # Remove any leading/trailing whitespace
236
+ if validate_cve_id(cve_id): # Validate CVE-ID
237
+ logger.info(f"OpenAI converted GHSA {ghsa_id} to CVE ID {cve_id}")
238
+ return cve_id
239
+ else:
240
+ logger.error(f"OpenAI returned an invalid CVE ID: {cve_id}")
241
+ raise ValueError(f"OpenAI returned an invalid CVE ID: {cve_id}")
242
+
243
+
244
+
245