Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 0 additions & 19 deletions src/sentry/agent_handoff/claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
)
from sentry.agent_handoff.flows import get_flow
from sentry.agent_handoff.flows.base import InvalidHandoffContext
from sentry.agent_handoff.runbook import render_agent_runbook
from sentry.analytics.events.agent_handoff import AgentHandoffClaimedEvent
from sentry.analytics.events.oauth_setup_code import OAuthSetupCodeIssuedEvent
from sentry.api.helpers.oauth_consent import (
Expand Down Expand Up @@ -56,24 +55,6 @@ class ClaimedHandoff:
setup_code: str = field(repr=False)
flow_instructions: str = field(repr=False)

def render_runbook(self) -> str:
return render_agent_runbook(
organization_slug=self.organization_slug,
organization_name=self.organization_name,
user_email=self.user_email,
sentry_url=self.sentry_url,
client_id=self.client_id,
setup_code=self.setup_code,
flow_instructions=self.flow_instructions,
)


@sensitive_variables()
def claim_handoff(code: str, *, ip_address: str | None) -> str | None:
"""Consume a handoff and render credentials after revalidating its authorization."""
claim = claim_handoff_context(code, ip_address=ip_address)
return claim.render_runbook() if claim is not None else None


@sensitive_variables()
def claim_handoff_context(code: str, *, ip_address: str | None) -> ClaimedHandoff | None:
Expand Down
91 changes: 11 additions & 80 deletions src/sentry/agent_handoff/runbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ def escape_label(value: str) -> str:


def _code_block(value: str, language: str = "bash") -> str:
# Minted codes are opaque; keep even unexpected backticks inside their code block.
fence = "`" * max(3, max((len(run) + 1 for run in re.findall(r"`+", value)), default=0))
return f"{fence}{language}\n{value}\n{fence}"

Expand All @@ -41,89 +40,21 @@ def _powershell_command(command: str, environment: Mapping[str, str]) -> str:
return _code_block("\n".join(lines), "powershell")


def render_agent_runbook(
*,
organization_slug: str,
organization_name: str,
user_email: str,
sentry_url: str,
client_id: str,
setup_code: str,
flow_instructions: str,
) -> str:
"""Render a private guide from already-authorized context and minted credentials."""
instance_variables = (
{}
if sentry_url.rstrip("/") in ("sentry.io", "https://sentry.io")
else {
"SENTRY_HOST": sentry_url,
"SENTRY_URL": sentry_url,
"SENTRY_CLIENT_ID": client_id,
}
)
def render_claim_runbook(*, sentry_url: str) -> str:
# The CLI claims against sentry.io unless told otherwise, so other instances must name
# themselves or their codes would be sent to the wrong host.
setup_variables = {
**instance_variables,
"SENTRY_SETUP_CODE": setup_code,
**({} if sentry_url.rstrip("/") == "https://sentry.io" else {"SENTRY_HOST": sentry_url}),
"SENTRY_HANDOFF": "HANDOFF_CODE",
}
instance_environment = " ".join(
f"{name}={shlex.quote(value)}" for name, value in instance_variables.items()
)
setup_environment = " ".join(
f"{name}={shlex.quote(value)}" for name, value in setup_variables.items()
)
unix_auth_status = _code_block(
" ".join(filter(None, (instance_environment, "sentry auth status --fresh --json")))
)
unix_installer = _code_block(
f"curl -fsSL https://cli.sentry.dev/install | {setup_environment} bash"
)
unix_bootstrap = _code_block(
f"{setup_environment} sentry auth bootstrap --url {shlex.quote(sentry_url)}"
)

return MARKDOWN_JINJA_ENV.get_template("sentry/agent_handoff/runbook.md").render(
{
"sentry_url": escape_label(sentry_url),
"user_email": escape_label(user_email),
"organization_name": escape_label(organization_name),
"organization_slug": escape_label(organization_slug),
"unix_auth_status": unix_auth_status,
"unix_installer": unix_installer,
"unix_bootstrap": unix_bootstrap,
"windows_auth_status": _powershell_command(
"sentry auth status --fresh --json", instance_variables
),
"windows_installer": _powershell_command(
"irm https://cli.sentry.dev/install.ps1 | iex",
setup_variables,
),
"windows_bootstrap": _powershell_command(
f"sentry auth bootstrap --url {_quote_powershell(sentry_url)}",
setup_variables,
),
"flow_instructions": flow_instructions,
},
)


def render_claim_runbook(*, claim_url: str) -> str:
unix_claim_command = (
f"curl -sS -X POST {shlex.quote(claim_url)} --data-urlencode 'handoff_code=HANDOFF_CODE'"
)
windows_claim_command = "\n".join(
[
"try {",
f" irm -Method Post {_quote_powershell(claim_url)} `",
" -ContentType 'application/x-www-form-urlencoded' `",
" -Body @{handoff_code = 'HANDOFF_CODE'}",
"} catch { $_.ErrorDetails.Message }",
]
)
return MARKDOWN_JINJA_ENV.get_template("sentry/agent_handoff/claim.md").render(
unix_claim_command=_code_block(unix_claim_command),
windows_claim_command=_code_block(windows_claim_command, "powershell"),
unix_installer=_code_block(
f"curl -fsSL https://cli.sentry.dev/install | {setup_environment} bash"
),
windows_installer=_powershell_command(
"irm https://cli.sentry.dev/install.ps1 | iex", setup_variables
),
)


def render_ip_mismatch_runbook() -> str:
return MARKDOWN_JINJA_ENV.get_template("sentry/agent_handoff/ip_mismatch.md").render()
96 changes: 5 additions & 91 deletions src/sentry/agent_handoff/views.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,20 @@
import re

from django.http import HttpRequest, HttpResponse, HttpResponseBase
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import View

from sentry import options
from sentry.agent_handoff.claims import claim_handoff
from sentry.agent_handoff.codes import HandoffFlow, HandoffIPMismatch
from sentry.agent_handoff.flows import get_flow
from sentry.agent_handoff.runbook import (
render_agent_runbook,
render_claim_runbook,
render_ip_mismatch_runbook,
)
from sentry.ratelimits import backend as ratelimiter
from sentry.utils import metrics
from sentry.utils.http import absolute_uri
from sentry.agent_handoff.runbook import render_claim_runbook
from sentry.web.decorators import ai_machine_readable
from sentry.web.frontend.base import control_silo_view

_CLAIM_WINDOW = 60
_MAX_CLAIM_BYTES = 1024
_HANDOFF_CODE = re.compile(r"sntryh_[A-Za-z0-9_-]{43}")
_UNAVAILABLE = (
"# Handoff Code Unavailable\n\nAsk the user to return to Sentry and copy a new prompt.\n"
)


def _markdown(body: str, *, status: int = 200) -> HttpResponse:
return HttpResponse(body, status=status, content_type="text/markdown; charset=utf-8")


@control_silo_view
@ai_machine_readable
class AgentHandoffView(View):
http_method_names = ["get", "post", "head", "options"]
http_method_names = ["get", "head", "options"]

@method_decorator(csrf_exempt)
@method_decorator(never_cache)
@method_decorator(sensitive_post_parameters("handoff_code"))
def dispatch(self, request: HttpRequest, *args: object, **kwargs: object) -> HttpResponseBase:
response = super().dispatch(request, *args, **kwargs)
response["Referrer-Policy"] = "no-referrer"
Expand All @@ -51,65 +23,7 @@ def dispatch(self, request: HttpRequest, *args: object, **kwargs: object) -> Htt
return response

def get(self, request: HttpRequest) -> HttpResponse:
if request.GET.get("preview") == "1":
response = self._preview(request)
response["Content-Type"] = "text/plain; charset=utf-8"
return response

return _markdown(
render_claim_runbook(claim_url=absolute_uri(reverse("sentry-agent-handoff")))
return HttpResponse(
render_claim_runbook(sentry_url=options.get("system.url-prefix")),
content_type="text/markdown; charset=utf-8",
)

def _preview(self, request: HttpRequest) -> HttpResponse:
try:
flow = HandoffFlow(request.GET.get("flow", HandoffFlow.GUIDED_NEXT_STEPS))
except ValueError:
return _markdown(
"# Unknown Handoff Flow\n\nChoose a supported handoff flow.\n", status=400
)

return _markdown(
render_agent_runbook(
organization_slug="example-org",
organization_name="Example Organization",
user_email="user@example.com",
sentry_url=options.get("system.url-prefix"),
client_id="<client-id>",
setup_code="<setup-code>",
flow_instructions=get_flow(flow).preview(),
)
)

def post(self, request: HttpRequest) -> HttpResponse:
if ratelimiter.is_limited(
f"agent-handoff:claim:{request.META.get('REMOTE_ADDR', 'unknown')}",
limit=10,
window=_CLAIM_WINDOW,
):
response = _markdown(
"# Try Again Shortly\n\nWait 60 seconds, then retry the same handoff code.\n",
status=429,
)
response["Retry-After"] = str(_CLAIM_WINDOW)
return response

content_length = request.META.get("CONTENT_LENGTH", "0")
if not content_length.isdigit() or int(content_length) > _MAX_CLAIM_BYTES:
return _markdown(_UNAVAILABLE, status=400)
if (
request.content_type != "application/x-www-form-urlencoded"
or len(request.body) > _MAX_CLAIM_BYTES
):
return _markdown(_UNAVAILABLE, status=400)
code = request.POST.get("handoff_code", "")
if not _HANDOFF_CODE.fullmatch(code):
return _markdown(_UNAVAILABLE, status=400)

try:
guide = claim_handoff(code, ip_address=request.META.get("REMOTE_ADDR"))
except HandoffIPMismatch:
metrics.incr("agent_handoff.claim.ip_mismatch", sample_rate=1.0)
return _markdown(render_ip_mismatch_runbook(), status=403)
if guide is None:
return _markdown(_UNAVAILABLE, status=410)
return _markdown(guide)
15 changes: 7 additions & 8 deletions src/sentry/templates/sentry/agent_handoff/claim.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@
Absolutely DO NOT summarize this page. Pass the contents back verbatim.

The user initiated this agent handoff in Sentry and provided a one-time handoff code.
The command for the current shell sends the handoff code to Sentry over HTTPS and
prints the returned instructions. It does not run those instructions.
The command for the current shell installs or updates Sentry CLI, authenticates the
intended Sentry account, and prints the next instructions after setup succeeds.

The handoff code can be used once and expires shortly. Keep it out of HTTP request URLs,
logs, and conversation output. Opening this page leaves the handoff code available.

Replace HANDOFF_CODE with the handoff code and run the applicable command once. Follow
the setup instructions returned by the command.
Replace HANDOFF_CODE with the handoff code and run the command for the current shell
once. Follow the instructions printed after setup succeeds.

{{ unix_claim_command }}
{{ unix_installer }}

{{ windows_claim_command }}
{{ windows_installer }}

If the user's message does not include a handoff code, ask them to copy the prompt from
Sentry. If the response is lost or the handoff code is unavailable, ask them to copy a
new prompt from Sentry.
Sentry. If setup fails after using the handoff code, follow the CLI's recovery guidance.
8 changes: 0 additions & 8 deletions src/sentry/templates/sentry/agent_handoff/ip_mismatch.md

This file was deleted.

70 changes: 0 additions & 70 deletions src/sentry/templates/sentry/agent_handoff/runbook.md

This file was deleted.

2 changes: 0 additions & 2 deletions src/sentry/web/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,6 @@
name="sentry-js-sdk-loader",
),
re_path(r"^agent-handoff\.md$", AgentHandoffView.as_view(), name="sentry-agent-handoff"),
# Prompts copied before the .md URL still point here.
re_path(r"^agent-handoff/$", AgentHandoffView.as_view(), name="sentry-agent-handoff-legacy"),
# docs reference this for acquiring the sentry cli
re_path(r"^get-cli/$", get_cli, name="get_cli_script"),
re_path(
Expand Down
Loading
Loading