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

Add security rules for JavaScript settings and base URL in Swift web views #48

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

ESS-ENN
Copy link
Collaborator

@ESS-ENN ESS-ENN commented Oct 28, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new security rules for webviews to enhance JavaScript handling and base URL configuration.
    • Added utility functions to enforce best practices in JavaScript settings and base URL assignments.
  • Tests

    • Implemented new test cases to validate JavaScript settings and base URL configurations in webviews, ensuring compliance with security standards.
    • Created snapshot configurations for testing JavaScript execution and base URL loading scenarios.

Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

Two new security rules have been added to YAML configuration files for Swift web views: one for managing JavaScript settings and another for ensuring proper base URL configurations. The JavaScript rule warns against enabling JavaScript unnecessarily, while the base URL rule addresses the risk of setting it to nil. Additionally, corresponding snapshot configurations and test cases have been created to validate these rules and their implementations in both WKWebView and UIWebView.

Changes

File Path Change Summary
rules/swift/security/swift-webview-config-allows-js-swift.yml New rule swift-webview-config-allows-js-swift added; includes utility function match_pattern_upgradeKnownHostsToHTTPS.
rules/swift/security/swift-webview-config-base-url-swift.yml New rule swift-webview-config-base-url-swift added to enforce baseURL settings.
tests/__snapshots__/swift-webview-config-allows-js-swift-snapshot.yml New snapshot for JavaScript settings in WKWebView added.
tests/__snapshots__/swift-webview-config-base-url-swift-snapshot.yml New snapshots for testing UIWebView behavior with nil base URL added.
tests/swift/swift-webview-config-allows-js-swift-test.yml New test case swift-webview-config-allows-js-swift added for validating JavaScript settings.
tests/swift/swift-webview-config-base-url-swift-test.yml New test case swift-webview-config-base-url-swift added to validate web view usage.

Poem

In the webview's dance, oh so bright,
JavaScript now treads with caution, just right.
Base URLs set, no more nil in sight,
Security's embrace, a developer's delight.
Hopping through code, with joy we unite,
For safer apps, let our changes take flight! 🐇✨


🪧 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 resolve resolve all the CodeRabbit review comments.
  • @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.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add security rules for JavaScript settings and base URL in Swift web views Oct 28, 2024
Copy link

@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: 4

🧹 Outside diff range and nitpick comments (10)
tests/swift/swift-webview-config-base-url-swift-test.yml (2)

3-5: Consider adding more comprehensive valid test cases.

While the current valid case tests WKWebView with nil baseURL, it would be beneficial to include additional valid cases:

  1. WKWebView with a proper baseURL
  2. WKWebView with different content loading methods

This would help ensure the rule doesn't generate false positives.

Example addition:

valid:
  - |
    let webview2 = WKWebView(...)
    webview2.loadHTMLString(someHtmlString, baseURL: nil)
+ - |
+   let webview3 = WKWebView(...)
+   webview3.loadHTMLString(someHtmlString, baseURL: URL(string: "https://example.com"))

1-12: Consider adding test cases for edge cases and security scenarios.

While the current test cases cover basic usage, consider adding tests for:

  1. Handling of about:blank URLs
  2. File URL handling
  3. Custom URL schemes
  4. Data URL handling

These scenarios are common attack vectors in web view implementations.

Would you like me to provide example test cases for these security-critical scenarios?

tests/swift/swift-webview-config-allows-js-swift-test.yml (1)

9-18: Consider adding more invalid test cases for comprehensive coverage.

The current invalid cases cover basic scenarios, but consider adding tests for:

  1. Missing configuration entirely
  2. Null/nil preferences
  3. Mixed usage of both APIs in the same configuration

Example additional test case:

  - |
    let config = WKWebViewConfiguration()
    // Missing preferences configuration entirely
  - |
    let config = WKWebViewConfiguration()
    config.defaultWebpagePreferences = nil
rules/swift/security/swift-webview-config-base-url-swift.yml (2)

1-12: Consider enhancing the security metadata.

While the metadata is well-structured, consider the following improvements:

  1. The severity level might need to be elevated to "error" since origin abuse can lead to serious security vulnerabilities
  2. The message could explicitly mention potential attack vectors (e.g., XSS, data theft)
  3. Add more specific references such as:
    • OWASP Top 10 Mobile risks
    • Apple's WebKit security documentation

