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

Connect to production hub server with authentication token #51

Merged
merged 3 commits into from
Jan 10, 2025

Conversation

justinshannon
Copy link
Contributor

@justinshannon justinshannon commented Jan 7, 2025

Summary by CodeRabbit

  • New Features

    • Added support for generating hub tokens in the authentication process.
    • Enhanced client authentication mechanism with more flexible dependency injection.
  • Refactor

    • Updated network connection and hub connection classes to support new authentication method.
    • Modified service provider to integrate new authentication interface.
  • Chores

    • Updated constructor signatures across multiple classes to include new authentication dependencies.

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The changes introduce a new GenerateHubToken method in the ClientAuth class and an associated IClientAuth interface across multiple files in the Vatsim.Network and vATIS.Desktop projects. The modifications primarily focus on updating constructor signatures to include an IClientAuth parameter, facilitating dependency injection for authentication. This allows for a more flexible approach to token generation and connection management throughout the application.

Changes

File Change Summary
Vatsim.Network/ClientAuth.cs Added GenerateHubToken() method that currently throws NotImplementedException
Vatsim.Network/IClientAuth.cs Added GenerateHubToken() method declaration returning nullable string
Vatsim.Network/FSDSession.cs Updated constructors to accept IClientAuth parameter and modified _clientAuth initialization
vATIS.Desktop/Networking/AtisHub/AtisHubConnection.cs Added IClientAuth to constructor and implemented token generation for Hub connection
vATIS.Desktop/Networking/NetworkConnection.cs Updated constructor to include IClientAuth parameter
vATIS.Desktop/ServiceProvider.cs Added singleton registration for IClientAuth and updated service creation methods

Sequence Diagram

sequenceDiagram
    participant Client
    participant NetworkConnection
    participant FSDSession
    participant ClientAuth
    
    Client->>NetworkConnection: Create with IClientAuth
    NetworkConnection->>FSDSession: Initialize with IClientAuth
    FSDSession->>ClientAuth: Request Hub Token
    ClientAuth-->>FSDSession: Return Token
    FSDSession-->>NetworkConnection: Confirm Initialization
Loading

Poem

🐰 A rabbit's tale of tokens new,
Hopping through auth with a breakthrough!
Interfaces dance, connections sing,
Flexibility is now the thing!
Code hops forward, smart and bright,
Authentication takes its flight! 🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 08289ec and 415eb3b.

📒 Files selected for processing (1)
  • vATIS.Desktop/Networking/AtisHub/AtisHubConnection.cs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • vATIS.Desktop/Networking/AtisHub/AtisHubConnection.cs

🪧 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. (Beta)
  • @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
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: 2

🔭 Outside diff range comments (1)
Vatsim.Network/FSDSession.cs (1)

Line range hint 11-12: Consider enhancing security measures.

The authentication mechanism could be strengthened:

  1. Use SecureString for storing sensitive keys in memory
  2. Implement key rotation mechanism
  3. Make challenge response window configurable
  4. Add logging for authentication failures

Example implementation for secure key storage:

-    private const int ServerAuthChallengeInterval = 60000;
-    private const int ServerAuthChallengeResponseWindow = 30000;
+    private static readonly TimeSpan ServerAuthChallengeInterval = TimeSpan.FromMinutes(1);
+    private static readonly TimeSpan ServerAuthChallengeResponseWindow = TimeSpan.FromSeconds(30);
+    private SecureString? _clientAuthSessionKey;
+    private SecureString? _clientAuthChallengeKey;

Consider implementing key rotation:

private async Task RotateAuthenticationKeys()
{
    // Implement key rotation logic
    // This should be called periodically to refresh the keys
}
🧹 Nitpick comments (2)
Vatsim.Network/IClientAuth.cs (1)

5-5: Add XML documentation for the new method.

Please add XML documentation comments to describe the purpose, return value, and possible null cases for the GenerateHubToken method.

+    /// <summary>
+    /// Generates an authentication token for hub server connection.
+    /// </summary>
+    /// <returns>The authentication token, or null if token generation fails.</returns>
     string? GenerateHubToken();
vATIS.Desktop/Networking/NetworkConnection.cs (1)

Line range hint 398-425: Consider enhancing connection resilience.

The connection logic could be improved in several ways:

  1. Add timeout handling for auth token retrieval
  2. Implement a retry mechanism for failed connections
  3. Consider making the port number configurable

