Skip to content

Conversation

networkfusion
Copy link
Member

@networkfusion networkfusion commented Aug 14, 2023

Description

Adds AWS Signature Version 4, this can be used instead of TLS certificates and will be required for supporting MQTT over WebSockets and HTTP Client support.

If can also be used for other AWS capabilities (e.g. S3 buckets).

It is not fully tested and could probably be optimized, but this is a major attempt towards support.

Motivation and Context

Builds upon #148

How Has This Been Tested?

Screenshots

Types of changes

  • Improvement (non-breaking change that improves a feature, code or algorithm)
  • Bug fix (non-breaking change which fixes an issue with code or algorithm)
  • New feature (non-breaking change which adds functionality to code)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Config and build (change in the configuration and build system, has no impact on code or features)
  • Dependencies (update dependencies and changes associated, has no impact on code or features)
  • Unit Tests (add new Unit Test(s) or improved existing one(s), has no impact on code or features)
  • Documentation (changes or updates in the documentation, has no impact on code or features)

Checklist:

  • My code follows the code style of this project (only if there are changes in source code).
  • My changes require an update to the documentation (there are changes that require the docs website to be updated).
  • I have updated the documentation accordingly (the changes require an update on the docs in this repo).
  • I have read the CONTRIBUTING document.
  • I have tested everything locally and all new and existing tests passed (only if there are changes in source code).
  • I have added new tests to cover my changes.

Copy link
Member

@Ellerbach Ellerbach left a comment

Choose a reason for hiding this comment

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

Few comments

/// </summary>
/// <param name="items">Items in the ArrayList</param>
/// <param name="comparer">The Comparer</param>
public static void Sort(this ArrayList items, IComparer comparer)
Copy link
Member

Choose a reason for hiding this comment

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

now I get your question on Discord :-)

Why not using a quick-sort algorithm? It's fast and simple: https://www.geeksforgeeks.org/quick-sort/
You even have it implemented directly in C# there.

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks, I will look into that as a later optimization. Given it is currently working as expected (in the context of my pesudo tests matching full fat .Net), I would rather not mess with it until appropriate unit tests are added and fully end to end tested.

@sonarqubecloud
Copy link

SonarCloud Quality Gate failed.    Quality Gate failed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 24 Code Smells

No Coverage information No Coverage information
12.0% 12.0% Duplication

idea Catch issues before they fail your Quality Gate with our IDE extension sonarlint SonarLint

Copy link

sonarqubecloud bot commented May 2, 2024

Quality Gate Failed Quality Gate failed

Failed conditions
12.0% Duplication on New Code (required ≤ 5%)

See analysis details on SonarCloud

Copy link

coderabbitai bot commented Aug 10, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this 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.

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
12.0% Duplication on New Code (required ≤ 5%)

See analysis details on SonarCloud

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
12.0% Duplication on New Code (required ≤ 5%)

See analysis details on SonarQube Cloud

@networkfusion
Copy link
Member Author

@coderabbitai full-review

Copy link

coderabbitai bot commented Jun 23, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@networkfusion I'll conduct a full review of this PR. Let me first gather information about the changes made.


🏁 Script executed:

#!/bin/bash
# Get PR information and changed files
echo "=== PR Information ==="
gh pr view 149 --json title,body,files,additions,deletions,changedFiles

echo -e "\n=== Files changed in this PR ==="
gh pr diff 149 --name-only

echo -e "\n=== Detailed diff ==="
gh pr diff 149

Length of output: 93270


🏁 Script executed:

#!/bin/bash
# Let's examine the code for duplication issues and get a better understanding of the implementation
echo "=== Examining duplication in signature classes ==="
fd "Signer.*\.cs" --exec cat {} \; | head -200

echo -e "\n=== Looking for duplicate string/hash handling code ==="
rg -A 5 -B 2 "ComputeHash|ToHexString|StringBuilder" nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/

echo -e "\n=== Checking for duplicate canonicalization logic ==="
rg -A 10 "canonicalize|Canonicalize" nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/

Length of output: 810


🏁 Script executed:

#!/bin/bash
# First, let's see the actual directory structure
echo "=== Current directory structure ==="
ls -la
find . -name "*.cs" -path "*AwsSignatureVersion4*" | head -10

