lockbot 3.0.1__tar.gz → 3.1.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.
Files changed (149) hide show
  1. {lockbot-3.0.1/python/lockbot.egg-info → lockbot-3.1.0}/PKG-INFO +1 -1
  2. {lockbot-3.0.1 → lockbot-3.1.0}/pyproject.toml +1 -1
  3. lockbot-3.1.0/python/lockbot/backend/app/audit/delegation.py +477 -0
  4. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/main.py +2 -0
  5. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/op_skill/SKILL.md +7 -0
  6. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/event_log.py +4 -1
  7. {lockbot-3.0.1 → lockbot-3.1.0/python/lockbot.egg-info}/PKG-INFO +1 -1
  8. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot.egg-info/SOURCES.txt +1 -0
  9. {lockbot-3.0.1 → lockbot-3.1.0}/LICENSE +0 -0
  10. {lockbot-3.0.1 → lockbot-3.1.0}/MANIFEST.in +0 -0
  11. {lockbot-3.0.1 → lockbot-3.1.0}/README.md +0 -0
  12. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/__init__.py +0 -0
  13. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/agent_client/__init__.py +0 -0
  14. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/agent_client/handoff.py +0 -0
  15. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/__init__.py +0 -0
  16. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/__init__.py +0 -0
  17. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/admin/__init__.py +0 -0
  18. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/admin/router.py +0 -0
  19. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/agent_skill/SKILL.md +0 -0
  20. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/audit/__init__.py +0 -0
  21. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/audit/models.py +0 -0
  22. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/audit/router.py +0 -0
  23. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/audit/service.py +0 -0
  24. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/auth/__init__.py +0 -0
  25. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/auth/dependencies.py +0 -0
  26. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/auth/models.py +0 -0
  27. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/auth/router.py +0 -0
  28. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/auth/schemas.py +0 -0
  29. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/backup/__init__.py +0 -0
  30. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/backup/router.py +0 -0
  31. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/backup/scheduler.py +0 -0
  32. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/backup/service.py +0 -0
  33. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bot_audit/__init__.py +0 -0
  34. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bot_audit/models.py +0 -0
  35. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bot_audit/router.py +0 -0
  36. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bot_audit/service.py +0 -0
  37. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/__init__.py +0 -0
  38. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/datasource.py +0 -0
  39. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/encryption.py +0 -0
  40. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/manager.py +0 -0
  41. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/metrics_access.py +0 -0
  42. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/metrics_signers.py +0 -0
  43. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/models.py +0 -0
  44. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/router.py +0 -0
  45. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/schemas.py +0 -0
  46. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/bots/webhook_handler.py +0 -0
  47. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/broadcast/__init__.py +0 -0
  48. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/broadcast/models.py +0 -0
  49. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/broadcast/router.py +0 -0
  50. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/broadcast/service.py +0 -0
  51. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/config.py +0 -0
  52. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/database.py +0 -0
  53. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/deployment.py +0 -0
  54. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/__init__.py +0 -0
  55. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/backup.py +0 -0
  56. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/connectors.py +0 -0
  57. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/display_names.py +0 -0
  58. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/models.py +0 -0
  59. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/proxy_settings.py +0 -0
  60. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/router.py +0 -0
  61. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/service.py +0 -0
  62. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/traffic.py +0 -0
  63. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/unbound.py +0 -0
  64. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/ws_process.py +0 -0
  65. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/feishu/ws_proxy.py +0 -0
  66. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/logs/__init__.py +0 -0
  67. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/managed_paths.py +0 -0
  68. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/rate_limit.py +0 -0
  69. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/__init__.py +0 -0
  70. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/activity.py +0 -0
  71. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/commands.py +0 -0
  72. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/discovery.py +0 -0
  73. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/errors.py +0 -0
  74. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/ingress.py +0 -0
  75. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/lease_history.py +0 -0
  76. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/notification_queue.py +0 -0
  77. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/notifications.py +0 -0
  78. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/observability.py +0 -0
  79. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/op_skill.py +0 -0
  80. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/operator.py +0 -0
  81. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/privacy.py +0 -0
  82. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/resources.py +0 -0
  83. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/rules.py +0 -0
  84. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/skill.py +0 -0
  85. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/snapshot.py +0 -0
  86. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/sources.py +0 -0
  87. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/traffic.py +0 -0
  88. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/usage.py +0 -0
  89. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/usage_cleanup.py +0 -0
  90. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/versioning.py +0 -0
  91. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/view_links.py +0 -0
  92. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_api/views.py +0 -0
  93. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/__init__.py +0 -0
  94. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/authority.py +0 -0
  95. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/credentials.py +0 -0
  96. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/dependencies.py +0 -0
  97. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/http_errors.py +0 -0
  98. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/models.py +0 -0
  99. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/pending.py +0 -0
  100. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/router.py +0 -0
  101. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/resource_auth/service.py +0 -0
  102. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/service_traffic.py +0 -0
  103. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/settings/__init__.py +0 -0
  104. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/settings/models.py +0 -0
  105. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/settings/router.py +0 -0
  106. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/sqlite_paths.py +0 -0
  107. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/state_migration.py +0 -0
  108. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/state_ownership.py +0 -0
  109. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/backend/app/static.py +0 -0
  110. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/__init__.py +0 -0
  111. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/base_bot.py +0 -0
  112. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/bot_instance.py +0 -0
  113. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/command_context.py +0 -0
  114. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/config.py +0 -0
  115. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/device_bot.py +0 -0
  116. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/device_usage_alert.py +0 -0
  117. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/device_usage_utils.py +0 -0
  118. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/handler.py +0 -0
  119. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/i18n/__init__.py +0 -0
  120. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/i18n/en.py +0 -0
  121. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/i18n/zh.py +0 -0
  122. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/io.py +0 -0
  123. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/message_adapter.py +0 -0
  124. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/msg_utils.py +0 -0
  125. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/node_bot.py +0 -0
  126. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/platforms/__init__.py +0 -0
  127. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/platforms/feishu.py +0 -0
  128. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/platforms/feishu_events.py +0 -0
  129. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/platforms/feishu_proxy.py +0 -0
  130. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/platforms/infoflow.py +0 -0
  131. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/platforms/registry.py +0 -0
  132. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/queue_bot.py +0 -0
  133. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/queue_device_bot.py +0 -0
  134. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/request.py +0 -0
  135. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/resource_policy.py +0 -0
  136. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/scheduler.py +0 -0
  137. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/core/utils.py +0 -0
  138. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/metrics/__init__.py +0 -0
  139. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/metrics/exporter.py +0 -0
  140. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot/metrics/gateway.py +0 -0
  141. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot.egg-info/dependency_links.txt +0 -0
  142. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot.egg-info/requires.txt +0 -0
  143. {lockbot-3.0.1 → lockbot-3.1.0}/python/lockbot.egg-info/top_level.txt +0 -0
  144. {lockbot-3.0.1 → lockbot-3.1.0}/setup.cfg +0 -0
  145. {lockbot-3.0.1 → lockbot-3.1.0}/tests/test_op_history_report.py +0 -0
  146. {lockbot-3.0.1 → lockbot-3.1.0}/tools/create_super_admin.py +0 -0
  147. {lockbot-3.0.1 → lockbot-3.1.0}/tools/deployment_preflight.py +0 -0
  148. {lockbot-3.0.1 → lockbot-3.1.0}/tools/gen_keys.py +0 -0
  149. {lockbot-3.0.1 → lockbot-3.1.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.0.1
3
+ Version: 3.1.0
4
4
  Summary: Cluster resource management and queuing for Infoflow and Feishu
5
5
  Author-email: Jianbang Yang <yangjianbang112@gmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "lockbot"
7
- version = "3.0.1"
7
+ version = "3.1.0"
8
8
  description = "Cluster resource management and queuing for Infoflow and Feishu"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -0,0 +1,477 @@
1
+ """Explicit, revocable task-note delegation. Never an extension of an ordinary OP key."""
2
+
3
+ import hashlib
4
+ import json
5
+ import re
6
+ import secrets
7
+ import threading
8
+ import time
9
+ from collections import OrderedDict
10
+ from datetime import datetime, timedelta, timezone
11
+
12
+ import jwt
13
+ from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
14
+ from fastapi.security import HTTPBearer
15
+ from pydantic import BaseModel, ConfigDict, Field, StrictInt, field_validator
16
+ from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, select
17
+ from sqlalchemy.orm import Mapped, Session, mapped_column
18
+
19
+ from lockbot.backend.app import config
20
+ from lockbot.backend.app.audit.models import AuditLog
21
+ from lockbot.backend.app.auth.dependencies import require_super_admin
22
+ from lockbot.backend.app.auth.models import User
23
+ from lockbot.backend.app.bots.models import Bot
24
+ from lockbot.backend.app.database import Base, get_db
25
+ from lockbot.backend.app.rate_limit import limiter
26
+
27
+ SCOPE = "task_notes:read"
28
+ MAX_TTL = 7 * 86400
29
+ _TOKEN = re.compile(r"^lba1\.([A-Za-z0-9_-]{22})\.([A-Za-z0-9_-]{43})$")
30
+ _guard = threading.RLock()
31
+ router = APIRouter(tags=["Audit delegation"])
32
+ audit_bearer = HTTPBearer(
33
+ auto_error=False,
34
+ scheme_name="TaskNoteAuditCredential",
35
+ description="Dedicated lba1 credential with task_notes:read; management JWT and OP keys are not accepted.",
36
+ )
37
+
38
+
39
+ class AuditCredential(Base):
40
+ __tablename__ = "audit_credentials"
41
+
42
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
43
+ public_id: Mapped[str] = mapped_column(String(32), unique=True)
44
+ name: Mapped[str] = mapped_column(String(64))
45
+ scope: Mapped[str] = mapped_column(String(32))
46
+ digest: Mapped[str] = mapped_column(String(64))
47
+ generation: Mapped[int] = mapped_column(Integer, default=1)
48
+ issuer_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id"))
49
+ issuer_token_version: Mapped[int] = mapped_column(Integer)
50
+ bots: Mapped[str] = mapped_column(Text)
51
+ created_at: Mapped[datetime] = mapped_column(DateTime)
52
+ expires_at: Mapped[datetime] = mapped_column(DateTime)
53
+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
54
+
55
+
56
+ class GrantCreate(BaseModel):
57
+ model_config = ConfigDict(extra="forbid")
58
+ name: str = Field(min_length=1, max_length=64)
59
+ bot_ids: list[StrictInt] = Field(min_length=1, max_length=100)
60
+ expires_in_seconds: int = Field(default=86400, ge=60, le=MAX_TTL)
61
+
62
+ @field_validator("bot_ids")
63
+ @classmethod
64
+ def explicit_bots(cls, values):
65
+ if any(value <= 0 for value in values) or len(set(values)) != len(values):
66
+ raise ValueError("Use explicit, unique positive bot IDs")
67
+ return values
68
+
69
+
70
+ class GrantRotate(BaseModel):
71
+ model_config = ConfigDict(extra="forbid")
72
+ expires_in_seconds: int = Field(default=86400, ge=60, le=MAX_TTL)
73
+
74
+
75
+ def _now():
76
+ return datetime.now(timezone.utc).replace(tzinfo=None)
77
+
78
+
79
+ def _iso(value):
80
+ return value.isoformat() + "Z" if value else None
81
+
82
+
83
+ def _deny(status, detail):
84
+ raise HTTPException(status, detail, headers={"Cache-Control": "no-store"})
85
+
86
+
87
+ def _audit(db, user, action, *, grant, bot_id=None, count=None, ip=None, result="success", reason=None, surface=None):
88
+ # This audit is a disclosure precondition: unlike ordinary best-effort logs it fails closed.
89
+ detail = {"principal": grant.public_id, "scope": SCOPE}
90
+ if reason is not None:
91
+ detail["reason"] = reason
92
+ if count is not None:
93
+ detail.update(surface=surface or "audit.task_notes", returned_count=count)
94
+ db.add(
95
+ AuditLog(
96
+ operator_id=user.id,
97
+ operator_username=user.username,
98
+ operator_role=user.role,
99
+ action=action,
100
+ target_type="bot" if bot_id is not None else "audit_credential",
101
+ target_id=bot_id if bot_id is not None else grant.id,
102
+ target_name=f"#{bot_id}" if bot_id is not None else grant.public_id,
103
+ detail=json.dumps(detail),
104
+ ip_address=ip,
105
+ result=result,
106
+ )
107
+ )
108
+ db.flush()
109
+
110
+
111
+ def _admin(db, user_id, token_version):
112
+ db.rollback()
113
+ user = db.get(User, user_id)
114
+ if (
115
+ user is None
116
+ or user.role != "super_admin"
117
+ or user.must_change_password
118
+ or user.effective_token_version != token_version
119
+ ):
120
+ _deny(403, "Current super administrator authority required")
121
+ return user
122
+
123
+
124
+ def _bot_identity(bot):
125
+ return {"id": bot.id, "uuid": bot.uuid, "revision": bot.identity_revision, "owner": bot.user_id}
126
+
127
+
128
+ def _bot_scope(db, bot_ids):
129
+ values = []
130
+ for bot_id in bot_ids:
131
+ bot = db.get(Bot, bot_id)
132
+ if bot is None or bot.is_deleted:
133
+ _deny(422, "Every permitted bot must exist and be active in the service")
134
+ values.append(_bot_identity(bot))
135
+ return values
136
+
137
+
138
+ def _metadata(row):
139
+ return {
140
+ "id": row.public_id,
141
+ "name": row.name,
142
+ "api_version": "1",
143
+ "scope": row.scope,
144
+ "bot_ids": [item["id"] for item in json.loads(row.bots)],
145
+ "generation": row.generation,
146
+ "created_at": _iso(row.created_at),
147
+ "expires_at": _iso(row.expires_at),
148
+ "revoked_at": _iso(row.revoked_at),
149
+ "issuer_id": row.issuer_id,
150
+ }
151
+
152
+
153
+ def _secret(row):
154
+ token = f"lba1.{row.public_id}.{secrets.token_urlsafe(32)}"
155
+ row.digest = hashlib.sha256(token.encode()).hexdigest()
156
+ return token
157
+
158
+
159
+ @router.post("/api/admin/audit-credentials", status_code=201)
160
+ @limiter.limit("10/minute")
161
+ def create_credential(
162
+ request: Request,
163
+ response: Response,
164
+ body: GrantCreate,
165
+ user: User = Depends(require_super_admin),
166
+ db: Session = Depends(get_db),
167
+ ):
168
+ response.headers["Cache-Control"] = "no-store"
169
+ user_id, version = user.id, user.effective_token_version
170
+ with _guard:
171
+ user = _admin(db, user_id, version)
172
+ active = (
173
+ db.query(AuditCredential)
174
+ .filter(AuditCredential.revoked_at.is_(None), AuditCredential.expires_at > _now())
175
+ .count()
176
+ )
177
+ if active >= 128:
178
+ _deny(409, "At most 128 active audit credentials are permitted")
179
+ now = _now()
180
+ row = AuditCredential(
181
+ public_id=secrets.token_urlsafe(16),
182
+ name=body.name,
183
+ scope=SCOPE,
184
+ generation=1,
185
+ issuer_id=user.id,
186
+ issuer_token_version=version,
187
+ bots=json.dumps(_bot_scope(db, body.bot_ids)),
188
+ created_at=now,
189
+ expires_at=now + timedelta(seconds=body.expires_in_seconds),
190
+ )
191
+ token = _secret(row)
192
+ db.add(row)
193
+ db.flush()
194
+ _audit(db, user, "audit_credential.create", grant=row, ip=request.client.host if request.client else None)
195
+ db.commit()
196
+ return {**_metadata(row), "credential": token, "shown_once": True}
197
+
198
+
199
+ @router.get("/api/admin/audit-credentials")
200
+ def credentials(
201
+ response: Response,
202
+ limit: int = Query(50, ge=1, le=100),
203
+ offset: int = Query(0, ge=0, le=10000),
204
+ user: User = Depends(require_super_admin),
205
+ db: Session = Depends(get_db),
206
+ ):
207
+ response.headers["Cache-Control"] = "no-store"
208
+ _admin(db, user.id, user.effective_token_version)
209
+ rows = db.query(AuditCredential).order_by(AuditCredential.id.desc()).offset(offset).limit(limit).all()
210
+ return {"items": [_metadata(row) for row in rows], "limit": limit, "offset": offset}
211
+
212
+
213
+ def _managed_grant(db, public_id):
214
+ row = db.execute(select(AuditCredential).where(AuditCredential.public_id == public_id)).scalar_one_or_none()
215
+ if row is None:
216
+ _deny(404, "Audit credential not found")
217
+ return row
218
+
219
+
220
+ @router.post("/api/admin/audit-credentials/{public_id}/rotate")
221
+ @limiter.limit("10/minute")
222
+ def rotate_credential(
223
+ public_id: str,
224
+ request: Request,
225
+ response: Response,
226
+ body: GrantRotate,
227
+ user: User = Depends(require_super_admin),
228
+ db: Session = Depends(get_db),
229
+ ):
230
+ response.headers["Cache-Control"] = "no-store"
231
+ user_id, version = user.id, user.effective_token_version
232
+ with _guard:
233
+ user = _admin(db, user_id, version)
234
+ row = _managed_grant(db, public_id)
235
+ if row.revoked_at is not None:
236
+ _deny(409, "Revoked credentials cannot be reactivated")
237
+ row.bots = json.dumps(_bot_scope(db, [item["id"] for item in json.loads(row.bots)]))
238
+ row.generation += 1
239
+ row.issuer_id, row.issuer_token_version = user.id, version
240
+ row.expires_at = _now() + timedelta(seconds=body.expires_in_seconds)
241
+ token = _secret(row)
242
+ _audit(db, user, "audit_credential.rotate", grant=row, ip=request.client.host if request.client else None)
243
+ db.commit()
244
+ return {**_metadata(row), "credential": token, "shown_once": True}
245
+
246
+
247
+ @router.delete("/api/admin/audit-credentials/{public_id}", status_code=204)
248
+ def revoke_credential(
249
+ public_id: str,
250
+ request: Request,
251
+ user: User = Depends(require_super_admin),
252
+ db: Session = Depends(get_db),
253
+ ):
254
+ user_id, version = user.id, user.effective_token_version
255
+ with _guard:
256
+ user = _admin(db, user_id, version)
257
+ row = _managed_grant(db, public_id)
258
+ if row.revoked_at is None:
259
+ row.revoked_at = _now()
260
+ row.generation += 1
261
+ _audit(db, user, "audit_credential.revoke", grant=row, ip=request.client.host if request.client else None)
262
+ db.commit()
263
+ return Response(status_code=204, headers={"Cache-Control": "no-store"})
264
+
265
+
266
+ class ReadBudget:
267
+ def __init__(self):
268
+ self.hits = OrderedDict()
269
+ self.lock = threading.Lock()
270
+
271
+ def check(self, public_id):
272
+ now = time.monotonic()
273
+ with self.lock:
274
+ hits = [value for value in self.hits.pop(public_id, []) if now - value < 60]
275
+ if len(hits) >= 30:
276
+ self.hits[public_id] = hits
277
+ raise HTTPException(
278
+ 429, "Audit read budget exceeded", headers={"Retry-After": "60", "Cache-Control": "no-store"}
279
+ )
280
+ self.hits[public_id] = [*hits, now]
281
+ while len(self.hits) > 256:
282
+ self.hits.popitem(last=False)
283
+
284
+
285
+ read_budget = ReadBudget()
286
+
287
+
288
+ def _authorize(db, request, bot_id):
289
+ db.rollback()
290
+ auth = request.headers.get("Authorization", "")
291
+ scheme, _, value = auth.partition(" ")
292
+ token = value if scheme.lower() == "bearer" else ""
293
+ match = _TOKEN.fullmatch(token)
294
+ if match is None:
295
+ _deny(401, "A dedicated audit credential is required")
296
+ row = db.execute(select(AuditCredential).where(AuditCredential.public_id == match[1])).scalar_one_or_none()
297
+ if row is None or not secrets.compare_digest(row.digest, hashlib.sha256(token.encode()).hexdigest()):
298
+ _deny(401, "Audit credential is invalid or expired")
299
+ issuer = db.get(User, row.issuer_id)
300
+
301
+ def reject(status, detail, reason):
302
+ # Only proven credentials have an attributable principal. Never log submitted headers.
303
+ if issuer is not None:
304
+ _audit(
305
+ db,
306
+ issuer,
307
+ "task_notes.denied",
308
+ grant=row,
309
+ bot_id=bot_id,
310
+ count=0,
311
+ result="failure",
312
+ reason=reason,
313
+ ip=request.client.host if request.client else None,
314
+ )
315
+ db.commit()
316
+ _deny(status, detail)
317
+
318
+ if row.scope != SCOPE or row.revoked_at is not None or row.expires_at <= _now():
319
+ reject(401, "Audit credential is invalid or expired", "inactive_credential")
320
+ if (
321
+ issuer is None
322
+ or issuer.role != "super_admin"
323
+ or issuer.must_change_password
324
+ or issuer.effective_token_version != row.issuer_token_version
325
+ ):
326
+ reject(403, "Audit delegation issuer no longer has authority", "issuer_authority")
327
+ bot = db.get(Bot, bot_id)
328
+ expected = next((item for item in json.loads(row.bots) if item["id"] == bot_id), None)
329
+ if bot is None or bot.is_deleted or expected != _bot_identity(bot):
330
+ reject(403, "Bot is outside this audit delegation or its identity changed", "bot_scope")
331
+ request.state.traffic_bot_id = bot.id
332
+ return row, issuer, bot
333
+
334
+
335
+ def _notes_projection(raw):
336
+ from lockbot.backend.app.resource_api.privacy import public_event
337
+
338
+ result = public_event(raw)
339
+ for key in ("agent_label", "purpose"):
340
+ if isinstance(raw.get(key), str):
341
+ result[key] = raw[key]
342
+ result["untrusted_text"] = True
343
+ return result
344
+
345
+
346
+ def _cursor_decode(cursor, row, bot, query, limit):
347
+ try:
348
+ value = jwt.decode(cursor, config.JWT_SECRET, algorithms=["HS256"], audience="audit-notes-page")
349
+ expected = [row.public_id, row.generation, _bot_identity(bot), query, limit]
350
+ if value["scope"] != expected:
351
+ raise ValueError()
352
+ return value["cursor"]
353
+ except (jwt.PyJWTError, ValueError, KeyError, TypeError):
354
+ _deny(400, "Audit cursor is invalid, expired or belongs to another scope")
355
+
356
+
357
+ def _finish_read(db, request, bot_id, ref, generation, count):
358
+ row, issuer, bot = _authorize(db, request, bot_id)
359
+ if row.public_id != ref or row.generation != generation:
360
+ _deny(401, "Audit delegation changed during the read")
361
+ _audit(
362
+ db,
363
+ issuer,
364
+ "task_notes.read",
365
+ grant=row,
366
+ bot_id=bot_id,
367
+ count=count,
368
+ surface="agent_history" if request.url.path.endswith("/agent-history") else "current_task_notes",
369
+ ip=request.client.host if request.client else None,
370
+ )
371
+ db.commit()
372
+ # Role/password changes and identity transfers can occur outside this API's guard.
373
+ _authorize(db, request, bot_id)
374
+ return row, bot
375
+
376
+
377
+ @router.get("/api/audit/bots/{bot_id}/agent-history")
378
+ @limiter.limit("60/minute")
379
+ def task_note_history(
380
+ bot_id: int,
381
+ request: Request,
382
+ response: Response,
383
+ cursor: str | None = Query(None, max_length=2048),
384
+ query: str = Query("", max_length=128),
385
+ limit: int = Query(25, ge=1, le=100),
386
+ _credential=Depends(audit_bearer),
387
+ db: Session = Depends(get_db),
388
+ ):
389
+ from lockbot.backend.app.resource_api.event_log import READ_BUDGET, read_history
390
+
391
+ response.headers["Cache-Control"] = "no-store"
392
+ row, _, bot = _authorize(db, request, bot_id)
393
+ ref, generation = row.public_id, row.generation
394
+ expiry = min(row.expires_at, _now() + timedelta(minutes=15)).replace(tzinfo=timezone.utc).timestamp()
395
+ read_budget.check(ref)
396
+ raw_cursor = _cursor_decode(cursor, row, bot, query, limit) if cursor else None
397
+ db.rollback() # File I/O must not hold a stale authority snapshot or SQLite read transaction.
398
+ result = read_history(bot_id, limit=limit, cursor=raw_cursor, query=query, private=True, project=_notes_projection)
399
+ with _guard:
400
+ row, issuer, bot = _authorize(db, request, bot_id)
401
+ if row.public_id != ref or row.generation != generation:
402
+ _deny(401, "Audit delegation changed during the read")
403
+ next_cursor = result.get("next_cursor")
404
+ if next_cursor:
405
+ result["next_cursor"] = jwt.encode(
406
+ {
407
+ "aud": "audit-notes-page",
408
+ "exp": expiry,
409
+ "scope": [ref, generation, _bot_identity(bot), query, limit],
410
+ "cursor": next_cursor,
411
+ },
412
+ config.JWT_SECRET,
413
+ algorithm="HS256",
414
+ )
415
+ _finish_read(db, request, bot_id, ref, generation, len(result["items"]))
416
+ return {
417
+ "bot_id": bot_id,
418
+ "scope": SCOPE,
419
+ "api_version": "1",
420
+ "audit_principal": ref,
421
+ **result,
422
+ "coverage": {"source": "agent_operation_notes", "complete_history": False, "read_budget_bytes": READ_BUDGET},
423
+ }
424
+
425
+
426
+ @router.get("/api/audit/bots/{bot_id}/task-notes")
427
+ @limiter.limit("60/minute")
428
+ def current_task_notes(
429
+ bot_id: int,
430
+ request: Request,
431
+ response: Response,
432
+ limit: int = Query(100, ge=1, le=200),
433
+ _credential=Depends(audit_bearer),
434
+ db: Session = Depends(get_db),
435
+ ):
436
+ from lockbot.backend.app.bots.manager import AdmissionFull, BotNotRunning, InstanceRetiring, bot_manager
437
+ from lockbot.backend.app.resource_api.usage import active_declarations, declarations_for_state
438
+
439
+ response.headers["Cache-Control"] = "no-store"
440
+ row, _, bot = _authorize(db, request, bot_id)
441
+ ref, generation = row.public_id, row.generation
442
+ read_budget.check(ref)
443
+ rows = active_declarations(db, bot, _now(), limit=limit + 1)
444
+ try:
445
+ with bot_manager.admit(bot_id, for_read=True) as lease:
446
+ captured_at, state = lease.bot.state_snapshot()
447
+ values = declarations_for_state(rows[:limit], state, captured_at)
448
+ except (BotNotRunning, InstanceRetiring, AdmissionFull):
449
+ _deny(503, "Current task notes require an available resource-state snapshot; use history for past notes")
450
+ # Personal declaration keys, holding proofs and authorization labels are not delegated.
451
+ allowed = {
452
+ "resource_id",
453
+ "actor",
454
+ "task_category",
455
+ "public_task",
456
+ "agent_label",
457
+ "purpose",
458
+ "updated_at",
459
+ "expires_at",
460
+ "untrusted_text",
461
+ }
462
+ from lockbot.backend.app.resource_api.event_log import _safe
463
+
464
+ items = [_safe({key: value for key, value in item.items() if key in allowed}) for item in values]
465
+ with _guard:
466
+ _finish_read(db, request, bot_id, ref, generation, len(items))
467
+ return {
468
+ "bot_id": bot_id,
469
+ "scope": SCOPE,
470
+ "api_version": "1",
471
+ "audit_principal": ref,
472
+ "captured_at": captured_at.isoformat(),
473
+ "items": items,
474
+ "truncated": len(rows) > limit,
475
+ "limit": limit,
476
+ "coverage": {"source": "live_task_declarations", "complete_history": False},
477
+ }
@@ -20,6 +20,7 @@ import lockbot.backend.app.feishu.models # noqa: F401
20
20
  import lockbot.backend.app.resource_auth.models # noqa: F401
21
21
  import lockbot.backend.app.settings.models # noqa: F401
22
22
  from lockbot.backend.app.admin.router import router as admin_router
23
+ from lockbot.backend.app.audit.delegation import router as audit_delegation_router
23
24
  from lockbot.backend.app.audit.router import router as audit_router
24
25
  from lockbot.backend.app.auth.router import router as auth_router
25
26
  from lockbot.backend.app.backup.router import router as backup_router
@@ -693,6 +694,7 @@ def create_app() -> FastAPI:
693
694
 
694
695
  app.include_router(broadcast_router)
695
696
  app.include_router(audit_router)
697
+ app.include_router(audit_delegation_router)
696
698
  app.include_router(backup_router)
697
699
  from lockbot.backend.app.resource_api.discovery import router as discovery_router
698
700
 
@@ -200,3 +200,10 @@ Prepare a redacted report for [Lockbot GitHub Issues](https://github.com/dynamic
200
200
  version, endpoint, status/error code, expected and actual behavior. Remove credentials, bind
201
201
  codes, webhook secrets and private task data. Do not publish logs or file issues without
202
202
  user authorization.
203
+
204
+
205
+ ## Detailed Agent notes require a separate audit grant
206
+
207
+ An ordinary OP key never authorizes other users' Agent names or detailed task notes. If an approved audit consumer needs these fields, ask a current super administrator to issue a separate, expiring `task_notes:read` credential through `POST /api/admin/audit-credentials` with explicit bot IDs. Management, rotation and revocation require that administrator's management session. The secret is shown once; keep it in a separate secret store and send it only in the Authorization header, never a URL. Do not substitute a personal key, OP key or management JWT for this audit credential.
208
+
209
+ The dedicated routes are `GET /api/audit/bots/{bot_id}/agent-history` and `GET /api/audit/bots/{bot_id}/task-notes`. They return bounded notes, not complete resource-use totals. Refer to the repository's `docs/design/delegated-task-notes.md` and the server's `/openapi.json` (Audit delegation tag) for the versioned contract and permission boundaries. Existing Agent/OP Skill version checks do not grant or renew audit authority.
@@ -17,6 +17,7 @@ BACKUPS = 9
17
17
  _write_lock = threading.Lock()
18
18
  _secrets = re.compile(
19
19
  r"/#/r/[0-9]+/[A-Za-z0-9_-]{22}|(?:lbr_|lbk_)[A-Za-z0-9_-]+|lbv1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"
20
+ r"|lba1\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}"
20
21
  r"|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"
21
22
  r"|(?i:Bearer\s+\S+)"
22
23
  )
@@ -192,7 +193,7 @@ READ_BUDGET = 1024 * 1024
192
193
  MAX_LINE_BYTES = 64 * 1024
193
194
 
194
195
 
195
- def read_history(bot_id, *, limit=25, cursor=None, query="", private=False, stream="agent"):
196
+ def read_history(bot_id, *, limit=25, cursor=None, query="", private=False, stream="agent", project=None):
196
197
  """Newest first, inode/offset cursor: appends do not shift subsequent pages.
197
198
 
198
199
  A rotated-away cursor fails explicitly rather than silently skipping history. File
@@ -332,6 +333,8 @@ def read_history(bot_id, *, limit=25, cursor=None, query="", private=False, stre
332
333
  row[field] = public[field]
333
334
  else:
334
335
  row = public
336
+ if project is not None:
337
+ row = project(row)
335
338
  if needle and needle not in json.dumps(row, ensure_ascii=False).casefold():
336
339
  continue
337
340
  row["id"] = f"{inode}:{position}"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lockbot
3
- Version: 3.0.1
3
+ Version: 3.1.0
4
4
  Summary: Cluster resource management and queuing for Infoflow and Feishu
5
5
  Author-email: Jianbang Yang <yangjianbang112@gmail.com>
6
6
  License: MIT
@@ -27,6 +27,7 @@ python/lockbot/backend/app/admin/__init__.py
27
27
  python/lockbot/backend/app/admin/router.py
28
28
  python/lockbot/backend/app/agent_skill/SKILL.md
29
29
  python/lockbot/backend/app/audit/__init__.py
30
+ python/lockbot/backend/app/audit/delegation.py
30
31
  python/lockbot/backend/app/audit/models.py
31
32
  python/lockbot/backend/app/audit/router.py
32
33
  python/lockbot/backend/app/audit/service.py
File without changes
File without changes
File without changes
File without changes
File without changes