158 lines
6.7 KiB
Python
158 lines
6.7 KiB
Python
"""Management-console group SSO. No hospital tokens or browser profiles are trusted."""
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
import re
|
|
import urllib.parse
|
|
import urllib.request
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
CLIENT_ID = "kefu"
|
|
PROVIDER = "zyt_group"
|
|
GID_PATTERN = re.compile(r"gid_[0-9a-f]{32}\Z")
|
|
CODE_PATTERN = re.compile(r"[A-Za-z0-9_-]{32,256}\Z")
|
|
VERIFIER_PATTERN = re.compile(r"[A-Za-z0-9._~-]{43,128}\Z")
|
|
MAX_RESPONSE_BYTES = 16 * 1024
|
|
|
|
|
|
class GroupSSOError(ValueError):
|
|
"""Safe message for the client; never include a remote response or credential."""
|
|
|
|
|
|
def _base_url(value: str) -> str:
|
|
if (not isinstance(value, str) or not value or len(value) > 2048
|
|
or any(ord(c) <= 32 or ord(c) == 127 for c in value)
|
|
or any(c in value for c in "\\%?#")):
|
|
raise ValueError("Invalid group SSO configuration")
|
|
parsed = urllib.parse.urlsplit(value)
|
|
if (parsed.scheme not in {"https", "http"} or not parsed.hostname
|
|
or parsed.username is not None or parsed.password is not None
|
|
or parsed.query or parsed.fragment):
|
|
raise ValueError("Invalid group SSO configuration")
|
|
# Accessing port also rejects malformed or out-of-range values.
|
|
parsed.port
|
|
host = parsed.hostname.lower()
|
|
if parsed.scheme == "http":
|
|
try:
|
|
loopback = ipaddress.ip_address(host).is_loopback
|
|
except ValueError:
|
|
loopback = host == "localhost"
|
|
if not loopback:
|
|
raise ValueError("HTTP is restricted to loopback")
|
|
if any(segment in {".", ".."} for segment in parsed.path.split("/")):
|
|
raise ValueError("Invalid group SSO configuration")
|
|
return value.rstrip("/")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GroupSSOConfig:
|
|
group_base_url: str
|
|
group_api_url: str
|
|
public_base_url: str
|
|
|
|
@classmethod
|
|
def from_env(cls) -> GroupSSOConfig | None:
|
|
values = [os.environ.get(name, "") for name in (
|
|
"ZYT_GROUP_BASE_URL", "ZYT_GROUP_API_URL", "KEFU_PUBLIC_BASE_URL",
|
|
)]
|
|
if not all(values):
|
|
return None
|
|
try:
|
|
return cls(*(_base_url(value) for value in values))
|
|
except ValueError:
|
|
# Invalid deployment configuration must fail closed.
|
|
return None
|
|
|
|
@property
|
|
def redirect_uri(self) -> str:
|
|
return self.public_base_url + "/auth/group-login"
|
|
|
|
def public_payload(self) -> dict[str, Any]:
|
|
return {"enabled": True, "client_id": CLIENT_ID,
|
|
"entry": self.group_base_url,
|
|
"authorize_url": self.group_base_url + "/sso/authorize",
|
|
"redirect_uri": self.redirect_uri}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GroupPasswordConfig:
|
|
"""Server-only direct login; no browser entry or callback is required."""
|
|
group_api_url: str
|
|
|
|
@classmethod
|
|
def from_env(cls) -> GroupPasswordConfig | None:
|
|
try:
|
|
return cls(_base_url(os.environ.get("ZYT_GROUP_API_URL", "")))
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
return None
|
|
|
|
|
|
def validate_identity(value: Any) -> dict[str, Any]:
|
|
expected = {"client_id", "gid", "source_admin_id", "account", "name", "company_id"}
|
|
if not isinstance(value, dict) or set(value) != expected:
|
|
raise GroupSSOError("集团登录响应无效,请重新登录")
|
|
if value["client_id"] != CLIENT_ID or not isinstance(value["gid"], str) or not GID_PATTERN.fullmatch(value["gid"]):
|
|
raise GroupSSOError("集团登录响应无效,请重新登录")
|
|
if (type(value["source_admin_id"]) is not int or value["source_admin_id"] <= 0
|
|
or type(value["company_id"]) is not int or value["company_id"] <= 0):
|
|
raise GroupSSOError("集团登录响应无效,请重新登录")
|
|
for key in ("account", "name"):
|
|
item = value[key]
|
|
if (not isinstance(item, str) or len(item) > 200
|
|
or any(ord(c) < 32 or ord(c) == 127 for c in item)
|
|
or (key == "account" and not item.strip())):
|
|
raise GroupSSOError("集团登录响应无效,请重新登录")
|
|
return {key: value[key] for key in expected}
|
|
|
|
|
|
def exchange(config: GroupSSOConfig, code: str, code_verifier: str) -> dict[str, Any]:
|
|
if not CODE_PATTERN.fullmatch(code) or not VERIFIER_PATTERN.fullmatch(code_verifier):
|
|
raise GroupSSOError("集团登录凭据无效,请重新登录")
|
|
return _post_identity(config.group_api_url, "/group/sso/exchange", {
|
|
"client_id": CLIENT_ID, "redirect_uri": config.redirect_uri,
|
|
"code": code, "code_verifier": code_verifier,
|
|
})
|
|
|
|
|
|
def password_login(config: GroupPasswordConfig, account: str, password: str) -> dict[str, Any]:
|
|
if (not isinstance(account, str) or not account.strip() or len(account) > 200
|
|
or any(ord(c) < 32 or ord(c) == 127 for c in account)
|
|
or not isinstance(password, str) or not password or len(password) > 4096):
|
|
raise GroupSSOError("用户名或密码不正确,或集团登录暂不可用")
|
|
# Credentials exist only in this request. Neither source tokens nor roles are
|
|
# accepted, persisted, or returned by the strict identity projection.
|
|
return _post_identity(config.group_api_url, "/group/kefu/login", {
|
|
"client_id": CLIENT_ID, "account": account, "password": password,
|
|
})
|
|
|
|
|
|
def _post_identity(api_url: str, path: str, payload: dict[str, str]) -> dict[str, Any]:
|
|
try:
|
|
# Revalidate even an explicitly constructed config. The path is supplied
|
|
# only by the two fixed call sites, never from the login request.
|
|
request = urllib.request.Request(_base_url(api_url) + path,
|
|
data=json.dumps(payload).encode("utf-8"), method="POST",
|
|
headers={"Content-Type": "application/json", "Accept": "application/json"})
|
|
# Neither proxy environment nor a remote redirect may change the recipient.
|
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
|
|
with opener.open(request, timeout=10) as response:
|
|
if response.status != 200:
|
|
raise ValueError("HTTP status")
|
|
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
if len(raw) > MAX_RESPONSE_BYTES:
|
|
raise ValueError("Response too large")
|
|
result = json.loads(raw.decode("utf-8"))
|
|
if not isinstance(result, dict) or type(result.get("code")) is not int or result["code"] != 1:
|
|
raise ValueError("Invalid envelope")
|
|
return validate_identity(result.get("data"))
|
|
except Exception:
|
|
raise GroupSSOError("用户名或密码不正确,或集团登录暂不可用") from None
|