1-65: Consider expanding rule scope for WKWebView.

While this rule correctly addresses baseURL security for UIWebView, note that:

  1. UIWebView is deprecated and should be migrated to WKWebView
  2. Similar baseURL security concerns apply to WKWebView
  3. The rule could be expanded to cover both view types or include a separate rule for WKWebView

Consider adding deprecation warnings when UIWebView is detected and suggesting migration to WKWebView.

tests/__snapshots__/swift-webview-config-base-url-swift-snapshot.yml (2)

1-114: Consider adding positive test cases

The current snapshots only demonstrate the unsafe patterns (negative cases). Consider adding positive test cases that show the correct usage with:

  1. WKWebView instead of UIWebView
  2. Proper baseURL configuration
  3. Secure content loading patterns

This would provide a complete picture of both what to avoid and what to do instead.

Would you like me to help create additional snapshot test cases demonstrating the secure patterns?


6-58: Improve test coverage with additional assertions

While the current labels provide good coverage for method calls and parameters, consider adding assertions for:

  1. Error handling scenarios
  2. Different baseURL values (not just nil)
  3. Various content types and encodings

This would help ensure the security rule catches all potential misconfigurations.

Also applies to: 62-114

rules/swift/security/swift-webview-config-allows-js-swift.yml (3)

1-11: Fix typo in rule message: "privelege" → "privilege"

The rule message contains a spelling error that should be corrected for professionalism.

-  the principle of least privelege.
+  the principle of least privilege.

12-108: Add documentation for the pattern matching logic

The complex AST pattern matching would benefit from documentation explaining:

  • What code patterns are being matched
  • Examples of code that would trigger the rule
  • Examples of code that would not trigger the rule

Add a comment block above the utils section explaining the pattern matching logic:

# Detects JavaScript enabled in WebViews through:
# 1. Direct property assignments:
#    webView.configuration.preferences.javaScriptEnabled = true
#    webView.configuration.preferences.allowsContentJavaScript = true
# 2. Property declarations with WKPreferences/WKWebpagePreferences initialization
#
# Does not flag when JavaScript is explicitly disabled or when the property
# is not set (defaults to false).
#
# Example matches:
#   let preferences = WKPreferences()
#   preferences.javaScriptEnabled = true
#
# Example non-matches:
#   let preferences = WKPreferences()
#   preferences.javaScriptEnabled = false
utils:

108-110: Consider adding severity conditions

The rule currently treats all JavaScript enabling equally. Consider adding severity conditions based on the context:

  • High severity: JavaScript enabled globally
  • Warning: JavaScript enabled for specific URLs

Would you like me to propose a pattern for contextual severity?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3195f93 and 40dc9d7.

📒 Files selected for processing (6)
  • rules/swift/security/swift-webview-config-allows-js-swift.yml (1 hunks)
  • rules/swift/security/swift-webview-config-base-url-swift.yml (1 hunks)
  • tests/snapshots/swift-webview-config-allows-js-swift-snapshot.yml (1 hunks)
  • tests/snapshots/swift-webview-config-base-url-swift-snapshot.yml (1 hunks)
  • tests/swift/swift-webview-config-allows-js-swift-test.yml (1 hunks)
  • tests/swift/swift-webview-config-base-url-swift-test.yml (1 hunks)
🔇 Additional comments (9)
tests/swift/swift-webview-config-base-url-swift-test.yml (2)

1-2: LGTM! Clear and descriptive test configuration ID.

The configuration ID accurately reflects its purpose for Swift web view base URL validation.


6-12: Verify the completeness of invalid test cases.

The test cases correctly identify UIWebView usage as invalid. However, let's verify if we're covering all potential misuse patterns.

Additionally, consider adding comments to explain why these cases are invalid:

invalid:
  - |
+   # UIWebView is deprecated and poses security risks
    let webview = UIWebView(...)
    webview.loadHTMLString(someHtmlString, baseURL: nil)
  - |
+   # Using nil baseURL with UIWebView can lead to origin abuse
    let webview3 = UIWebView(...)
    webview3.load(data, mimetype: "application/json", textEncodingName: "UTF8", baseURL: nil)
✅ Verification successful

Test cases are comprehensive and well-structured

