Skip to content

Automate browser based workflows with AI

Omit request bodies for restricted organizations (SKY-18935) (#9056)

Aaron Perez7b0774b21845
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 315c7ecc5..425176c34 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -7284,6 +7284,54 @@
"title": "Until"
}
},
+ {
+ "name": "action",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Action"
+ }
+ },
+ {
+ "name": "actor_user_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Actor User Id"
+ }
+ },
+ {
+ "name": "resource_type",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Resource Type"
+ }
+ },
{
"name": "limit",
"in": "query",
@@ -7372,6 +7420,138 @@
}
]
}
+ },
+ "/v1/audit-events/runs/export": {
+ "get": {
+ "tags": [
+ "Server"
+ ],
+ "summary": "Export workflow run activity",
+ "description": "Export top-level workflow runs for the authenticated organization as JSON or CSV. Only organization admins and full API keys may export. The default window is the last 90 days, with timezone-aware since/until bounds, newest-first keyset pagination, and a maximum page size of 500. CSV output uses fixed columns and is protected from spreadsheet formula execution.",
+ "operationId": "export_run_activity_v1_audit_events_runs_export_get",
+ "parameters": [
+ {
+ "name": "since",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Since"
+ }
+ },
+ {
+ "name": "until",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Until"
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 500,
+ "minimum": 1,
+ "default": 100,
+ "title": "Limit"
+ }
+ },
+ {
+ "name": "cursor",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Cursor"
+ }
+ },
+ {
+ "name": "format",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "enum": [
+ "json",
+ "csv"
+ ],
+ "type": "string",
+ "default": "json",
+ "title": "Format"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "A page of workflow run activity as JSON, or a CSV download when format=csv.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RunActivityExportResponse"
+ }
+ },
+ "text/csv": {
+ "schema": {
+ "type": "string",
+ "format": "binary"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "The caller must be an organization admin or use a full API key.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AuditExportDenialResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "x-fern-sdk-method-name": "export_run_activity",
+ "security": [
+ {
+ "ApiKeyAuth": []
+ }
+ ]
+ }
}
},
"components": {
@@ -22039,6 +22219,118 @@
"type": "object",
"title": "RetryRunWebhookRequest"
},
+ "RunActivityExportResponse": {
+ "properties": {
+ "rows": {
+ "items": {
+ "$ref": "#/components/schemas/RunActivityExportRow"
+ },
+ "type": "array",
+ "title": "Rows"
+ },
+ "next": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Next"
+ }
+ },
+ "type": "object",
+ "required": [
+ "rows",
+ "next"
+ ],
+ "title": "RunActivityExportResponse"
+ },
+ "RunActivityExportRow": {
+ "properties": {
+ "workflow_run_id": {
+ "type": "string",
+ "title": "Workflow Run Id"
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At"
+ },
+ "workflow_permanent_id": {
+ "type": "string",
+ "title": "Workflow Permanent Id"
+ },
+ "trigger_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Trigger Type"
+ },
+ "created_by": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Created By"
+ },
+ "requested_by": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Requested By"
+ },
+ "workflow_schedule_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Workflow Schedule Id"
+ },
+ "retried_from_workflow_run_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Retried From Workflow Run Id"
+ }
+ },
+ "type": "object",
+ "required": [
+ "workflow_run_id",
+ "created_at",
+ "workflow_permanent_id",
+ "trigger_type",
+ "created_by",
+ "requested_by",
+ "workflow_schedule_id",
+ "retried_from_workflow_run_id"
+ ],
+ "title": "RunActivityExportRow"
+ },
"RunEngine": {
"type": "string",
"enum": [
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 76e3f146f..4b6fd9178 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -991,6 +991,9 @@ OnePasswordTelemetryErrorClass = Literal["invalid_token", "rate_limited", "timeo
class AgentFunction:
+ def should_log_request_bodies(self, organization_id: str) -> bool:
+ return True
+
async def accessible_workflow_folder_ids(self, principal: RequestPrincipal | None) -> set[str] | None:
"""Return visible folder IDs for Cloud request lists; OSS keeps organization-wide visibility."""
return None
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index a030171b9..3b71aa2d8 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -17,6 +17,7 @@ from starlette.requests import ClientDisconnect
from starlette.responses import Response
from skyvern.config import settings
+from skyvern.forge import app
from skyvern.forge.log_redaction import (
REDACTED,
SENSITIVE_HEADERS,
@@ -199,6 +200,26 @@ def _identity_log_fields() -> dict[str, str | int | bool | None]:
return fields
+def _should_log_request_bodies() -> bool:
+ identity = _request_identity.get()
+ if identity is None or identity.organization_id is None:
+ return True
+ return app.AGENT_FUNCTION.should_log_request_bodies(identity.organization_id)
+
+
+def _schedule_validation_error_code(status_code: int, response_body: str) -> str | None:
+ if status_code != 400:
+ return None
+ try:
+ response = json.loads(response_body)
+ except json.JSONDecodeError:
+ return None
+ detail = response.get("detail") if isinstance(response, dict) else None
+ if isinstance(detail, str) and detail.startswith("Missing schedule parameters for workflow "):
+ return "missing_schedule_parameters"
+ return None
+
+
def integration_platform_from_user_agent(user_agent: str | None) -> str | None:
if not isinstance(user_agent, str) or not user_agent.strip():
return None
@@ -331,6 +352,7 @@ def _log_unhandled_request(
"""Emit the raw-request row after the server error handler selects a response."""
exc = sys.exc_info()[1]
try:
+ body_fields = {"body": body} if _should_log_request_bodies() else {}
# No traceback: the server error handler already logs it, and with one this row can pass the
# container log driver's 16 KiB line limit and be split into fragments that lose every field.
LOG.error(
@@ -339,9 +361,9 @@ def _log_unhandled_request(
path=path,
status_code=status_code,
client_ip=client_ip,
- body=body,
headers=headers,
duration_seconds=time.monotonic() - start_time,
+ **body_fields,
**(exception_log_fields(exc) if exc is not None else {}),
**_identity_log_fields(),
)
@@ -371,18 +393,26 @@ def _log_request(
log_method = LOG.info
try:
+ body_fields = (
+ {
+ "body": body,
+ "response_body": response_body,
+ # backwards-compat: keep error_body for existing Datadog queries
+ "error_body": response_body if status_code >= 400 else None,
+ }
+ if _should_log_request_bodies()
+ else {}
+ )
log_method(
"api.raw_request",
method=method,
path=path,
status_code=status_code,
client_ip=client_ip,
- body=body,
headers=headers,
- response_body=response_body,
- # backwards-compat: keep error_body for existing Datadog queries
- error_body=response_body if status_code >= 400 else None,
duration_seconds=time.monotonic() - start_time,
+ error_code=_schedule_validation_error_code(status_code, response_body),
+ **body_fields,
**_identity_log_fields(),
)
except Exception:
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index 680116cce..b142fa356 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -36,6 +36,7 @@ from sqlalchemy import (
update,
)
from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.engine import RowMapping
from sqlalchemy.exc import IntegrityError, SQLAlchemyError, StatementError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.compiler import compiles
@@ -452,6 +453,58 @@ def _final_webhook_claim_is_free(stale_before: datetime) -> ColumnElement[bool]:
class WorkflowRunsRepository(BaseRepository):
"""Database operations for workflow runs."""
+ @db_operation("list_workflow_run_activity_for_export", log_errors=False)
+ async def list_for_activity_export(
+ self,
+ *,
+ organization_id: str,
+ since: datetime,
+ until: datetime,
+ before_created_at: datetime | None,
+ before_workflow_run_id: str | None,
+ limit: int,
+ ) -> list[RowMapping]:
+ filters = [
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.created_at >= to_naive_utc(since),
+ WorkflowRunModel.created_at <= to_naive_utc(until),
+ WorkflowRunModel.parent_workflow_run_id.is_(None),
+ ]
+ before_created_at = to_naive_utc(before_created_at)
+ if before_created_at is not None and before_workflow_run_id is not None:
+ filters.append(
+ (WorkflowRunModel.created_at < before_created_at)
+ | (
+ (WorkflowRunModel.created_at == before_created_at)
+ & (WorkflowRunModel.workflow_run_id < before_workflow_run_id)
+ )
+ )
+ # Bound the index walk at the cursor instead of filtering every newer run.
+ filters.append(WorkflowRunModel.created_at <= before_created_at)
+
+ async with self.Session() as session:
+ return list(
+ (
+ await session.execute(
+ select(
+ WorkflowRunModel.workflow_run_id,
+ WorkflowRunModel.created_at,
+ WorkflowRunModel.workflow_permanent_id,
+ WorkflowRunModel.trigger_type,
+ WorkflowRunModel.created_by,
+ WorkflowRunModel.requested_by,
+ WorkflowRunModel.workflow_schedule_id,
+ WorkflowRunModel.retried_from_workflow_run_id,
+ )
+ .where(*filters)
+ .order_by(WorkflowRunModel.created_at.desc(), WorkflowRunModel.workflow_run_id.desc())
+ .limit(limit)
+ )
+ )
+ .mappings()
+ .all()
+ )
+
async def finalize_workflow_run_for_dispatch(
self,
*,
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 181a590c2..b277808c0 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -16,7 +16,10 @@ from sqlalchemy.exc import OperationalError
from starlette.requests import ClientDisconnect, Request
from starlette.types import ASGIApp, Receive, Scope, Send
-from skyvern.forge import api_app, request_logging
+from skyvern.forge import api_app
+from skyvern.forge import app as forge_app
+from skyvern.forge import request_logging
+from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.log_redaction import (
REDACTED,
SENSITIVE_FIELDS,
@@ -43,6 +46,13 @@ from skyvern.forge.sdk.core.run_submission_gate import RunSubmissionGate
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.services.org_auth_service import apply_request_org_context
+
+class _NoRequestBodiesAgentFunction(AgentFunction):
+ def should_log_request_bodies(self, organization_id: str) -> bool:
+ assert organization_id == "o_request_log"
+ return False
+
+
# ---------------------------------------------------------------------------
# _client_ip_from_headers
# ---------------------------------------------------------------------------
@@ -749,6 +759,26 @@ def _make_app(unhandled_exception_status: int = 500) -> FastAPI:
),
}
+ @app.post("/_test_request_logging_org")
+ async def create_org_task(error: bool = False) -> dict:
+ set_request_organization("o_request_log")
+ if error:
+ raise HTTPException(status_code=403, detail="response value")
+ return {"accepted": True}
+
+ @app.post("/api/v1/workflows/{workflow_id}/schedules")
+ async def create_invalid_schedule(workflow_id: str) -> JSONResponse:
+ set_request_organization("o_request_log")
+ return JSONResponse(
+ status_code=400,
+ content={"detail": f"Missing schedule parameters for workflow {workflow_id}: SYNTHETIC_MISSING_PARAMETER"},
+ )
+
+ @app.post("/_test_request_logging_org_boom")
+ async def create_org_task_boom() -> dict:
+ set_request_organization("o_request_log")
+ raise ValueError("request failed")
+
@app.post("/integration-platform")
async def integration_platform() -> dict:
identity = get_request_principal_state()
@@ -1045,6 +1075,97 @@ class TestMiddlewareLogVolume:
assert response.status_code == 500
assert log_mock.error.call_args.kwargs["organization_id"] == "o_385835488455492960"
+ @pytest.mark.parametrize("allow_bodies", [False, True])
+ @pytest.mark.parametrize("error", [False, True])
+ def test_authenticated_request_bodies_follow_agent_function_policy(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch, allow_bodies: bool, error: bool
+ ) -> None:
+ agent_function = AgentFunction() if allow_bodies else _NoRequestBodiesAgentFunction()
+ monkeypatch.setattr(forge_app, "AGENT_FUNCTION", agent_function)
+
+ response = TestClient(_make_app()).post(
+ "/_test_request_logging_org", params={"error": error}, json={"input": "request value"}
+ )
+
+ expected_status = 403 if error else 200
+ assert response.status_code == expected_status
+ logged = (log_mock.warning if error else log_mock.info).call_args.kwargs
+ assert logged["organization_id"] == "o_request_log"
+ assert {"method", "path", "status_code", "duration_seconds"} <= logged.keys()
+ assert ({"body", "response_body", "error_body"} <= logged.keys()) is allow_bodies
+ if allow_bodies:
+ assert agent_function.should_log_request_bodies("o_request_log") is True
+ assert "request value" in logged["body"]
+ if error:
+ assert logged["error_body"] == logged["response_body"]
+ else:
+ assert "accepted" in logged["response_body"]
+
+ @pytest.mark.parametrize("allow_bodies", [False, True])
+ def test_schedule_validation_error_has_safe_classification(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch, allow_bodies: bool
+ ) -> None:
+ monkeypatch.setattr(
+ forge_app,
+ "AGENT_FUNCTION",
+ AgentFunction() if allow_bodies else _NoRequestBodiesAgentFunction(),
+ )
+
+ response = TestClient(_make_app()).post(
+ "/api/v1/workflows/wpid_test/schedules",
+ json={"SYNTHETIC_REQUEST_SECRET": "SYNTHETIC_REQUEST_VALUE"},
+ )
+
+ assert response.status_code == 400
+ logged = log_mock.warning.call_args.kwargs
+ assert logged["error_code"] == "missing_schedule_parameters"
+ assert ({"body", "response_body", "error_body"} <= logged.keys()) is allow_bodies
+ if allow_bodies:
+ assert "SYNTHETIC_MISSING_PARAMETER" in logged["error_body"]
+ else:
+ assert "SYNTHETIC_MISSING_PARAMETER" not in repr(log_mock.warning.call_args)
+ assert "SYNTHETIC_REQUEST_SECRET" not in repr(log_mock.warning.call_args)
+ assert "SYNTHETIC_REQUEST_VALUE" not in repr(log_mock.warning.call_args)
+
+ @pytest.mark.parametrize(
+ ("status_code", "response_body"),
+ [
+ (400, '{"detail":"Unknown schedule parameters for workflow wpid_test: name"}'),
+ (403, '{"detail":"Missing schedule parameters for workflow wpid_test: name"}'),
+ (400, "not json"),
+ (400, "[]"),
+ ],
+ )
+ def test_schedule_validation_error_code_ignores_other_responses(self, status_code: int, response_body: str) -> None:
+ assert request_logging._schedule_validation_error_code(status_code, response_body) is None
+
+ def test_unhandled_request_body_is_omitted_when_agent_function_disallows_it(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(forge_app, "AGENT_FUNCTION", _NoRequestBodiesAgentFunction())
+
+ response = TestClient(_make_app(), raise_server_exceptions=False).post(
+ "/_test_request_logging_org_boom", json={"input": "request value"}
+ )
+
+ assert response.status_code == 500
+ logged = log_mock.error.call_args.kwargs
+ assert logged["organization_id"] == "o_request_log"
+ assert "body" not in logged
+ assert {"method", "path", "status_code", "duration_seconds"} <= logged.keys()
+
+ def test_request_without_resolved_organization_keeps_body_logging(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(forge_app, "AGENT_FUNCTION", _NoRequestBodiesAgentFunction())
+
+ response = TestClient(_make_app()).post("/tasks", json={"input": "request value"})
+
+ assert response.status_code == 200
+ logged = log_mock.info.call_args.kwargs
+ assert "organization_id" not in logged
+ assert {"body", "response_body", "error_body"} <= logged.keys()
+
def test_organization_does_not_leak_into_a_later_unauthenticated_request(
self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
) -> None: