Skip to content

feat: support short-lived token endpoint #369

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

Merged
merged 2 commits into from
Apr 14, 2025
Merged

feat: support short-lived token endpoint #369

merged 2 commits into from
Apr 14, 2025

Conversation

naomi-lgbt
Copy link
Contributor

@naomi-lgbt naomi-lgbt commented Apr 10, 2025

Proposed changes

Types of changes

What types of changes does your code introduce to the community .NET SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

Summary by CodeRabbit

  • New Features
    • Introduced new authentication functionality to enable generating short-lived access tokens.
    • Added streamlined support for creating an authentication client for secure API access.
    • Provided a sample .NET project demonstrating how to retrieve and display authentication tokens using an environment-configured API key.
    • Added a structured response for access token grants, including token and expiration details.

Copy link
Contributor

coderabbitai bot commented Apr 10, 2025

Walkthrough

This pull request introduces a new authentication feature into the Deepgram SDK. It adds an AuthClient class and a corresponding factory method, a new v1 authentication client implementation with its interface, and supporting utility and model classes. Additionally, an example project demonstrating token acquisition via the new client is included. All changes focus on streamlining authentication using a short-lived JWT obtained through a POST request.

Changes

File(s) Change Summary
Deepgram/AuthClient.cs
Deepgram/ClientFactory.cs
Introduced AuthClient (extending Client) and added CreateAuthClient factory method to initialize it.
Deepgram/Clients/Auth/v1/Client.cs
Deepgram/Clients/Interfaces/v1/IAuthClient.cs
Added v1 authentication client implementation with an asynchronous GrantToken method and defined the new IAuthClient interface.
Deepgram/Clients/Auth/v1/UriSegments.cs
Deepgram/Models/Auth/v1/GrantTokenResponse.cs
Added a utility class UriSegments containing the GRANTTOKEN constant and introduced the GrantTokenResponse record to encapsulate token response details.
examples/auth/grant-token/Auth.csproj
examples/auth/grant-token/Program.cs
Added a new example project and program demonstrating the authentication flow by acquiring and displaying a token.

Sequence Diagram(s)

sequenceDiagram
    participant P as Program
    participant F as ClientFactory
    participant AC as AuthClient / IAuthClient
    participant API as Deepgram API

    P->>F: Call CreateAuthClient(apiKey, options, httpId)
    F->>AC: Instantiate AuthClient
    P->>AC: Invoke GrantToken(...)
    AC->>API: POST request to '/grant' endpoint
    API-->>AC: Return GrantTokenResponse
    AC-->>P: Return token details
Loading

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 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 70f4966 and 5ba2038.

📒 Files selected for processing (1)
  • Deepgram/Clients/Auth/v1/Client.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Deepgram/Clients/Auth/v1/Client.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.
  • @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 (12)
Deepgram/ClientFactory.cs (1)

59-62: Consider adding versioned auth client creation.

The ClientFactory includes versioned methods for other clients (e.g., CreateListenWebSocketClient with version parameter), but not for the new AuthClient. Consider adding a versioned method for consistency with the pattern used for other clients.

+ /// <summary>
+ /// This method allows you to create an AuthClient with a specific version of the client.
+ /// TODO: this should be revisited at a later time. Opportunity to use reflection to get the type of the client
+ /// </summary>
+ public static object CreateAuthClient(int version, string apiKey = "", DeepgramHttpClientOptions? options = null, string? httpId = null)
+ {
+     // Currently only a single version of the AuthClient exists
+     return new AuthClient(apiKey, options, httpId);
+ }
examples/auth/grant-token/Auth.csproj (4)

3-8: Inconsistent indentation in project file.

The project file uses tabs for indentation, which is inconsistent with the standard .NET project format that typically uses spaces. Consider standardizing the indentation across all project files.

-	<PropertyGroup>
-		<OutputType>Exe</OutputType>
-		<TargetFramework>net8.0</TargetFramework>
-		<ImplicitUsings>enable</ImplicitUsings>
-		<Nullable>enable</Nullable>	
-	</PropertyGroup>
+    <PropertyGroup>
+        <OutputType>Exe</OutputType>
+        <TargetFramework>net8.0</TargetFramework>
+        <ImplicitUsings>enable</ImplicitUsings>
+        <Nullable>enable</Nullable>
+    </PropertyGroup>

10-12: Inconsistent indentation in ItemGroup.

The ItemGroup element also uses tabs for indentation, which should be standardized to match other project files in the repository.

-	<ItemGroup>	
-		<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
-	</ItemGroup>
+    <ItemGroup>
+        <PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
+    </ItemGroup>

14-16: Inconsistent indentation in ProjectReference ItemGroup.

This ItemGroup also uses tabs for indentation and has an inconsistent spacing in the element.

-	<ItemGroup>
-	  <ProjectReference Include="..\..\..\Deepgram\Deepgram.csproj" />
-	</ItemGroup>
+    <ItemGroup>
+        <ProjectReference Include="..\..\..\Deepgram\Deepgram.csproj" />
+    </ItemGroup>