The current test cases adequately cover the main security concerns with UIWebView:

  • They test both loadHTMLString and load methods with nil baseURL
  • The rule implementation properly detects these patterns through AST matching
  • The security message clearly explains the risk of origin abuse
  • The rule references relevant CWE-272 and MASVS standards

The suggestion to add comments is not necessary as the rule already includes detailed documentation in its message and note fields.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other UIWebView loading methods that should be tested
rg "UIWebView.*load" --type swift

Length of output: 184


Script:

#!/bin/bash
# Let's first check what Swift files exist in the repository
fd -e swift

# Then let's search for any UIWebView related patterns more broadly
rg "UIWebView" -l

Length of output: 218


Script:

#!/bin/bash
# Let's examine the content of these files to understand the full context
cat tests/swift/swift-webview-config-base-url-swift-test.yml rules/swift/security/swift-webview-config-base-url-swift.yml tests/__snapshots__/swift-webview-config-base-url-swift-snapshot.yml

Length of output: 5062

tests/swift/swift-webview-config-allows-js-swift-test.yml (1)

1-1: LGTM! Clear and descriptive test case identifier.

The test case ID follows a clear naming convention and accurately reflects its purpose.

rules/swift/security/swift-webview-config-base-url-swift.yml (1)

32-45: Enhance nil detection patterns.

The current pattern only catches literal nil assignments but might miss:

  1. Implicit nil (e.g., optional parameters)
  2. Variables containing nil
  3. Optional chaining results

Let's verify if there are such cases in the codebase:

✅ Verification successful

The current pattern is sufficient for its security purpose

Based on the search results, we can see that the pattern is correctly targeting the security concern of using nil baseURL in WebView configurations. The test files show that the primary use case is indeed direct nil assignments (baseURL: nil), which is precisely what the current pattern detects. While there could theoretically be other ways to pass nil values, the pattern focuses on the most common and direct security risk.

The test cases in the codebase demonstrate:

  • Direct nil assignments in loadHTMLString calls
  • Similar patterns in related methods like load(data, ...) with baseURL: nil

Since this is a security rule specifically targeting the unsafe practice of explicitly setting nil base URLs in WebView configurations, the current pattern appropriately captures the intended violations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential missed nil assignments in web view configurations

# Look for optional parameters and nil assignments in web view related code
ast-grep --pattern 'loadHTMLString($_: String, baseURL: $_?)'

# Look for variable assignments that might contain nil
rg -l "baseURL\s*=\s*\w+" | xargs rg "let\s+\w+\s*:\s*URL\?"

Length of output: 126


Script:

#!/bin/bash
# Let's try a different approach to find WebView configurations and nil assignments

# Look for WebView configurations with baseURL
rg -A 5 "loadHTMLString.*baseURL"

# Search for WebView related code with optional URL types
rg "URL\?" -A 3 -B 3

# Find any WebView configuration patterns
ast-grep --pattern 'webView.loadHTMLString($$$)'

# Look for optional URL declarations and assignments
ast-grep --pattern 'var $_: URL?'

Length of output: 1687

tests/__snapshots__/swift-webview-config-allows-js-swift-snapshot.yml (3)

1-2: LGTM: Clear snapshot identifier.

The snapshot file is properly identified for the Swift web view JavaScript configuration security rule.


3-51: Verify the WKPreferences JavaScript configuration pattern.

The snapshot correctly captures the pattern for detecting JavaScript enablement in WKPreferences, including:

  • Primary label on the direct JavaScript enablement
  • Secondary labels for precise AST matching
  • Proper character positions for accurate source mapping

This will help identify instances where JavaScript is explicitly enabled, which is the security concern being addressed.

Let's verify this pattern against the codebase:

✅ Verification successful

Pattern verification successful for WKPreferences JavaScript configuration

The pattern correctly identifies instances of JavaScript enablement in WKPreferences, as evidenced by matching occurrences in both test and snapshot files. The pattern's structure accurately captures:

  • The WKPreferences initialization
  • Explicit JavaScript enablement via the javaScriptEnabled property
  • Proper source mapping with accurate character positions

The matches found validate that this security rule is necessary for detecting potentially risky JavaScript configurations in WebKit preferences.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the prevalence of JavaScript enablement in WKPreferences
# Expected: Find instances where JavaScript is being enabled, confirming the need for this security rule