Example implementation:

 public async Task Connect(string? serverAddress = null)
 {
     ArgumentNullException.ThrowIfNull(_atisStation);
 
-    await _authTokenManager.GetAuthToken();
+    using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+    try {
+        await _authTokenManager.GetAuthToken(cts.Token);
+    }
+    catch (OperationCanceledException) {
+        throw new Exception("Auth token retrieval timed out");
+    }
 
     var bestServer = await _downloader.DownloadStringAsync(VatsimServerEndpoint);
     if (!string.IsNullOrEmpty(bestServer))
     {
         if (Regex.IsMatch(bestServer, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", RegexOptions.CultureInvariant))
         {
-            _fsdSession.Connect(serverAddress ?? bestServer, 6809);
+            await ConnectWithRetry(serverAddress ?? bestServer, _appConfig.Port ?? 6809);
             _previousMetar = "";
         }
         else
         {
             throw new Exception("Invalid server address format: " + bestServer);
         }
     }

Add the retry helper method:

private async Task ConnectWithRetry(string server, int port, int maxAttempts = 3)
{
    for (int attempt = 1; attempt <= maxAttempts; attempt++)
    {
        try
        {
            _fsdSession.Connect(server, port);
            return;
        }
        catch (Exception) when (attempt < maxAttempts)
        {
            await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
        }
    }
    _fsdSession.Connect(server, port); // Let the last attempt throw
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14f459d and 08289ec.

📒 Files selected for processing (6)
  • Vatsim.Network/ClientAuth.cs (1 hunks)
  • Vatsim.Network/FSDSession.cs (1 hunks)
  • Vatsim.Network/IClientAuth.cs (1 hunks)
  • vATIS.Desktop/Networking/AtisHub/AtisHubConnection.cs (3 hunks)
  • vATIS.Desktop/Networking/NetworkConnection.cs (2 hunks)
  • vATIS.Desktop/ServiceProvider.cs (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build (macos-latest)
  • GitHub Check: Analyze (cpp)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (5)
vATIS.Desktop/Networking/AtisHub/AtisHubConnection.cs (1)

37-40: Add null check for the hub token.

The token provider should handle the case where GenerateHubToken returns null. Consider adding appropriate error handling.

-                    options.AccessTokenProvider = () => Task.FromResult(_clientAuth.GenerateHubToken());
+                    options.AccessTokenProvider = () =>
+                    {
+                        var token = _clientAuth.GenerateHubToken();
+                        if (token == null)
+                        {
+                            throw new InvalidOperationException("Failed to generate hub authentication token");
+                        }
+                        return Task.FromResult(token);
+                    };
✅ Verification successful

Add null check for the hub token as suggested

The review comment is valid because GenerateHubToken() is declared with a nullable return type (string?) in the IClientAuth interface, indicating that null is a valid return value by design. The suggested null check with InvalidOperationException would prevent potential runtime issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find IClientAuth interface and implementations
ast-grep --pattern 'interface IClientAuth {
  $$$
}'

# Find GenerateHubToken method implementations
ast-grep --pattern 'GenerateHubToken() {
  $$$
}'

# Search for other usages of GenerateHubToken
rg "GenerateHubToken" -A 2

Length of output: 690

vATIS.Desktop/ServiceProvider.cs (1)

42-42: LGTM! Clean dependency injection setup.

The service registration and dependency injection changes are well-structured and maintain the existing patterns in the codebase.

Also applies to: 114-114, 150-151

vATIS.Desktop/Networking/NetworkConnection.cs (2)

61-61: LGTM! Good use of dependency injection.

The addition of IClientAuth parameter improves testability and follows SOLID principles.


98-101: LGTM! Proper initialization of FsdSession with authentication.

The changes correctly integrate the authentication mechanism while maintaining thread safety through SynchronizationContext.

Vatsim.Network/FSDSession.cs (1)

88-94: LGTM! Well-structured constructor changes.

The changes maintain good constructor chaining pattern while properly integrating the authentication mechanism.

Also applies to: 97-109

Vatsim.Network/ClientAuth.cs Show resolved Hide resolved
vATIS.Desktop/Networking/AtisHub/AtisHubConnection.cs Outdated Show resolved Hide resolved
@justinshannon justinshannon added this pull request to the merge queue Jan 10, 2025
Merged via the queue into main with commit 036af54 Jan 10, 2025
7 checks passed
@justinshannon justinshannon deleted the hub-authentication branch January 10, 2025 02:29
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