echo -e "\n=== Looking for duplicate code patterns across signer files ==="
rg -A 5 -B 2 "ComputeHash|ToHexString|StringBuilder" --type cs

echo -e "\n=== Checking canonicalization duplication ==="
rg -A 10 -B 2 "canonicalize|Canonicalize" --type cs

echo -e "\n=== Examining query parameter processing duplication ==="
rg -A 8 -B 2 "paramDictionary|queryParameters.*Split" --type cs

Length of output: 1711


🏁 Script executed:

#!/bin/bash
# Let's try a different approach to find and examine the files
echo "=== Finding all C# files ==="
find . -name "*.cs" | sort

echo -e "\n=== Examining the signature files specifically ==="
find . -name "*Signer*.cs" -exec basename {} \;

echo -e "\n=== Looking at the duplicate code patterns using grep ==="
grep -r "ComputeHash\|ToHexString\|StringBuilder" . --include="*.cs" | head -20

echo -e "\n=== Checking canonicalization methods ==="
grep -r "Canonicalize" . --include="*.cs" -A 3 | head -30

echo -e "\n=== Looking for query parameter processing patterns ==="
grep -r "paramDictionary\|queryParameters.*Split" . --include="*.cs" -A 5 | head -40

Length of output: 849


🏁 Script executed:

#!/bin/bash
# Let's look at the repository structure first
echo "=== Repository structure ==="
find . -type f -name "*.cs" | head -20

echo -e "\n=== List files in nanoFramework.Aws.IoTCore.Devices directory ==="
ls -la nanoFramework.Aws.IoTCore.Devices/

echo -e "\n=== Check if AwsSignatureVersion4 directory exists ==="
ls -la nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/ 2>/dev/null || echo "Directory not found"

echo -e "\n=== Get actual content of one of the signer files to understand duplication ==="
cat nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForAuthorizationHeader.cs 2>/dev/null | head -50

echo -e "\n=== Look for patterns across multiple files ==="
cat nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForQueryParameterAuth.cs 2>/dev/null | grep -A 5 -B 5 "paramDictionary\|canonicalized"

Length of output: 1248


🏁 Script executed:

#!/bin/bash
# Let's check what branch we're on and try to get the PR changes
echo "=== Git branch info ==="
git branch -a
git status

echo -e "\n=== Try to checkout the PR branch ==="
git fetch origin pull/149/head:pr-149 2>/dev/null || echo "Could not fetch PR branch"
git checkout pr-149 2>/dev/null || echo "Could not checkout PR branch"

echo -e "\n=== Check if files exist now ==="
ls -la nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/ 2>/dev/null || echo "Still not found"

echo -e "\n=== Let's look at the git log to understand the commits ==="
git log --oneline -n 10

echo -e "\n=== Check current HEAD ==="
git rev-parse HEAD

Length of output: 767


🏁 Script executed:

#!/bin/bash
# Let's configure sparse checkout to include all files and then examine the duplication
echo "=== Configuring sparse checkout to include all files ==="
git config core.sparseCheckout false
git read-tree -m -u HEAD

echo -e "\n=== Now check if the AwsSignatureVersion4 files exist ==="
ls -la nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/ 2>/dev/null || echo "Still not found, let's try different approach"

echo -e "\n=== Let's examine the git diff directly to understand duplication ==="
git show HEAD --name-only

echo -e "\n=== Try to see the actual files from git ==="
git show HEAD:nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForAuthorizationHeader.cs | head -100

Length of output: 7554


🏁 Script executed:

#!/bin/bash
# Now let's examine the duplication patterns across the different signer files
echo "=== Examining SignerForQueryParameterAuth.cs to identify duplication ==="
git show HEAD:nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForQueryParameterAuth.cs | head -150

echo -e "\n=== Examining SignerForPOST.cs ==="
git show HEAD:nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForPOST.cs | head -150

echo -e "\n=== Examining SignerForChunkedUpload.cs ==="
git show HEAD:nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForChunkedUpload.cs | head -150