# Search for WKPreferences JavaScript configuration
rg -U "let.*WKPreferences.*\n.*javaScriptEnabled.*=.*true" 

Length of output: 474


52-101: Verify the WKWebpagePreferences JavaScript configuration pattern.

The snapshot correctly captures an alternative pattern for JavaScript enablement through WKWebpagePreferences, including:

  • Primary label on allowsContentJavaScript enablement
  • Secondary labels for precise AST matching
  • Configuration chain with WKWebViewConfiguration

This comprehensively covers another vector for JavaScript enablement.

Let's verify this pattern against the codebase:

✅ Verification successful

The WKWebpagePreferences JavaScript configuration pattern is correctly captured

The verification confirms that the snapshot correctly represents the JavaScript enablement pattern through WKWebpagePreferences. The codebase shows consistent usage of both:

  • Modern WKWebpagePreferences.allowsContentJavaScript pattern (as shown in snapshot)
  • Legacy WKPreferences.javaScriptEnabled pattern

The test files and snapshots demonstrate proper coverage of both patterns, with appropriate labeling for AST matching. The rule file (swift-webview-config-allows-js-swift.yml) also confirms that both patterns are properly handled in security checks.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the prevalence of JavaScript enablement in WKWebpagePreferences
# Expected: Find instances where content JavaScript is being enabled

# Search for WKWebpagePreferences JavaScript configuration
rg -U "let.*WKWebpagePreferences.*\n.*allowsContentJavaScript.*=.*true"

Length of output: 474


Script:

#!/bin/bash
# Let's search for both WKWebpagePreferences and WKPreferences patterns
# to understand the complete JavaScript enablement landscape

# Search for WKWebpagePreferences pattern
rg -U "WKWebpagePreferences.*\n.*allowsContentJavaScript.*=.*true" -A 2

# Search for WKPreferences pattern
rg -U "WKPreferences.*\n.*javaScriptEnabled.*=.*true" -A 2

# Search for any other potential JavaScript enablement in WebKit configurations
rg -i "javascript.*enabled|javascript.*allow" -A 2

Length of output: 4851

tests/__snapshots__/swift-webview-config-base-url-swift-snapshot.yml (1)

4-5: Warning: UIWebView is deprecated and poses security risks

The snapshots use UIWebView which has been deprecated by Apple since iOS 12 due to security and performance concerns. While these appear to be negative test cases demonstrating unsafe patterns, it's worth noting that:

  1. Production code should migrate to WKWebView
  2. Setting nil as baseURL can lead to:
    • Origin spoofing
    • Cross-origin resource access issues
    • Potential bypass of same-origin policy

Let's verify if there are any remaining UIWebView usages that need migration:

Also applies to: 60-61

rules/swift/security/swift-webview-config-allows-js-swift.yml (1)

12-108: Verify coverage of all JavaScript-enabling properties

Let's verify that we're catching all possible ways to enable JavaScript in WebViews.

✅ Verification successful

JavaScript configuration properties are properly covered

Based on the search results, the current rule correctly covers all JavaScript-enabling properties in WebKit:

  1. javaScriptEnabled for WKPreferences
  2. allowsContentJavaScript for WKWebpagePreferences

The test files and snapshots confirm these are the main properties used to enable JavaScript in WebViews. The rule's pattern matches both properties and their respective preference classes (WKPreferences and WKWebpagePreferences). No additional JavaScript-enabling configuration properties were found in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for JavaScript-related properties in WebKit and UIKit frameworks
# that might not be covered by the current patterns

# Look for additional JavaScript-related properties
rg -i "javascript.*enabled|javascript.*allow" 

# Look for WebView configuration patterns
ast-grep --pattern 'class $_ {
  $$$
  var $F: $_
  $$$
}' | rg -i "javascript|webview|configuration"

Length of output: 1220


Script:

#!/bin/bash
# Let's search more specifically for WebView configurations and JavaScript-related settings

# Search for WKWebView configuration patterns
rg -i "wkwebview|uiwebview" -A 5 -B 5

# Search for WKPreferences and WKWebpagePreferences
rg -i "wkpreferences|webpagepreferences" -A 5 -B 5

# Look for any other potential JavaScript configuration methods
rg -i "javascript.*config|script.*enabled|script.*allow" -A 3

Length of output: 20022

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.

1 participant