lockbot 2.15.2__tar.gz → 3.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {lockbot-2.15.2/python/lockbot.egg-info → lockbot-3.0.0}/PKG-INFO +4 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/pyproject.toml +2 -1
- lockbot-3.0.0/python/lockbot/agent_client/__init__.py +1 -0
- lockbot-3.0.0/python/lockbot/agent_client/handoff.py +229 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/agent_skill/SKILL.md +21 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/auth/dependencies.py +8 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/backup/service.py +19 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bot_audit/router.py +3 -2
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/manager.py +7 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/metrics_access.py +5 -17
- lockbot-3.0.0/python/lockbot/backend/app/bots/metrics_signers.py +171 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/router.py +107 -8
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/schemas.py +8 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/broadcast/service.py +9 -5
- lockbot-3.0.0/python/lockbot/backend/app/feishu/__init__.py +1 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/backup.py +75 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/connectors.py +228 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/display_names.py +218 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/models.py +44 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/proxy_settings.py +33 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/router.py +532 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/service.py +138 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/traffic.py +36 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/unbound.py +150 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/ws_process.py +46 -0
- lockbot-3.0.0/python/lockbot/backend/app/feishu/ws_proxy.py +38 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/main.py +23 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/managed_paths.py +1 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/op_skill/SKILL.md +63 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/activity.py +3 -2
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/commands.py +7 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/discovery.py +15 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/errors.py +32 -0
- lockbot-3.0.0/python/lockbot/backend/app/resource_api/event_log.py +353 -0
- lockbot-3.0.0/python/lockbot/backend/app/resource_api/lease_history.py +398 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/operator.py +88 -2
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/privacy.py +16 -3
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/resources.py +4 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/skill.py +2 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/usage.py +69 -5
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/views.py +5 -0
- lockbot-3.0.0/python/lockbot/backend/app/service_traffic.py +446 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/settings/router.py +73 -4
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/base_bot.py +23 -2
- lockbot-3.0.0/python/lockbot/core/command_context.py +43 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/device_bot.py +9 -9
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/handler.py +23 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/i18n/zh.py +1 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/io.py +22 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/node_bot.py +8 -8
- lockbot-3.0.0/python/lockbot/core/platforms/feishu.py +454 -0
- lockbot-3.0.0/python/lockbot/core/platforms/feishu_events.py +118 -0
- lockbot-3.0.0/python/lockbot/core/platforms/feishu_proxy.py +74 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/platforms/registry.py +1 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/queue_bot.py +7 -7
- {lockbot-2.15.2 → lockbot-3.0.0/python/lockbot.egg-info}/PKG-INFO +4 -1
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot.egg-info/SOURCES.txt +21 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot.egg-info/requires.txt +4 -0
- lockbot-3.0.0/tests/test_op_history_report.py +171 -0
- lockbot-3.0.0/tools/deployment_preflight.py +118 -0
- lockbot-2.15.2/python/lockbot/backend/app/resource_api/event_log.py +0 -166
- lockbot-2.15.2/python/lockbot/backend/app/service_traffic.py +0 -219
- lockbot-2.15.2/python/lockbot/core/command_context.py +0 -5
- {lockbot-2.15.2 → lockbot-3.0.0}/LICENSE +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/MANIFEST.in +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/README.md +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/admin/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/admin/router.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/audit/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/audit/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/audit/router.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/audit/service.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/auth/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/auth/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/auth/router.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/auth/schemas.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/backup/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/backup/router.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/backup/scheduler.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bot_audit/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bot_audit/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bot_audit/service.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/datasource.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/encryption.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/bots/webhook_handler.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/broadcast/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/broadcast/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/broadcast/router.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/config.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/database.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/deployment.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/logs/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/rate_limit.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/ingress.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/notification_queue.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/notifications.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/observability.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/op_skill.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/rules.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/snapshot.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/sources.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/traffic.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/usage_cleanup.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/versioning.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_api/view_links.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/authority.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/credentials.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/dependencies.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/http_errors.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/pending.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/router.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/resource_auth/service.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/settings/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/settings/models.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/sqlite_paths.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/state_migration.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/state_ownership.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/backend/app/static.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/bot_instance.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/config.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/device_usage_alert.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/device_usage_utils.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/i18n/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/i18n/en.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/message_adapter.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/msg_utils.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/platforms/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/platforms/infoflow.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/queue_device_bot.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/request.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/resource_policy.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/scheduler.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/core/utils.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/metrics/__init__.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/metrics/exporter.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot/metrics/gateway.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot.egg-info/dependency_links.txt +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/python/lockbot.egg-info/top_level.txt +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/setup.cfg +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/tools/create_super_admin.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/tools/gen_keys.py +0 -0
- {lockbot-2.15.2 → lockbot-3.0.0}/tools/reset_super_admin_password.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lockbot
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: Cluster resource management bot for IM platforms
|
|
5
5
|
Author-email: Jianbang Yang <yangjianbang112@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -35,6 +35,9 @@ Requires-Dist: httpx
|
|
|
35
35
|
Requires-Dist: slowapi
|
|
36
36
|
Requires-Dist: pyzipper
|
|
37
37
|
Requires-Dist: bce-python-sdk
|
|
38
|
+
Provides-Extra: feishu
|
|
39
|
+
Requires-Dist: lark-oapi==1.7.5; extra == "feishu"
|
|
40
|
+
Requires-Dist: websockets==15.0.1; extra == "feishu"
|
|
38
41
|
Provides-Extra: dev
|
|
39
42
|
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
40
43
|
Requires-Dist: pytest-xdist<4,>=3.6; extra == "dev"
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "lockbot"
|
|
7
|
-
version = "
|
|
7
|
+
version = "3.0.0"
|
|
8
8
|
description = "Cluster resource management bot for IM platforms"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = {text = "MIT"}
|
|
@@ -46,6 +46,7 @@ dependencies = [
|
|
|
46
46
|
]
|
|
47
47
|
|
|
48
48
|
[project.optional-dependencies]
|
|
49
|
+
feishu = ["lark-oapi==1.7.5", "websockets==15.0.1"]
|
|
49
50
|
dev = [
|
|
50
51
|
"pytest>=7.0",
|
|
51
52
|
"pytest-xdist>=3.6,<4",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional stdlib-only client reference helpers; no HTTP or command execution."""
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Build final payloads from trusted orchestration policy, not child-Agent prose.
|
|
2
|
+
|
|
3
|
+
The caller must authenticate context/manifest on the approved origin and retain the
|
|
4
|
+
original envelope outside the child's writable state. These helpers do no I/O.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
|
|
10
|
+
SERVICE_ID = "lockbot.resource-api"
|
|
11
|
+
MODES = {"command_only", "public_category", "private_details"}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class GateError(ValueError):
|
|
15
|
+
"""Do not send, guess another credential or replay a previous command."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _text(value, maximum=512):
|
|
19
|
+
if (
|
|
20
|
+
not isinstance(value, str)
|
|
21
|
+
or not 1 <= len(value) <= maximum
|
|
22
|
+
or not value.strip()
|
|
23
|
+
or any(ord(c) < 32 or ord(c) == 127 for c in value)
|
|
24
|
+
):
|
|
25
|
+
raise GateError("Expected bounded plain text")
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _origin(value):
|
|
30
|
+
_text(value, 2048)
|
|
31
|
+
try:
|
|
32
|
+
parsed = urlsplit(value)
|
|
33
|
+
if (
|
|
34
|
+
parsed.scheme not in {"http", "https"}
|
|
35
|
+
or not parsed.hostname
|
|
36
|
+
or parsed.username is not None
|
|
37
|
+
or parsed.password is not None
|
|
38
|
+
or parsed.path not in {"", "/"}
|
|
39
|
+
or parsed.query
|
|
40
|
+
or parsed.fragment
|
|
41
|
+
or "\\" in value
|
|
42
|
+
or any(char.isspace() for char in value)
|
|
43
|
+
or parsed.port == 0
|
|
44
|
+
):
|
|
45
|
+
raise GateError("Expected the verified service origin")
|
|
46
|
+
except ValueError as error:
|
|
47
|
+
raise GateError("Invalid service origin") from error
|
|
48
|
+
return value.rstrip("/")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def scope_from_authenticated_context(origin, context, credential_ref):
|
|
52
|
+
"""Record an already authenticated identity; this function cannot verify TLS/key use."""
|
|
53
|
+
if not isinstance(context, dict):
|
|
54
|
+
raise GateError("Missing authenticated context")
|
|
55
|
+
server, bot, actor = context.get("server", {}), context.get("bot", {}), context.get("actor", {})
|
|
56
|
+
if (
|
|
57
|
+
not isinstance(server, dict)
|
|
58
|
+
or server.get("service_id") != SERVICE_ID
|
|
59
|
+
or server.get("api_version") != "1"
|
|
60
|
+
or context.get("credential_scope") != "one_user_one_bot"
|
|
61
|
+
or context.get("agent_access_enabled") is not True
|
|
62
|
+
or not isinstance(bot, dict)
|
|
63
|
+
or type(bot.get("id")) is not int
|
|
64
|
+
or bot["id"] <= 0
|
|
65
|
+
or not isinstance(actor, dict)
|
|
66
|
+
):
|
|
67
|
+
raise GateError("Unsupported or disabled authenticated scope")
|
|
68
|
+
reference = _text(credential_ref)
|
|
69
|
+
if reference.startswith(("lbr_", "lbk_", "Bearer ")):
|
|
70
|
+
raise GateError("Pass a private-store reference, never a bearer key")
|
|
71
|
+
return {
|
|
72
|
+
"origin": _origin(origin),
|
|
73
|
+
"service_id": SERVICE_ID,
|
|
74
|
+
"instance_id": _text(server.get("instance_id"), 128),
|
|
75
|
+
"bot_uuid": _text(bot.get("uuid"), 128),
|
|
76
|
+
"bot_id": bot["id"],
|
|
77
|
+
"actor": {
|
|
78
|
+
"platform": _text(actor.get("platform"), 64),
|
|
79
|
+
"external_user_id": _text(actor.get("external_user_id")),
|
|
80
|
+
},
|
|
81
|
+
"credential_ref": reference,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _policy(value):
|
|
86
|
+
if (
|
|
87
|
+
not isinstance(value, dict)
|
|
88
|
+
or set(value) != {"version", "mode"}
|
|
89
|
+
or type(value.get("version")) is not int
|
|
90
|
+
or value["version"] != 1
|
|
91
|
+
or not isinstance(value.get("mode"), str)
|
|
92
|
+
or value["mode"] not in MODES
|
|
93
|
+
):
|
|
94
|
+
raise GateError("Unsupported privacy policy")
|
|
95
|
+
return dict(value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def make_handoff(origin, authenticated_context, credential_ref, policy=None):
|
|
99
|
+
"""Create a JSON-serializable envelope; keep an immutable trusted copy in the parent."""
|
|
100
|
+
return {
|
|
101
|
+
"schema_version": 1,
|
|
102
|
+
"scope": scope_from_authenticated_context(origin, authenticated_context, credential_ref),
|
|
103
|
+
"privacy_policy": _policy(policy if policy is not None else {"version": 1, "mode": "command_only"}),
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _envelope(value):
|
|
108
|
+
if (
|
|
109
|
+
not isinstance(value, dict)
|
|
110
|
+
or set(value) != {"schema_version", "scope", "privacy_policy"}
|
|
111
|
+
or type(value.get("schema_version")) is not int
|
|
112
|
+
or value["schema_version"] != 1
|
|
113
|
+
or not isinstance(value.get("scope"), dict)
|
|
114
|
+
):
|
|
115
|
+
raise GateError("Unsupported handoff envelope")
|
|
116
|
+
_policy(value["privacy_policy"])
|
|
117
|
+
return value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _matched_scope(trusted_handoff, origin, context, credential_ref):
|
|
121
|
+
trusted = _envelope(trusted_handoff)
|
|
122
|
+
current = scope_from_authenticated_context(origin, context, credential_ref)
|
|
123
|
+
if trusted["scope"] != current:
|
|
124
|
+
raise GateError("Credential/service/bot/actor scope changed")
|
|
125
|
+
return current
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def final_command_payload(trusted_handoff, child_handoff, *, origin, authenticated_context, credential_ref, candidate):
|
|
129
|
+
"""Return a fresh allowlisted body; never mutate inputs, send or retry a command.
|
|
130
|
+
|
|
131
|
+
The original parent policy is authoritative. A child cannot replace it by
|
|
132
|
+
editing its serialized envelope. Command authorization remains the caller's job.
|
|
133
|
+
"""
|
|
134
|
+
trusted = _envelope(trusted_handoff)
|
|
135
|
+
if _envelope(child_handoff) != trusted:
|
|
136
|
+
raise GateError("Child changed the trusted handoff policy or scope")
|
|
137
|
+
_matched_scope(trusted, origin, authenticated_context, credential_ref)
|
|
138
|
+
if not isinstance(candidate, dict):
|
|
139
|
+
raise GateError("Missing command candidate")
|
|
140
|
+
result = {"command": _text(candidate.get("command"))}
|
|
141
|
+
privacy = authenticated_context.get("usage_privacy")
|
|
142
|
+
if not isinstance(privacy, dict):
|
|
143
|
+
return result
|
|
144
|
+
mode = trusted["privacy_policy"]["mode"]
|
|
145
|
+
if mode == "public_category":
|
|
146
|
+
categories = privacy.get("public_task_categories")
|
|
147
|
+
if not isinstance(categories, dict) or not categories:
|
|
148
|
+
return result
|
|
149
|
+
category = candidate.get("task_category")
|
|
150
|
+
if category is not None:
|
|
151
|
+
if not isinstance(category, str) or category not in categories:
|
|
152
|
+
raise GateError("Choose a public category ID from authenticated context")
|
|
153
|
+
result["task_category"] = category
|
|
154
|
+
elif mode == "private_details":
|
|
155
|
+
fields = privacy.get("private_fields")
|
|
156
|
+
if (
|
|
157
|
+
privacy.get("legacy_purpose_visibility") != "private"
|
|
158
|
+
or not isinstance(fields, list)
|
|
159
|
+
or "purpose" not in fields
|
|
160
|
+
or "agent_label" not in fields
|
|
161
|
+
):
|
|
162
|
+
return result
|
|
163
|
+
for field, maximum in (("purpose", 512), ("agent_label", 64)):
|
|
164
|
+
if candidate.get(field) is not None:
|
|
165
|
+
result[field] = _text(candidate[field], maximum)
|
|
166
|
+
return result
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _instant(value):
|
|
170
|
+
try:
|
|
171
|
+
instant = datetime.fromisoformat(_text(value, 64).replace("Z", "+00:00"))
|
|
172
|
+
if instant.tzinfo is None:
|
|
173
|
+
raise ValueError("Timezone required")
|
|
174
|
+
return instant.astimezone(timezone.utc)
|
|
175
|
+
except (ValueError, TypeError) as error:
|
|
176
|
+
raise GateError("Expected an absolute lease timestamp") from error
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def lease_matches(trusted_handoff, *, origin, authenticated_context, credential_ref, resource_id, saved, holder, now):
|
|
180
|
+
"""Compare this task's saved evidence with a fresh resource holder; no release I/O.
|
|
181
|
+
|
|
182
|
+
Current APIs expose start_time; holding_id is additionally checked when present
|
|
183
|
+
in saved evidence. No public Agent label is used as an ownership boundary.
|
|
184
|
+
"""
|
|
185
|
+
scope = _matched_scope(trusted_handoff, origin, authenticated_context, credential_ref)
|
|
186
|
+
if not isinstance(saved, dict) or not isinstance(holder, dict):
|
|
187
|
+
return False
|
|
188
|
+
actor = scope["actor"]
|
|
189
|
+
if (
|
|
190
|
+
saved.get("resource_id") != _text(resource_id)
|
|
191
|
+
or saved.get("actor") != actor
|
|
192
|
+
or holder.get("platform") != actor["platform"]
|
|
193
|
+
or holder.get("external_user_id") != actor["external_user_id"]
|
|
194
|
+
or _instant(saved.get("start_time")) != _instant(holder.get("start_time"))
|
|
195
|
+
or _instant(holder.get("expires_at")) <= _instant(now)
|
|
196
|
+
):
|
|
197
|
+
return False
|
|
198
|
+
return saved.get("holding_id") is None or saved["holding_id"] == holder.get("holding_id")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def feedback_url(trusted_handoff, *, manifest_origin, verified_manifest):
|
|
202
|
+
"""Return only the verified manifest's feedback entry; never submit or upload anything."""
|
|
203
|
+
scope = _envelope(trusted_handoff)["scope"]
|
|
204
|
+
if (
|
|
205
|
+
_origin(manifest_origin) != scope.get("origin")
|
|
206
|
+
or not isinstance(verified_manifest, dict)
|
|
207
|
+
or verified_manifest.get("service_id") != scope.get("service_id")
|
|
208
|
+
or verified_manifest.get("instance_id") != scope.get("instance_id")
|
|
209
|
+
):
|
|
210
|
+
raise GateError("Feedback manifest does not match the verified service")
|
|
211
|
+
url = _text(verified_manifest.get("issues_url"), 2048)
|
|
212
|
+
try:
|
|
213
|
+
parsed = urlsplit(url)
|
|
214
|
+
port = parsed.port
|
|
215
|
+
except ValueError as error:
|
|
216
|
+
raise GateError("Invalid feedback entry") from error
|
|
217
|
+
if (
|
|
218
|
+
parsed.scheme != "https"
|
|
219
|
+
or not parsed.hostname
|
|
220
|
+
or parsed.username is not None
|
|
221
|
+
or parsed.password is not None
|
|
222
|
+
or parsed.query
|
|
223
|
+
or parsed.fragment
|
|
224
|
+
or "\\" in url
|
|
225
|
+
or any(char.isspace() for char in url)
|
|
226
|
+
or port == 0
|
|
227
|
+
):
|
|
228
|
+
raise GateError("Invalid feedback entry")
|
|
229
|
+
return url
|
|
@@ -261,6 +261,9 @@ its bot ID once as a legacy fallback. Never scan IDs or fall back to another pla
|
|
|
261
261
|
who enrolled it. You cannot choose or spoof the identity — it is fixed at enrollment.
|
|
262
262
|
- **Enrollment is chat-only.** A human runs `bind <code>` in the bot's IM group to confirm a
|
|
263
263
|
pending credential. `bind` / `unbind` / `bindings` are refused over HTTP by design.
|
|
264
|
+
On Feishu, mention the enterprise bot in the explicitly configured resource group;
|
|
265
|
+
direct messages do not enroll a resource credential. Preserve the exact `actor.platform`
|
|
266
|
+
from context in connection memory; matching display names across platforms are not the same identity.
|
|
264
267
|
- One verified user has one active key per bot; their own agents share it. Other users and bots have separate keys. Do not repeatedly enroll to get a key per agent.
|
|
265
268
|
- Agent access is enabled by default for new bots; an explicit disabled setting is retained. The owner can change it and save the configuration. Disabling access pauses it; a valid key can work again after re-enabling. `unbind` permanently revokes the key.
|
|
266
269
|
- A credential lives until revoked (unless this deployment configures an expiry). It is revoked by: chat `unbind`, an owner revoke, bot delete,
|
|
@@ -588,6 +591,16 @@ Keep checks running throughout long tasks, not only at acquisition. Honour the a
|
|
|
588
591
|
|
|
589
592
|
## Declare work without publishing private task details
|
|
590
593
|
|
|
594
|
+
For delegated/background work, carry a versioned privacy policy with the verified service,
|
|
595
|
+
instance, bot UUID, resource actor and credential reference. Keep the parent's trusted policy
|
|
596
|
+
outside the child's writable state; check the final encoded payload against it rather than
|
|
597
|
+
trusting a child summary. Default to command-only, allow public categories only under an
|
|
598
|
+
explicit policy, and send private fields only when that policy and current server capability
|
|
599
|
+
both permit them. A changed scope/policy means stop, never try another key or replay a command.
|
|
600
|
+
An optional stdlib [handoff/payload-gate reference](https://github.com/dynamicheart/lockbot/blob/release/2.x/docs/usage/agent-handoff.md)
|
|
601
|
+
provides executable checks and an offline example; clients may implement equivalent checks
|
|
602
|
+
without installing a Python SDK. Lease evidence uses real actor/start time, never Agent labels.
|
|
603
|
+
|
|
591
604
|
Check `/api/agent/context.usage_privacy` before sending notes. On servers advertising this
|
|
592
605
|
policy, `task_category` is the only public task description. Choose exactly one ID from
|
|
593
606
|
`public_task_categories`, for example `operator_testing`, `communication_testing`,
|
|
@@ -635,6 +648,14 @@ and other users' public categories. Never attribute a task by machine name alone
|
|
|
635
648
|
verified actor and resource ID. `usage: null` is not proof that nobody registered a task.
|
|
636
649
|
A declaration does not prove ownership or change the queue order. It disappears when the
|
|
637
650
|
lease, TTL or authorization is no longer valid. DELETE your declaration to remove it.
|
|
651
|
+
For task-scoped cleanup, first verify this task's actor/resource/lease and read its own
|
|
652
|
+
current declaration. When context declares `usage_privacy.conditional_cleanup`, save the
|
|
653
|
+
private `revision` value and send it unchanged as the `If-Match` header on DELETE.
|
|
654
|
+
The server rejects changed/expired declarations or changed leases with 412. Stop and
|
|
655
|
+
re-read; never retry without the precondition or delete a replacement task's declaration.
|
|
656
|
+
This deletes metadata only: it does not free or renew resources. A revision is not an
|
|
657
|
+
ownership proof or credential and is hidden from other users. Old servers without this
|
|
658
|
+
capability require coordination; do not assume their unconditional delete is race-safe.
|
|
638
659
|
Refresh an expiring declaration without repeating `lock`, which extends resource time.
|
|
639
660
|
If a mutation returns `may_have_executed`, read state before retrying.
|
|
640
661
|
|
|
@@ -10,7 +10,7 @@ Depends(get_current_user), so no other changes are needed.
|
|
|
10
10
|
from datetime import datetime, timedelta, timezone
|
|
11
11
|
|
|
12
12
|
import jwt
|
|
13
|
-
from fastapi import Depends, HTTPException, status
|
|
13
|
+
from fastapi import Depends, HTTPException, Request, status
|
|
14
14
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
15
15
|
from sqlalchemy import select
|
|
16
16
|
from sqlalchemy.orm import Session
|
|
@@ -35,6 +35,7 @@ def create_access_token(user_id: int, token_version: int = 0, must_change_passwo
|
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
def get_current_user(
|
|
38
|
+
request: Request,
|
|
38
39
|
credentials: HTTPAuthorizationCredentials | None = Depends(_security),
|
|
39
40
|
db: Session = Depends(get_db),
|
|
40
41
|
) -> User:
|
|
@@ -56,6 +57,12 @@ def get_current_user(
|
|
|
56
57
|
if user.effective_token_version != token_version:
|
|
57
58
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired, please login again")
|
|
58
59
|
|
|
60
|
+
request.state.traffic_management = {
|
|
61
|
+
"id": "user:" + str(user.id),
|
|
62
|
+
"kind": "management",
|
|
63
|
+
"user": user.username,
|
|
64
|
+
"platform": "",
|
|
65
|
+
}
|
|
59
66
|
return user
|
|
60
67
|
|
|
61
68
|
|
|
@@ -329,6 +329,10 @@ def _read_backup_bots(zf) -> list[dict]:
|
|
|
329
329
|
result = []
|
|
330
330
|
for r in rows:
|
|
331
331
|
d = dict(r)
|
|
332
|
+
if (d.get("platform") or "").lower() == "feishu":
|
|
333
|
+
from lockbot.backend.app.feishu.backup import read_application_metadata
|
|
334
|
+
|
|
335
|
+
d["_feishu_application"] = read_application_metadata(conn, d["id"])
|
|
332
336
|
if "uuid" not in d:
|
|
333
337
|
d["uuid"] = None
|
|
334
338
|
result.append(d)
|
|
@@ -517,6 +521,15 @@ def restore_apply(
|
|
|
517
521
|
current_user_id: int,
|
|
518
522
|
db,
|
|
519
523
|
) -> dict:
|
|
524
|
+
"""Keep route restoration and its commit serialized against application removal."""
|
|
525
|
+
from lockbot.backend.app.feishu.connectors import connectors
|
|
526
|
+
|
|
527
|
+
with connectors.application_guard():
|
|
528
|
+
db.rollback()
|
|
529
|
+
return _restore_apply(file_bytes, password, source_secret_key, selected_uuids, current_user_id, db)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _restore_apply(file_bytes, password, source_secret_key, selected_uuids, current_user_id, db):
|
|
520
533
|
"""
|
|
521
534
|
Actually restore selected bots from a backup zip.
|
|
522
535
|
|
|
@@ -743,6 +756,9 @@ def restore_apply(
|
|
|
743
756
|
existing.token = token_enc
|
|
744
757
|
existing.status = "recovery_required"
|
|
745
758
|
existing.pid = None
|
|
759
|
+
from lockbot.backend.app.feishu.backup import restore_route
|
|
760
|
+
|
|
761
|
+
restore_route(db, existing, bb, source_secret_key)
|
|
746
762
|
# Commit the new config, then install the archived state atomically. If
|
|
747
763
|
# the state cannot be installed after the config commit (or the commit
|
|
748
764
|
# result is unknown), the row and its saved state may be inconsistent — a
|
|
@@ -794,6 +810,9 @@ def restore_apply(
|
|
|
794
810
|
db.add(bot_obj)
|
|
795
811
|
try:
|
|
796
812
|
db.flush() # get bot_obj.id
|
|
813
|
+
from lockbot.backend.app.feishu.backup import restore_route
|
|
814
|
+
|
|
815
|
+
restore_route(db, bot_obj, bb, source_secret_key)
|
|
797
816
|
db.commit()
|
|
798
817
|
except IntegrityError:
|
|
799
818
|
db.rollback()
|
|
@@ -9,7 +9,7 @@ from lockbot.backend.app.auth.models import User
|
|
|
9
9
|
from lockbot.backend.app.bot_audit.models import BotAuditLog
|
|
10
10
|
from lockbot.backend.app.bots.router import _get_user_bot
|
|
11
11
|
from lockbot.backend.app.database import get_db
|
|
12
|
-
from lockbot.backend.app.resource_api.privacy import audit_private_read,
|
|
12
|
+
from lockbot.backend.app.resource_api.privacy import audit_private_read, private_task_view
|
|
13
13
|
|
|
14
14
|
router = APIRouter(tags=["bots"])
|
|
15
15
|
|
|
@@ -18,6 +18,7 @@ router = APIRouter(tags=["bots"])
|
|
|
18
18
|
def bot_audit_logs(
|
|
19
19
|
bot_id: int,
|
|
20
20
|
response: Response,
|
|
21
|
+
include_private: bool = False,
|
|
21
22
|
page: int = Query(1, ge=1),
|
|
22
23
|
limit: int = Query(20, ge=1, le=100),
|
|
23
24
|
user: User = Depends(get_current_user),
|
|
@@ -32,7 +33,7 @@ def bot_audit_logs(
|
|
|
32
33
|
.limit(limit)
|
|
33
34
|
.all()
|
|
34
35
|
)
|
|
35
|
-
private =
|
|
36
|
+
private = private_task_view(db, user, include_private)
|
|
36
37
|
items = [_to_out(row) for row in rows]
|
|
37
38
|
if private and items:
|
|
38
39
|
audit_private_read(db, user, bot_id=bot_id, surface="management.authorization_audit")
|
|
@@ -399,6 +399,13 @@ class BotManager:
|
|
|
399
399
|
scheduler=self._scheduler, # managed mode: shared scheduler
|
|
400
400
|
)
|
|
401
401
|
instance.bot.binding_hook = self._make_binding_hook(bot_id, config_dict)
|
|
402
|
+
from lockbot.backend.app.resource_api.lease_history import LeaseJournal
|
|
403
|
+
|
|
404
|
+
try:
|
|
405
|
+
with instance.bot._lock:
|
|
406
|
+
instance.config._lifecycle_observer = LeaseJournal(bot_id, instance.bot)
|
|
407
|
+
except Exception:
|
|
408
|
+
logger.warning("Bot %s lifecycle evidence is unavailable", bot_id)
|
|
402
409
|
|
|
403
410
|
with self._lock:
|
|
404
411
|
# The transition owner guarantees no competing start published in the meantime.
|
|
@@ -1,33 +1,21 @@
|
|
|
1
1
|
"""Issue short read-only data-source grants; never query or proxy hardware metrics."""
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
|
-
import os
|
|
5
|
-
import stat
|
|
6
4
|
import time
|
|
7
5
|
from datetime import timezone
|
|
8
|
-
from pathlib import Path
|
|
9
6
|
|
|
10
7
|
import jwt
|
|
11
8
|
|
|
12
9
|
from lockbot.backend.app.bots.datasource import public_datasource
|
|
10
|
+
from lockbot.backend.app.bots.metrics_signers import select_metrics_signer
|
|
13
11
|
|
|
14
12
|
|
|
15
13
|
def issue_metrics_access(db, bot, source=None, *, expires_at=None):
|
|
16
14
|
source = source or public_datasource(bot)
|
|
17
15
|
if not source or source.get("accessMode", "independent") != "short_lived":
|
|
18
16
|
return None
|
|
19
|
-
|
|
20
|
-
if
|
|
21
|
-
return None
|
|
22
|
-
try:
|
|
23
|
-
path = Path(key_path)
|
|
24
|
-
info = path.stat()
|
|
25
|
-
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) & 0o077 or info.st_size > 4096:
|
|
26
|
-
return None
|
|
27
|
-
secret = path.read_bytes()
|
|
28
|
-
if len(secret) < 32:
|
|
29
|
-
return None
|
|
30
|
-
except OSError:
|
|
17
|
+
signer = select_metrics_signer(source.get("endpoint"))
|
|
18
|
+
if signer is None:
|
|
31
19
|
return None
|
|
32
20
|
from lockbot.backend.app.resource_api.discovery import ensure_instance_id
|
|
33
21
|
|
|
@@ -58,12 +46,12 @@ def issue_metrics_access(db, bot, source=None, *, expires_at=None):
|
|
|
58
46
|
{
|
|
59
47
|
"iss": ensure_instance_id(db),
|
|
60
48
|
"sub": bot.uuid,
|
|
61
|
-
"aud":
|
|
49
|
+
"aud": signer.audience,
|
|
62
50
|
"iat": issued,
|
|
63
51
|
"exp": expiry,
|
|
64
52
|
"nodes": nodes,
|
|
65
53
|
},
|
|
66
|
-
secret,
|
|
54
|
+
signer.secret,
|
|
67
55
|
algorithm="HS256",
|
|
68
56
|
)
|
|
69
57
|
return {"token": token, "expires_at": expiry, "scope": "metrics:read"}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Deployment-only, source-specific metrics signing keys. Never read paths from HTTP input."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import ipaddress
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import stat
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
12
|
+
|
|
13
|
+
MAX_CONFIG_BYTES = 64 * 1024
|
|
14
|
+
MAX_SOURCES = 64
|
|
15
|
+
MAX_KEY_BYTES = 4096
|
|
16
|
+
REGISTRY_ENV = "METRICS_GRANT_SIGNERS_FILE"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, repr=False)
|
|
20
|
+
class MetricsSigner:
|
|
21
|
+
audience: str
|
|
22
|
+
secret: bytes
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def canonical_audience(value):
|
|
26
|
+
"""Require one unambiguous spelling; never move grants between URL aliases."""
|
|
27
|
+
if (
|
|
28
|
+
not isinstance(value, str)
|
|
29
|
+
or not 1 <= len(value) <= 2048
|
|
30
|
+
or any(ord(char) <= 32 or ord(char) >= 127 for char in value)
|
|
31
|
+
or any(char in value for char in ("?", "#", "\\", "%"))
|
|
32
|
+
):
|
|
33
|
+
raise ValueError("Invalid metrics audience")
|
|
34
|
+
parsed = urlsplit(value)
|
|
35
|
+
if (
|
|
36
|
+
parsed.scheme not in {"http", "https"}
|
|
37
|
+
or not parsed.hostname
|
|
38
|
+
or parsed.username is not None
|
|
39
|
+
or parsed.password is not None
|
|
40
|
+
or parsed.query
|
|
41
|
+
or parsed.fragment
|
|
42
|
+
):
|
|
43
|
+
raise ValueError("Invalid metrics audience")
|
|
44
|
+
host = parsed.hostname
|
|
45
|
+
if ":" in host:
|
|
46
|
+
host = "[" + ipaddress.IPv6Address(host).compressed + "]"
|
|
47
|
+
else:
|
|
48
|
+
if len(host) > 253 or any(
|
|
49
|
+
not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) for label in host.split(".")
|
|
50
|
+
):
|
|
51
|
+
raise ValueError("Invalid metrics audience")
|
|
52
|
+
# Browsers accept alternative numeric IP spellings; require dotted decimal.
|
|
53
|
+
if all(re.fullmatch(r"(?:0x[0-9a-f]+|[0-9]+)", label) for label in host.split(".")):
|
|
54
|
+
host = str(ipaddress.IPv4Address(host))
|
|
55
|
+
port = parsed.port
|
|
56
|
+
if port is not None and not 1 <= port <= 65535:
|
|
57
|
+
raise ValueError("Invalid metrics audience")
|
|
58
|
+
authority = host + (f":{port}" if port is not None and port != {"http": 80, "https": 443}[parsed.scheme] else "")
|
|
59
|
+
path = parsed.path.rstrip("/")
|
|
60
|
+
if (
|
|
61
|
+
not re.fullmatch(r"(?:/[A-Za-z0-9._~-]+)*", path)
|
|
62
|
+
or any(part in {".", ".."} for part in path.split("/"))
|
|
63
|
+
or "//" in parsed.path
|
|
64
|
+
):
|
|
65
|
+
raise ValueError("Invalid metrics audience")
|
|
66
|
+
canonical = urlunsplit((parsed.scheme, authority, path, "", ""))
|
|
67
|
+
if canonical != value:
|
|
68
|
+
raise ValueError("Use the canonical metrics audience")
|
|
69
|
+
return canonical
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _private_file(value, maximum):
|
|
73
|
+
if not isinstance(value, str) or not value or not Path(value).is_absolute():
|
|
74
|
+
raise ValueError("Private file requires an absolute deployment path")
|
|
75
|
+
path = Path(value)
|
|
76
|
+
before = path.lstat()
|
|
77
|
+
if not stat.S_ISREG(before.st_mode):
|
|
78
|
+
raise ValueError("Private file must be regular")
|
|
79
|
+
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
80
|
+
descriptor = os.open(path, flags)
|
|
81
|
+
try:
|
|
82
|
+
info = os.fstat(descriptor)
|
|
83
|
+
if (
|
|
84
|
+
not stat.S_ISREG(info.st_mode)
|
|
85
|
+
or stat.S_IMODE(info.st_mode) != 0o600
|
|
86
|
+
or info.st_uid not in {0, os.geteuid()}
|
|
87
|
+
or (info.st_dev, info.st_ino) != (before.st_dev, before.st_ino)
|
|
88
|
+
or not 1 <= info.st_size <= maximum
|
|
89
|
+
):
|
|
90
|
+
raise ValueError("Unsafe private file")
|
|
91
|
+
body = bytearray()
|
|
92
|
+
while len(body) <= maximum:
|
|
93
|
+
chunk = os.read(descriptor, min(8192, maximum + 1 - len(body)))
|
|
94
|
+
if not chunk:
|
|
95
|
+
break
|
|
96
|
+
body.extend(chunk)
|
|
97
|
+
after = os.fstat(descriptor)
|
|
98
|
+
if (
|
|
99
|
+
len(body) != info.st_size
|
|
100
|
+
or len(body) > maximum
|
|
101
|
+
or (after.st_size, after.st_mtime_ns, after.st_ctime_ns)
|
|
102
|
+
!= (info.st_size, info.st_mtime_ns, info.st_ctime_ns)
|
|
103
|
+
):
|
|
104
|
+
raise ValueError("Private file changed during read")
|
|
105
|
+
return bytes(body), (info.st_dev, info.st_ino)
|
|
106
|
+
finally:
|
|
107
|
+
os.close(descriptor)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _unique_object(pairs):
|
|
111
|
+
result = {}
|
|
112
|
+
for key, value in pairs:
|
|
113
|
+
if key in result:
|
|
114
|
+
raise ValueError("Duplicate metrics signer configuration field")
|
|
115
|
+
result[key] = value
|
|
116
|
+
return result
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _registry_signer(endpoint):
|
|
120
|
+
audience = canonical_audience(endpoint)
|
|
121
|
+
body, registry_identity = _private_file(os.environ[REGISTRY_ENV], MAX_CONFIG_BYTES)
|
|
122
|
+
config = json.loads(body, object_pairs_hook=_unique_object)
|
|
123
|
+
if (
|
|
124
|
+
not isinstance(config, dict)
|
|
125
|
+
or set(config) != {"version", "sources"}
|
|
126
|
+
or type(config["version"]) is not int
|
|
127
|
+
or config["version"] != 1
|
|
128
|
+
or not isinstance(config["sources"], list)
|
|
129
|
+
or not 1 <= len(config["sources"]) <= MAX_SOURCES
|
|
130
|
+
):
|
|
131
|
+
raise ValueError("Invalid metrics signer configuration")
|
|
132
|
+
audiences, identities, digests = set(), {registry_identity}, set()
|
|
133
|
+
selected = None
|
|
134
|
+
for source in config["sources"]:
|
|
135
|
+
if not isinstance(source, dict) or set(source) != {"audience", "key_file"}:
|
|
136
|
+
raise ValueError("Invalid metrics signer source")
|
|
137
|
+
target = canonical_audience(source["audience"])
|
|
138
|
+
secret, identity = _private_file(source["key_file"], MAX_KEY_BYTES)
|
|
139
|
+
digest = hashlib.sha256(secret).digest()
|
|
140
|
+
if len(secret) < 32 or target in audiences or identity in identities or digest in digests:
|
|
141
|
+
raise ValueError("Metrics signer sources must be distinct")
|
|
142
|
+
audiences.add(target)
|
|
143
|
+
identities.add(identity)
|
|
144
|
+
digests.add(digest)
|
|
145
|
+
if target == audience:
|
|
146
|
+
selected = MetricsSigner(target, secret)
|
|
147
|
+
return selected
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def select_metrics_signer(endpoint):
|
|
151
|
+
"""Reload on every issuance; configured registry errors must never fall back."""
|
|
152
|
+
if not isinstance(endpoint, str):
|
|
153
|
+
return None
|
|
154
|
+
try:
|
|
155
|
+
if REGISTRY_ENV in os.environ:
|
|
156
|
+
return _registry_signer(endpoint)
|
|
157
|
+
# Preserve the existing single-file mode and exact audience spelling.
|
|
158
|
+
key_path = os.environ.get("METRICS_GRANT_SECRET_FILE", "")
|
|
159
|
+
if not key_path:
|
|
160
|
+
return None
|
|
161
|
+
path = Path(key_path)
|
|
162
|
+
info = path.stat()
|
|
163
|
+
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) & 0o077 or info.st_size > MAX_KEY_BYTES:
|
|
164
|
+
return None
|
|
165
|
+
secret = path.read_bytes()
|
|
166
|
+
if len(secret) < 32:
|
|
167
|
+
return None
|
|
168
|
+
return MetricsSigner(endpoint.rstrip("/"), secret)
|
|
169
|
+
except (OSError, ValueError, TypeError, KeyError, UnicodeError, RecursionError):
|
|
170
|
+
# This value crosses public context/view/test paths: expose no private paths.
|
|
171
|
+
return None
|