Skip to content

Commit 1f66aed

Browse files
simonwclaude
andcommitted
Ask the user to approve CSP origins granted by agent tools
An allowed origin is a channel for data to leave a sandboxed app, so the agent should not be able to add one silently. app_create now pauses with context.ask_user() to list any requested csp_origins and what allowing them means before the app is created, after the existing allow-list and apps-set-csp checks. Declining leaves nothing created. Adds an app_set_csp_origins tool so the agent can change the allowed origins of an existing app, which previously required the edit page. Newly added origins go through the same approval prompt; origins the app already has may be kept even when outside the configured allow-list, matching the edit page. Pure removals and no-op calls do not prompt. The stored query and CSP flows share one _ask_approval helper. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AntsSDFjTehLtuZhQQPQyD
1 parent 1438a2a commit 1f66aed

4 files changed

Lines changed: 835 additions & 34 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,9 @@ Stored query access is configured using a picker on the create and edit pages. T
7373

7474
### Agent tools
7575

76-
If [datasette-agent](https://github.com/datasette/datasette-agent) is installed, this plugin registers tools that let the agent build and edit stored apps: `app_list`, `app_create`, `app_view`, `app_str_replace`, `app_insert`, `app_edit`, `app_render`, `app_set_stored_queries` and `app_debug`. These respect the same `create-app` and `edit-app` permissions as the web interface.
76+
If [datasette-agent](https://github.com/datasette/datasette-agent) is installed, this plugin registers tools that let the agent build and edit stored apps: `app_list`, `app_create`, `app_view`, `app_str_replace`, `app_insert`, `app_edit`, `app_render`, `app_set_stored_queries`, `app_set_csp_origins` and `app_debug`. These respect the same `create-app`, `edit-app` and `apps-set-csp` permissions as the web interface.
7777

78-
Allowing an app to call stored queries is a data access grant, so the agent cannot do it on its own. When `app_create` is called with `stored_queries`, or `app_set_stored_queries` adds a query an app did not already have, the agent pauses and asks you to approve the grant in the chat. The question shows each query's name, title, description, parameters, whether it is a write query and its full SQL, plus any queries that would lose access. Approving creates the app or records a new app revision; declining leaves things unchanged and tells the agent to check with you. Queries that do not exist or that you cannot view are rejected before you are asked, and removing queries from an app does not require approval.
78+
Allowing an app to call stored queries or contact external origins is a data access grant, so the agent cannot do it on its own. When `app_create` is called with `stored_queries` or `csp_origins`, when `app_set_stored_queries` adds a query an app did not already have, or when `app_set_csp_origins` adds a new origin, the agent pauses and asks you to approve the grant in the chat. For stored queries the question shows each query's name, title, description, parameters, whether it is a write query and its full SQL. For origins it lists each new origin and explains that the app could send data it can read to them. Both questions also list any queries or origins that would lose access. Approving creates the app or records a new app revision; declining leaves things unchanged and tells the agent to check with you. Queries that do not exist or that you cannot view, and origins outside the allow-list for users without `apps-set-csp`, are rejected before you are asked. Removing queries or origins from an app does not require approval.
7979

8080
### Permissions
8181

‎datasette_apps/agent_tools.py‎

Lines changed: 239 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,10 @@
4646
"create": (
4747
"Create a new stored Datasette HTML app. Use this when the user asks "
4848
"you to build a new app and you do not already have an app_id. "
49-
"Passing stored_queries pauses to ask the user to approve that "
50-
"access before the app is created, so mention which stored queries "
51-
"the app needs and why before calling this." + APP_RUNTIME_API_GUIDANCE
49+
"Passing stored_queries or csp_origins pauses to ask the user to "
50+
"approve that access before the app is created, so mention which "
51+
"stored queries and origins the app needs and why before calling "
52+
"this." + APP_RUNTIME_API_GUIDANCE
5253
),
5354
"set_stored_queries": (
5455
"Replace the allow-list of stored queries an existing stored "
@@ -59,6 +60,16 @@
5960
"stored queries the app needs and why before calling this. Requires "
6061
"edit permission for that app."
6162
),
63+
"set_csp_origins": (
64+
"Replace the allow-list of exact https:// origins an existing stored "
65+
"Datasette app may contact for scripts, styles, images, and fetch "
66+
"requests. Pass the complete list; any origin not included is "
67+
"removed from the app. Adding an origin the app did not already have "
68+
"pauses to ask the user to approve it, because an allowed origin can "
69+
"be used to send data out of the app, so mention which origins the "
70+
"app needs and why before calling this. Requires edit permission for "
71+
"that app."
72+
),
6273
"view": (
6374
"View the current HTML source for a stored Datasette app, with "
6475
"line numbers. Requires edit permission for that app."
@@ -347,30 +358,111 @@ def _stored_query_access_text(app_name, granted, removed=()):
347358
return "\n".join(lines)
348359

349360

350-
async def _ask_stored_query_approval(context, app_name, granted, removed=()):
351-
"""Ask the user to approve granting an app these stored queries.
361+
async def _ask_approval(context, prompt, *, html, text, unavailable_message):
362+
"""Ask the user a yes/no approval question.
352363
353364
Returns True or False. In an interactive conversation this suspends
354365
the turn (QuestionPending propagates); when questions are unsupported
355366
it returns an error string for the model instead.
356367
"""
357368
if context is None:
358-
return _error(STORED_QUERY_APPROVAL_UNAVAILABLE)
369+
return _error(unavailable_message)
359370
try:
360-
approved = await context.ask_user(
361-
_stored_query_access_prompt(app_name, granted),
362-
html=_stored_query_access_html(app_name, granted, removed),
363-
text=_stored_query_access_text(app_name, granted, removed),
364-
)
371+
approved = await context.ask_user(prompt, html=html, text=text)
365372
except Exception as e:
366373
# Matched by name so datasette-agent stays an optional dependency;
367374
# QuestionPending (an llm.PauseChain) must keep propagating.
368375
if e.__class__.__name__ == "QuestionsNotSupported":
369-
return _error(STORED_QUERY_APPROVAL_UNAVAILABLE)
376+
return _error(unavailable_message)
370377
raise
371378
return bool(approved)
372379

373380

381+
async def _ask_stored_query_approval(context, app_name, granted, removed=()):
382+
"""Ask the user to approve granting an app these stored queries."""
383+
return await _ask_approval(
384+
context,
385+
_stored_query_access_prompt(app_name, granted),
386+
html=_stored_query_access_html(app_name, granted, removed),
387+
text=_stored_query_access_text(app_name, granted, removed),
388+
unavailable_message=STORED_QUERY_APPROVAL_UNAVAILABLE,
389+
)
390+
391+
392+
CSP_ORIGIN_APPROVAL_UNAVAILABLE = (
393+
"Allowing an app to contact external origins requires the user's "
394+
"approval, which is not available in this context. The user can set "
395+
"allowed origins themselves on the app's edit page."
396+
)
397+
398+
CSP_ORIGIN_ACCESS_NOTE = (
399+
"Allowed origins can serve the app's scripts, stylesheets and images "
400+
"and receive fetch requests, so the app could send data it can read "
401+
"to them."
402+
)
403+
404+
405+
def _csp_origins_prompt(app_name, added):
406+
return "Allow {} to contact {} external origin{}?".format(
407+
app_name, len(added), "" if len(added) == 1 else "s"
408+
)
409+
410+
411+
def _csp_origins_html(app_name, added, removed=()):
412+
"""Trusted HTML shown above the approval question: every origin the app
413+
would gain, plus a plain statement of what that lets it do."""
414+
parts = [
415+
'<div class="datasette-app-csp-origin-approval">',
416+
"<p><strong>{}</strong> will be allowed to contact {} external "
417+
"origin{}:</p>".format(
418+
html.escape(app_name), len(added), "" if len(added) == 1 else "s"
419+
),
420+
"<ul>{}</ul>".format(
421+
"".join(
422+
"<li><code>{}</code></li>".format(html.escape(origin))
423+
for origin in added
424+
)
425+
),
426+
"<p>{}</p>".format(html.escape(CSP_ORIGIN_ACCESS_NOTE)),
427+
]
428+
if removed:
429+
parts.append(
430+
"<p>Access will be removed for: {}</p>".format(
431+
", ".join(
432+
"<code>{}</code>".format(html.escape(origin)) for origin in removed
433+
)
434+
)
435+
)
436+
parts.append("</div>")
437+
return "".join(parts)
438+
439+
440+
def _csp_origins_text(app_name, added, removed=()):
441+
lines = [
442+
"{} will be allowed to contact {} external origin{}:".format(
443+
app_name, len(added), "" if len(added) == 1 else "s"
444+
)
445+
]
446+
lines.extend(" " + origin for origin in added)
447+
lines.append("")
448+
lines.append(CSP_ORIGIN_ACCESS_NOTE)
449+
if removed:
450+
lines.append("")
451+
lines.append("Access will be removed for: " + ", ".join(removed))
452+
return "\n".join(lines)
453+
454+
455+
async def _ask_csp_origins_approval(context, app_name, added, removed=()):
456+
"""Ask the user to approve letting an app contact these origins."""
457+
return await _ask_approval(
458+
context,
459+
_csp_origins_prompt(app_name, added),
460+
html=_csp_origins_html(app_name, added, removed),
461+
text=_csp_origins_text(app_name, added, removed),
462+
unavailable_message=CSP_ORIGIN_APPROVAL_UNAVAILABLE,
463+
)
464+
465+
374466
def _declined(message, app_id=None):
375467
payload = {"ok": False, "cancelled": True, "message": message}
376468
if app_id is not None:
@@ -430,6 +522,19 @@ async def _app_create(
430522
"proceed - for example, call app_create again without "
431523
"stored_queries."
432524
)
525+
if csp_origins:
526+
# An allowed origin is a channel for data to leave the app, so it
527+
# is approved the same way, before the app exists.
528+
approved = await _ask_csp_origins_approval(context, name, csp_origins)
529+
if approved is not True:
530+
if isinstance(approved, str):
531+
return approved
532+
return _declined(
533+
"The user declined to let this app contact the requested "
534+
"origins, so the app was not created. Ask the user how to "
535+
"proceed - for example, call app_create again without "
536+
"csp_origins."
537+
)
433538
try:
434539
app = await Registry(datasette).create_stored_app(
435540
actor_id=_actor_id(actor),
@@ -449,6 +554,7 @@ async def _app_create(
449554
"name": app["name"],
450555
"version": app["current_version"],
451556
"stored_queries": app["stored_queries"],
557+
"csp_origins": csp_origins,
452558
"status": (
453559
"Created app. The user can open it with the rendered View app "
454560
"link above."
@@ -590,29 +696,43 @@ async def _with_app_edit_permission(datasette, actor, app_id, callback):
590696
return await callback()
591697

592698

593-
def _csp_origins_schema_description(datasette=None):
594-
description = (
595-
"Optional exact https:// origins this app may contact "
596-
"for scripts, styles, images, and fetch requests"
597-
)
699+
def _csp_origins_rules_description(datasette):
700+
"""The allow-list or permission rules that apply to setting origins."""
598701
if datasette is None:
599-
return description
702+
return ""
600703
# The schema is built once at registration time, not per-actor, so this
601704
# describes the rules for users without the apps-set-csp permission.
602705
allowlist = configured_csp_allowlist(datasette)
603706
if allowlist:
604-
return description + (
707+
return (
605708
". Origins must come from this allow-list: {} "
606709
"(the apps-set-csp permission lifts this restriction)".format(
607710
", ".join(allowlist)
608711
)
609712
)
610-
return description + (
713+
return (
611714
". Requires the apps-set-csp permission; no origin allow-list is "
612715
"configured, so users without that permission cannot set origins"
613716
)
614717

615718

719+
def _csp_origins_schema_description(datasette=None):
720+
return (
721+
"Optional exact https:// origins this app may contact for scripts, "
722+
"styles, images, and fetch requests. The user is asked to approve this "
723+
"access before the app is created" + _csp_origins_rules_description(datasette)
724+
)
725+
726+
727+
def _set_csp_origins_schema_description(datasette=None):
728+
return (
729+
"The complete list of exact https:// origins this app may contact for "
730+
"scripts, styles, images, and fetch requests; an empty list removes all "
731+
"network access. The user is asked to approve newly added origins"
732+
+ _csp_origins_rules_description(datasette)
733+
)
734+
735+
616736
async def _app_set_stored_queries(
617737
datasette, actor, app_id, stored_queries, context=None
618738
):
@@ -669,18 +789,85 @@ async def _app_set_stored_queries(
669789
"status": "Updated stored query access; saved as app revision v{}.".format(
670790
version["version"]
671791
),
672-
"_html": _render_app(
673-
Editable(
674-
ref=app_id,
675-
content="",
676-
metadata={
677-
"app_id": app_id,
678-
"name": app["name"],
679-
"path": datasette.urls.path(app["path"]),
680-
},
681-
version=version["version"],
682-
)
683-
)["_html"],
792+
"_html": _render_app_update(datasette, app, version["version"]),
793+
}
794+
)
795+
796+
797+
def _render_app_update(datasette, app, version):
798+
return _render_app(
799+
Editable(
800+
ref=app["id"],
801+
content="",
802+
metadata={
803+
"app_id": app["id"],
804+
"name": app["name"],
805+
"path": datasette.urls.path(app["path"]),
806+
},
807+
version=version,
808+
)
809+
)["_html"]
810+
811+
812+
async def _app_set_csp_origins(datasette, actor, app_id, csp_origins, context=None):
813+
if not await _can_edit_app(datasette, actor, app_id):
814+
return _error("Permission denied: edit-app", app_id=app_id)
815+
registry = Registry(datasette)
816+
app = await registry.get_app(app_id)
817+
if app is None or app["external"]:
818+
return _error("Stored app not found", app_id=app_id)
819+
current = await registry.get_csp_origins(app_id)
820+
try:
821+
# Like the edit page, origins the app already has may be kept even
822+
# when they are outside the configured allow-list.
823+
resolved = await resolve_csp_origins(
824+
datasette, actor, csp_origins or [], existing_origins=current
825+
)
826+
except ValueError as e:
827+
return _error(str(e), app_id=app_id)
828+
resolved = sorted(resolved)
829+
added = [origin for origin in resolved if origin not in current]
830+
removed = [origin for origin in current if origin not in resolved]
831+
if not added and not removed:
832+
return json.dumps(
833+
{
834+
"app_id": app_id,
835+
"csp_origins": resolved,
836+
"status": "No change: the app already had exactly these origins.",
837+
}
838+
)
839+
if added:
840+
# Only new origins need approval - dropping access is not a
841+
# data-access decision. ask_user() replays its stored answer when
842+
# this call re-executes, so it must come before the update.
843+
approved = await _ask_csp_origins_approval(
844+
context, app["name"] or app_id, added, removed
845+
)
846+
if approved is not True:
847+
if isinstance(approved, str):
848+
return approved
849+
return _declined(
850+
"The user declined to let this app contact the requested "
851+
"origins, so its allowed origins were left unchanged. Ask the "
852+
"user how to proceed.",
853+
app_id=app_id,
854+
)
855+
try:
856+
await registry.set_csp_origins(app_id, resolved, actor_id=_actor_id(actor))
857+
except KeyError:
858+
return _error("Stored app not found", app_id=app_id)
859+
version = await registry.get_current_version(app_id)
860+
return json.dumps(
861+
{
862+
"app_id": app_id,
863+
"version": version["version"],
864+
"csp_origins": resolved,
865+
"added": added,
866+
"removed": removed,
867+
"status": "Updated allowed origins; saved as app revision v{}.".format(
868+
version["version"]
869+
),
870+
"_html": _render_app_update(datasette, app, version["version"]),
684871
}
685872
)
686873

@@ -1007,6 +1194,26 @@ async def app_render(datasette, actor, app_id):
10071194
},
10081195
fn=_app_set_stored_queries,
10091196
),
1197+
AgentTool(
1198+
name="app_set_csp_origins",
1199+
description=APP_TOOL_DESCRIPTIONS["set_csp_origins"],
1200+
input_schema={
1201+
"type": "object",
1202+
"properties": {
1203+
"app_id": {
1204+
"type": "string",
1205+
"description": "The stored Datasette app ID",
1206+
},
1207+
"csp_origins": {
1208+
"type": "array",
1209+
"description": _set_csp_origins_schema_description(datasette),
1210+
"items": {"type": "string"},
1211+
},
1212+
},
1213+
"required": ["app_id", "csp_origins"],
1214+
},
1215+
fn=_app_set_csp_origins,
1216+
),
10101217
AgentTool(
10111218
name="app_debug",
10121219
description=APP_TOOL_DESCRIPTIONS["debug"],

0 commit comments

Comments
 (0)