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

feat: add article managing-short-lived-api-keys #15

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Managing Short-Lived API Keys in Deepgram

Managing API keys efficiently is crucial for establishing secure and effective connections to Deepgram's speech-to-text API. Implementing short-lived API keys is a robust method to enhance security, particularly for in-browser applications. This article will guide you through key considerations when using short-lived API keys.

## Understanding API Key Management

When designing your system to handle short-lived API keys, it's essential to consider the lifecycle of these keys — from creation, active use, to deletion. Here's a basic run-through of the actions:

1. **Creating API Keys**: Generate API keys for user sessions and associate them with user profiles to track usage.
2. **Using API Keys**: Establish a secure connection using the API key. Ensure API keys are never exposed in client-side code.
3. **Deleting API Keys**: After successfully establishing a connection, delete the API key to prevent unauthorized reuse.

### Additional Considerations:

- **Tracking Usage**: By associating API keys with users, you can monitor and detect any suspicious activity.
- **Setting Expiration**: Assign a short expiration to API keys (e.g., 10 seconds) to limit potential misuse.
- **Rate Limiting**: Implement rate limiting to safeguard against abuse of API calls.

## Implementation Across SDKs

Here's a basic example of how to manage API keys using different Deepgram SDKs. Ensure you handle API key creation and deletion securely within server-side logic, possibly coordinating with a back-end

### Python

```python
import deepgram_sdk

# Create an instance of the Deepgram client
client = deepgram_sdk.Client()
api_key = client.create_api_key(expiry='10s')

def establish_and_cleanup_connection():
# Establish your connection
# ...

# Delete API key
client.delete_api_key(api_key.id)
```

### JavaScript/Node.js

```javascript
const { Deepgram } = require('@deepgram/sdk');

const deepgram = new Deepgram('your_deepgram_api_key');

async function setupConnection() {
const apiKey = await deepgram.createApiKey({expiry: '10s'});
// Establish connection
// ...

// Delete API Key
await deepgram.deleteApiKey(apiKey.id);
}
```

### .NET

```csharp
using Deepgram;

var deepgramClient = new DeepgramClient();
var apiKey = await deepgramClient.CreateApiKeyAsync(expiry: "10s");

// Establish connection

await deepgramClient.DeleteApiKeyAsync(apiKey.Id);
```

### Go

```go
import "deepgram-sdk-go"

deepgram := deepgram.NewClient()
apiKey, _ := deepgram.CreateApiKey("10s")

// Establish connection

_ = deepgram.DeleteApiKey(apiKey.Id)
```

### Rust

```rust
use deepgram_sdk::Deepgram;

let deepgram = Deepgram::new();
let api_key = deepgram.create_api_key("10s").await.unwrap();

// Establish connection

deepgram.delete_api_key(api_key.id).await.unwrap();
```

## Conclusion

By implementing short-lived keys with these considerations, you can maintain a secure connection environment for your Deepgram integrations. Remember, owing to no automatic expiration policy in Deepgram, manual cleanup is crucial.

