fix(vedastro): authenticate and verify calculation inputs (BUG-2171)

This commit is contained in:
jesse-ux
2026-11-22 15:56:15 +08:00
parent 1b2af85ba6
commit d82be4319a
27 changed files with 838 additions and 463 deletions
+107 -225
View File
@@ -16,7 +16,6 @@ from __future__ import annotations
import argparse
import contextlib
import enum
import inspect
import importlib
import importlib.util
import io
@@ -27,6 +26,23 @@ import sys
from pathlib import Path
from typing import Any
try:
from scripts.vedastro_response_contract import (
KEY_MISSING,
api_key,
ayanamsa_name,
response_failure,
verified_response,
)
except ModuleNotFoundError: # pragma: no cover - direct CLI execution
from vedastro_response_contract import (
KEY_MISSING,
api_key,
ayanamsa_name,
response_failure,
verified_response,
)
ROOT = Path(__file__).resolve().parents[1]
PACKAGE_NAME = "VedAstro"
@@ -40,199 +56,6 @@ DEFAULT_VENV_PYTHONS = (
ROOT / "venv_vedastro" / "bin" / "python",
)
CHILD_RUNNER = r"""
import contextlib
import enum
import importlib
import io
import json
import sys
MODULE_CANDIDATES = ("vedastro", "VedAstro")
def _offset_to_string(offset):
if isinstance(offset, str):
raw = offset.strip()
if not raw:
return "+00:00"
if raw[0] in "+-" and ":" in raw:
return raw
try:
offset = float(raw)
except ValueError:
return raw
if isinstance(offset, (int, float)):
sign = "+" if offset >= 0 else "-"
absolute = abs(float(offset))
hours = int(absolute)
minutes = int(round((absolute - hours) * 60))
if minutes == 60:
hours += 1
minutes = 0
return f"{sign}{hours:02d}:{minutes:02d}"
return "+00:00"
def _import_module():
for name in MODULE_CANDIDATES:
with contextlib.redirect_stdout(io.StringIO()):
try:
return name, importlib.import_module(name)
except ModuleNotFoundError:
continue
return None, None
def _coerce(module, value):
if isinstance(value, list):
return [_coerce(module, item) for item in value]
if isinstance(value, dict):
enum_name = value.get("__vedastro_enum__")
if enum_name:
enum_type = getattr(module, enum_name)
return getattr(enum_type, value["value"])
type_name = value.get("__vedastro_type__")
if type_name == "GeoLocation":
return module.GeoLocation(
value["location_name"],
value["longitude"],
value["latitude"],
)
if type_name == "Time":
geolocation = _coerce(module, value["geolocation"]) if value.get("geolocation") else None
if value.get("time_string") is not None:
return module.Time(value["time_string"], geolocation)
time_string = (
f"{int(value['hour']):02d}:{int(value['minute']):02d} "
f"{int(value['day']):02d}/{int(value['month']):02d}/{int(value['year'])} "
f"{_offset_to_string(value.get('offset', '+00:00'))}"
)
return module.Time(time_string, geolocation)
if type_name:
target = getattr(module, type_name)
args = [_coerce(module, item) for item in value.get("args", [])]
kwargs = {
key: _coerce(module, item)
for key, item in value.get("kwargs", {}).items()
}
if args or kwargs:
return target(*args, **kwargs)
payload = {
key: _coerce(module, item)
for key, item in value.items()
if not key.startswith("__")
}
return target(**payload)
return {
key: _coerce(module, item)
for key, item in value.items()
}
return value
def _serialize(value):
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, enum.Enum):
return {
"type": type(value).__name__,
"name": value.name,
"value": value.value,
}
if isinstance(value, (list, tuple, set)):
return [_serialize(item) for item in value]
if isinstance(value, dict):
return {str(key): _serialize(item) for key, item in value.items()}
if hasattr(value, "to_json"):
try:
payload = value.to_json()
if isinstance(payload, str):
try:
return json.loads(payload)
except json.JSONDecodeError:
return payload
return _serialize(payload)
except Exception:
pass
if hasattr(value, "__dict__"):
return {
key: _serialize(item)
for key, item in vars(value).items()
if not key.startswith("_")
}
return str(value)
def _resolve_callable(module, method_name):
parts = [part for part in method_name.split(".") if part]
if not parts:
raise AttributeError("empty_method_name")
if len(parts) == 1:
return getattr(module.Calculate, parts[0])
current = module
for part in parts:
current = getattr(current, part)
return current
def main():
method = sys.argv[1]
params = json.loads(sys.argv[2])
module_name, module = _import_module()
if module is None:
print(json.dumps({
"available": False,
"status": "python_package_not_installed",
"method": method,
"source": "vedastro_python_bridge_child",
}))
return
call_target = _resolve_callable(module, method)
args = []
kwargs = {}
if isinstance(params, dict) and ("args" in params or "kwargs" in params):
args = [_coerce(module, item) for item in params.get("args", [])]
kwargs = {
key: _coerce(module, item)
for key, item in params.get("kwargs", {}).items()
}
elif isinstance(params, dict):
kwargs = {
key: _coerce(module, item)
for key, item in params.items()
}
elif isinstance(params, list):
args = [_coerce(module, item) for item in params]
elif params is not None:
args = [_coerce(module, params)]
with contextlib.redirect_stdout(io.StringIO()):
result = call_target(*args, **kwargs)
print(json.dumps({
"available": True,
"status": "ok",
"method": method,
"module_name": module_name,
"result": _serialize(result),
"source": "vedastro_python_bridge",
}))
if __name__ == "__main__":
main()
"""
CAPABILITY_RUNNER = r"""
import contextlib
import importlib
@@ -433,24 +256,56 @@ def _serialize_runtime_value(value: Any) -> Any:
return str(value)
def _resolve_runtime_callable(module: Any, method_name: str) -> Any:
parts = [part for part in method_name.split(".") if part]
if not parts:
raise AttributeError("empty_method_name")
if len(parts) == 1:
return getattr(module.Calculate, parts[0])
current = module
for part in parts:
current = getattr(current, part)
return current
def _resolve_runtime_callable(calculate: Any, method_name: str) -> Any:
name = method_name.removeprefix("Calculate.")
if not name or name.startswith("_") or name == "SetAPIKey" or "." in name:
raise AttributeError("unsupported_calculator_method")
return getattr(calculate, name)
class _ProviderRejected(RuntimeError):
pass
def _verified_calculator(module: Any, key: str, ayanamsa: str) -> Any:
# Reuse the pinned SDK's argument serializers. Its normal transport unwraps
# Payload before callers can check Input, so validate at its request boundary.
import requests
class VerifiedCalculate(module.Calculate):
@classmethod
def _make_request(cls, endpoint, params):
body = {**params, "Ayanamsa": ayanamsa, "APIKey": cls.api_key}
response = requests.post(
f"{cls.base_url}/{endpoint}", json=body, timeout=120, allow_redirects=False,
)
response.raise_for_status()
envelope = verified_response(endpoint, body, response.json(), key)
if envelope["Status"] != "Pass":
raise _ProviderRejected(response_failure(envelope))
payload = envelope["Payload"]
if isinstance(payload, dict) and len(payload) == 1:
return next(iter(payload.values()))
return payload
VerifiedCalculate.SetAPIKey(key)
return VerifiedCalculate
def _call_in_current_python(method: str, params: dict[str, Any]) -> dict[str, Any]:
key = api_key()
if not key:
return _provider_blocked(method, KEY_MISSING)
module_name, module = _import_runtime_module()
if module is None:
return _missing_package_result(method)
try:
target = _resolve_runtime_callable(module, method)
settings = dict(params) if isinstance(params, dict) else {}
ayanamsa = ayanamsa_name(settings.pop("ayanamsa", "lahiri"))
if isinstance(params, dict):
params = settings
calculate = _verified_calculator(module, key, ayanamsa)
target = _resolve_runtime_callable(calculate, method)
args: list[Any] = []
kwargs: dict[str, Any] = {}
if isinstance(params, dict) and ("args" in params or "kwargs" in params):
@@ -473,6 +328,8 @@ def _call_in_current_python(method: str, params: dict[str, Any]) -> dict[str, An
"python_bin": sys.executable,
"source": "vedastro_python_bridge",
}
except _ProviderRejected as exc:
return _provider_blocked(method, str(exc))
except Exception as exc:
return {
"available": False,
@@ -480,7 +337,7 @@ def _call_in_current_python(method: str, params: dict[str, Any]) -> dict[str, An
"method": method,
"module_name": module_name,
"python_bin": sys.executable,
"error": {"type": type(exc).__name__, "message": str(exc)},
"error": {"type": type(exc).__name__},
"source": "vedastro_python_bridge",
}
@@ -549,7 +406,8 @@ def _select_python_bin() -> str | None:
def _call_via_child_python(python_bin: str, method: str, params: dict[str, Any]) -> dict[str, Any]:
child_env = os.environ.copy()
completed = subprocess.run(
[python_bin, "-c", CHILD_RUNNER, method, json.dumps(params, ensure_ascii=False)],
[python_bin, str(Path(__file__).resolve()), "--sdk-child", "--method", method,
"--params-json", json.dumps(params, ensure_ascii=False)],
check=False,
capture_output=True,
text=True,
@@ -562,8 +420,6 @@ def _call_via_child_python(python_bin: str, method: str, params: dict[str, Any])
"status": "bridge_runtime_error",
"method": method,
"python_bin": python_bin,
"stderr": (completed.stderr or "").strip(),
"stdout_excerpt": (completed.stdout or "").strip()[:500],
"source": "vedastro_python_bridge",
}
@@ -575,8 +431,6 @@ def _call_via_child_python(python_bin: str, method: str, params: dict[str, Any])
"status": "bridge_invalid_json",
"method": method,
"python_bin": python_bin,
"stdout_excerpt": (completed.stdout or "").strip()[:500],
"stderr": (completed.stderr or "").strip()[:500],
"source": "vedastro_python_bridge",
}
@@ -668,6 +522,15 @@ def _missing_package_result(method: str) -> dict[str, Any]:
}
def _provider_blocked(method: str, status: str) -> dict[str, Any]:
return {
"available": False,
"status": status,
"method": method,
"source": "vedastro_python_bridge",
}
def call_method(method: str, params: dict[str, Any]) -> dict[str, Any]:
stub = os.environ.get(STUB_RESULT_ENV, "").strip()
if stub:
@@ -683,6 +546,9 @@ def call_method(method: str, params: dict[str, Any]) -> dict[str, Any]:
if os.environ.get(FORCE_UNAVAILABLE_ENV, "").strip().lower() in {"1", "true", "yes"}:
return _missing_package_result(method)
if not api_key():
return _provider_blocked(method, KEY_MISSING)
if _package_available():
return _call_in_current_python(method, params)
@@ -701,14 +567,26 @@ def list_capabilities() -> dict[str, Any]:
return _list_capabilities_via_child_python(python_bin)
def _fanout_status(rows: dict[str, Any]) -> str:
statuses = ["ok" if row["Status"] == "Pass" else row["Payload"]["status"] for row in rows.values()]
if all(status == "ok" for status in statuses):
return "ok"
if all(status == statuses[0] for status in statuses):
return statuses[0]
return "partial"
def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
def call(method: str, params: dict[str, Any]) -> dict[str, Any]:
return call_method(method, {**params, "ayanamsa": payload.get("ayanamsa") or "lahiri"})
if method_key == "event_tag_catalog":
return call_method("GetAllEventDataGroupedByTag", {})
return call("GetAllEventDataGroupedByTag", {})
if method_key == "planet_longitude":
planet = payload["planet"]
time = payload["time"]
return call_method(
return call(
"PlanetNirayanaLongitude",
{
"args": [
@@ -722,12 +600,12 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
birth_time = payload["birth_time"]
check_time = payload["check_time"]
levels = int(payload.get("levels", 3))
return call_method("DasaAtTime", {"args": [birth_time, check_time, levels]})
return call("DasaAtTime", {"args": [birth_time, check_time, levels]})
if method_key == "chara_dasha_snapshot":
birth_time = payload["birth_time"]
check_time = payload["check_time"]
return call_method("GetCharaDasaAtTime", {"args": [birth_time, check_time]})
return call("GetCharaDasaAtTime", {"args": [birth_time, check_time]})
if method_key == "official_full_snapshot_bundle":
birth_time = payload["birth_time"]
@@ -744,7 +622,7 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
section_statuses: dict[str, str] = {}
for planet in planets:
report = call_method(
report = call(
"AllPlanetData",
{
"args": [
@@ -758,10 +636,10 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
"Payload": {"AllPlanetData": report.get("result")} if report.get("status") == "ok" else report,
}
if chart_core:
section_statuses["chart_core"] = "ok"
section_statuses["chart_core"] = _fanout_status(chart_core)
for house in houses:
report = call_method(
report = call(
"AllHouseData",
{
"args": [
@@ -775,22 +653,22 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
"Payload": {"AllHouseData": report.get("result")} if report.get("status") == "ok" else report,
}
if house_core:
section_statuses["house_core"] = "ok"
section_statuses["house_core"] = _fanout_status(house_core)
dasha_report = call_method(
dasha_report = call(
"DasaAtRange",
{"args": [birth_time, start_time, end_time, levels, precision_hours]},
)
vimshottari_report = call_method(
vimshottari_report = call(
"DasaAtTime",
{"args": [birth_time, check_time, levels]},
)
chara_report = call_method(
chara_report = call(
"GetCharaDasaAtTime",
{"args": [birth_time, check_time]},
)
strength_report = call_method("AllPlanetStrength", {"args": [birth_time]})
ashtakavarga_report = call_method("AshtakvargaLifeMap", {"args": [birth_time]})
strength_report = call("AllPlanetStrength", {"args": [birth_time]})
ashtakavarga_report = call("AshtakvargaLifeMap", {"args": [birth_time]})
snapshot_sections = {
"chart_core": chart_core,
@@ -818,7 +696,8 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
}
for section_name in ("dasha_all", "vimshottari_now", "chara_dasha_now", "shadbala", "ashtakavarga"):
section_statuses[section_name] = "ok" if snapshot_sections[section_name]["Status"] == "Pass" else "fail"
row = snapshot_sections[section_name]
section_statuses[section_name] = "ok" if row["Status"] == "Pass" else row["Payload"]["status"]
filled_sections = [name for name, status in section_statuses.items() if status == "ok"]
overall_status = "ok" if filled_sections else "blocked"
@@ -853,6 +732,7 @@ def call_high_value(method_key: str, payload: dict[str, Any]) -> dict[str, Any]:
def main() -> int:
parser = argparse.ArgumentParser(description="VedAstro Python bridge")
parser.add_argument("--print-schema", action="store_true")
parser.add_argument("--sdk-child", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--method", default="")
parser.add_argument("--params-json", default="{}")
parser.add_argument("--high-value", default="")
@@ -895,6 +775,8 @@ def main() -> int:
],
},
}
elif args.sdk_child:
result = _call_in_current_python(args.method, json.loads(args.params_json))
elif args.list_capabilities:
result = list_capabilities()
elif args.high_value: