Ajuste para API privilegiada
This commit is contained in:
1 parent
8e9f080f73
commit
10efdab397
6 files changed
+171
-106
No files matched your search
+4
-1
@@ -11,8 +11,11 @@ COPY assets /app/assets/
|
||||
EXPOSE 8080
|
||||
|
||||
# Definir variable de entorno por defecto (puede sobreescribirse en K8s/OpenShift/Docker)
|
||||
ENV HARBOR_URL="https://tu-harbor-corporativo.com"
|
||||
ENV HARBOR_URL="https://harbor.tu-dominio.com"
|
||||
ENV HARBOR_ROBOT="admin"
|
||||
ENV HARBOR_TOKEN="tu-token-super-secreto-aqui"
|
||||
|
||||
# Ejecutar el proxy de Python
|
||||
CMD ["python3", "proxy-harbor.py"]
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
docker run --env-file .env -p 8080:8080 harbor-security-portal
|
||||
@@ -1,23 +1,31 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: harbor-security-portal
|
||||
name: harbor-vuln-portal
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: harbor-security-portal
|
||||
app: harbor-vuln-portal
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: harbor-security-portal
|
||||
app: harbor-vuln-portal
|
||||
spec:
|
||||
containers:
|
||||
- name: portal
|
||||
image: tu-registro-interno/harbor-security-portal:latest
|
||||
- name: proxy
|
||||
image: tu-registry/harbor-vuln-portal:latest
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
env:
|
||||
- name: HARBOR_URL
|
||||
value: "https://harbor.tu-empresa.com"
|
||||
value: "https://harbor.tu-dominio.com"
|
||||
- name: HARBOR_ROBOT
|
||||
value: "usuario"
|
||||
- name: HARBOR_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: harbor-robot-secret # Recomendado usar Secrets en K8s/OpenShift
|
||||
key: token
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
HARBOR_URL=https://harbor.tu-dominio.com
|
||||
HARBOR_ROBOT=admin
|
||||
HARBOR_TOKEN=tu-token-super-secreto-aqui
|
||||
|
||||
+87
-75
@@ -34,21 +34,15 @@
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-3">
|
||||
<div id="connection-badge" class="flex items-center space-x-2 bg-amber-500/10 border border-amber-500/20 text-amber-400 px-3 py-1.5 rounded-md text-xs font-medium">
|
||||
<div id="connection-badge" class="flex items-center space-x-2 bg-amber-500/10 border border-amber-500/20 text-amber-400 px-3.5 py-2 rounded-lg text-xs font-medium">
|
||||
<span id="connection-dot" class="w-2 h-2 rounded-full bg-amber-400 animate-pulse"></span>
|
||||
<span id="connection-status-text">Sin Autenticar</span>
|
||||
<span id="connection-status-text">Comprobando conexión...</span>
|
||||
</div>
|
||||
|
||||
<!-- Botón de Exportar a Excel (CSV) -->
|
||||
<button onclick="exportToCsv()" class="flex items-center space-x-2 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-3.5 py-2 rounded-lg text-sm font-medium transition">
|
||||
<i class="fa-solid fa-file-excel text-emerald-400"></i>
|
||||
<span>Exportar Excel</span>
|
||||
</button>
|
||||
|
||||
<button onclick="openConfigModal()" class="flex items-center space-x-2 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 px-3.5 py-2 rounded-lg text-sm font-medium transition">
|
||||
<i class="fa-solid fa-key text-sky-400"></i>
|
||||
<span>Credenciales</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -77,6 +71,26 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mini Gráfica de Barras Apiladas (Distribución de Severidad) -->
|
||||
<div class="bg-slate-900 border border-slate-800 rounded-xl p-4 shadow-sm space-y-2">
|
||||
<div class="flex justify-between items-center text-xs text-slate-400 font-medium">
|
||||
<span>Distribución de Severidad de Vulnerabilidades</span>
|
||||
<span id="chart-fixable-label" class="text-slate-500">Correcciones (Fixable): Cargando...</span>
|
||||
</div>
|
||||
<div class="w-full h-3 bg-slate-950 rounded-full overflow-hidden flex border border-slate-800">
|
||||
<div id="bar-critical" class="bg-red-500 h-full transition-all duration-500" style="width: 0%" title="Críticas"></div>
|
||||
<div id="bar-high" class="bg-orange-500 h-full transition-all duration-500" style="width: 0%" title="Altas"></div>
|
||||
<div id="bar-medium" class="bg-yellow-500 h-full transition-all duration-500" style="width: 0%" title="Medias"></div>
|
||||
<div id="bar-low" class="bg-blue-400 h-full transition-all duration-500" style="width: 0%" title="Bajas"></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-4 pt-1 text-[11px] text-slate-400">
|
||||
<div class="flex items-center gap-1.5"><span class="w-2 h-2 rounded-full bg-red-500"></span> Críticas</div>
|
||||
<div class="flex items-center gap-1.5"><span class="w-2 h-2 rounded-full bg-orange-500"></span> Altas</div>
|
||||
<div class="flex items-center gap-1.5"><span class="w-2 h-2 rounded-full bg-yellow-500"></span> Medias</div>
|
||||
<div class="flex items-center gap-1.5"><span class="w-2 h-2 rounded-full bg-blue-400"></span> Bajas</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Panel de Filtros API -->
|
||||
<div class="bg-slate-900 border border-slate-800 rounded-xl p-5 shadow-sm space-y-4">
|
||||
<h2 class="text-lg font-semibold text-white flex items-center gap-2 border-b border-slate-800 pb-3">
|
||||
@@ -104,7 +118,7 @@
|
||||
<div class="flex items-end gap-2 pt-5 md:pt-0">
|
||||
<button onclick="applyFilters(1)" class="bg-sky-500 hover:bg-sky-600 text-white font-semibold text-sm px-6 py-2.5 rounded-lg flex items-center gap-2 transition shadow-md">
|
||||
<i id="search-btn-icon" class="fa-solid fa-magnifying-glass"></i>
|
||||
<span>SEARCH API</span>
|
||||
<span>BUSCAR</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -147,7 +161,7 @@
|
||||
<div id="empty-state" class="py-16 text-center space-y-4">
|
||||
<div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-800 text-slate-400 mb-2"><i class="fa-solid fa-magnifying-glass text-2xl"></i></div>
|
||||
<h3 class="text-lg font-medium text-slate-300">Realiza una búsqueda para consultar la API</h3>
|
||||
<p class="text-sm text-slate-500">Selecciona un filtro superior y pulsa SEARCH API.</p>
|
||||
<p class="text-sm text-slate-500">Selecciona un filtro superior y pulsa BUSCAR.</p>
|
||||
</div>
|
||||
|
||||
<!-- Controles de Paginación -->
|
||||
@@ -167,22 +181,7 @@
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Modal Config (Conectar) -->
|
||||
<div id="config-modal" class="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm hidden flex items-center justify-center p-4">
|
||||
<div class="bg-slate-900 border border-slate-800 rounded-xl w-full max-w-lg shadow-2xl p-6 space-y-5">
|
||||
<h3 class="text-lg font-bold text-white flex items-center gap-2"><i class="fa-solid fa-key text-sky-400"></i> Autenticación Harbor</h3>
|
||||
<div class="space-y-4">
|
||||
<div><label class="block text-xs text-slate-400 mb-1">Usuario</label><input type="text" id="config-harbor-user" class="w-full bg-slate-800 border border-slate-700 text-sm rounded-lg p-2.5 outline-none font-mono"></div>
|
||||
<div><label class="block text-xs text-slate-400 mb-1">Token / Contraseña</label><input type="password" id="config-harbor-token" class="w-full bg-slate-800 border border-slate-700 text-sm rounded-lg p-2.5 outline-none font-mono"></div>
|
||||
</div>
|
||||
<div class="flex justify-end gap-3 border-t border-slate-800 pt-4">
|
||||
<button onclick="closeConfigModal()" class="px-4 py-2 bg-slate-800 text-slate-300 rounded-lg text-sm">Cancelar</button>
|
||||
<button onclick="saveConfig()" class="px-5 py-2 bg-sky-500 hover:bg-sky-600 text-white rounded-lg text-sm font-semibold transition">Conectar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal CVE con Alineación Izquierda Corregida -->
|
||||
<!-- Modal CVE -->
|
||||
<div id="cve-modal" class="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm hidden flex items-center justify-center p-4">
|
||||
<div class="bg-slate-900 border border-slate-800 rounded-xl w-full max-w-2xl shadow-2xl p-6 space-y-5">
|
||||
<div class="flex justify-between items-start border-b border-slate-800 pb-3">
|
||||
@@ -214,7 +213,6 @@
|
||||
|
||||
<div class="space-y-2">
|
||||
<p class="text-xs font-semibold uppercase text-slate-400">Ubicación del Artefacto en Harbor</p>
|
||||
<!-- Clases text-left, break-all para asegurar alineación izquierda limpia -->
|
||||
<div id="modal-cve-location" class="bg-slate-950 p-4 rounded-lg border border-slate-800 text-xs font-mono text-slate-300 space-y-1 text-left break-all"></div>
|
||||
</div>
|
||||
|
||||
@@ -226,28 +224,72 @@
|
||||
|
||||
<script>
|
||||
let filteredVulnerabilities = [];
|
||||
let userAuth = { user: '', token: '' };
|
||||
let currentPage = 1;
|
||||
let pageSize = 10;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
loadSessionAuth();
|
||||
checkConnectionStatus();
|
||||
onFilterTypeChange();
|
||||
fetchGlobalSummary();
|
||||
applyFilters(1);
|
||||
});
|
||||
|
||||
async function checkConnectionStatus() {
|
||||
try {
|
||||
const response = await fetch('/api/status');
|
||||
const status = await response.json();
|
||||
|
||||
const badge = document.getElementById('connection-badge');
|
||||
const dot = document.getElementById('connection-dot');
|
||||
const text = document.getElementById('connection-status-text');
|
||||
|
||||
if (status.connected) {
|
||||
badge.className = "flex items-center space-x-2 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-3.5 py-2 rounded-lg text-xs font-medium";
|
||||
dot.className = "w-2 h-2 rounded-full bg-emerald-400";
|
||||
text.textContent = `Conectado a: ${status.harbor_url}`;
|
||||
} else {
|
||||
badge.className = "flex items-center space-x-2 bg-red-500/10 border border-red-500/20 text-red-400 px-3.5 py-2 rounded-lg text-xs font-medium";
|
||||
dot.className = "w-2 h-2 rounded-full bg-red-400";
|
||||
text.textContent = "No se ha podido conectar";
|
||||
}
|
||||
} catch (e) {
|
||||
const badge = document.getElementById('connection-badge');
|
||||
badge.className = "flex items-center space-x-2 bg-red-500/10 border border-red-500/20 text-red-400 px-3.5 py-2 rounded-lg text-xs font-medium";
|
||||
document.getElementById('connection-dot').className = "w-2 h-2 rounded-full bg-red-400";
|
||||
document.getElementById('connection-status-text').textContent = "No se ha podido conectar";
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchGlobalSummary() {
|
||||
try {
|
||||
const response = await fetch('/api/summary', { headers: getAuthHeaders() });
|
||||
const response = await fetch('/api/summary');
|
||||
if (!response.ok) return;
|
||||
const summary = await response.json();
|
||||
|
||||
document.getElementById('count-total').textContent = summary.total_vuls || 0;
|
||||
document.getElementById('count-critical').textContent = summary.critical_cnt || 0;
|
||||
document.getElementById('count-high').textContent = summary.high_cnt || 0;
|
||||
document.getElementById('count-medium').textContent = summary.medium_cnt || 0;
|
||||
document.getElementById('count-low').textContent = summary.low_cnt || 0;
|
||||
const total = summary.total_vuls || 0;
|
||||
const critical = summary.critical_cnt || 0;
|
||||
const high = summary.high_cnt || 0;
|
||||
const medium = summary.medium_cnt || 0;
|
||||
const low = summary.low_cnt || 0;
|
||||
|
||||
document.getElementById('count-total').textContent = total;
|
||||
document.getElementById('count-critical').textContent = critical;
|
||||
document.getElementById('count-high').textContent = high;
|
||||
document.getElementById('count-medium').textContent = medium;
|
||||
document.getElementById('count-low').textContent = low;
|
||||
|
||||
if (summary.fixable_cnt !== undefined) {
|
||||
document.getElementById('chart-fixable-label').textContent = `${total} total con ${summary.fixable_cnt} corregibles`;
|
||||
} else {
|
||||
document.getElementById('chart-fixable-label').textContent = `${total} vulnerabilidades totales`;
|
||||
}
|
||||
|
||||
if (total > 0) {
|
||||
document.getElementById('bar-critical').style.width = `${(critical / total) * 100}%`;
|
||||
document.getElementById('bar-high').style.width = `${(high / total) * 100}%`;
|
||||
document.getElementById('bar-medium').style.width = `${(medium / total) * 100}%`;
|
||||
document.getElementById('bar-low').style.width = `${(low / total) * 100}%`;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error obteniendo summary global:", e);
|
||||
}
|
||||
@@ -290,35 +332,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function loadSessionAuth() {
|
||||
userAuth.user = sessionStorage.getItem('harbor_user') || '';
|
||||
userAuth.token = sessionStorage.getItem('harbor_token') || '';
|
||||
document.getElementById('config-harbor-user').value = userAuth.user;
|
||||
document.getElementById('config-harbor-token').value = userAuth.token;
|
||||
if(userAuth.user) updateConnectionBadge(true, `Usuario: ${userAuth.user}`);
|
||||
else updateConnectionBadge(false, 'Sin Autenticar');
|
||||
}
|
||||
|
||||
function saveConfig() {
|
||||
userAuth.user = document.getElementById('config-harbor-user').value.trim();
|
||||
userAuth.token = document.getElementById('config-harbor-token').value.trim();
|
||||
sessionStorage.setItem('harbor_user', userAuth.user);
|
||||
sessionStorage.setItem('harbor_token', userAuth.token);
|
||||
closeConfigModal();
|
||||
loadSessionAuth();
|
||||
fetchGlobalSummary();
|
||||
applyFilters(1);
|
||||
}
|
||||
|
||||
function getAuthHeaders() {
|
||||
const headers = new Headers();
|
||||
headers.append('Accept', 'application/json');
|
||||
if (userAuth.user && userAuth.token) {
|
||||
headers.append('Authorization', `Basic ${btoa(`${userAuth.user}:${userAuth.token}`)}`);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function applyFilters(targetPage = 1) {
|
||||
currentPage = targetPage;
|
||||
const filterType = document.getElementById('filter-type').value;
|
||||
@@ -351,7 +364,7 @@
|
||||
page_size: pageSize
|
||||
});
|
||||
|
||||
const response = await fetch(`/api/search?${params.toString()}`, { headers: getAuthHeaders() });
|
||||
const response = await fetch(`/api/search?${params.toString()}`);
|
||||
if(!response.ok) throw new Error("Error en la consulta a la API");
|
||||
|
||||
filteredVulnerabilities = await response.json();
|
||||
@@ -413,8 +426,16 @@
|
||||
sev === 'high' ? 'bg-orange-500/10 text-orange-400' :
|
||||
sev === 'medium' ? 'bg-yellow-500/10 text-yellow-400' : 'bg-blue-500/10 text-blue-400';
|
||||
|
||||
// Construcción del enlace externo hacia Aqua Security AVD (o adaptarlo según necesidad)
|
||||
const cveUrl = `https://avd.aquasec.com/nvd/${item.cve_id.toLowerCase()}`;
|
||||
|
||||
tr.innerHTML = `
|
||||
<td class="px-4 py-3.5 font-mono text-sky-400"><button onclick="openCveModal(${index})" class="hover:underline">${item.cve_id}</button></td>
|
||||
<td class="px-4 py-3.5 font-mono text-sky-400">
|
||||
<a href="${cveUrl}" target="_blank" rel="noopener noreferrer" class="hover:underline flex items-center gap-1.5">
|
||||
<span>${item.cve_id}</span>
|
||||
<i class="fa-solid fa-arrow-up-right-from-square text-[10px] opacity-70"></i>
|
||||
</a>
|
||||
</td>
|
||||
<td class="px-4 py-3.5"><span class="px-2 py-1 rounded text-xs font-bold ${sevColor}">${item.severity}</span></td>
|
||||
<td class="px-4 py-3.5 font-mono text-white">${item.package} <span class="text-xs text-slate-500 block">${item.version}</span></td>
|
||||
<td class="px-4 py-3.5"><span class="px-2 py-0.5 rounded bg-slate-800 text-xs text-slate-300">${item.project}</span></td>
|
||||
@@ -484,7 +505,6 @@
|
||||
document.getElementById('modal-cve-fix').textContent = item.fixed_version || 'N/A';
|
||||
document.getElementById('modal-cve-desc').textContent = item.description || 'Sin descripción disponible.';
|
||||
|
||||
// Estructura limpia en divs con alineación izquierda perfecta
|
||||
document.getElementById('modal-cve-location').innerHTML = `
|
||||
<div>Proyecto: ${item.project}</div>
|
||||
<div>Repositorio: ${item.repository}</div>
|
||||
@@ -495,14 +515,6 @@
|
||||
}
|
||||
|
||||
function closeCveModal() { document.getElementById('cve-modal').classList.add('hidden'); }
|
||||
function openConfigModal() { document.getElementById('config-modal').classList.remove('hidden'); }
|
||||
function closeConfigModal() { document.getElementById('config-modal').classList.add('hidden'); }
|
||||
|
||||
function updateConnectionBadge(isConnected, text) {
|
||||
const badge = document.getElementById('connection-badge');
|
||||
badge.className = isConnected ? "flex items-center space-x-2 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-3 py-1.5 rounded-md text-xs font-medium" : "flex items-center space-x-2 bg-amber-500/10 border border-amber-500/20 text-amber-400 px-3 py-1.5 rounded-md text-xs font-medium";
|
||||
document.getElementById('connection-status-text').textContent = text;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+60
-24
@@ -3,10 +3,24 @@ import http.server
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import json
|
||||
import ssl
|
||||
from urllib.parse import urlparse, parse_qs, urlencode
|
||||
import base64
|
||||
|
||||
HARBOR_URL = os.environ.get("HARBOR_URL", "https://demo.goharbor.io").rstrip("/")
|
||||
PORT = 8080
|
||||
HARBOR_URL = os.environ.get("HARBOR_URL", "https://harbor.tu-dominio.com").rstrip("/")
|
||||
PORT = int(os.environ.get("PORT", 8080))
|
||||
|
||||
HARBOR_ROBOT = os.environ.get("HARBOR_ROBOT", "")
|
||||
HARBOR_TOKEN = os.environ.get("HARBOR_TOKEN", "")
|
||||
|
||||
DEFAULT_AUTH_HEADER = None
|
||||
if HARBOR_ROBOT and HARBOR_TOKEN:
|
||||
credentials = f"{HARBOR_ROBOT}:{HARBOR_TOKEN}"
|
||||
encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
|
||||
DEFAULT_AUTH_HEADER = f"Basic {encoded_credentials}"
|
||||
print(f"[*] Autenticación por defecto configurada mediante variables de entorno para el usuario robot: {HARBOR_ROBOT}")
|
||||
|
||||
SSL_CONTEXT = ssl._create_unverified_context()
|
||||
|
||||
def fetch_json(url, auth_header):
|
||||
req = urllib.request.Request(url)
|
||||
@@ -14,7 +28,7 @@ def fetch_json(url, auth_header):
|
||||
if auth_header:
|
||||
req.add_header("Authorization", auth_header)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=8) as response:
|
||||
with urllib.request.urlopen(req, timeout=8, context=SSL_CONTEXT) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
except Exception:
|
||||
return None
|
||||
@@ -32,7 +46,6 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
parsed_url = urlparse(self.path)
|
||||
path = parsed_url.path
|
||||
query_params = {k: v[0] for k, v in parse_qs(parsed_url.query).items()}
|
||||
auth_header = self.headers.get("Authorization")
|
||||
|
||||
if path == "/" or path == "/index.html":
|
||||
self.serve_file("index.html", "text/html")
|
||||
@@ -41,15 +54,40 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
self.serve_static_asset()
|
||||
return
|
||||
|
||||
# ENDPOINT DE ESTADO DE CONEXIÓN
|
||||
if path == "/api/status":
|
||||
connected = False
|
||||
try:
|
||||
# Probamos a consultar proyectos o summary para validar las credenciales del robot
|
||||
target_api = f"{HARBOR_URL}/api/v2.0/systeminfo"
|
||||
req = urllib.request.Request(target_api)
|
||||
req.add_header("Accept", "application/json")
|
||||
if DEFAULT_AUTH_HEADER:
|
||||
req.add_header("Authorization", DEFAULT_AUTH_HEADER)
|
||||
|
||||
with urllib.request.urlopen(req, timeout=5, context=SSL_CONTEXT) as response:
|
||||
if response.status == 200:
|
||||
connected = True
|
||||
except Exception:
|
||||
connected = False
|
||||
|
||||
status_data = {
|
||||
"connected": connected,
|
||||
"harbor_url": HARBOR_URL,
|
||||
"robot_user": HARBOR_ROBOT if HARBOR_ROBOT else "No configurado"
|
||||
}
|
||||
self.send_json_response(status_data)
|
||||
return
|
||||
|
||||
# ENDPOINT DE MÉTRICAS GLOBALES (SUMMARY)
|
||||
if path == "/api/summary":
|
||||
target_api = f"{HARBOR_URL}/api/v2.0/security/summary?with_dangerous_cve=false&with_dangerous_artifact=false"
|
||||
req = urllib.request.Request(target_api)
|
||||
req.add_header("Accept", "application/json")
|
||||
if auth_header:
|
||||
req.add_header("Authorization", auth_header)
|
||||
if DEFAULT_AUTH_HEADER:
|
||||
req.add_header("Authorization", DEFAULT_AUTH_HEADER)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
with urllib.request.urlopen(req, timeout=10, context=SSL_CONTEXT) as response:
|
||||
data = response.read()
|
||||
self.send_response(response.status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
@@ -62,12 +100,12 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
# ENDPOINT DE EXPORTACIÓN MASIVA (CSV/EXCEL)
|
||||
if path == "/api/export":
|
||||
self.handle_export_vulnerabilities(query_params, auth_header)
|
||||
self.handle_export_vulnerabilities(query_params)
|
||||
return
|
||||
|
||||
# BÚSQUEDA NATIVA /security/vul CON PAGINACIÓN
|
||||
if path == "/api/search":
|
||||
self.handle_native_vulnerability_search(query_params, auth_header)
|
||||
self.handle_native_vulnerability_search(query_params)
|
||||
return
|
||||
|
||||
target_url = f"{HARBOR_URL}{path}"
|
||||
@@ -76,11 +114,11 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
req = urllib.request.Request(target_url)
|
||||
req.add_header("Accept", "application/json")
|
||||
if auth_header:
|
||||
req.add_header("Authorization", auth_header)
|
||||
if DEFAULT_AUTH_HEADER:
|
||||
req.add_header("Authorization", DEFAULT_AUTH_HEADER)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req) as response:
|
||||
with urllib.request.urlopen(req, context=SSL_CONTEXT) as response:
|
||||
data = response.read()
|
||||
self.send_response(response.status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
@@ -100,13 +138,13 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(json.dumps({"error": str(e)}).encode("utf-8"))
|
||||
|
||||
def handle_native_vulnerability_search(self, params, auth_header):
|
||||
self._process_vul_search(params, auth_header, is_export=False)
|
||||
def handle_native_vulnerability_search(self, params):
|
||||
self._process_vul_search(params, is_export=False)
|
||||
|
||||
def handle_export_vulnerabilities(self, params, auth_header):
|
||||
self._process_vul_search(params, auth_header, is_export=True)
|
||||
def handle_export_vulnerabilities(self, params):
|
||||
self._process_vul_search(params, is_export=True)
|
||||
|
||||
def _process_vul_search(self, params, auth_header, is_export=False):
|
||||
def _process_vul_search(self, params, is_export=False):
|
||||
filter_type = params.get("filter_type", "All")
|
||||
query = params.get("query", "").strip()
|
||||
severity_raw = params.get("severity", "").strip()
|
||||
@@ -120,8 +158,7 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
project_map = {}
|
||||
|
||||
try:
|
||||
# Mapeo rápido de proyectos opcional solo para mostrar nombres bonitos en la tabla si hiciera falta
|
||||
projects_data = fetch_json(f"{HARBOR_URL}/api/v2.0/projects?page_size=100", auth_header)
|
||||
projects_data = fetch_json(f"{HARBOR_URL}/api/v2.0/projects?page_size=100", DEFAULT_AUTH_HEADER)
|
||||
if projects_data:
|
||||
for p in projects_data:
|
||||
project_map[p.get("project_id")] = p.get("name")
|
||||
@@ -131,7 +168,6 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
elif filter_type == "Package" and query:
|
||||
q_conditions.append(f"package={query}")
|
||||
elif filter_type == "Repository Name" and query:
|
||||
# Búsqueda directa por repositorio (ej: demo8/mysql)
|
||||
q_conditions.append(f"repository_name={query}")
|
||||
elif filter_type == "Digest" and query:
|
||||
q_conditions.append(f"digest={query}")
|
||||
@@ -166,10 +202,10 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
req = urllib.request.Request(target_api)
|
||||
req.add_header("Accept", "application/json")
|
||||
if auth_header:
|
||||
req.add_header("Authorization", auth_header)
|
||||
if DEFAULT_AUTH_HEADER:
|
||||
req.add_header("Authorization", DEFAULT_AUTH_HEADER)
|
||||
|
||||
with urllib.request.urlopen(req, timeout=15) as response:
|
||||
with urllib.request.urlopen(req, timeout=15, context=SSL_CONTEXT) as response:
|
||||
raw_data = json.loads(response.read().decode("utf-8"))
|
||||
|
||||
formatted_results = []
|
||||
@@ -232,5 +268,5 @@ class HarborProxyHandler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
if __name__ == "__main__":
|
||||
server = http.server.HTTPServer(("0.0.0.0", PORT), HarborProxyHandler)
|
||||
print(f"[*] Proxy Harbor con repositorio directo corriendo en el puerto {PORT}, conectado a: {HARBOR_URL}")
|
||||
print(f"[*] Proxy Harbor corriendo en el puerto {PORT}, conectado a: {HARBOR_URL}")
|
||||
server.serve_forever()
|
||||
Reference in new issue
Block a user