## References
- [Deepgram SDK Documentation](https://developers.deepgram.com/docs/getting-started-with-pre-recorded-audio)
- [Deepgram API Management](https://developers.deepgram.com/docs/security)
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using Deepgram; // Hypothetical Deepgram SDK namespace

class Program
{
static void Main()
{
// Retrieve the Deepgram API key from environment variables
string apiKey = Environment.GetEnvironmentVariable("DEEPGRAM_API_KEY");

// Initialize Deepgram client
var deepgramClient = new DeepgramClient(apiKey);

// Retrieve the API key ID from environment variables
string keyId = Environment.GetEnvironmentVariable("DEEPGRAM_KEY_ID");

// Assume the key was used prior in logic
DeleteApiKey(keyId);
}

// Function to simulate API key deletion logic
static void DeleteApiKey(string keyId)
{
Console.WriteLine($"Deleting API key with ID: {keyId}");
// Insert actual key deletion code here
}
}

// Note: This script defines a stub function `DeleteApiKey`,
// Replace it with actual deletion logic supported by your key management approach.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"fmt"
"os"
)

func main() {
// Read the Deepgram API Key from an environment variable
apiKey := os.Getenv("DEEPGRAM_API_KEY")

// Create a new Deepgram client (Placeholder as actual function depends on SDK)
client := NewDeepgramClient(apiKey)

// Example to delete an API key after use
keyID := os.Getenv("DEEPGRAM_KEY_ID")

// Assume the key is used prior in logic
deleteAPIKey(client, keyID)
}

// NewDeepgramClient is a placeholder to represent Deepgram client creation
func NewDeepgramClient(apiKey string) *DeepgramClient {
// Initialize and return a new Deepgram client
return &DeepgramClient{apiKey: apiKey}
}

// DeepgramClient is a struct representing a Deepgram client
// This is a placeholder for the existing struct within Deepgram SDK
type DeepgramClient struct {
apiKey string
}

// Function to delete an API key
func deleteAPIKey(client *DeepgramClient, keyID string) {
fmt.Printf("Deleting API key with ID: %s\n", keyID)
// Implement actual key deletion logic here if available
}

// Assume this logic calls a backend service or directly uses the Deepgram SDK
// to manage the lifecycle of API keys.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require('dotenv').config();
const deepgram = require('@deepgram/sdk');

// Retrieve API key from environment variables
const apiKey = process.env.DEEPGRAM_API_KEY;

// Initialize Deepgram SDK client
const deepgramClient = new deepgram.Deepgram(apiKey);

// Function to simulate API key deletion logic
async function deleteApiKey(keyId) {
console.log(`Deleting API key with id: ${keyId}`);
// Insert actual API key deletion logic here using your own backend or management service
}

// Example usage
(async () => {
const keyId = process.env.DEEPGRAM_KEY_ID;
// Assume the API key is used here

// Delete the API key immediately after use
await deleteApiKey(keyId);
})();

// Ensure to have DEEPGRAM_API_KEY and DEEPGRAM_KEY_ID in your `.env` file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import os
from deepgram import Deepgram

# Retrieve the Deepgram API key from environment variables
API_KEY = os.getenv('DEEPGRAM_API_KEY')

# Instantiate the Deepgram client
dg_client = Deepgram(api_key=API_KEY)

# Placeholder to represent where the key would be deleted
# Typically, logic to delete/discard key goes here

def delete_key(key_id):
# Logic that should be executed after the connection is established
print(f'Deleting key with ID: {key_id}')
# Note: This must be replaced with actual Deepgram API key deletion code

if __name__ == "__main__":
key_id = os.getenv('DEEPGRAM_KEY_ID')

# Assume the key was used prior in logic
delete_key(key_id)

# This script assumes you would replace the `delete_key` function placeholder
# with actual deletion implementation supported by your key management scheme.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::env;
use deepgram::{Deepgram, DeepgramError};

fn main() -> Result<(), DeepgramError> {
// Fetch API key from environment variables
let api_key = env::var("DEEPGRAM_API_KEY").expect("DEEPGRAM_API_KEY not set");

// Create a new Deepgram client
let client = Deepgram::new(api_key);

// Sample logic to delete key after use
let key_id = env::var("DEEPGRAM_KEY_ID").expect("DEEPGRAM_KEY_ID not set");

// Assume the key is used prior in logic
delete_api_key(&client, &key_id)?;

Ok(())
}

fn delete_api_key(client: &Deepgram, key_id: &str) -> Result<(), DeepgramError> {
// Logic to delete or disable the key
// Note: Actual implementation depends on Deepgram SDK support for key management
println!("Deleting key with id: {}", key_id);
Ok(())
}

// This code assumes the existence of the hypothetical function `delete_api_key`
// It should be replaced by actual key management logic when supported.