18-20: Inconsistent spacing in Using ItemGroup.

The Using ItemGroup uses spaces but has a different level of indentation compared to the other ItemGroup with spaces.

-    <ItemGroup>
-        <Using Include="Deepgram" />
-    </ItemGroup>
+    <ItemGroup>
+        <Using Include="Deepgram" />
+    </ItemGroup>
examples/auth/grant-token/Program.cs (2)

22-26: Consider enhancing error handling.

The current implementation only checks if the token response is null. Consider adding more comprehensive error handling such as try/catch blocks to handle potential API errors or network issues.

// generate token
var tokenResp = await deepgramClient.GrantToken();
if (tokenResp == null)
{
    Console.WriteLine("GrantToken failed.");
    Environment.Exit(1);
}
+catch (Exception ex)
+{
+    Console.WriteLine($"Error obtaining token: {ex.Message}");
+    Environment.Exit(1);
+}

28-31: Consider handling null token values.

The code directly accesses AccessToken and ExpiresIn properties without checking if they are null, which could lead to potential null reference exceptions.

-string token = tokenResp.AccessToken;
-string ttl = tokenResp.ExpiresIn.ToString();
+string token = tokenResp.AccessToken ?? "Token not provided";
+string ttl = tokenResp.ExpiresIn?.ToString() ?? "TTL not provided";
Console.WriteLine($"Token: {token}");
Console.WriteLine($"TTL: {ttl}");
Deepgram/Models/Auth/v1/GrantTokenResponse.cs (2)

12-14: JSON annotation inconsistency.

The indentation of the [JsonPropertyName] attribute is inconsistent with the [JsonIgnore] attribute.

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
-	[JsonPropertyName("access_token")]
+[JsonPropertyName("access_token")]
public string? AccessToken { get; set; }

19-21: JSON annotation inconsistency.

The indentation of the [JsonPropertyName] attribute is inconsistent with the [JsonIgnore] attribute.

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
-	[JsonPropertyName("expires_in")]
+[JsonPropertyName("expires_in")]
public decimal? ExpiresIn { get; set; }
Deepgram/Clients/Auth/v1/Client.cs (3)

5-8: Potential unused namespace import.

The Deepgram.Models.Authenticate.v1 namespace is imported but doesn't appear to be used in the class.

-using Deepgram.Models.Authenticate.v1;
using Deepgram.Models.Auth.v1;
using Deepgram.Clients.Interfaces.v1;
using Deepgram.Abstractions.v1;

13-13: Incorrect XML documentation.

The XML comment references "Models Client" but this is actually an "Auth Client".

/// <summary>
-/// Implements version 1 of the Models Client.
+/// Implements version 1 of the Auth Client.
/// </summary>

24-37: Implementation looks good but could benefit from exception handling.

The GrantToken method implementation is correct, but consider adding explicit exception handling to log errors and provide more context in case of failures.

