HeshamXOR commited on
Commit
e83acd1
·
1 Parent(s): eedf401

Add partner malware analysis API

Browse files
PARTNER_API.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MalwareGuard Partner API
2
+
3
+ Use this API when another project needs a simple malware verdict for a URL or
4
+ Windows PE file.
5
+
6
+ ## Deployments
7
+
8
+ - Frontend on Vercel: `https://malwareguard-one.vercel.app`
9
+ - Backend on Hugging Face Space: `https://heshamxor-malwareguard.hf.space`
10
+ - Recommended public API base URL through Vercel: `https://malwareguard-one.vercel.app/api/partner`
11
+ - Direct backend API base URL: `https://heshamxor-malwareguard.hf.space/api/partner`
12
+
13
+ The Vercel app rewrites `/api/*` requests to the Hugging Face backend, so partner
14
+ projects can use the Vercel base URL and avoid browser CORS issues.
15
+
16
+ ## Authentication
17
+
18
+ Production deployments should set:
19
+
20
+ ```env
21
+ PARTNER_API_KEYS=shared-secret-key
22
+ ```
23
+
24
+ Partners must send the key in every request:
25
+
26
+ ```http
27
+ X-API-Key: shared-secret-key
28
+ ```
29
+
30
+ If partners call the API directly from a browser frontend, add their deployed
31
+ frontend origin to the backend `CORS_ORIGINS` environment variable.
32
+
33
+ If multiple groups need access, set comma-separated keys:
34
+
35
+ ```env
36
+ PARTNER_API_KEYS=group-a-key,group-b-key
37
+ ```
38
+
39
+ ## Health
40
+
41
+ ```bash
42
+ curl https://malwareguard-one.vercel.app/api/partner/health \
43
+ -H "X-API-Key: shared-secret-key"
44
+ ```
45
+
46
+ ## Analyze a URL
47
+
48
+ ```bash
49
+ curl -X POST https://malwareguard-one.vercel.app/api/partner/analyze-url \
50
+ -H "Content-Type: application/json" \
51
+ -H "X-API-Key: shared-secret-key" \
52
+ -d '{"url":"https://example.com/login"}'
53
+ ```
54
+
55
+ Response:
56
+
57
+ ```json
58
+ {
59
+ "analysis_type": "url",
60
+ "target": "https://example.com/login",
61
+ "verdict": "Malicious",
62
+ "is_malicious": true,
63
+ "malicious_score": 0.84,
64
+ "confidence_level": "High",
65
+ "threshold_used": 0.5,
66
+ "source": "malwareguard-url-hypermodel",
67
+ "details": {
68
+ "base_model_scores": {},
69
+ "top_signals": {}
70
+ }
71
+ }
72
+ ```
73
+
74
+ ## Analyze a File
75
+
76
+ Only Windows PE files are supported, such as `.exe`, `.dll`, and `.sys`.
77
+ Maximum file size is 50 MB.
78
+
79
+ ```bash
80
+ curl -X POST https://malwareguard-one.vercel.app/api/partner/analyze-file \
81
+ -H "X-API-Key: shared-secret-key" \
82
+ -F "file=@sample.exe"
83
+ ```
84
+
85
+ Response:
86
+
87
+ ```json
88
+ {
89
+ "analysis_type": "file",
90
+ "target": "sample.exe",
91
+ "verdict": "Malicious",
92
+ "is_malicious": true,
93
+ "malicious_score": 0.91,
94
+ "confidence_level": "High",
95
+ "threshold_used": 0.5,
96
+ "source": "malwareguard-ember-xgboost",
97
+ "sha256": "file_sha256_hash",
98
+ "file_size": 123456,
99
+ "feature_count": 2381,
100
+ "inference_time_ms": 3.2,
101
+ "details": {}
102
+ }
103
+ ```
backend/app/config.py CHANGED
@@ -76,8 +76,12 @@ class Settings(BaseSettings):
76
  rate_limit_chat: str = "20/minute"
77
  rate_limit_feedback: str = "20/minute"
78
  rate_limit_admin: str = "60/minute"
 
79
  rate_limit_prediction: str = "60/minute"
80
  rate_limit_virustotal: str = "10/minute"
 
 
 
81
 
82
 
83
  # CORS Origins
@@ -107,7 +111,7 @@ class Settings(BaseSettings):
107
  @property
108
  def effective_cors_origins(self) -> list[str]:
109
  if self.is_production:
110
- return PRODUCTION_CORS_ORIGINS
111
  return list(dict.fromkeys([*LOCAL_CORS_ORIGINS, *self.cors_origins]))
112
 
113
  @property
 
76
  rate_limit_chat: str = "20/minute"
77
  rate_limit_feedback: str = "20/minute"
78
  rate_limit_admin: str = "60/minute"
79
+ rate_limit_partner: str = "30/minute"
80
  rate_limit_prediction: str = "60/minute"
