OMCHOKSI108 commited on
Commit
fd66e93
·
0 Parent(s):

deploy CodeSecAudit RAG service

Browse files
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY rag_service/ rag_service/
6
+
7
+ RUN pip install --no-cache-dir \
8
+ fastapi>=0.100.0 \
9
+ uvicorn[standard]>=0.20.0 \
10
+ sentence-transformers>=2.2.0 \
11
+ numpy>=1.24.0 \
12
+ requests>=2.31.0 \
13
+ pydantic>=2.0.0
14
+
15
+ ENV RAG_BUILD_ON_START=true
16
+ ENV RAG_DATASET_REPO=OMCHOKSI108/CodeSecAudit-RAG
17
+ ENV RAG_CORPUS_FILE=rag/rag_corpus.jsonl.gz
18
+ ENV RAG_EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
19
+ ENV RAG_INDEX_PATH=/tmp/codesec_rag_index
20
+
21
+ EXPOSE 7860
22
+
23
+ CMD ["uvicorn", "rag_service.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CodeSecAudit RAG Service
3
+ emoji: 🛡️
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # CodeSecAudit RAG Service
12
+
13
+ Remote RAG microservice for OWASP cheat sheet retrieval. Deployed as a Hugging Face Space with Docker SDK.
14
+
15
+ ## Deploy
16
+
17
+ 1. Create a new Space at https://huggingface.co/new-space
18
+ 2. Choose **Docker** (not Streamlit/Gradio)
19
+ 3. Set Space SDK to **Docker**
20
+ 4. Copy these files:
21
+ - `Dockerfile`
22
+ - `start.sh`
23
+ - The entire `rag_service/` directory
24
+
25
+ Or use the automated script: `python scripts/deploy_hf_rag_space.py`
26
+
27
+ 5. Add Secrets in Space Settings:
28
+
29
+ | Secret | Required | Description |
30
+ |---|---|---|
31
+ | `RAG_API_KEY` | **Production** | Shared API key for request auth. If empty, the service is **public** — anyone can search. |
32
+ | `RAG_DATASET_REPO` | No | HF dataset repo (default: `OMCHOKSI108/CodeSecAudit-RAG`) |
33
+ | `RAG_EMBEDDING_MODEL` | No | Sentence-transformer model (default: `sentence-transformers/all-MiniLM-L6-v2`) |
34
+
35
+ > **Production**: Always set `RAG_API_KEY`. Without it, the service is public and anyone with the URL can query your RAG index.
36
+
37
+ 6. Space will build and start on port 7860.
38
+
39
+ ## Health check
40
+
41
+ ```bash
42
+ curl https://your-space.hf.space/health
43
+ ```
44
+
45
+ ## Search
46
+
47
+ ```bash
48
+ curl -X POST https://your-space.hf.space/rag/search \
49
+ -H "Content-Type: application/json" \
50
+ -H "X-CodeSec-RAG-Key: your-key" \
51
+ -d '{"query":"sql injection prepared statements","top_k":3}'
52
+ ```
rag_service/README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CodeSecAudit RAG Service
2
+
3
+ Remote RAG microservice for OWASP cheat sheet retrieval.
4
+
5
+ ## Run locally
6
+
7
+ ```bash
8
+ pip install fastapi uvicorn sentence-transformers numpy requests pydantic
9
+ uvicorn rag_service.main:app --port 7860
10
+ ```
11
+
12
+ ## API
13
+
14
+ | Endpoint | Method | Description |
15
+ |---|---|---|
16
+ | `/` | GET | Service info |
17
+ | `/health` | GET | Health check |
18
+ | `/rag/search` | POST | Search RAG corpus |
19
+
20
+ ### POST /rag/search
21
+
22
+ ```json
23
+ {"query": "sql injection prepared statements", "top_k": 3}
24
+ ```
25
+
26
+ Set `RAG_API_KEY` env var and pass `X-CodeSec-RAG-Key` header to protect the endpoint.
rag_service/__init__.py ADDED
File without changes
rag_service/index.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import json
3
+ import logging
4
+ import os
5
+ import time
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import numpy as np
10
+ import requests
11
+ from sentence_transformers import SentenceTransformer
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ DEFAULT_DATASET_REPO = "OMCHOKSI108/CodeSecAudit-RAG"
16
+ DEFAULT_CORPUS_FILE = "rag/rag_corpus.jsonl.gz"
17
+ DEFAULT_EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
18
+
19
+
20
+ class RagIndex:
21
+ def __init__(self):
22
+ self.dataset_repo: str = os.getenv("RAG_DATASET_REPO", DEFAULT_DATASET_REPO)
23
+ self.corpus_file: str = os.getenv("RAG_CORPUS_FILE", DEFAULT_CORPUS_FILE)
24
+ self.embed_model_name: str = os.getenv("RAG_EMBEDDING_MODEL", DEFAULT_EMBED_MODEL)
25
+ self.max_results: int = int(os.getenv("RAG_MAX_RESULTS", "8"))
26
+
27
+ self._model: Optional[SentenceTransformer] = None
28
+ self._chunks: list[dict] = []
29
+ self._embeddings: Optional[np.ndarray] = None
30
+
31
+ @property
32
+ def model(self) -> SentenceTransformer:
33
+ if self._model is None:
34
+ logger.info("Loading embedding model: %s", self.embed_model_name)
35
+ self._model = SentenceTransformer(self.embed_model_name)
36
+ return self._model
37
+
38
+ def load_corpus(self) -> int:
39
+ url = f"https://huggingface.co/datasets/{self.dataset_repo}/resolve/main/{self.corpus_file}"
40
+ logger.info("Downloading corpus from %s", url)
41
+ resp = requests.get(url, timeout=120)
42
+ resp.raise_for_status()
43
+ raw = gzip.decompress(resp.content)
44
+ chunks = []
45
+ for line in raw.decode("utf-8").splitlines():
46
+ line = line.strip()
47
+ if line:
48
+ chunks.append(json.loads(line))
49
+ self._chunks = chunks
50
+ logger.info("Loaded %d chunks", len(chunks))
51
+ return len(chunks)
52
+
53
+ def build_index(self) -> None:
54
+ logger.info("Embedding %d chunks with %s ...", len(self._chunks), self.embed_model_name)
55
+ texts = [c.get("content", "") or c.get("text", "") for c in self._chunks]
56
+ self._embeddings = self.model.encode(texts, show_progress_bar=True)
57
+ logger.info("Index built: shape=%s", self._embeddings.shape)
58
+
59
+ def search(self, query: str, top_k: int = 3) -> list[dict]:
60
+ if self._embeddings is None or not self._chunks:
61
+ return []
62
+
63
+ k = min(top_k, self.max_results, len(self._chunks))
64
+ query_vec = self.model.encode([query])[0]
65
+ scores = np.dot(self._embeddings, query_vec) / (
66
+ np.linalg.norm(self._embeddings, axis=1) * np.linalg.norm(query_vec) + 1e-12
67
+ )
68
+ top_indices = np.argsort(scores)[::-1][:k]
69
+
70
+ results = []
71
+ for rank, idx in enumerate(top_indices, 1):
72
+ c = self._chunks[idx]
73
+ results.append({
74
+ "rank": rank,
75
+ "score": float(scores[idx]),
76
+ "title": c.get("title", ""),
77
+ "section_title": c.get("section_title", "") or c.get("section", ""),
78
+ "cwe_id": c.get("cwe_id", ""),
79
+ "content": c.get("content", "") or c.get("text", ""),
80
+ "source_file": c.get("source_file", "") or c.get("source", ""),
81
+ })
82
+ return results
83
+
84
+ @property
85
+ def is_loaded(self) -> bool:
86
+ return self._embeddings is not None
87
+
88
+ @property
89
+ def embedding_count(self) -> int:
90
+ return len(self._embeddings) if self._embeddings is not None else 0
91
+
92
+ @property
93
+ def document_count(self) -> int:
94
+ return len(self._chunks)
95
+
96
+ @property
97
+ def total_chunks(self) -> int:
98
+ return len(self._chunks)
rag_service/main.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import time
4
+
5
+ from fastapi import FastAPI, HTTPException, Request
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+
8
+ from rag_service.index import DEFAULT_DATASET_REPO, DEFAULT_EMBED_MODEL, RagIndex
9
+ from rag_service.schemas import (
10
+ SearchMetadata,
11
+ SearchRequest,
12
+ SearchResponse,
13
+ SearchResultItem,
14
+ )
15
+
16
+ logger = logging.getLogger(__name__)
17
+ logging.basicConfig(level=logging.INFO)
18
+
19
+ START_TIME = time.time()
20
+
21
+ app = FastAPI(
22
+ title="CodeSecAudit RAG Service",
23
+ description="Remote RAG retrieval service for OWASP cheat sheets",
24
+ version="0.6.0",
25
+ )
26
+
27
+ app.add_middleware(
28
+ CORSMiddleware,
29
+ allow_origins=["*"],
30
+ allow_credentials=True,
31
+ allow_methods=["*"],
32
+ allow_headers=["*"],
33
+ )
34
+
35
+ index = RagIndex()
36
+ api_key = os.getenv("RAG_API_KEY", "")
37
+
38
+
39
+ def _verify_key(request: Request) -> None:
40
+ if not api_key:
41
+ return
42
+ key = request.headers.get("X-CodeSec-RAG-Key", "")
43
+ if key != api_key:
44
+ raise HTTPException(status_code=401, detail="Unauthorized")
45
+
46
+
47
+ @app.on_event("startup")
48
+ def startup():
49
+ build_on_start = os.getenv("RAG_BUILD_ON_START", "true").lower() in ("1", "true", "yes")
50
+ if build_on_start:
51
+ logger.info("RAG_BUILD_ON_START=true — loading corpus and building index")
52
+ try:
53
+ n = index.load_corpus()
54
+ logger.info("Loaded %d chunks from dataset", n)
55
+ index.build_index()
56
+ logger.info("Index built successfully (%d chunks, %d embeddings)",
57
+ index.total_chunks, index.embedding_count)
58
+ except Exception as e:
59
+ logger.error("Failed to build index on startup: %s", e)
60
+ else:
61
+ logger.info("RAG_BUILD_ON_START=false — index not loaded")
62
+
63
+
64
+ @app.get("/")
65
+ def root():
66
+ return {
67
+ "service": "CodeSecAudit RAG Service",
68
+ "version": "0.6.0",
69
+ "status": "ok",
70
+ "embedding_model": os.getenv("RAG_EMBEDDING_MODEL", DEFAULT_EMBED_MODEL),
71
+ "dataset_repo": os.getenv("RAG_DATASET_REPO", DEFAULT_DATASET_REPO),
72
+ "total_chunks": index.total_chunks,
73
+ "api_key_protected": bool(api_key),
74
+ "uptime_seconds": int(time.time() - START_TIME),
75
+ }
76
+
77
+
78
+ @app.get("/health")
79
+ def health():
80
+ return {
81
+ "status": "ok",
82
+ "index_loaded": index.is_loaded,
83
+ "total_chunks": index.total_chunks,
84
+ "embedding_count": index.embedding_count,
85
+ "embedding_model": os.getenv("RAG_EMBEDDING_MODEL", DEFAULT_EMBED_MODEL),
86
+ "uptime_seconds": int(time.time() - START_TIME),
87
+ }
88
+
89
+
90
+ @app.post("/rag/search", response_model=SearchResponse)
91
+ def search(req: SearchRequest, request: Request):
92
+ _verify_key(request)
93
+ t0 = time.time()
94
+ results = index.search(req.query, top_k=req.top_k)
95
+ elapsed = (time.time() - t0) * 1000
96
+
97
+ return SearchResponse(
98
+ query=req.query,
99
+ top_k=req.top_k,
100
+ results=[SearchResultItem(**r) for r in results],
101
+ metadata=SearchMetadata(
102
+ embedding_model=os.getenv("RAG_EMBEDDING_MODEL", DEFAULT_EMBED_MODEL),
103
+ dataset_repo=os.getenv("RAG_DATASET_REPO", DEFAULT_DATASET_REPO),
104
+ total_chunks=index.total_chunks,
105
+ query_time_ms=round(elapsed, 2),
106
+ ),
107
+ )
rag_service/schemas.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+
3
+
4
+ class SearchRequest(BaseModel):
5
+ query: str = Field(min_length=1, description="Search query")
6
+ top_k: int = Field(default=3, ge=1, le=20, description="Number of results")
7
+
8
+
9
+ class SearchResultItem(BaseModel):
10
+ rank: int
11
+ score: float
12
+ title: str = ""
13
+ section_title: str = ""
14
+ cwe_id: str = ""
15
+ content: str = ""
16
+ source_file: str = ""
17
+
18
+
19
+ class SearchMetadata(BaseModel):
20
+ embedding_model: str
21
+ dataset_repo: str
22
+ total_chunks: int = 0
23
+ query_time_ms: float = 0.0
24
+
25
+
26
+ class SearchResponse(BaseModel):
27
+ query: str
28
+ top_k: int
29
+ results: list[SearchResultItem] = Field(default_factory=list)
30
+ metadata: SearchMetadata
start.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ echo "=== CodeSecAudit RAG Service ==="
5
+ echo "Dataset : ${RAG_DATASET_REPO:-OMCHOKSI108/CodeSecAudit-RAG}"
6
+ echo "Model : ${RAG_EMBEDDING_MODEL:-sentence-transformers/all-MiniLM-L6-v2}"
7
+ echo "Port : 7860"
8
+ echo ""
9
+
10
+ uvicorn rag_service.main:app --host 0.0.0.0 --port 7860