-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
151 lines (121 loc) · 4.31 KB
/
Copy pathapi.py
File metadata and controls
151 lines (121 loc) · 4.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
REST API for MacroScanner - Bridges Python scanning logic with Java FX frontend
"""
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import os
import tempfile
import json
import logging
from pathlib import Path
from scanner.scan_service import scan_file
from utils.file_validator import validate_file
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = FastAPI(
title="MacroScanner API",
description="Scans Microsoft Office documents for potentially dangerous macros",
version="1.0.0"
)
UPLOAD_DIR = tempfile.gettempdir()
@app.get("/health")
async def health_check():
return {
"status": "healthy",
"service": "MacroScanner",
"version": "1.0.0"
}
@app.post("/api/v1/scan/file-path")
async def scan_file_path(file_path: str):
try:
logger.info(f"Scanning file: {file_path}")
if not os.path.exists(file_path):
raise HTTPException(status_code=400, detail="File does not exist")
if not os.path.isfile(file_path):
raise HTTPException(status_code=400, detail="Path is not a file")
result = scan_file(file_path)
logger.info(f"Scan completed: {result.get('title')}")
return JSONResponse(content=result, status_code=200)
except Exception as e:
logger.error(f"Scan error: {str(e)}", exc_info=True)
return JSONResponse(
content={
"risk_level": "ERROR",
"title": "Scan Error",
"message": str(e),
"recommendation": "Please try again or contact support"
},
status_code=500
)
@app.post("/api/v1/scan/upload")
async def scan_uploaded_file(file: UploadFile = File(...)):
temp_file_path = None
try:
logger.info(f"Processing uploaded file: {file.filename}")
_, file_extension = os.path.splitext(file.filename)
file_extension = file_extension.lower()
SUPPORTED_EXTENSIONS = {".doc", ".docx", ".docm", ".xls", ".xlsm", ".pptm"}
if file_extension not in SUPPORTED_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"Unsupported file type: {file_extension}"
)
temp_file_path = os.path.join(UPLOAD_DIR, file.filename)
with open(temp_file_path, "wb") as f:
content = await file.read()
f.write(content)
result = scan_file(temp_file_path)
logger.info(f"Scan completed: {result.get('title')}")
return JSONResponse(content=result, status_code=200)
except HTTPException:
raise
except Exception as e:
logger.error(f"Upload scan error: {str(e)}", exc_info=True)
return JSONResponse(
content={
"risk_level": "ERROR",
"title": "Scan Error",
"message": str(e),
"recommendation": "Please try again or contact support"
},
status_code=500
)
finally:
if temp_file_path and os.path.exists(temp_file_path):
try:
os.remove(temp_file_path)
logger.info(f"Cleaned up temp file: {temp_file_path}")
except Exception as e:
logger.warning(f"Could not delete temp file: {e}")
@app.post("/api/v1/validate/file")
async def validate_file_endpoint(file_path: str):
try:
is_valid, error = validate_file(file_path)
if is_valid:
return {
"valid": True,
"message": "File is valid and can be scanned"
}
else:
return JSONResponse(
content={
"valid": False,
"message": error
},
status_code=400
)
except Exception as e:
logger.error(f"Validation error: {str(e)}")
return JSONResponse(
content={
"valid": False,
"message": str(e)
},
status_code=500
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")