public async Task<GrantTokenResponse> GrantToken(CancellationTokenSource? cancellationToken = default,
    Dictionary<string, string>? addons = null, Dictionary<string, string>? headers = null)
{
    Log.Verbose("AuthClient.GrantToken", "ENTER");

+   try
+   {
        var uri = GetUri(_options, $"auth/{UriSegments.GRANTTOKEN}");
        var result = await PostAsync<object, GrantTokenResponse>(uri, null, cancellationToken, addons, headers);

        Log.Information("GrantToken", $"{uri} Succeeded");
        Log.Debug("GrantToken", $"result: {result}");
        Log.Verbose("AuthClient.GrantToken", "LEAVE");

        return result;
+   }
+   catch (Exception ex)
+   {
+       Log.Error("AuthClient.GrantToken", $"Failed to grant token: {ex.Message}");
+       Log.Verbose("AuthClient.GrantToken", "LEAVE");
+       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 86c1716 and 70f4966.

📒 Files selected for processing (8)
  • Deepgram/AuthClient.cs (1 hunks)
  • Deepgram/ClientFactory.cs (1 hunks)
  • Deepgram/Clients/Auth/v1/Client.cs (1 hunks)
  • Deepgram/Clients/Auth/v1/UriSegments.cs (1 hunks)
  • Deepgram/Clients/Interfaces/v1/IAuthClient.cs (1 hunks)
  • Deepgram/Models/Auth/v1/GrantTokenResponse.cs (1 hunks)
  • examples/auth/grant-token/Auth.csproj (1 hunks)
  • examples/auth/grant-token/Program.cs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
Deepgram/Clients/Interfaces/v1/IAuthClient.cs (3)
Deepgram/Clients/Auth/v1/Client.cs (1)
  • Task (24-37)
examples/auth/grant-token/Program.cs (1)
  • Task (11-38)
Deepgram.Tests/UnitTests/HttpExtensionsTests/HttpClientExtensionTests.cs (1)
  • Dictionary (143-153)
Deepgram/Models/Auth/v1/GrantTokenResponse.cs (1)
Deepgram/Utilities/JsonSerializeOptions.cs (1)
  • JsonSerializeOptions (7-13)
Deepgram/Clients/Auth/v1/Client.cs (4)
Deepgram/Clients/Interfaces/v1/IAuthClient.cs (1)
  • Task (20-21)
examples/auth/grant-token/Program.cs (1)
  • Task (11-38)
Deepgram/Logger/Log.cs (3)
  • Verbose (75-78)
  • Information (91-94)
  • Debug (83-86)
Deepgram/Clients/Auth/v1/UriSegments.cs (1)
  • UriSegments (7-12)
🔇 Additional comments (10)
Deepgram/AuthClient.cs (1)

10-19: Good implementation of the auth client class.

The AuthClient class correctly extends the base Client class and is well-documented with appropriate XML comments. The implementation follows the same pattern as other client classes in the SDK, providing a consistent API for users.

Deepgram/Clients/Auth/v1/UriSegments.cs (1)

7-12: Good practice using constants instead of magic strings.

Using a dedicated constants class for URI segments improves maintainability and helps prevent errors from typos. The naming convention (uppercase) follows standard practices for constants.

Deepgram/ClientFactory.cs (1)

52-62: Well-integrated factory method for AuthClient.

The CreateAuthClient method follows the same pattern as other client creation methods in the factory, maintaining consistency in the API. The implementation and documentation are appropriate.

examples/auth/grant-token/Auth.csproj (1)

1-22: Well-structured example project.

The example project is properly configured with appropriate dependencies and references. It targets .NET 8.0 and includes the necessary reference to the Deepgram project.

Deepgram/Clients/Interfaces/v1/IAuthClient.cs (1)

20-21: Interface method implementation looks good.

The GrantToken method signature is well-defined with appropriate optional parameters and return type.

examples/auth/grant-token/Program.cs (1)

11-38: Example shows clear implementation of token acquisition.

The example provides a clear demonstration of how to use the new auth client to obtain a token, including proper initialization and cleanup.

Deepgram/Models/Auth/v1/GrantTokenResponse.cs (2)

7-30: Well-structured response model.

The response model is well-structured using C# records, with appropriate JSON attributes and null handling, which aligns with the rest of the SDK design patterns.


28-28:

✅ Verification successful

Verify if Regex.Unescape is necessary.

The use of Regex.Unescape might be unnecessary depending on the expected content. Typically, JsonSerializer.Serialize already produces well-formed JSON.


🏁 Script executed:

#!/bin/bash
# Check usage of Regex.Unescape in other model classes

# Find other ToString methods that use JsonSerializer.Serialize
rg -A 1 -B 1 "override\s+string\s+ToString" --glob="*.cs" | grep -A 1 -B 1 "JsonSerializer.Serialize"

Length of output: 101


Regex.Unescape Usage Confirmed as Intentional

Based on our review and prior learnings from the codebase (see Deepgram/Models/Speak/v1/WebSocket/MetadataResponse.cs), the use of Regex.Unescape in the ToString method for JSON serialization is intentional. Although the shell script did not return additional instances, the project convention supports using it to produce the desired JSON output.

Deepgram/Clients/Auth/v1/Client.cs (2)

17-38: Implementation provides clean and concise solution for token acquisition.

The client implementation follows the SDK's patterns with proper inheritance, logging, and HTTP request construction. The code is well-organized and easy to understand.


18-18:

❓ Verification inconclusive

Constructor uses recent C# feature.

The class uses C# 12's primary constructor syntax, which is good for conciseness but ensure the SDK's minimum required .NET version supports this feature.


🏁 Script executed:

#!/bin/bash
# Check the target framework version in the project file
fd -e csproj | xargs cat | grep -A 5 -B 5 "TargetFramework"

Length of output: 13068


Action: Verify .NET Target Compatibility for C#12 Primary Constructors

The updated constructor uses the concise, C# 12 primary constructor syntax—which is fully supported when building for .NET 8.0 as indicated by the <TargetFramework> settings and <LangVersion>latest</LangVersion>. However, since the SDK also targets netstandard2.0, please verify that:

  • The net8.0 build (which supports C#12 features) is isolated from any issues that might arise from multi-targeting.
  • The netstandard2.0 target compiles and functions correctly with this syntax—or that it’s conditionally excluded if needed.

If any compatibility concerns appear on the netstandard2.0 side, consider either conditionally compiling this feature or updating the minimal supported framework accordingly.

jpvajda
jpvajda previously approved these changes Apr 11, 2025
Copy link
Contributor

@jpvajda jpvajda left a comment

Choose a reason for hiding this comment

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

LGTM!

@naomi-lgbt naomi-lgbt merged commit f83b5c4 into main Apr 14, 2025
3 checks passed
@naomi-lgbt naomi-lgbt deleted the feat/auth branch April 14, 2025 16:09
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