PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。 钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。 认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。 验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。 尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
This commit is contained in:
@@ -278,7 +278,7 @@ def pp_find_entry(manifest):
|
||||
def pp_download(manifest, max_bytes):
|
||||
entry = pp_find_entry(manifest)
|
||||
if entry is None:
|
||||
raise MissingSource("PP ledger entry for this locator no longer exists")
|
||||
entry = {}
|
||||
# Ledger titles may omit the extension; recover the true file name from the
|
||||
# local path or source URL before type checks run.
|
||||
manifest_name = manifest.setdefault("name", "")
|
||||
@@ -301,9 +301,23 @@ def pp_download(manifest, max_bytes):
|
||||
if expected_hash and len(expected_hash) == 64 and actual != expected_hash:
|
||||
raise FetchError("PP local copy hash mismatch (ledger changed?)", retryable=True, code="local_mismatch")
|
||||
return str(candidate), size, actual, True
|
||||
url = entry.get("url", "")
|
||||
if not url:
|
||||
raise MissingSource("PP ledger entry has no local file and no download URL")
|
||||
from pp_client import active_client, record_observation, observation, PPError
|
||||
client = None
|
||||
try:
|
||||
client = active_client()
|
||||
inventory = client.inventory(client.login())
|
||||
record_observation(client.config, observation('valid'))
|
||||
except PPError as error:
|
||||
if client is not None:
|
||||
record_observation(client.config, observation(error.state))
|
||||
raise FetchError(str(error), retryable=error.state == 'unavailable', code='pp_' + error.state) from None
|
||||
locator = manifest.get('locator_hash', '')
|
||||
matches = [row for row in inventory['items'] if row.get('online') == 1 and (row.get('potalGroup') or {}).get('groupName') == '公开' and digest_of(str(row.get('fileUrl') or '').strip()) == locator]
|
||||
if not matches:
|
||||
raise MissingSource('PP file is no longer visible in the configured portal')
|
||||
url = str(matches[0].get('fileUrl') or '').strip()
|
||||
if not pathlib.PurePosixPath(manifest['name']).suffix:
|
||||
manifest['name'] += pathlib.PurePosixPath(urllib.parse.unquote(urllib.parse.urlsplit(url).path)).suffix
|
||||
path, size, actual = http_get(url, {}, 180, max_bytes)
|
||||
expected_hash = str(entry.get("sha256", "")).lower()
|
||||
if expected_hash and len(expected_hash) == 64 and actual != expected_hash:
|
||||
|
||||
@@ -8,6 +8,7 @@ import argparse,csv,io,json,os,pathlib,re,subprocess,sys,tempfile
|
||||
from collections import deque
|
||||
sys.path.insert(0,'/app/scripts')
|
||||
from source_catalog_import import build_alist_source,build_dingtalk_sources,build_pp_live_source,catalog_sql,validate_source
|
||||
from pp_client import active_client,record_observation,observation,PPError
|
||||
class RefreshBlocked(RuntimeError):pass
|
||||
|
||||
_source_name='';_last_directory=''
|
||||
@@ -39,12 +40,16 @@ def run_psql(sql):
|
||||
if result.returncode:raise RuntimeError('catalog activation failed')
|
||||
|
||||
def refresh_pp():
|
||||
sys.path.insert(0,'/sources/pp');from download_scope_a import login,fetch_inventory
|
||||
emit('connecting',10,'正在登录PP资料下载中心')
|
||||
try:token=login('/run/source-secrets/pp_credentials.json')
|
||||
except Exception as error:raise RefreshBlocked('PP登录失败,请在来源链接更新凭据') from error
|
||||
emit('scanning',35,'正在实时读取PP公开资料清单')
|
||||
inventory=fetch_inventory(token)
|
||||
client=None
|
||||
try:
|
||||
client=active_client();token=client.login()
|
||||
emit('scanning',35,'正在实时读取PP公开资料清单')
|
||||
inventory=client.inventory(token)
|
||||
record_observation(client.config,observation('valid'))
|
||||
except PPError as error:
|
||||
if client is not None:record_observation(client.config,observation(error.state))
|
||||
raise RefreshBlocked(str(error)+',请在数据源配置检查PP连接') from error
|
||||
emit('building',75,'正在构建PP八类目录快照',len(inventory.get('items',[])),len(inventory.get('items',[])))
|
||||
manifest={}
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""PP read-only API client; the only PP authentication protocol implementation.
|
||||
|
||||
API checks and new worker tasks load the same atomically activated configuration.
|
||||
Secrets enter the check subprocess on stdin, never through argv or stdout.
|
||||
"""
|
||||
import contextlib
|
||||
import datetime
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_BASE = "https://api.dobot.cn"
|
||||
DEFAULT_STATE = "/data/source-auth/pp/settings.json"
|
||||
MESSAGES = {
|
||||
"valid": "认证有效 · 目录可读",
|
||||
"incomplete": "配置未完成,请填写账号和密码",
|
||||
"auth_failed": "PP 拒绝认证,请检查账号和密码",
|
||||
"permission_denied": "已认证,但目录权限不足",
|
||||
"unavailable": "PP 暂时无法检查,请稍后重试",
|
||||
"invalid_response": "PP 接口地址或返回格式不兼容",
|
||||
}
|
||||
|
||||
class PPError(Exception):
|
||||
def __init__(self, state):
|
||||
self.state = state
|
||||
super().__init__(MESSAGES[state])
|
||||
|
||||
def observation(state):
|
||||
return {"state": state, "message": MESSAGES[state], "checked_at": datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
||||
|
||||
def validate_base(raw, allow_http=False):
|
||||
if not isinstance(raw, str) or len(raw) > 300 or raw.strip() != raw:
|
||||
raise PPError("invalid_response")
|
||||
try:
|
||||
u = urllib.parse.urlsplit(raw)
|
||||
if (u.scheme not in (("https", "http") if allow_http else ("https",))
|
||||
or not u.hostname or u.username is not None or u.password is not None
|
||||
or u.path not in ("", "/") or u.query or u.fragment or "?" in raw or "#" in raw):
|
||||
raise PPError("invalid_response")
|
||||
_ = u.port
|
||||
except ValueError:
|
||||
raise PPError("invalid_response") from None
|
||||
return raw.rstrip("/")
|
||||
|
||||
def load_config(path=None):
|
||||
p = pathlib.Path(path or os.environ.get("PP_AUTH_STATE_FILE") or DEFAULT_STATE)
|
||||
if p.exists():
|
||||
info = p.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) & 0o077:
|
||||
raise PPError("incomplete")
|
||||
state = json.loads(p.read_text(encoding="utf-8"))
|
||||
config = state.get("active")
|
||||
if not isinstance(config, dict):
|
||||
raise PPError("incomplete")
|
||||
else:
|
||||
legacy = pathlib.Path(os.environ.get("PP_LEGACY_CREDENTIALS_FILE") or "/run/source-secrets/pp_credentials.json")
|
||||
try:
|
||||
config = json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
raise PPError("incomplete") from None
|
||||
config = {**config, "base_url": config.get("base_url") or DEFAULT_BASE, "id": "legacy"}
|
||||
validate_base(config.get("base_url"))
|
||||
if not config.get("username") or not config.get("password"):
|
||||
raise PPError("incomplete")
|
||||
return config
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
class Client:
|
||||
def __init__(self, config, allow_http=False, timeout=20):
|
||||
self.config = dict(config)
|
||||
self.base = validate_base(config.get("base_url"), allow_http)
|
||||
self.timeout = timeout
|
||||
self.opener = urllib.request.build_opener(NoRedirect())
|
||||
|
||||
def request(self, path, token="", body=None, login=False):
|
||||
headers = {"Accept": "application/json", "User-Agent": "KnowledgeGovernance/PPReadOnly"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
req = urllib.request.Request(self.base + path, data=body, headers=headers)
|
||||
try:
|
||||
with self.opener.open(req, timeout=self.timeout) as response:
|
||||
raw = response.read((8 << 20) + 1)
|
||||
if len(raw) > 8 << 20:
|
||||
raise PPError("invalid_response")
|
||||
payload = json.loads(raw)
|
||||
except urllib.error.HTTPError as error:
|
||||
error.close()
|
||||
if error.code == 401 or (error.code == 403 and login):
|
||||
raise PPError("auth_failed") from None
|
||||
if error.code == 403:
|
||||
raise PPError("permission_denied") from None
|
||||
if error.code in (408, 425, 429) or error.code >= 500:
|
||||
raise PPError("unavailable") from None
|
||||
raise PPError("invalid_response") from None
|
||||
except (TimeoutError, OSError):
|
||||
raise PPError("unavailable") from None
|
||||
except (ValueError, TypeError):
|
||||
raise PPError("invalid_response") from None
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("code"), int) or isinstance(payload.get("code"), bool):
|
||||
raise PPError("invalid_response")
|
||||
if payload["code"] != 0:
|
||||
code = payload["code"]
|
||||
if code in (408, 429) or 500 <= code < 600:
|
||||
raise PPError("unavailable")
|
||||
if login or code == 401:
|
||||
raise PPError("auth_failed")
|
||||
if code == 403:
|
||||
raise PPError("permission_denied")
|
||||
raise PPError("invalid_response")
|
||||
return payload.get("data")
|
||||
|
||||
def login(self):
|
||||
if not self.config.get("username") or not self.config.get("password"):
|
||||
raise PPError("incomplete")
|
||||
body = urllib.parse.urlencode({"username": self.config["username"], "password": self.config["password"]}).encode()
|
||||
data = self.request("/admin/login/token", body=body, login=True)
|
||||
token = data.get("access_token") if isinstance(data, dict) else None
|
||||
if not isinstance(token, str) or not token:
|
||||
raise PPError("invalid_response")
|
||||
return token
|
||||
|
||||
def page(self, token, current=1, size=200):
|
||||
query = urllib.parse.urlencode({"current": current, "size": size})
|
||||
data = self.request("/potal/file/back/page?" + query, token=token)
|
||||
if (not isinstance(data, dict) or not isinstance(data.get("list"), list)
|
||||
or not isinstance(data.get("total"), int) or isinstance(data.get("total"), bool)
|
||||
or data["total"] < 0 or not isinstance(data.get("hasNextPage"), bool)):
|
||||
raise PPError("invalid_response")
|
||||
return data
|
||||
|
||||
def check(self):
|
||||
try:
|
||||
self.page(self.login(), size=1)
|
||||
return observation("valid")
|
||||
except PPError as error:
|
||||
return observation(error.state)
|
||||
|
||||
def inventory(self, token):
|
||||
items = []
|
||||
for current in range(1, 10001):
|
||||
page = self.page(token, current)
|
||||
items.extend(page["list"])
|
||||
if not page["hasNextPage"]:
|
||||
if len(items) != page["total"]:
|
||||
raise PPError("invalid_response")
|
||||
return {"reported_total": page["total"], "pages": current, "items": items}
|
||||
raise PPError("invalid_response")
|
||||
|
||||
def record_observation(config, result, path=None):
|
||||
"""An old task may update only the observation of its own active revision."""
|
||||
p = pathlib.Path(path or os.environ.get("PP_AUTH_STATE_FILE") or DEFAULT_STATE)
|
||||
if not p.is_file():
|
||||
return
|
||||
with os.fdopen(os.open(str(p) + ".lock", os.O_CREAT | os.O_RDWR, 0o600), "r+", encoding="utf-8") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
state = json.loads(p.read_text(encoding="utf-8"))
|
||||
if not state.get("active") or state["active"].get("id") != config.get("id"):
|
||||
return
|
||||
old = state.get("observation")
|
||||
if result.get("state") == "unavailable" and isinstance(old, dict):
|
||||
result = {**result, "previous": old.get("previous") or old}
|
||||
state["observation"] = result
|
||||
fd, temp = tempfile.mkstemp(prefix=".pp-next-", dir=p.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as out:
|
||||
json.dump(state, out, ensure_ascii=False)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temp, p)
|
||||
directory = os.open(p.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(temp)
|
||||
|
||||
def active_client():
|
||||
return Client(load_config())
|
||||
|
||||
def main():
|
||||
try:
|
||||
config = json.load(sys.stdin)
|
||||
result = Client(config).check()
|
||||
except PPError as error:
|
||||
result = observation(error.state)
|
||||
except Exception:
|
||||
result = observation("unavailable")
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
import json
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
import pathlib
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import pp_client
|
||||
|
||||
class PPClientTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.calls=[];self.login_code=0;self.list_status=200;self.items=[]
|
||||
owner=self
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self,*args):pass
|
||||
def do_POST(self):
|
||||
owner.calls.append((self.command,self.path));self.rfile.read(int(self.headers.get('Content-Length','0')))
|
||||
self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'code':owner.login_code,'data':{'access_token':'example-token'} if owner.login_code==0 else {}}).encode())
|
||||
def do_GET(self):
|
||||
owner.calls.append((self.command,self.path))
|
||||
if self.path=='/file.pdf':
|
||||
content=b'%PDF-1.4\nExample PP download\n';self.send_response(200);self.send_header('Content-Length',str(len(content)));self.end_headers();self.wfile.write(content);return
|
||||
self.send_response(owner.list_status);self.end_headers();self.wfile.write(json.dumps({'code':0,'data':{'list':owner.items,'total':len(owner.items),'hasNextPage':False}}).encode())
|
||||
self.server=HTTPServer(('127.0.0.1',0),Handler);self.thread=threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start()
|
||||
self.client=pp_client.Client({'base_url':'http://127.0.0.1:'+str(self.server.server_port),'username':'example','password':'example-password'},allow_http=True)
|
||||
def tearDown(self):self.server.shutdown();self.server.server_close();self.thread.join()
|
||||
def test_check_really_logs_in_and_reads_empty_directory(self):
|
||||
result=self.client.check();self.assertEqual(result['state'],'valid');self.assertEqual([x[0] for x in self.calls],['POST','GET']);self.assertTrue(self.calls[0][1].endswith('/admin/login/token'));self.assertTrue(self.calls[1][1].startswith('/potal/file/back/page?'))
|
||||
def test_explicit_rejection_never_reads_catalog(self):
|
||||
self.login_code=401;result=self.client.check();self.assertEqual(result['state'],'auth_failed');self.assertEqual(len(self.calls),1)
|
||||
def test_permission_failure_and_transient_remain_distinct(self):
|
||||
self.list_status=403;self.assertEqual(self.client.check()['state'],'permission_denied');self.list_status=429;self.assertEqual(self.client.check()['state'],'unavailable')
|
||||
def test_latest_saved_active_config_owns_each_new_task(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
p=pathlib.Path(root)/'settings.json';p.write_text(json.dumps({'active':{'id':'one','base_url':'https://one.example.invalid','username':'example','password':'example-password'}}));p.chmod(0o600)
|
||||
self.assertEqual(pp_client.load_config(str(p))['id'],'one');p.write_text(json.dumps({'active':{'id':'two','base_url':'https://two.example.invalid','username':'example','password':'example-password'}}));self.assertEqual(pp_client.load_config(str(p))['base_url'],'https://two.example.invalid')
|
||||
def test_refresh_consumer_uses_the_shared_client(self):
|
||||
import live_catalog_refresh
|
||||
with patch('live_catalog_refresh.active_client',return_value=self.client),patch('live_catalog_refresh.build_pp_live_source',side_effect=lambda inventory,manifest:inventory),contextlib.redirect_stdout(io.StringIO()):
|
||||
result=live_catalog_refresh.refresh_pp()
|
||||
self.assertEqual(result['items'],[]);self.assertEqual([x[0] for x in self.calls],['POST','GET'])
|
||||
def test_download_consumer_uses_current_portal_and_real_file_bytes(self):
|
||||
import artifact_fetch
|
||||
url=self.client.base+'/file.pdf'
|
||||
self.items=[{'online':1,'potalGroup':{'groupName':'公开'},'fileUrl':url}]
|
||||
with patch('pp_client.active_client',return_value=self.client),patch('artifact_fetch.pp_find_entry',return_value=None):
|
||||
path,size,digest,local=artifact_fetch.pp_download({'locator_hash':hashlib.sha256(url.encode()).hexdigest(),'name':'example.pdf'},1024)
|
||||
try:
|
||||
self.assertFalse(local);self.assertGreater(size,0);self.assertEqual(hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest(),digest)
|
||||
self.assertEqual([x[0] for x in self.calls],['POST','GET','GET'])
|
||||
finally:os.unlink(path)
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user