mirror of
https://github.com/simstudioai/sim.git
synced 2026-09-24 15:45:35 +08:00
fix(integrations): close regressions found in the final validation sweep (#6764)
* fix(integrations): close regressions found in the final validation sweep
An independent read-only audit of the eight integrations merged to staging
today found defects in every one, most of them side effects of the surgery
those PRs performed on already-shipped code.
Data loss and destructive paths:
- cloudflare: restore the shipped subBlock ids on read filters so existing
workflows keep their DNS/zone/purge filters. Losing them made
list_dns_records return the entire zone with success: true, which a
downstream delete fan-out would then target. The colliding write controls
are renamed instead, chosen by blast radius.
- cloudflare: refuse an update_ruleset_rule that would tear down the rule it
edits. PATCH is a replace, so an omitted action_parameters unbound the WAF
managed ruleset and every override under it.
- cloudflare: split the hidden `enabled` control so a value set while drafting
can no longer disable a live WAF or rate-limiting rule.
- cloudflare: stop `name` leaking into update_dns_record and renaming a live record.
- okta: stop a blank name overwriting a stored group name via the LLM path.
The block guard covered only the UI.
Broken on the default path:
- microsoft_ad: update_user sent accountEnabled: "" on its own default, so
every call left at "No Change" failed. Same tri-state defect already fixed
for forceChangePasswordNextSignInWithMfa; `visibility` fixed alongside it.
- cloudflare: `domain` is required for self_hosted (the default app type),
ssh, vnc and rdp; add saas_app/target_criteria and drop dash_sso, which has
no request variant.
Silent wrong results:
- datadog: list_monitors inherited Create Monitor's tag filter and returned a
filtered list as if complete.
- servicenow: `fields` carried both a JSON body and a projection on the three
legacy generic operations. The regression test for this fed already-JSON and
could not fail; it now feeds a real projection.
- splunk: cancel_search_job reported failure on success by parsing an XML body
as JSON; readSplunkJson now tolerates it.
- okta: sendEmail === true dropped a string 'true', silently skipping the
deactivation email.
Security:
- mssql: add writetext/updatetext/readtext to the statement screen. \bupdate\b
cannot match UPDATETEXT, so both were reachable through the read-only path.
- crowdstrike: chunk repeated-query ids. At the published caps a single request
built a ~68 KB query string, past typical proxy limits.
Also: splunk count=0 unbounded read, splunk pagination totals, the `nobody`
placeholder that reintroduced the namespace bug by copy-paste, okta cursor and
activate controls split per operation, servicenow sysparm_having syntax and two
required controls no longer pre-seeded with consequential values, datadog block
outputs reconciled with tool outputs, and 16 escaped apostrophes that corrupted
the published Entra docs.
One scope removed from microsoft_ad (User.Read.All). Directory.Read.All and
GroupMember.ReadWrite.All were proposed for removal and verified still required;
a test now asserts they stay.
* fix(integrations): surface corrupt Splunk bodies and partial CrowdStrike deletes
Narrows readSplunkJson's non-JSON tolerance to XML. The dispatching and
job-control endpoints answer in XML, but a body that is neither empty nor XML
was meant to be JSON, so swallowing its parse failure handed get_search_results
an empty envelope and reported a lost result set as a search with zero events.
Annotates a batched CrowdStrike delete that fails partway with the IDs its
earlier batches already removed. Falcon cannot roll those back, so a bare
failure left the caller unable to tell what was gone and a blind retry
re-targeted IDs that no longer existed.
Registers the Cloudflare subblock-ID migration the registry-stability check
requires. The suffixed read-filter IDs never shipped in a release and every
block already materializes the restored IDs, so they are dropped rather than
renamed onto values the collision guard would discard anyway.
* fix(integrations): close the three defects Bugbot found in the sweep
An execute rule sent an explicit empty action_parameters object past the new
guard, because presence was checked rather than emptiness. `{}` is the same
payload Cloudflare's schema default produces, so it unbound the managed ruleset
the guard exists to protect.
Datadog's new List Monitors pagination used a bare `Number()`, so a typo or an
unresolved reference in either advanced field reached Datadog as a literal NaN
— the pattern this same sweep fixed for Entra `top` and the Splunk numerics.
Okta's block still marked the group name required on update, blocking a
description-only update that the tool, its merge helper, and the API all accept.
* fix(integrations): confine the Splunk XML tolerance and the CrowdStrike commit list
Splitting the XML tolerance out of readSplunkJson into readSplunkDispatchJson
puts it only on the three dispatching and job-control tools that need it. The
results path can no longer read any non-JSON body as an empty envelope, so a 2xx
HTML interstitial surfaces instead of reporting a search that matched nothing.
The dispatch reader anchors on the one documented `<response>` root, so an
interstitial fails there too.
A batched delete now records the IDs Falcon echoed in `resources` rather than
the IDs that were requested. A batch can answer 200 while reporting per-ID
failures, and naming those as deleted told the caller to drop still-live
indicators from the retry.
* test(crowdstrike): pin batched partial-delete parity with an unbatched request
A 2xx envelope carrying per-ID errors is a partial success, not a failure —
failedWithoutResources fails the operation only when nothing came back at all.
The batched path already reports it exactly as a single request does, with
deletedIds naming what Falcon confirmed and errors naming what it refused. Pin
that so the contract is not mistaken for a swallowed failure.
* fix(splunk): read the dispatch XML envelope instead of discarding it
A dispatch answering in the documented XML form was replaced with an empty
object, so create_search_job and dispatch_saved_search threw a missing-sid error
after the remote job had already been created — stranding a job the caller could
no longer poll or cancel. The envelope is now projected onto the same `{ sid }`
shape output_mode=json produces, so the search ID survives.
Matching only the opening tag also accepted a body cut off mid-transfer, which
on a cancellation reported a truncated response as a successful cancel. The
pattern now spans the closing tag, so a truncated envelope falls through to
JSON.parse and throws.
This commit is contained in:
@@ -494,7 +494,7 @@ Gets DNS analytics report for a zone including query counts and trends.
|
||||
| `zoneId` | string | Yes | The zone ID to get DNS analytics for |
|
||||
| `since` | string | No | Start date for analytics \(ISO 8601, e.g., "2024-01-01T00:00:00Z"\) or relative \(e.g., "-6h"\) |
|
||||
| `until` | string | No | End date for analytics \(ISO 8601, e.g., "2024-01-31T23:59:59Z"\) or relative \(e.g., "now"\) |
|
||||
| `metrics` | string | Yes | Comma-separated metrics to retrieve \(e.g., "queryCount,uncachedCount,staleCount,responseTimeAvg,responseTimeMedian,responseTime90th,responseTime99th"\) |
|
||||
| `metrics` | string | No | Comma-separated metrics to retrieve \(e.g., "queryCount,uncachedCount,staleCount,responseTimeAvg,responseTimeMedian,responseTime90th,responseTime99th"\). Optional — Cloudflare returns its default metric set when it is omitted |
|
||||
| `dimensions` | string | No | Comma-separated dimensions to group by \(e.g., "queryName,queryType,responseCode,responseCached,coloName,origin,dayOfWeek,tcp,ipVersion,querySizeBucket,responseSizeBucket"\) |
|
||||
| `filters` | string | No | Filters to apply to the data \(e.g., "queryType==A"\) |
|
||||
| `sort` | string | No | Sort order for the result set. Fields must be included in metrics or dimensions \(e.g., "+queryCount" or "-responseTimeAvg"\) |
|
||||
@@ -678,7 +678,7 @@ Creates a zone ruleset for a phase, optionally seeded with its first rules. Use
|
||||
| `zoneId` | string | Yes | The zone ID to create the ruleset in |
|
||||
| `name` | string | Yes | Human-readable name for the ruleset |
|
||||
| `phase` | string | Yes | The ruleset phase, e.g. http_ratelimit, http_request_firewall_custom, http_request_firewall_managed, http_request_transform, http_request_dynamic_redirect |
|
||||
| `kind` | string | No | Ruleset kind: zone, custom, managed, or root. Use zone to create a phase entry point ruleset. Defaults to zone |
|
||||
| `kind` | string | No | Ruleset kind: zone or custom. Use zone to create a phase entry point ruleset and custom for a ruleset an execute rule deploys. Defaults to zone. "root" is the account-level phase entry point and "managed" is Cloudflare-owned, so neither can be created on this zone-scoped endpoint |
|
||||
| `description` | string | No | Description of the ruleset |
|
||||
| `rules` | json | No | JSON array of rules to seed the ruleset with, in evaluation order. Each rule takes action, expression, and optionally description, enabled, action_parameters, and ratelimit |
|
||||
| `apiKey` | string | Yes | Cloudflare API Token |
|
||||
@@ -767,8 +767,8 @@ Updates a rule in a zone ruleset. Cloudflare replaces the rule definition rather
|
||||
| `expression` | string | Yes | Cloudflare filter expression selecting matching requests. Required because this endpoint replaces the rule definition — omitting it resets the stored expression |
|
||||
| `description` | string | No | Human-readable description of the rule |
|
||||
| `enabled` | boolean | No | Whether the rule is enabled |
|
||||
| `ref` | string | No | Reference tag that stays stable across rule updates |
|
||||
| `actionParameters` | string | No | JSON object of action-specific parameters, e.g. \{"id":"<MANAGED_RULESET_ID>","overrides":\{"rules":\[\{"id":"<RULE_ID>","action":"log","enabled":true,"score_threshold":40\}\]\}\} |
|
||||
| `ref` | string | No | Reference tag that stays stable across rule updates. Because the update replaces the rule, omitting it resets the tag to the rule ID and breaks anything matching on the old value |
|
||||
| `actionParameters` | string | No | JSON object of action-specific parameters, e.g. \{"id":"<MANAGED_RULESET_ID>","overrides":\{"rules":\[\{"id":"<RULE_ID>","action":"log","enabled":true,"score_threshold":40\}\]\}\}. Required on an execute rule and must be sent on every update: the endpoint replaces the rule, so omitting it resets action_parameters to \{\} — which unbinds the managed ruleset the rule deploys and every override under it |
|
||||
| `ratelimit` | string | No | JSON rate limiting configuration to preserve on a rule in the http_ratelimit phase, e.g. \{"characteristics":\["cf.colo.id","ip.src"\],"period":60,"requests_per_period":100\}. Because the update replaces the rule, omitting this on a rate limiting rule stops it rate limiting |
|
||||
| `logging` | string | No | JSON logging configuration to preserve, e.g. \{"enabled":true\}. Omitting it on a rule that had logging configured resets it to the default |
|
||||
| `apiKey` | string | Yes | Cloudflare API Token |
|
||||
@@ -1075,8 +1075,8 @@ Creates a Cloudflare Access (Zero Trust) application that puts an identity check
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `accountId` | string | Yes | The Cloudflare account ID. Access applications are account-scoped |
|
||||
| `type` | string | Yes | Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, dash_sso, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint |
|
||||
| `domain` | string | No | The primary hostname and path secured by Access, e.g. internal.example.com or example.com/admin. Required for the self_hosted, ssh, vnc, rdp, and bookmark types; the saas, app_launcher, warp, biso, dash_sso, infrastructure, mcp, mcp_portal, and proxy_endpoint types do not accept it |
|
||||
| `type` | string | Yes | Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint. dash_sso has no request variant and cannot be created through the API |
|
||||
| `domain` | string | No | The primary hostname and path secured by Access, e.g. internal.example.com or example.com/admin. Required for the self_hosted, ssh, vnc, and rdp types; optional for bookmark and mcp_portal; read-only for app_launcher, warp, biso, and proxy_endpoint; and absent from the saas, infrastructure, and mcp variants |
|
||||
| `name` | string | No | Friendly name shown in the dashboard and App Launcher |
|
||||
| `sessionDuration` | string | No | How long an Access session stays valid, e.g. 24h or 30m |
|
||||
| `allowedIdps` | string | No | Comma-separated identity provider IDs users may authenticate with. Leave empty to allow all configured providers |
|
||||
@@ -1087,6 +1087,8 @@ Creates a Cloudflare Access (Zero Trust) application that puts an identity check
|
||||
| `logoUrl` | string | No | Logo image URL shown in the dashboard and App Launcher |
|
||||
| `tags` | string | No | Comma-separated tag names categorizing the application |
|
||||
| `policies` | string | No | JSON array of policies to attach. Entries may be reusable policy IDs or inline policy objects, e.g. \["<POLICY_ID>"\] |
|
||||
| `saasApp` | string | No | JSON SaaS configuration, required for the saas type and rejected on every other type. SAML, e.g. \{"auth_type":"saml","consumer_service_url":"https://example.com/acs","sp_entity_id":"https://example.com"\}; OIDC, e.g. \{"auth_type":"oidc","client_id":"...","redirect_uris":\["https://example.com/callback"\]\} |
|
||||
| `targetCriteria` | string | No | JSON array of infrastructure target criteria, required for the infrastructure and rdp types and rejected on every other type, e.g. \[\{"port":22,"protocol":"SSH","target_attributes":\{"hostname":\["production"\]\}\}\] |
|
||||
| `apiKey` | string | Yes | Cloudflare API Token |
|
||||
|
||||
#### Output
|
||||
@@ -1120,8 +1122,8 @@ Updates a Cloudflare Access (Zero Trust) application. This replaces the applicat
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `accountId` | string | Yes | The Cloudflare account ID. Access applications are account-scoped |
|
||||
| `appId` | string | Yes | The Access application ID to update |
|
||||
| `type` | string | Yes | Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, dash_sso, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint |
|
||||
| `domain` | string | No | The primary hostname and path secured by Access. Required for the self_hosted, ssh, vnc, rdp, and bookmark types; the saas, app_launcher, warp, biso, dash_sso, infrastructure, mcp, mcp_portal, and proxy_endpoint types do not accept it |
|
||||
| `type` | string | Yes | Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint. dash_sso has no request variant and cannot be written through the API |
|
||||
| `domain` | string | No | The primary hostname and path secured by Access. Required for the self_hosted, ssh, vnc, and rdp types; optional for bookmark and mcp_portal; read-only for app_launcher, warp, biso, and proxy_endpoint; and absent from the saas, infrastructure, and mcp variants |
|
||||
| `name` | string | No | Friendly name shown in the dashboard and App Launcher |
|
||||
| `sessionDuration` | string | No | How long an Access session stays valid, e.g. 24h or 30m |
|
||||
| `allowedIdps` | string | No | Comma-separated identity provider IDs users may authenticate with |
|
||||
@@ -1131,6 +1133,8 @@ Updates a Cloudflare Access (Zero Trust) application. This replaces the applicat
|
||||
| `customDenyUrl` | string | No | URL denied users are redirected to |
|
||||
| `logoUrl` | string | No | Logo image URL shown in the dashboard and App Launcher |
|
||||
| `tags` | string | No | Comma-separated tag names categorizing the application |
|
||||
| `saasApp` | string | No | JSON SaaS configuration, required for the saas type and rejected on every other type. SAML, e.g. \{"auth_type":"saml","consumer_service_url":"https://example.com/acs","sp_entity_id":"https://example.com"\}; OIDC, e.g. \{"auth_type":"oidc","client_id":"...","redirect_uris":\["https://example.com/callback"\]\} |
|
||||
| `targetCriteria` | string | No | JSON array of infrastructure target criteria, required for the infrastructure and rdp types and rejected on every other type, e.g. \[\{"port":22,"protocol":"SSH","target_attributes":\{"hostname":\["production"\]\}\}\] |
|
||||
| `policies` | string | No | JSON array of policies to attach. Entries may be reusable policy IDs or inline policy objects |
|
||||
| `apiKey` | string | Yes | Cloudflare API Token |
|
||||
|
||||
@@ -1224,7 +1228,7 @@ Creates a Cloudflare Access (Zero Trust) policy on an application, deciding who
|
||||
| `exclude` | string | No | JSON array of Access rules evaluated with NOT logic — matching any one rejects the request |
|
||||
| `require` | string | No | JSON array of Access rules evaluated with AND logic — all of them must match |
|
||||
| `precedence` | number | No | Evaluation order of the policy within the application |
|
||||
| `sessionDuration` | string | No | How long a session granted by this policy stays valid, e.g. 24h |
|
||||
| `sessionDuration` | string | No | How long a session granted by this policy stays valid, e.g. 24h. Leave it unset on a policy attached to an infrastructure-typed application — Cloudflare rejects those with error 12130 |
|
||||
| `approvalRequired` | boolean | No | Whether an approver must grant each access request |
|
||||
| `isolationRequired` | boolean | No | Whether the session must run in a remote isolated browser |
|
||||
| `purposeJustificationRequired` | boolean | No | Whether users must state a reason for access |
|
||||
@@ -1267,7 +1271,7 @@ Updates a Cloudflare Access (Zero Trust) policy on an application. This replaces
|
||||
| `exclude` | string | No | JSON array of Access rules evaluated with NOT logic |
|
||||
| `require` | string | No | JSON array of Access rules evaluated with AND logic |
|
||||
| `precedence` | number | No | Evaluation order of the policy within the application |
|
||||
| `sessionDuration` | string | No | How long a session granted by this policy stays valid, e.g. 24h |
|
||||
| `sessionDuration` | string | No | How long a session granted by this policy stays valid, e.g. 24h. Leave it unset on a policy attached to an infrastructure-typed application — Cloudflare rejects those with error 12130 |
|
||||
| `approvalRequired` | boolean | No | Whether an approver must grant each access request |
|
||||
| `isolationRequired` | boolean | No | Whether the session must run in a remote isolated browser |
|
||||
| `purposeJustificationRequired` | boolean | No | Whether users must state a reason for access |
|
||||
|
||||
@@ -148,7 +148,7 @@ Close an open CrowdStrike Falcon Real Time Response session (DELETE /real-time-r
|
||||
|
||||
### CrowdStrike Execute RTR Command
|
||||
|
||||
Run a read-only Real Time Response command in an open CrowdStrike Falcon session (POST /real-time-response/entities/command/v1). baseCommand names the family only (cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ipconfig, ls, mount, netstat, ps, reg); subcommands go in commandString. Host-modifying commands need the Active Responder or Admin endpoints. Requires the "Real time response: Read" API scope.
|
||||
Run a read-only Real Time Response command in an open CrowdStrike Falcon session (POST /real-time-response/entities/command/v1). baseCommand names the family only (cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ifconfig, ipconfig, ls, mount, netstat, ps, reg, users); subcommands go in commandString. Host-modifying commands need the Active Responder or Admin endpoints. Requires the "Real time response: Read" API scope.
|
||||
|
||||
#### Input
|
||||
|
||||
@@ -158,7 +158,7 @@ Run a read-only Real Time Response command in an open CrowdStrike Falcon session
|
||||
| `clientSecret` | string | Yes | CrowdStrike Falcon API client secret |
|
||||
| `cloud` | string | Yes | CrowdStrike Falcon cloud region |
|
||||
| `sessionId` | string | Yes | RTR session ID returned by Init RTR Session |
|
||||
| `baseCommand` | string | Yes | Read-only RTR base command family, one of: cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ipconfig, ls, mount, netstat, ps, reg. Subcommands belong in commandString, not here. |
|
||||
| `baseCommand` | string | Yes | Read-only RTR base command family, one of: cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ifconfig, ipconfig, ls, mount, netstat, ps, reg, users. Subcommands belong in commandString, not here — and only reg query is read-tier, since reg set and reg delete are Active Responder commands. |
|
||||
| `commandString` | string | Yes | Full command line to run, such as "ls C:\\Windows" or "reg query HKLM\\Software" |
|
||||
|
||||
#### Output
|
||||
@@ -501,6 +501,10 @@ Get CrowdStrike Identity Protection sensor details for one or more device IDs (P
|
||||
| ↳ `statusCauses` | array | Documented causes behind the current status |
|
||||
| ↳ `tiEnabled` | string | Threat intelligence enablement status |
|
||||
| `count` | number | Number of sensors returned |
|
||||
| `pagination` | json | Pagination metadata \(limit, offset, total\) |
|
||||
| ↳ `limit` | number | Page size used for the query |
|
||||
| ↳ `offset` | number | Offset returned by CrowdStrike |
|
||||
| ↳ `total` | number | Total records available |
|
||||
| `errors` | array | Errors CrowdStrike returned alongside a partially successful response |
|
||||
| ↳ `code` | number | CrowdStrike error code |
|
||||
| ↳ `id` | string | Identifier the error applies to |
|
||||
@@ -676,7 +680,7 @@ Add hosts to or remove hosts from a CrowdStrike Falcon static host group (POST /
|
||||
|
||||
### CrowdStrike Query Alerts
|
||||
|
||||
Search CrowdStrike Falcon alerts with a Falcon Query Language filter and return their composite IDs. Uses the current Alerts API (GET /alerts/queries/alerts/v2), which supersedes the deprecated Detects API. Requires the "Alerts: Read" API scope.
|
||||
Search CrowdStrike Falcon alerts with a Falcon Query Language filter and return their composite IDs. Uses the current Alerts API (GET /alerts/queries/alerts/v2), which replaced the Detects API decommissioned on September 30, 2025. Requires the "Alerts: Read" API scope.
|
||||
|
||||
#### Input
|
||||
|
||||
@@ -902,7 +906,7 @@ Update CrowdStrike Falcon alerts by composite ID: change status, assign or unass
|
||||
|
||||
### CrowdStrike Update Indicators
|
||||
|
||||
Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/entities/indicators/v1). DESTRUCTIVE: CrowdStrike blanks out any field you omit, so read each indicator with crowdstrike_get_indicator_details first and resend its full field set with your edits applied. Changing action or scope changes prevention behavior fleet-wide. type and value are immutable. Requires the "IOC Management: Write" API scope.
|
||||
Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/entities/indicators/v1). DESTRUCTIVE: omitted fields may be cleared, so read each indicator with crowdstrike_get_indicator_details first and resend its full field set with your edits applied. Changing action or scope changes prevention behavior fleet-wide. type and value are immutable. Requires the "IOC Management: Write" API scope.
|
||||
|
||||
#### Input
|
||||
|
||||
@@ -911,7 +915,7 @@ Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/ent
|
||||
| `clientId` | string | Yes | CrowdStrike Falcon API client ID |
|
||||
| `clientSecret` | string | Yes | CrowdStrike Falcon API client secret |
|
||||
| `cloud` | string | Yes | CrowdStrike Falcon cloud region |
|
||||
| `indicators` | json | Yes | JSON array of indicators to update. Each entry requires id, and must also repeat every field it wants to keep: CrowdStrike blanks out any updatable field the entry omits. Updatable fields: action, severity, description, source, tags \(array\), platforms \(array\), applied_globally \(boolean\), host_groups \(array\), expiration \(ISO 8601\), mobile_action, metadata \(\{ filename \}\). type and value cannot be changed. |
|
||||
| `indicators` | json | Yes | JSON array of indicators to update. Each entry requires id, and should also repeat every field it wants to keep: an updatable field the entry omits may be cleared. Updatable fields: action, severity, description, source, tags \(array\), platforms \(array\), applied_globally \(boolean\), host_groups \(array\), expiration \(ISO 8601\), mobile_action, metadata \(\{ filename \}\). type and value cannot be changed. |
|
||||
| `comment` | string | No | Audit comment explaining why these indicators were updated |
|
||||
| `retrodetects` | boolean | No | Whether to generate retroactive detections for the updated indicators |
|
||||
| `ignoreWarnings` | boolean | No | Whether to apply the updates even when CrowdStrike returns warnings |
|
||||
|
||||
@@ -366,7 +366,7 @@ List all scheduled downtimes in Datadog.
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `currentOnly` | boolean | No | Only return currently active downtimes |
|
||||
| `limit` | number | No | Number of downtimes to return per page \(default: 30, max: 100\) |
|
||||
| `limit` | number | No | Number of downtimes to return per page. Datadog defaults to 30 and declares no maximum; keep this at 100 or below to stay within the bound Sim recommends. |
|
||||
| `offset` | number | No | Index of the first downtime to return \(e.g., 0, 30, 60\) |
|
||||
| `apiKey` | string | Yes | Datadog API key |
|
||||
| `applicationKey` | string | Yes | Datadog Application key |
|
||||
|
||||
@@ -46,9 +46,9 @@ List users in Azure AD (Microsoft Entra ID)
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `top` | number | No | Maximum number of users to return \(default 100, max 999\) |
|
||||
| `filter` | string | No | OData filter expression \(e.g., "department eq \'Sales\'"\) |
|
||||
| `filter` | string | No | OData filter expression \(e.g., "department eq 'Sales'"\) |
|
||||
| `search` | string | No | Search string to filter users by displayName or mail |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -175,7 +175,7 @@ List groups in Azure AD (Microsoft Entra ID)
|
||||
| `top` | number | No | Maximum number of groups to return \(default 100, max 999\) |
|
||||
| `filter` | string | No | OData filter expression \(e.g., "securityEnabled eq true"\) |
|
||||
| `search` | string | No | Search string to filter groups by displayName or description |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -291,7 +291,7 @@ List members of a group in Azure AD (Microsoft Entra ID)
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `groupId` | string | No | Group ID. Not needed when Next Page is provided to fetch a later page. |
|
||||
| `top` | number | No | Maximum number of members to return \(default 100, max 999\) |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -479,7 +479,7 @@ List sign-in events from the Microsoft Entra ID sign-in logs, newest first. Requ
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `top` | number | No | Maximum number of sign-ins to return \(default and maximum page size is 1000\) |
|
||||
| `filter` | string | No | OData filter expression. Filterable fields include userPrincipalName, userId, appId, appDisplayName, ipAddress, createdDateTime, conditionalAccessStatus, riskState and status/errorCode. Example: "createdDateTime ge 2024-01-01T00:00:00Z and status/errorCode ne 0". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -499,7 +499,7 @@ List directory audit records showing who changed what in Microsoft Entra ID, suc
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `top` | number | No | Maximum number of audit records to return |
|
||||
| `filter` | string | No | OData filter expression. Filterable fields include activityDateTime, activityDisplayName, correlationId, loggedByService, initiatedBy and targetResources. Example: "activityDateTime ge 2024-01-01T00:00:00Z". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -520,7 +520,7 @@ List the application role assignments granted to a user, including assignments t
|
||||
| `userId` | string | No | User ID or user principal name. Not needed when Next Page is provided to fetch a later page. |
|
||||
| `top` | number | No | Maximum number of assignments to return |
|
||||
| `filter` | string | No | OData filter expression. Filterable fields include id, resourceId and principalDisplayName. Example: "resourceId eq 8e881353-1735-45af-af21-ee1344582a4d". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -584,9 +584,9 @@ List the enterprise applications and service principals in the tenant, including
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `top` | number | No | Maximum number of service principals to return \(default and maximum page size is 100\) |
|
||||
| `filter` | string | No | OData filter expression. Example: "servicePrincipalType eq \'Application\'" or "startsWith\(displayName, \'Salesforce\'\)". |
|
||||
| `filter` | string | No | OData filter expression. Example: "servicePrincipalType eq 'Application'" or "startsWith\(displayName, 'Salesforce'\)". |
|
||||
| `search` | string | No | Search string matched against the service principal display name |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -605,8 +605,8 @@ List every user, group, and service principal assigned to an application, by rea
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `servicePrincipalId` | string | No | Object ID of the service principal. Use List Service Principals to find it. Not needed when Next Page is provided to fetch a later page. |
|
||||
| `filter` | string | No | OData filter expression supporting eq and startswith. Example: "principalType eq \'User\'". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `filter` | string | No | OData filter expression supporting eq and startswith. Example: "principalType eq 'User'". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -696,9 +696,9 @@ List the devices registered in Microsoft Entra ID
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `top` | number | No | Maximum number of devices to return |
|
||||
| `filter` | string | No | OData filter expression. Example: "accountEnabled eq false" or "operatingSystem eq \'Windows\'". |
|
||||
| `filter` | string | No | OData filter expression. Example: "accountEnabled eq false" or "operatingSystem eq 'Windows'". |
|
||||
| `search` | string | No | Search string matched against the device display name |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -749,7 +749,7 @@ List the devices a user has registered or owns. Devices the caller cannot read a
|
||||
| `userId` | string | No | User ID or user principal name. Not needed when Next Page is provided to fetch a later page. |
|
||||
| `deviceRelationship` | string | No | Which devices to list: "registered" for devices the user registered, or "owned" for devices the user owns. Defaults to "registered". |
|
||||
| `top` | number | No | Maximum number of devices to return |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -768,8 +768,8 @@ List the conditional access policies configured in the tenant, including their s
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `top` | number | No | Maximum number of policies to return |
|
||||
| `filter` | string | No | OData filter expression. Example: "state eq \'enabled\'". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results |
|
||||
| `filter` | string | No | OData filter expression. Example: "state eq 'enabled'". |
|
||||
| `nextLink` | string | No | Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results |
|
||||
|
||||
#### Output
|
||||
|
||||
|
||||
@@ -405,7 +405,7 @@ Update a group profile in your Okta organization. Only groups of OKTA_GROUP type
|
||||
| `apiKey` | string | Yes | Okta API token for authentication |
|
||||
| `domain` | string | Yes | Okta domain \(e.g., dev-123456.okta.com\) |
|
||||
| `groupId` | string | Yes | Group ID to update |
|
||||
| `name` | string | Yes | Updated group name |
|
||||
| `name` | string | No | Updated group name. Leave blank to keep the stored name |
|
||||
| `description` | string | No | Updated group description |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -142,7 +142,7 @@ Compute aggregate statistics (count, sum, average, min, max, group by) over a Se
|
||||
| `sumFields` | string | No | Comma-separated numeric fields to sum |
|
||||
| `minFields` | string | No | Comma-separated fields to compute the minimum of |
|
||||
| `maxFields` | string | No | Comma-separated fields to compute the maximum of |
|
||||
| `having` | string | No | Filter on aggregate results \(e.g., "count>5"\) |
|
||||
| `having` | string | No | Filter on aggregate results, written as aggregate^field^operator^value and comma-separated for more than one \(e.g., "count^priority^>^3" or "count^state^=^1,avg^priority^>^3"\) |
|
||||
| `displayValue` | string | No | Return display values for grouped reference fields: "true", "false", or "all" |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -91,6 +91,8 @@ Run an SPL search synchronously and return its results in a single call (oneshot
|
||||
| `firedAlerts` | json | Triggered instances of an alert \(\[\{name, savedSearchName, alertType, severity, sid, triggerTime\}\]\) |
|
||||
| `indexes` | json | Indexes configured on the instance \(\[\{name, datatype, disabled, totalEventCount, currentDBSizeMB, maxTotalDataSizeMB, minTime, maxTime\}\]\) |
|
||||
| `apps` | json | Apps installed on the instance \(name, label, version, author, disabled\) |
|
||||
| `total` | number | Total number of entries matching a list request, from the response paging envelope. Compare with offset to decide whether another page remains. |
|
||||
| `offset` | number | Offset of the first entry in the returned page, from the paging envelope |
|
||||
|
||||
### Splunk Create Search Job
|
||||
|
||||
@@ -186,7 +188,7 @@ Fetch the transformed results of a completed Splunk search job by search ID, wit
|
||||
| `owner` | string | No | Namespace owner for /servicesNS requests \(e.g. admin, or nobody for app-shared objects\). Leave both this and the app empty to use the authenticated user context; set only one and the other becomes the - wildcard. |
|
||||
| `app` | string | No | Namespace app context for /servicesNS requests \(e.g. search\). Leave both this and the owner empty to use the authenticated user context; set only one and the other becomes the - wildcard. |
|
||||
| `sid` | string | Yes | Search ID of the job whose results to fetch \(e.g. 1457683115.100\) |
|
||||
| `count` | number | No | Maximum number of result rows to return. Defaults to 100. Page through larger result sets with offset rather than raising this — a completed job can hold millions of rows. |
|
||||
| `count` | number | No | Maximum number of result rows to return. Defaults to 100. Page through larger result sets with offset rather than raising this — a completed job can hold millions of rows. 0 is rejected here even though Splunk reads it as "every row". |
|
||||
| `offset` | number | No | First result row \(0-indexed\) from which to begin returning data |
|
||||
| `fields` | string | No | Comma-separated list of fields to return for each row \(e.g. _time,host,source\). Returns all fields when omitted. |
|
||||
| `addSummaryToMetadata` | boolean | No | Include field summary statistics in the response |
|
||||
@@ -243,6 +245,8 @@ Fetch the transformed results of a completed Splunk search job by search ID, wit
|
||||
| `firedAlerts` | json | Triggered instances of an alert \(\[\{name, savedSearchName, alertType, severity, sid, triggerTime\}\]\) |
|
||||
| `indexes` | json | Indexes configured on the instance \(\[\{name, datatype, disabled, totalEventCount, currentDBSizeMB, maxTotalDataSizeMB, minTime, maxTime\}\]\) |
|
||||
| `apps` | json | Apps installed on the instance \(name, label, version, author, disabled\) |
|
||||
| `total` | number | Total number of entries matching a list request, from the response paging envelope. Compare with offset to decide whether another page remains. |
|
||||
| `offset` | number | Offset of the first entry in the returned page, from the paging envelope |
|
||||
|
||||
### Splunk Cancel Search Job
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ const { fetchMock } = vi.hoisted(() => ({
|
||||
fetchMock: vi.fn(),
|
||||
}))
|
||||
|
||||
import { MAX_ID_URL_BYTES } from '@/app/api/tools/crowdstrike/query/operations'
|
||||
import { POST } from '@/app/api/tools/crowdstrike/query/route'
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
@@ -933,4 +934,279 @@ describe('CrowdStrike extended operations', () => {
|
||||
'detection_suppress'
|
||||
)
|
||||
})
|
||||
|
||||
describe('by-ids URL byte budget', () => {
|
||||
/** Long enough that the contract maxima would generate a URL past any proxy limit. */
|
||||
function longIds(count: number, prefix: string): string[] {
|
||||
return Array.from({ length: count }, (_, index) =>
|
||||
`${prefix}-${String(index).padStart(4, '0')}`.padEnd(64, 'x')
|
||||
)
|
||||
}
|
||||
|
||||
function idsFromUrl(rawUrl: string): string[] {
|
||||
return new URL(rawUrl).searchParams.getAll('ids')
|
||||
}
|
||||
|
||||
/** The 8 KB request line + header cap common to proxies and load balancers. */
|
||||
const PROXY_REQUEST_LINE_LIMIT = 8192
|
||||
|
||||
it('keeps the budget under the request-line limit proxies enforce', () => {
|
||||
expect(MAX_ID_URL_BYTES).toBeLessThanOrEqual(PROXY_REQUEST_LINE_LIMIT)
|
||||
})
|
||||
|
||||
it('splits an oversized indicator lookup into batches that each stay under the URL budget', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) =>
|
||||
Promise.resolve(
|
||||
jsonResponse({
|
||||
meta: { pagination: { limit: 1, offset: 0, total: 300 } },
|
||||
resources: idsFromUrl(rawUrl).map((id) => ({ id, type: 'sha256', value: id })),
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_get_indicator_details', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
const lookupUrls = fetchMock.mock.calls.slice(1).map((call) => String(call[0]))
|
||||
expect(lookupUrls.length).toBeGreaterThan(1)
|
||||
for (const url of lookupUrls) {
|
||||
expect(url.length).toBeLessThanOrEqual(MAX_ID_URL_BYTES)
|
||||
}
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.output.count).toBe(300)
|
||||
expect(data.output.indicators.map((indicator: { id: string }) => indicator.id)).toEqual(
|
||||
indicatorIds
|
||||
)
|
||||
expect(lookupUrls.flatMap(idsFromUrl)).toEqual(indicatorIds)
|
||||
})
|
||||
|
||||
it('merges the envelope errors every batch reported', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) => {
|
||||
const ids = idsFromUrl(rawUrl)
|
||||
return Promise.resolve(
|
||||
jsonResponse({
|
||||
resources: ids.slice(1).map((id) => ({ id, type: 'sha256', value: id })),
|
||||
errors: [{ code: 404, id: ids[0], message: 'Indicator not found' }],
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_get_indicator_details', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
const batchCount = fetchMock.mock.calls.length - 1
|
||||
expect(batchCount).toBeGreaterThan(1)
|
||||
expect(data.output.errors).toHaveLength(batchCount)
|
||||
})
|
||||
|
||||
it('surfaces an upstream failure raised by a later batch instead of swallowing it', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
let lookupCall = 0
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) => {
|
||||
lookupCall += 1
|
||||
if (lookupCall === 2) {
|
||||
return Promise.resolve(
|
||||
jsonResponse({ errors: [{ code: 429, message: 'Rate limit exceeded' }] }, 429)
|
||||
)
|
||||
}
|
||||
return Promise.resolve(
|
||||
jsonResponse({
|
||||
resources: idsFromUrl(rawUrl).map((id) => ({ id, type: 'sha256', value: id })),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_get_indicator_details', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(429)
|
||||
expect(data.success).toBe(false)
|
||||
expect(data.error).toBe('Rate limit exceeded')
|
||||
})
|
||||
|
||||
/**
|
||||
* A batched delete has no rollback: every batch that answered `ok` really removed
|
||||
* its indicators. Reporting only the failing batch's message would leave the
|
||||
* caller unable to tell what is already gone, and a blind retry would re-target
|
||||
* IDs that no longer exist.
|
||||
*/
|
||||
it('names the indicators earlier batches already deleted when a later batch fails', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
let deleteCall = 0
|
||||
const deletedByFirstBatch: string[] = []
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) => {
|
||||
deleteCall += 1
|
||||
if (deleteCall === 2) {
|
||||
return Promise.resolve(
|
||||
jsonResponse({ errors: [{ code: 429, message: 'Rate limit exceeded' }] }, 429)
|
||||
)
|
||||
}
|
||||
const ids = idsFromUrl(rawUrl)
|
||||
deletedByFirstBatch.push(...ids)
|
||||
return Promise.resolve(jsonResponse({ resources: ids }))
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_delete_indicators', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(429)
|
||||
expect(data.success).toBe(false)
|
||||
expect(deletedByFirstBatch.length).toBeGreaterThan(0)
|
||||
expect(data.error).toContain('Rate limit exceeded')
|
||||
expect(data.error).toContain(`${deletedByFirstBatch.length} ID(s) were already deleted`)
|
||||
expect(data.error).toContain(deletedByFirstBatch[0])
|
||||
})
|
||||
|
||||
/**
|
||||
* A batch can answer 200 while reporting per-ID failures in `errors`. Recording
|
||||
* the requested chunk would name indicators that are still live and tell the
|
||||
* caller to drop them from the retry, so only the IDs Falcon echoed in
|
||||
* `resources` count as committed.
|
||||
*/
|
||||
it('reports only the IDs Falcon confirmed, not every ID in a partly-failed batch', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
let deleteCall = 0
|
||||
let skipped = ''
|
||||
const confirmed: string[] = []
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) => {
|
||||
deleteCall += 1
|
||||
if (deleteCall === 2) {
|
||||
return Promise.resolve(
|
||||
jsonResponse({ errors: [{ code: 429, message: 'Rate limit exceeded' }] }, 429)
|
||||
)
|
||||
}
|
||||
const ids = idsFromUrl(rawUrl)
|
||||
skipped = ids[0]
|
||||
confirmed.push(...ids.slice(1))
|
||||
return Promise.resolve(
|
||||
jsonResponse({
|
||||
resources: ids.slice(1),
|
||||
errors: [{ code: 404, id: ids[0], message: 'Indicator not found' }],
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_delete_indicators', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(429)
|
||||
expect(confirmed.length).toBeGreaterThan(0)
|
||||
expect(data.error).toContain(`${confirmed.length} ID(s) were already deleted`)
|
||||
expect(data.error).not.toContain(skipped)
|
||||
})
|
||||
|
||||
/**
|
||||
* A 2xx envelope carrying per-ID errors is a partial success, not a failure —
|
||||
* `failedWithoutResources` only fails the operation when nothing came back at
|
||||
* all. The batched path must report it exactly as a single request would:
|
||||
* `deletedIds` names what Falcon confirmed and `errors` names what it refused,
|
||||
* which is stricter reconciliation than the prose message the transport-failure
|
||||
* path has to fall back on. A retry excludes `deletedIds`.
|
||||
*/
|
||||
it('reports a 2xx per-ID delete failure as partial success, matching an unbatched request', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
let deleteCall = 0
|
||||
let refused = ''
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) => {
|
||||
deleteCall += 1
|
||||
const ids = idsFromUrl(rawUrl)
|
||||
if (deleteCall === 2) {
|
||||
refused = ids[0]
|
||||
return Promise.resolve(
|
||||
jsonResponse({
|
||||
resources: ids.slice(1),
|
||||
errors: [{ code: 404, id: ids[0], message: 'Indicator not found' }],
|
||||
})
|
||||
)
|
||||
}
|
||||
return Promise.resolve(jsonResponse({ resources: ids }))
|
||||
})
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_delete_indicators', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.success).toBe(true)
|
||||
expect(refused).not.toBe('')
|
||||
expect(data.output.deletedIds).not.toContain(refused)
|
||||
expect(data.output.count).toBe(indicatorIds.length - 1)
|
||||
expect(data.output.errors).toContainEqual(expect.objectContaining({ id: refused, code: 404 }))
|
||||
})
|
||||
|
||||
it('leaves a first-batch delete failure unannotated — nothing was committed', async () => {
|
||||
const indicatorIds = longIds(300, 'ioc')
|
||||
|
||||
fetchMock.mockImplementation(() =>
|
||||
Promise.resolve(jsonResponse({ errors: [{ code: 403, message: 'Access denied' }] }, 403))
|
||||
)
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_delete_indicators', indicatorIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(data.error).toBe('Access denied')
|
||||
})
|
||||
|
||||
it('splits an oversized vulnerability lookup at the Spotlight cap', async () => {
|
||||
const vulnerabilityIds = longIds(400, 'vuln')
|
||||
|
||||
fetchMock.mockImplementation((rawUrl: string) =>
|
||||
Promise.resolve(
|
||||
jsonResponse({
|
||||
resources: idsFromUrl(rawUrl).map((id) => ({ id })),
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
const response = await POST(
|
||||
requestFor({ operation: 'crowdstrike_get_vulnerability_details', vulnerabilityIds })
|
||||
)
|
||||
const data = await response.json()
|
||||
|
||||
const lookupUrls = fetchMock.mock.calls.slice(1).map((call) => String(call[0]))
|
||||
expect(lookupUrls.length).toBeGreaterThan(1)
|
||||
for (const url of lookupUrls) {
|
||||
expect(url.length).toBeLessThanOrEqual(MAX_ID_URL_BYTES)
|
||||
}
|
||||
expect(data.output.count).toBe(400)
|
||||
})
|
||||
|
||||
it('keeps a filter-only delete on a single request', async () => {
|
||||
fetchMock.mockResolvedValueOnce(jsonResponse({ resources: ['ioc-1'] }))
|
||||
|
||||
const response = await POST(
|
||||
requestFor({
|
||||
operation: 'crowdstrike_delete_indicators',
|
||||
filter: "source:'automation'",
|
||||
comment: 'cleanup',
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { isRecordLike } from '@sim/utils/object'
|
||||
import { truncate } from '@sim/utils/string'
|
||||
import type { CrowdstrikeQueryBody } from '@/lib/api/contracts/tools/crowdstrike'
|
||||
import {
|
||||
buildUrl,
|
||||
type CrowdStrikeCallResult,
|
||||
callCrowdStrike,
|
||||
getBoolean,
|
||||
@@ -9,7 +12,9 @@ import {
|
||||
getFirstRecordResource,
|
||||
getNumber,
|
||||
getPagination,
|
||||
getRecordArray,
|
||||
getRecordResources,
|
||||
getResourcesArray,
|
||||
getSpotlightPagination,
|
||||
getString,
|
||||
getStringResources,
|
||||
@@ -83,6 +88,170 @@ export function failedWithoutResources(
|
||||
return resourceCount === 0 && getEnvelopeErrors(result.data).length > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Falcon's by-ids lookups carry every ID in the query string, so a request at the
|
||||
* contract maxima (1000 indicator IDs at ~68 bytes each) would generate a ~68 KB
|
||||
* URL. Proxies and load balancers commonly cap the request line plus headers at
|
||||
* 8 KB, so batches are sized to keep each generated URL at or under half of that,
|
||||
* leaving the rest of the budget for headers.
|
||||
*/
|
||||
export const MAX_ID_URL_BYTES = 4096
|
||||
|
||||
/**
|
||||
* Batches by cumulative encoded length rather than by a fixed count: Falcon IDs
|
||||
* range from 32-character AIDs to long composite alert IDs, so a count-based cap
|
||||
* would either waste the budget or blow past it. A single ID longer than the
|
||||
* budget still gets its own batch — truncating the list would silently drop it.
|
||||
*/
|
||||
export function chunkIdsByUrlBudget(ids: string[], budget: number): string[][] {
|
||||
const chunks: string[][] = []
|
||||
let current: string[] = []
|
||||
let used = 0
|
||||
|
||||
for (const id of ids) {
|
||||
const cost = `&ids=${encodeURIComponent(id)}`.length
|
||||
if (current.length > 0 && used + cost > budget) {
|
||||
chunks.push(current)
|
||||
current = []
|
||||
used = 0
|
||||
}
|
||||
current.push(id)
|
||||
used += cost
|
||||
}
|
||||
|
||||
if (current.length > 0) {
|
||||
chunks.push(current)
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
/**
|
||||
* Caps how much of the already-committed ID list is spelled out in a partial-failure
|
||||
* message. A by-ids delete can carry 1000 IDs at ~68 bytes each, so the full list
|
||||
* would bury the actual failure under ~68 KB of text.
|
||||
*/
|
||||
const MAX_COMMITTED_IDS_IN_MESSAGE = 400
|
||||
|
||||
/**
|
||||
* Rewrites a failed batch's envelope so the reported error names the deletions the
|
||||
* earlier batches already committed.
|
||||
*
|
||||
* Batches run sequentially and Falcon has no way to roll back a deletion it already
|
||||
* performed. Short-circuiting on a later batch would therefore report a bare failure
|
||||
* over work that already happened, and a blind retry would target IDs that no longer
|
||||
* exist. Only the message survives to the caller ({@link fail} keeps `status` and the
|
||||
* message, not `data`), so the committed list is written onto `errors[0].message`,
|
||||
* which is the first thing {@link getFalconErrorMessage} reads.
|
||||
*
|
||||
* `committed` holds the IDs Falcon echoed in `resources`, never the IDs that were
|
||||
* requested, so an ID that failed inside an otherwise-200 batch is not reported as
|
||||
* deleted.
|
||||
*/
|
||||
function withCommittedIds(
|
||||
result: CrowdStrikeCallResult,
|
||||
committed: string[]
|
||||
): CrowdStrikeCallResult {
|
||||
if (committed.length === 0) return result
|
||||
|
||||
const envelope = isRecordLike(result.data) ? result.data : {}
|
||||
const existing = getRecordArray(envelope.errors)
|
||||
const reason = getFalconErrorMessage(result.data, 'CrowdStrike rejected a later batch.')
|
||||
const message =
|
||||
`${reason} This request was split into batches and ${committed.length} ID(s) were already deleted ` +
|
||||
`before the failing batch; they were not rolled back, so retry only the remainder. ` +
|
||||
`Deleted: ${truncate(committed.join(', '), MAX_COMMITTED_IDS_IN_MESSAGE)}`
|
||||
|
||||
return {
|
||||
...result,
|
||||
data: { ...envelope, errors: [{ ...(existing[0] ?? {}), message }, ...existing.slice(1)] },
|
||||
}
|
||||
}
|
||||
|
||||
interface ByIdsRequestOptions {
|
||||
method: 'GET' | 'DELETE'
|
||||
path: string
|
||||
ids: string[] | undefined
|
||||
query?: Record<string, string | number | boolean | undefined>
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues a by-ids lookup as however many requests it takes to stay under
|
||||
* `MAX_ID_URL_BYTES`, then presents the batches as one `{ meta, resources, errors }`
|
||||
* envelope so callers read the same shape a single request returns.
|
||||
*
|
||||
* Batches run sequentially: resource order matches the caller's ID order, the
|
||||
* endpoint's rate limit only ever sees one request at a time, and a failing batch
|
||||
* short-circuits with its own status instead of being merged away. A `DELETE` that
|
||||
* fails partway also carries the IDs its earlier batches already removed — see
|
||||
* {@link withCommittedIds}. `meta` comes
|
||||
* from the first batch — pagination is meaningless for a lookup that names every
|
||||
* ID it wants, and no by-ids operation here reads it.
|
||||
*/
|
||||
async function callCrowdStrikeByIds(
|
||||
baseUrl: string,
|
||||
accessToken: string,
|
||||
options: ByIdsRequestOptions
|
||||
): Promise<CrowdStrikeCallResult> {
|
||||
const prefix = buildUrl(baseUrl, {
|
||||
method: options.method,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
})
|
||||
const chunks = chunkIdsByUrlBudget(
|
||||
options.ids ?? [],
|
||||
Math.max(MAX_ID_URL_BYTES - prefix.length, 1)
|
||||
)
|
||||
|
||||
if (chunks.length <= 1) {
|
||||
return callCrowdStrike(baseUrl, accessToken, {
|
||||
method: options.method,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
repeatedQuery: { ids: options.ids },
|
||||
})
|
||||
}
|
||||
|
||||
const resources: unknown[] = []
|
||||
const errors: unknown[] = []
|
||||
const committed: string[] = []
|
||||
let meta: unknown
|
||||
let status = 200
|
||||
|
||||
for (const [index, chunk] of chunks.entries()) {
|
||||
const result = await callCrowdStrike(baseUrl, accessToken, {
|
||||
method: options.method,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
repeatedQuery: { ids: chunk },
|
||||
})
|
||||
|
||||
if (!result.ok) {
|
||||
return options.method === 'DELETE' ? withCommittedIds(result, committed) : result
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the IDs Falcon echoed in `resources` were actually deleted. A batch can
|
||||
* answer 200 while reporting per-ID failures in `errors`, so recording the
|
||||
* requested chunk would name indicators that are still live and tell the
|
||||
* caller to drop them from the retry.
|
||||
*/
|
||||
if (options.method === 'DELETE') {
|
||||
committed.push(...getStringResources(result.data))
|
||||
}
|
||||
|
||||
if (index === 0) {
|
||||
status = result.status
|
||||
meta = isRecordLike(result.data) ? result.data.meta : undefined
|
||||
}
|
||||
|
||||
resources.push(...getResourcesArray(result.data))
|
||||
errors.push(...getRecordArray(isRecordLike(result.data) ? result.data.errors : undefined))
|
||||
}
|
||||
|
||||
return { ok: true, status, data: { meta, resources, errors } }
|
||||
}
|
||||
|
||||
function buildAlertActionParameters(
|
||||
body: Extract<ExtendedBody, { operation: 'crowdstrike_update_alerts' }>
|
||||
) {
|
||||
@@ -251,10 +420,10 @@ export async function executeCrowdStrikeOperation(
|
||||
}
|
||||
|
||||
case 'crowdstrike_get_host_group_details': {
|
||||
const result = await callCrowdStrike(baseUrl, accessToken, {
|
||||
const result = await callCrowdStrikeByIds(baseUrl, accessToken, {
|
||||
method: 'GET',
|
||||
path: '/devices/entities/host-groups/v1',
|
||||
repeatedQuery: { ids: body.hostGroupIds },
|
||||
ids: body.hostGroupIds,
|
||||
})
|
||||
if (!result.ok) return fail(result, 'Failed to fetch CrowdStrike host group details')
|
||||
|
||||
@@ -330,10 +499,10 @@ export async function executeCrowdStrikeOperation(
|
||||
}
|
||||
|
||||
case 'crowdstrike_get_indicator_details': {
|
||||
const result = await callCrowdStrike(baseUrl, accessToken, {
|
||||
const result = await callCrowdStrikeByIds(baseUrl, accessToken, {
|
||||
method: 'GET',
|
||||
path: '/iocs/entities/indicators/v1',
|
||||
repeatedQuery: { ids: body.indicatorIds },
|
||||
ids: body.indicatorIds,
|
||||
})
|
||||
if (!result.ok) return fail(result, 'Failed to fetch CrowdStrike indicator details')
|
||||
|
||||
@@ -397,11 +566,11 @@ export async function executeCrowdStrikeOperation(
|
||||
}
|
||||
|
||||
case 'crowdstrike_delete_indicators': {
|
||||
const result = await callCrowdStrike(baseUrl, accessToken, {
|
||||
const result = await callCrowdStrikeByIds(baseUrl, accessToken, {
|
||||
method: 'DELETE',
|
||||
path: '/iocs/entities/indicators/v1',
|
||||
query: { comment: body.comment, filter: body.filter },
|
||||
repeatedQuery: { ids: body.filter ? undefined : body.indicatorIds },
|
||||
ids: body.filter ? undefined : body.indicatorIds,
|
||||
})
|
||||
if (!result.ok) return fail(result, 'Failed to delete CrowdStrike indicators')
|
||||
|
||||
@@ -449,10 +618,10 @@ export async function executeCrowdStrikeOperation(
|
||||
}
|
||||
|
||||
case 'crowdstrike_get_vulnerability_details': {
|
||||
const result = await callCrowdStrike(baseUrl, accessToken, {
|
||||
const result = await callCrowdStrikeByIds(baseUrl, accessToken, {
|
||||
method: 'GET',
|
||||
path: '/spotlight/entities/vulnerabilities/v2',
|
||||
repeatedQuery: { ids: body.vulnerabilityIds },
|
||||
ids: body.vulnerabilityIds,
|
||||
})
|
||||
if (!result.ok) return fail(result, 'Failed to fetch CrowdStrike vulnerability details')
|
||||
|
||||
|
||||
@@ -131,6 +131,27 @@ describe('validateReadOnlyQuery', () => {
|
||||
expect(validateReadOnlyQuery(query).isValid).toBe(false)
|
||||
})
|
||||
|
||||
/**
|
||||
* `\bupdate\b` cannot match `UPDATETEXT` — there is no word boundary after
|
||||
* `update` — so each text statement has to be screened in its own right.
|
||||
*/
|
||||
it.each([
|
||||
"SELECT 1 UPDATETEXT dbo.t.col @ptr 0 NULL 'x'",
|
||||
"SELECT 1 WRITETEXT dbo.t.col @ptr 'x'",
|
||||
'SELECT 1 READTEXT dbo.t.col @ptr 0 16',
|
||||
])('rejects the text statement batch %s', (query) => {
|
||||
expect(validateReadOnlyQuery(query).isValid).toBe(false)
|
||||
})
|
||||
|
||||
/** The same statements reached through the WHERE screen, which shares the list. */
|
||||
it.each([
|
||||
"id = 1 UPDATETEXT dbo.t.col @ptr 0 NULL 'x'",
|
||||
"id = 1 WRITETEXT dbo.t.col @ptr 'x'",
|
||||
'id = 1 READTEXT dbo.t.col @ptr 0 16',
|
||||
])('rejects the text statement %s in a WHERE clause', (where) => {
|
||||
expect(() => buildDeleteQuery('dbo.users', where)).toThrow()
|
||||
})
|
||||
|
||||
/**
|
||||
* The guard against over-screening. `FETCH` is excluded from the keyword list
|
||||
* because `OFFSET … FETCH NEXT` is the standard paging clause, and the added
|
||||
@@ -140,6 +161,7 @@ describe('validateReadOnlyQuery', () => {
|
||||
'SELECT * FROM dbo.users ORDER BY id OFFSET 10 ROWS FETCH NEXT 20 ROWS ONLY',
|
||||
'WITH p AS (SELECT id FROM dbo.o) SELECT * FROM p ORDER BY id OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY',
|
||||
'SELECT settled, offset_value, begin_date FROM dbo.t',
|
||||
'SELECT updatetext_id, writetext_flag, readtext_offset FROM dbo.t',
|
||||
'SELECT TOP (100) id, name FROM dbo.users WHERE is_active = 1',
|
||||
])('still accepts the legitimate read %s', (query) => {
|
||||
expect(validateReadOnlyQuery(query).isValid).toBe(true)
|
||||
|
||||
@@ -189,6 +189,14 @@ export async function executeQuery(
|
||||
* `SET`/`BEGIN`/`COMMIT`/`ROLLBACK` because session and transaction state are
|
||||
* changed the same way (`SET IDENTITY_INSERT`, `SET ANSI_NULLS`).
|
||||
*
|
||||
* The text statements `UPDATETEXT`, `WRITETEXT`, and `READTEXT` are listed in
|
||||
* their own right rather than left to `update`: there is no word boundary after
|
||||
* `update` in `UPDATETEXT`, so `\bupdate\b` never matches it and
|
||||
* `SELECT 1 UPDATETEXT dbo.t.col @ptr 0 NULL 'x'` would otherwise pass every
|
||||
* screen on the advertised read-only path. `READTEXT` reads rather than writes,
|
||||
* but it introduces a second statement in exactly the same semicolon-less way,
|
||||
* which is what this list exists to reject.
|
||||
*
|
||||
* `FETCH` is deliberately **absent**: `OFFSET … FETCH NEXT` is the standard
|
||||
* T-SQL paging clause, so screening it would reject the ordinary paged SELECT
|
||||
* this operation exists to run. Word boundaries keep the additions off ordinary
|
||||
@@ -196,7 +204,7 @@ export async function executeQuery(
|
||||
* @see https://learn.microsoft.com/en-us/sql/t-sql/statements/statements
|
||||
*/
|
||||
const MSSQL_STATEMENT_KEYWORDS =
|
||||
/\b(?:insert|update|delete|merge|drop|create|alter|truncate|disable|enable|set|begin|commit|rollback|grant|revoke|deny|exec|execute|backup|restore|shutdown|reconfigure|dbcc|kill|checkpoint|use|bulk|revert|setuser|openrowset|opendatasource|openquery|openxml|waitfor|into)\b/i
|
||||
/\b(?:insert|update|updatetext|writetext|readtext|delete|merge|drop|create|alter|truncate|disable|enable|set|begin|commit|rollback|grant|revoke|deny|exec|execute|backup|restore|shutdown|reconfigure|dbcc|kill|checkpoint|use|bulk|revert|setuser|openrowset|opendatasource|openquery|openxml|waitfor|into)\b/i
|
||||
|
||||
/** Extended, OLE-automation, and system stored procedures, called with or without `EXEC`. */
|
||||
const MSSQL_PROCEDURE_PATTERN = /\b(?:xp_|sp_)\w+/i
|
||||
|
||||
@@ -19,23 +19,31 @@ import type { CloudflareResponse } from '@/tools/cloudflare/types'
|
||||
*
|
||||
* Every such control therefore carries its own id and is republished here under
|
||||
* the tool's param name, before any coercion in the mapper reads it.
|
||||
*
|
||||
* Which side of a collision gets the new id is not a free choice. Block state
|
||||
* is never migrated, and `extractBlockParams` (`serializer/index.ts`) drops a
|
||||
* stored value whose id matches no subBlock config — a deleted input — so the
|
||||
* renamed side silently loses whatever shipped workflows stored. The read
|
||||
* filters therefore keep their original ids, where losing a value means
|
||||
* returning the whole zone under `success: true`, and the write controls take
|
||||
* the new ones, where losing a value means a PATCH simply omits the field.
|
||||
*/
|
||||
const SUBBLOCK_ALIASES: Record<string, Record<string, string>> = {
|
||||
create_zone: { type: 'zoneType' },
|
||||
list_zones: { name: 'zoneNameFilter' },
|
||||
create_dns_record: { type: 'recordType', proxied: 'recordProxied' },
|
||||
list_dns_records: {
|
||||
type: 'dnsTypeFilter',
|
||||
name: 'dnsNameFilter',
|
||||
content: 'dnsContentFilter',
|
||||
order: 'dnsOrder',
|
||||
proxied: 'dnsProxiedFilter',
|
||||
create_dns_record: { type: 'recordType', proxied: 'recordProxied', tags: 'recordTags' },
|
||||
update_dns_record: {
|
||||
type: 'updateRecordType',
|
||||
name: 'updateRecordName',
|
||||
content: 'updateRecordContent',
|
||||
proxied: 'updateRecordProxied',
|
||||
tags: 'updateRecordTags',
|
||||
},
|
||||
list_dns_records: { order: 'dnsOrder' },
|
||||
list_certificates: { status: 'certificateStatus' },
|
||||
purge_cache: { tags: 'purgeTags' },
|
||||
create_ruleset: { name: 'rulesetName' },
|
||||
update_ruleset_rule: { enabled: 'updateRuleEnabled' },
|
||||
create_rate_limit_rule: { action: 'rateLimitAction' },
|
||||
update_rate_limit_rule: { action: 'updateRateLimitAction' },
|
||||
update_rate_limit_rule: { action: 'updateRateLimitAction', enabled: 'updateRuleEnabled' },
|
||||
create_access_application: { type: 'appType', tags: 'accessAppTags' },
|
||||
update_access_application: { type: 'updateAppType', tags: 'accessAppTags' },
|
||||
update_access_policy: { decision: 'updatePolicyDecision' },
|
||||
@@ -44,8 +52,20 @@ const SUBBLOCK_ALIASES: Record<string, Record<string, string>> = {
|
||||
list_access_service_tokens: { name: 'listNameFilter' },
|
||||
list_worker_scripts: { tags: 'workerTagFilter' },
|
||||
list_tunnels: { status: 'tunnelStatus', name: 'listNameFilter' },
|
||||
list_r2_buckets: { cursor: 'r2Cursor' },
|
||||
list_rulesets: { cursor: 'rulesetCursor' },
|
||||
}
|
||||
|
||||
/**
|
||||
* Access application types whose request schema makes `domain` mandatory.
|
||||
*
|
||||
* `access_app_request` is an `anyOf` over per-type variants: `domain` is
|
||||
* required on the self_hosted, ssh, vnc, and rdp variants, optional and
|
||||
* writable on bookmark and mcp_portal, read-only on app_launcher, warp, biso,
|
||||
* and proxy_endpoint, and absent from saas, infrastructure, and mcp.
|
||||
*/
|
||||
const DOMAIN_REQUIRED_APP_TYPES = ['self_hosted', 'ssh', 'vnc', 'rdp'] as const
|
||||
|
||||
/** Every alias subBlock id, so none of them can reach a tool as a param. */
|
||||
const ALIASED_SUBBLOCK_IDS = [
|
||||
...new Set(Object.values(SUBBLOCK_ALIASES).flatMap((aliases) => Object.values(aliases))),
|
||||
@@ -69,7 +89,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
byOperation: {
|
||||
list_zones: [
|
||||
'List zones',
|
||||
{ text: 'named', field: 'zoneNameFilter' },
|
||||
{ text: 'named', field: 'name' },
|
||||
{ text: ', with status', field: 'status' },
|
||||
],
|
||||
get_zone: [{ text: 'Read details of zone', field: 'zoneId', core: true }],
|
||||
@@ -80,8 +100,8 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
delete_zone: [{ text: 'Delete zone', field: 'zoneId', core: true }],
|
||||
list_dns_records: [
|
||||
{ text: 'List DNS records in zone', field: 'zoneId', core: true },
|
||||
{ text: ', of type', field: 'dnsTypeFilter' },
|
||||
{ text: ', named', field: 'dnsNameFilter' },
|
||||
{ text: ', of type', field: 'type' },
|
||||
{ text: ', named', field: 'name' },
|
||||
],
|
||||
create_dns_record: [
|
||||
{ text: 'Add DNS record', field: 'name', core: true },
|
||||
@@ -90,7 +110,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
],
|
||||
update_dns_record: [
|
||||
{ text: 'Update DNS record', field: 'recordId', core: true },
|
||||
{ text: ', pointing it at', field: 'content' },
|
||||
{ text: ', pointing it at', field: 'updateRecordContent' },
|
||||
{ text: ', with TTL', field: 'ttl' },
|
||||
],
|
||||
delete_dns_record: [
|
||||
@@ -114,7 +134,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
],
|
||||
purge_cache: [
|
||||
{ text: 'Purge cache for zone', field: 'zoneId', core: true },
|
||||
{ text: ', limited to', field: ['files', 'prefixes', 'hosts', 'purgeTags'] },
|
||||
{ text: ', limited to', field: ['files', 'prefixes', 'hosts', 'tags'] },
|
||||
],
|
||||
list_rulesets: [{ text: 'List rulesets in zone', field: 'zoneId', core: true }],
|
||||
get_ruleset: [
|
||||
@@ -296,7 +316,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
|
||||
// List Zones inputs
|
||||
{
|
||||
id: 'zoneNameFilter',
|
||||
id: 'name',
|
||||
title: 'Domain Name',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by domain (e.g., example.com)',
|
||||
@@ -445,7 +465,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
condition: { field: 'operation', value: 'list_dns_records' },
|
||||
},
|
||||
{
|
||||
id: 'dnsTypeFilter',
|
||||
id: 'type',
|
||||
title: 'Record Type',
|
||||
type: 'dropdown',
|
||||
options: [
|
||||
@@ -463,7 +483,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'dnsNameFilter',
|
||||
id: 'name',
|
||||
title: 'Name Filter',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by record name (exact match)',
|
||||
@@ -471,7 +491,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'dnsContentFilter',
|
||||
id: 'content',
|
||||
title: 'Content Filter',
|
||||
type: 'short-input',
|
||||
placeholder: 'Filter by record content (exact match)',
|
||||
@@ -521,7 +541,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'dnsProxiedFilter',
|
||||
id: 'proxied',
|
||||
title: 'Proxied Filter',
|
||||
type: 'dropdown',
|
||||
options: [
|
||||
@@ -665,7 +685,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
id: 'recordTags',
|
||||
title: 'Tags',
|
||||
type: 'short-input',
|
||||
placeholder: 'Comma-separated tags (e.g., production,web)',
|
||||
@@ -691,7 +711,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
condition: { field: 'operation', value: 'update_dns_record' },
|
||||
},
|
||||
{
|
||||
id: 'type',
|
||||
id: 'updateRecordType',
|
||||
title: 'Record Type',
|
||||
type: 'dropdown',
|
||||
options: [
|
||||
@@ -709,7 +729,12 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'name',
|
||||
/**
|
||||
* Renaming a live DNS record is a write, and this control is advanced, so
|
||||
* sharing the bare `name` id let a name typed under any other operation
|
||||
* reach the PATCH and rename the record.
|
||||
*/
|
||||
id: 'updateRecordName',
|
||||
title: 'Record Name',
|
||||
type: 'short-input',
|
||||
placeholder: 'e.g., example.com or sub.example.com',
|
||||
@@ -717,7 +742,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'content',
|
||||
id: 'updateRecordContent',
|
||||
title: 'New Content',
|
||||
type: 'short-input',
|
||||
placeholder: 'e.g., 192.0.2.1',
|
||||
@@ -733,7 +758,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'proxied',
|
||||
id: 'updateRecordProxied',
|
||||
title: 'Proxied',
|
||||
type: 'dropdown',
|
||||
options: [
|
||||
@@ -762,7 +787,7 @@ export const CloudflareBlock: BlockConfig<CloudflareResponse> = {
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'tags',
|
||||
id: 'updateRecordTags',
|
||||
title: 'Tags',
|
||||
type: 'short-input',
|
||||
placeholder: 'Comma-separated tags (e.g., production,web)',
|
||||
@@ -1126,7 +1151,7 @@ Return ONLY the comma-separated URLs - no explanations, no extra text.`,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'purgeTags',
|
||||
id: 'tags',
|
||||
title: 'Cache Tags',
|
||||
type: 'short-input',
|
||||
placeholder: 'Comma-separated cache tags (Enterprise only)',
|
||||
@@ -1252,7 +1277,6 @@ Return ONLY the comma-separated URLs - no explanations, no extra text.`,
|
||||
options: [
|
||||
{ label: 'Zone (phase entry point)', id: 'zone' },
|
||||
{ label: 'Custom', id: 'custom' },
|
||||
{ label: 'Root', id: 'root' },
|
||||
],
|
||||
value: () => 'zone',
|
||||
condition: { field: 'operation', value: 'create_ruleset' },
|
||||
@@ -1444,12 +1468,31 @@ Return ONLY the expression - no explanations, no quotes around the whole express
|
||||
value: () => '',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
'create_ruleset_rule',
|
||||
'update_ruleset_rule',
|
||||
'create_rate_limit_rule',
|
||||
'update_rate_limit_rule',
|
||||
],
|
||||
value: ['create_ruleset_rule', 'create_rate_limit_rule'],
|
||||
},
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
/**
|
||||
* The update endpoints replace the rule, so `enabled` is a live on/off
|
||||
* switch for WAF and rate limiting there rather than a starting state.
|
||||
* Sharing the create control's id let a `false` chosen while drafting a
|
||||
* new rule reach a later update and disable an enforcing rule — from a
|
||||
* field the operation does not render in basic mode, since an advanced
|
||||
* control serializes on stored value alone, before its `condition` runs.
|
||||
*/
|
||||
id: 'updateRuleEnabled',
|
||||
title: 'Enabled',
|
||||
type: 'dropdown',
|
||||
options: [
|
||||
{ label: 'Leave unchanged (Cloudflare re-enables the rule)', id: '' },
|
||||
{ label: 'Yes', id: 'true' },
|
||||
{ label: 'No', id: 'false' },
|
||||
],
|
||||
value: () => '',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: ['update_ruleset_rule', 'update_rate_limit_rule'],
|
||||
},
|
||||
mode: 'advanced',
|
||||
},
|
||||
@@ -1485,6 +1528,12 @@ Return ONLY the expression - no explanations, no quotes around the whole express
|
||||
id: 'actionParameters',
|
||||
title: 'Action Parameters',
|
||||
type: 'long-input',
|
||||
/**
|
||||
* An `execute` rule carries the managed ruleset it deploys here, and the
|
||||
* update endpoint replaces the rule — so leaving this blank resets
|
||||
* action_parameters to {} and unbinds that ruleset.
|
||||
*/
|
||||
required: { field: 'action', value: 'execute' },
|
||||
placeholder: '{"id":"<MANAGED_RULESET_ID>","overrides":{"action":"log"}}',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
@@ -1688,7 +1737,6 @@ Return ONLY the comma-separated list - no explanations, no extra text.`,
|
||||
{ label: 'WARP', id: 'warp' },
|
||||
{ label: 'Browser Isolation', id: 'biso' },
|
||||
{ label: 'Bookmark', id: 'bookmark' },
|
||||
{ label: 'Dashboard SSO', id: 'dash_sso' },
|
||||
{ label: 'Infrastructure', id: 'infrastructure' },
|
||||
{ label: 'RDP', id: 'rdp' },
|
||||
{ label: 'MCP', id: 'mcp' },
|
||||
@@ -1717,7 +1765,6 @@ Return ONLY the comma-separated list - no explanations, no extra text.`,
|
||||
{ label: 'WARP', id: 'warp' },
|
||||
{ label: 'Browser Isolation', id: 'biso' },
|
||||
{ label: 'Bookmark', id: 'bookmark' },
|
||||
{ label: 'Dashboard SSO', id: 'dash_sso' },
|
||||
{ label: 'Infrastructure', id: 'infrastructure' },
|
||||
{ label: 'RDP', id: 'rdp' },
|
||||
{ label: 'MCP', id: 'mcp' },
|
||||
@@ -1731,12 +1778,56 @@ Return ONLY the comma-separated list - no explanations, no extra text.`,
|
||||
id: 'domain',
|
||||
title: 'Domain',
|
||||
type: 'short-input',
|
||||
placeholder: 'Required for self_hosted, ssh, vnc, rdp, and bookmark apps',
|
||||
placeholder: 'e.g., internal.example.com — required for self_hosted, ssh, vnc, and rdp apps',
|
||||
required: (values) =>
|
||||
values?.operation === 'update_access_application'
|
||||
? { field: 'updateAppType', value: [...DOMAIN_REQUIRED_APP_TYPES] }
|
||||
: { field: 'appType', value: [...DOMAIN_REQUIRED_APP_TYPES] },
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: ['create_access_application', 'update_access_application'],
|
||||
},
|
||||
},
|
||||
{
|
||||
/** `saas_app` is required on the saas request variant and rejected elsewhere. */
|
||||
id: 'saasApp',
|
||||
title: 'SaaS Application',
|
||||
type: 'long-input',
|
||||
required: true,
|
||||
placeholder: '{"auth_type":"saml","consumer_service_url":"https://example.com/acs"}',
|
||||
condition: (values) =>
|
||||
values?.operation === 'update_access_application'
|
||||
? {
|
||||
field: 'updateAppType',
|
||||
value: 'saas',
|
||||
and: { field: 'operation', value: 'update_access_application' },
|
||||
}
|
||||
: {
|
||||
field: 'appType',
|
||||
value: 'saas',
|
||||
and: { field: 'operation', value: 'create_access_application' },
|
||||
},
|
||||
},
|
||||
{
|
||||
/** `target_criteria` is required on the infrastructure and rdp variants. */
|
||||
id: 'targetCriteria',
|
||||
title: 'Target Criteria',
|
||||
type: 'long-input',
|
||||
required: true,
|
||||
placeholder: '[{"port":22,"protocol":"ssh","target_attributes":{"hostname":["app"]}}]',
|
||||
condition: (values) =>
|
||||
values?.operation === 'update_access_application'
|
||||
? {
|
||||
field: 'updateAppType',
|
||||
value: ['infrastructure', 'rdp'],
|
||||
and: { field: 'operation', value: 'update_access_application' },
|
||||
}
|
||||
: {
|
||||
field: 'appType',
|
||||
value: ['infrastructure', 'rdp'],
|
||||
and: { field: 'operation', value: 'create_access_application' },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'accessAppDomainFilter',
|
||||
title: 'Domain Filter',
|
||||
@@ -2208,11 +2299,24 @@ Return ONLY the JSON array - no explanations, no markdown fences.`,
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'cursor',
|
||||
/**
|
||||
* R2 returns its cursor at `result_info.cursor` and the Rulesets API at
|
||||
* `result_info.cursors.after`. The two are not interchangeable, so a
|
||||
* cursor carried across from the other list 400s.
|
||||
*/
|
||||
id: 'r2Cursor',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'Pagination cursor from a previous call',
|
||||
condition: { field: 'operation', value: ['list_r2_buckets', 'list_rulesets'] },
|
||||
condition: { field: 'operation', value: 'list_r2_buckets' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'rulesetCursor',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'Pagination cursor from a previous call',
|
||||
condition: { field: 'operation', value: 'list_rulesets' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
@@ -2543,13 +2647,31 @@ Return ONLY the JSON array - no explanations, no markdown fences.`,
|
||||
description: 'Whether the created DNS record is proxied through Cloudflare',
|
||||
},
|
||||
certificateStatus: { type: 'string', description: 'Certificate pack status filter' },
|
||||
zoneNameFilter: { type: 'string', description: 'Domain name filter when listing zones' },
|
||||
dnsTypeFilter: { type: 'string', description: 'DNS record type filter when listing records' },
|
||||
dnsNameFilter: { type: 'string', description: 'Record name filter when listing records' },
|
||||
dnsContentFilter: { type: 'string', description: 'Record content filter when listing records' },
|
||||
dnsOrder: { type: 'string', description: 'Sort field when listing DNS records' },
|
||||
dnsProxiedFilter: { type: 'string', description: 'Proxied filter when listing DNS records' },
|
||||
purgeTags: { type: 'string', description: 'Comma-separated cache tags to purge' },
|
||||
recordTags: { type: 'string', description: 'Tags applied to a created DNS record' },
|
||||
updateRecordType: {
|
||||
type: 'string',
|
||||
description: 'Record type a replaced DNS record ends up with',
|
||||
},
|
||||
updateRecordName: {
|
||||
type: 'string',
|
||||
description: 'Record name a replaced DNS record ends up with',
|
||||
},
|
||||
updateRecordContent: {
|
||||
type: 'string',
|
||||
description: 'Content a replaced DNS record ends up with',
|
||||
},
|
||||
updateRecordProxied: {
|
||||
type: 'string',
|
||||
description: 'Whether a replaced DNS record ends up proxied through Cloudflare',
|
||||
},
|
||||
updateRecordTags: { type: 'string', description: 'Tags a replaced DNS record ends up with' },
|
||||
updateRuleEnabled: {
|
||||
type: 'string',
|
||||
description: 'Whether a replaced WAF or rate limiting rule ends up enabled',
|
||||
},
|
||||
r2Cursor: { type: 'string', description: 'Pagination cursor when listing R2 buckets' },
|
||||
rulesetCursor: { type: 'string', description: 'Pagination cursor when listing rulesets' },
|
||||
workerTagFilter: { type: 'string', description: 'Tag filter when listing Worker scripts' },
|
||||
accessAppTags: { type: 'string', description: 'Tag names applied to an Access application' },
|
||||
listNameFilter: {
|
||||
@@ -2675,6 +2797,14 @@ Return ONLY the JSON array - no explanations, no markdown fences.`,
|
||||
customDenyUrl: { type: 'string', description: 'URL denied users are redirected to' },
|
||||
logoUrl: { type: 'string', description: 'Application logo URL' },
|
||||
policies: { type: 'string', description: 'JSON array of policies to attach' },
|
||||
saasApp: {
|
||||
type: 'string',
|
||||
description: 'JSON SaaS configuration for a saas-typed Access application',
|
||||
},
|
||||
targetCriteria: {
|
||||
type: 'string',
|
||||
description: 'JSON target criteria for an infrastructure- or rdp-typed Access application',
|
||||
},
|
||||
decision: { type: 'string', description: 'Access policy decision' },
|
||||
include: { type: 'string', description: 'JSON array of Access rules evaluated with OR logic' },
|
||||
exclude: { type: 'string', description: 'JSON array of Access rules evaluated with NOT logic' },
|
||||
@@ -2894,6 +3024,22 @@ Return ONLY the JSON array - no explanations, no markdown fences.`,
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool param names an alias may safely read a stored value back from.
|
||||
*
|
||||
* A value sitting under the bare param name is a workflow saved before that
|
||||
* control was renamed — unless a control still claims the name and could have
|
||||
* put the value there itself. Two claims disqualify a name:
|
||||
*
|
||||
* - a `mode: 'advanced'` control, because `shouldSerializeSubBlock` serializes
|
||||
* one on stored value alone, before its `condition` runs, so the value may be
|
||||
* another operation's hidden field bleeding across;
|
||||
* - a control with a seeded default, because block state is seeded by subBlock
|
||||
* id whatever the selected operation, so the value may be a default nobody
|
||||
* chose (`decision` reads back as `allow` from the create-policy control).
|
||||
*
|
||||
* Excluding both keeps the legacy read from re-opening what the aliases closed.
|
||||
*/
|
||||
export const CloudflareBlockMeta = {
|
||||
tags: ['cloud', 'monitoring'],
|
||||
url: 'https://www.cloudflare.com',
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { RTR_READ_ONLY_BASE_COMMANDS } from '@/lib/api/contracts/tools/crowdstrike'
|
||||
import { CrowdStrikeBlock } from '@/blocks/blocks/crowdstrike'
|
||||
|
||||
/**
|
||||
@@ -154,28 +155,18 @@ describe('CrowdStrike block params', () => {
|
||||
).toThrow(/500/)
|
||||
})
|
||||
|
||||
it('offers only the documented read-tier RTR base command families', () => {
|
||||
/**
|
||||
* Asserted against the contract constant rather than a second hand-maintained
|
||||
* literal: the route validates `base_command` with `RTR_READ_ONLY_BASE_COMMANDS`,
|
||||
* so a dropdown that drifts from it either hides a command the API accepts or
|
||||
* offers one the API rejects. Duplicating the list here would just move the
|
||||
* drift into the test.
|
||||
*/
|
||||
it('offers exactly the read-tier RTR base command families the contract accepts', () => {
|
||||
const baseCommand = CrowdStrikeBlock.subBlocks.find((subBlock) => subBlock.id === 'baseCommand')
|
||||
const ids = (baseCommand?.options as { id: string }[] | undefined)?.map((option) => option.id)
|
||||
|
||||
expect(ids).toEqual([
|
||||
'cat',
|
||||
'cd',
|
||||
'clear',
|
||||
'csrutil',
|
||||
'env',
|
||||
'eventlog',
|
||||
'filehash',
|
||||
'getsid',
|
||||
'help',
|
||||
'history',
|
||||
'ipconfig',
|
||||
'ls',
|
||||
'mount',
|
||||
'netstat',
|
||||
'ps',
|
||||
'reg',
|
||||
])
|
||||
expect(ids).toEqual([...RTR_READ_ONLY_BASE_COMMANDS])
|
||||
})
|
||||
|
||||
it('offers no write-tier RTR base command under the read-scoped tool', () => {
|
||||
|
||||
@@ -355,6 +355,12 @@ export const CrowdStrikeBlock: BlockConfig<CrowdStrikeResponse> = {
|
||||
},
|
||||
mode: 'advanced',
|
||||
},
|
||||
/**
|
||||
* Falcon has two sort spellings. Alerts, IOC Management, Spotlight, and Cases
|
||||
* document `field|direction`; Host Groups and Identity Protection sensors
|
||||
* document `field.direction`. One placeholder cannot show both, so the field
|
||||
* is declared twice under the same id with mutually exclusive conditions.
|
||||
*/
|
||||
{
|
||||
id: 'sort',
|
||||
title: 'Sort',
|
||||
@@ -363,9 +369,7 @@ export const CrowdStrikeBlock: BlockConfig<CrowdStrikeResponse> = {
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
'crowdstrike_query_sensors',
|
||||
'crowdstrike_query_alerts',
|
||||
'crowdstrike_query_host_groups',
|
||||
'crowdstrike_query_indicators',
|
||||
'crowdstrike_query_vulnerabilities',
|
||||
'crowdstrike_query_cases',
|
||||
@@ -373,6 +377,17 @@ export const CrowdStrikeBlock: BlockConfig<CrowdStrikeResponse> = {
|
||||
},
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'sort',
|
||||
title: 'Sort',
|
||||
type: 'short-input',
|
||||
placeholder: 'name.asc',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: ['crowdstrike_query_sensors', 'crowdstrike_query_host_groups'],
|
||||
},
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'includeHidden',
|
||||
title: 'Include Hidden Alerts',
|
||||
@@ -695,12 +710,14 @@ export const CrowdStrikeBlock: BlockConfig<CrowdStrikeResponse> = {
|
||||
{ label: 'getsid (Windows, macOS)', id: 'getsid' },
|
||||
{ label: 'help', id: 'help' },
|
||||
{ label: 'history', id: 'history' },
|
||||
{ label: 'ifconfig (macOS, Linux)', id: 'ifconfig' },
|
||||
{ label: 'ipconfig', id: 'ipconfig' },
|
||||
{ label: 'ls', id: 'ls' },
|
||||
{ label: 'mount', id: 'mount' },
|
||||
{ label: 'netstat', id: 'netstat' },
|
||||
{ label: 'ps', id: 'ps' },
|
||||
{ label: 'reg (Windows)', id: 'reg' },
|
||||
{ label: 'reg (Windows, query only)', id: 'reg' },
|
||||
{ label: 'users (Windows)', id: 'users' },
|
||||
],
|
||||
value: () => 'ls',
|
||||
condition: { field: 'operation', value: 'crowdstrike_execute_rtr_command' },
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Guards the Datadog block's params mapper and declared outputs against the tools they front.
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DatadogBlock } from '@/blocks/blocks/datadog'
|
||||
import * as datadogTools from '@/tools/datadog'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
const toolsById = new Map<string, ToolConfig>(
|
||||
Object.values(datadogTools)
|
||||
.filter(
|
||||
(value): value is ToolConfig => typeof value === 'object' && value !== null && 'id' in value
|
||||
)
|
||||
.map((tool) => [tool.id, tool])
|
||||
)
|
||||
|
||||
const mapParams = DatadogBlock.tools.config?.params
|
||||
|
||||
/**
|
||||
* The block hands the executor `{ ...inputs, ...transformedParams }`, so a mapper that simply
|
||||
* omits a key leaves the raw serialized subblock value in place. Every assertion about leakage
|
||||
* has to run against this merged shape rather than the mapper's return value alone.
|
||||
*/
|
||||
function mergedParams(inputs: Record<string, unknown>): Record<string, unknown> {
|
||||
return { ...inputs, ...(mapParams?.(inputs as never) as Record<string, unknown>) }
|
||||
}
|
||||
|
||||
const baseInputs = { apiKey: 'key', applicationKey: 'app-key', site: 'datadoghq.com' }
|
||||
|
||||
describe('datadog list_monitors params', () => {
|
||||
/**
|
||||
* `monitorTags` is Create Monitor's advanced tag field, but it serializes for every operation.
|
||||
* Leaving it in the merge silently filters the monitor list while presenting it as complete.
|
||||
*/
|
||||
it('clears a leftover Create Monitor tag filter after the merge', () => {
|
||||
const params = mergedParams({
|
||||
...baseInputs,
|
||||
operation: 'datadog_list_monitors',
|
||||
monitorTags: 'team:backend',
|
||||
})
|
||||
|
||||
expect(params.monitorTags).toBeUndefined()
|
||||
})
|
||||
|
||||
it('still forwards the List Monitors filters', () => {
|
||||
const params = mergedParams({
|
||||
...baseInputs,
|
||||
operation: 'datadog_list_monitors',
|
||||
listMonitorName: 'CPU',
|
||||
listMonitorTags: 'env:prod',
|
||||
})
|
||||
|
||||
expect(params.name).toBe('CPU')
|
||||
expect(params.tags).toBe('env:prod')
|
||||
})
|
||||
|
||||
it('forwards pagination as numbers', () => {
|
||||
const params = mergedParams({
|
||||
...baseInputs,
|
||||
operation: 'datadog_list_monitors',
|
||||
listMonitorPageSize: '50',
|
||||
listMonitorPage: '2',
|
||||
})
|
||||
|
||||
expect(params.pageSize).toBe(50)
|
||||
expect(params.page).toBe(2)
|
||||
})
|
||||
|
||||
/**
|
||||
* These are advanced free-text fields, so they can carry a typo or an unresolved
|
||||
* reference. A bare `Number()` would put the literal `NaN` in the query string
|
||||
* rather than omitting the parameter.
|
||||
*/
|
||||
it('drops a non-numeric pagination value instead of sending NaN', () => {
|
||||
const params = mergedParams({
|
||||
...baseInputs,
|
||||
operation: 'datadog_list_monitors',
|
||||
listMonitorPageSize: 'fifty',
|
||||
listMonitorPage: '{{unresolved}}',
|
||||
})
|
||||
|
||||
expect(params.pageSize).toBeUndefined()
|
||||
expect(params.page).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps an explicit page 0, which is Datadog’s first page', () => {
|
||||
const params = mergedParams({
|
||||
...baseInputs,
|
||||
operation: 'datadog_list_monitors',
|
||||
listMonitorPage: '0',
|
||||
})
|
||||
|
||||
expect(params.page).toBe(0)
|
||||
})
|
||||
|
||||
it('exposes pagination subBlocks gated on List Monitors', () => {
|
||||
const paginationIds = ['listMonitorPageSize', 'listMonitorPage']
|
||||
for (const id of paginationIds) {
|
||||
const subBlock = DatadogBlock.subBlocks.find((candidate) => candidate.id === id)
|
||||
expect(subBlock, `missing subBlock ${id}`).toBeDefined()
|
||||
expect(subBlock?.condition).toEqual({ field: 'operation', value: 'datadog_list_monitors' })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('datadog create_monitor params', () => {
|
||||
/** Clearing the leak must not disarm the operation the field actually belongs to. */
|
||||
it('still sends monitor tags as the create payload tags', () => {
|
||||
const params = mergedParams({
|
||||
...baseInputs,
|
||||
operation: 'datadog_create_monitor',
|
||||
name: 'High CPU',
|
||||
type: 'metric alert',
|
||||
monitorQuery: 'avg(last_5m):avg:system.cpu.user{*} > 90',
|
||||
monitorTags: 'team:backend',
|
||||
})
|
||||
|
||||
expect(params.tags).toBe('team:backend')
|
||||
})
|
||||
})
|
||||
|
||||
describe('datadog block outputs', () => {
|
||||
const outputs = DatadogBlock.outputs
|
||||
|
||||
it('declares the fields mute and unmute return', () => {
|
||||
for (const toolId of ['datadog_mute_monitor', 'datadog_unmute_monitor']) {
|
||||
const toolOutputs = Object.keys(toolsById.get(toolId)?.outputs ?? {})
|
||||
expect(toolOutputs).toContain('monitorId')
|
||||
for (const field of toolOutputs) {
|
||||
expect(outputs, `${toolId} emits ${field}`).toHaveProperty(field)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/** `errors` is the only signal that Datadog rejected part of a submitted metric batch. */
|
||||
it('declares the submit_metrics errors field', () => {
|
||||
expect(Object.keys(toolsById.get('datadog_submit_metrics')?.outputs ?? {})).toContain('errors')
|
||||
expect(outputs).toHaveProperty('errors')
|
||||
})
|
||||
|
||||
it('declares no output no tool can produce', () => {
|
||||
const emitted = new Set<string>()
|
||||
for (const toolId of DatadogBlock.tools.access ?? []) {
|
||||
for (const field of Object.keys(toolsById.get(toolId)?.outputs ?? {})) {
|
||||
emitted.add(field)
|
||||
}
|
||||
}
|
||||
|
||||
expect(Object.keys(outputs).filter((field) => !emitted.has(field))).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,20 @@ function toSwitchBoolean(value: unknown): boolean | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a List Monitors pagination input, dropping anything that is not a finite
|
||||
* number. These are advanced free-text fields, so they can carry a typo or an
|
||||
* unresolved reference, and a bare `Number()` would put the literal `NaN` in the
|
||||
* query string instead of omitting the parameter. An untouched subBlock resolves
|
||||
* to `null` and an empty one to `''`; both are omissions rather than zeros, while
|
||||
* an explicit `0` is Datadog's own first page and is kept.
|
||||
*/
|
||||
function datadogPageNumber(value: unknown): number | undefined {
|
||||
if (value == null || value === '') return undefined
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : undefined
|
||||
}
|
||||
|
||||
export const DatadogBlock: BlockConfig<DatadogResponse> = {
|
||||
type: 'datadog',
|
||||
name: 'Datadog',
|
||||
@@ -514,6 +528,22 @@ Return ONLY valid JSON - no explanations, no markdown code blocks.`,
|
||||
condition: { field: 'operation', value: 'datadog_list_monitors' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'listMonitorPageSize',
|
||||
title: 'Page Size',
|
||||
type: 'short-input',
|
||||
placeholder: '50',
|
||||
condition: { field: 'operation', value: 'datadog_list_monitors' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'listMonitorPage',
|
||||
title: 'Page Number',
|
||||
type: 'short-input',
|
||||
placeholder: '0',
|
||||
condition: { field: 'operation', value: 'datadog_list_monitors' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
|
||||
// Mute / Unmute Monitor inputs
|
||||
{
|
||||
@@ -1989,6 +2019,14 @@ Return ONLY the search query string - no explanations.`,
|
||||
...baseParams,
|
||||
name: params.listMonitorName || undefined,
|
||||
tags: params.listMonitorTags || undefined,
|
||||
/**
|
||||
* `monitorTags` belongs to Create Monitor but serializes for every operation, and
|
||||
* the block merges these params over the raw inputs. Without an explicit clear, a
|
||||
* leftover value would filter this list while presenting it as complete.
|
||||
*/
|
||||
monitorTags: undefined,
|
||||
pageSize: datadogPageNumber(params.listMonitorPageSize),
|
||||
page: datadogPageNumber(params.listMonitorPage),
|
||||
}
|
||||
|
||||
case 'datadog_mute_monitor':
|
||||
@@ -2352,6 +2390,8 @@ Return ONLY the search query string - no explanations.`,
|
||||
downtimeId: { type: 'string', description: 'Downtime ID to cancel' },
|
||||
listMonitorName: { type: 'string', description: 'Filter monitors by name' },
|
||||
listMonitorTags: { type: 'string', description: 'Filter monitors by tags' },
|
||||
listMonitorPageSize: { type: 'number', description: 'Monitors to return per page' },
|
||||
listMonitorPage: { type: 'number', description: 'Monitor page number (0-indexed)' },
|
||||
// Incidents
|
||||
incidentId: { type: 'string', description: 'Incident UUID' },
|
||||
incidentTitle: { type: 'string', description: 'Incident title' },
|
||||
@@ -2452,12 +2492,15 @@ Return ONLY the search query string - no explanations.`,
|
||||
// Metrics
|
||||
series: { type: 'json', description: 'Timeseries data' },
|
||||
status: { type: 'string', description: 'Query status' },
|
||||
errors: { type: 'json', description: 'Metric series rejected during submission' },
|
||||
// Events
|
||||
event: { type: 'json', description: 'Event data' },
|
||||
events: { type: 'json', description: 'List of events' },
|
||||
// Monitors
|
||||
monitor: { type: 'json', description: 'Monitor data' },
|
||||
monitors: { type: 'json', description: 'List of monitors' },
|
||||
monitorId: { type: 'number', description: 'ID of the muted or unmuted monitor' },
|
||||
name: { type: 'string', description: 'Name of the muted or unmuted monitor' },
|
||||
overallState: { type: 'string', description: 'Monitor state after muting or unmuting' },
|
||||
// Logs
|
||||
logs: { type: 'json', description: 'Log entries' },
|
||||
nextLogId: { type: 'string', description: 'Pagination cursor for logs' },
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { MicrosoftAdBlock } from '@/blocks/blocks/microsoft_ad'
|
||||
|
||||
/**
|
||||
* The tri-state assertions run against `{ ...inputs, ...buildParams(inputs) }`, the shape the
|
||||
* generic tool handler actually forwards. A key the mapper merely omits is *not* dropped by that
|
||||
* merge — the raw subBlock string survives — so asserting on the mapper's return alone would
|
||||
* pass against the broken code.
|
||||
*/
|
||||
describe('MicrosoftAdBlock', () => {
|
||||
const buildParams = MicrosoftAdBlock.tools.config.params!
|
||||
|
||||
const subBlock = (id: string) =>
|
||||
MicrosoftAdBlock.subBlocks.find((candidate) => candidate.id === id)!
|
||||
|
||||
describe('accountEnabled tri-state', () => {
|
||||
it('clears the "No Change" default instead of forwarding an empty string', () => {
|
||||
const inputs = { operation: 'update_user', userId: 'user-1', accountEnabled: '' }
|
||||
const finalInputs = { ...inputs, ...buildParams(inputs) }
|
||||
|
||||
expect(finalInputs.accountEnabled).toBeUndefined()
|
||||
})
|
||||
|
||||
it('is the serialized default, so the empty case is the common case', () => {
|
||||
const accountEnabled = subBlock('accountEnabled')
|
||||
|
||||
expect(accountEnabled.value?.()).toBe('')
|
||||
expect(accountEnabled.mode).toBeUndefined()
|
||||
})
|
||||
|
||||
it('coerces an explicit update_user choice to a boolean', () => {
|
||||
const enabled = { operation: 'update_user', userId: 'user-1', accountEnabled: 'true' }
|
||||
const disabled = { operation: 'update_user', userId: 'user-1', accountEnabled: 'false' }
|
||||
|
||||
expect({ ...enabled, ...buildParams(enabled) }.accountEnabled).toBe(true)
|
||||
expect({ ...disabled, ...buildParams(disabled) }.accountEnabled).toBe(false)
|
||||
})
|
||||
|
||||
it('coerces the create_user choice to a boolean and clears the update-side value', () => {
|
||||
const inputs = {
|
||||
operation: 'create_user',
|
||||
displayName: 'Ada',
|
||||
accountEnabled: '',
|
||||
accountEnabledCreate: 'false',
|
||||
}
|
||||
const finalInputs = { ...inputs, ...buildParams(inputs) }
|
||||
|
||||
expect(finalInputs.accountEnabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('visibility tri-state', () => {
|
||||
it('clears the "No Change" default instead of forwarding an empty string', () => {
|
||||
const inputs = { operation: 'update_group', groupId: 'group-1', visibility: '' }
|
||||
const finalInputs = { ...inputs, ...buildParams(inputs) }
|
||||
|
||||
expect(finalInputs.visibility).toBeUndefined()
|
||||
})
|
||||
|
||||
it('passes an explicit visibility through on both operations', () => {
|
||||
const update = { operation: 'update_group', groupId: 'group-1', visibility: 'Public' }
|
||||
const create = {
|
||||
operation: 'create_group',
|
||||
visibility: '',
|
||||
visibilityCreate: 'HiddenMembership',
|
||||
}
|
||||
|
||||
expect({ ...update, ...buildParams(update) }.visibility).toBe('Public')
|
||||
expect({ ...create, ...buildParams(create) }.visibility).toBe('HiddenMembership')
|
||||
})
|
||||
})
|
||||
|
||||
describe('top coercion', () => {
|
||||
it('never forwards NaN for a non-numeric page size', () => {
|
||||
const inputs = { operation: 'list_users', top: 'all' }
|
||||
const finalInputs = { ...inputs, ...buildParams(inputs) }
|
||||
|
||||
expect(finalInputs.top).toBeUndefined()
|
||||
})
|
||||
|
||||
it('coerces a numeric page size', () => {
|
||||
const inputs = { operation: 'list_users', top: '100' }
|
||||
|
||||
expect({ ...inputs, ...buildParams(inputs) }.top).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('groupId requirement', () => {
|
||||
it('requires a Group ID for list_group_members on the first page', () => {
|
||||
const required = subBlock('groupId').required as (values?: Record<string, unknown>) => {
|
||||
field: string
|
||||
value: string[]
|
||||
}
|
||||
|
||||
expect(required({}).value).toContain('list_group_members')
|
||||
})
|
||||
|
||||
it('drops the requirement only while continuing from a nextLink', () => {
|
||||
const required = subBlock('groupId').required as (values?: Record<string, unknown>) => {
|
||||
field: string
|
||||
value: string[]
|
||||
}
|
||||
const { value } = required({ nextLink: 'https://graph.microsoft.com/v1.0/groups/g/members' })
|
||||
|
||||
expect(value).not.toContain('list_group_members')
|
||||
expect(value).toEqual(
|
||||
expect.arrayContaining([
|
||||
'get_group',
|
||||
'update_group',
|
||||
'delete_group',
|
||||
'add_group_member',
|
||||
'remove_group_member',
|
||||
])
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* `User.ReadWrite.All` is listed on every `/users` read this block performs — list, get,
|
||||
* licenseDetails, registeredDevices, and ownedDevices — so `User.Read.All` was pure consent
|
||||
* noise. `Directory.Read.All` and `GroupMember.ReadWrite.All` are deliberately retained:
|
||||
* `GET /subscribedSkus` names neither `LicenseAssignment.ReadWrite.All` nor any scope left in
|
||||
* this list, and `POST /groups/{id}/members/$ref` accepts `GroupMember.ReadWrite.All` only.
|
||||
*/
|
||||
describe('requested OAuth scopes', () => {
|
||||
const requiredScopes =
|
||||
MicrosoftAdBlock.subBlocks.find((candidate) => candidate.id === 'credential')
|
||||
?.requiredScopes ?? []
|
||||
|
||||
it('does not request User.Read.All, which User.ReadWrite.All subsumes', () => {
|
||||
expect(requiredScopes).toContain('User.ReadWrite.All')
|
||||
expect(requiredScopes).not.toContain('User.Read.All')
|
||||
})
|
||||
|
||||
it('keeps the scopes no retained scope covers', () => {
|
||||
expect(requiredScopes).toEqual(
|
||||
expect.arrayContaining(['Directory.Read.All', 'GroupMember.ReadWrite.All'])
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -33,6 +33,28 @@ const ALWAYS_USER_ID_OPERATIONS = USER_ID_OPERATIONS.filter(
|
||||
(operation) => !PAGED_USER_ID_OPERATIONS.includes(operation)
|
||||
)
|
||||
|
||||
/** Operations that act on a single group and therefore require the Group ID field. */
|
||||
const GROUP_ID_OPERATIONS = [
|
||||
'get_group',
|
||||
'update_group',
|
||||
'delete_group',
|
||||
'list_group_members',
|
||||
'add_group_member',
|
||||
'remove_group_member',
|
||||
]
|
||||
|
||||
/**
|
||||
* Group operations that page through an `@odata.nextLink`. The continuation URL already
|
||||
* addresses the group, so these are the only group operations that can run without a Group ID,
|
||||
* and only when continuing from a previous page.
|
||||
*/
|
||||
const PAGED_GROUP_ID_OPERATIONS = ['list_group_members']
|
||||
|
||||
/** Group operations that always require a Group ID, whichever page is being fetched. */
|
||||
const ALWAYS_GROUP_ID_OPERATIONS = GROUP_ID_OPERATIONS.filter(
|
||||
(operation) => !PAGED_GROUP_ID_OPERATIONS.includes(operation)
|
||||
)
|
||||
|
||||
/** Collection operations that accept a page size and an @odata.nextLink continuation URL. */
|
||||
const PAGED_OPERATIONS = [
|
||||
'list_users',
|
||||
@@ -433,27 +455,16 @@ export const MicrosoftAdBlock: BlockConfig<MicrosoftAdResponse> = {
|
||||
title: 'Group ID',
|
||||
type: 'short-input',
|
||||
placeholder: 'Group ID (GUID)',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
'get_group',
|
||||
'update_group',
|
||||
'delete_group',
|
||||
'list_group_members',
|
||||
'add_group_member',
|
||||
'remove_group_member',
|
||||
],
|
||||
},
|
||||
required: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
'get_group',
|
||||
'update_group',
|
||||
'delete_group',
|
||||
'add_group_member',
|
||||
'remove_group_member',
|
||||
],
|
||||
},
|
||||
condition: { field: 'operation', value: GROUP_ID_OPERATIONS },
|
||||
/**
|
||||
* `list_group_members` pages through an `@odata.nextLink` that already addresses the
|
||||
* group, so it is the only member of this set that can run without a Group ID, and only
|
||||
* when continuing from a previous page.
|
||||
*/
|
||||
required: (values) =>
|
||||
values?.nextLink
|
||||
? { field: 'operation', value: ALWAYS_GROUP_ID_OPERATIONS }
|
||||
: { field: 'operation', value: GROUP_ID_OPERATIONS },
|
||||
},
|
||||
// Create group fields
|
||||
{
|
||||
@@ -817,7 +828,8 @@ export const MicrosoftAdBlock: BlockConfig<MicrosoftAdResponse> = {
|
||||
tool: (params) => `microsoft_ad_${params.operation}`,
|
||||
params: (params) => {
|
||||
const result: Record<string, unknown> = {}
|
||||
if (params.top) result.top = Number(params.top)
|
||||
const top = Number(params.top)
|
||||
result.top = params.top && Number.isFinite(top) ? top : undefined
|
||||
if (params.nextLink) result.nextLink = params.nextLink
|
||||
const values = params as Record<string, unknown>
|
||||
result.filter = values[FILTER_FIELD_BY_OPERATION[params.operation]] || undefined
|
||||
@@ -829,10 +841,13 @@ export const MicrosoftAdBlock: BlockConfig<MicrosoftAdResponse> = {
|
||||
: undefined
|
||||
}
|
||||
if (params.operation === 'update_user') {
|
||||
if (params.accountEnabled) result.accountEnabled = params.accountEnabled === 'true'
|
||||
result.accountEnabled = params.accountEnabled
|
||||
? params.accountEnabled === 'true'
|
||||
: undefined
|
||||
} else if (params.operation === 'create_user') {
|
||||
if (params.accountEnabledCreate)
|
||||
result.accountEnabled = params.accountEnabledCreate === 'true'
|
||||
result.accountEnabled = params.accountEnabledCreate
|
||||
? params.accountEnabledCreate === 'true'
|
||||
: undefined
|
||||
}
|
||||
if (params.mailEnabled !== undefined) result.mailEnabled = params.mailEnabled === 'true'
|
||||
if (params.securityEnabled !== undefined)
|
||||
@@ -843,9 +858,9 @@ export const MicrosoftAdBlock: BlockConfig<MicrosoftAdResponse> = {
|
||||
if (params.groupDescription) result.description = params.groupDescription
|
||||
if (params.groupTypes !== undefined) result.groupTypes = params.groupTypes
|
||||
if (params.operation === 'update_group') {
|
||||
if (params.visibility) result.visibility = params.visibility
|
||||
result.visibility = params.visibility || undefined
|
||||
} else if (params.operation === 'create_group') {
|
||||
if (params.visibilityCreate) result.visibility = params.visibilityCreate
|
||||
result.visibility = params.visibilityCreate || undefined
|
||||
}
|
||||
return result
|
||||
},
|
||||
|
||||
@@ -59,6 +59,22 @@ describe('Okta block params transform', () => {
|
||||
expect(merged.description).toBe('Eng team')
|
||||
})
|
||||
|
||||
/**
|
||||
* The update tool declares `name` optional and its merge helper carries the
|
||||
* stored name through when the field is blank, so requiring it on the block
|
||||
* would block a description-only update the tool and the API both accept.
|
||||
* Create has no stored name to fall back on and still requires it.
|
||||
*/
|
||||
it('requires the group name only when creating a group', () => {
|
||||
const groupName = OktaBlock.subBlocks.find((subBlock) => subBlock.id === 'groupName')
|
||||
|
||||
expect(groupName?.condition).toEqual({
|
||||
field: 'operation',
|
||||
value: ['okta_create_group', 'okta_update_group'],
|
||||
})
|
||||
expect(groupName?.required).toEqual({ field: 'operation', value: ['okta_create_group'] })
|
||||
})
|
||||
|
||||
it('keeps a false toggle, which is a real choice rather than a blank field', () => {
|
||||
const merged = merge({
|
||||
...BASE,
|
||||
|
||||
+145
-18
@@ -22,6 +22,23 @@ const SEND_EMAIL_DEFAULT_ON_OPERATIONS = ['okta_activate_user', 'okta_reset_pass
|
||||
|
||||
const SEND_EMAIL_DEFAULT_ON = new Set(SEND_EMAIL_DEFAULT_ON_OPERATIONS)
|
||||
|
||||
/**
|
||||
* The cursor subBlock each paginated operation reads.
|
||||
*
|
||||
* Okta's `after` cursor is opaque and scoped to the endpoint that minted it, so
|
||||
* every operation carries its own field rather than sharing one.
|
||||
*/
|
||||
const CURSOR_FIELD_BY_OPERATION: Record<string, string> = {
|
||||
okta_list_users: 'after',
|
||||
okta_list_groups: 'groupsAfter',
|
||||
okta_list_group_members: 'groupMembersAfter',
|
||||
okta_get_logs: 'logsAfter',
|
||||
okta_list_apps: 'appsAfter',
|
||||
okta_list_app_users: 'appUsersAfter',
|
||||
okta_list_app_groups: 'appGroupsAfter',
|
||||
okta_list_group_rules: 'groupRulesAfter',
|
||||
}
|
||||
|
||||
/** Treats a blank subBlock value as absent. */
|
||||
function blankToUndefined(value: unknown): unknown {
|
||||
return value === null || value === '' ? undefined : value
|
||||
@@ -464,11 +481,27 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
condition: { field: 'operation', value: ['okta_create_user', 'okta_update_user'] },
|
||||
mode: 'advanced',
|
||||
},
|
||||
/**
|
||||
* Okta's `activate` default is inverted between the two operations that take
|
||||
* it: creating a user activates unless told otherwise, enrolling a factor
|
||||
* does not. One shared switch could only be seeded for one of them, and
|
||||
* because it is advanced `shouldSerializeSubBlock` skips its condition, so
|
||||
* the other operation inherited the wrong answer. Each gets its own field
|
||||
* and the params mapper picks by operation.
|
||||
*/
|
||||
{
|
||||
id: 'activate',
|
||||
title: 'Activate Immediately',
|
||||
type: 'switch',
|
||||
condition: { field: 'operation', value: ['okta_create_user', 'okta_enroll_factor'] },
|
||||
value: () => 'true',
|
||||
condition: { field: 'operation', value: 'okta_create_user' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'activateFactor',
|
||||
title: 'Activate Immediately',
|
||||
type: 'switch',
|
||||
condition: { field: 'operation', value: 'okta_enroll_factor' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
// Group name (for create/update group)
|
||||
@@ -478,7 +511,13 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
type: 'short-input',
|
||||
placeholder: 'Engineering Team',
|
||||
condition: { field: 'operation', value: ['okta_create_group', 'okta_update_group'] },
|
||||
required: { field: 'operation', value: ['okta_create_group', 'okta_update_group'] },
|
||||
/**
|
||||
* Required only on create, where Okta has no stored name to fall back on.
|
||||
* An update is a read-modify-write that carries the stored name through, so
|
||||
* a blank name means "leave it alone" — requiring it here would block a
|
||||
* description-only update the tool and API both accept.
|
||||
*/
|
||||
required: { field: 'operation', value: ['okta_create_group'] },
|
||||
},
|
||||
{
|
||||
id: 'groupDescription',
|
||||
@@ -889,24 +928,77 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
},
|
||||
mode: 'advanced',
|
||||
},
|
||||
/**
|
||||
* One cursor field per operation.
|
||||
*
|
||||
* Okta mints `after` per endpoint and rejects a cursor issued by another
|
||||
* one, so a single shared field carried a `list_users` cursor straight into
|
||||
* `list_groups`. Being advanced, `shouldSerializeSubBlock` skips its
|
||||
* condition, so the stale value reached the wire unseen; the params mapper
|
||||
* publishes only the field belonging to the selected operation.
|
||||
*/
|
||||
{
|
||||
id: 'after',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
'okta_list_users',
|
||||
'okta_list_groups',
|
||||
'okta_list_group_members',
|
||||
'okta_get_logs',
|
||||
'okta_list_apps',
|
||||
'okta_list_app_users',
|
||||
'okta_list_app_groups',
|
||||
'okta_list_group_rules',
|
||||
],
|
||||
},
|
||||
condition: { field: 'operation', value: 'okta_list_users' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'groupsAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_list_groups' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'groupMembersAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_list_group_members' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'logsAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_get_logs' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'appsAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_list_apps' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'appUsersAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_list_app_users' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'appGroupsAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_list_app_groups' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
id: 'groupRulesAfter',
|
||||
title: 'Cursor',
|
||||
type: 'short-input',
|
||||
placeholder: 'nextCursor from a previous run',
|
||||
condition: { field: 'operation', value: 'okta_list_group_rules' },
|
||||
mode: 'advanced',
|
||||
},
|
||||
],
|
||||
@@ -973,6 +1065,9 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
* with an empty string rather than leaving it untouched.
|
||||
*/
|
||||
params: (params) => {
|
||||
const operation = String(params.operation)
|
||||
const cursorField = CURSOR_FIELD_BY_OPERATION[operation]
|
||||
|
||||
const result: Record<string, unknown> = {
|
||||
apiKey: params.apiKey,
|
||||
domain: params.domain,
|
||||
@@ -992,9 +1087,16 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
* so a stale value from a previously selected operation can still be
|
||||
* present here.
|
||||
*/
|
||||
sendEmail: SEND_EMAIL_DEFAULT_ON.has(String(params.operation))
|
||||
sendEmail: SEND_EMAIL_DEFAULT_ON.has(operation)
|
||||
? blankToUndefined(params.sendEmail)
|
||||
: blankToUndefined(params.sendDeactivationEmail),
|
||||
/** Same stale-advanced-value hazard: pick the toggle for this operation. */
|
||||
activate:
|
||||
operation === 'okta_enroll_factor'
|
||||
? blankToUndefined(params.activateFactor)
|
||||
: blankToUndefined(params.activate),
|
||||
/** A cursor is only valid on the endpoint that minted it. */
|
||||
after: cursorField ? blankToUndefined(params[cursorField]) : undefined,
|
||||
}
|
||||
|
||||
const mappedKeys = new Set([
|
||||
@@ -1009,6 +1111,10 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
'ruleSearch',
|
||||
'sendEmail',
|
||||
'sendDeactivationEmail',
|
||||
'activate',
|
||||
'activateFactor',
|
||||
'after',
|
||||
...Object.values(CURSOR_FIELD_BY_OPERATION),
|
||||
])
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (!mappedKeys.has(key)) result[key] = blankToUndefined(value)
|
||||
@@ -1038,6 +1144,10 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
title: { type: 'string', description: 'Job title' },
|
||||
department: { type: 'string', description: 'Department' },
|
||||
activate: { type: 'boolean', description: 'Activate user immediately on creation' },
|
||||
activateFactor: {
|
||||
type: 'boolean',
|
||||
description: 'Activate the MFA factor immediately on enrollment',
|
||||
},
|
||||
groupName: { type: 'string', description: 'Group name' },
|
||||
groupDescription: { type: 'string', description: 'Group description' },
|
||||
sendEmail: { type: 'boolean', description: 'Whether to send email notification' },
|
||||
@@ -1046,7 +1156,20 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
description: 'Whether to send the deactivation or removal email notification',
|
||||
},
|
||||
q: { type: 'string', description: 'Keyword search query' },
|
||||
after: { type: 'string', description: 'Cursor for the next page of results' },
|
||||
after: { type: 'string', description: 'Cursor for the next page of users' },
|
||||
groupsAfter: { type: 'string', description: 'Cursor for the next page of groups' },
|
||||
groupMembersAfter: { type: 'string', description: 'Cursor for the next page of group members' },
|
||||
logsAfter: { type: 'string', description: 'Cursor for the next page of System Log events' },
|
||||
appsAfter: { type: 'string', description: 'Cursor for the next page of applications' },
|
||||
appUsersAfter: {
|
||||
type: 'string',
|
||||
description: 'Cursor for the next page of application users',
|
||||
},
|
||||
appGroupsAfter: {
|
||||
type: 'string',
|
||||
description: 'Cursor for the next page of application groups',
|
||||
},
|
||||
groupRulesAfter: { type: 'string', description: 'Cursor for the next page of group rules' },
|
||||
since: { type: 'string', description: 'Start of the System Log time window' },
|
||||
until: { type: 'string', description: 'End of the System Log time window' },
|
||||
sortOrder: { type: 'string', description: 'System Log sort order' },
|
||||
@@ -1143,7 +1266,11 @@ export const OktaBlock: BlockConfig<OktaResponse> = {
|
||||
deactivated: { type: 'boolean', description: 'Whether user was deactivated' },
|
||||
suspended: { type: 'boolean', description: 'Whether user was suspended' },
|
||||
unsuspended: { type: 'boolean', description: 'Whether user was unsuspended' },
|
||||
activated: { type: 'boolean', description: 'Whether user was activated' },
|
||||
activated: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Activation timestamp on a user read. Activate User reports `true` here instead.',
|
||||
},
|
||||
deleted: { type: 'boolean', description: 'Whether resource was deleted' },
|
||||
activationUrl: { type: 'string', description: 'Activation URL (when sendEmail is false)' },
|
||||
activationToken: { type: 'string', description: 'Activation token (when sendEmail is false)' },
|
||||
|
||||
@@ -21,6 +21,26 @@ const FILE_FIELD = ['uploadFile', 'fileReference'] as const
|
||||
|
||||
const RECORD_MATCH_FIELD = ['sysId', 'number', 'query'] as const
|
||||
|
||||
/** JSON-valued subblocks, paired with the control label to name in a parse error. */
|
||||
const JSON_SUBBLOCKS = [
|
||||
['additionalFields', 'Additional Fields'],
|
||||
['variables', 'Item Variables'],
|
||||
] as const
|
||||
|
||||
/**
|
||||
* Parses a JSON-valued subblock, naming the control the typo is in.
|
||||
*
|
||||
* `tools.config.params` runs unguarded, so a bare `JSON.parse` escapes as
|
||||
* `JSON Parse error: Expected '}'` with nothing pointing at the field to fix.
|
||||
*/
|
||||
function parseJsonSubBlock(value: string, label: string): unknown {
|
||||
try {
|
||||
return JSON.parse(value)
|
||||
} catch {
|
||||
throw new Error(`${label} must be a JSON object`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Generic Table API operations, which address an arbitrary table by name. */
|
||||
const GENERIC_TABLE_OPS = [
|
||||
'servicenow_create_record',
|
||||
@@ -70,6 +90,17 @@ const SEMANTIC_UPDATE_OPS = [
|
||||
/** Every operation that writes through the Table API. */
|
||||
const SEMANTIC_WRITE_OPS = [...SEMANTIC_CREATE_OPS, ...SEMANTIC_UPDATE_OPS] as const
|
||||
|
||||
/**
|
||||
* Every operation whose tool spreads `writeParams` — `fields`, `displayValue`,
|
||||
* and `inputDisplayValue`.
|
||||
*
|
||||
* `update_approval` addresses its record by `approvalSysId` rather than the
|
||||
* shared `sysId`, so it stays out of `SEMANTIC_UPDATE_OPS`, but it declares the
|
||||
* same write params. Leaving it out of these controls made it the one operation
|
||||
* where a stale advanced `displayValue`/`returnFields` reached the wire unseen.
|
||||
*/
|
||||
const SEMANTIC_WRITE_PARAM_OPS = [...SEMANTIC_WRITE_OPS, 'servicenow_update_approval'] as const
|
||||
|
||||
/**
|
||||
* Write operations that accept the raw `additionalFields` escape hatch. Excludes
|
||||
* `add_incident_comment`, whose body is exactly one journal field, so a value
|
||||
@@ -97,7 +128,7 @@ const PAGINATED_OPS = [
|
||||
*/
|
||||
const SEMANTIC_DISPLAY_VALUE_OPS: ReadonlySet<string> = new Set([
|
||||
...SEMANTIC_READ_OPS,
|
||||
...SEMANTIC_WRITE_OPS,
|
||||
...SEMANTIC_WRITE_PARAM_OPS,
|
||||
])
|
||||
|
||||
/** Operations whose tool takes a `state`, from whichever control owns that state model. */
|
||||
@@ -519,14 +550,22 @@ Output: {"short_description": "Network outage", "description": "Network connecti
|
||||
value: () => 'all',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [...SEMANTIC_READ_OPS, ...SEMANTIC_WRITE_OPS],
|
||||
value: [...SEMANTIC_READ_OPS, ...SEMANTIC_WRITE_PARAM_OPS],
|
||||
},
|
||||
description:
|
||||
'How reference and choice fields come back. "all" (the default) returns both the sys_id and the label as {value, display_value}.',
|
||||
mode: 'advanced',
|
||||
},
|
||||
/**
|
||||
* Read Records keeps its projection on its own id.
|
||||
*
|
||||
* Sharing `fields` with the Create/Update Record JSON bodies meant one
|
||||
* stored value served two value spaces: a projection selected into Create
|
||||
* Record threw an uncaught `SyntaxError`, and a JSON body selected into
|
||||
* Read Records went out as `sysparm_fields=[object Object]`.
|
||||
*/
|
||||
{
|
||||
id: 'fields',
|
||||
id: 'readFields',
|
||||
title: 'Fields to Return',
|
||||
type: 'short-input',
|
||||
placeholder: 'number,short_description,priority',
|
||||
@@ -545,7 +584,7 @@ Output: {"short_description": "Network outage", "description": "Network connecti
|
||||
'servicenow_search_knowledge',
|
||||
'servicenow_get_knowledge_article',
|
||||
...SEMANTIC_READ_OPS,
|
||||
...SEMANTIC_WRITE_OPS,
|
||||
...SEMANTIC_WRITE_PARAM_OPS,
|
||||
],
|
||||
},
|
||||
description: 'Comma-separated list of fields',
|
||||
@@ -662,9 +701,10 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
id: 'having',
|
||||
title: 'Having',
|
||||
type: 'short-input',
|
||||
placeholder: 'count>5',
|
||||
placeholder: 'count^priority^>^3',
|
||||
condition: { field: 'operation', value: 'servicenow_aggregate' },
|
||||
description: 'Filter on aggregate results',
|
||||
description:
|
||||
'Filter on aggregate results, written as aggregate^field^operator^value and comma-separated for more than one',
|
||||
mode: 'advanced',
|
||||
},
|
||||
// Attachment record sys_id (list + upload)
|
||||
@@ -836,7 +876,11 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
title: 'Target State',
|
||||
type: 'combobox',
|
||||
options: [...CHANGE_STATE_OPTIONS],
|
||||
value: () => CHANGE_STATE_OPTIONS[0].id,
|
||||
/**
|
||||
* Deliberately unseeded. A seeded first option ("New") meant running the
|
||||
* operation untouched moved the change backwards; `required` now forces an
|
||||
* explicit choice instead.
|
||||
*/
|
||||
condition: { field: 'operation', value: 'servicenow_update_change_state' },
|
||||
required: true,
|
||||
description:
|
||||
@@ -1350,7 +1394,10 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
title: 'Decision',
|
||||
type: 'dropdown',
|
||||
options: [...APPROVAL_DECISION_OPTIONS],
|
||||
value: () => APPROVAL_DECISION_OPTIONS[0].id,
|
||||
/**
|
||||
* Deliberately unseeded. Seeding the first option defaulted the operation
|
||||
* to Approve, so `required` forces the caller to pick a decision.
|
||||
*/
|
||||
condition: { field: 'operation', value: 'servicenow_update_approval' },
|
||||
required: true,
|
||||
},
|
||||
@@ -1525,7 +1572,7 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
{ label: 'Yes — resolve display names to sys_ids', id: 'true' },
|
||||
],
|
||||
value: () => 'false',
|
||||
condition: { field: 'operation', value: [...SEMANTIC_WRITE_OPS] },
|
||||
condition: { field: 'operation', value: [...SEMANTIC_WRITE_PARAM_OPS] },
|
||||
description:
|
||||
'Sets sysparm_input_display_value, letting you write "Beth Anglin" into assigned_to instead of a sys_id. Also reinterprets date and time values in your timezone rather than GMT.',
|
||||
mode: 'advanced',
|
||||
@@ -1580,6 +1627,7 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
const {
|
||||
operation,
|
||||
fields,
|
||||
readFields,
|
||||
returnFields,
|
||||
file,
|
||||
attachmentLimit,
|
||||
@@ -1642,11 +1690,11 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
rest.updateView = rest.updateView === true || rest.updateView === 'true'
|
||||
}
|
||||
|
||||
for (const key of ['additionalFields', 'variables'] as const) {
|
||||
for (const [key, label] of JSON_SUBBLOCKS) {
|
||||
const value = rest[key]
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim()
|
||||
rest[key] = trimmed ? JSON.parse(trimmed) : undefined
|
||||
rest[key] = trimmed ? parseJsonSubBlock(trimmed, label) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1660,20 +1708,21 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
}
|
||||
|
||||
/**
|
||||
* `fields` means two different things: a JSON body on Create/Update
|
||||
* Record, and a comma-separated projection everywhere else. The generic
|
||||
* Table API tools keep the original `fields` subblock id, since renaming
|
||||
* it would orphan the stored value of every workflow already using them;
|
||||
* every operation added since reads `returnFields` instead, so a JSON
|
||||
* body can never arrive as a projection or the reverse.
|
||||
* The `fields` tool param means two different things: a JSON body on
|
||||
* Create/Update Record, and a comma-separated projection everywhere
|
||||
* else. Every subblock therefore owns exactly one of those value
|
||||
* spaces — `fields` is the Create/Update body, `readFields` is Read
|
||||
* Records' projection, `returnFields` is every other operation's — so a
|
||||
* JSON body can never arrive as a projection or the reverse.
|
||||
*/
|
||||
if (isCreateOrUpdate) {
|
||||
if (!fields) return { ...rest, fields: undefined }
|
||||
const parsedFields = typeof fields === 'string' ? JSON.parse(fields) : fields
|
||||
const parsedFields =
|
||||
typeof fields === 'string' ? parseJsonSubBlock(fields, 'Fields') : fields
|
||||
return { ...rest, fields: parsedFields }
|
||||
}
|
||||
|
||||
const projection = operation === 'servicenow_read_record' ? fields : returnFields
|
||||
const projection = operation === 'servicenow_read_record' ? readFields : returnFields
|
||||
return { ...rest, fields: projection || undefined }
|
||||
},
|
||||
},
|
||||
@@ -1694,6 +1743,10 @@ Output: {"state": "2", "assigned_to": "john.doe", "work_notes": "Assigned and st
|
||||
},
|
||||
offset: { type: 'number', description: 'Pagination offset' },
|
||||
fields: { type: 'json', description: 'Fields object or JSON string' },
|
||||
readFields: {
|
||||
type: 'string',
|
||||
description: 'Comma-separated fields to return (Read Records)',
|
||||
},
|
||||
displayValue: { type: 'string', description: 'Display value mode for reference fields' },
|
||||
semanticDisplayValue: {
|
||||
type: 'string',
|
||||
|
||||
@@ -136,3 +136,97 @@ describe('SplunkBlock subBlocks', () => {
|
||||
expect([...optionIds].sort()).toEqual([...SplunkBlock.tools.access].sort())
|
||||
})
|
||||
})
|
||||
|
||||
describe('SplunkBlock subBlock placeholders', () => {
|
||||
function subBlock(id: string) {
|
||||
const found = SplunkBlock.subBlocks.find((block) => block.id === id)
|
||||
if (!found) throw new Error(`SplunkBlock is missing the ${id} subBlock`)
|
||||
return found
|
||||
}
|
||||
|
||||
function subBlocksFor(id: string, operation: string) {
|
||||
return SplunkBlock.subBlocks.filter((block) => {
|
||||
if (block.id !== id) return false
|
||||
const value = block.condition?.value
|
||||
return Array.isArray(value) ? value.includes(operation) : value === operation
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* `nobody` names the shared-application owner, so it is one specific owner
|
||||
* rather than a neutral filler — and users copy placeholders. `-` is the
|
||||
* documented wildcard for all users, which is what the namespace builder
|
||||
* already substitutes.
|
||||
*/
|
||||
it('offers the - wildcard as the namespace owner, not nobody', () => {
|
||||
expect(subBlock('owner').placeholder).toBe('-')
|
||||
})
|
||||
|
||||
/**
|
||||
* The old placeholder claimed a default of 100 for all five operations (the real
|
||||
* default is 30 for the four collection endpoints) and advertised `0 returns
|
||||
* all` — an unbounded read that Get Search Results now rejects outright. Because
|
||||
* this block keeps subBlock ids unique, one field serves every operation, so it
|
||||
* must not state a rule that holds for only some of them.
|
||||
*/
|
||||
it('does not advertise a wrong default or an unbounded read on Max Results', () => {
|
||||
const shown = subBlocksFor('count', 'splunk_get_search_results')
|
||||
expect(shown).toHaveLength(1)
|
||||
|
||||
const placeholder = String(shown[0].placeholder)
|
||||
expect(placeholder).not.toContain('100')
|
||||
expect(placeholder).not.toMatch(/0 returns all/)
|
||||
})
|
||||
|
||||
/** The per-operation detail the placeholder can no longer carry. */
|
||||
it('documents the differing defaults and the 0 rule on the count input', () => {
|
||||
const description = String(SplunkBlock.inputs.count.description)
|
||||
|
||||
expect(description).toContain('30')
|
||||
expect(description).toContain('100')
|
||||
expect(description).toMatch(/reject/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SplunkBlock numeric coercion', () => {
|
||||
/**
|
||||
* A bare `Number()` sent `NaN` for an unparseable value, which serializes as the
|
||||
* literal `NaN` and makes Splunk reject the request with an error that names the
|
||||
* field but not the cause. Omitting it lets Splunk apply its own default.
|
||||
*/
|
||||
it.each(['abc', 'twenty', '12px'])('omits an unparseable Max Results (%s)', (count) => {
|
||||
const merged = mergedInputs({ operation: 'splunk_list_indexes', count })
|
||||
|
||||
expect(merged.count).not.toBe(Number.NaN)
|
||||
expect(mapParams({ operation: 'splunk_list_indexes', count })).not.toHaveProperty('count')
|
||||
})
|
||||
|
||||
it('omits an unparseable value on every numeric field it maps', () => {
|
||||
const result = mapParams({
|
||||
operation: 'splunk_dispatch_saved_search',
|
||||
savedSearchName: 'Errors',
|
||||
dispatchMaxCount: 'abc',
|
||||
dispatchMaxTime: 'abc',
|
||||
dispatchTtl: 'abc',
|
||||
offset: 'abc',
|
||||
})
|
||||
|
||||
expect(result).not.toHaveProperty('dispatchMaxCount')
|
||||
expect(result).not.toHaveProperty('dispatchMaxTime')
|
||||
expect(result).not.toHaveProperty('dispatchTtl')
|
||||
expect(result).not.toHaveProperty('offset')
|
||||
})
|
||||
|
||||
it('still coerces the numeric forms it is given', () => {
|
||||
expect(
|
||||
mapParams({ operation: 'splunk_create_search_job', autoCancel: '300', maxCount: 5000 })
|
||||
).toMatchObject({ autoCancel: 300, maxCount: 5000 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('SplunkBlock outputs', () => {
|
||||
it('declares the paging total and offset the list tools now project', () => {
|
||||
expect(SplunkBlock.outputs).toHaveProperty('total')
|
||||
expect(SplunkBlock.outputs).toHaveProperty('offset')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,26 @@ function toSplunkToggle(value: unknown): boolean | undefined {
|
||||
return value !== 'false' && value !== '0'
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a numeric Splunk field, dropping anything that is not a finite number.
|
||||
*
|
||||
* A bare `Number()` turns a typo like `abc` into `NaN`, which serializes into the
|
||||
* query string or form body as the literal `NaN` — Splunk then rejects the whole
|
||||
* request with an error that names the field but not the cause. Omitting the field
|
||||
* instead lets Splunk apply its own documented default, which is what an unusable
|
||||
* value should fall back to.
|
||||
*
|
||||
* An untouched subBlock resolves to `null` and an empty one to `''`; both are
|
||||
* omissions rather than zeros, so neither may reach `Number()` (which reads both
|
||||
* as `0`).
|
||||
*/
|
||||
function assignSplunkNumber(target: Record<string, unknown>, key: string, value: unknown): void {
|
||||
if (value == null || value === '') return
|
||||
const parsed = Number(value)
|
||||
if (!Number.isFinite(parsed)) return
|
||||
target[key] = parsed
|
||||
}
|
||||
|
||||
export const SplunkBlock: BlockConfig<SplunkResponse> = {
|
||||
type: 'splunk',
|
||||
name: 'Splunk',
|
||||
@@ -133,7 +153,7 @@ export const SplunkBlock: BlockConfig<SplunkResponse> = {
|
||||
id: 'owner',
|
||||
title: 'Namespace Owner',
|
||||
type: 'short-input',
|
||||
placeholder: 'nobody',
|
||||
placeholder: '-',
|
||||
mode: 'advanced',
|
||||
},
|
||||
{
|
||||
@@ -405,11 +425,20 @@ Examples:
|
||||
condition: { field: 'operation', value: 'splunk_list_indexes' },
|
||||
},
|
||||
|
||||
/**
|
||||
* One Max Results field serves five operations whose defaults differ (30 for
|
||||
* the four collection endpoints, 100 for search results) and whose handling of
|
||||
* `count=0` differs too — the collections read it as "every entry", while
|
||||
* search results reject it because nothing downstream bounds that read. This
|
||||
* block keeps subBlock ids unique, so rather than state one group's rule as if
|
||||
* it were shared, the placeholder states neither and the per-operation detail
|
||||
* lives in the `count` input description.
|
||||
*/
|
||||
{
|
||||
id: 'count',
|
||||
title: 'Max Results',
|
||||
type: 'short-input',
|
||||
placeholder: '100 (0 returns all)',
|
||||
placeholder: 'Leave empty for the Splunk default',
|
||||
condition: {
|
||||
field: 'operation',
|
||||
value: [
|
||||
@@ -460,17 +489,17 @@ Examples:
|
||||
params: (params) => {
|
||||
const result: Record<string, unknown> = {}
|
||||
|
||||
if (params.count != null && params.count !== '') result.count = Number(params.count)
|
||||
if (params.offset != null && params.offset !== '') result.offset = Number(params.offset)
|
||||
assignSplunkNumber(result, 'count', params.count)
|
||||
assignSplunkNumber(result, 'offset', params.offset)
|
||||
|
||||
switch (params.operation) {
|
||||
case 'splunk_run_search':
|
||||
if (params.autoCancel) result.autoCancel = Number(params.autoCancel)
|
||||
if (params.maxCount) result.maxCount = Number(params.maxCount)
|
||||
assignSplunkNumber(result, 'autoCancel', params.autoCancel)
|
||||
assignSplunkNumber(result, 'maxCount', params.maxCount)
|
||||
break
|
||||
case 'splunk_create_search_job':
|
||||
if (params.autoCancel) result.autoCancel = Number(params.autoCancel)
|
||||
if (params.maxCount) result.maxCount = Number(params.maxCount)
|
||||
assignSplunkNumber(result, 'autoCancel', params.autoCancel)
|
||||
assignSplunkNumber(result, 'maxCount', params.maxCount)
|
||||
result.enableLookups = toSplunkToggle(params.enableLookups)
|
||||
result.allowPartialResults = toSplunkToggle(params.allowPartialResults)
|
||||
break
|
||||
@@ -485,9 +514,9 @@ Examples:
|
||||
result.name = params.savedSearchName
|
||||
result.triggerActions = toSplunkToggle(params.triggerActions)
|
||||
result.forceDispatch = toSplunkToggle(params.forceDispatch)
|
||||
if (params.dispatchMaxCount) result.dispatchMaxCount = Number(params.dispatchMaxCount)
|
||||
if (params.dispatchMaxTime) result.dispatchMaxTime = Number(params.dispatchMaxTime)
|
||||
if (params.dispatchTtl) result.dispatchTtl = Number(params.dispatchTtl)
|
||||
assignSplunkNumber(result, 'dispatchMaxCount', params.dispatchMaxCount)
|
||||
assignSplunkNumber(result, 'dispatchMaxTime', params.dispatchMaxTime)
|
||||
assignSplunkNumber(result, 'dispatchTtl', params.dispatchTtl)
|
||||
break
|
||||
case 'splunk_get_fired_alerts':
|
||||
result.name = params.alertName
|
||||
@@ -552,7 +581,11 @@ Examples:
|
||||
description: 'Whether to dispatch even when the saved search is already running',
|
||||
},
|
||||
datatype: { type: 'string', description: 'Index type filter: all, event, or metric' },
|
||||
count: { type: 'number', description: 'Maximum number of entries to return' },
|
||||
count: {
|
||||
type: 'number',
|
||||
description:
|
||||
'Maximum number of entries to return. The Splunk default is 30 for the collection endpoints and 100 for search results. The collection endpoints read 0 as "return every entry"; search results reject it, since a completed job can hold hundreds of thousands of rows.',
|
||||
},
|
||||
offset: { type: 'number', description: 'Index of the first entry to return' },
|
||||
},
|
||||
|
||||
@@ -633,6 +666,15 @@ Examples:
|
||||
type: 'json',
|
||||
description: 'Apps installed on the instance (name, label, version, author, disabled)',
|
||||
},
|
||||
total: {
|
||||
type: 'number',
|
||||
description:
|
||||
'Total number of entries matching a list request, from the response paging envelope. Compare with offset to decide whether another page remains.',
|
||||
},
|
||||
offset: {
|
||||
type: 'number',
|
||||
description: 'Offset of the first entry in the returned page, from the paging envelope',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -746,7 +746,10 @@ const HOST_GROUP_ACTIONS = ['add-hosts', 'remove-hosts'] as const
|
||||
* and it accepts only these base commands. Subcommands ride in `command_string`
|
||||
* (`eventlog view ...`, `reg query ...`), never in `base_command`; the write-tier
|
||||
* variants such as `eventlog backup` belong to `/entities/active-responder-command/v1`
|
||||
* and would fail here on scope.
|
||||
* and would fail here on scope. `reg` is read-tier only as `reg query` — `reg set`
|
||||
* and `reg delete` are Active Responder commands on that same write-tier endpoint.
|
||||
* `ifconfig` and `users` are the macOS/Linux counterparts to `ipconfig` and are
|
||||
* read-tier on this endpoint.
|
||||
*/
|
||||
export const RTR_READ_ONLY_BASE_COMMANDS = [
|
||||
'cat',
|
||||
@@ -759,12 +762,14 @@ export const RTR_READ_ONLY_BASE_COMMANDS = [
|
||||
'getsid',
|
||||
'help',
|
||||
'history',
|
||||
'ifconfig',
|
||||
'ipconfig',
|
||||
'ls',
|
||||
'mount',
|
||||
'netstat',
|
||||
'ps',
|
||||
'reg',
|
||||
'users',
|
||||
] as const
|
||||
|
||||
const performHostGroupActionSchema = baseRequestSchema.extend({
|
||||
@@ -814,10 +819,10 @@ const getIndicatorDetailsSchema = baseRequestSchema.extend({
|
||||
* constrained here. Unknown keys pass through so newly documented IOC fields keep
|
||||
* working without a contract change.
|
||||
*
|
||||
* This guards blanks only. CrowdStrike separately documents that *omitting* a
|
||||
* field on PATCH also overwrites it with a blank value, and no schema can detect
|
||||
* an absent key — that hazard is carried in the `crowdstrike_update_indicators`
|
||||
* tool and parameter descriptions instead.
|
||||
* This guards blanks only. Omitted fields have also been observed to come back
|
||||
* cleared after a PATCH — CrowdStrike publishes no statement either way — and no
|
||||
* schema can detect an absent key, so that hazard is carried in the
|
||||
* `crowdstrike_update_indicators` tool and parameter descriptions instead.
|
||||
*/
|
||||
const indicatorPayloadSchema = z
|
||||
.object({
|
||||
@@ -878,7 +883,10 @@ const createIndicatorsSchema = baseRequestSchema.extend({
|
||||
indicators: z
|
||||
.array(createIndicatorPayloadSchema)
|
||||
.min(1, 'At least one indicator is required')
|
||||
.max(200, 'CrowdStrike accepts at most 200 indicators per request'),
|
||||
.max(
|
||||
200,
|
||||
'Sim caps this request at 200 indicators; CrowdStrike publishes no limit for this endpoint'
|
||||
),
|
||||
comment: nonBlankQuerySchema('Comment'),
|
||||
retrodetects: z.boolean().optional(),
|
||||
ignoreWarnings: z.boolean().optional(),
|
||||
@@ -889,7 +897,10 @@ const updateIndicatorsSchema = baseRequestSchema.extend({
|
||||
indicators: z
|
||||
.array(updateIndicatorPayloadSchema)
|
||||
.min(1, 'At least one indicator is required')
|
||||
.max(200, 'CrowdStrike accepts at most 200 indicators per request'),
|
||||
.max(
|
||||
200,
|
||||
'Sim caps this request at 200 indicators; CrowdStrike publishes no limit for this endpoint'
|
||||
),
|
||||
comment: nonBlankQuerySchema('Comment'),
|
||||
retrodetects: z.boolean().optional(),
|
||||
ignoreWarnings: z.boolean().optional(),
|
||||
|
||||
@@ -4801,7 +4801,7 @@
|
||||
"operations": [
|
||||
{
|
||||
"name": "Query Alerts",
|
||||
"description": "Search CrowdStrike Falcon alerts with a Falcon Query Language filter and return their composite IDs. Uses the current Alerts API (GET /alerts/queries/alerts/v2), which supersedes the deprecated Detects API. Requires the \"Alerts: Read\" API scope."
|
||||
"description": "Search CrowdStrike Falcon alerts with a Falcon Query Language filter and return their composite IDs. Uses the current Alerts API (GET /alerts/queries/alerts/v2), which replaced the Detects API decommissioned on September 30, 2025. Requires the \"Alerts: Read\" API scope."
|
||||
},
|
||||
{
|
||||
"name": "Get Alert Details",
|
||||
@@ -4841,7 +4841,7 @@
|
||||
},
|
||||
{
|
||||
"name": "Update Indicators",
|
||||
"description": "Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/entities/indicators/v1). DESTRUCTIVE: CrowdStrike blanks out any field you omit, so read each indicator with crowdstrike_get_indicator_details first and resend its full field set with your edits applied. Changing action or scope changes prevention behavior fleet-wide. type and value are immutable. Requires the \"IOC Management: Write\" API scope."
|
||||
"description": "Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/entities/indicators/v1). DESTRUCTIVE: omitted fields may be cleared, so read each indicator with crowdstrike_get_indicator_details first and resend its full field set with your edits applied. Changing action or scope changes prevention behavior fleet-wide. type and value are immutable. Requires the \"IOC Management: Write\" API scope."
|
||||
},
|
||||
{
|
||||
"name": "Delete Indicators",
|
||||
@@ -4861,7 +4861,7 @@
|
||||
},
|
||||
{
|
||||
"name": "Execute RTR Command",
|
||||
"description": "Run a read-only Real Time Response command in an open CrowdStrike Falcon session (POST /real-time-response/entities/command/v1). baseCommand names the family only (cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ipconfig, ls, mount, netstat, ps, reg); subcommands go in commandString. Host-modifying commands need the Active Responder or Admin endpoints. Requires the \"Real time response: Read\" API scope."
|
||||
"description": "Run a read-only Real Time Response command in an open CrowdStrike Falcon session (POST /real-time-response/entities/command/v1). baseCommand names the family only (cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ifconfig, ipconfig, ls, mount, netstat, ps, reg, users); subcommands go in commandString. Host-modifying commands need the Active Responder or Admin endpoints. Requires the \"Real time response: Read\" API scope."
|
||||
},
|
||||
{
|
||||
"name": "Get RTR Command Status",
|
||||
|
||||
@@ -334,7 +334,6 @@ export const OAUTH_PROVIDERS: Record<string, OAuthProviderConfig> = {
|
||||
'openid',
|
||||
'profile',
|
||||
'email',
|
||||
'User.Read.All',
|
||||
'User.ReadWrite.All',
|
||||
'Group.ReadWrite.All',
|
||||
'GroupMember.ReadWrite.All',
|
||||
|
||||
@@ -256,7 +256,6 @@ export const SCOPE_DESCRIPTIONS: Record<string, string> = {
|
||||
'Sites.ReadWrite.All': 'Read and write Sharepoint sites',
|
||||
'Sites.Manage.All': 'Manage Sharepoint sites',
|
||||
'https://dynamics.microsoft.com/user_impersonation': 'Access Microsoft Dataverse on your behalf',
|
||||
'User.Read.All': 'Read all user profiles',
|
||||
'User.ReadWrite.All': 'Read and write all user profiles',
|
||||
'GroupMember.ReadWrite.All': 'Read and write all group memberships',
|
||||
'Directory.Read.All': 'Read directory data',
|
||||
|
||||
@@ -423,6 +423,71 @@ describe('migrateSubblockIds', () => {
|
||||
expect(blocks.b3.subBlocks.code).toBeDefined()
|
||||
})
|
||||
|
||||
/**
|
||||
* The suffixed Cloudflare read-filter ids existed only between #6740 and the
|
||||
* restore, and never shipped in a release. They are dropped rather than renamed
|
||||
* onto `name`/`type`/`content`/`proxied`/`tags`, which every Cloudflare block
|
||||
* already materializes — a rename would hit the collision guard and discard the
|
||||
* value regardless, while leaving the stale key parked in state.
|
||||
*/
|
||||
describe('cloudflare block', () => {
|
||||
it('drops the staging-only read-filter ids without disturbing the restored ids', () => {
|
||||
const input: Record<string, BlockState> = {
|
||||
b1: makeBlock({
|
||||
type: 'cloudflare',
|
||||
subBlocks: {
|
||||
operation: { id: 'operation', type: 'dropdown', value: 'list_dns_records' },
|
||||
zoneNameFilter: { id: 'zoneNameFilter', type: 'short-input', value: 'example.com' },
|
||||
dnsNameFilter: { id: 'dnsNameFilter', type: 'short-input', value: 'www' },
|
||||
dnsTypeFilter: { id: 'dnsTypeFilter', type: 'dropdown', value: 'A' },
|
||||
dnsContentFilter: { id: 'dnsContentFilter', type: 'short-input', value: '1.2.3.4' },
|
||||
dnsProxiedFilter: { id: 'dnsProxiedFilter', type: 'dropdown', value: 'true' },
|
||||
purgeTags: { id: 'purgeTags', type: 'short-input', value: 'tag-a' },
|
||||
cursor: { id: 'cursor', type: 'short-input', value: 'abc' },
|
||||
name: { id: 'name', type: 'short-input', value: '' },
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
const { blocks, migrated } = migrateSubblockIds(input)
|
||||
|
||||
expect(migrated).toBe(true)
|
||||
for (const legacyId of [
|
||||
'zoneNameFilter',
|
||||
'dnsNameFilter',
|
||||
'dnsTypeFilter',
|
||||
'dnsContentFilter',
|
||||
'dnsProxiedFilter',
|
||||
'purgeTags',
|
||||
'cursor',
|
||||
]) {
|
||||
expect(blocks.b1.subBlocks[legacyId]).toBeUndefined()
|
||||
expect(blocks.b1.subBlocks[`_removed_${legacyId}`]).toBeUndefined()
|
||||
}
|
||||
expect(blocks.b1.subBlocks.operation.value).toBe('list_dns_records')
|
||||
expect(blocks.b1.subBlocks.name.value).toBe('')
|
||||
})
|
||||
|
||||
it('leaves a workflow saved on the restored ids untouched', () => {
|
||||
const input: Record<string, BlockState> = {
|
||||
b1: makeBlock({
|
||||
type: 'cloudflare',
|
||||
subBlocks: {
|
||||
operation: { id: 'operation', type: 'dropdown', value: 'list_dns_records' },
|
||||
name: { id: 'name', type: 'short-input', value: 'www' },
|
||||
type: { id: 'type', type: 'dropdown', value: 'A' },
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
const { blocks, migrated } = migrateSubblockIds(input)
|
||||
|
||||
expect(migrated).toBe(false)
|
||||
expect(blocks.b1.subBlocks.name.value).toBe('www')
|
||||
expect(blocks.b1.subBlocks.type.value).toBe('A')
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle blocks with empty subBlocks', () => {
|
||||
const input: Record<string, BlockState> = {
|
||||
b1: makeBlock({ type: 'knowledge', subBlocks: {} }),
|
||||
|
||||
@@ -114,6 +114,35 @@ export const SUBBLOCK_ID_MIGRATIONS: Record<string, Record<string, string>> = {
|
||||
host: '_removed_host',
|
||||
apiKey: '_removed_apiKey',
|
||||
},
|
||||
/**
|
||||
* The Cloudflare block briefly gave its DNS/zone read filters and its cache-purge
|
||||
* tag list operation-suffixed IDs, and added a single shared `cursor`. This PR
|
||||
* restores the shipped IDs (`name`, `type`, `content`, `proxied`, `tags`) so saved
|
||||
* workflows keep filtering, and splits the cursor per endpoint.
|
||||
*
|
||||
* The suffixed IDs are dropped rather than renamed onto their shipped
|
||||
* counterparts. They existed only between #6740 and this change and never
|
||||
* appeared in a release, so no deployed workflow carries them — and a rename
|
||||
* could not restore a value even for a workflow edited in that window. Block
|
||||
* state materializes an entry for every subblock the config declares, not just
|
||||
* the active operation's, so `name`/`type`/`content`/`proxied`/`tags` are always
|
||||
* already present; {@link migrateBlockSubblockIds} would hit its collision guard
|
||||
* and discard the source value anyway. Mapping them as renames would therefore
|
||||
* claim a recovery that never happens, while leaving the stale value parked in
|
||||
* state and riding along in exports.
|
||||
*
|
||||
* `cursor` split into `r2Cursor` and `rulesetCursor`, so there is no single
|
||||
* replacement to name.
|
||||
*/
|
||||
cloudflare: {
|
||||
zoneNameFilter: '_removed_zoneNameFilter',
|
||||
dnsNameFilter: '_removed_dnsNameFilter',
|
||||
dnsTypeFilter: '_removed_dnsTypeFilter',
|
||||
dnsContentFilter: '_removed_dnsContentFilter',
|
||||
dnsProxiedFilter: '_removed_dnsProxiedFilter',
|
||||
purgeTags: '_removed_purgeTags',
|
||||
cursor: '_removed_cursor',
|
||||
},
|
||||
rippling: {
|
||||
action: '_removed_action',
|
||||
candidateDepartment: '_removed_candidateDepartment',
|
||||
|
||||
@@ -151,28 +151,31 @@ describe('subBlock ids that share a tool param keep their own default', () => {
|
||||
const mapped = mapFor('create_dns_record', { zoneId: 'zone1' })
|
||||
|
||||
for (const alias of [
|
||||
'zoneType',
|
||||
'recordType',
|
||||
'recordProxied',
|
||||
'recordTags',
|
||||
'updateRecordType',
|
||||
'updateRecordName',
|
||||
'updateRecordContent',
|
||||
'updateRecordProxied',
|
||||
'updateRecordTags',
|
||||
'dnsOrder',
|
||||
'certificateStatus',
|
||||
'appType',
|
||||
'updateAppType',
|
||||
'updatePolicyDecision',
|
||||
'rulesetName',
|
||||
'updateRuleEnabled',
|
||||
'rateLimitAction',
|
||||
'updateRateLimitAction',
|
||||
'rulesetName',
|
||||
'zoneNameFilter',
|
||||
'zoneType',
|
||||
'dnsTypeFilter',
|
||||
'dnsNameFilter',
|
||||
'dnsContentFilter',
|
||||
'dnsOrder',
|
||||
'dnsProxiedFilter',
|
||||
'purgeTags',
|
||||
'workerTagFilter',
|
||||
'appType',
|
||||
'updateAppType',
|
||||
'accessAppTags',
|
||||
'updatePolicyDecision',
|
||||
'listNameFilter',
|
||||
'accessAppDomainFilter',
|
||||
'workerTagFilter',
|
||||
'tunnelStatus',
|
||||
'r2Cursor',
|
||||
'rulesetCursor',
|
||||
]) {
|
||||
expect(mapped[alias], `alias ${alias} reached the tool`).toBeUndefined()
|
||||
}
|
||||
@@ -222,6 +225,15 @@ describe('a shared subBlock id means the same thing everywhere', () => {
|
||||
'rulesetId',
|
||||
])
|
||||
|
||||
/**
|
||||
* Ids a read filter and a written value share on purpose. Both sides render a
|
||||
* control the user can see and edit for their own operation, so a carried-over
|
||||
* value is visible rather than hidden — and these are the ids shipped
|
||||
* workflows already store, which a rename would strand (see
|
||||
* `the ids shipped workflows already store are still live`).
|
||||
*/
|
||||
const SHARED_VISIBLE_IDS = new Set(['name', 'content'])
|
||||
|
||||
const WRITE_PREFIXES = ['create_', 'update_', 'delete_', 'purge_', 'revoke_']
|
||||
|
||||
function operationsFor(subBlock: (typeof CloudflareBlock.subBlocks)[number]): string[] {
|
||||
@@ -236,7 +248,7 @@ describe('a shared subBlock id means the same thing everywhere', () => {
|
||||
const kindsById = new Map<string, Set<string>>()
|
||||
|
||||
for (const subBlock of CloudflareBlock.subBlocks) {
|
||||
if (ADDRESSING_IDS.has(subBlock.id)) continue
|
||||
if (ADDRESSING_IDS.has(subBlock.id) || SHARED_VISIBLE_IDS.has(subBlock.id)) continue
|
||||
for (const operation of operationsFor(subBlock)) {
|
||||
const kind = WRITE_PREFIXES.some((prefix) => operation.startsWith(prefix))
|
||||
? 'write'
|
||||
@@ -330,3 +342,291 @@ describe('no hidden advanced control feeds an operation that cannot show it', ()
|
||||
expect(leaks).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Block state is never migrated, and `extractBlockParams` (`serializer/index.ts`)
|
||||
* drops a stored value whose id matches no subBlock config — for a non-custom
|
||||
* block that is a deleted input. So renaming a control strands whatever shipped
|
||||
* workflows stored under the old id, and no mapper-level fallback can recover
|
||||
* it: the value is gone before `tools.config.params` runs.
|
||||
*
|
||||
* That decides which side of an id collision may be renamed. A read filter that
|
||||
* loses its value returns the whole zone with `success: true` — which a
|
||||
* downstream `delete_dns_record` then fans out over — so filters keep the ids
|
||||
* shipped workflows already hold. A write control that loses its value just
|
||||
* omits the field from a PATCH, so the new id goes there.
|
||||
*/
|
||||
describe('the ids shipped workflows already store are still live', () => {
|
||||
function operationsFor(id: string): string[] {
|
||||
return CloudflareBlock.subBlocks.flatMap((subBlock) => {
|
||||
if (subBlock.id !== id) return []
|
||||
const condition = subBlock.condition
|
||||
if (!condition || typeof condition !== 'object' || !('field' in condition)) return []
|
||||
if (condition.field !== 'operation') return []
|
||||
const value = condition.value
|
||||
return Array.isArray(value) ? value.map(String) : [String(value)]
|
||||
})
|
||||
}
|
||||
|
||||
it.each([
|
||||
['list_dns_records', 'type'],
|
||||
['list_dns_records', 'name'],
|
||||
['list_dns_records', 'content'],
|
||||
['list_dns_records', 'proxied'],
|
||||
['list_dns_records', 'search'],
|
||||
['list_zones', 'name'],
|
||||
['list_zones', 'status'],
|
||||
['purge_cache', 'tags'],
|
||||
])('%s still reads its %s filter from the id it shipped with', (operation, id) => {
|
||||
expect(operationsFor(id)).toContain(operation)
|
||||
})
|
||||
|
||||
it('still passes each of those filters through to the tool', () => {
|
||||
const records = mapFor('list_dns_records', {
|
||||
zoneId: 'zone1',
|
||||
type: 'A',
|
||||
name: 'www.example.com',
|
||||
content: '203.0.113.10',
|
||||
proxied: 'true',
|
||||
search: 'legacy',
|
||||
})
|
||||
expect(records.type).toBe('A')
|
||||
expect(records.name).toBe('www.example.com')
|
||||
expect(records.content).toBe('203.0.113.10')
|
||||
expect(records.proxied).toBe(true)
|
||||
expect(records.search).toBe('legacy')
|
||||
|
||||
expect(mapFor('list_zones', { name: 'example.com', status: 'active' })).toMatchObject({
|
||||
name: 'example.com',
|
||||
status: 'active',
|
||||
})
|
||||
expect(mapFor('purge_cache', { zoneId: 'z1', tags: 'a,b' }).tags).toBe('a,b')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the rule enable switch is split between creating and updating', () => {
|
||||
it('never carries a create-time enabled onto a rule update', () => {
|
||||
// `enabled` is advanced, so it serializes on stored value alone, before its
|
||||
// condition runs. Shared, a `false` chosen while drafting a new rule would
|
||||
// disable a live WAF or rate limiting rule on a later update.
|
||||
for (const operation of ['update_ruleset_rule', 'update_rate_limit_rule']) {
|
||||
const mapped = mapFor(operation, {
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
enabled: 'false',
|
||||
})
|
||||
expect(mapped.enabled, `${operation} took a create-time enabled`).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('sends the update control when the caller sets it', () => {
|
||||
expect(
|
||||
mapFor('update_ruleset_rule', {
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
updateRuleEnabled: 'false',
|
||||
}).enabled
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('still sends the create control on the create operations', () => {
|
||||
expect(
|
||||
mapFor('create_ruleset_rule', { zoneId: 'z1', rulesetId: 'rs1', enabled: 'false' }).enabled
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a DNS record rename cannot be inherited from another operation', () => {
|
||||
it('ignores a name typed under any other operation', () => {
|
||||
// `name` is shared by zone, Access application, policy, and service token
|
||||
// creation. The update control is advanced, so a shared id let any of those
|
||||
// reach the PATCH and rename the live record.
|
||||
expect(
|
||||
mapFor('update_dns_record', { zoneId: 'z1', recordId: 'rec1', name: 'ci-pipeline' }).name
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('renames only when the record-name control is set', () => {
|
||||
expect(
|
||||
mapFor('update_dns_record', {
|
||||
zoneId: 'z1',
|
||||
recordId: 'rec1',
|
||||
updateRecordName: 'www.example.com',
|
||||
}).name
|
||||
).toBe('www.example.com')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Access application types the API can actually build', () => {
|
||||
const appTypeOptions = (id: string) => {
|
||||
const subBlock = CloudflareBlock.subBlocks.find((sub) => sub.id === id)
|
||||
const options = subBlock?.options
|
||||
return (Array.isArray(options) ? options : []).map((option) =>
|
||||
typeof option === 'string' ? option : ((option as { id?: string }).id ?? '')
|
||||
)
|
||||
}
|
||||
|
||||
it('drops dash_sso, which has no request variant at all', () => {
|
||||
expect(appTypeOptions('appType')).not.toContain('dash_sso')
|
||||
expect(appTypeOptions('updateAppType')).not.toContain('dash_sso')
|
||||
})
|
||||
|
||||
it('requires a domain exactly for the types whose request schema demands one', () => {
|
||||
const domain = CloudflareBlock.subBlocks.find((sub) => sub.id === 'domain')
|
||||
const required = domain?.required
|
||||
expect(typeof required).toBe('function')
|
||||
const resolve = required as (values?: Record<string, unknown>) => {
|
||||
field: string
|
||||
value: string | number | boolean | Array<string | number | boolean>
|
||||
}
|
||||
|
||||
const onCreate = resolve({ operation: 'create_access_application' })
|
||||
expect(onCreate.field).toBe('appType')
|
||||
expect(onCreate.value).toEqual(['self_hosted', 'ssh', 'vnc', 'rdp'])
|
||||
|
||||
const onUpdate = resolve({ operation: 'update_access_application' })
|
||||
expect(onUpdate.field).toBe('updateAppType')
|
||||
expect(onUpdate.value).toEqual(['self_hosted', 'ssh', 'vnc', 'rdp'])
|
||||
})
|
||||
|
||||
it('carries the fields saas, infrastructure, and rdp applications cannot be created without', () => {
|
||||
for (const tool of [
|
||||
cloudflareTools.cloudflareCreateAccessApplicationTool,
|
||||
cloudflareTools.cloudflareUpdateAccessApplicationTool,
|
||||
]) {
|
||||
const body = tool.request.body?.({
|
||||
accountId: 'acct1',
|
||||
appId: 'app1',
|
||||
apiKey,
|
||||
type: 'saas',
|
||||
saasApp: '{"auth_type":"saml"}',
|
||||
targetCriteria: '[{"port":22,"protocol":"SSH"}]',
|
||||
} as never) as Record<string, unknown>
|
||||
|
||||
expect(body.saas_app).toEqual({ auth_type: 'saml' })
|
||||
expect(body.target_criteria).toEqual([{ port: 22, protocol: 'SSH' }])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the ruleset kind offered matches the endpoint', () => {
|
||||
it('does not offer root, which only exists at the account level', () => {
|
||||
const kind = CloudflareBlock.subBlocks.find((sub) => sub.id === 'kind')
|
||||
const options = (Array.isArray(kind?.options) ? kind.options : []).map(
|
||||
(option) => (option as { id?: string }).id ?? ''
|
||||
)
|
||||
|
||||
expect(options).not.toContain('root')
|
||||
expect(options).toContain('zone')
|
||||
})
|
||||
})
|
||||
|
||||
describe('an update that would tear down the rule it edits is refused', () => {
|
||||
const updateRule = cloudflareTools.cloudflareUpdateRulesetRuleTool
|
||||
|
||||
it('refuses an execute rule with no action parameters', () => {
|
||||
// PATCH replaces the rule, so omitting action_parameters resets it to {} and
|
||||
// unbinds the managed ruleset the rule deploys, plus every override under it.
|
||||
expect(() =>
|
||||
updateRule.request.body?.({
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
apiKey,
|
||||
action: 'execute',
|
||||
expression: 'true',
|
||||
} as never)
|
||||
).toThrow(/Action Parameters is required/)
|
||||
})
|
||||
|
||||
/**
|
||||
* An explicit `{}` is the same payload Cloudflare's schema default produces, so
|
||||
* it does the same damage as omitting the field. Checking presence rather than
|
||||
* emptiness let it through the guard.
|
||||
*/
|
||||
it('refuses an execute rule whose action parameters are an empty object', () => {
|
||||
expect(() =>
|
||||
updateRule.request.body?.({
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
apiKey,
|
||||
action: 'execute',
|
||||
expression: 'true',
|
||||
actionParameters: '{}',
|
||||
} as never)
|
||||
).toThrow(/Action Parameters is required/)
|
||||
})
|
||||
|
||||
it('leaves an empty action parameters object alone on a non-execute action', () => {
|
||||
const body = updateRule.request.body?.({
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
apiKey,
|
||||
action: 'block',
|
||||
expression: 'true',
|
||||
actionParameters: '{}',
|
||||
} as never) as Record<string, unknown>
|
||||
|
||||
expect(body.action_parameters).toEqual({})
|
||||
})
|
||||
|
||||
it('accepts an execute rule that resends its action parameters', () => {
|
||||
const body = updateRule.request.body?.({
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
apiKey,
|
||||
action: 'execute',
|
||||
expression: 'true',
|
||||
actionParameters: '{"id":"managed-1"}',
|
||||
} as never) as Record<string, unknown>
|
||||
|
||||
expect(body.action_parameters).toEqual({ id: 'managed-1' })
|
||||
})
|
||||
|
||||
it('leaves non-execute actions alone', () => {
|
||||
expect(() =>
|
||||
updateRule.request.body?.({
|
||||
zoneId: 'z1',
|
||||
rulesetId: 'rs1',
|
||||
ruleId: 'r1',
|
||||
apiKey,
|
||||
action: 'block',
|
||||
expression: 'true',
|
||||
} as never)
|
||||
).not.toThrow()
|
||||
})
|
||||
|
||||
it('warns in both descriptions that omission resets the field', () => {
|
||||
expect(updateRule.params.actionParameters.description).toMatch(/resets action_parameters/)
|
||||
expect(updateRule.params.ref.description).toMatch(/omitting it resets/)
|
||||
})
|
||||
|
||||
it('requires action parameters in the block whenever the action is execute', () => {
|
||||
const actionParameters = CloudflareBlock.subBlocks.find((sub) => sub.id === 'actionParameters')
|
||||
expect(actionParameters?.required).toEqual({ field: 'action', value: 'execute' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('optional and per-API pagination params', () => {
|
||||
it('does not force a metrics list the DNS analytics API treats as optional', () => {
|
||||
expect(cloudflareTools.cloudflareDnsAnalyticsTool.params.metrics.required).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the R2 and ruleset cursors apart', () => {
|
||||
// R2 answers with result_info.cursor and the Rulesets API with
|
||||
// result_info.cursors.after, so a cursor carried across the two 400s.
|
||||
expect(
|
||||
mapFor('list_r2_buckets', { accountId: 'a1', rulesetCursor: 'ruleset-1' }).cursor
|
||||
).toBeUndefined()
|
||||
expect(mapFor('list_rulesets', { zoneId: 'z1', r2Cursor: 'r2-1' }).cursor).toBeUndefined()
|
||||
expect(mapFor('list_r2_buckets', { accountId: 'a1', r2Cursor: 'r2-1' }).cursor).toBe('r2-1')
|
||||
expect(mapFor('list_rulesets', { zoneId: 'z1', rulesetCursor: 'ruleset-1' }).cursor).toBe(
|
||||
'ruleset-1'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
mapAccessApplication,
|
||||
parseCsvParam,
|
||||
parseJsonArrayParam,
|
||||
parseJsonObjectParam,
|
||||
} from '@/tools/cloudflare/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
@@ -34,14 +35,14 @@ export const createAccessApplicationTool: ToolConfig<
|
||||
required: true,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, dash_sso, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint',
|
||||
'Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint. dash_sso has no request variant and cannot be created through the API',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'The primary hostname and path secured by Access, e.g. internal.example.com or example.com/admin. Required for the self_hosted, ssh, vnc, rdp, and bookmark types; the saas, app_launcher, warp, biso, dash_sso, infrastructure, mcp, mcp_portal, and proxy_endpoint types do not accept it',
|
||||
'The primary hostname and path secured by Access, e.g. internal.example.com or example.com/admin. Required for the self_hosted, ssh, vnc, and rdp types; optional for bookmark and mcp_portal; read-only for app_launcher, warp, biso, and proxy_endpoint; and absent from the saas, infrastructure, and mcp variants',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
@@ -105,6 +106,20 @@ export const createAccessApplicationTool: ToolConfig<
|
||||
description:
|
||||
'JSON array of policies to attach. Entries may be reusable policy IDs or inline policy objects, e.g. ["<POLICY_ID>"]',
|
||||
},
|
||||
saasApp: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'JSON SaaS configuration, required for the saas type and rejected on every other type. SAML, e.g. {"auth_type":"saml","consumer_service_url":"https://example.com/acs","sp_entity_id":"https://example.com"}; OIDC, e.g. {"auth_type":"oidc","client_id":"...","redirect_uris":["https://example.com/callback"]}',
|
||||
},
|
||||
targetCriteria: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'JSON array of infrastructure target criteria, required for the infrastructure and rdp types and rejected on every other type, e.g. [{"port":22,"protocol":"SSH","target_attributes":{"hostname":["production"]}}]',
|
||||
},
|
||||
apiKey: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
@@ -121,10 +136,11 @@ export const createAccessApplicationTool: ToolConfig<
|
||||
body: (params) => {
|
||||
const body: Record<string, unknown> = { type: params.type }
|
||||
/**
|
||||
* `domain` exists only on the self_hosted, ssh, vnc, rdp, and bookmark
|
||||
* request variants; the saas, app_launcher, warp, biso, dash_sso,
|
||||
* infrastructure, mcp, mcp_portal, and proxy_endpoint variants have no
|
||||
* such field, so sending a blank one makes those app types unbuildable.
|
||||
* `domain` is writable only on the self_hosted, ssh, vnc, rdp, bookmark,
|
||||
* and mcp_portal request variants — required on the first four — read-only
|
||||
* on app_launcher, warp, biso, and proxy_endpoint, and absent from saas,
|
||||
* infrastructure, and mcp. Sending a blank one makes those types
|
||||
* unbuildable, so it is only forwarded when set.
|
||||
*/
|
||||
if (params.domain) body.domain = params.domain
|
||||
if (params.name) body.name = params.name
|
||||
@@ -149,6 +165,12 @@ export const createAccessApplicationTool: ToolConfig<
|
||||
const policies = parseJsonArrayParam(params.policies, 'Policies')
|
||||
if (policies) body.policies = policies
|
||||
|
||||
const saasApp = parseJsonObjectParam(params.saasApp, 'SaaS Application')
|
||||
if (saasApp) body.saas_app = saasApp
|
||||
|
||||
const targetCriteria = parseJsonArrayParam(params.targetCriteria, 'Target Criteria')
|
||||
if (targetCriteria) body.target_criteria = targetCriteria
|
||||
|
||||
return body
|
||||
},
|
||||
},
|
||||
|
||||
@@ -77,7 +77,8 @@ export const createAccessPolicyTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'How long a session granted by this policy stays valid, e.g. 24h',
|
||||
description:
|
||||
'How long a session granted by this policy stays valid, e.g. 24h. Leave it unset on a policy attached to an infrastructure-typed application — Cloudflare rejects those with error 12130',
|
||||
},
|
||||
approvalRequired: {
|
||||
type: 'boolean',
|
||||
|
||||
@@ -46,7 +46,7 @@ export const createRulesetTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Ruleset kind: zone, custom, managed, or root. Use zone to create a phase entry point ruleset. Defaults to zone',
|
||||
'Ruleset kind: zone or custom. Use zone to create a phase entry point ruleset and custom for a ruleset an execute rule deploys. Defaults to zone. "root" is the account-level phase entry point and "managed" is Cloudflare-owned, so neither can be created on this zone-scoped endpoint',
|
||||
},
|
||||
description: {
|
||||
type: 'string',
|
||||
|
||||
@@ -38,10 +38,10 @@ export const dnsAnalyticsTool: ToolConfig<
|
||||
},
|
||||
metrics: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Comma-separated metrics to retrieve (e.g., "queryCount,uncachedCount,staleCount,responseTimeAvg,responseTimeMedian,responseTime90th,responseTime99th")',
|
||||
'Comma-separated metrics to retrieve (e.g., "queryCount,uncachedCount,staleCount,responseTimeAvg,responseTimeMedian,responseTime90th,responseTime99th"). Optional — Cloudflare returns its default metric set when it is omitted',
|
||||
},
|
||||
dimensions: {
|
||||
type: 'string',
|
||||
|
||||
@@ -971,6 +971,8 @@ export interface CloudflareCreateAccessApplicationParams extends CloudflareBaseP
|
||||
logoUrl?: string
|
||||
tags?: string
|
||||
policies?: string
|
||||
saasApp?: string
|
||||
targetCriteria?: string
|
||||
}
|
||||
|
||||
export interface CloudflareUpdateAccessApplicationParams
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
mapAccessApplication,
|
||||
parseCsvParam,
|
||||
parseJsonArrayParam,
|
||||
parseJsonObjectParam,
|
||||
} from '@/tools/cloudflare/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
@@ -40,14 +41,14 @@ export const updateAccessApplicationTool: ToolConfig<
|
||||
required: true,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, dash_sso, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint',
|
||||
'Application type: self_hosted, saas, ssh, vnc, app_launcher, warp, biso, bookmark, infrastructure, rdp, mcp, mcp_portal, or proxy_endpoint. dash_sso has no request variant and cannot be written through the API',
|
||||
},
|
||||
domain: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'The primary hostname and path secured by Access. Required for the self_hosted, ssh, vnc, rdp, and bookmark types; the saas, app_launcher, warp, biso, dash_sso, infrastructure, mcp, mcp_portal, and proxy_endpoint types do not accept it',
|
||||
'The primary hostname and path secured by Access. Required for the self_hosted, ssh, vnc, and rdp types; optional for bookmark and mcp_portal; read-only for app_launcher, warp, biso, and proxy_endpoint; and absent from the saas, infrastructure, and mcp variants',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
@@ -103,6 +104,20 @@ export const updateAccessApplicationTool: ToolConfig<
|
||||
visibility: 'user-or-llm',
|
||||
description: 'Comma-separated tag names categorizing the application',
|
||||
},
|
||||
saasApp: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'JSON SaaS configuration, required for the saas type and rejected on every other type. SAML, e.g. {"auth_type":"saml","consumer_service_url":"https://example.com/acs","sp_entity_id":"https://example.com"}; OIDC, e.g. {"auth_type":"oidc","client_id":"...","redirect_uris":["https://example.com/callback"]}',
|
||||
},
|
||||
targetCriteria: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'JSON array of infrastructure target criteria, required for the infrastructure and rdp types and rejected on every other type, e.g. [{"port":22,"protocol":"SSH","target_attributes":{"hostname":["production"]}}]',
|
||||
},
|
||||
policies: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
@@ -126,10 +141,11 @@ export const updateAccessApplicationTool: ToolConfig<
|
||||
body: (params) => {
|
||||
const body: Record<string, unknown> = { type: params.type }
|
||||
/**
|
||||
* `domain` exists only on the self_hosted, ssh, vnc, rdp, and bookmark
|
||||
* request variants; the saas, app_launcher, warp, biso, dash_sso,
|
||||
* infrastructure, mcp, mcp_portal, and proxy_endpoint variants have no
|
||||
* such field, so sending a blank one makes those app types unbuildable.
|
||||
* `domain` is writable only on the self_hosted, ssh, vnc, rdp, bookmark,
|
||||
* and mcp_portal request variants — required on the first four — read-only
|
||||
* on app_launcher, warp, biso, and proxy_endpoint, and absent from saas,
|
||||
* infrastructure, and mcp. Sending a blank one makes those types
|
||||
* unbuildable, so it is only forwarded when set.
|
||||
*/
|
||||
if (params.domain) body.domain = params.domain
|
||||
if (params.name) body.name = params.name
|
||||
@@ -154,6 +170,12 @@ export const updateAccessApplicationTool: ToolConfig<
|
||||
const policies = parseJsonArrayParam(params.policies, 'Policies')
|
||||
if (policies) body.policies = policies
|
||||
|
||||
const saasApp = parseJsonObjectParam(params.saasApp, 'SaaS Application')
|
||||
if (saasApp) body.saas_app = saasApp
|
||||
|
||||
const targetCriteria = parseJsonArrayParam(params.targetCriteria, 'Target Criteria')
|
||||
if (targetCriteria) body.target_criteria = targetCriteria
|
||||
|
||||
return body
|
||||
},
|
||||
},
|
||||
|
||||
@@ -82,7 +82,8 @@ export const updateAccessPolicyTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'How long a session granted by this policy stays valid, e.g. 24h',
|
||||
description:
|
||||
'How long a session granted by this policy stays valid, e.g. 24h. Leave it unset on a policy attached to an infrastructure-typed application — Cloudflare rejects those with error 12130',
|
||||
},
|
||||
approvalRequired: {
|
||||
type: 'boolean',
|
||||
|
||||
@@ -70,14 +70,15 @@ export const updateRulesetRuleTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'Reference tag that stays stable across rule updates',
|
||||
description:
|
||||
'Reference tag that stays stable across rule updates. Because the update replaces the rule, omitting it resets the tag to the rule ID and breaks anything matching on the old value',
|
||||
},
|
||||
actionParameters: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'JSON object of action-specific parameters, e.g. {"id":"<MANAGED_RULESET_ID>","overrides":{"rules":[{"id":"<RULE_ID>","action":"log","enabled":true,"score_threshold":40}]}}',
|
||||
'JSON object of action-specific parameters, e.g. {"id":"<MANAGED_RULESET_ID>","overrides":{"rules":[{"id":"<RULE_ID>","action":"log","enabled":true,"score_threshold":40}]}}. Required on an execute rule and must be sent on every update: the endpoint replaces the rule, so omitting it resets action_parameters to {} — which unbinds the managed ruleset the rule deploys and every override under it',
|
||||
},
|
||||
ratelimit: {
|
||||
type: 'string',
|
||||
@@ -116,6 +117,19 @@ export const updateRulesetRuleTool: ToolConfig<
|
||||
if (params.ref) body.ref = params.ref
|
||||
|
||||
const actionParameters = parseJsonObjectParam(params.actionParameters, 'Action Parameters')
|
||||
/**
|
||||
* PATCH replaces the rule, so action_parameters that is omitted falls back
|
||||
* to the schema default of {}. On an execute rule that drops the managed
|
||||
* ruleset ID, unbinding the WAF managed ruleset and every override under
|
||||
* it. An explicit `{}` is the same payload by a different route and does
|
||||
* the same damage, so emptiness is what is checked rather than presence.
|
||||
* Refuse rather than silently tear the rule down.
|
||||
*/
|
||||
if (params.action === 'execute' && Object.keys(actionParameters ?? {}).length === 0) {
|
||||
throw new Error(
|
||||
'Action Parameters is required when the action is "execute". This endpoint replaces the rule, so sending it empty or omitting it would reset action_parameters and unbind the managed ruleset. Read the rule with "Get Ruleset" and resend its action_parameters.'
|
||||
)
|
||||
}
|
||||
if (actionParameters) body.action_parameters = actionParameters
|
||||
|
||||
const ratelimit = parseJsonObjectParam(params.ratelimit, 'Rate Limiting Configuration')
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { crowdstrikeQueryBodySchema } from '@/lib/api/contracts/tools/crowdstrike'
|
||||
import { CrowdStrikeBlock } from '@/blocks/blocks/crowdstrike'
|
||||
import { crowdstrikeExecuteRtrCommandTool } from '@/tools/crowdstrike/execute_rtr_command'
|
||||
import { crowdstrikeGetSensorAggregatesTool } from '@/tools/crowdstrike/get_sensor_aggregates'
|
||||
import { crowdstrikeGetSensorDetailsTool } from '@/tools/crowdstrike/get_sensor_details'
|
||||
import { crowdstrikeQueryAlertsTool } from '@/tools/crowdstrike/query_alerts'
|
||||
import { crowdstrikeQuerySensorsTool } from '@/tools/crowdstrike/query_sensors'
|
||||
import type {
|
||||
CrowdStrikeGetSensorAggregatesResponse,
|
||||
CrowdStrikeGetSensorDetailsResponse,
|
||||
CrowdStrikeQuerySensorsResponse,
|
||||
} from '@/tools/crowdstrike/types'
|
||||
import { crowdstrikeUpdateIndicatorsTool } from '@/tools/crowdstrike/update_indicators'
|
||||
|
||||
const credentials = {
|
||||
clientId: 'client-id',
|
||||
clientSecret: 'client-secret',
|
||||
cloud: 'us-1' as const,
|
||||
}
|
||||
|
||||
function issueMessages(result: ReturnType<typeof crowdstrikeQueryBodySchema.safeParse>) {
|
||||
return result.success ? [] : result.error.issues.map((issue) => issue.message)
|
||||
}
|
||||
|
||||
describe('CrowdStrike indicator batch cap', () => {
|
||||
const oversizedIndicators = {
|
||||
crowdstrike_create_indicators: Array.from({ length: 201 }, (_, index) => ({
|
||||
type: 'sha256',
|
||||
value: `value-${index}`,
|
||||
applied_globally: true,
|
||||
})),
|
||||
crowdstrike_update_indicators: Array.from({ length: 201 }, (_, index) => ({
|
||||
id: `ioc-${index}`,
|
||||
action: 'prevent',
|
||||
})),
|
||||
} as const
|
||||
|
||||
it('attributes the 200-indicator cap to Sim rather than to CrowdStrike', () => {
|
||||
for (const operation of [
|
||||
'crowdstrike_create_indicators',
|
||||
'crowdstrike_update_indicators',
|
||||
] as const) {
|
||||
const messages = issueMessages(
|
||||
crowdstrikeQueryBodySchema.safeParse({
|
||||
...credentials,
|
||||
operation,
|
||||
indicators: oversizedIndicators[operation],
|
||||
})
|
||||
)
|
||||
|
||||
expect(messages).toContain(
|
||||
'Sim caps this request at 200 indicators; CrowdStrike publishes no limit for this endpoint'
|
||||
)
|
||||
expect(messages.join('\n')).not.toMatch(/CrowdStrike accepts at most 200 indicators/)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('CrowdStrike update-indicators guidance', () => {
|
||||
it('states the omitted-field hazard as observed rather than as documented behavior', () => {
|
||||
const { description } = crowdstrikeUpdateIndicatorsTool
|
||||
expect(description).not.toMatch(/blanks out any field you omit/)
|
||||
expect(description).toMatch(/omitted fields may be cleared/)
|
||||
expect(description).toMatch(/resend its full field set/)
|
||||
|
||||
const indicatorsParam = crowdstrikeUpdateIndicatorsTool.params.indicators
|
||||
expect(indicatorsParam.description).not.toMatch(/blanks out any updatable field/)
|
||||
expect(indicatorsParam.description).toMatch(/may be cleared/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('CrowdStrike alerts API lineage', () => {
|
||||
it('calls the Detects API decommissioned, not deprecated', () => {
|
||||
expect(crowdstrikeQueryAlertsTool.description).not.toMatch(/deprecated Detects API/)
|
||||
expect(crowdstrikeQueryAlertsTool.description).toMatch(/decommissioned on September 30, 2025/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('CrowdStrike sensor outputs', () => {
|
||||
it('declares pagination on every sensor-listing tool', () => {
|
||||
expect(crowdstrikeQuerySensorsTool.outputs.pagination).toBeDefined()
|
||||
expect(crowdstrikeGetSensorDetailsTool.outputs.pagination).toBeDefined()
|
||||
})
|
||||
|
||||
it('declares errors on every sensor tool', () => {
|
||||
expect(crowdstrikeQuerySensorsTool.outputs.errors).toBeDefined()
|
||||
expect(crowdstrikeGetSensorDetailsTool.outputs.errors).toBeDefined()
|
||||
expect(crowdstrikeGetSensorAggregatesTool.outputs.errors).toBeDefined()
|
||||
})
|
||||
|
||||
/**
|
||||
* The route emits `errors` on all three sensor envelopes and the contract requires
|
||||
* it, so the response interfaces must carry it too. Interfaces are erased at
|
||||
* runtime, so these literals are the check: dropping `errors` from any of the
|
||||
* three makes them a compile error (TS2353) in the editor and in any `tsc` run
|
||||
* that includes test files. `apps/sim/tsconfig.json` excludes test files, so
|
||||
* `bun run type-check` alone will not catch it.
|
||||
*/
|
||||
it('types errors on every sensor response interface', () => {
|
||||
const querySensors: CrowdStrikeQuerySensorsResponse['output'] = {
|
||||
count: 0,
|
||||
errors: [],
|
||||
pagination: null,
|
||||
sensors: [],
|
||||
}
|
||||
const sensorDetails: CrowdStrikeGetSensorDetailsResponse['output'] = {
|
||||
count: 0,
|
||||
errors: [],
|
||||
pagination: null,
|
||||
sensors: [],
|
||||
}
|
||||
const sensorAggregates: CrowdStrikeGetSensorAggregatesResponse['output'] = {
|
||||
aggregates: [],
|
||||
count: 0,
|
||||
errors: [],
|
||||
}
|
||||
|
||||
expect(querySensors.errors).toEqual([])
|
||||
expect(sensorDetails.errors).toEqual([])
|
||||
expect(sensorAggregates.errors).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('CrowdStrike RTR read-only base commands', () => {
|
||||
function parseBaseCommand(baseCommand: string) {
|
||||
return crowdstrikeQueryBodySchema.safeParse({
|
||||
...credentials,
|
||||
operation: 'crowdstrike_execute_rtr_command',
|
||||
sessionId: 'session-1',
|
||||
baseCommand,
|
||||
commandString: `${baseCommand} `,
|
||||
})
|
||||
}
|
||||
|
||||
it('accepts the non-Windows network and session triage commands', () => {
|
||||
expect(parseBaseCommand('ifconfig').success).toBe(true)
|
||||
expect(parseBaseCommand('users').success).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the read-tier commands PSFalcon and Caracara document', () => {
|
||||
for (const baseCommand of ['csrutil', 'reg', 'eventlog']) {
|
||||
expect(parseBaseCommand(baseCommand).success).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('still rejects a write-tier base command', () => {
|
||||
expect(parseBaseCommand('rm').success).toBe(false)
|
||||
})
|
||||
|
||||
it('documents that only reg query is read-tier', () => {
|
||||
expect(crowdstrikeExecuteRtrCommandTool.params.baseCommand.description).toMatch(
|
||||
/only reg query is read-tier/
|
||||
)
|
||||
})
|
||||
|
||||
it('offers ifconfig and users in the block dropdown', () => {
|
||||
const baseCommandBlock = CrowdStrikeBlock.subBlocks.find((block) => block.id === 'baseCommand')
|
||||
const optionIds = (baseCommandBlock?.options as { id: string }[] | undefined)?.map(
|
||||
(option) => option.id
|
||||
)
|
||||
expect(optionIds).toContain('ifconfig')
|
||||
expect(optionIds).toContain('users')
|
||||
})
|
||||
})
|
||||
|
||||
describe('CrowdStrike sort placeholders', () => {
|
||||
it('shows the dot form for the collections that document it and the pipe form elsewhere', () => {
|
||||
const sortBlocks = CrowdStrikeBlock.subBlocks.filter((block) => block.id === 'sort')
|
||||
expect(sortBlocks).toHaveLength(2)
|
||||
|
||||
for (const operation of ['crowdstrike_query_host_groups', 'crowdstrike_query_sensors']) {
|
||||
const match = sortBlocks.find((block) =>
|
||||
(block.condition as { value: string[] }).value.includes(operation)
|
||||
)
|
||||
expect(match?.placeholder).toBe('name.asc')
|
||||
}
|
||||
|
||||
for (const operation of [
|
||||
'crowdstrike_query_alerts',
|
||||
'crowdstrike_query_indicators',
|
||||
'crowdstrike_query_vulnerabilities',
|
||||
'crowdstrike_query_cases',
|
||||
]) {
|
||||
const match = sortBlocks.find((block) =>
|
||||
(block.condition as { value: string[] }).value.includes(operation)
|
||||
)
|
||||
expect(match?.placeholder).toBe('created_timestamp|desc')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -11,7 +11,7 @@ export const crowdstrikeExecuteRtrCommandTool: ToolConfig<
|
||||
id: 'crowdstrike_execute_rtr_command',
|
||||
name: 'CrowdStrike Execute RTR Command',
|
||||
description:
|
||||
'Run a read-only Real Time Response command in an open CrowdStrike Falcon session (POST /real-time-response/entities/command/v1). baseCommand names the family only (cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ipconfig, ls, mount, netstat, ps, reg); subcommands go in commandString. Host-modifying commands need the Active Responder or Admin endpoints. Requires the "Real time response: Read" API scope.',
|
||||
'Run a read-only Real Time Response command in an open CrowdStrike Falcon session (POST /real-time-response/entities/command/v1). baseCommand names the family only (cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ifconfig, ipconfig, ls, mount, netstat, ps, reg, users); subcommands go in commandString. Host-modifying commands need the Active Responder or Admin endpoints. Requires the "Real time response: Read" API scope.',
|
||||
version: '1.0.0',
|
||||
|
||||
params: {
|
||||
@@ -44,7 +44,7 @@ export const crowdstrikeExecuteRtrCommandTool: ToolConfig<
|
||||
required: true,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Read-only RTR base command family, one of: cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ipconfig, ls, mount, netstat, ps, reg. Subcommands belong in commandString, not here.',
|
||||
'Read-only RTR base command family, one of: cat, cd, clear, csrutil, env, eventlog, filehash, getsid, help, history, ifconfig, ipconfig, ls, mount, netstat, ps, reg, users. Subcommands belong in commandString, not here — and only reg query is read-tier, since reg set and reg delete are Active Responder commands.',
|
||||
},
|
||||
commandString: {
|
||||
type: 'string',
|
||||
|
||||
@@ -179,6 +179,16 @@ export const crowdstrikeGetSensorDetailsTool: ToolConfig<
|
||||
type: 'number',
|
||||
description: 'Number of sensors returned',
|
||||
},
|
||||
pagination: {
|
||||
type: 'json',
|
||||
description: 'Pagination metadata (limit, offset, total)',
|
||||
optional: true,
|
||||
properties: {
|
||||
limit: { type: 'number', description: 'Page size used for the query', optional: true },
|
||||
offset: { type: 'number', description: 'Offset returned by CrowdStrike', optional: true },
|
||||
total: { type: 'number', description: 'Total records available', optional: true },
|
||||
},
|
||||
},
|
||||
errors: {
|
||||
type: 'array',
|
||||
description: 'Errors CrowdStrike returned alongside a partially successful response',
|
||||
|
||||
@@ -11,7 +11,7 @@ export const crowdstrikeQueryAlertsTool: ToolConfig<
|
||||
id: 'crowdstrike_query_alerts',
|
||||
name: 'CrowdStrike Query Alerts',
|
||||
description:
|
||||
'Search CrowdStrike Falcon alerts with a Falcon Query Language filter and return their composite IDs. Uses the current Alerts API (GET /alerts/queries/alerts/v2), which supersedes the deprecated Detects API. Requires the "Alerts: Read" API scope.',
|
||||
'Search CrowdStrike Falcon alerts with a Falcon Query Language filter and return their composite IDs. Uses the current Alerts API (GET /alerts/queries/alerts/v2), which replaced the Detects API decommissioned on September 30, 2025. Requires the "Alerts: Read" API scope.',
|
||||
version: '1.0.0',
|
||||
|
||||
params: {
|
||||
|
||||
@@ -101,6 +101,7 @@ interface CrowdStrikeSensor {
|
||||
export interface CrowdStrikeQuerySensorsResponse extends ToolResponse {
|
||||
output: {
|
||||
count: number
|
||||
errors: CrowdStrikeApiError[]
|
||||
pagination: CrowdStrikePagination | null
|
||||
sensors: CrowdStrikeSensor[]
|
||||
}
|
||||
@@ -109,6 +110,7 @@ export interface CrowdStrikeQuerySensorsResponse extends ToolResponse {
|
||||
export interface CrowdStrikeGetSensorDetailsResponse extends ToolResponse {
|
||||
output: {
|
||||
count: number
|
||||
errors: CrowdStrikeApiError[]
|
||||
pagination: CrowdStrikePagination | null
|
||||
sensors: CrowdStrikeSensor[]
|
||||
}
|
||||
@@ -138,6 +140,7 @@ export interface CrowdStrikeGetSensorAggregatesResponse extends ToolResponse {
|
||||
output: {
|
||||
aggregates: CrowdStrikeSensorAggregateResult[]
|
||||
count: number
|
||||
errors: CrowdStrikeApiError[]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export const crowdstrikeUpdateIndicatorsTool: ToolConfig<
|
||||
id: 'crowdstrike_update_indicators',
|
||||
name: 'CrowdStrike Update Indicators',
|
||||
description:
|
||||
'Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/entities/indicators/v1). DESTRUCTIVE: CrowdStrike blanks out any field you omit, so read each indicator with crowdstrike_get_indicator_details first and resend its full field set with your edits applied. Changing action or scope changes prevention behavior fleet-wide. type and value are immutable. Requires the "IOC Management: Write" API scope.',
|
||||
'Update custom CrowdStrike Falcon indicators of compromise by ID (PATCH /iocs/entities/indicators/v1). DESTRUCTIVE: omitted fields may be cleared, so read each indicator with crowdstrike_get_indicator_details first and resend its full field set with your edits applied. Changing action or scope changes prevention behavior fleet-wide. type and value are immutable. Requires the "IOC Management: Write" API scope.',
|
||||
version: '1.0.0',
|
||||
|
||||
params: {
|
||||
@@ -38,7 +38,7 @@ export const crowdstrikeUpdateIndicatorsTool: ToolConfig<
|
||||
required: true,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'JSON array of indicators to update. Each entry requires id, and must also repeat every field it wants to keep: CrowdStrike blanks out any updatable field the entry omits. Updatable fields: action, severity, description, source, tags (array), platforms (array), applied_globally (boolean), host_groups (array), expiration (ISO 8601), mobile_action, metadata ({ filename }). type and value cannot be changed.',
|
||||
'JSON array of indicators to update. Each entry requires id, and should also repeat every field it wants to keep: an updatable field the entry omits may be cleared. Updatable fields: action, severity, description, source, tags (array), platforms (array), applied_globally (boolean), host_groups (array), expiration (ISO 8601), mobile_action, metadata ({ filename }). type and value cannot be changed.',
|
||||
},
|
||||
comment: {
|
||||
type: 'string',
|
||||
|
||||
@@ -38,7 +38,8 @@ export const cancelDowntimeTool: ToolConfig<CancelDowntimeParams, CancelDowntime
|
||||
request: {
|
||||
url: (params) => {
|
||||
const site = params.site || 'datadoghq.com'
|
||||
return `https://api.${site}/api/v2/downtime/${params.downtimeId}`
|
||||
const downtimeId = encodeURIComponent(String(params.downtimeId).trim())
|
||||
return `https://api.${site}/api/v2/downtime/${downtimeId}`
|
||||
},
|
||||
method: 'DELETE',
|
||||
headers: (params) => ({
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cancelDowntimeTool } from '@/tools/datadog/cancel_downtime'
|
||||
import { createDowntimeTool } from '@/tools/datadog/create_downtime'
|
||||
import { createEventTool } from '@/tools/datadog/create_event'
|
||||
import { createMonitorTool } from '@/tools/datadog/create_monitor'
|
||||
import { getIncidentTool } from '@/tools/datadog/get_incident'
|
||||
import { getMonitorTool } from '@/tools/datadog/get_monitor'
|
||||
import { listDashboardsTool } from '@/tools/datadog/list_dashboards'
|
||||
import { listDowntimesTool } from '@/tools/datadog/list_downtimes'
|
||||
import { listIncidentsTool } from '@/tools/datadog/list_incidents'
|
||||
import { listMonitorsTool } from '@/tools/datadog/list_monitors'
|
||||
import { muteMonitorTool } from '@/tools/datadog/mute_monitor'
|
||||
import { queryLogsTool } from '@/tools/datadog/query_logs'
|
||||
import { queryTimeseriesTool } from '@/tools/datadog/query_timeseries'
|
||||
@@ -449,6 +453,79 @@ describe('splitCommaList input tolerance', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('path parameter encoding', () => {
|
||||
/** A pasted id often carries surrounding whitespace, which would 404 as `%20123`. */
|
||||
it('trims and encodes the monitor id in get_monitor', () => {
|
||||
const url = callUrl(getMonitorTool, { ...auth, monitorId: ' 12 3 ' } as any)
|
||||
expect(url).toContain('/api/v1/monitor/12%203')
|
||||
expect(url).not.toContain('/monitor/ 12')
|
||||
})
|
||||
|
||||
it('trims and encodes the downtime id in cancel_downtime', () => {
|
||||
const url = callUrl(cancelDowntimeTool, { ...auth, downtimeId: ' a/b ' } as any)
|
||||
expect(url).toContain('/api/v2/downtime/a%2Fb')
|
||||
expect(url).not.toContain('/downtime/ a')
|
||||
})
|
||||
})
|
||||
|
||||
describe('list_downtimes limit description', () => {
|
||||
/**
|
||||
* The Datadog v2 spec declares `default: 30` and `example: 100` but no `maximum`, so the
|
||||
* description must not present 100 as a vendor-enforced ceiling.
|
||||
*/
|
||||
it('does not claim a vendor maximum', () => {
|
||||
const description = listDowntimesTool.params.limit.description ?? ''
|
||||
expect(description).not.toMatch(/max:\s*100/)
|
||||
expect(description).toMatch(/declares no maximum/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('list_monitors pagination', () => {
|
||||
/**
|
||||
* Datadog returns every monitor when `page` is absent, so both page params have to reach
|
||||
* the request for the page size to have any effect.
|
||||
*/
|
||||
it('sends page and page_size', () => {
|
||||
const url = callUrl(listMonitorsTool, { ...auth, page: 2, pageSize: 50 } as any)
|
||||
expect(url).toContain('page=2')
|
||||
expect(url).toContain('page_size=50')
|
||||
})
|
||||
})
|
||||
|
||||
describe('list_dashboards filters', () => {
|
||||
/** `filter[shared]` and `filter[deleted]` are incompatible, so an off toggle sends nothing. */
|
||||
it('omits both filters when neither is enabled', () => {
|
||||
const url = callUrl(listDashboardsTool, { ...auth, filterShared: false, filterDeleted: false })
|
||||
expect(url).not.toContain('filter%5Bshared%5D')
|
||||
expect(url).not.toContain('filter%5Bdeleted%5D')
|
||||
})
|
||||
|
||||
it('sends only the filter that is enabled', () => {
|
||||
const url = callUrl(listDashboardsTool, { ...auth, filterShared: true, filterDeleted: false })
|
||||
expect(url).toContain('filter%5Bshared%5D=true')
|
||||
expect(url).not.toContain('filter%5Bdeleted%5D')
|
||||
})
|
||||
})
|
||||
|
||||
describe('submit_metrics errors output', () => {
|
||||
/** `errors` is the only signal that Datadog rejected part of an accepted submission. */
|
||||
it('reports errors on the success path', async () => {
|
||||
const result = await submitMetricsTool.transformResponse!(
|
||||
jsonResponse({ errors: ['metric name too long'] })
|
||||
)
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.output.errors).toEqual(['metric name too long'])
|
||||
})
|
||||
|
||||
it('reports errors on the failure path', async () => {
|
||||
const result = await submitMetricsTool.transformResponse!(
|
||||
jsonResponse({ errors: ['bad payload'] }, { status: 400 })
|
||||
)
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.output.errors).toEqual(['bad payload'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('registry surface', () => {
|
||||
it('keeps create_event on api-key-only auth', () => {
|
||||
expect(createEventTool.params.applicationKey).toBeUndefined()
|
||||
|
||||
@@ -56,8 +56,9 @@ export const getMonitorTool: ToolConfig<GetMonitorParams, GetMonitorResponse> =
|
||||
if (params.groupStates) queryParams.set('group_states', params.groupStates)
|
||||
if (params.withDowntimes) queryParams.set('with_downtimes', 'true')
|
||||
|
||||
const monitorId = encodeURIComponent(String(params.monitorId).trim())
|
||||
const queryString = queryParams.toString()
|
||||
return `https://api.${site}/api/v1/monitor/${params.monitorId}${queryString ? `?${queryString}` : ''}`
|
||||
return `https://api.${site}/api/v1/monitor/${monitorId}${queryString ? `?${queryString}` : ''}`
|
||||
},
|
||||
method: 'GET',
|
||||
headers: (params) => ({
|
||||
|
||||
@@ -55,12 +55,14 @@ export const listDashboardsTool: ToolConfig<ListDashboardsParams, ListDashboards
|
||||
},
|
||||
|
||||
request: {
|
||||
/**
|
||||
* Datadog treats `filter[shared]` and `filter[deleted]` as incompatible, so each is sent
|
||||
* only when the caller turned it on rather than sending both as `false`.
|
||||
*/
|
||||
url: (params) => {
|
||||
const queryParams = new URLSearchParams()
|
||||
if (params.filterShared !== undefined)
|
||||
queryParams.set('filter[shared]', String(params.filterShared))
|
||||
if (params.filterDeleted !== undefined)
|
||||
queryParams.set('filter[deleted]', String(params.filterDeleted))
|
||||
if (params.filterShared) queryParams.set('filter[shared]', 'true')
|
||||
if (params.filterDeleted) queryParams.set('filter[deleted]', 'true')
|
||||
if (params.count !== undefined) queryParams.set('count', String(params.count))
|
||||
if (params.start !== undefined) queryParams.set('start', String(params.start))
|
||||
const queryString = queryParams.toString()
|
||||
|
||||
@@ -24,7 +24,8 @@ export const listDowntimesTool: ToolConfig<ListDowntimesParams, ListDowntimesRes
|
||||
type: 'number',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'Number of downtimes to return per page (default: 30, max: 100)',
|
||||
description:
|
||||
'Number of downtimes to return per page. Datadog defaults to 30 and declares no maximum; keep this at 100 or below to stay within the bound Sim recommends.',
|
||||
},
|
||||
offset: {
|
||||
type: 'number',
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const TOOL_DIR = join(import.meta.dirname, '.')
|
||||
|
||||
/**
|
||||
* A backslash-escaped single quote that is not itself escaped. The docs generator parses these
|
||||
* files as *source* rather than importing them, so `department eq \'Sales\'` reaches the
|
||||
* published MDX with its backslashes intact and, in a table cell, truncates the row.
|
||||
* The lookbehind spares the regex-escape idiom `replace(/\\/g, '\\\\')`, where the quote is
|
||||
* preceded by a genuine escaped backslash.
|
||||
*/
|
||||
const ESCAPED_SINGLE_QUOTE = /(?<!\\)\\'/
|
||||
|
||||
describe('microsoft_ad tool sources', () => {
|
||||
const files = readdirSync(TOOL_DIR).filter(
|
||||
(file) => file.endsWith('.ts') && !file.endsWith('.test.ts')
|
||||
)
|
||||
|
||||
it('covers every tool file', () => {
|
||||
expect(files.length).toBeGreaterThan(30)
|
||||
})
|
||||
|
||||
it.each(files)('%s escapes no single quotes', (file) => {
|
||||
const offenders = readFileSync(join(TOOL_DIR, file), 'utf8')
|
||||
.split('\n')
|
||||
.map((line, index) => ({ line, number: index + 1 }))
|
||||
.filter(({ line }) => ESCAPED_SINGLE_QUOTE.test(line))
|
||||
|
||||
expect(offenders).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -42,14 +42,14 @@ export const listConditionalAccessPoliciesTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'OData filter expression. Example: "state eq \'enabled\'".',
|
||||
description: `OData filter expression. Example: "state eq 'enabled'".`,
|
||||
},
|
||||
nextLink: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -42,8 +42,7 @@ export const listDevicesTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'OData filter expression. Example: "accountEnabled eq false" or "operatingSystem eq \'Windows\'".',
|
||||
description: `OData filter expression. Example: "accountEnabled eq false" or "operatingSystem eq 'Windows'".`,
|
||||
},
|
||||
search: {
|
||||
type: 'string',
|
||||
@@ -56,7 +55,7 @@ export const listDevicesTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -49,7 +49,7 @@ export const listDirectoryAuditsTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -44,7 +44,7 @@ export const listGroupMembersTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -50,7 +50,7 @@ export const listGroupsTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -39,15 +39,14 @@ export const listServicePrincipalAppRoleAssignmentsTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'OData filter expression supporting eq and startswith. Example: "principalType eq \'User\'".',
|
||||
description: `OData filter expression supporting eq and startswith. Example: "principalType eq 'User'".`,
|
||||
},
|
||||
nextLink: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -48,8 +48,7 @@ export const listServicePrincipalsTool: ToolConfig<
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'OData filter expression. Example: "servicePrincipalType eq \'Application\'" or "startsWith(displayName, \'Salesforce\')".',
|
||||
description: `OData filter expression. Example: "servicePrincipalType eq 'Application'" or "startsWith(displayName, 'Salesforce')".`,
|
||||
},
|
||||
search: {
|
||||
type: 'string',
|
||||
@@ -62,7 +61,7 @@ export const listServicePrincipalsTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -49,7 +49,7 @@ export const listSignInsTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -53,7 +53,7 @@ export const listUserAppRoleAssignmentsTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { listUserDevicesTool } from '@/tools/microsoft_ad/list_user_devices'
|
||||
|
||||
const buildUrl = listUserDevicesTool.request.url as (params: Record<string, unknown>) => string
|
||||
|
||||
const REGISTERED_NEXT_LINK =
|
||||
'https://graph.microsoft.com/v1.0/users/user-1/registeredDevices?$skiptoken=abc'
|
||||
const OWNED_NEXT_LINK = 'https://graph.microsoft.com/v1.0/users/user-1/ownedDevices?$skiptoken=abc'
|
||||
|
||||
describe('listUserDevicesTool url', () => {
|
||||
it('builds the relationship path for the first page', () => {
|
||||
expect(buildUrl({ userId: 'user-1' })).toContain('/registeredDevices')
|
||||
expect(buildUrl({ userId: 'user-1', deviceRelationship: 'owned' })).toContain('/ownedDevices')
|
||||
})
|
||||
|
||||
it('accepts a continuation URL for the selected relationship', () => {
|
||||
expect(buildUrl({ nextLink: REGISTERED_NEXT_LINK })).toContain('/registeredDevices')
|
||||
expect(buildUrl({ nextLink: OWNED_NEXT_LINK, deviceRelationship: 'owned' })).toContain(
|
||||
'/ownedDevices'
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* The Next Page field is shared across operations and keeps its value when the Device Link
|
||||
* dropdown changes. Accepting either relationship segment would silently keep paging the one
|
||||
* the user just switched away from.
|
||||
*/
|
||||
it('rejects a continuation URL for the other relationship', () => {
|
||||
expect(() => buildUrl({ nextLink: REGISTERED_NEXT_LINK, deviceRelationship: 'owned' })).toThrow(
|
||||
/continues "registeredDevices", but this operation reads "ownedDevices"/
|
||||
)
|
||||
expect(() => buildUrl({ nextLink: OWNED_NEXT_LINK, deviceRelationship: 'registered' })).toThrow(
|
||||
/continues "ownedDevices", but this operation reads "registeredDevices"/
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an unknown relationship before touching the continuation URL', () => {
|
||||
expect(() =>
|
||||
buildUrl({ nextLink: REGISTERED_NEXT_LINK, deviceRelationship: 'managed' })
|
||||
).toThrow(/Device relationship must be "registered" or "owned"/)
|
||||
})
|
||||
})
|
||||
@@ -58,21 +58,22 @@ export const listUserDevicesTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
url: (params) => {
|
||||
if (params.nextLink)
|
||||
return assertGraphNextPageUrlForCollection(params.nextLink, [
|
||||
'registeredDevices',
|
||||
'ownedDevices',
|
||||
])
|
||||
const userId = params.userId?.trim()
|
||||
if (!userId) throw new Error('User ID is required')
|
||||
const relationship = params.deviceRelationship?.trim() || 'registered'
|
||||
const path = RELATIONSHIP_PATHS[relationship]
|
||||
if (!path) throw new Error('Device relationship must be "registered" or "owned"')
|
||||
/**
|
||||
* Assert against the currently selected relationship only. Accepting both would let a
|
||||
* continuation URL for `registeredDevices` keep paging that collection after the Device
|
||||
* Link dropdown was flipped to `ownedDevices`, silently returning the other relationship.
|
||||
*/
|
||||
if (params.nextLink) return assertGraphNextPageUrlForCollection(params.nextLink, [path])
|
||||
const userId = params.userId?.trim()
|
||||
if (!userId) throw new Error('User ID is required')
|
||||
const base = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(userId)}/${path}`
|
||||
return params.top ? `${base}?$top=${params.top}` : base
|
||||
},
|
||||
|
||||
@@ -34,7 +34,7 @@ export const listUsersTool: ToolConfig<MicrosoftAdListUsersParams, MicrosoftAdLi
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'OData filter expression (e.g., "department eq \'Sales\'")',
|
||||
description: `OData filter expression (e.g., "department eq 'Sales'")`,
|
||||
},
|
||||
search: {
|
||||
type: 'string',
|
||||
@@ -47,7 +47,7 @@ export const listUsersTool: ToolConfig<MicrosoftAdListUsersParams, MicrosoftAdLi
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Continuation URL from a previous response\'s "nextLink" output, used to fetch the next page of results',
|
||||
"Continuation URL from a previous response's 'nextLink' output, used to fetch the next page of results",
|
||||
},
|
||||
},
|
||||
request: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { validateOktaDomain } from '@/lib/core/security/input-validation'
|
||||
import type { OktaDeactivateUserParams, OktaDeactivateUserResponse } from '@/tools/okta/types'
|
||||
import { oktaHeaders, throwOktaError } from '@/tools/okta/utils'
|
||||
import { isOktaFlagEnabled, oktaHeaders, throwOktaError } from '@/tools/okta/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
const logger = createLogger('OktaDeactivateUser')
|
||||
@@ -46,7 +46,7 @@ export const oktaDeactivateUserTool: ToolConfig<
|
||||
request: {
|
||||
url: (params) => {
|
||||
const domain = validateOktaDomain(params.domain)
|
||||
const sendEmail = params.sendEmail === true
|
||||
const sendEmail = isOktaFlagEnabled(params.sendEmail)
|
||||
return `https://${domain}/api/v1/users/${encodeURIComponent(params.userId.trim())}/lifecycle/deactivate?sendEmail=${sendEmail}`
|
||||
},
|
||||
method: 'POST',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { validateOktaDomain } from '@/lib/core/security/input-validation'
|
||||
import type { OktaDeleteUserParams, OktaDeleteUserResponse } from '@/tools/okta/types'
|
||||
import { oktaHeaders, throwOktaError } from '@/tools/okta/utils'
|
||||
import { isOktaFlagEnabled, oktaHeaders, throwOktaError } from '@/tools/okta/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
const logger = createLogger('OktaDeleteUser')
|
||||
@@ -43,7 +43,7 @@ export const oktaDeleteUserTool: ToolConfig<OktaDeleteUserParams, OktaDeleteUser
|
||||
request: {
|
||||
url: (params) => {
|
||||
const domain = validateOktaDomain(params.domain)
|
||||
const sendEmail = params.sendEmail === true
|
||||
const sendEmail = isOktaFlagEnabled(params.sendEmail)
|
||||
return `https://${domain}/api/v1/users/${encodeURIComponent(params.userId.trim())}?sendEmail=${sendEmail}`
|
||||
},
|
||||
method: 'DELETE',
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OktaBlock } from '@/blocks/blocks/okta'
|
||||
import { oktaDeactivateUserTool } from '@/tools/okta/deactivate_user'
|
||||
import { oktaDeleteUserTool } from '@/tools/okta/delete_user'
|
||||
import { oktaGetLogsTool } from '@/tools/okta/get_logs'
|
||||
import { oktaGetUserTool } from '@/tools/okta/get_user'
|
||||
import { oktaUpdateGroupTool } from '@/tools/okta/update_group'
|
||||
@@ -11,6 +13,16 @@ import { mergeOktaGroupProfile } from '@/tools/okta/utils'
|
||||
|
||||
const AUTH = { apiKey: 'token', domain: 'dev-123456.okta.com' }
|
||||
|
||||
/**
|
||||
* Calls a declarative `url` builder with the untyped shape a tool really
|
||||
* receives. An LLM tool call, a `<Block.output>` reference, and an
|
||||
* API-triggered run all deliver every value as text, which the typed params
|
||||
* interface does not model.
|
||||
*/
|
||||
function builtUrl(build: (params: never) => string, params: Record<string, unknown>): string {
|
||||
return build(params as never)
|
||||
}
|
||||
|
||||
/** Narrows a declarative `body` builder's union return to a plain object. */
|
||||
function builtBody(build: () => unknown): Record<string, unknown> {
|
||||
return build() as Record<string, unknown>
|
||||
@@ -52,6 +64,23 @@ describe('okta update_group profile merge', () => {
|
||||
expect(merged.description).toBe('Updated')
|
||||
})
|
||||
|
||||
it('keeps the stored name when the caller supplies a blank one', () => {
|
||||
// `name` is `user-or-llm`, and a model routinely emits `""` for a field it
|
||||
// has nothing to say about. The group profile declares no required
|
||||
// attributes, so Okta would persist the blank over the stored name.
|
||||
const merged = mergeOktaGroupProfile(
|
||||
{ name: 'Engineering', description: 'All engineers' },
|
||||
{ name: '', description: 'Updated' }
|
||||
)
|
||||
|
||||
expect(merged.name).toBe('Engineering')
|
||||
expect(merged.description).toBe('Updated')
|
||||
})
|
||||
|
||||
it('does not require a name, matching the description it advertises', () => {
|
||||
expect(oktaUpdateGroupTool.params.name.required).toBe(false)
|
||||
})
|
||||
|
||||
it('still applies an explicitly supplied empty description', () => {
|
||||
const merged = mergeOktaGroupProfile(
|
||||
{ name: 'Engineering', description: 'All engineers' },
|
||||
@@ -134,6 +163,32 @@ describe('okta update_user partial merge', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('okta lifecycle sendEmail coercion', () => {
|
||||
// An LLM tool call, a `<Block.output>` reference, and an API-triggered run all
|
||||
// deliver a boolean as text, so a strict `=== true` check silently sent
|
||||
// `sendEmail=false` and the deactivation email never went out.
|
||||
it('honours a stringified sendEmail on deactivate_user', () => {
|
||||
expect(
|
||||
builtUrl(oktaDeactivateUserTool.request.url, { ...AUTH, userId: '00u1', sendEmail: 'true' })
|
||||
).toContain('sendEmail=true')
|
||||
})
|
||||
|
||||
it('honours a stringified sendEmail on delete_user', () => {
|
||||
expect(
|
||||
builtUrl(oktaDeleteUserTool.request.url, { ...AUTH, userId: '00u1', sendEmail: 'true' })
|
||||
).toContain('sendEmail=true')
|
||||
})
|
||||
|
||||
it('still defaults to not sending when the flag is absent or false', () => {
|
||||
expect(builtUrl(oktaDeactivateUserTool.request.url, { ...AUTH, userId: '00u1' })).toContain(
|
||||
'sendEmail=false'
|
||||
)
|
||||
expect(
|
||||
builtUrl(oktaDeleteUserTool.request.url, { ...AUTH, userId: '00u1', sendEmail: 'false' })
|
||||
).toContain('sendEmail=false')
|
||||
})
|
||||
})
|
||||
|
||||
describe('okta get_logs query building', () => {
|
||||
it('sends limit=0 rather than treating it as absent', () => {
|
||||
const url = oktaGetLogsTool.request.url({ ...AUTH, limit: 0 })
|
||||
@@ -206,6 +261,70 @@ describe('okta block params mapping', () => {
|
||||
expect(merged.sendEmail).toBe(false)
|
||||
})
|
||||
|
||||
it('reads the activate toggle that belongs to the selected operation', () => {
|
||||
// Okta's `activate` default is inverted between these two operations, so a
|
||||
// single shared switch handed each of them the other one's answer.
|
||||
expect(
|
||||
mergedBlockParams({
|
||||
operation: 'okta_create_user',
|
||||
...AUTH,
|
||||
activate: false,
|
||||
activateFactor: true,
|
||||
}).activate
|
||||
).toBe(false)
|
||||
expect(
|
||||
mergedBlockParams({
|
||||
operation: 'okta_enroll_factor',
|
||||
...AUTH,
|
||||
activate: true,
|
||||
activateFactor: false,
|
||||
}).activate
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves enroll_factor unactivated when only a stale create-user toggle is present', () => {
|
||||
const merged = mergedBlockParams({
|
||||
operation: 'okta_enroll_factor',
|
||||
...AUTH,
|
||||
userId: '00u1',
|
||||
activate: true,
|
||||
})
|
||||
|
||||
expect(merged.activate).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sends only the cursor minted by the selected operation', () => {
|
||||
const merged = mergedBlockParams({
|
||||
operation: 'okta_list_groups',
|
||||
...AUTH,
|
||||
after: 'cursor-from-list-users',
|
||||
groupsAfter: 'cursor-from-list-groups',
|
||||
})
|
||||
|
||||
expect(merged.after).toBe('cursor-from-list-groups')
|
||||
})
|
||||
|
||||
it('drops a stale cursor left behind by another list operation', () => {
|
||||
const merged = mergedBlockParams({
|
||||
operation: 'okta_list_groups',
|
||||
...AUTH,
|
||||
after: 'cursor-from-list-users',
|
||||
})
|
||||
|
||||
expect(merged.after).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops any cursor on an operation that does not paginate', () => {
|
||||
const merged = mergedBlockParams({
|
||||
operation: 'okta_get_user',
|
||||
...AUTH,
|
||||
userId: '00u1',
|
||||
after: 'cursor-from-list-users',
|
||||
})
|
||||
|
||||
expect(merged.after).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops a non-numeric limit instead of forwarding the raw string', () => {
|
||||
const merged = mergedBlockParams({
|
||||
operation: 'okta_list_users',
|
||||
@@ -224,6 +343,12 @@ describe('okta block output contract', () => {
|
||||
expect(oktaGetUserTool.outputs?.activated).toMatchObject({ type: 'string' })
|
||||
})
|
||||
|
||||
it('declares activated as the timestamp string the user reads emit', () => {
|
||||
// `get_user` and `list_users` publish Okta's activation timestamp here, so a
|
||||
// boolean declaration mistyped every saved `<Okta.activated>` reference.
|
||||
expect(OktaBlock.outputs.activated).toMatchObject({ type: 'string' })
|
||||
})
|
||||
|
||||
it('declares every subBlock the params mapper reads', () => {
|
||||
const subBlockIds = new Set(OktaBlock.subBlocks.map((subBlock) => subBlock.id))
|
||||
expect(subBlockIds.has('ruleSearch')).toBe(true)
|
||||
|
||||
@@ -408,7 +408,7 @@ export interface OktaCreateGroupResponse extends ToolResponse {
|
||||
// Update Group
|
||||
export interface OktaUpdateGroupParams extends OktaBaseParams {
|
||||
groupId: string
|
||||
name: string
|
||||
name?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -56,9 +56,9 @@ export const oktaUpdateGroupTool: ToolConfig<OktaUpdateGroupParams, OktaUpdateGr
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'Updated group name',
|
||||
description: 'Updated group name. Leave blank to keep the stored name',
|
||||
},
|
||||
description: {
|
||||
type: 'string',
|
||||
|
||||
@@ -36,6 +36,17 @@ export async function throwOktaError(
|
||||
throw new Error(error.errorSummary || fallbackMessage)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a boolean flag that may have arrived as a string.
|
||||
*
|
||||
* A flag reaches a tool as text whenever it comes from an LLM tool call, a
|
||||
* `<Block.output>` reference, or an API-triggered run, so a strict `=== true`
|
||||
* check silently turns "send the email" into `sendEmail=false`.
|
||||
*/
|
||||
export function isOktaFlagEnabled(value: unknown): boolean {
|
||||
return value === true || value === 'true'
|
||||
}
|
||||
|
||||
const NEXT_LINK_PATTERN = /<([^>]+)>\s*;\s*rel="next"/i
|
||||
|
||||
/**
|
||||
@@ -73,14 +84,19 @@ export function parseOktaPagination(response: Response): {
|
||||
* description on a rename, and every org-defined custom attribute on any
|
||||
* update. Merging over the current profile is what makes an omitted field mean
|
||||
* "leave it alone" instead of "delete it".
|
||||
*
|
||||
* `name` is applied only when it is truthy. A model routinely emits `""` for a
|
||||
* field it has nothing to say about, and the group profile declares no required
|
||||
* attributes, so Okta would happily persist the blank over the stored name.
|
||||
* The read-modify-write already carries the stored name through.
|
||||
*/
|
||||
export function mergeOktaGroupProfile(
|
||||
existing: OktaGroupProfile | undefined,
|
||||
updates: { name: string; description?: string }
|
||||
updates: { name?: string; description?: string }
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...existing,
|
||||
name: updates.name,
|
||||
...(updates.name ? { name: updates.name } : {}),
|
||||
...(updates.description === undefined ? {} : { description: updates.description }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,8 @@ export const aggregateTool: ToolConfig<ServiceNowAggregateParams, ServiceNowAggr
|
||||
type: 'string',
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description: 'Filter on aggregate results (e.g., "count>5")',
|
||||
description:
|
||||
'Filter on aggregate results, written as aggregate^field^operator^value and comma-separated for more than one (e.g., "count^priority^>^3" or "count^state^=^1,avg^priority^>^3")',
|
||||
},
|
||||
displayValue: {
|
||||
type: 'string',
|
||||
|
||||
@@ -282,9 +282,45 @@ describe('block params mapping keeps per-operation defaults from colliding', ()
|
||||
...auth,
|
||||
operation: 'servicenow_update_change_state',
|
||||
sysId: 'chg1',
|
||||
targetState: '3',
|
||||
} as never) as Record<string, unknown>
|
||||
|
||||
expect(mapped.state).toBe('-5')
|
||||
expect(mapped.state).toBe('3')
|
||||
})
|
||||
|
||||
/**
|
||||
* Both controls are `required: true` and visible, so a seeded value is a
|
||||
* consequential answer the caller never gave: Move Change State would PATCH
|
||||
* the change backwards to New, and Approve or Reject would approve.
|
||||
*/
|
||||
it.each([
|
||||
['targetState', 'servicenow_update_change_state'],
|
||||
['decision', 'servicenow_update_approval'],
|
||||
])('leaves the required %s control unseeded', (subBlockId) => {
|
||||
const subBlock = ServiceNowBlock.subBlocks.find((candidate) => candidate.id === subBlockId)
|
||||
|
||||
expect(subBlock?.required).toBe(true)
|
||||
expect(subBlock?.value).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sends no state for a change transition until one is chosen', () => {
|
||||
const mapped = mapParams?.({
|
||||
...seededDefaults(),
|
||||
...auth,
|
||||
operation: 'servicenow_update_change_state',
|
||||
sysId: 'chg1',
|
||||
} as never) as Record<string, unknown>
|
||||
|
||||
expect(mapped.state).toBeFalsy()
|
||||
})
|
||||
|
||||
it('sends no approval decision until one is chosen', () => {
|
||||
const merged = mergedParams({
|
||||
operation: 'servicenow_update_approval',
|
||||
approvalSysId: 'apr1',
|
||||
})
|
||||
|
||||
expect(merged.decision).toBeFalsy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -354,11 +390,25 @@ describe('one subBlock id never carries two different value spaces', () => {
|
||||
)
|
||||
|
||||
/**
|
||||
* `fields` carries a JSON body on Create/Update Record and a comma-separated
|
||||
* projection everywhere else. The shipped ids keep the original `fields`
|
||||
* subblock, so the split is one-directional: no operation added since can put
|
||||
* a projection where a JSON body is parsed, or a body where a projection goes.
|
||||
* The `fields` tool param carries a JSON body on Create/Update Record and a
|
||||
* comma-separated projection everywhere else, so no subBlock id may serve
|
||||
* both. These assertions store the value under the id the *projection*
|
||||
* control really writes to, which is the whole point: sharing `fields`
|
||||
* between Read Records and the two JSON bodies left one stored value
|
||||
* straddling both value spaces.
|
||||
*/
|
||||
const readProjectionId = ServiceNowBlock.subBlocks.find(
|
||||
(subBlock) =>
|
||||
subBlock.title === 'Fields to Return' &&
|
||||
subBlock.condition &&
|
||||
'value' in subBlock.condition &&
|
||||
subBlock.condition.value === 'servicenow_read_record'
|
||||
)?.id
|
||||
|
||||
it('gives Read Records a projection control of its own', () => {
|
||||
expect(readProjectionId).toBeDefined()
|
||||
})
|
||||
|
||||
it('never sends a JSON body as a field projection', () => {
|
||||
const merged = mergedParams({
|
||||
operation: 'servicenow_list_incidents',
|
||||
@@ -368,16 +418,83 @@ describe('one subBlock id never carries two different value spaces', () => {
|
||||
expect(merged.fields).toBe('number,short_description')
|
||||
})
|
||||
|
||||
it('never parses a field projection as a create body', () => {
|
||||
it('never sends a stale create body as the Read Records projection', () => {
|
||||
const merged = mergedParams({
|
||||
operation: 'servicenow_create_record',
|
||||
operation: 'servicenow_read_record',
|
||||
tableName: 'incident',
|
||||
fields: '{"short_description":"x"}',
|
||||
returnFields: 'number,short_description',
|
||||
})
|
||||
expect(merged.fields).toEqual({ short_description: 'x' })
|
||||
|
||||
expect(merged.fields).toBeUndefined()
|
||||
})
|
||||
|
||||
it('never parses a field projection as a create body', () => {
|
||||
expect(() =>
|
||||
mergedParams({
|
||||
operation: 'servicenow_create_record',
|
||||
tableName: 'incident',
|
||||
[readProjectionId as string]: 'number,short_description',
|
||||
})
|
||||
).not.toThrow()
|
||||
})
|
||||
|
||||
it('never lets one subBlock id carry both a JSON body and a plain projection', () => {
|
||||
const typesById = new Map<string, Set<string>>()
|
||||
for (const subBlock of ServiceNowBlock.subBlocks) {
|
||||
const types = typesById.get(subBlock.id) ?? new Set<string>()
|
||||
types.add(subBlock.type)
|
||||
typesById.set(subBlock.id, types)
|
||||
}
|
||||
|
||||
const straddling = [...typesById.entries()]
|
||||
.filter(([, types]) => types.has('code') && types.has('short-input'))
|
||||
.map(([id]) => id)
|
||||
|
||||
expect(straddling).toEqual([])
|
||||
})
|
||||
|
||||
/**
|
||||
* `tools.config.params` runs unguarded, so a bare `JSON.parse` escaped as
|
||||
* `JSON Parse error: Expected '}'` with nothing naming the control to fix.
|
||||
*/
|
||||
it.each([
|
||||
['additionalFields', 'servicenow_update_incident', 'Additional Fields must be a JSON object'],
|
||||
['variables', 'servicenow_order_catalog_item', 'Item Variables must be a JSON object'],
|
||||
['fields', 'servicenow_create_record', 'Fields must be a JSON object'],
|
||||
])('names the %s control when its JSON is malformed', (subBlockId, operation, message) => {
|
||||
expect(() =>
|
||||
mergedParams({ operation, tableName: 'incident', sysId: 'x', [subBlockId]: '{"a": }' })
|
||||
).toThrow(message)
|
||||
})
|
||||
|
||||
/**
|
||||
* `update_approval` spreads the same `writeParams` as the other semantic
|
||||
* writes but addresses its record by `approvalSysId`, so it sat outside
|
||||
* `SEMANTIC_WRITE_OPS` and was the one operation where a stale advanced
|
||||
* `displayValue`/`returnFields` reached the wire with no control surfacing it.
|
||||
*/
|
||||
it('surfaces the semantic display-value default on update_approval', () => {
|
||||
const merged = mergedParams({
|
||||
operation: 'servicenow_update_approval',
|
||||
approvalSysId: 'apr1',
|
||||
decision: 'approved',
|
||||
})
|
||||
|
||||
expect(merged.displayValue).toBe(DEFAULT_DISPLAY_VALUE)
|
||||
})
|
||||
|
||||
it.each(['semanticDisplayValue', 'returnFields', 'inputDisplayValue'])(
|
||||
'offers the %s control on update_approval',
|
||||
(subBlockId) => {
|
||||
const subBlock = ServiceNowBlock.subBlocks.find((candidate) => candidate.id === subBlockId)
|
||||
const conditionValue =
|
||||
subBlock?.condition && 'value' in subBlock.condition ? subBlock.condition.value : undefined
|
||||
const ops = Array.isArray(conditionValue) ? conditionValue : [conditionValue]
|
||||
|
||||
expect(ops).toContain('servicenow_update_approval')
|
||||
}
|
||||
)
|
||||
|
||||
it('leaves the generic Table API operations without a semantic state', () => {
|
||||
const merged = mergedParams({
|
||||
operation: 'servicenow_read_record',
|
||||
@@ -618,3 +735,23 @@ describe('get_change_next_states', () => {
|
||||
).rejects.toThrow('No Record found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ServiceNow aggregate having syntax', () => {
|
||||
/**
|
||||
* `sysparm_having` takes `aggregate^field^operator^value`, comma-separated for
|
||||
* more than one clause. The documented `count>5` form is not valid syntax, so
|
||||
* anyone following it got an empty or unfiltered result.
|
||||
*/
|
||||
it('documents the encoded aggregate^field^operator^value form', () => {
|
||||
const description = aggregateTool.params.having?.description ?? ''
|
||||
|
||||
expect(description).toContain('aggregate^field^operator^value')
|
||||
expect(description).not.toContain('count>5')
|
||||
})
|
||||
|
||||
it('shows the same form in the block placeholder', () => {
|
||||
const having = ServiceNowBlock.subBlocks.find((subBlock) => subBlock.id === 'having')
|
||||
|
||||
expect(having?.placeholder).toBe('count^priority^>^3')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
buildSplunkFormHeaders,
|
||||
buildSplunkUrl,
|
||||
mapSplunkMessages,
|
||||
readSplunkJson,
|
||||
readSplunkDispatchJson,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
SPLUNK_MESSAGES_OUTPUT,
|
||||
splunkPathSegment,
|
||||
@@ -43,7 +43,7 @@ export const cancelSearchJobTool: ToolConfig<
|
||||
},
|
||||
|
||||
transformResponse: async (response: Response, params) => {
|
||||
const data = await readSplunkJson(response)
|
||||
const data = await readSplunkDispatchJson(response)
|
||||
return {
|
||||
success: true,
|
||||
output: {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
buildSplunkFormHeaders,
|
||||
buildSplunkUrl,
|
||||
normalizeSearchQuery,
|
||||
readSplunkDispatchJson,
|
||||
requireSplunkSid,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
} from '@/tools/splunk/utils'
|
||||
@@ -150,7 +151,7 @@ export const createSearchJobTool: ToolConfig<
|
||||
},
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
const data = await response.json()
|
||||
const data = await readSplunkDispatchJson(response)
|
||||
return { success: true, output: { sid: requireSplunkSid(data) } }
|
||||
},
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
buildSplunkFormBody,
|
||||
buildSplunkFormHeaders,
|
||||
buildSplunkUrl,
|
||||
readSplunkDispatchJson,
|
||||
requireSplunkSid,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
splunkPathSegment,
|
||||
@@ -106,7 +107,7 @@ export const dispatchSavedSearchTool: ToolConfig<
|
||||
},
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
const data = await response.json()
|
||||
const data = await readSplunkDispatchJson(response)
|
||||
return { success: true, output: { sid: requireSplunkSid(data) } }
|
||||
},
|
||||
|
||||
|
||||
@@ -13,6 +13,27 @@ import {
|
||||
} from '@/tools/splunk/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
/**
|
||||
* Refuses the `count=0` that Splunk documents as "return all available results".
|
||||
*
|
||||
* Nothing downstream bounds that read: {@link readSplunkJson} buffers the whole
|
||||
* body with a single `response.text()` and every row is then materialized into
|
||||
* the block output. The sid is not necessarily a job this workflow dispatched —
|
||||
* a scheduled saved search carries `dispatch.max_count`, which defaults to
|
||||
* 500000 — so "all" is a number the caller has no way to know in advance.
|
||||
*
|
||||
* Paging with `offset` reaches the same rows with a bounded response per call,
|
||||
* which is what the parameter description directs callers to do.
|
||||
*/
|
||||
function assertBoundedResultCount(count: number | undefined): void {
|
||||
if (count == null || (count as unknown) === '') return
|
||||
if (Number(count) === 0) {
|
||||
throw new Error(
|
||||
'Splunk reads count=0 as "return every result row", which is unbounded — a scheduled job can hold hundreds of thousands of rows. Set a positive count and page through the results with offset.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads transformed results from `search/v2/jobs/{sid}/results`. The v1 instance of
|
||||
* this endpoint is deprecated and turned off by default from Splunk Enterprise 9.0.1
|
||||
@@ -42,7 +63,7 @@ export const getSearchResultsTool: ToolConfig<
|
||||
required: false,
|
||||
visibility: 'user-or-llm',
|
||||
description:
|
||||
'Maximum number of result rows to return. Defaults to 100. Page through larger result sets with offset rather than raising this — a completed job can hold millions of rows.',
|
||||
'Maximum number of result rows to return. Defaults to 100. Page through larger result sets with offset rather than raising this — a completed job can hold millions of rows. 0 is rejected here even though Splunk reads it as "every row".',
|
||||
},
|
||||
offset: {
|
||||
type: 'number',
|
||||
@@ -67,6 +88,7 @@ export const getSearchResultsTool: ToolConfig<
|
||||
|
||||
request: {
|
||||
url: (params) => {
|
||||
assertBoundedResultCount(params.count)
|
||||
const url = buildSplunkUrl(
|
||||
params,
|
||||
`/search/v2/jobs/${splunkPathSegment(params.sid)}/results`,
|
||||
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
getEntryContent,
|
||||
getEntryName,
|
||||
getSplunkEntries,
|
||||
getSplunkPaging,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
SPLUNK_OFFSET_OUTPUT,
|
||||
SPLUNK_TOTAL_OUTPUT,
|
||||
} from '@/tools/splunk/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
@@ -48,6 +51,7 @@ export const listAppsTool: ToolConfig<SplunkListAppsParams, SplunkListAppsRespon
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
const data = await response.json()
|
||||
const paging = getSplunkPaging(data)
|
||||
return {
|
||||
success: true,
|
||||
output: {
|
||||
@@ -69,6 +73,8 @@ export const listAppsTool: ToolConfig<SplunkListAppsParams, SplunkListAppsRespon
|
||||
stateChangeRequiresRestart: asBoolean(content.state_change_requires_restart),
|
||||
}
|
||||
}),
|
||||
total: paging.total,
|
||||
offset: paging.offset,
|
||||
},
|
||||
}
|
||||
},
|
||||
@@ -115,5 +121,7 @@ export const listAppsTool: ToolConfig<SplunkListAppsParams, SplunkListAppsRespon
|
||||
},
|
||||
},
|
||||
},
|
||||
total: SPLUNK_TOTAL_OUTPUT,
|
||||
offset: SPLUNK_OFFSET_OUTPUT,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
getEntryContent,
|
||||
getEntryName,
|
||||
getSplunkEntries,
|
||||
getSplunkPaging,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
SPLUNK_OFFSET_OUTPUT,
|
||||
SPLUNK_TOTAL_OUTPUT,
|
||||
} from '@/tools/splunk/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
@@ -56,6 +59,7 @@ export const listFiredAlertsTool: ToolConfig<
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
const data = await response.json()
|
||||
const paging = getSplunkPaging(data)
|
||||
return {
|
||||
success: true,
|
||||
output: {
|
||||
@@ -68,6 +72,8 @@ export const listFiredAlertsTool: ToolConfig<
|
||||
triggeredAlertCount: asNumber(content.triggered_alert_count),
|
||||
}
|
||||
}),
|
||||
total: paging.total,
|
||||
offset: paging.offset,
|
||||
},
|
||||
}
|
||||
},
|
||||
@@ -86,5 +92,7 @@ export const listFiredAlertsTool: ToolConfig<
|
||||
},
|
||||
},
|
||||
},
|
||||
total: SPLUNK_TOTAL_OUTPUT,
|
||||
offset: SPLUNK_OFFSET_OUTPUT,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import {
|
||||
getEntryContent,
|
||||
getEntryName,
|
||||
getSplunkEntries,
|
||||
getSplunkPaging,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
SPLUNK_OFFSET_OUTPUT,
|
||||
SPLUNK_TOTAL_OUTPUT,
|
||||
} from '@/tools/splunk/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
|
||||
@@ -55,6 +58,7 @@ export const listIndexesTool: ToolConfig<SplunkListIndexesParams, SplunkListInde
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
const data = await response.json()
|
||||
const paging = getSplunkPaging(data)
|
||||
return {
|
||||
success: true,
|
||||
output: {
|
||||
@@ -78,6 +82,8 @@ export const listIndexesTool: ToolConfig<SplunkListIndexesParams, SplunkListInde
|
||||
thawedPath: asString(content.thawedPath),
|
||||
}
|
||||
}),
|
||||
total: paging.total,
|
||||
offset: paging.offset,
|
||||
},
|
||||
}
|
||||
},
|
||||
@@ -113,5 +119,7 @@ export const listIndexesTool: ToolConfig<SplunkListIndexesParams, SplunkListInde
|
||||
},
|
||||
},
|
||||
},
|
||||
total: SPLUNK_TOTAL_OUTPUT,
|
||||
offset: SPLUNK_OFFSET_OUTPUT,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -7,8 +7,11 @@ import {
|
||||
buildSplunkHeaders,
|
||||
buildSplunkUrl,
|
||||
getSplunkEntries,
|
||||
getSplunkPaging,
|
||||
mapSavedSearchEntry,
|
||||
SPLUNK_CONNECTION_PARAMS,
|
||||
SPLUNK_OFFSET_OUTPUT,
|
||||
SPLUNK_TOTAL_OUTPUT,
|
||||
savedSearchFieldQuery,
|
||||
} from '@/tools/splunk/utils'
|
||||
import type { ToolConfig } from '@/tools/types'
|
||||
@@ -59,9 +62,14 @@ export const listSavedSearchesTool: ToolConfig<
|
||||
|
||||
transformResponse: async (response: Response) => {
|
||||
const data = await response.json()
|
||||
const paging = getSplunkPaging(data)
|
||||
return {
|
||||
success: true,
|
||||
output: { savedSearches: getSplunkEntries(data).map(mapSavedSearchEntry) },
|
||||
output: {
|
||||
savedSearches: getSplunkEntries(data).map(mapSavedSearchEntry),
|
||||
total: paging.total,
|
||||
offset: paging.offset,
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
@@ -71,5 +79,7 @@ export const listSavedSearchesTool: ToolConfig<
|
||||
description: 'Saved searches configured in Splunk',
|
||||
items: { type: 'object', properties: SAVED_SEARCH_OUTPUT_FIELDS },
|
||||
},
|
||||
total: SPLUNK_TOTAL_OUTPUT,
|
||||
offset: SPLUNK_OFFSET_OUTPUT,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,8 +2,14 @@
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { cancelSearchJobTool } from '@/tools/splunk/cancel_search_job'
|
||||
import { createSearchJobTool } from '@/tools/splunk/create_search_job'
|
||||
import { dispatchSavedSearchTool } from '@/tools/splunk/dispatch_saved_search'
|
||||
import { getFiredAlertsTool } from '@/tools/splunk/get_fired_alerts'
|
||||
import { getSearchResultsTool } from '@/tools/splunk/get_search_results'
|
||||
import { listAppsTool } from '@/tools/splunk/list_apps'
|
||||
import { listFiredAlertsTool } from '@/tools/splunk/list_fired_alerts'
|
||||
import { listIndexesTool } from '@/tools/splunk/list_indexes'
|
||||
import { listSavedSearchesTool } from '@/tools/splunk/list_saved_searches'
|
||||
|
||||
const BASE = { baseUrl: 'https://splunk.example.com:8089' }
|
||||
@@ -52,3 +58,115 @@ describe('getFiredAlertsTool', () => {
|
||||
expect(url).not.toContain('offset=')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSearchResultsTool count bound', () => {
|
||||
/**
|
||||
* Splunk documents `count=0` as "return all available results" and nothing
|
||||
* downstream bounds it — the whole body is buffered with a single
|
||||
* `response.text()` and every row is materialized. The sid may name a scheduled
|
||||
* job whose `dispatch.max_count` defaults to 500000.
|
||||
*/
|
||||
it.each([0, '0'])('rejects count=%s rather than issuing an unbounded read', (count) => {
|
||||
expect(() => getSearchResultsTool.request.url({ ...BASE, sid: '1.1', count } as never)).toThrow(
|
||||
/unbounded/
|
||||
)
|
||||
})
|
||||
|
||||
it('still sends a positive count, and omits an untouched one', () => {
|
||||
expect(
|
||||
getSearchResultsTool.request.url({ ...BASE, sid: '1.1', count: 500 } as never)
|
||||
).toContain('count=500')
|
||||
|
||||
const untouched = getSearchResultsTool.request.url({
|
||||
...BASE,
|
||||
sid: '1.1',
|
||||
count: null,
|
||||
} as never)
|
||||
expect(untouched).not.toContain('count=')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* `output_mode` is absent from the documented parameter table for the dispatching
|
||||
* and job-control endpoints, whose only documented response is the XML
|
||||
* `<response><sid>...</sid></response>`. Parsing that as JSON threw, which reported
|
||||
* a cancel that really did cancel as a failure and lost the search ID of a job
|
||||
* that had already been created.
|
||||
*/
|
||||
const SPLUNK_XML_SID = '<?xml version="1.0"?><response><sid>1457683115.100</sid></response>'
|
||||
|
||||
describe('POST tools tolerate an XML body', () => {
|
||||
it('reports a successful cancel instead of a JSON parse failure', async () => {
|
||||
const result = await cancelSearchJobTool.transformResponse?.(
|
||||
new Response(SPLUNK_XML_SID, { status: 200 }),
|
||||
{ ...BASE, sid: '1457683115.100' } as never
|
||||
)
|
||||
|
||||
expect(result?.success).toBe(true)
|
||||
expect(result?.output.sid).toBe('1457683115.100')
|
||||
})
|
||||
|
||||
/**
|
||||
* The dispatch was accepted and the job exists, so the search ID is read out of
|
||||
* the XML rather than discarded. Failing here would strand a job the caller can
|
||||
* no longer poll or cancel.
|
||||
*/
|
||||
it.each([
|
||||
['create_search_job', createSearchJobTool],
|
||||
['dispatch_saved_search', dispatchSavedSearchTool],
|
||||
])('keeps the search ID %s returned in XML', async (_label, tool) => {
|
||||
const result = await tool.transformResponse?.(
|
||||
new Response(SPLUNK_XML_SID, { status: 200 }),
|
||||
BASE as never
|
||||
)
|
||||
|
||||
expect(result?.success).toBe(true)
|
||||
expect(result?.output.sid).toBe('1457683115.100')
|
||||
})
|
||||
|
||||
/**
|
||||
* A body cut off mid-transfer must not read as a complete envelope: on a cancel
|
||||
* that would report a truncated response as a successful cancellation.
|
||||
*/
|
||||
it('rejects a truncated envelope on cancel', async () => {
|
||||
await expect(
|
||||
cancelSearchJobTool.transformResponse?.(
|
||||
new Response('<response><sid>145768311', { status: 200 }),
|
||||
{ ...BASE, sid: '1457683115.100' } as never
|
||||
)
|
||||
).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Splunk answers every collection endpoint with a `paging` envelope. Without
|
||||
* projecting `total`, a full page and the last page are indistinguishable, so
|
||||
* `offset` is unusable as a pagination control.
|
||||
*/
|
||||
describe('list tools project the paging envelope', () => {
|
||||
const PAGING_BODY = JSON.stringify({
|
||||
entry: [{ name: 'one', content: {} }],
|
||||
paging: { total: 412, perPage: 30, offset: 30 },
|
||||
})
|
||||
|
||||
it.each([
|
||||
['list_saved_searches', listSavedSearchesTool],
|
||||
['list_apps', listAppsTool],
|
||||
['list_indexes', listIndexesTool],
|
||||
['list_fired_alerts', listFiredAlertsTool],
|
||||
])('%s reports total and offset', async (_label, tool) => {
|
||||
const result = await tool.transformResponse?.(new Response(PAGING_BODY), BASE as never)
|
||||
|
||||
expect(result?.output).toMatchObject({ total: 412, offset: 30 })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['list_saved_searches', listSavedSearchesTool],
|
||||
['list_apps', listAppsTool],
|
||||
['list_indexes', listIndexesTool],
|
||||
['list_fired_alerts', listFiredAlertsTool],
|
||||
])('%s declares total and offset as outputs', (_label, tool) => {
|
||||
expect(tool.outputs).toHaveProperty('total')
|
||||
expect(tool.outputs).toHaveProperty('offset')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -146,6 +146,8 @@ export interface SplunkListSavedSearchesParams extends SplunkBaseParams {
|
||||
export interface SplunkListSavedSearchesResponse extends ToolResponse {
|
||||
output: {
|
||||
savedSearches: SplunkSavedSearch[]
|
||||
total: number | null
|
||||
offset: number | null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +189,8 @@ export interface SplunkListFiredAlertsResponse extends ToolResponse {
|
||||
updated: string | null
|
||||
triggeredAlertCount: number | null
|
||||
}[]
|
||||
total: number | null
|
||||
offset: number | null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,6 +242,8 @@ export interface SplunkListIndexesResponse extends ToolResponse {
|
||||
coldPath: string | null
|
||||
thawedPath: string | null
|
||||
}[]
|
||||
total: number | null
|
||||
offset: number | null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +269,8 @@ export interface SplunkListAppsResponse extends ToolResponse {
|
||||
checkForUpdates: boolean | null
|
||||
stateChangeRequiresRestart: boolean | null
|
||||
}[]
|
||||
total: number | null
|
||||
offset: number | null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
buildSplunkFormBody,
|
||||
buildSplunkHeaders,
|
||||
buildSplunkUrl,
|
||||
getSplunkPaging,
|
||||
normalizeSearchQuery,
|
||||
readSplunkDispatchJson,
|
||||
readSplunkJson,
|
||||
requireSplunkSid,
|
||||
savedSearchFieldQuery,
|
||||
@@ -83,6 +85,116 @@ describe('readSplunkJson', () => {
|
||||
it('still parses a real body', async () => {
|
||||
await expect(readSplunkJson(new Response('{"results":[]}'))).resolves.toEqual({ results: [] })
|
||||
})
|
||||
|
||||
/**
|
||||
* The results path must never turn an unparseable body into an empty result set:
|
||||
* that reports a lost result set as a search that legitimately matched nothing.
|
||||
* The XML dispatch tolerance is deliberately not reachable from here.
|
||||
*/
|
||||
it('throws on a truncated JSON body rather than reporting an empty result set', async () => {
|
||||
await expect(readSplunkJson(new Response('{"results":[{"_raw":"partial'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('throws on a non-JSON body', async () => {
|
||||
await expect(readSplunkJson(new Response('upstream connect error'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('throws on a 2xx HTML interstitial instead of reporting zero events', async () => {
|
||||
await expect(
|
||||
readSplunkJson(new Response('<!DOCTYPE html><html><body>Sign in</body></html>'))
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('throws even on the dispatch XML envelope — results are always JSON', async () => {
|
||||
await expect(
|
||||
readSplunkJson(new Response('<response><sid>1457683115.100</sid></response>'))
|
||||
).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('readSplunkDispatchJson', () => {
|
||||
/**
|
||||
* `output_mode` is not in the documented parameter table for the dispatching and
|
||||
* job-control endpoints, and the only response the reference documents for them
|
||||
* is XML. The envelope is projected onto the same `{ sid }` shape JSON produces,
|
||||
* so a dispatch that answered in XML keeps the search ID of the job it just
|
||||
* created instead of erroring after the remote work already happened.
|
||||
*/
|
||||
it('reads the search ID out of the documented XML response', async () => {
|
||||
await expect(
|
||||
readSplunkDispatchJson(new Response('<response><sid>1457683115.100</sid></response>'))
|
||||
).resolves.toEqual({ sid: '1457683115.100' })
|
||||
})
|
||||
|
||||
it('accepts the XML declaration and attributes on the root', async () => {
|
||||
await expect(
|
||||
readSplunkDispatchJson(
|
||||
new Response('<?xml version="1.0" encoding="UTF-8"?><response><sid>1.1</sid></response>')
|
||||
)
|
||||
).resolves.toEqual({ sid: '1.1' })
|
||||
})
|
||||
|
||||
/** Job control documents "Returned values: None", so there is no sid to find. */
|
||||
it('returns an empty envelope for a job-control response with no sid', async () => {
|
||||
await expect(readSplunkDispatchJson(new Response('<response/>'))).resolves.toEqual({})
|
||||
await expect(
|
||||
readSplunkDispatchJson(new Response('<response><messages/></response>'))
|
||||
).resolves.toEqual({})
|
||||
})
|
||||
|
||||
/**
|
||||
* A body cut off mid-transfer still starts with the documented root. Matching the
|
||||
* opening tag alone read it as a complete envelope that carried nothing, which on
|
||||
* a cancellation reported a truncated response as a successful cancel.
|
||||
*/
|
||||
it('throws on a truncated envelope rather than reporting a successful cancel', async () => {
|
||||
await expect(readSplunkDispatchJson(new Response('<response><sid>145768311'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('still parses a JSON body', async () => {
|
||||
await expect(readSplunkDispatchJson(new Response('{"sid":"1.1"}'))).resolves.toEqual({
|
||||
sid: '1.1',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns an empty envelope for 204 and for an empty body', async () => {
|
||||
await expect(readSplunkDispatchJson(new Response(null, { status: 204 }))).resolves.toEqual({})
|
||||
await expect(readSplunkDispatchJson(new Response(' '))).resolves.toEqual({})
|
||||
})
|
||||
|
||||
/**
|
||||
* The tolerance is anchored to the one documented root element. A proxy error
|
||||
* page or an SSO interstitial served with a 2xx is not a successful dispatch, and
|
||||
* reading it as an empty envelope would hide it behind the missing-sid message.
|
||||
*/
|
||||
it('throws on a 2xx HTML interstitial rather than reading it as an empty envelope', async () => {
|
||||
await expect(
|
||||
readSplunkDispatchJson(new Response('<!DOCTYPE html><html><body>Sign in</body></html>'))
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('throws on some other XML document', async () => {
|
||||
await expect(
|
||||
readSplunkDispatchJson(new Response('<error><message>Gateway timeout</message></error>'))
|
||||
).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSplunkPaging', () => {
|
||||
it('projects total and offset from the collection paging envelope', () => {
|
||||
expect(getSplunkPaging({ paging: { total: 412, perPage: 30, offset: 30 } })).toEqual({
|
||||
total: 412,
|
||||
offset: 30,
|
||||
})
|
||||
})
|
||||
|
||||
it('reads the Atom-nested form and tolerates a response with no envelope', () => {
|
||||
expect(getSplunkPaging({ feed: { paging: { total: 7, offset: 0 } } })).toEqual({
|
||||
total: 7,
|
||||
offset: 0,
|
||||
})
|
||||
expect(getSplunkPaging({ entry: [] })).toEqual({ total: null, offset: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('requireSplunkSid', () => {
|
||||
|
||||
+117
-15
@@ -67,9 +67,9 @@ function normalizeBaseUrl(baseUrl: string): string {
|
||||
*
|
||||
* When only one node is supplied the other is filled with the documented wildcard
|
||||
* `-` — "To indicate all users, all apps, or resources shared by all users, use the
|
||||
* wildcard dash (-) symbol". `nobody` is NOT a neutral filler: it names the
|
||||
* shared-application owner, so using it would silently hide every user-private
|
||||
* object in the requested app.
|
||||
* wildcard dash (-) symbol". `nobody` is not an equivalent filler: the reference
|
||||
* documents it as the owner name for objects shared at the app level, so it names
|
||||
* one specific owner where `-` names every owner.
|
||||
*/
|
||||
function namespacePrefix(params: SplunkBaseParams): string {
|
||||
const owner = params.owner?.trim()
|
||||
@@ -152,17 +152,80 @@ export function buildSplunkFormBody(
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a Splunk JSON body, tolerating an empty one. The results endpoint answers
|
||||
* `204 No Content` with no body while a job has not produced results yet, and the job
|
||||
* control endpoint documents "Returned values: None". `Response.json()` throws on an
|
||||
* empty body, so a caller that polled a still-running job would surface
|
||||
* `Unexpected end of JSON input` instead of an empty result set.
|
||||
* Read a Splunk JSON body, tolerating only an empty one.
|
||||
*
|
||||
* The results endpoint answers `204 No Content` with no body while a job has not
|
||||
* produced results yet, and the job control endpoint documents "Returned values:
|
||||
* None". `Response.json()` throws on an empty body, so a caller that polled a
|
||||
* still-running job would surface `Unexpected end of JSON input` instead of an
|
||||
* empty result set.
|
||||
*
|
||||
* Nothing else is tolerated. Every request pins `output_mode=json`, so a
|
||||
* non-empty body that will not parse is corrupt, truncated, or not from Splunk at
|
||||
* all — a proxy's HTML error page or an SSO interstitial served with a 2xx.
|
||||
* Swallowing any of those would hand `get_search_results` an empty envelope and
|
||||
* report a lost result set as a search that legitimately matched nothing.
|
||||
*
|
||||
* Callers that must accept the documented XML dispatch envelope use
|
||||
* {@link readSplunkDispatchJson} instead; the tolerance is deliberately not
|
||||
* available on this path.
|
||||
*/
|
||||
export async function readSplunkJson(response: Response): Promise<unknown> {
|
||||
if (response.status === 204) return {}
|
||||
const text = await response.text()
|
||||
if (!text.trim()) return {}
|
||||
return JSON.parse(text)
|
||||
const body = (await response.text()).trim()
|
||||
if (!body) return {}
|
||||
return JSON.parse(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* The one XML body the reference documents: `<response><sid>...</sid></response>`,
|
||||
* optionally preceded by an XML declaration, with the self-closing `<response/>`
|
||||
* allowed for the job-control endpoints that return no value.
|
||||
*
|
||||
* The closing tag is part of the match, not just the opening one. Anchoring both
|
||||
* ends is what makes a body that was cut off mid-transfer fail instead of reading
|
||||
* as a complete envelope that simply carried nothing — which on a cancellation
|
||||
* would report a truncated response as a successful cancel.
|
||||
*/
|
||||
const SPLUNK_XML_RESPONSE =
|
||||
/^(?:<\?xml[^>]*\?>\s*)?<response(?:\s[^>]*)?(?:\/>|>([\s\S]*)<\/response>)$/i
|
||||
|
||||
/** The `sid` a dispatch envelope carries, when it carries one. */
|
||||
const SPLUNK_XML_SID = /<sid>([\s\S]*?)<\/sid>/i
|
||||
|
||||
/**
|
||||
* Read a body from the dispatching and job-control endpoints, which may answer in
|
||||
* XML rather than JSON.
|
||||
*
|
||||
* `output_mode` does not appear in the documented parameter table for these
|
||||
* endpoints, so the XML `<response><sid>...</sid></response>` is the only response
|
||||
* the reference actually promises. Throwing on it would report a request that
|
||||
* succeeded server-side as a failure — the job really was dispatched, and
|
||||
* cancelling a job really does cancel it.
|
||||
*
|
||||
* The envelope is projected onto the same `{ sid }` shape `output_mode=json`
|
||||
* produces rather than being discarded, so a dispatch that answered in XML still
|
||||
* hands back the search ID of the job it just created instead of losing it and
|
||||
* erroring after the remote work happened. A job-control response that carries no
|
||||
* `sid` yields `{}`, which is what those endpoints document ("Returned values:
|
||||
* None"). A JSON body still parses normally.
|
||||
*
|
||||
* Only that complete envelope is accepted. Anything else — an HTML error page
|
||||
* served with a 2xx, another XML document, or a truncated envelope — falls through
|
||||
* to `JSON.parse` and throws.
|
||||
*/
|
||||
export async function readSplunkDispatchJson(response: Response): Promise<unknown> {
|
||||
if (response.status === 204) return {}
|
||||
const body = (await response.text()).trim()
|
||||
if (!body) return {}
|
||||
|
||||
const envelope = SPLUNK_XML_RESPONSE.exec(body)
|
||||
if (envelope) {
|
||||
const sid = SPLUNK_XML_SID.exec(envelope[1] ?? '')?.[1]?.trim()
|
||||
return sid ? { sid } : {}
|
||||
}
|
||||
|
||||
return JSON.parse(body)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,10 +233,16 @@ export async function readSplunkJson(response: Response): Promise<unknown> {
|
||||
* the response as `<response><sid>...</sid></response>` with a single returned value,
|
||||
* `sid`, which `output_mode=json` renders as a flat `{ "sid": "..." }`.
|
||||
*
|
||||
* A missing `sid` is never a successful dispatch — it means the request produced
|
||||
* something other than a job (for example `exec_mode=oneshot`, which the reference
|
||||
* says "Does not return the search ID"). Fail loudly instead of handing the workflow
|
||||
* a null sid that only breaks two blocks later.
|
||||
* `output_mode` is not in the documented parameter table for these endpoints, so the
|
||||
* XML form is the only response the reference actually promises.
|
||||
* {@link readSplunkDispatchJson} projects that envelope onto the same `{ sid }` shape,
|
||||
* so an instance answering in XML reaches this function with a usable search ID
|
||||
* rather than an empty object.
|
||||
*
|
||||
* A missing `sid` is therefore never a successful dispatch — it means the request
|
||||
* produced something other than a job, for example `exec_mode=oneshot`, which the
|
||||
* reference says "Does not return the search ID". Fail loudly instead of handing the
|
||||
* workflow a null sid that only breaks two blocks later.
|
||||
*/
|
||||
export function requireSplunkSid(data: unknown): string {
|
||||
const sid = asString((data as { sid?: unknown })?.sid) ?? getEntryName(getSplunkEntries(data)[0])
|
||||
@@ -222,6 +291,39 @@ export function getSplunkEntries(data: unknown): SplunkAtomEntry[] {
|
||||
return entries as SplunkAtomEntry[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Project the `paging` envelope every Splunk collection response carries
|
||||
* (`{ total, perPage, offset }`) so a caller paging with `offset` can tell how
|
||||
* many entries exist in total. Without it a full page and the last page look
|
||||
* identical and there is no way to know whether to ask for another.
|
||||
*
|
||||
* `total` is the count of entries matching the request, not the size of the page
|
||||
* that was returned — `entry.length` is already that.
|
||||
*/
|
||||
export function getSplunkPaging(data: unknown): { total: number | null; offset: number | null } {
|
||||
const root = (data ?? {}) as { paging?: unknown; feed?: { paging?: unknown } }
|
||||
const paging = (root.paging ?? root.feed?.paging ?? {}) as {
|
||||
total?: unknown
|
||||
offset?: unknown
|
||||
}
|
||||
return { total: asNumber(paging.total), offset: asNumber(paging.offset) }
|
||||
}
|
||||
|
||||
/** Shared output schema for the `paging.total` projection on collection endpoints. */
|
||||
export const SPLUNK_TOTAL_OUTPUT = {
|
||||
type: 'number' as const,
|
||||
description:
|
||||
'Total number of entries matching the request, from the response paging envelope. Compare with offset to decide whether another page remains.',
|
||||
optional: true,
|
||||
}
|
||||
|
||||
/** Shared output schema for the `paging.offset` projection on collection endpoints. */
|
||||
export const SPLUNK_OFFSET_OUTPUT = {
|
||||
type: 'number' as const,
|
||||
description: 'Offset of the first entry in this page, echoed from the response paging envelope',
|
||||
optional: true,
|
||||
}
|
||||
|
||||
/** The per-entry property dictionary, or an empty object when the entry has none. */
|
||||
export function getEntryContent(entry: SplunkAtomEntry | undefined): Record<string, unknown> {
|
||||
return (entry?.content as Record<string, unknown>) ?? {}
|
||||
|
||||
Reference in New Issue
Block a user