273 lines
9.8 KiB
Python
273 lines
9.8 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Script de prueba con autenticación real
|
|
Usar después de extraer las claves con Ghidra
|
|
|
|
INSTRUCCIONES:
|
|
1. Extraer ACCESS_KEY y SECRET_KEY con Ghidra (ver GHIDRA_GUIDE.md)
|
|
2. Reemplazar las claves en las líneas 16-17
|
|
3. Ejecutar: python3 test_real_auth.py
|
|
"""
|
|
|
|
import requests
|
|
from adif_auth import AdifAuthenticator
|
|
import json
|
|
|
|
# ============================================================
|
|
# REEMPLAZAR ESTAS CLAVES CON LAS EXTRAÍDAS DE GHIDRA
|
|
# ============================================================
|
|
ACCESS_KEY = "and20210615" # ✅ Extraído con Ghidra
|
|
SECRET_KEY = "Jthjtr946RTt" # ✅ Extraído con Ghidra
|
|
# ============================================================
|
|
|
|
def test_departures(user_id=None):
|
|
"""
|
|
Prueba 1: Salidas desde Madrid Atocha
|
|
"""
|
|
print("\n" + "="*70)
|
|
print("TEST 1: Salidas desde Madrid Atocha")
|
|
print("="*70)
|
|
|
|
auth = AdifAuthenticator(access_key=ACCESS_KEY, secret_key=SECRET_KEY)
|
|
|
|
url = "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpaths/departures/traffictype/"
|
|
payload = {
|
|
"commercialService": "BOTH",
|
|
"commercialStopType": "BOTH",
|
|
"page": {"pageNumber": 0},
|
|
"stationCode": "10200", # Madrid Atocha
|
|
"trafficType": "ALL"
|
|
}
|
|
|
|
headers = auth.get_auth_headers("POST", url, payload, user_id=user_id)
|
|
headers["User-key"] = auth.USER_KEY_CIRCULATION
|
|
|
|
print(f"\nURL: {url}")
|
|
print(f"Payload: {json.dumps(payload, indent=2)}")
|
|
print(f"\nHeaders generados:")
|
|
for key, value in headers.items():
|
|
if key == "Authorization":
|
|
print(f" {key}: {value[:50]}... (truncado)")
|
|
else:
|
|
print(f" {key}: {value}")
|
|
|
|
print("\nEnviando petición...")
|
|
response = requests.post(url, json=payload, headers=headers, timeout=10)
|
|
|
|
print(f"\nStatus Code: {response.status_code}")
|
|
|
|
if response.status_code == 200:
|
|
print("✅ ¡ÉXITO! Autenticación funcionando correctamente")
|
|
data = response.json()
|
|
print(f"\nTotal de salidas encontradas: {data.get('totalElements', 'N/A')}")
|
|
|
|
if 'departures' in data and len(data['departures']) > 0:
|
|
print(f"\nPrimera salida:")
|
|
first = data['departures'][0]
|
|
print(f" - Número: {first.get('commercialNumber', 'N/A')}")
|
|
print(f" - Origen: {first.get('originStationName', 'N/A')}")
|
|
print(f" - Destino: {first.get('destinationStationName', 'N/A')}")
|
|
print(f" - Tipo: {first.get('trafficType', 'N/A')}")
|
|
|
|
return True
|
|
else:
|
|
print(f"❌ Error: {response.status_code}")
|
|
print(f"Respuesta: {response.text[:500]}")
|
|
return False
|
|
|
|
|
|
def test_between_stations(user_id=None):
|
|
"""
|
|
Prueba 2: Trenes entre Madrid y Barcelona
|
|
"""
|
|
print("\n" + "="*70)
|
|
print("TEST 2: Trenes entre Madrid Atocha y Barcelona Sants")
|
|
print("="*70)
|
|
|
|
auth = AdifAuthenticator(access_key=ACCESS_KEY, secret_key=SECRET_KEY)
|
|
|
|
url = "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpaths/betweenstations/traffictype/"
|
|
payload = {
|
|
"commercialService": "BOTH",
|
|
"commercialStopType": "BOTH",
|
|
"originStationCode": "10200", # Madrid Atocha
|
|
"destinationStationCode": "71801", # Barcelona Sants
|
|
"page": {"pageNumber": 0},
|
|
"trafficType": "ALL"
|
|
}
|
|
|
|
headers = auth.get_auth_headers("POST", url, payload, user_id=user_id)
|
|
headers["User-key"] = auth.USER_KEY_CIRCULATION
|
|
|
|
print(f"\nURL: {url}")
|
|
print(f"Ruta: Madrid Atocha (10200) → Barcelona Sants (71801)")
|
|
|
|
print("\nEnviando petición...")
|
|
response = requests.post(url, json=payload, headers=headers, timeout=10)
|
|
|
|
print(f"\nStatus Code: {response.status_code}")
|
|
|
|
if response.status_code == 200:
|
|
print("✅ ¡ÉXITO! Autenticación funcionando correctamente")
|
|
data = response.json()
|
|
print(f"\nTotal de trenes encontrados: {data.get('totalElements', 'N/A')}")
|
|
|
|
if 'betweenStations' in data and len(data['betweenStations']) > 0:
|
|
print(f"\nPrimer tren:")
|
|
first = data['betweenStations'][0]
|
|
print(f" - Número: {first.get('commercialNumber', 'N/A')}")
|
|
print(f" - Origen: {first.get('originStationName', 'N/A')}")
|
|
print(f" - Destino: {first.get('destinationStationName', 'N/A')}")
|
|
print(f" - Tipo: {first.get('trafficType', 'N/A')}")
|
|
|
|
return True
|
|
else:
|
|
print(f"❌ Error: {response.status_code}")
|
|
print(f"Respuesta: {response.text[:500]}")
|
|
return False
|
|
|
|
|
|
def test_station_info(user_id=None):
|
|
"""
|
|
Prueba 3: Información de estación
|
|
"""
|
|
print("\n" + "="*70)
|
|
print("TEST 3: Información detallada de Madrid Atocha")
|
|
print("="*70)
|
|
|
|
auth = AdifAuthenticator(access_key=ACCESS_KEY, secret_key=SECRET_KEY)
|
|
|
|
url = "https://estaciones.api.adif.es/portroyalmanager/secure/stations/onestation/"
|
|
payload = {
|
|
"stationCode": "10200", # Madrid Atocha
|
|
"detailedInfo": {
|
|
"extendedStationInfo": True,
|
|
"stationActivities": True,
|
|
"stationBanner": True,
|
|
"stationCommercialServices": True,
|
|
"stationInfo": True,
|
|
"stationServices": True,
|
|
"stationTransportServices": True
|
|
}
|
|
}
|
|
|
|
headers = auth.get_auth_headers("POST", url, payload, user_id=user_id)
|
|
headers["User-key"] = auth.USER_KEY_STATIONS
|
|
|
|
print(f"\nURL: {url}")
|
|
print(f"Estación: Madrid Atocha (10200)")
|
|
|
|
print("\nEnviando petición...")
|
|
response = requests.post(url, json=payload, headers=headers, timeout=10)
|
|
|
|
print(f"\nStatus Code: {response.status_code}")
|
|
|
|
if response.status_code == 200:
|
|
print("✅ ¡ÉXITO! Autenticación funcionando correctamente")
|
|
data = response.json()
|
|
|
|
if 'stationName' in data:
|
|
print(f"\nNombre: {data.get('stationName', 'N/A')}")
|
|
print(f"Código: {data.get('stationCode', 'N/A')}")
|
|
print(f"Dirección: {data.get('address', 'N/A')}")
|
|
|
|
if 'stationServices' in data:
|
|
print(f"\nServicios disponibles: {len(data['stationServices'])}")
|
|
|
|
return True
|
|
else:
|
|
print(f"❌ Error: {response.status_code}")
|
|
print(f"Respuesta: {response.text[:500]}")
|
|
return False
|
|
|
|
|
|
def main():
|
|
"""
|
|
Ejecutar todas las pruebas
|
|
"""
|
|
print("\n" + "╔"+"═"*68+"╗")
|
|
print("║" + " "*15 + "PRUEBA DE AUTENTICACIÓN ADIF API" + " "*21 + "║")
|
|
print("╚"+"═"*68+"╝")
|
|
|
|
# Verificar que las claves fueron cambiadas
|
|
if ACCESS_KEY == "YOUR_ACCESS_KEY_FROM_GHIDRA" or SECRET_KEY == "YOUR_SECRET_KEY_FROM_GHIDRA":
|
|
print("\n⚠️ ERROR: Debes reemplazar las claves en las líneas 16-17")
|
|
print(" Ver GHIDRA_GUIDE.md para instrucciones de extracción")
|
|
print("\n Pasos:")
|
|
print(" 1. Abrir Ghidra")
|
|
print(" 2. Analizar lib/x86_64/libapi-keys.so")
|
|
print(" 3. Buscar funciones getAccessKeyPro y getSecretKeyPro")
|
|
print(" 4. Copiar las claves del código decompilado")
|
|
print(" 5. Reemplazar en este archivo (líneas 16-17)")
|
|
return
|
|
|
|
# Generar un USER_ID persistente para toda la sesión
|
|
import uuid
|
|
user_id = str(uuid.uuid4())
|
|
|
|
print(f"\n📋 Configuración:")
|
|
print(f" ACCESS_KEY: {ACCESS_KEY[:10]}...{ACCESS_KEY[-10:]} ({len(ACCESS_KEY)} chars)")
|
|
print(f" SECRET_KEY: {SECRET_KEY[:10]}...{SECRET_KEY[-10:]} ({len(SECRET_KEY)} chars)")
|
|
print(f" USER_ID: {user_id}")
|
|
|
|
# Ejecutar pruebas
|
|
results = []
|
|
|
|
try:
|
|
results.append(("Salidas desde Madrid", test_departures(user_id=user_id)))
|
|
except Exception as e:
|
|
print(f"❌ Error en test_departures: {e}")
|
|
results.append(("Salidas desde Madrid", False))
|
|
|
|
try:
|
|
results.append(("Trenes Madrid-Barcelona", test_between_stations(user_id=user_id)))
|
|
except Exception as e:
|
|
print(f"❌ Error en test_between_stations: {e}")
|
|
results.append(("Trenes Madrid-Barcelona", False))
|
|
|
|
try:
|
|
results.append(("Info de estación", test_station_info(user_id=user_id)))
|
|
except Exception as e:
|
|
print(f"❌ Error en test_station_info: {e}")
|
|
results.append(("Info de estación", False))
|
|
|
|
# Resumen
|
|
print("\n" + "="*70)
|
|
print("RESUMEN DE PRUEBAS")
|
|
print("="*70)
|
|
|
|
success_count = sum(1 for _, success in results if success)
|
|
total_count = len(results)
|
|
|
|
for test_name, success in results:
|
|
status = "✅ PASS" if success else "❌ FAIL"
|
|
print(f"{status} - {test_name}")
|
|
|
|
print(f"\nResultado: {success_count}/{total_count} pruebas exitosas")
|
|
|
|
if success_count == total_count:
|
|
print("\n🎉 ¡FELICIDADES! Todas las pruebas pasaron")
|
|
print(" La autenticación está funcionando correctamente")
|
|
print("\n📚 Próximos pasos:")
|
|
print(" - Explorar otros endpoints en API_REQUEST_BODIES.md")
|
|
print(" - Implementar tu aplicación usando adif_auth.py")
|
|
print(" - Revisar FINAL_SUMMARY.md para más información")
|
|
elif success_count > 0:
|
|
print(f"\n⚠️ Algunas pruebas fallaron ({total_count - success_count}/{total_count})")
|
|
print(" - Verifica que las claves sean correctas")
|
|
print(" - Revisa los mensajes de error arriba")
|
|
else:
|
|
print("\n❌ Todas las pruebas fallaron")
|
|
print(" Posibles problemas:")
|
|
print(" 1. Las claves extraídas son incorrectas")
|
|
print(" 2. Hay un error en el proceso de extracción")
|
|
print(" 3. Las claves han cambiado en una nueva versión de la app")
|
|
print("\n Soluciones:")
|
|
print(" - Revisar GHIDRA_GUIDE.md paso a paso")
|
|
print(" - Verificar que analizaste el archivo correcto")
|
|
print(" - Asegurarte de copiar las claves completas (sin espacios)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|