Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Components - splunk #15966

Merged
merged 9 commits into from
Mar 26, 2025
Merged

New Components - splunk #15966

merged 9 commits into from
Mar 26, 2025

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Mar 19, 2025

Resolves #15893

Note to QA (@vunguyenhung ): Set the selfSigned prop to true for testing.

Summary by CodeRabbit

  • New Features

    • Introduced new actions for creating events, running searches, and retrieving search job statuses, enhancing user control over Splunk operations.
    • Added sources to capture new alerts, search events, and search results, enabling robust real-time monitoring with deduplication.
    • Expanded configuration options, allowing for customizable job parameters, index management, saved searches, and self-signed certificate handling.
  • Chores

    • Updated integration version and dependencies to boost performance and maintainability.

Copy link

vercel bot commented Mar 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Mar 25, 2025 9:53pm
pipedream-docs ⬜️ Ignored (Inspect) Mar 25, 2025 9:53pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Mar 25, 2025 9:53pm

Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

Walkthrough

This pull request introduces a series of new Splunk modules, including action modules (create-event, run-search, get-search-job-status) and source modules (new-alert-fired, new-search-event, new-search-result, along with a common base). The Splunk application module has been expanded with new property definitions and methods for enhanced interaction with the Splunk API. Additionally, the package configuration has been updated to increase the version and add new dependencies.

Changes

File(s) Change Summary
components/splunk/actions/…/create-event.mjs, components/splunk/actions/…/get-search-job-status.mjs, components/splunk/actions/…/run-search.mjs New action modules exported as default objects with properties (key, name, description, version, type, props) and asynchronous run methods for creating events, running search queries, and retrieving search job status.
components/splunk/sources/common/base.mjs, components/splunk/sources/new-alert-fired/new-alert-fired.mjs, components/splunk/sources/new-search-event/new-search-event.mjs, components/splunk/sources/new-search-result/new-search-result.mjs New source modules added with default exports for handling Splunk data. The common base provides shared properties and methods, while the other modules define sources with metadata, deduplication strategies, and run methods that process events, alerts, or search results.
components/splunk/splunk.app.mjs Expanded propDefinitions to include jobId, indexName, savedSearchName, and query; added multiple new methods (_baseUrl, _makeRequest, listJobs, etc.) for API interactions; removed authKeys.
components/splunk/package.json Version bumped from 0.0.1 to 0.1.0 and new dependencies (@pipedream/platform, https, md5) have been added.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant User
    participant CreateEvent as Create Event Action
    participant SplunkAPI as Splunk API
    User->>CreateEvent: Trigger "Create Event" action
    CreateEvent->>SplunkAPI: Call sendEvent(index, eventData, source, sourcetype)
    SplunkAPI-->>CreateEvent: Return success response
    CreateEvent-->>User: Emit summary message
Loading
sequenceDiagram
    participant Scheduler
    participant NewAlert as New Alert Source
    participant SplunkSys as Splunk App
    Scheduler->>NewAlert: Poll for fired alerts
    NewAlert->>SplunkSys: Call listFiredAlerts()
    SplunkSys-->>NewAlert: Return alert data
    NewAlert->>NewAlert: Generate metadata for each alert
    NewAlert-->>Scheduler: Emit alert events

Assessment against linked issues

