Skip to content

Automate browser based workflows with AI

Audit credential, folder, schedule, tag and script writes, and cap how long an audit write can hold a request (#8764)

Aaron Perezd1f395f55dca
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index e3d54dacd..09f3fa98f 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -78,6 +78,7 @@ from skyvern.forge.sdk.services.request_principal import (
BearerIdentityResolution,
BearerIdentityStatus,
RequestPrincipal,
+ get_request_principal,
)
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVar
@@ -122,7 +123,7 @@ LOG = structlog.get_logger()
@dataclass(frozen=True)
class AuditEvent:
- """Safe, bounded metadata for a customer-initiated write; never include values or request bodies."""
+ """Ids and field names for a customer-initiated write; never secrets or request bodies. A tag's id is its text."""
organization_id: str
action: str
@@ -133,6 +134,21 @@ class AuditEvent:
auth_kind: str | None = None
+async def record_request_audit_event(
+ organization_id: str,
+ action: str,
+ resource_type: str,
+ resource_id: str | None,
+ *,
+ changed_fields: tuple[str, ...] = (),
+ related_resource_ids: tuple[str, ...] = (),
+) -> None:
+ await app.AGENT_FUNCTION.record_audit_event(
+ get_request_principal(),
+ AuditEvent(organization_id, action, resource_type, resource_id, changed_fields, related_resource_ids),
+ )
+
+
EMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS = 30
EMAIL_OTP_MAX_RESULTS = 5
EMAIL_OTP_SEARCH_INTERVAL_SECONDS = 30
diff --git a/skyvern/forge/sdk/db/repositories/folders.py b/skyvern/forge/sdk/db/repositories/folders.py
index c577f8a56..da30216d5 100644
--- a/skyvern/forge/sdk/db/repositories/folders.py
+++ b/skyvern/forge/sdk/db/repositories/folders.py
@@ -168,8 +168,8 @@ class FoldersRepository(BaseRepository):
folder_id: str,
organization_id: str,
delete_workflows: bool = False,
- ) -> bool:
- """Soft delete a folder. Optionally delete all workflows in the folder."""
+ ) -> list[str] | None:
+ """Soft delete a folder and return the workflows deleted with it, or None when there is no such folder."""
async with self.Session() as session:
# Check if folder exists
folder_stmt = (
@@ -180,8 +180,9 @@ class FoldersRepository(BaseRepository):
folder_result = await session.execute(folder_stmt)
folder = folder_result.scalar_one_or_none()
if not folder:
- return False
+ return None
+ workflow_permanent_ids: list[str] = []
# If delete_workflows is True, delete all workflows in the folder
if delete_workflows:
# Get workflow permanent IDs in the folder (inline logic)
@@ -243,7 +244,7 @@ class FoldersRepository(BaseRepository):
# Soft delete the folder
folder.deleted_at = datetime.now(timezone.utc)
await session.commit()
- return True
+ return workflow_permanent_ids
@db_operation("get_folder_workflow_count")
async def get_folder_workflow_count(
diff --git a/skyvern/forge/sdk/db/repositories/organizations.py b/skyvern/forge/sdk/db/repositories/organizations.py
index d96b12906..3ced13647 100644
--- a/skyvern/forge/sdk/db/repositories/organizations.py
+++ b/skyvern/forge/sdk/db/repositories/organizations.py
@@ -580,10 +580,10 @@ class OrganizationsRepository(BaseRepository):
self,
organization_id: str,
token_type: OrganizationAuthTokenType,
- ) -> None:
- """Invalidate all existing tokens of a specific type for an organization."""
+ ) -> int:
+ """Invalidate all existing tokens of a specific type for an organization; returns how many were valid."""
async with self.Session() as session:
- await session.execute(
+ result = await session.execute(
update(OrganizationAuthTokenModel)
.filter_by(organization_id=organization_id)
.filter_by(token_type=token_type)
@@ -591,6 +591,7 @@ class OrganizationsRepository(BaseRepository):
.values(valid=False)
)
await session.commit()
+ return result.rowcount
@db_operation("invalidate_org_auth_token")
async def invalidate_org_auth_token(
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 751985a4d..3ada0d15a 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -42,7 +42,7 @@ from skyvern.exceptions import (
get_user_facing_exception_message,
)
from skyvern.forge import app
-from skyvern.forge.agent_functions import AuditEvent
+from skyvern.forge.agent_functions import AuditEvent, record_request_audit_event
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.crypto import calculate_sha256
from skyvern.forge.sdk.api.llm.custom_llm_registry import (
@@ -1657,6 +1657,9 @@ async def create_folder(
title=data.title,
description=data.description,
)
+ await record_request_audit_event(
+ current_org.organization_id, "workflow_folder.create", "workflow_folder", folder_model.folder_id
+ )
workflow_count = await app.DATABASE.folders.get_folder_workflow_count(
folder_id=folder_model.folder_id,
organization_id=current_org.organization_id,
@@ -1836,6 +1839,17 @@ async def update_folder(
if not folder:
raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=f"Folder {folder_id} not found")
+ changed_fields = tuple(
+ name for name, value in (("title", data.title), ("description", data.description)) if value is not None
+ )
+ if changed_fields:
+ await record_request_audit_event(
+ current_org.organization_id,
+ "workflow_folder.update",
+ "workflow_folder",
+ folder.folder_id,
+ changed_fields=changed_fields,
+ )
workflow_count = await app.DATABASE.folders.get_folder_workflow_count(
folder_id=folder.folder_id,
organization_id=current_org.organization_id,
@@ -1873,14 +1887,22 @@ async def delete_folder(
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> dict:
analytics.capture("skyvern-oss-folder-delete")
- success = await app.DATABASE.folders.soft_delete_folder(
+ deleted_workflow_ids = await app.DATABASE.folders.soft_delete_folder(
folder_id=folder_id,
organization_id=current_org.organization_id,
delete_workflows=delete_workflows,
)
- if not success:
+ if deleted_workflow_ids is None:
raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=f"Folder {folder_id} not found")
+ await record_request_audit_event(
+ current_org.organization_id,
+ "workflow_folder.delete",
+ "workflow_folder",
+ folder_id,
+ changed_fields=("delete_workflows",) if delete_workflows else (),
+ related_resource_ids=tuple(deleted_workflow_ids),
+ )
return {"status": "deleted", "folder_id": folder_id, "workflows_deleted": delete_workflows}
@@ -1920,6 +1942,14 @@ async def update_workflow_folder(
status_code=http_status.HTTP_404_NOT_FOUND, detail=f"Workflow {workflow_permanent_id} not found"
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "workflow.update",
+ "workflow",
+ workflow.workflow_permanent_id,
+ changed_fields=("folder_id",),
+ related_resource_ids=(workflow.folder_id,) if workflow.folder_id else (),
+ )
return workflow
except ValueError as e:
raise HTTPException(status_code=http_status.HTTP_400_BAD_REQUEST, detail=str(e)) from e
@@ -1976,22 +2006,24 @@ async def _apply_tag_changes_with_retry(
label_sets: list[str] | None = None,
label_deletes: list[str] | None = None,
colors: dict[str, str] | None = None,
-) -> None:
+) -> bool:
"""Wrap ``apply_tag_changes`` with one IntegrityError retry: concurrent
- same-identity SETs race the partial UNIQUE; last-write-wins, else 409."""
+ same-identity SETs race the partial UNIQUE; last-write-wins, else 409.
+ Returns whether any tag changed."""
for attempt in range(2):
try:
- await app.DATABASE.tags.apply_tag_changes(
- workflow_permanent_id=workflow_permanent_id,
- organization_id=organization_id,
- sets=sets,
- deletes=deletes,
- context=context,
- label_sets=label_sets,
- label_deletes=label_deletes,
- colors=colors,
+ return bool(
+ await app.DATABASE.tags.apply_tag_changes(
+ workflow_permanent_id=workflow_permanent_id,
+ organization_id=organization_id,
+ sets=sets,
+ deletes=deletes,
+ context=context,
+ label_sets=label_sets,
+ label_deletes=label_deletes,
+ colors=colors,
+ )
)
- return
except IntegrityError:
if attempt == 0:
await asyncio.sleep(random.uniform(0.01, 0.05))
@@ -2000,6 +2032,7 @@ async def _apply_tag_changes_with_retry(
status_code=http_status.HTTP_409_CONFLICT,
detail="Tag write conflicted with a concurrent update; please retry",
)
+ return False
async def _apply_run_tag_changes_with_retry(
@@ -2012,22 +2045,23 @@ async def _apply_run_tag_changes_with_retry(
label_sets: list[str] | None = None,
label_deletes: list[str] | None = None,
colors: dict[str, str] | None = None,
-) -> None:
+) -> bool:
"""Wrap ``apply_run_tag_changes`` with the same concurrency behavior as
workflow tags. Org-mismatch is mapped to the route-level 404 contract."""
for attempt in range(2):
try:
- await app.DATABASE.tags.apply_run_tag_changes(
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- sets=sets,
- deletes=deletes,
- context=context,
- label_sets=label_sets,
- label_deletes=label_deletes,
- colors=colors,
+ return bool(
+ await app.DATABASE.tags.apply_run_tag_changes(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ sets=sets,
+ deletes=deletes,
+ context=context,
+ label_sets=label_sets,
+ label_deletes=label_deletes,
+ colors=colors,
+ )
)
- return
except RunTagWorkflowRunMismatch as e:
raise HTTPException(
status_code=http_status.HTTP_404_NOT_FOUND,
@@ -2041,6 +2075,7 @@ async def _apply_run_tag_changes_with_retry(
status_code=http_status.HTTP_409_CONFLICT,
detail="Tag write conflicted with a concurrent update; please retry",
)
+ return False
async def _rename_tag_value_with_retry(
@@ -2128,7 +2163,7 @@ async def apply_workflow_tags(
grouped_deletes: set[str] = {d.key for d in data.tags_to_delete if d.key is not None}
label_deletes: list[str] = [d.value for d in data.tags_to_delete if d.key is None and d.value is not None]
try:
- await _apply_tag_changes_with_retry(
+ tags_changed = await _apply_tag_changes_with_retry(
workflow_permanent_id=workflow_permanent_id,
organization_id=organization_id,
sets=grouped_sets,
@@ -2142,6 +2177,10 @@ async def apply_workflow_tags(
# Cap-breach is the only ValueError surfaced; treat as 422 (user input).
raise HTTPException(status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e)) from e
+ if tags_changed:
+ await record_request_audit_event(
+ organization_id, "workflow.update", "workflow", workflow_permanent_id, changed_fields=("tags",)
+ )
return await _build_tags_response(workflow_permanent_id, organization_id)
@@ -2178,13 +2217,17 @@ async def delete_workflow_tag(
await _assert_workflow_in_org(workflow_permanent_id, organization_id)
write_ctx = _tag_write_context_from_caller(caller)
- await _apply_tag_changes_with_retry(
+ tags_changed = await _apply_tag_changes_with_retry(
workflow_permanent_id=workflow_permanent_id,
organization_id=organization_id,
sets={},
deletes={key},
context=write_ctx,
)
+ if tags_changed:
+ await record_request_audit_event(
+ organization_id, "workflow.update", "workflow", workflow_permanent_id, changed_fields=("tags",)
+ )
return await _build_tags_response(workflow_permanent_id, organization_id)
@@ -2321,7 +2364,7 @@ async def apply_run_tags(
grouped_deletes: set[str] = {d.key for d in data.tags_to_delete if d.key is not None}
label_deletes: list[str] = [d.value for d in data.tags_to_delete if d.key is None and d.value is not None]
try:
- await _apply_run_tag_changes_with_retry(
+ tags_changed = await _apply_run_tag_changes_with_retry(
workflow_run_id=workflow_run_id,
organization_id=organization_id,
sets=grouped_sets,
@@ -2334,6 +2377,10 @@ async def apply_run_tags(
except ValueError as e:
raise HTTPException(status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e)) from e
+ if tags_changed:
+ await record_request_audit_event(
+ organization_id, "workflow_run.update", "workflow_run", workflow_run_id, changed_fields=("tags",)
+ )
return await _build_run_tags_response(workflow_run_id, organization_id)
@@ -2367,13 +2414,17 @@ async def delete_run_tag(
_validate_path_key(key)
write_ctx = _tag_write_context_from_caller(caller)
- await _apply_run_tag_changes_with_retry(
+ tags_changed = await _apply_run_tag_changes_with_retry(
workflow_run_id=workflow_run_id,
organization_id=organization_id,
sets={},
deletes={key},
context=write_ctx,
)
+ if tags_changed:
+ await record_request_audit_event(
+ organization_id, "workflow_run.update", "workflow_run", workflow_run_id, changed_fields=("tags",)
+ )
return await _build_run_tags_response(workflow_run_id, organization_id)
@@ -2521,6 +2572,7 @@ async def update_tag_key(
)
if row is None:
raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=f"Tag key '{key}' not found")
+ await record_request_audit_event(organization_id, "tag.update", "tag", row.key, changed_fields=("description",))
# Populate the real count so PATCH and GET /tag-keys agree (the ORM row
# has no count attribute, so model_validate would default it to 0).
counts = await app.DATABASE.tags.count_active_workflows_per_key(organization_id=organization_id)
@@ -2559,6 +2611,7 @@ async def delete_tag_key(
)
if delete_result is None:
raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=f"Tag key '{key}' not found")
+ await record_request_audit_event(organization_id, "tag.delete", "tag", key)
return TagKeyDeleteResponse(
key=key,
removed_from_workflow_count=delete_result.removed_from_workflow_count,
@@ -2632,6 +2685,7 @@ async def create_tag_value(
)
except TagValueAlreadyExists as e:
raise HTTPException(status_code=http_status.HTTP_409_CONFLICT, detail=str(e)) from e
+ await record_request_audit_event(current_org.organization_id, "tag.create", "tag", f"{row.key}:{row.value}")
return TagValue(key=row.key, value=row.value, color=row.color, workflow_count=0)
@@ -2671,6 +2725,9 @@ async def update_tag_value(
status_code=http_status.HTTP_404_NOT_FOUND,
detail=f"Tag value '{key}:{data.value}' not found",
)
+ await record_request_audit_event(
+ organization_id, "tag.update", "tag", f"{row.key}:{row.value}", changed_fields=("color",)
+ )
count = await app.DATABASE.tags.count_active_workflows_for_value(
organization_id=organization_id, key=row.key, value=row.value
)
@@ -2720,6 +2777,14 @@ async def rename_tag_value(
status_code=http_status.HTTP_404_NOT_FOUND,
detail=f"Tag value '{key}:{data.value}' not found",
)
+ await record_request_audit_event(
+ caller.organization.organization_id,
+ "tag.update",
+ "tag",
+ f"{result.key}:{result.value}",
+ changed_fields=("value",),
+ related_resource_ids=(f"{key}:{data.value}",),
+ )
return TagValueRenameResponse(
key=result.key,
value=result.value,
@@ -2766,6 +2831,7 @@ async def delete_tag_value(
status_code=http_status.HTTP_404_NOT_FOUND,
detail=f"Tag value '{key}:{data.value}' not found",
)
+ await record_request_audit_event(organization_id, "tag.delete", "tag", f"{key}:{data.value}")
return TagValueDeleteResponse(
key=key,
value=data.value,
@@ -5461,11 +5527,19 @@ async def set_workflow_template_status(
Template status is stored at the workflow_permanent_id level (not per-version),
meaning all versions of a workflow share the same template status.
"""
- return await app.WORKFLOW_SERVICE.set_template_status(
+ result = await app.WORKFLOW_SERVICE.set_template_status(
organization_id=current_org.organization_id,
workflow_permanent_id=workflow_permanent_id,
is_template=is_template,
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "workflow.update",
+ "workflow",
+ workflow_permanent_id,
+ changed_fields=("is_template",),
+ )
+ return result
@legacy_base_router.get(
diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.py
index 10bca62c2..f973b84cf 100644
--- a/skyvern/forge/sdk/routes/credentials.py
+++ b/skyvern/forge/sdk/routes/credentials.py
@@ -49,6 +49,7 @@ from skyvern.exceptions import BrowserProfileNotFound
from skyvern.exceptions import HttpException as SkyvernHttpException
from skyvern.exceptions import SkyvernHTTPException
from skyvern.forge import app
+from skyvern.forge.agent_functions import record_request_audit_event
from skyvern.forge.sdk.api.files import discard_temp_working_dir
from skyvern.forge.sdk.core.aiohttp_helper import aiohttp_request
from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
@@ -740,6 +741,9 @@ async def create_credential(
)
raise HTTPException(status_code=502, detail=detail)
+ await record_request_audit_event(
+ current_org.organization_id, "credential.create", "credential", credential.credential_id
+ )
if credential.vault_type == CredentialVaultType.BITWARDEN:
# Early resyncing the Bitwarden vault
background_tasks.add_task(fetch_credential_item_background, credential.item_id)
@@ -947,6 +951,15 @@ async def rename_credential(
if not updated:
raise HTTPException(status_code=500, detail="Failed to update credential")
+ changed_fields = tuple(sorted(update_kwargs.keys() - {"credential_id", "organization_id"}))
+ if changed_fields:
+ await record_request_audit_event(
+ current_org.organization_id,
+ "credential.update",
+ "credential",
+ updated.credential_id,
+ changed_fields=changed_fields,
+ )
return _convert_to_response(updated)
@@ -2047,16 +2060,30 @@ async def update_credential(
pin_provided = "pin_saved_session_ip" in data.model_fields_set
bpid_provided = "browser_profile_id" in data.model_fields_set
auto_profile_disabled_provided = "auto_profile_disabled" in data.model_fields_set
- if bpid_provided or pin_provided or auto_profile_disabled_provided:
- # Only pass browser_profile_id when the caller sent it — a pin-only update must not pass the
- # field's omitted default (None) and unlink the profile via the repo's unlink sentinel.
- profile_update: dict[str, Any] = {"browser_profile_id": data.browser_profile_id} if bpid_provided else {}
- updated_credential = await _update_credential_or_profile_conflict(
- credential_id=credential_id,
- organization_id=current_org.organization_id,
- **profile_update,
- pin_saved_session_ip=data.pin_saved_session_ip if pin_provided else None,
- auto_profile_disabled=data.auto_profile_disabled if auto_profile_disabled_provided else None,
+ changed_fields = ["credential"]
+ # The secret is already overwritten, so the audit row is written even when the profile update is refused.
+ try:
+ if bpid_provided or pin_provided or auto_profile_disabled_provided:
+ # Only pass browser_profile_id when the caller sent it — a pin-only update must not pass the
+ # field's omitted default (None) and unlink the profile via the repo's unlink sentinel.
+ profile_update: dict[str, Any] = {"browser_profile_id": data.browser_profile_id} if bpid_provided else {}
+ updated_credential = await _update_credential_or_profile_conflict(
+ credential_id=credential_id,
+ organization_id=current_org.organization_id,
+ **profile_update,
+ pin_saved_session_ip=data.pin_saved_session_ip if pin_provided else None,
+ auto_profile_disabled=data.auto_profile_disabled if auto_profile_disabled_provided else None,
+ )
+ changed_fields += sorted(
+ data.model_fields_set & {"auto_profile_disabled", "browser_profile_id", "pin_saved_session_ip"}
+ )
+ finally:
+ await record_request_audit_event(
+ current_org.organization_id,
+ "credential.update",
+ "credential",
+ credential_id,
+ changed_fields=tuple(changed_fields),
)
return _convert_to_response(updated_credential)
@@ -2219,6 +2246,7 @@ async def delete_credential(
)
_clear_cached_totp_code_preview(organization_id=current_org.organization_id, credential_id=credential_id)
+ await record_request_audit_event(current_org.organization_id, "credential.delete", "credential", credential_id)
return None
@@ -2485,6 +2513,9 @@ async def create_credential_folder(
title=data.title,
description=data.description,
)
+ await record_request_audit_event(
+ current_org.organization_id, "credential_folder.create", "credential_folder", folder.folder_id
+ )
return _to_credential_folder_response(folder, 0)
@@ -2586,6 +2617,15 @@ async def update_credential_folder(
if not folder:
raise HTTPException(status_code=404, detail=f"Credential folder {folder_id} not found")
+ await record_request_audit_event(
+ current_org.organization_id,
+ "credential_folder.update",
+ "credential_folder",
+ folder.folder_id,
+ changed_fields=tuple(
+ name for name, value in (("title", data.title), ("description", data.description)) if value is not None
+ ),
+ )
credential_count = await app.DATABASE.credential_folders.get_credential_folder_credential_count(
folder_id=folder.folder_id,
organization_id=current_org.organization_id,
@@ -2617,6 +2657,9 @@ async def delete_credential_folder(
if not success:
raise HTTPException(status_code=404, detail=f"Credential folder {folder_id} not found")
+ await record_request_audit_event(
+ current_org.organization_id, "credential_folder.delete", "credential_folder", folder_id
+ )
return {"status": "deleted", "folder_id": folder_id}
@@ -2652,6 +2695,14 @@ async def update_credential_folder_assignment(
if not credential:
raise HTTPException(status_code=404, detail=f"Credential {credential_id} not found")
+ await record_request_audit_event(
+ current_org.organization_id,
+ "credential.update",
+ "credential",
+ credential.credential_id,
+ changed_fields=("folder_id",),
+ related_resource_ids=(credential.folder_id,) if credential.folder_id else (),
+ )
return _convert_to_response(credential)
@@ -2945,6 +2996,12 @@ async def update_onepassword_token(
organization_id=current_org.organization_id,
token_id=auth_token.id,
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "vault_provider.update",
+ "vault_provider",
+ OrganizationAuthTokenType.onepassword_service_account.value,
+ )
return CreateOnePasswordTokenResponse(token=OrganizationAuthTokenMetadata.from_token(auth_token))
@@ -2985,10 +3042,14 @@ async def clear_org_auth_credential(
if not token_type:
raise HTTPException(status_code=404, detail="Unsupported organization auth credential provider")
try:
- await app.DATABASE.organizations.invalidate_org_auth_tokens(
+ invalidated_count = await app.DATABASE.organizations.invalidate_org_auth_tokens(
organization_id=current_org.organization_id,
token_type=token_type,
)
+ if invalidated_count:
+ await record_request_audit_event(
+ current_org.organization_id, "vault_provider.delete", "vault_provider", token_type.value
+ )
return ClearOrganizationAuthTokenResponse(success=True)
except Exception as e:
LOG.error(
@@ -3096,6 +3157,12 @@ async def update_bitwarden_credential(
organization_id=current_org.organization_id,
token_id=auth_token.id,
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "vault_provider.update",
+ "vault_provider",
+ OrganizationAuthTokenType.bitwarden_credential.value,
+ )
return _to_safe_bitwarden_response(auth_token)
@@ -3201,6 +3268,12 @@ async def update_azure_client_secret_credential(
organization_id=current_org.organization_id,
token_id=auth_token.id,
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "vault_provider.update",
+ "vault_provider",
+ OrganizationAuthTokenType.azure_client_secret_credential.value,
+ )
return AzureClientSecretCredentialResponse(token=auth_token)
@@ -3307,6 +3380,12 @@ async def update_custom_credential_service_config(
organization_id=current_org.organization_id,
token_id=auth_token.id,
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "vault_provider.update",
+ "vault_provider",
+ OrganizationAuthTokenType.custom_credential_service.value,
+ )
return CustomCredentialServiceConfigResponse(token=auth_token)
diff --git a/skyvern/forge/sdk/routes/scripts.py b/skyvern/forge/sdk/routes/scripts.py
index 92e9d9489..f26860969 100644
--- a/skyvern/forge/sdk/routes/scripts.py
+++ b/skyvern/forge/sdk/routes/scripts.py
@@ -9,6 +9,7 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.db.models import WorkflowScriptModel
from skyvern.forge import app
+from skyvern.forge.agent_functions import record_request_audit_event
from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
from skyvern.forge.sdk.routes.routers import base_router
from skyvern.forge.sdk.schemas.organizations import Organization
@@ -242,12 +243,20 @@ async def create_script(
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> CreateScriptResponse:
"""Create a new script with optional files and metadata."""
- return await script_service.create_script(
+ result = await script_service.create_script(
organization_id=current_org.organization_id,
workflow_id=data.workflow_id,
run_id=data.run_id,
files=data.files,
)
+ await record_request_audit_event(
+ current_org.organization_id,
+ "script.create",
+ "script",
+ result.script_id,
+ related_resource_ids=(data.workflow_id,) if data.workflow_id else (),
+ )
+ return result
@base_router.post(
@@ -261,11 +270,21 @@ async def deploy_cached_script(
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> DeployCachedScriptResponse:
"""Validate or commit a cached script deployment."""
- return await cached_script_deploy_service.deploy_cached_script(
+ result = await cached_script_deploy_service.deploy_cached_script(
organization_id=current_org.organization_id,
workflow_permanent_id=workflow_permanent_id,
request=data,
)
+ if result.script_was_created:
+ await record_request_audit_event(
+ current_org.organization_id,
+ "script.update",
+ "script",
+ result.script_id,
+ changed_fields=("version",),
+ related_resource_ids=(workflow_permanent_id,),
+ )
+ return result
@base_router.get(
@@ -677,6 +696,9 @@ async def deploy_script(
requires_agent=sb.requires_agent,
)
+ await record_request_audit_event(
+ current_org.organization_id, "script.update", "script", new_script.script_id, changed_fields=("version",)
+ )
return CreateScriptResponse(
script_id=new_script.script_id,
version=new_script.version,
@@ -1120,6 +1142,7 @@ async def delete_workflow_cache_key_value(
workflow_permanent_id=workflow_permanent_id,
)
+ await record_request_audit_event(current_org.organization_id, "script.delete", "workflow", workflow_permanent_id)
LOG.info(
"Deleted workflow cache key value",
organization_id=current_org.organization_id,
@@ -1183,6 +1206,10 @@ async def clear_workflow_cache(
workflow_permanent_id=workflow_permanent_id,
)
+ if deleted_count:
+ await record_request_audit_event(
+ current_org.organization_id, "script.delete", "workflow", workflow_permanent_id
+ )
LOG.info(
"Cleared workflow cache",
organization_id=current_org.organization_id,
@@ -1237,6 +1264,14 @@ async def pin_workflow_script(
if not result:
raise HTTPException(status_code=404, detail="No script found for the given cache key value")
+ await record_request_audit_event(
+ current_org.organization_id,
+ "script.update",
+ "script",
+ result.script_id,
+ changed_fields=("is_pinned",),
+ related_resource_ids=(workflow_permanent_id,),
+ )
return PinScriptResponse(
workflow_permanent_id=workflow_permanent_id,
cache_key_value=data.cache_key_value,
@@ -1284,6 +1319,14 @@ async def unpin_workflow_script(
if not result:
raise HTTPException(status_code=404, detail="No script found for the given cache key value")
+ await record_request_audit_event(
+ current_org.organization_id,
+ "script.update",
+ "script",
+ result.script_id,
+ changed_fields=("is_pinned",),
+ related_resource_ids=(workflow_permanent_id,),
+ )
return PinScriptResponse(
workflow_permanent_id=workflow_permanent_id,
cache_key_value=data.cache_key_value,
@@ -1413,6 +1456,14 @@ async def review_script_with_instructions(
review_results=review_results,
)
+ await record_request_audit_event(
+ organization_id,
+ "script.update",
+ "script",
+ new_script.script_id,
+ changed_fields=("version",),
+ related_resource_ids=(workflow_permanent_id,),
+ )
LOG.info(
"Script reviewed with user instructions",
organization_id=organization_id,
diff --git a/skyvern/forge/sdk/routes/workflow_schedules.py b/skyvern/forge/sdk/routes/workflow_schedules.py
index 0df9e4120..c00954221 100644
--- a/skyvern/forge/sdk/routes/workflow_schedules.py
+++ b/skyvern/forge/sdk/routes/workflow_schedules.py
@@ -8,6 +8,7 @@ from fastapi import Depends, HTTPException, Query, status
from fastapi.exceptions import RequestValidationError
from skyvern.forge import app
+from skyvern.forge.agent_functions import record_request_audit_event
from skyvern.forge.sdk.core.permissions.schedule_limit_checker import ScheduleLimitCheckerFactory
from skyvern.forge.sdk.db._sentinels import _UNSET
from skyvern.forge.sdk.db.agent_db import ScheduleLimitExceededError
@@ -36,6 +37,17 @@ LOG = structlog.get_logger()
SCHEDULE_SYNC_ERROR_DETAIL = "Failed to sync schedule with scheduling service"
# Leaves time for the row write and the scheduler create to land before the requested first tick.
MIN_FIRST_FIRE_LEAD = timedelta(seconds=60)
+_AUDITED_SCHEDULE_FIELDS = {
+ "cron_expression",
+ "description",
+ "enabled",
+ "first_fire_at",
+ "interval_seconds",
+ "name",
+ "parameters",
+ "run_at",
+ "timezone",
+}
def _require_schedules_enabled() -> None:
@@ -233,6 +245,15 @@ async def _set_schedule_enabled(
)
raise _schedule_sync_error() from e
+ if previous_enabled != enabled:
+ await record_request_audit_event(
+ organization.organization_id,
+ "workflow_schedule.update",
+ "workflow_schedule",
+ workflow_schedule_id,
+ changed_fields=("enabled",),
+ related_resource_ids=(workflow_permanent_id,),
+ )
LOG.info(
"Workflow schedule enabled state updated",
organization_id=organization.organization_id,
@@ -433,6 +454,13 @@ async def create_workflow_schedule(
)
raise _schedule_sync_error() from e
+ await record_request_audit_event(
+ organization.organization_id,
+ "workflow_schedule.create",
+ "workflow_schedule",
+ schedule.workflow_schedule_id,
+ related_resource_ids=(workflow.workflow_permanent_id,),
+ )
LOG.info(
"Workflow schedule created",
organization_id=organization.organization_id,
@@ -658,6 +686,18 @@ async def update_workflow_schedule(
)
raise _schedule_sync_error() from e
+ before = existing.model_dump(include=_AUDITED_SCHEDULE_FIELDS)
+ after = schedule.model_dump(include=_AUDITED_SCHEDULE_FIELDS)
+ changed_fields = tuple(sorted(name for name in after if before[name] != after[name]))
+ if changed_fields:
+ await record_request_audit_event(
+ organization.organization_id,
+ "workflow_schedule.update",
+ "workflow_schedule",
+ workflow_schedule_id,
+ changed_fields=changed_fields,
+ related_resource_ids=(workflow_permanent_id,),
+ )
LOG.info(
"Workflow schedule updated",
organization_id=organization.organization_id,
@@ -720,6 +760,13 @@ async def cancel_workflow_schedule(
backend_schedule_id=existing.backend_schedule_id,
)
+ await record_request_audit_event(
+ organization.organization_id,
+ "workflow_schedule.cancel",
+ "workflow_schedule",
+ workflow_schedule_id,
+ related_resource_ids=(workflow_permanent_id,),
+ )
LOG.info(
"One-time workflow schedule canceled",
organization_id=organization.organization_id,
@@ -844,6 +891,13 @@ async def delete_workflow_schedule_route(
)
raise _schedule_sync_error() from e
+ await record_request_audit_event(
+ organization.organization_id,
+ "workflow_schedule.delete",
+ "workflow_schedule",
+ workflow_schedule_id,
+ related_resource_ids=(workflow_permanent_id,),
+ )
LOG.info(
"Workflow schedule deleted",
organization_id=organization.organization_id,
diff --git a/tests/unit/test_credential_update_params.py b/tests/unit/test_credential_update_params.py
index 8ad5eac1d..bf51cf798 100644
--- a/tests/unit/test_credential_update_params.py
+++ b/tests/unit/test_credential_update_params.py
@@ -1636,6 +1636,7 @@ async def test_oss_route_allows_disabling_sequential_credential(monkeypatch: pyt
SimpleNamespace(
supports_sequential_credentials=lambda: False,
should_lock_credential_write=AsyncMock(return_value=False),
+ record_audit_event=AsyncMock(),
),
)