agents-framework 0.3.0__py3-none-any.whl
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.
- agents_framework-0.3.0.dist-info/METADATA +1364 -0
- agents_framework-0.3.0.dist-info/RECORD +50 -0
- agents_framework-0.3.0.dist-info/WHEEL +5 -0
- agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
- agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
- agents_framework-0.3.0.dist-info/top_level.txt +1 -0
- framework/__init__.py +0 -0
- framework/__main__.py +9 -0
- framework/action_page.py +1102 -0
- framework/approval_buttons.py +775 -0
- framework/approvals.py +678 -0
- framework/calendar_card.py +276 -0
- framework/cli.py +273 -0
- framework/codex_llm.py +401 -0
- framework/config.py +126 -0
- framework/drafter.py +263 -0
- framework/interfaces.py +96 -0
- framework/llm.py +744 -0
- framework/plugins/__init__.py +147 -0
- framework/plugins/agentmail_source.py +355 -0
- framework/plugins/approval_destination.py +478 -0
- framework/plugins/command_action.py +248 -0
- framework/plugins/digest_destination.py +546 -0
- framework/plugins/email_destination.py +248 -0
- framework/plugins/fanout_destination.py +160 -0
- framework/plugins/github_org_source.py +226 -0
- framework/plugins/github_releases_source.py +420 -0
- framework/plugins/ics_source.py +594 -0
- framework/plugins/llm_scorer.py +411 -0
- framework/plugins/multi_source.py +241 -0
- framework/plugins/reddit_source.py +625 -0
- framework/plugins/regex_scorer.py +93 -0
- framework/plugins/rss_source.py +346 -0
- framework/plugins/signal_destination.py +133 -0
- framework/plugins/slack_destination.py +461 -0
- framework/plugins/slack_draft_action.py +137 -0
- framework/plugins/slack_post_action.py +65 -0
- framework/plugins/slack_workspace_source.py +992 -0
- framework/plugins/twitter_action.py +210 -0
- framework/plugins/websearch_source.py +761 -0
- framework/plugins/wordpress_action.py +413 -0
- framework/proposals.py +246 -0
- framework/registry.py +166 -0
- framework/runlog.py +125 -0
- framework/runner.py +243 -0
- framework/schedule.py +571 -0
- framework/signal_messenger.py +1418 -0
- framework/slack.py +801 -0
- framework/state.py +39 -0
- framework/templating.py +76 -0
framework/action_page.py
ADDED
|
@@ -0,0 +1,1102 @@
|
|
|
1
|
+
"""The action page: one link, one lead, acted on without Slack (issue #124).
|
|
2
|
+
|
|
3
|
+
A third way to resolve a proposal, beside the `do <id>` reply
|
|
4
|
+
(`framework/approvals.py`) and the Block Kit button
|
|
5
|
+
(`framework/approval_buttons.py`). The reason it exists is not that a third
|
|
6
|
+
mechanism is desirable: it is that the two existing ones both require a Slack
|
|
7
|
+
account in the agent's workspace, and the people who decide on leads are not
|
|
8
|
+
all in Slack and do not want to be. A Signal group gets a blurb and a link;
|
|
9
|
+
the link opens this page; the verdict happens here.
|
|
10
|
+
|
|
11
|
+
What that buys, beyond reaching people Slack cannot:
|
|
12
|
+
|
|
13
|
+
- **There is nothing to reconcile across surfaces.** The same lead announced
|
|
14
|
+
to a Slack channel and a Signal group is one proposal with one link, so
|
|
15
|
+
resolving it resolves it everywhere by construction. Cross-surface state,
|
|
16
|
+
convergence after an outage and the double-execution window between two
|
|
17
|
+
surfaces are not solved here, they are absent.
|
|
18
|
+
- **A new surface costs nothing.** Email, SMS, a web digest: each needs only
|
|
19
|
+
to render a blurb and a URL. No surface needs a way to send a decision
|
|
20
|
+
back, which is what made approving from Signal expensive (#121: a receive
|
|
21
|
+
loop on an account only one process can hold).
|
|
22
|
+
|
|
23
|
+
Everything else is deliberately shared with the button path: the same
|
|
24
|
+
`ProposalStore`, the same compare-and-set claim, the same step runner. A tap
|
|
25
|
+
here, a click in Slack and a `do <id>` reply cannot both execute, because all
|
|
26
|
+
three take the proposal through `transition(pending -> running)` and only one
|
|
27
|
+
can win. No new concurrency reasoning was introduced and none should be.
|
|
28
|
+
|
|
29
|
+
Config, in the workspace's `config.json`:
|
|
30
|
+
|
|
31
|
+
"approvals": {
|
|
32
|
+
"channel_id": "C0123456789",
|
|
33
|
+
"bot_token_env": "SOME_BOT_TOKEN",
|
|
34
|
+
"trusted_user_ids": ["U0123456789"],
|
|
35
|
+
"action_page": {
|
|
36
|
+
"base_url": "https://example.invalid/leads",
|
|
37
|
+
"bind": "127.0.0.1",
|
|
38
|
+
"port": 8731,
|
|
39
|
+
"post_label": "Draft outreach"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
`base_url` is how the link reads to whoever receives it, which is not
|
|
44
|
+
necessarily how this process is reached: a tunnel or a reverse proxy sits in
|
|
45
|
+
between, so the two are configured separately and nothing here guesses. It is
|
|
46
|
+
the only key a *posting* run needs; `bind` and `port` are read only by the
|
|
47
|
+
listener that serves the page. `post_label` renames the first verdict, for the
|
|
48
|
+
same reason the Slack card can (#76): "Post" is wrong for an action that
|
|
49
|
+
drafts something a human will send.
|
|
50
|
+
|
|
51
|
+
## The URL is the credential, and that is the whole security model
|
|
52
|
+
|
|
53
|
+
The reply path trusts a Slack user id; the button path trusts a Slack user id.
|
|
54
|
+
A link has no identity behind it. Whoever holds the URL can act, and in a
|
|
55
|
+
Signal group that means every member, anyone who joins later and scrolls back,
|
|
56
|
+
and any device backup. This is a real reduction in authorization strength and
|
|
57
|
+
should be chosen deliberately, for a group whose members would all have been
|
|
58
|
+
in `trusted_user_ids` anyway.
|
|
59
|
+
|
|
60
|
+
It is not, however, unprecedented in this codebase: a Slack `response_url` is
|
|
61
|
+
described in `framework/approval_buttons.py` as "a bearer capability (30
|
|
62
|
+
minutes, five uses)", and the same discipline is applied here.
|
|
63
|
+
|
|
64
|
+
- **The token is not the proposal id.** Ids are short by design -- a base-36
|
|
65
|
+
counter plus three random base-36 characters, about 47 thousand
|
|
66
|
+
possibilities for a given counter value -- which is ample against someone
|
|
67
|
+
typing `do p10` into a channel and nowhere near enough for something
|
|
68
|
+
reachable over HTTP. The link carries its own `secrets.token_urlsafe(32)`,
|
|
69
|
+
compared with `secrets.compare_digest`.
|
|
70
|
+
- **A token resolves exactly one proposal**, never the store. It is useless
|
|
71
|
+
against any other lead.
|
|
72
|
+
- **Single use falls out of the claim.** The first verdict moves the
|
|
73
|
+
proposal off `pending`; every later request fails the compare-and-set and
|
|
74
|
+
is told what the proposal already is. No separate "token spent" state
|
|
75
|
+
exists to get out of step with the proposal's.
|
|
76
|
+
- **The token must not leak outward.** The page sends
|
|
77
|
+
`Referrer-Policy: no-referrer` and marks links `rel="noreferrer noopener"`,
|
|
78
|
+
because the blurb is about somebody else's web page and a plain anchor
|
|
79
|
+
would hand our token to that site in the `Referer` header. It is still in
|
|
80
|
+
the reader's browser history and in the logs of anything the request
|
|
81
|
+
passes through; `base_url` should therefore point at something private.
|
|
82
|
+
|
|
83
|
+
## A GET must never act
|
|
84
|
+
|
|
85
|
+
This is the correctness condition for the whole design, not a preference.
|
|
86
|
+
Signal, Slack and iMessage all build link previews by fetching the URL **from
|
|
87
|
+
the recipient's device**, so a link whose GET resolves the proposal is
|
|
88
|
+
resolved by the message rendering on somebody's phone, before a human has read
|
|
89
|
+
it. The same mechanism made "unsubscribe" links unusable for a decade, courtesy
|
|
90
|
+
of corporate mail scanners.
|
|
91
|
+
|
|
92
|
+
So: `GET` renders and is idempotent; only `POST` resolves. The POST carries a
|
|
93
|
+
form token the GET minted (an HMAC over the link token under a per-process
|
|
94
|
+
secret), which also means a third-party page cannot forge the request on a
|
|
95
|
+
reader's behalf -- it cannot read the GET's response to learn the field. A
|
|
96
|
+
restart between the GET and the POST invalidates the form token and the page
|
|
97
|
+
says to reload; that is the cost of keeping no server-side session.
|
|
98
|
+
|
|
99
|
+
## Nothing untrusted becomes HTML
|
|
100
|
+
|
|
101
|
+
The blurb is a Reddit post, a LinkedIn post or whatever else a source
|
|
102
|
+
produced, which is to say it is attacker-controlled text that a human asked to
|
|
103
|
+
see. It is HTML-escaped and rendered as preformatted text, and the only anchor
|
|
104
|
+
on the page is the lead's own URL, which is checked for an `http`/`https`
|
|
105
|
+
scheme first. No Markdown is turned into markup here and none should be: a
|
|
106
|
+
stored cross-site scripting bug on a page that resolves proposals would hand
|
|
107
|
+
the token and the verdict to whoever wrote the post.
|
|
108
|
+
"""
|
|
109
|
+
from __future__ import annotations
|
|
110
|
+
|
|
111
|
+
import hmac
|
|
112
|
+
import html
|
|
113
|
+
import json
|
|
114
|
+
import os
|
|
115
|
+
import secrets
|
|
116
|
+
import sys
|
|
117
|
+
import threading
|
|
118
|
+
from time import monotonic as _monotonic
|
|
119
|
+
from hashlib import sha256
|
|
120
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
121
|
+
from pathlib import Path
|
|
122
|
+
from typing import Any
|
|
123
|
+
from urllib.parse import parse_qs, urlparse
|
|
124
|
+
|
|
125
|
+
from framework.approvals import (
|
|
126
|
+
ApprovalsConfig,
|
|
127
|
+
VARIANT_DRAFT,
|
|
128
|
+
VARIANT_POST,
|
|
129
|
+
_now_iso,
|
|
130
|
+
_run_steps,
|
|
131
|
+
_slack_call,
|
|
132
|
+
has_draftable_step,
|
|
133
|
+
steps_detail,
|
|
134
|
+
)
|
|
135
|
+
from framework.config import ConfigError
|
|
136
|
+
from framework.slack import to_mrkdwn
|
|
137
|
+
from framework.proposals import (
|
|
138
|
+
STATUS_DONE,
|
|
139
|
+
STATUS_FAILED,
|
|
140
|
+
STATUS_PENDING,
|
|
141
|
+
STATUS_RUNNING,
|
|
142
|
+
STATUS_SKIPPED,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
TOKEN_FIELD = "link_token"
|
|
146
|
+
DECIDED_VIA = "link"
|
|
147
|
+
PATH_PREFIX = "/a"
|
|
148
|
+
|
|
149
|
+
_TOKEN_BYTES = 32
|
|
150
|
+
# A whole proposal page is a few KiB of form fields at the very most; anything
|
|
151
|
+
# larger is not a verdict from this page's own form.
|
|
152
|
+
_MAX_BODY = 8192
|
|
153
|
+
_VERDICTS = {"post": VARIANT_POST, "draft": VARIANT_DRAFT, "discard": "discard"}
|
|
154
|
+
_DEFAULT_BIND = "127.0.0.1"
|
|
155
|
+
_DEFAULT_PORT = 8731
|
|
156
|
+
_DEFAULT_POST_LABEL = "Post"
|
|
157
|
+
|
|
158
|
+
# Minted once per process and never stored: it only has to outlive the gap
|
|
159
|
+
# between a GET and the POST that follows it.
|
|
160
|
+
_FORM_SECRET = secrets.token_bytes(32)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class ActionPageError(RuntimeError):
|
|
164
|
+
"""The action page cannot serve: bad config, or the port is unusable."""
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class ActionPageConfig:
|
|
168
|
+
def __init__(
|
|
169
|
+
self,
|
|
170
|
+
base_url: str,
|
|
171
|
+
bind: str = _DEFAULT_BIND,
|
|
172
|
+
port: int = _DEFAULT_PORT,
|
|
173
|
+
post_label: str = _DEFAULT_POST_LABEL,
|
|
174
|
+
):
|
|
175
|
+
self.base_url = base_url.rstrip("/")
|
|
176
|
+
self.bind = bind
|
|
177
|
+
self.port = port
|
|
178
|
+
self.post_label = post_label
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def load_action_page(block: dict[str, Any], config_path: Path) -> ActionPageConfig | None:
|
|
182
|
+
"""The `approvals.action_page` block, or None when there is none.
|
|
183
|
+
|
|
184
|
+
Absent is the normal case and not an error: every deployment before #124
|
|
185
|
+
approves in Slack only.
|
|
186
|
+
"""
|
|
187
|
+
raw = block.get("action_page")
|
|
188
|
+
if raw is None:
|
|
189
|
+
retval = None
|
|
190
|
+
return retval
|
|
191
|
+
if not isinstance(raw, dict):
|
|
192
|
+
raise ConfigError(f"{config_path}: 'approvals.action_page' must be an object")
|
|
193
|
+
base_url = raw.get("base_url")
|
|
194
|
+
if not base_url or not isinstance(base_url, str):
|
|
195
|
+
raise ConfigError(
|
|
196
|
+
f"{config_path}: 'approvals.action_page.base_url' is required -- how the link "
|
|
197
|
+
"reads to whoever receives it, which is not necessarily how this process is "
|
|
198
|
+
"reached (a tunnel or proxy may sit in between)"
|
|
199
|
+
)
|
|
200
|
+
parsed = urlparse(base_url)
|
|
201
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
202
|
+
raise ConfigError(
|
|
203
|
+
f"{config_path}: 'approvals.action_page.base_url' must be an absolute "
|
|
204
|
+
f"http(s) URL; got {base_url!r}"
|
|
205
|
+
)
|
|
206
|
+
port = raw.get("port", _DEFAULT_PORT)
|
|
207
|
+
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
|
|
208
|
+
raise ConfigError(
|
|
209
|
+
f"{config_path}: 'approvals.action_page.port' must be a port number 1-65535"
|
|
210
|
+
)
|
|
211
|
+
retval = ActionPageConfig(
|
|
212
|
+
base_url=base_url,
|
|
213
|
+
bind=str(raw.get("bind", _DEFAULT_BIND)),
|
|
214
|
+
port=port,
|
|
215
|
+
post_label=str(raw.get("post_label", _DEFAULT_POST_LABEL)),
|
|
216
|
+
)
|
|
217
|
+
return retval
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def mint_token() -> str:
|
|
221
|
+
"""A link token: 32 random bytes, URL-safe, not derived from the proposal."""
|
|
222
|
+
retval = secrets.token_urlsafe(_TOKEN_BYTES)
|
|
223
|
+
return retval
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def action_path(workspace: str, token: str) -> str:
|
|
227
|
+
retval = f"{PATH_PREFIX}/{workspace}/{token}"
|
|
228
|
+
return retval
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def action_url(base_url: str, workspace: str, token: str) -> str:
|
|
232
|
+
retval = f"{base_url.rstrip('/')}{action_path(workspace, token)}"
|
|
233
|
+
return retval
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def base_url_for(workspace: str | os.PathLike) -> str | None:
|
|
237
|
+
"""`approvals.action_page.base_url` from a workspace, for a posting run.
|
|
238
|
+
|
|
239
|
+
A destination needs the base URL to render a link, and reading it from the
|
|
240
|
+
one place the listener reads it from is the point: a second config key for
|
|
241
|
+
the same value is a second thing to get out of step. Returns None when the
|
|
242
|
+
workspace does not configure an action page, which is how a destination
|
|
243
|
+
knows to post no link rather than a broken one.
|
|
244
|
+
"""
|
|
245
|
+
path = Path(workspace) / "config.json"
|
|
246
|
+
raw = json.loads(path.read_text())
|
|
247
|
+
block = raw.get("approvals") if isinstance(raw, dict) else None
|
|
248
|
+
retval = None
|
|
249
|
+
if not isinstance(block, dict):
|
|
250
|
+
return retval
|
|
251
|
+
# The same parser the listener uses, so the two cannot disagree. An earlier
|
|
252
|
+
# version read the key directly and applied none of the validation, which
|
|
253
|
+
# meant a relative `base_url` or an out-of-range `port` let the posting run
|
|
254
|
+
# mint links happily while `--listen` refused to start -- links in somebody's
|
|
255
|
+
# Signal group for a page no process serves, and nothing anywhere noticing.
|
|
256
|
+
# A malformed config now fails the run that posts, in the same words the
|
|
257
|
+
# listener would have used.
|
|
258
|
+
page = load_action_page(block, path)
|
|
259
|
+
if page is not None:
|
|
260
|
+
retval = page.base_url
|
|
261
|
+
return retval
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def find_by_token(store: Any, token: str) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
|
|
265
|
+
"""The proposal whose `link_token` is `token`, and the snapshot it came from.
|
|
266
|
+
|
|
267
|
+
Reads the whole store rather than keeping a token index: the store is one
|
|
268
|
+
small JSON file per workspace and an index is another thing that can
|
|
269
|
+
disagree with the proposals it describes.
|
|
270
|
+
|
|
271
|
+
The snapshot is returned because `siblings()` needs the same proposals and
|
|
272
|
+
used to take the store's exclusive lock a second time for them. That lock
|
|
273
|
+
is the one the Slack button path and the polling pass also take, so two
|
|
274
|
+
locked reads per request -- both of them before any credential check, so a
|
|
275
|
+
bogus token paid the same cost -- let an unauthenticated flood slow the
|
|
276
|
+
other paths by a factor of fifty at the 95th percentile on a store of a
|
|
277
|
+
few hundred KB. One read per request is the cheap half of that fix.
|
|
278
|
+
"""
|
|
279
|
+
retval: tuple[dict[str, Any] | None, list[dict[str, Any]]] = (None, [])
|
|
280
|
+
# `compare_digest` on `str` raises TypeError unless both sides are ASCII,
|
|
281
|
+
# and the path arrives decoded as iso-8859-1, so any raw byte >= 0x80 in
|
|
282
|
+
# the token segment would reach it. A real token is urlsafe base64 and so
|
|
283
|
+
# always ASCII; anything else is a miss, not an error.
|
|
284
|
+
if not token or not token.isascii():
|
|
285
|
+
return retval
|
|
286
|
+
with store._locked(): # noqa: SLF001 - the store's own read path, under its lock
|
|
287
|
+
data = store._read() # noqa: SLF001
|
|
288
|
+
proposals = data["proposals"]
|
|
289
|
+
retval = (None, proposals)
|
|
290
|
+
for proposal in proposals:
|
|
291
|
+
held = proposal.get(TOKEN_FIELD)
|
|
292
|
+
if isinstance(held, str) and secrets.compare_digest(held, token):
|
|
293
|
+
retval = (proposal, proposals)
|
|
294
|
+
break
|
|
295
|
+
return retval
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _form_token(link_token: str) -> str:
|
|
299
|
+
retval = hmac.new(_FORM_SECRET, link_token.encode(), sha256).hexdigest()
|
|
300
|
+
return retval
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _form_token_ok(link_token: str, given: str) -> bool:
|
|
304
|
+
retval = bool(given) and hmac.compare_digest(_form_token(link_token), given)
|
|
305
|
+
return retval
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _esc(value: Any) -> str:
|
|
309
|
+
retval = html.escape(str(value), quote=True)
|
|
310
|
+
return retval
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _path_without_token(path: str) -> str:
|
|
314
|
+
"""A request path with its last segment replaced, for logging.
|
|
315
|
+
|
|
316
|
+
The last segment is the token, which is the credential, so no log line may
|
|
317
|
+
carry it -- that is why the handler's own `log_message` is silenced. The
|
|
318
|
+
rest of the path is what an operator needs to tell a prefix problem from
|
|
319
|
+
an unknown workspace.
|
|
320
|
+
"""
|
|
321
|
+
parts = urlparse(path).path.strip("/").split("/")
|
|
322
|
+
if len(parts) < 2:
|
|
323
|
+
retval = "/" + "/".join(parts)
|
|
324
|
+
return retval
|
|
325
|
+
retval = "/" + "/".join(parts[:-1] + ["<token>"])
|
|
326
|
+
return retval
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
_MISS_REPORT_SECONDS = 60
|
|
330
|
+
_misses = [0, 0.0] # count since the last line, time of that line
|
|
331
|
+
_misses_lock = threading.Lock()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _count_miss(path: str) -> None:
|
|
335
|
+
"""Tally a request that resolved to nothing, and say so periodically.
|
|
336
|
+
|
|
337
|
+
A healthy page used to print nothing but the startup line until somebody
|
|
338
|
+
posted a verdict: GETs, 404s and unknown workspaces were all silent, so
|
|
339
|
+
"every tap is missing" and "nobody has tapped yet" produced identical
|
|
340
|
+
output -- which is how a wrong `base_url`, a path a proxy mangles, or a
|
|
341
|
+
workspace left out of `listen_for` stay invisible. One line a minute is
|
|
342
|
+
enough to tell those apart without turning a flood into a log of its own.
|
|
343
|
+
"""
|
|
344
|
+
with _misses_lock:
|
|
345
|
+
_misses[0] += 1
|
|
346
|
+
now = _monotonic()
|
|
347
|
+
if now - _misses[1] < _MISS_REPORT_SECONDS:
|
|
348
|
+
return
|
|
349
|
+
count, _misses[0], _misses[1] = _misses[0], 0, now
|
|
350
|
+
print(
|
|
351
|
+
f"agent: action-page served {count} request(s) that resolved to nothing "
|
|
352
|
+
f"in the last {_MISS_REPORT_SECONDS}s; most recent {_path_without_token(path)}",
|
|
353
|
+
file=sys.stderr,
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _safe_link(url: Any) -> str:
|
|
358
|
+
"""The lead's own URL as an anchor, or empty when it is not http(s).
|
|
359
|
+
|
|
360
|
+
A `javascript:` or `data:` URL in a scraped field would otherwise become a
|
|
361
|
+
clickable script on a page that resolves proposals.
|
|
362
|
+
"""
|
|
363
|
+
retval = ""
|
|
364
|
+
text = str(url or "").strip()
|
|
365
|
+
if not text:
|
|
366
|
+
return retval
|
|
367
|
+
if urlparse(text).scheme not in ("http", "https"):
|
|
368
|
+
return retval
|
|
369
|
+
retval = (
|
|
370
|
+
f'<p class="src"><a href="{_esc(text)}" rel="noreferrer noopener" '
|
|
371
|
+
f'target="_blank">{_esc(text)}</a></p>'
|
|
372
|
+
)
|
|
373
|
+
return retval
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
_STYLE = """
|
|
377
|
+
:root { color-scheme: light dark; --fg: #16181d; --bg: #fbfbfd; --mut: #5c6370;
|
|
378
|
+
--line: #d9dce3; --card: #ffffff; --accent: #2b5fd9; }
|
|
379
|
+
@media (prefers-color-scheme: dark) { :root {
|
|
380
|
+
--fg: #e7e9ee; --bg: #14161a; --mut: #9aa2b1; --line: #2b2f38; --card: #1b1e24;
|
|
381
|
+
--accent: #7aa2ff; } }
|
|
382
|
+
* { box-sizing: border-box; }
|
|
383
|
+
body { margin: 0; padding: 24px 16px; background: var(--bg); color: var(--fg);
|
|
384
|
+
font: 16px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; }
|
|
385
|
+
main { max-width: 44rem; margin: 0 auto; }
|
|
386
|
+
h1 { font-size: 1.15rem; margin: 0 0 2px; }
|
|
387
|
+
.meta { color: var(--mut); font-size: .85rem; margin: 0 0 18px; }
|
|
388
|
+
.card { background: var(--card); border: 1px solid var(--line); border-radius: 10px;
|
|
389
|
+
padding: 16px 18px; margin: 0 0 20px; }
|
|
390
|
+
pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; font: inherit; }
|
|
391
|
+
.src { margin: 14px 0 0; overflow-wrap: anywhere; font-size: .9rem; }
|
|
392
|
+
form { display: flex; flex-wrap: wrap; gap: 10px; }
|
|
393
|
+
button { font: inherit; padding: 11px 20px; border-radius: 8px; border: 1px solid var(--line);
|
|
394
|
+
background: var(--card); color: var(--fg); cursor: pointer; }
|
|
395
|
+
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
|
396
|
+
.note { color: var(--mut); font-size: .85rem; margin: 18px 0 0; }
|
|
397
|
+
.done { border-left: 3px solid var(--accent); padding-left: 14px; }
|
|
398
|
+
"""
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _page(title: str, body: str) -> bytes:
|
|
402
|
+
retval = (
|
|
403
|
+
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
|
404
|
+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
|
405
|
+
"<meta name=\"referrer\" content=\"no-referrer\">"
|
|
406
|
+
"<meta name=\"robots\" content=\"noindex, nofollow\">"
|
|
407
|
+
f"<title>{_esc(title)}</title><style>{_STYLE}</style></head>"
|
|
408
|
+
f"<body><main>{body}</main></body></html>"
|
|
409
|
+
).encode()
|
|
410
|
+
return retval
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def proposal_content(payload: dict[str, Any]) -> str:
|
|
414
|
+
"""The text a human approved, whichever of the two payload shapes holds it.
|
|
415
|
+
|
|
416
|
+
The destination records one of two shapes. `signal` mode assembles the
|
|
417
|
+
blurb itself and stores it under `rendered`; `run` mode -- which is the
|
|
418
|
+
default -- stores what the agent's `render()` returned, whose content key
|
|
419
|
+
is `body_md` with the footer alongside it. The page read only `rendered`,
|
|
420
|
+
so every `run`-mode proposal rendered "(no content recorded)" above live
|
|
421
|
+
verdict buttons and the recipient was asked to approve something they
|
|
422
|
+
could not see. `_retract_card` had the same gap, where the empty string
|
|
423
|
+
became a Slack section block that `chat.update` refuses, leaving live the
|
|
424
|
+
buttons the retraction exists to remove.
|
|
425
|
+
|
|
426
|
+
Returns "" when the payload carries no content at all, which is a caller's
|
|
427
|
+
decision to handle rather than this function's to paper over.
|
|
428
|
+
"""
|
|
429
|
+
retval = str(
|
|
430
|
+
payload.get("rendered") or payload.get("body_md") or payload.get("text") or ""
|
|
431
|
+
)
|
|
432
|
+
footer = payload.get("footer")
|
|
433
|
+
if retval and footer:
|
|
434
|
+
# `run` mode keeps the footer beside the body, and the card a human
|
|
435
|
+
# saw in Slack has them joined. `signal` mode has already joined them
|
|
436
|
+
# into `rendered` and carries no separate footer, so this adds nothing
|
|
437
|
+
# there rather than duplicating it.
|
|
438
|
+
retval += f"\n\n{footer}"
|
|
439
|
+
return retval
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def siblings(proposals: list[dict[str, Any]], proposal: dict[str, Any]) -> list[dict[str, Any]]:
|
|
443
|
+
"""Other proposals for the same lead: one per configured action.
|
|
444
|
+
|
|
445
|
+
A config with two actions announces one lead carrying two links. Both pages
|
|
446
|
+
showed the same title and the same blurb, so a recipient who resolved one
|
|
447
|
+
and then opened the other read it as "my tap did not register" and tapped
|
|
448
|
+
again -- running a *different* action deliberately. The pages now name each
|
|
449
|
+
other, which is cheaper than explaining it afterwards.
|
|
450
|
+
"""
|
|
451
|
+
retval = []
|
|
452
|
+
url = (proposal.get("payload") or {}).get("url")
|
|
453
|
+
if not url:
|
|
454
|
+
return retval
|
|
455
|
+
for other in proposals:
|
|
456
|
+
if other.get("id") == proposal.get("id"):
|
|
457
|
+
continue
|
|
458
|
+
if (other.get("payload") or {}).get("url") == url:
|
|
459
|
+
retval.append(other)
|
|
460
|
+
return retval
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def render_proposal(
|
|
464
|
+
cfg: ApprovalsConfig,
|
|
465
|
+
page: ActionPageConfig,
|
|
466
|
+
proposal: dict[str, Any],
|
|
467
|
+
proposals: list[dict[str, Any]] | None = None,
|
|
468
|
+
) -> bytes:
|
|
469
|
+
"""The GET page: the lead, then the verdicts. Reads nothing, changes nothing."""
|
|
470
|
+
payload = proposal.get("payload") or {}
|
|
471
|
+
blurb = proposal_content(payload) or "(no content recorded)"
|
|
472
|
+
lead = str(payload.get("title") or proposal["id"])
|
|
473
|
+
action = str(proposal.get("action") or "")
|
|
474
|
+
# The action is in the heading, not only in the grey line, because with
|
|
475
|
+
# more than one action per lead the heading was the only thing a recipient
|
|
476
|
+
# read and it was identical on both pages.
|
|
477
|
+
title = f"{action}: {lead}" if action else lead
|
|
478
|
+
token = str(proposal.get(TOKEN_FIELD) or "")
|
|
479
|
+
status = str(proposal.get("status") or "")
|
|
480
|
+
|
|
481
|
+
kin = siblings(proposals, proposal) if proposals else []
|
|
482
|
+
kin_note = ""
|
|
483
|
+
if kin:
|
|
484
|
+
rows = ", ".join(
|
|
485
|
+
f"{_esc(o.get('action', ''))} ({_esc(o.get('status', ''))})" for o in kin
|
|
486
|
+
)
|
|
487
|
+
kin_note = (
|
|
488
|
+
f'<p class="note">This lead has {len(kin)} other proposal(s), each with its own '
|
|
489
|
+
f"link and its own decision: {rows}. Resolving this one does not resolve those.</p>"
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
head = (
|
|
493
|
+
f"<h1>{_esc(title)}</h1>"
|
|
494
|
+
f'<p class="meta">{_esc(cfg.agent)} · proposal '
|
|
495
|
+
f"{_esc(proposal['id'])} · {_esc(action)}</p>"
|
|
496
|
+
f'<div class="card"><pre>{_esc(blurb)}</pre>{_safe_link(payload.get("url"))}</div>'
|
|
497
|
+
+ kin_note
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
if status != STATUS_PENDING:
|
|
501
|
+
retval = _page(
|
|
502
|
+
title,
|
|
503
|
+
head + f'<p class="note done">This one is already <strong>{_esc(status)}</strong>'
|
|
504
|
+
+ (
|
|
505
|
+
f" (via {_esc(proposal.get('decided_via'))})"
|
|
506
|
+
if proposal.get("decided_via")
|
|
507
|
+
else ""
|
|
508
|
+
)
|
|
509
|
+
+ ". Nothing ran just now.</p>",
|
|
510
|
+
)
|
|
511
|
+
return retval
|
|
512
|
+
|
|
513
|
+
buttons = [("post", page.post_label, "primary")]
|
|
514
|
+
if has_draftable_step(cfg, str(proposal.get("action") or "")):
|
|
515
|
+
buttons.append(("draft", "Draft", ""))
|
|
516
|
+
buttons.append(("discard", "Discard", ""))
|
|
517
|
+
fields = (
|
|
518
|
+
f'<input type="hidden" name="form_token" value="{_esc(_form_token(token))}">'
|
|
519
|
+
if token
|
|
520
|
+
else ""
|
|
521
|
+
)
|
|
522
|
+
controls = "".join(
|
|
523
|
+
f'<button class="{cls}" name="verdict" value="{verdict}">{_esc(label)}</button>'
|
|
524
|
+
for verdict, label, cls in buttons
|
|
525
|
+
)
|
|
526
|
+
retval = _page(
|
|
527
|
+
title,
|
|
528
|
+
head
|
|
529
|
+
# No `action`, so the form posts to the URL this page was fetched
|
|
530
|
+
# from. A root-relative action discarded any path a reverse proxy
|
|
531
|
+
# serves the page under -- the deployment the README describes, and
|
|
532
|
+
# the documented `base_url` carries a path -- which left the GET
|
|
533
|
+
# working and the POST going somewhere nothing listens. Posting to the
|
|
534
|
+
# current URL is correct under every proxy shape.
|
|
535
|
+
+ '<form method="post">'
|
|
536
|
+
+ fields
|
|
537
|
+
+ controls
|
|
538
|
+
+ "</form>"
|
|
539
|
+
+ '<p class="note">Acting here is the same as approving in Slack: it resolves this '
|
|
540
|
+
"lead everywhere it was posted. Whoever holds this link can act on it, so treat it "
|
|
541
|
+
"as the decision itself.</p>",
|
|
542
|
+
)
|
|
543
|
+
return retval
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _tell_slack(cfg: ApprovalsConfig, store: Any, proposal_id: str, text: str) -> str:
|
|
547
|
+
"""Mirror the verdict into the approval channel; never fail the page for it.
|
|
548
|
+
|
|
549
|
+
The proposal is already resolved by the time this runs, exactly as on the
|
|
550
|
+
reply path ("if posting the outcome fails, the status is already right").
|
|
551
|
+
The difference is that a human is holding an open page, so the failure is
|
|
552
|
+
reported to them and to stderr rather than raised.
|
|
553
|
+
|
|
554
|
+
What it must not do is lose the failure. Three things record it: the page
|
|
555
|
+
the human is holding, a stderr line carrying the proposal id and the real
|
|
556
|
+
error (a `channel_not_found` and an `invalid_auth` need different repairs,
|
|
557
|
+
and `type(exc).__name__` alone said neither), and `slack_mirrored: false`
|
|
558
|
+
on the proposal -- without which a `done` lead could leave no trace in
|
|
559
|
+
Slack at all and no durable evidence that it should have.
|
|
560
|
+
"""
|
|
561
|
+
retval = ""
|
|
562
|
+
if not cfg.bot_token or not cfg.channel_id:
|
|
563
|
+
return retval
|
|
564
|
+
try:
|
|
565
|
+
_slack_call(
|
|
566
|
+
"chat.postMessage", cfg.bot_token, cfg.timeout, channel=cfg.channel_id, text=text
|
|
567
|
+
)
|
|
568
|
+
except Exception as exc:
|
|
569
|
+
retval = f"Slack was not told ({type(exc).__name__}); the verdict is recorded regardless."
|
|
570
|
+
print(
|
|
571
|
+
f"agent={cfg.agent} action-page could not mirror proposal={proposal_id} "
|
|
572
|
+
f"to Slack: {type(exc).__name__}: {exc}",
|
|
573
|
+
file=sys.stderr,
|
|
574
|
+
)
|
|
575
|
+
current = store.get(proposal_id) or {}
|
|
576
|
+
now = current.get("status")
|
|
577
|
+
if now:
|
|
578
|
+
try:
|
|
579
|
+
store.transition(proposal_id, now, now, slack_mirrored=False)
|
|
580
|
+
except Exception as inner:
|
|
581
|
+
# The store is the thing that is broken, which is a bigger
|
|
582
|
+
# problem than the Slack failure above and used to be silent:
|
|
583
|
+
# the only line printed named Slack, so an operator read it as
|
|
584
|
+
# "Slack is down" and never learned the store was unwritable
|
|
585
|
+
# and the `slack_mirrored` marker never landed.
|
|
586
|
+
print(
|
|
587
|
+
f"agent={cfg.agent} action-page could not mark proposal={proposal_id} "
|
|
588
|
+
f"unmirrored; the store is unwritable: {type(inner).__name__}: {inner}",
|
|
589
|
+
file=sys.stderr,
|
|
590
|
+
)
|
|
591
|
+
return retval
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _retract_card(route: Any, proposal: dict[str, Any], line: str) -> bool:
|
|
595
|
+
"""Edit the Block Kit card in place, buttons replaced by the outcome.
|
|
596
|
+
|
|
597
|
+
Without this a link verdict left the Slack card untouched: live Post /
|
|
598
|
+
Draft / Discard buttons on a lead that is already closed. Clicking one was
|
|
599
|
+
always safe -- the claim refuses it -- but a reader scrolling the channel
|
|
600
|
+
had no way to know the lead was decided, which is the failure that would
|
|
601
|
+
have confused people daily.
|
|
602
|
+
|
|
603
|
+
Returns whether the card was edited, so the caller can skip the separate
|
|
604
|
+
outcome message rather than saying the same thing twice.
|
|
605
|
+
"""
|
|
606
|
+
ts = str(proposal.get("card_ts") or "")
|
|
607
|
+
cfg = route.cfg
|
|
608
|
+
retval = False
|
|
609
|
+
if not ts or not cfg.channel_id:
|
|
610
|
+
return retval
|
|
611
|
+
# Function-level: `framework/approval_buttons.py` imports this module at
|
|
612
|
+
# module scope to serve the page, so importing it back at module scope
|
|
613
|
+
# would be a cycle. This is the one thing needed from it.
|
|
614
|
+
from framework.approval_buttons import outcome_blocks
|
|
615
|
+
|
|
616
|
+
payload = proposal.get("payload") or {}
|
|
617
|
+
# A section block's text must be 1-3000 characters, so empty content makes
|
|
618
|
+
# `chat.update` answer `invalid_blocks` and the buttons stay live on a
|
|
619
|
+
# closed lead. Removing the buttons matters more than the content does, so
|
|
620
|
+
# a payload with nothing in it is still retracted, with the gap stated on
|
|
621
|
+
# the card rather than hidden.
|
|
622
|
+
content = proposal_content(payload) or "(content not recorded)"
|
|
623
|
+
try:
|
|
624
|
+
route.responder.update(
|
|
625
|
+
cfg.channel_id, ts, f"{content}\n\n{line}", outcome_blocks(to_mrkdwn(content), line)
|
|
626
|
+
)
|
|
627
|
+
retval = True
|
|
628
|
+
except Exception as exc:
|
|
629
|
+
print(
|
|
630
|
+
f"agent={cfg.agent} action-page could not retract the card for "
|
|
631
|
+
f"proposal={proposal['id']}: {type(exc).__name__}: {exc}",
|
|
632
|
+
file=sys.stderr,
|
|
633
|
+
)
|
|
634
|
+
return retval
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def resolve(route: Any, proposal: dict[str, Any], verdict: str) -> tuple[bytes, str]:
|
|
638
|
+
"""Act on one POSTed verdict; return (page bytes, log summary).
|
|
639
|
+
|
|
640
|
+
Ordering is the button path's and the reply path's, and for the same
|
|
641
|
+
reason: claim, then steps, then the terminal status, then anyone is told.
|
|
642
|
+
Every exit that does not claim leaves the proposal exactly as it was, so
|
|
643
|
+
Slack can still resolve it.
|
|
644
|
+
"""
|
|
645
|
+
cfg = route.cfg
|
|
646
|
+
store = route.store
|
|
647
|
+
proposal_id = proposal["id"]
|
|
648
|
+
payload = proposal.get("payload") or {}
|
|
649
|
+
title = str(payload.get("title") or proposal_id)
|
|
650
|
+
# No `decided_by`: the link carries no identity, and a value here would
|
|
651
|
+
# read as an actor in the store next to the Slack user ids the other two
|
|
652
|
+
# paths record. `decided_via` is the whole truth about who acted.
|
|
653
|
+
decided = {"decided_ts": _now_iso(), "decided_via": DECIDED_VIA}
|
|
654
|
+
|
|
655
|
+
def already() -> tuple[bytes, str]:
|
|
656
|
+
current = store.get(proposal_id) or {}
|
|
657
|
+
status = current.get("status", "gone")
|
|
658
|
+
body = (
|
|
659
|
+
f"<h1>{_esc(title)}</h1>"
|
|
660
|
+
f'<p class="note done">Proposal {_esc(proposal_id)} is already '
|
|
661
|
+
f"<strong>{_esc(status)}</strong>"
|
|
662
|
+
+ (f" (via {_esc(current.get('decided_via'))})" if current.get("decided_via") else "")
|
|
663
|
+
+ ". Nothing ran.</p>"
|
|
664
|
+
)
|
|
665
|
+
return (_page(title, body), f"proposal={proposal_id} verdict=already-{status} via=link")
|
|
666
|
+
|
|
667
|
+
if verdict == "discard":
|
|
668
|
+
if store.transition(proposal_id, STATUS_PENDING, STATUS_SKIPPED, **decided) is None:
|
|
669
|
+
retval = already()
|
|
670
|
+
return retval
|
|
671
|
+
line = f"Discarded from the action link at {_now_iso()}. Nothing ran."
|
|
672
|
+
note = ""
|
|
673
|
+
if not _retract_card(route, proposal, line):
|
|
674
|
+
note = _tell_slack(
|
|
675
|
+
cfg, store, proposal_id,
|
|
676
|
+
f"Proposal {proposal_id} discarded from the action link.",
|
|
677
|
+
)
|
|
678
|
+
body = (
|
|
679
|
+
f"<h1>{_esc(title)}</h1>"
|
|
680
|
+
f'<p class="note done">Discarded. Nothing ran, and proposal '
|
|
681
|
+
f"{_esc(proposal_id)} is closed.</p>"
|
|
682
|
+
+ (f'<p class="note">{_esc(note)}</p>' if note else "")
|
|
683
|
+
)
|
|
684
|
+
retval = (_page(title, body), f"proposal={proposal_id} verdict=discard via=link")
|
|
685
|
+
return retval
|
|
686
|
+
|
|
687
|
+
variant = _VERDICTS[verdict]
|
|
688
|
+
if variant == VARIANT_DRAFT and not has_draftable_step(cfg, str(proposal.get("action") or "")):
|
|
689
|
+
body = (
|
|
690
|
+
f"<h1>{_esc(title)}</h1>"
|
|
691
|
+
f'<p class="note">This action has no step a draft can draft, so there is nothing '
|
|
692
|
+
f"to draft. Proposal {_esc(proposal_id)} is still open.</p>"
|
|
693
|
+
)
|
|
694
|
+
retval = (_page(title, body), f"proposal={proposal_id} verdict=draft-refused via=link")
|
|
695
|
+
return retval
|
|
696
|
+
|
|
697
|
+
claimed = store.transition(
|
|
698
|
+
proposal_id,
|
|
699
|
+
STATUS_PENDING,
|
|
700
|
+
STATUS_RUNNING,
|
|
701
|
+
claimed_at=_now_iso(),
|
|
702
|
+
claimed_pid=os.getpid(),
|
|
703
|
+
# The pid here is the long-lived listener's, not a pass that exits.
|
|
704
|
+
# `framework/approvals.py` decides a `running` proposal is stuck partly
|
|
705
|
+
# by the claiming pid being gone, which can never happen for a claim
|
|
706
|
+
# made in this process -- so it is told which kind of claim this is.
|
|
707
|
+
claimed_via=DECIDED_VIA,
|
|
708
|
+
variant=variant,
|
|
709
|
+
**decided,
|
|
710
|
+
)
|
|
711
|
+
if claimed is None:
|
|
712
|
+
retval = already()
|
|
713
|
+
return retval
|
|
714
|
+
|
|
715
|
+
results, error = _run_steps(cfg, store, proposal, variant=variant)
|
|
716
|
+
if error is None:
|
|
717
|
+
store.transition(proposal_id, STATUS_RUNNING, STATUS_DONE, results=results)
|
|
718
|
+
status, detail = STATUS_DONE, steps_detail(results)
|
|
719
|
+
else:
|
|
720
|
+
store.transition(proposal_id, STATUS_RUNNING, STATUS_FAILED, results=results, error=error)
|
|
721
|
+
status, detail = STATUS_FAILED, f"{error} Steps: {steps_detail(results)}"
|
|
722
|
+
line = f"{status} ({variant}) from the action link at {_now_iso()}. {detail}"
|
|
723
|
+
note = ""
|
|
724
|
+
if not _retract_card(route, proposal, line):
|
|
725
|
+
note = _tell_slack(
|
|
726
|
+
cfg, store, proposal_id,
|
|
727
|
+
f"Proposal {proposal_id} {status} ({variant}) from the action link. {detail}",
|
|
728
|
+
)
|
|
729
|
+
body = (
|
|
730
|
+
f"<h1>{_esc(title)}</h1>"
|
|
731
|
+
f'<p class="note done"><strong>{_esc(status)}</strong> · {_esc(detail)}</p>'
|
|
732
|
+
+ (f'<p class="note">{_esc(note)}</p>' if note else "")
|
|
733
|
+
)
|
|
734
|
+
retval = (_page(title, body), f"proposal={proposal_id} verdict={variant} status={status} via=link")
|
|
735
|
+
return retval
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def _not_found() -> bytes:
|
|
739
|
+
"""One body for every miss: no token, wrong token, unserved workspace.
|
|
740
|
+
|
|
741
|
+
Saying which would turn the page into an oracle for guessing tokens.
|
|
742
|
+
"""
|
|
743
|
+
retval = _page(
|
|
744
|
+
"Nothing here",
|
|
745
|
+
'<h1>Nothing here</h1><p class="note">This link does not open anything. It may have '
|
|
746
|
+
"been mistyped, or it may belong to an agent this server does not serve.</p>",
|
|
747
|
+
)
|
|
748
|
+
return retval
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
class ActionPageHandler(BaseHTTPRequestHandler):
|
|
752
|
+
"""GET renders, POST resolves. `routes` is set on the server object.
|
|
753
|
+
|
|
754
|
+
`protocol_version` stays at HTTP/1.0 deliberately, which means every
|
|
755
|
+
response closes its connection. HTTP/1.1 keep-alive makes any handler that
|
|
756
|
+
answers *without* consuming the request body a request-smuggling primitive:
|
|
757
|
+
the unread bytes are parsed as the next request on the same connection, so
|
|
758
|
+
a POST to a bogus token carrying a framed POST in its body executed the
|
|
759
|
+
second one -- with no valid token on the outer request. Draining the body
|
|
760
|
+
on every early return fixes the paths this class controls, and that is done
|
|
761
|
+
below, but `BaseHTTPRequestHandler` also answers on its own (a malformed
|
|
762
|
+
request line, an unimplemented method) where there is no hook to drain
|
|
763
|
+
from. One connection per response removes the whole class instead of
|
|
764
|
+
patching its members, and the cost is nothing: a human opens this page a
|
|
765
|
+
handful of times.
|
|
766
|
+
"""
|
|
767
|
+
|
|
768
|
+
protocol_version = "HTTP/1.0"
|
|
769
|
+
# Without this a connection that opens and never finishes its request line
|
|
770
|
+
# holds a thread forever; a few dozen of them are a denial of service from
|
|
771
|
+
# one host with no credentials.
|
|
772
|
+
timeout = 15
|
|
773
|
+
|
|
774
|
+
def version_string(self) -> str:
|
|
775
|
+
# The default advertises the Python version, which is free
|
|
776
|
+
# reconnaissance for anything that finds the port.
|
|
777
|
+
retval = "agents"
|
|
778
|
+
return retval
|
|
779
|
+
|
|
780
|
+
def log_message(self, format: str, *args: Any) -> None: # noqa: A002
|
|
781
|
+
# The default writes the request line to stderr, and the request line
|
|
782
|
+
# holds the link token. One line per verdict is printed by the handler
|
|
783
|
+
# instead, with the proposal id and no token.
|
|
784
|
+
return
|
|
785
|
+
|
|
786
|
+
def _send(self, code: int, body: bytes) -> None:
|
|
787
|
+
self.send_response(code)
|
|
788
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
789
|
+
self.send_header("Content-Length", str(len(body)))
|
|
790
|
+
self.send_header("Cache-Control", "no-store")
|
|
791
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
792
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
793
|
+
self.send_header("X-Frame-Options", "DENY")
|
|
794
|
+
self.send_header(
|
|
795
|
+
"Content-Security-Policy",
|
|
796
|
+
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
797
|
+
)
|
|
798
|
+
self.end_headers()
|
|
799
|
+
self.wfile.write(body)
|
|
800
|
+
# HTTP/1.0 already implies this; stated so that raising
|
|
801
|
+
# `protocol_version` later cannot silently reopen the smuggling class.
|
|
802
|
+
self.close_connection = True
|
|
803
|
+
|
|
804
|
+
def _route(self) -> tuple[Any, dict[str, Any], str, list[dict[str, Any]]] | None:
|
|
805
|
+
"""(route, proposal, token, store snapshot) for this request's path, or None.
|
|
806
|
+
|
|
807
|
+
The snapshot travels with the proposal so that one locked read of the
|
|
808
|
+
store serves both the token lookup and the other-proposals note.
|
|
809
|
+
|
|
810
|
+
Never raises. `_route` runs before the handlers' own `try`, so an
|
|
811
|
+
exception here reaches `socketserver.handle_error` and prints a full
|
|
812
|
+
traceback per request -- which an unauthenticated caller could trigger
|
|
813
|
+
at will. A store that cannot be read is reported once per request as a
|
|
814
|
+
single line and treated as a miss, because answering differently would
|
|
815
|
+
also tell a caller which workspaces exist.
|
|
816
|
+
"""
|
|
817
|
+
try:
|
|
818
|
+
retval = self._route_inner()
|
|
819
|
+
except Exception as exc:
|
|
820
|
+
# The message, not just the type. This is the one failure here
|
|
821
|
+
# that is systematic rather than per-request -- an unreadable or
|
|
822
|
+
# hand-edited store turns every link in the group into the same
|
|
823
|
+
# "may have been mistyped" page -- and it was the only place in
|
|
824
|
+
# this module that dropped the message. The path is reported with
|
|
825
|
+
# its last segment removed, because that segment is the token.
|
|
826
|
+
print(
|
|
827
|
+
f"agent: action-page route failed for {_path_without_token(self.path)}: "
|
|
828
|
+
f"{type(exc).__name__}: {exc}",
|
|
829
|
+
file=sys.stderr,
|
|
830
|
+
)
|
|
831
|
+
retval = None
|
|
832
|
+
return retval
|
|
833
|
+
|
|
834
|
+
def _route_inner(self) -> tuple[Any, dict[str, Any], str, list[dict[str, Any]]] | None:
|
|
835
|
+
parts = urlparse(self.path).path.strip("/").split("/")
|
|
836
|
+
# The last three segments, not the only three: a reverse proxy that
|
|
837
|
+
# preserves the path serves this under whatever prefix `base_url`
|
|
838
|
+
# carries, and an exact arity match 404'd every one of those requests.
|
|
839
|
+
# A longer path grants nothing -- the token is still the whole
|
|
840
|
+
# credential, and an unknown one is still a miss.
|
|
841
|
+
if len(parts) < 3 or f"/{parts[-3]}" != PATH_PREFIX:
|
|
842
|
+
retval = None
|
|
843
|
+
return retval
|
|
844
|
+
parts = parts[-3:]
|
|
845
|
+
route = getattr(self.server, "routes", {}).get(parts[1])
|
|
846
|
+
if route is None:
|
|
847
|
+
retval = None
|
|
848
|
+
return retval
|
|
849
|
+
proposal, proposals = find_by_token(route.store, parts[2])
|
|
850
|
+
retval = None if proposal is None else (route, proposal, parts[2], proposals)
|
|
851
|
+
return retval
|
|
852
|
+
|
|
853
|
+
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler's name
|
|
854
|
+
found = self._route()
|
|
855
|
+
if found is None:
|
|
856
|
+
_count_miss(self.path)
|
|
857
|
+
self._send(404, _not_found())
|
|
858
|
+
return
|
|
859
|
+
route, proposal, _, proposals = found
|
|
860
|
+
page = getattr(self.server, "page")
|
|
861
|
+
self._send(200, render_proposal(route.cfg, page, proposal, proposals))
|
|
862
|
+
|
|
863
|
+
def do_HEAD(self) -> None: # noqa: N802
|
|
864
|
+
# Some previewers send HEAD first. Same safety as GET and no body.
|
|
865
|
+
found = self._route()
|
|
866
|
+
if found is None:
|
|
867
|
+
_count_miss(self.path)
|
|
868
|
+
self._send(200 if found else 404, b"")
|
|
869
|
+
|
|
870
|
+
def _body(self) -> bytes | None:
|
|
871
|
+
"""The whole request body, or None when the request was already refused.
|
|
872
|
+
|
|
873
|
+
Read before anything else looks at the request, so that every path out
|
|
874
|
+
of `do_POST` -- including a 404 for a token that does not exist -- has
|
|
875
|
+
consumed exactly the bytes the request declared. See the class
|
|
876
|
+
docstring for why an unread body is a smuggling primitive rather than
|
|
877
|
+
an untidiness.
|
|
878
|
+
"""
|
|
879
|
+
if self.headers.get("Transfer-Encoding"):
|
|
880
|
+
# The chunked framing is the other half of the same smuggling
|
|
881
|
+
# class, and nothing here needs it.
|
|
882
|
+
self._send(400, _page("Not supported", "<h1>Not supported</h1>"))
|
|
883
|
+
retval = None
|
|
884
|
+
return retval
|
|
885
|
+
try:
|
|
886
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
887
|
+
except ValueError:
|
|
888
|
+
length = -1
|
|
889
|
+
if not 0 <= length <= _MAX_BODY:
|
|
890
|
+
self._send(400, _page("Too large", "<h1>Too large</h1>"))
|
|
891
|
+
retval = None
|
|
892
|
+
return retval
|
|
893
|
+
try:
|
|
894
|
+
retval = self.rfile.read(length)
|
|
895
|
+
except OSError:
|
|
896
|
+
# A client that promised more than it sent; nothing was decided.
|
|
897
|
+
retval = None
|
|
898
|
+
if retval is not None and len(retval) != length:
|
|
899
|
+
self._send(400, _page("Incomplete", "<h1>Incomplete</h1>"))
|
|
900
|
+
retval = None
|
|
901
|
+
return retval
|
|
902
|
+
|
|
903
|
+
@staticmethod
|
|
904
|
+
def _fail_open_claim(route: Any, proposal_id: str, exc: Exception) -> str:
|
|
905
|
+
"""Close a claim this request made, after the request itself blew up.
|
|
906
|
+
|
|
907
|
+
Returns the status the proposal is left in, because the page has to
|
|
908
|
+
say which of three things happened and the CAS alone cannot tell them
|
|
909
|
+
apart. It misses both when the request raised before claiming -- the
|
|
910
|
+
proposal is still `pending`, nothing ran -- and when the request
|
|
911
|
+
already wrote a terminal status, where the steps really did run. The
|
|
912
|
+
page used to assert the middle case unconditionally, so a human was
|
|
913
|
+
told their decision had failed and not to retry when in fact nothing
|
|
914
|
+
had been recorded at all.
|
|
915
|
+
"""
|
|
916
|
+
try:
|
|
917
|
+
if route.store.transition(
|
|
918
|
+
proposal_id, STATUS_RUNNING, STATUS_FAILED,
|
|
919
|
+
error=f"action page raised after claiming: {type(exc).__name__}: {exc}",
|
|
920
|
+
) is not None:
|
|
921
|
+
print(
|
|
922
|
+
f"agent={route.cfg.agent} proposal={proposal_id} verdict=failed via=link "
|
|
923
|
+
f"(closed after an error; steps may have run) at={_now_iso()}",
|
|
924
|
+
flush=True,
|
|
925
|
+
)
|
|
926
|
+
return STATUS_FAILED
|
|
927
|
+
retval = str((route.store.get(proposal_id) or {}).get("status") or "")
|
|
928
|
+
print(
|
|
929
|
+
f"agent={route.cfg.agent} action-page left proposal={proposal_id} "
|
|
930
|
+
f"status={retval or 'unknown'} after the error above (no claim to close)",
|
|
931
|
+
file=sys.stderr,
|
|
932
|
+
)
|
|
933
|
+
return retval
|
|
934
|
+
except Exception as inner:
|
|
935
|
+
# Nothing further is possible: the store is what is broken. The
|
|
936
|
+
# stderr line above names the proposal, which is what a human
|
|
937
|
+
# needs to go and look.
|
|
938
|
+
print(
|
|
939
|
+
f"agent={route.cfg.agent} action-page could not close "
|
|
940
|
+
f"proposal={proposal_id}: {type(inner).__name__}: {inner}",
|
|
941
|
+
file=sys.stderr,
|
|
942
|
+
)
|
|
943
|
+
return ""
|
|
944
|
+
|
|
945
|
+
def do_POST(self) -> None: # noqa: N802
|
|
946
|
+
raw = self._body()
|
|
947
|
+
if raw is None:
|
|
948
|
+
return
|
|
949
|
+
found = self._route()
|
|
950
|
+
if found is None:
|
|
951
|
+
_count_miss(self.path)
|
|
952
|
+
self._send(404, _not_found())
|
|
953
|
+
return
|
|
954
|
+
route, proposal, token, _ = found
|
|
955
|
+
fields = parse_qs(raw.decode("utf-8", "replace"))
|
|
956
|
+
if not _form_token_ok(token, (fields.get("form_token") or [""])[0]):
|
|
957
|
+
self._send(
|
|
958
|
+
400,
|
|
959
|
+
_page(
|
|
960
|
+
"Reload this page",
|
|
961
|
+
'<h1>Reload this page</h1><p class="note">This form is from an older '
|
|
962
|
+
"session of the server, or did not come from this page. Nothing ran -- "
|
|
963
|
+
"reload and act again.</p>",
|
|
964
|
+
),
|
|
965
|
+
)
|
|
966
|
+
return
|
|
967
|
+
verdict = (fields.get("verdict") or [""])[0]
|
|
968
|
+
if verdict not in _VERDICTS:
|
|
969
|
+
self._send(400, _page("Unknown verdict", "<h1>Unknown verdict</h1>"))
|
|
970
|
+
return
|
|
971
|
+
try:
|
|
972
|
+
body, summary = resolve(route, proposal, verdict)
|
|
973
|
+
except Exception as exc:
|
|
974
|
+
# One bad request must not take the server down. But the proposal
|
|
975
|
+
# may already be claimed, and a claim made here can never go stale
|
|
976
|
+
# the way the polling pass's does -- its pid is the listener's and
|
|
977
|
+
# stays alive -- so leaving it `running` hid it from `stuck=N` for
|
|
978
|
+
# the whole `hours` window while its steps had really run. Close it
|
|
979
|
+
# as failed, best effort, and say the error out loud.
|
|
980
|
+
print(
|
|
981
|
+
f"agent={route.cfg.agent} action-page failed on "
|
|
982
|
+
f"proposal={proposal['id']}: {type(exc).__name__}: {exc}",
|
|
983
|
+
file=sys.stderr,
|
|
984
|
+
)
|
|
985
|
+
state = self._fail_open_claim(route, proposal["id"], exc)
|
|
986
|
+
if state == STATUS_FAILED:
|
|
987
|
+
note = (
|
|
988
|
+
"The decision was recorded as failed. Some of its steps may already "
|
|
989
|
+
"have run, so check before trying again rather than tapping twice."
|
|
990
|
+
)
|
|
991
|
+
elif state in (STATUS_DONE, STATUS_SKIPPED):
|
|
992
|
+
note = (
|
|
993
|
+
"The decision itself went through and its steps ran; what failed came "
|
|
994
|
+
"afterwards, telling the other places about it. Do not tap again."
|
|
995
|
+
)
|
|
996
|
+
else:
|
|
997
|
+
note = (
|
|
998
|
+
"Nothing was recorded and nothing ran -- the error came before the "
|
|
999
|
+
"decision was taken. This lead is still open and can be acted on again."
|
|
1000
|
+
)
|
|
1001
|
+
self._send(
|
|
1002
|
+
500,
|
|
1003
|
+
_page("That did not work", f'<h1>That did not work</h1><p class="note">{note}</p>'),
|
|
1004
|
+
)
|
|
1005
|
+
return
|
|
1006
|
+
print(f"agent={route.cfg.agent} {summary} at={_now_iso()}", flush=True)
|
|
1007
|
+
self._send(200, body)
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
class _BoundedHTTPServer(ThreadingHTTPServer):
|
|
1011
|
+
"""`ThreadingHTTPServer` with a ceiling on concurrent connections.
|
|
1012
|
+
|
|
1013
|
+
The handler's `timeout` is per socket operation, not per request: it
|
|
1014
|
+
reclaims an *idle* connection after 15s, but a client that sends one byte
|
|
1015
|
+
every ten seconds resets it on every byte and keeps its thread for as long
|
|
1016
|
+
as it cares to. Nothing here bounds how long one connection lasts, so what
|
|
1017
|
+
this class bounds is how many of them there can be: the mixin spawns a
|
|
1018
|
+
thread per connection with no limit, so a flood from a single host
|
|
1019
|
+
exhausts the laptop's threads -- and with them the Socket Mode listener in
|
|
1020
|
+
the same process and anything else sharing the machine.
|
|
1021
|
+
|
|
1022
|
+
The ceiling converts that into a bounded, visible refusal, which is a
|
|
1023
|
+
better failure but is still one: enough held connections make the page
|
|
1024
|
+
unavailable to the person it was sent to. That is accepted rather than
|
|
1025
|
+
solved, because it cannot be solved here. A per-client ceiling would be the
|
|
1026
|
+
usual answer and is the wrong one for this deployment -- behind a tunnel or
|
|
1027
|
+
a reverse proxy every connection arrives from the proxy, so a per-address
|
|
1028
|
+
limit would throttle the normal case and leave the abnormal one untouched.
|
|
1029
|
+
|
|
1030
|
+
What actually bounds it is not being reachable by strangers: `bind`
|
|
1031
|
+
defaults to loopback, and a non-loopback bind is warned about at startup.
|
|
1032
|
+
This is a page for a handful of people behind a tailnet or a tunnel you
|
|
1033
|
+
control, not an internet-facing server, and an stdlib threaded server
|
|
1034
|
+
should not be asked to be one.
|
|
1035
|
+
"""
|
|
1036
|
+
|
|
1037
|
+
max_connections = 64
|
|
1038
|
+
|
|
1039
|
+
def __init__(self, *args: Any, **kwargs: Any):
|
|
1040
|
+
super().__init__(*args, **kwargs)
|
|
1041
|
+
self._slots = threading.BoundedSemaphore(self.max_connections)
|
|
1042
|
+
|
|
1043
|
+
def process_request(self, request: Any, client_address: Any) -> None:
|
|
1044
|
+
if not self._slots.acquire(blocking=False):
|
|
1045
|
+
print(
|
|
1046
|
+
f"agent: action-page refused a connection; all {self.max_connections} "
|
|
1047
|
+
"slots are busy",
|
|
1048
|
+
file=sys.stderr,
|
|
1049
|
+
)
|
|
1050
|
+
self.shutdown_request(request)
|
|
1051
|
+
return
|
|
1052
|
+
super().process_request(request, client_address)
|
|
1053
|
+
|
|
1054
|
+
def process_request_thread(self, request: Any, client_address: Any) -> None:
|
|
1055
|
+
try:
|
|
1056
|
+
super().process_request_thread(request, client_address)
|
|
1057
|
+
finally:
|
|
1058
|
+
self._slots.release()
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
def serve_action_page(routes: dict[str, Any], page: ActionPageConfig) -> ThreadingHTTPServer:
|
|
1062
|
+
"""Start the action page on its own thread and return the server.
|
|
1063
|
+
|
|
1064
|
+
A thread rather than a process, so the page and the Socket Mode client
|
|
1065
|
+
share one `ProposalStore` per workspace and therefore one claim. Binding
|
|
1066
|
+
failure is raised here, at start, rather than discovered when somebody taps
|
|
1067
|
+
a link.
|
|
1068
|
+
"""
|
|
1069
|
+
try:
|
|
1070
|
+
server = _BoundedHTTPServer((page.bind, page.port), ActionPageHandler)
|
|
1071
|
+
except OSError as exc:
|
|
1072
|
+
raise ActionPageError(
|
|
1073
|
+
f"action page cannot bind {page.bind}:{page.port}: {exc}"
|
|
1074
|
+
) from exc
|
|
1075
|
+
if page.bind not in ("127.0.0.1", "::1", "localhost"):
|
|
1076
|
+
# Not fatal: a tailnet address is a legitimate bind. But the page has
|
|
1077
|
+
# no authentication beyond the link token and no rate limiting worth
|
|
1078
|
+
# the name, so a bind reachable by strangers is nearly always a
|
|
1079
|
+
# mistake, and finding out from the logs beats finding out otherwise.
|
|
1080
|
+
print(
|
|
1081
|
+
f"agent: action page is bound to {page.bind}, not loopback. Anything that can "
|
|
1082
|
+
"reach it can try link tokens and can exhaust its connection ceiling; put it "
|
|
1083
|
+
"behind a tailnet or a tunnel you control rather than a public interface.",
|
|
1084
|
+
file=sys.stderr,
|
|
1085
|
+
)
|
|
1086
|
+
# `ThreadingHTTPServer.shutdown()` stops `serve_forever` and leaves the
|
|
1087
|
+
# listening socket open, so a second bind in the same process fails with
|
|
1088
|
+
# EADDRINUSE. In production every caller of shutdown() is on its way to
|
|
1089
|
+
# process exit and the OS reclaims the fd regardless, but a method that
|
|
1090
|
+
# does not finish its job is something a later caller will rely on.
|
|
1091
|
+
_close = server.shutdown
|
|
1092
|
+
|
|
1093
|
+
def shutdown_and_close() -> None:
|
|
1094
|
+
_close()
|
|
1095
|
+
server.server_close()
|
|
1096
|
+
|
|
1097
|
+
server.shutdown = shutdown_and_close # type: ignore[method-assign]
|
|
1098
|
+
server.routes = routes # type: ignore[attr-defined]
|
|
1099
|
+
server.page = page # type: ignore[attr-defined]
|
|
1100
|
+
server.daemon_threads = True
|
|
1101
|
+
threading.Thread(target=server.serve_forever, name="action-page", daemon=True).start()
|
|
1102
|
+
return server
|