#!/usr/bin/env python
"""
Script to extract the list of services (endpoints) from an OpenAPI descriptor (JSON format).

It's a failover when the following script cannot be used:

https://github.com/righettod/toolbox-pentest-web/blob/master/scripts/identify-services-from-openapi-descriptor.sh

It take the OpenAPI descriptor JSON file as single argument.
"""
import json
import sys
endpoints = {}
with open(sys.argv[1], encoding="utf-8", mode="r") as f:
    descriptor = json.loads(f.read())
for pth in descriptor["spec"]["paths"]:
    if pth not in endpoints:
        endpoints[pth] = []
    for http_method in descriptor["spec"]["paths"][pth]:
        endpoints[pth].append(http_method.upper())
print("[+] API information")
if "info" in descriptor["spec"]:
    infos = descriptor["spec"]["info"]
    for info in infos:
        print(f"{info.title():<15} : {infos[info]}")
print(f"Endpoints count : {len(endpoints)}")
print("[+] List of endpoints")
for endpoint in sorted(endpoints, key=endpoints.get):
    endpoints[endpoint].sort()
    print(f"{endpoint:<25} => {', '.join(endpoints[endpoint])}")