echo -e "\n=== Let's look at the query parameter processing code specifically ==="
git show HEAD:nanoFramework.Aws.IoTCore.Devices/AwsSignatureVersion4/SignerForAuthorizationHeader.cs | grep -A 20 "paramDictionary.*Hashtable"

Length of output: 21282


@networkfusion Thank you for this substantial contribution! I've completed a full review of PR #149, which adds AWS Signature Version 4 support to enable MQTT over WebSockets and broader AWS service integration.

🎯 Overall Assessment

This is a significant and valuable feature addition that implements AWS Signature Version 4 authentication. The functionality is well-structured with a proper inheritance hierarchy using SignerBase and specialized implementations for different use cases.

⚠️ Quality Gate Issue: Code Duplication (12%)

The main issue causing the SonarCloud quality gate failure is significant code duplication across the signer classes. I've identified the specific patterns:

Primary Duplication Sources:

1. Query Parameter Processing Logic - appears identically in all 4 signer classes:

var paramDictionary = new Hashtable();
var qparam = queryParameters.Split('&');
foreach (string p in qparam)
{
    var items = p.Split('=');
    if (items.Length == 1)
    {
        paramDictionary.Add(items[0], null);
    }
    else
    {
        paramDictionary.Add(items[0], items[1]);
    }
}

var sb = new StringBuilder();
var paramKeys = new ArrayList();

foreach (DictionaryEntry kvp in paramDictionary)
{
    paramKeys.Add(kvp.Key);
}

paramKeys.Sort(StringComparer.Ordinal);
foreach (var p in paramKeys)
{
    if (sb.Length > 0)
        sb.Append("&");
    sb.Append($"{p}={paramDictionary[p]}");
}

2. Host Header Construction - duplicated across multiple files:

var hostHeader = EndpointUri.Host;
hostHeader += ":" + EndpointUri.Port; // FIXME: should use //if (!EndpointUri.IsDefaultPort)
headers.Add("Host", hostHeader);

3. Common Signature Computation Patterns - similar datetime handling, canonicalization, and HMAC-SHA256 computation logic.

🔧 Recommended Solutions

To reduce duplication below the 5% threshold, extract common functionality into the SignerBase class:

// In SignerBase class
protected string CanonicalizeQueryParameters(string queryParameters)
{
    if (string.IsNullOrEmpty(queryParameters))
        return string.Empty;
        
    var paramDictionary = ParseQueryParameters(queryParameters);
    return BuildCanonicalQueryString(paramDictionary);
}

protected Hashtable ParseQueryParameters(string queryParameters)
{
    var paramDictionary = new Hashtable();
    var qparam = queryParameters.Split('&');
    foreach (string p in qparam)
    {
        var items = p.Split('=');
        if (items.Length == 1)
        {
            paramDictionary.Add(items[0], null);
        }
        else
        {
            paramDictionary.Add(items[0], items[1]);
        }
    }
    return paramDictionary;
}

protected void AddHostHeader(IDictionary headers)
{
    if (!headers.Contains("Host"))
    {
        var hostHeader = EndpointUri.Host;
        if (!EndpointUri.IsDefaultPort)
        {
            hostHeader += ":" + EndpointUri.Port;
        }
        headers.Add("Host", hostHeader);
    }
}

💡 Additional Improvements

  1. Host Port Logic: Fix the FIXME comment by properly checking IsDefaultPort
  2. Error Handling: Consider adding validation for malformed query parameters
  3. Documentation: The implementation is well-documented, which is excellent
  4. Unit Tests: The included tests are a good start for validation

🏆 Positive Aspects

  • Comprehensive Implementation: Covers multiple AWS signature scenarios
  • Good Architecture: Proper inheritance hierarchy with SignerBase
  • Crypto Implementation: Custom SHA256 and HMAC-SHA256 for nanoFramework constraints
  • Test Coverage: Includes unit tests for validation
  • Documentation: Well-commented code explaining AWS signature requirements

📋 Summary

This is a high-quality, substantial feature addition that just needs refactoring to eliminate code duplication. The functionality is valuable and the architecture is sound. Once the duplication is addressed, this will be an excellent addition to the nanoFramework AWS IoT Core capabilities.

Priority: Extract common methods to resolve the 12% duplication issue and pass the quality gate.

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.

2 participants