Objective Addressed Explanation
Actions: create-event, run-search, get-search-job-status [#15893]
Sources: new-alert-instant and new-search-result [#15893]

Suggested labels

action, trigger / source

Suggested reviewers

  • jcortes

Poem

I'm a little rabbit, hopping through the code,
With Splunk actions and sources easing my load.
Events send and alerts chime, a merry parade,
Search queries and results elegantly displayed.
Through the forest of functions I softly roam,
In the garden of logic I've found my home.
Hoppity cheers to this PR—code blooms like a poem!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/splunk/sources/new-alert-fired/new-alert-fired.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

components/splunk/splunk.app.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (13)
components/splunk/actions/create-event/create-event.mjs (2)

44-57: Add error handling to the run method

Consider adding try/catch block around the API call to handle potential errors gracefully and provide better error messages to users.

 async run({ $ }) {
+  try {
     const response = await this.splunk.sendEvent({
       $,
       selfSigned: this.selfSigned,
       params: {
         index: this.indexName,
         source: this.source,
         sourcetype: this.sourcetype,
       },
       data: this.eventData,
     });
     $.export("$summary", `Event sent to index ${this.indexName} successfully`);
     return response;
+  } catch (error) {
+    $.export("$summary", `Failed to send event: ${error.message}`);
+    throw error;
+  }
 },

55-55: Include more details in the success summary

Consider adding more context to the success message to help users understand what was sent.

-    $.export("$summary", `Event sent to index ${this.indexName} successfully`);
+    $.export("$summary", `Event sent to index "${this.indexName}" successfully${this.source ? ` with source "${this.source}"` : ""}`);
components/splunk/actions/get-search-job-status/get-search-job-status.mjs (1)

27-35: Add error handling to the run method

Consider adding try/catch block around the API call to handle potential errors gracefully and provide better error messages to users.

 async run({ $ }) {
+  try {
     const response = await this.splunk.getSearchJobStatus({
       $,
       selfSigned: this.selfSigned,
       jobId: this.jobId,
     });
     $.export("$summary", `Successfully retrieved status for job ID ${this.jobId}`);
     return response;
+  } catch (error) {
+    $.export("$summary", `Failed to retrieve job status: ${error.message}`);
+    throw error;
+  }
 },
components/splunk/actions/run-search/run-search.mjs (3)

32-32: Fix formatting in latestTime description

There's extra leading whitespace in the latestTime description that should be removed for consistency with the earliestTime description.

-      description: "  Specify a time string. Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string. Refer to [Time modifiers](https://docs.splunk.com/Documentation/Splunk/9.4.1/SearchReference/SearchTimeModifiers) for search for information and examples of specifying a time string.",
+      description: "Specify a time string. Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string. Refer to [Time modifiers](https://docs.splunk.com/Documentation/Splunk/9.4.1/SearchReference/SearchTimeModifiers) for search for information and examples of specifying a time string.",

36-48: Add error handling to the run method

Consider adding try/catch block around the API call to handle potential errors gracefully and provide better error messages to users.

 async run({ $ }) {
+  try {
     const response = await this.splunk.executeSearchQuery({
       $,
       selfSigned: this.selfSigned,
       data: {
         search: this.query,
         earliest_time: this.earliestTime,
         latest_time: this.latestTime,
       },
     });
     $.export("$summary", `Executed Splunk search query: ${this.query}`);
     return response;
+  } catch (error) {
+    $.export("$summary", `Failed to execute search query: ${error.message}`);
+    throw error;
+  }
 },

46-46: Include more context in success summary

Consider adding more information to the success message, such as the time range if specified.

-    $.export("$summary", `Executed Splunk search query: ${this.query}`);
+    $.export("$summary", `Executed Splunk search query: ${this.query}${this.earliestTime ? ` from ${this.earliestTime}` : ""}${this.latestTime ? ` to ${this.latestTime}` : ""}`);
components/splunk/sources/new-search-result/new-search-result.mjs (1)

13-19: Consider enhancing the metadata generation with result timestamps.

The generateMeta method currently uses Date.now() for the timestamp, which represents when the event was processed rather than when it occurred. If the Splunk result contains its own timestamp, consider using that for more accurate event sequencing.

generateMeta(result) {
  return {
    id: result.sid,
    summary: `New Search Results with SID: ${result.sid}`,
-   ts: Date.now(),
+   ts: result._time ? new Date(result._time).getTime() : Date.now(),
  };
},
components/splunk/sources/new-search-event/new-search-event.mjs (1)

14-20: Enhance event metadata for better information and deduplication.

The current metadata generation has several areas for improvement:

  1. The summary is generic and could be more informative
  2. Using MD5 of the entire event might not be the most efficient approach if a unique field is available
  3. The timestamp should ideally come from the event itself when available
generateMeta(event) {
+  // Extract a more meaningful summary from the event if possible
+  const eventName = event.name || event._raw?.slice(0, 30) || "Unknown";
+  
+  // Use a specific field if available, or fall back to MD5 hash
+  const eventId = event.id || event._cd || md5(JSON.stringify(event));
+  
+  // Use event timestamp if available, fall back to current time
+  const eventTime = event._time ? new Date(event._time).getTime() : Date.now();
+  
  return {
-    id: md5(JSON.stringify(event)),
-    summary: "New Search Event",
-    ts: Date.now(),
+    id: eventId,
+    summary: `New Search Event: ${eventName}`,
+    ts: eventTime,
  };
},
components/splunk/sources/new-alert-fired/new-alert-fired.mjs (1)

13-19: Use alert timestamp for more accurate event sequencing.

The current implementation uses the current time for the event timestamp rather than the actual time when the alert was triggered. If the alert object contains its own timestamp, it would be more accurate to use that.

generateMeta(alert) {
+  // Use the alert's trigger time if available
+  const alertTime = alert.trigger_time || alert.triggered_at || Date.now();
  return {
    id: alert.id,
    summary: `New Alert Fired: ${alert.name}`,
-   ts: Date.now(),
+   ts: alertTime,
  };
},
components/splunk/splunk.app.mjs (4)

8-74: Fix minor spelling issue in the documentation.

In the description for query (line 73), "sytax" should be "syntax". This helps keep the documentation polished and clear.

- description: "The Splunk search query. Example: `search *`. [See the documentation](https://docs.splunk.com/Documentation/Splunk/9.4.1/SearchReference/Search) for more information about search command sytax."
+ description: "The Splunk search query. Example: `search *`. [See the documentation](https://docs.splunk.com/Documentation/Splunk/9.4.1/SearchReference/Search) for more information about search command syntax."

65-69: Document security implications.

While allowing self-signed certificates (via selfSigned) is sometimes necessary, it poses security risks in production environments. Consider providing a cautionary note in user-facing documentation to emphasize these risks and encourage secure certificates whenever possible.


105-128: Use consistent naming in resource methods.

While the listJobs, listIndexes, listSavedSearches, and listFiredAlerts methods have uniform naming, consider a shared pattern for request parameters (e.g., passing opts consistently). This keeps the API predictable.


160-166: Validate input before sending events.

sendEvent posts data to Splunk. Consider adding minimal validation (e.g., verifying a non-empty payload) to prevent unintended or malformed events.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d7c0ac and c6094bf.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • components/splunk/actions/create-event/create-event.mjs (1 hunks)
  • components/splunk/actions/get-search-job-status/get-search-job-status.mjs (1 hunks)
  • components/splunk/actions/run-search/run-search.mjs (1 hunks)
  • components/splunk/package.json (2 hunks)
  • components/splunk/sources/common/base.mjs (1 hunks)
  • components/splunk/sources/new-alert-fired/new-alert-fired.mjs (1 hunks)
  • components/splunk/sources/new-search-event/new-search-event.mjs (1 hunks)
  • components/splunk/sources/new-search-result/new-search-result.mjs (1 hunks)
  • components/splunk/splunk.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (9)
components/splunk/package.json (2)

3-3: Version update looks good

The version bump from 0.0.1 to 0.1.0 follows semantic versioning practices, correctly indicating this is a minor feature update rather than just a patch.


15-18:

✅ Verification successful

Verify necessity of the 'https' dependency

The 'https' module is a native Node.js module that should be available without explicit installation. Consider removing this dependency unless you're using a specific version or feature not available in the native module.

Additionally, note that MD5 is considered cryptographically weak for security-sensitive applications. If you're using it for non-security purposes like generating unique identifiers, that's acceptable.


🏁 Script executed:

#!/bin/bash
# Check if the 'https' module is used in a non-standard way in the codebase

echo "Checking for custom usage of 'https' module..."
rg -A 3 -B 3 "import.*https" --type js

Length of output: 2741


Action: Remove explicit installation of the native 'https' module

After verifying the codebase, there’s no evidence of any non-standard or custom usage of the 'https' module that would justify keeping its explicit installation in the dependencies. Since Node.js provides 'https' natively, it's safe to remove it from components/splunk/package.json unless a specific version or extended functionality is actually required. Additionally, please ensure that the use of MD5 (if any) is limited to non-security-related purposes, due to its known cryptographic weaknesses.

  • File: components/splunk/package.json (Lines 15–18)
components/splunk/actions/create-event/create-event.mjs (1)

1-58: Well-structured new action module

The Create Event action is well-organized, following Pipedream's component patterns with appropriate documentation links, clear property definitions, and a clean implementation.

components/splunk/actions/get-search-job-status/get-search-job-status.mjs (1)

1-36: Well-structured new action module

The Get Search Job Status action is well-organized, following Pipedream's component patterns with appropriate documentation links, clear property definitions, and a clean implementation.

components/splunk/actions/run-search/run-search.mjs (1)

1-49: Well-structured new action module

The Run Search action is well-organized, following Pipedream's component patterns with appropriate documentation links, clear property definitions, and a clean implementation.

components/splunk/sources/new-alert-fired/new-alert-fired.mjs (1)

21-38:

✅ Verification successful

Limit and filter alert processing for better performance.

The current implementation collects all alerts without any filtering or limits, which could lead to processing a large number of alerts and impact performance.

async run() {
+  // Use pagination parameters to limit and filter alerts
+  const paginationParams = {
+    count: 20, // Process a reasonable number of alerts
+    offset: 0,
+    // Only retrieve relatively recent alerts
+    timeRange: "-24h",
+  };
+
  const results = this.splunk.paginate({
    resourceFn: this.splunk.listFiredAlerts,
    args: {
      selfSigned: this.selfSigned,
+     ...paginationParams,
    },
  });

  const alerts = [];
+ let count = 0;
  for await (const item of results) {
    alerts.push(item);
+   count++;
+   // Additional safeguard to prevent processing too many alerts
+   if (count >= 50) break;
  }

  alerts.forEach((alert) => {
    const meta = this.generateMeta(alert);
    this.$emit(alert, meta);
  });
},

🏁 Script executed:

#!/bin/bash
# Check if the Splunk listFiredAlerts method supports pagination and time range parameters
rg -A 10 "listFiredAlerts\s*\([^)]*\)\s*{" components/splunk/

Length of output: 189


Below is a revised shell script using a corrected regex pattern that should properly match the definition of the listFiredAlerts method. Please run the script to manually verify whether this method supports additional pagination parameters (like count, offset, and a timeRange) as suggested in the review comment.

Next Steps:

  • Run the revised shell script to check the method’s signature.
  • Based on the output, verify that the Splunk API indeed supports the additional parameters before proceeding with the refactor.

Once you confirm the method supports these parameters, you can safely adopt the refactoring changes suggested in the review.


🏁 Script executed:

#!/bin/bash
# Corrected regex pattern to search for the definition of listFiredAlerts
rg -A 10 'listFiredAlerts\s*\([^)]*\)\s*\{' components/splunk/

Length of output: 827


Action Required: Confirm Pagination Parameters in Alert Processing

After verifying the implementation of listFiredAlerts in components/splunk/splunk.app.mjs, we see that the method accepts an opts object and spreads its properties into the request. This confirms that passing additional options (including pagination parameters like count, offset, and timeRange) is supported.

  • Verified Location:

    • components/splunk/splunk.app.mjs – The listFiredAlerts(opts = {}) method spreads opts into the request.
  • Key Considerations:

    • The suggested approach to limit and filter alerts by spreading paginationParams into the arguments of listFiredAlerts is valid.
    • The additional safeguard in the loop (using a counter and breaking after 50 alerts) is an extra measure to protect against excessive processing.

Please ensure that the backend API correctly interprets these pagination parameters. Once confirmed, you can incorporate the diff snippet below to improve performance by limiting alert processing:

 async run() {
+  // Use pagination parameters to limit and filter alerts
+  const paginationParams = {
+    count: 20, // Process a reasonable number of alerts at once
+    offset: 0,
+    // Only retrieve alerts from the past 24 hours
+    timeRange: "-24h",
+  };
 
   const results = this.splunk.paginate({
     resourceFn: this.splunk.listFiredAlerts,
     args: {
       selfSigned: this.selfSigned,
+      ...paginationParams,
     },
   });
 
   const alerts = [];
+  let count = 0;
   for await (const item of results) {
     alerts.push(item);
+    count++;
+    // Additional safeguard to prevent processing too many alerts
+    if (count >= 50) break;
   }
 
   alerts.forEach((alert) => {
     const meta = this.generateMeta(alert);
     this.$emit(alert, meta);
   });
 },
components/splunk/splunk.app.mjs (3)

80-104: Review certificate-rejection override for potential security impact.

The _makeRequest() method sets rejectUnauthorized: false if selfSigned is true. This can allow MITM attacks. If this is only for local dev or test scenarios, confirm it’s properly documented or restricted from production usage.


129-159: Confirm request methods.

executeSearchQuery uses POST, but getSearchJobStatus, getSearchResults, and getSearchEvents use GET by default. Ensure both the method and endpoint path align with Splunk’s expectations (e.g., older Splunk versions might differ in endpoints).


77-79:

❓ Verification inconclusive

Ensure base URL correctness.

The _baseUrl() method constructs a URL that appends :${this.$auth.api_port}. Confirm that user-supplied values don’t inadvertently include a port, which could cause malformed URLs.


🏁 Script executed:

#!/bin/bash
# Searching for references to `api_url` in the repo to confirm usage consistency.
rg -A 3 '\$auth\.api_url'

Length of output: 2818


Attention: Validate API URL Inputs in Splunk App

Please double-check that the value provided in this.$auth.api_url does not already include a port. Unlike other components that simply append additional path segments, the Splunk app explicitly concatenates :${this.$auth.api_port} to the URL when constructing the base endpoint. If the API URL already embeds a port, it could yield a malformed URL (e.g., duplicating port information). Ensure that any user-supplied values are sanitized or validated accordingly.

  • Location: components/splunk/splunk.app.mjs (Lines 77-79)

luancazarine
luancazarine previously approved these changes Mar 19, 2025
Copy link
Collaborator

@luancazarine luancazarine left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @michelle0927, LGTM! Ready for QA!

@vunguyenhung
Copy link
Collaborator

Hi @michelle0927, could you remove the Self-signed prop on each action/source and use the variable this.splunk.$auth.self_signed on the app? I've recently added this so that end-user only need to specify self_signed once

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
components/splunk/sources/common/base.mjs (1)

16-25: 🛠️ Refactor suggestion

Enhance getRecentJobIds() to Filter Jobs

The current implementation fetches all jobs, which can degrade performance. To mitigate this, update the method to only fetch jobs within a recent time window and limit the number of results.

async getRecentJobIds() {
+  // Add parameters to filter jobs by time and limit results
+  const timeRange = {
+    // Default to jobs from the last hour
+    earliestTime: "-1h",
+    latestTime: "now",
+  };
  
  const results = this.splunk.paginate({
    resourceFn: this.splunk.listJobs,
    args: {
+     ...timeRange,
+     count: 20, // Limit the number of jobs to process
+     // Use the auth property instead of individual selfSigned parameters
    },
  });
  const jobIds = [];
  for await (const job of results) {
    jobIds.push(job.content.sid);
  }
  return jobIds;
},
🧹 Nitpick comments (4)
components/splunk/sources/new-alert-fired/test-event.mjs (1)

1-30: Consider anonymizing potentially sensitive information in test data.

The test event contains what appears to be a real IP address (44.210.81.125) in the host field. While this may be intentional for testing, it's generally better practice to use reserved IP ranges for documentation and test data (like 192.0.2.x, 198.51.100.x, or 203.0.113.x from TEST-NET ranges).

Also note that several fields like sid, search_name, and owner are empty. This is likely intentional for a test event, but ensure these will be populated correctly in production.

components/splunk/actions/run-search/run-search.mjs (2)

18-25: Add error handling to run method.

The current implementation doesn't include any error handling. If the Splunk API call fails, the action will fail without providing clear error information to the user.

Add try/catch block to handle potential errors:

async run({ $ }) {
+  try {
    const response = await this.splunk.executeSearchQuery({
      $,
      name: this.name,
    });
    $.export("$summary", `Executed Splunk search: ${this.name}`);
    return response;
+  } catch (error) {
+    $.export("$summary", `Failed to execute Splunk search: ${this.name}`);
+    throw error;
+  }
},

11-16: Prop name doesn't match propDefinition name.

There might be confusion between the prop name name and the propDefinition name savedSearchName. Consider using consistent naming to improve code clarity.

name: {
  propDefinition: [
    splunk,
    "savedSearchName",
  ],
+  // Optional: Add a label or description to clarify this represents the saved search name
},
components/splunk/sources/new-search-result/new-search-result.mjs (1)

23-29: Improve generateMeta method with more meaningful identification.

The current implementation uses result.id which may not exist or be meaningful. Consider using more specific identifiers from the Splunk job content.

generateMeta(result) {
  return {
-    id: result.id,
+    id: result.content?.sid || result.id,
-    summary: `New Search with ID: ${result.id}`,
+    summary: `New Search Results: ${result.content?.label || result.content?.sid || 'Unknown'}`,
    ts: Date.now(),
  };
},
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c6094bf and d0170bf.

📒 Files selected for processing (9)
  • components/splunk/actions/create-event/create-event.mjs (1 hunks)
  • components/splunk/actions/get-search-job-status/get-search-job-status.mjs (1 hunks)
  • components/splunk/actions/run-search/run-search.mjs (1 hunks)
  • components/splunk/sources/common/base.mjs (1 hunks)
  • components/splunk/sources/new-alert-fired/new-alert-fired.mjs (1 hunks)
  • components/splunk/sources/new-alert-fired/test-event.mjs (1 hunks)
  • components/splunk/sources/new-search-event/new-search-event.mjs (1 hunks)
  • components/splunk/sources/new-search-result/new-search-result.mjs (1 hunks)
  • components/splunk/splunk.app.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • components/splunk/actions/get-search-job-status/get-search-job-status.mjs
  • components/splunk/actions/create-event/create-event.mjs
  • components/splunk/sources/new-search-event/new-search-event.mjs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (8)
components/splunk/actions/run-search/run-search.mjs (1)

18-24:

✅ Verification successful

Implement selfSigned property as requested in PR comments.

Per the PR comments, you should use this.splunk.$auth.self_signed within the application instead of setting the selfSigned property on each action or source. This will streamline the process and allow end-users to specify the option only once.

Update the executeSearchQuery call to use the auth property:

const response = await this.splunk.executeSearchQuery({
  $,
  name: this.name,
+  // Use the auth property instead of individual selfSigned parameters
+  // as requested in PR comments by vunguyenhung
});

Let's verify if the executeSearchQuery method in the Splunk app already handles the self_signed property from auth:


🏁 Script executed:

#!/bin/bash
# Check how executeSearchQuery is implemented and if it uses $auth.self_signed
rg -A 10 "executeSearchQuery\s*\(" components/splunk/splunk.app.mjs

Length of output: 310


Action: Use global auth for self-signed configuration in Splunk search actions

Based on our verification, the executeSearchQuery implementation in components/splunk/splunk.app.mjs simply spreads any options provided into its request. This confirms that the function will honor any self-signed configuration if passed via the global auth (this.splunk.$auth.self_signed). Therefore, instead of supplying a selfSigned parameter locally, you should rely on the auth property.

  • In components/splunk/actions/run-search/run-search.mjs (lines 18‑24), remove any local selfSigned handling and ensure that executeSearchQuery is called without an explicit selfSigned parameter.
  • Confirm that this.splunk.$auth.self_signed is set up globally so that it applies to all requests without duplication.

Please update the code accordingly and verify that the auth property is correctly configured in the Splunk module.

components/splunk/sources/new-search-result/new-search-result.mjs (1)

31-47: Improve error handling and consider result limits.

The current implementation lacks error handling when fetching search results and doesn't limit the number of jobs processed, which could impact performance.

async run() {
-  const jobs = await this.getRecentJobs();
+  try {
+    // Limit the number of jobs to process to avoid performance issues
+    const jobs = await this.getRecentJobs();
+    const jobsToProcess = jobs.slice(0, 10); // Process only the 10 most recent jobs
  
-    for (const job of jobs) {
+    for (const job of jobsToProcess) {
      if (job.content?.resultCount > 0) {
+        try {
          const { results } = await this.splunk.getSearchResults({
            jobId: job.content.sid,
+            // Use the auth property instead of individual selfSigned parameters
          });
          if (results) {
            job.results = results;
          }
+        } catch (error) {
+          console.log(`Error retrieving results for job ${job.content.sid}:`, error.message);
+        }
      }
    }
  
-    jobs.forEach((result) => {
+    jobsToProcess.forEach((result) => {
      const meta = this.generateMeta(result);
      this.$emit(result, meta);
    });
+  } catch (error) {
+    console.error("Error processing search results:", error);
+  }
},
components/splunk/sources/new-alert-fired/new-alert-fired.mjs (1)

1-36: LGTM! Good implementation of the Splunk alert source.

The source module is well-structured with good separation of concerns between the metadata generation and event processing. It correctly follows the pattern of emitting events with metadata and has basic validation to prevent processing empty requests.

components/splunk/splunk.app.mjs (5)

1-3: Verify the https module usage

The https module is imported and used for creating an agent to handle self-signed certificates. This corrects the previous comment flagging it as an unused import.


8-61: Well-structured prop definitions with dynamic options.

The prop definitions are well organized and include descriptive labels and documentation links. I particularly like the implementation of the async options for dropdowns that fetch data from Splunk.


63-89: Good implementation of centralized request handling with self-signed cert support.

The _makeRequest method properly centralizes the API request logic and leverages this.$auth.self_signed for handling self-signed certificates, which aligns with the suggestion from vunguyenhung to use this auth property instead of setting it on individual components.


90-153: Well-organized API methods with consistent patterns.

The methods for interacting with the Splunk API follow a consistent pattern, making the code more maintainable. Each method properly leverages the centralized _makeRequest function with appropriate path and parameter handling.


154-181: Enhance error handling in pagination logic.

If paging.total or entry are missing from the API response, this code could throw errors. Consider adding validation or try/catch to handle unexpected responses from Splunk.

async *paginate({
  resourceFn,
  args,
  max,
}) {
  args = {
    ...args,
    params: {
      ...args?.params,
      count: DEFAULT_LIMIT,
    },
  };
  let hasMore, count = 0;
  try {
    do {
      const {
        entry = [], paging = { total: 0 },
      } = await resourceFn(args);
      for (const item of entry) {
        yield item;
        count++;
        if (max && count >= max) {
          return;
        }
      }
      hasMore = paging.total > count;
+     // Ensure offset is initialized if it doesn't exist
+     args.params.offset = (args.params.offset || 0) + args.params.count;
-     args.params.offset += args.params.count;
    } while (hasMore);
+  } catch (err) {
+    console.error("Error during pagination:", err);
+    throw err;
+  }
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
components/splunk/splunk.app.mjs (2)

9-61: Consider extracting shared logic in prop definitions.
Each prop definition (e.g. jobId, indexName, savedSearchName) fetches lists from Splunk with nearly identical logic. You could reduce repetition by creating a helper function that accepts a resource-fetching method (like listJobs, listIndexes, etc.) and returns the mapped results.


59-59: Correct the “sytax” typo.

- description: "The Splunk search query. Example: `search *`. [See the documentation](... more information about search command sytax.",
+ description: "The Splunk search query. Example: `search *`. [See the documentation](... more information about search command syntax.",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d0170bf and 061a60d.

📒 Files selected for processing (2)
  • components/splunk/sources/new-alert-fired/new-alert-fired.mjs (1 hunks)
  • components/splunk/splunk.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Verify TypeScript components
🔇 Additional comments (5)
components/splunk/splunk.app.mjs (3)

1-3: Imports look good.
No issues with using both @pipedream/platform’s axios and the built-in https module since the latter is leveraged for custom SSL handling.


84-88: Be cautious with ignoring SSL verification.
Disabling certificate checks can expose users to potential man-in-the-middle attacks. Confirm this is strictly for testing or trusted internal networks.


171-198: Enhance error handling in the pagination logic.
If paging.total or entry are missing, the code could break. Consider a try/catch or validation of Splunk responses to improve robustness.

components/splunk/sources/new-alert-fired/new-alert-fired.mjs (2)

49-56: Validate _time in generateMeta().
If alert.result._time is missing or not numeric, you could end up with NaN. Consider gracefully handling invalid or unexpected data to avoid partial or misleading results.


58-66: The “run” method looks good.
Emitting the alert data with metadata is straightforward. No additional concerns here.

@michelle0927
Copy link
Collaborator Author

/approve

@michelle0927 michelle0927 merged commit b79f82f into master Mar 26, 2025
11 checks passed
@michelle0927 michelle0927 deleted the issue-15893 branch March 26, 2025 14:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Components] splunk
3 participants