81
  rate_limit_virustotal: str = "10/minute"
82
+
83
+ # Partner API access
84
+ partner_api_keys: str = ""
85
 
86
 
87
  # CORS Origins
 
111
  @property
112
  def effective_cors_origins(self) -> list[str]:
113
  if self.is_production:
114
+ return list(dict.fromkeys([*PRODUCTION_CORS_ORIGINS, *self.cors_origins]))
115
  return list(dict.fromkeys([*LOCAL_CORS_ORIGINS, *self.cors_origins]))
116
 
117
  @property
backend/app/main.py CHANGED
@@ -19,7 +19,7 @@ from slowapi.errors import RateLimitExceeded
19
 
20
  from .config import settings
21
  from .rate_limit import limiter
22
- from .routers import admin, auth, predict, virustotal, chat, upload, url, feedback
23
  from .database import init_db
24
  from .services.ml_service import get_ml_service
25
  from .services.shap_service import get_shap_service
@@ -164,7 +164,7 @@ app.add_middleware(
164
  allow_origins=settings.effective_cors_origins,
165
  allow_credentials=True,
166
  allow_methods=["GET", "POST", "PATCH", "OPTIONS"],
167
- allow_headers=["Authorization", "Content-Type"],
168
  )
169
 
170
 
@@ -216,6 +216,7 @@ app.include_router(url.router)
216
  app.include_router(feedback.router)
217
  app.include_router(auth.router)
218
  app.include_router(admin.router)
 
219
 
220
 
221
  @app.get("/", tags=["root"])
 
19
 
20
  from .config import settings
21
  from .rate_limit import limiter
22
+ from .routers import admin, auth, partner, predict, virustotal, chat, upload, url, feedback
23
  from .database import init_db
24
  from .services.ml_service import get_ml_service
25
  from .services.shap_service import get_shap_service
 
164
  allow_origins=settings.effective_cors_origins,
165
  allow_credentials=True,
166
  allow_methods=["GET", "POST", "PATCH", "OPTIONS"],
167
+ allow_headers=["Authorization", "Content-Type", "X-API-Key"],
168
  )
169
 
170
 
 
216
  app.include_router(feedback.router)
217
  app.include_router(auth.router)
218
  app.include_router(admin.router)
219
+ app.include_router(partner.router)
220
 
221
 
222
  @app.get("/", tags=["root"])
backend/app/routers/partner.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Partner-facing malware analysis API.
2
+
3
+ These endpoints expose a stable, compact contract for external projects without
4
+ requiring them to understand MalwareGuard's internal dashboard/auth responses.
5
+ """
6
+
7
+ from typing import Any, Literal, Optional
8
+ import hashlib
9
+ import logging
10
+
11
+ from fastapi import APIRouter, Header, HTTPException, Request, UploadFile, File
12
+ from pydantic import BaseModel, Field, field_validator
13
+
14
+ from ..config import settings
15
+ from ..models.prediction import PredictionLabel
16
+ from ..rate_limit import limiter
17
+ from ..services.ember_features import LIEF_AVAILABLE, extract_features_and_lief
18
+ from ..services.ml_service import get_ml_service
19
+ from ..services.url_service import get_url_service
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ router = APIRouter(prefix="/api/partner", tags=["partner-api"])
24
+
25
+
26
+ class PartnerURLRequest(BaseModel):
27
+ """Request body for partner URL analysis."""
28
+
29
+ url: str = Field(..., min_length=3, max_length=4096)
30
+ threshold: Optional[float] = Field(None, ge=0.0, le=1.0)
31
+
32
+ @field_validator("url")
33
+ @classmethod
34
+ def clean_url(cls, value: str) -> str:
35
+ value = value.strip()
36
+ if not value:
37
+ raise ValueError("URL cannot be empty")
38
+ return value
39
+
40
+
41
+ class PartnerAnalysisResponse(BaseModel):
42
+ """Small public response shared by file and URL analysis."""
43
+
44
+ analysis_type: Literal["file", "url"]
45
+ target: str
46
+ verdict: PredictionLabel
47
+ is_malicious: bool
48
+ malicious_score: float = Field(..., ge=0.0, le=1.0)
49
+ confidence_level: str
50
+ threshold_used: float
51
+ source: str
52
+ sha256: Optional[str] = None
53
+ file_size: Optional[int] = None
54
+ feature_count: Optional[int] = None
55
+ inference_time_ms: Optional[float] = None
56
+ details: dict[str, Any] = Field(default_factory=dict)
57
+
58
+
59
+ def _configured_partner_keys() -> set[str]:
60
+ return {key.strip() for key in settings.partner_api_keys.split(",") if key.strip()}
61
+
62
+
63
+ def _verify_partner_key(x_api_key: str | None) -> None:
64
+ keys = _configured_partner_keys()
65
+ if not keys and not settings.is_production:
66
+ return
67
+ if not keys:
68
+ raise HTTPException(status_code=503, detail="Partner API keys are not configured")
69
+ if not x_api_key or x_api_key not in keys:
70
+ raise HTTPException(status_code=401, detail="Invalid or missing partner API key")
71
+
72
+
73
+ @router.get("/health")
74
+ async def partner_health(x_api_key: str | None = Header(default=None, alias="X-API-Key")):
75
+ """Health check for external partner integrations."""
76
+ _verify_partner_key(x_api_key)
77
+ return {
78
+ "status": "healthy",
79
+ "endpoints": {
80
+ "url": "/api/partner/analyze-url",
81
+ "file": "/api/partner/analyze-file",
82
+ },
83
+ }
84
+
85
+
86
+ @router.post("/analyze-url", response_model=PartnerAnalysisResponse)
87
+ @limiter.limit(settings.rate_limit_partner)
88
+ async def analyze_partner_url(
89
+ request: Request,
90
+ body: PartnerURLRequest,
91
+ x_api_key: str | None = Header(default=None, alias="X-API-Key"),
92
+ ):
93
+ """Analyze a URL and return a compact verdict for external consumers."""
94
+ _verify_partner_key(x_api_key)
95
+ url_service = get_url_service()
96
+ if not url_service.model_loaded:
97
+ raise HTTPException(status_code=503, detail="URL model not loaded")
98
+
99
+ threshold = body.threshold if body.threshold is not None else settings.prediction_threshold
100
+ result = url_service.predict(body.url, threshold=threshold)
101
+ verdict = PredictionLabel.MALICIOUS if result["prediction"] == "Malicious" else PredictionLabel.BENIGN
102
+
103
+ return PartnerAnalysisResponse(
104
+ analysis_type="url",
105
+ target=result["url"],
106
+ verdict=verdict,
107
+ is_malicious=verdict == PredictionLabel.MALICIOUS,
108
+ malicious_score=result["malicious_score"],
109
+ confidence_level=result["confidence_level"],
110
+ threshold_used=result["threshold_used"],
111
+ source="malwareguard-url-hypermodel",
112
+ inference_time_ms=result["inference_time_ms"],
113
+ details={
114
+ "base_model_scores": result.get("base_model_scores", {}),
115
+ "top_signals": result.get("top_signals", {}),
116
+ },
117
+ )
118
+
119
+
120
+ @router.post("/analyze-file", response_model=PartnerAnalysisResponse)
121
+ @limiter.limit(settings.rate_limit_partner)
122
+ async def analyze_partner_file(
123
+ request: Request,
124
+ file: UploadFile = File(..., description="Windows PE file to analyze"),
125
+ x_api_key: str | None = Header(default=None, alias="X-API-Key"),
126
+ ):
127
+ """Analyze a Windows PE file and return a compact verdict for partners."""
128
+ _verify_partner_key(x_api_key)
129
+ if not LIEF_AVAILABLE:
130
+ raise HTTPException(status_code=503, detail="PE parsing library is not available")
131
+
132
+ try:
133
+ content = await file.read()
134
+ except Exception as exc:
135
+ raise HTTPException(status_code=400, detail=f"Failed to read file: {exc}") from exc
136
+
137
+ if not content:
138
+ raise HTTPException(status_code=400, detail="Empty file uploaded")
139
+ if len(content) > 50 * 1024 * 1024:
140
+ raise HTTPException(status_code=400, detail="File too large. Maximum size is 50MB.")
141
+ if content[:2] != b"MZ":
142
+ raise HTTPException(status_code=400, detail="Invalid PE file. File must be a Windows executable.")
143
+
144
+ filename = file.filename or "unknown"
145
+ sha256 = hashlib.sha256(content).hexdigest()
146
+
147
+ try:
148
+ features, _, _ = extract_features_and_lief(content)
149
+ features_list = features.tolist()
150
+ except Exception as exc:
151
+ logger.error("Partner file feature extraction failed for %s: %s", filename, exc)
152
+ raise HTTPException(status_code=500, detail="Feature extraction failed") from exc
153
+
154
+ try:
155
+ prediction = get_ml_service().predict(features_list, sha256=sha256)
156
+ except Exception as exc:
157
+ logger.error("Partner file prediction failed for %s: %s", filename, exc)
158
+ raise HTTPException(status_code=500, detail="Prediction failed") from exc
159
+
160
+ return PartnerAnalysisResponse(
161
+ analysis_type="file",
162
+ target=filename,
163
+ verdict=prediction.prediction,
164
+ is_malicious=prediction.prediction == PredictionLabel.MALICIOUS,
165
+ malicious_score=prediction.probability,
166
+ confidence_level=prediction.confidence.value,
167
+ threshold_used=prediction.threshold_used,
168
+ source="malwareguard-ember-xgboost",
169
+ sha256=sha256,
170
+ file_size=len(content),
171
+ feature_count=len(features_list),
172
+ inference_time_ms=prediction.inference_time_ms,
173
+ )