Skip to content

Commit 2f8c651

Browse files
authored
Fix AI API key not persisted in cache (#39)
The AI API key has a json:"-" tag for security (to prevent exposure in API responses), but this caused it to be excluded when caching ChatbotSettings. After the first message, settings were served from cache with an empty API key, causing subsequent AI requests to fail with "AI not configured" error. Solution: Create a chatbotSettingsCache wrapper struct that explicitly includes the API key when caching, similar to how whatsAppAccountCache handles the AccessToken field. Fixes #38
1 parent c3abcc5 commit 2f8c651

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

internal/handlers/cache.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ const (
3131
aiContextsCachePrefix = "chatbot:ai_contexts:"
3232
)
3333

34+
// chatbotSettingsCache is used for caching since AI.APIKey has json:"-" tag
35+
type chatbotSettingsCache struct {
36+
models.ChatbotSettings
37+
AIAPIKey string `json:"ai_api_key_cache"`
38+
}
39+
3440
// getChatbotSettingsCached retrieves chatbot settings from cache or database
3541
func (a *App) getChatbotSettingsCached(orgID uuid.UUID, whatsAppAccount string) (*models.ChatbotSettings, error) {
3642
ctx := context.Background()
@@ -39,9 +45,11 @@ func (a *App) getChatbotSettingsCached(orgID uuid.UUID, whatsAppAccount string)
3945
// Try cache first
4046
cached, err := a.Redis.Get(ctx, cacheKey).Result()
4147
if err == nil && cached != "" {
42-
var settings models.ChatbotSettings
43-
if err := json.Unmarshal([]byte(cached), &settings); err == nil {
44-
return &settings, nil
48+
var cacheData chatbotSettingsCache
49+
if err := json.Unmarshal([]byte(cached), &cacheData); err == nil {
50+
// Restore the API key from the cache wrapper
51+
cacheData.ChatbotSettings.AI.APIKey = cacheData.AIAPIKey
52+
return &cacheData.ChatbotSettings, nil
4553
}
4654
}
4755

@@ -56,8 +64,12 @@ func (a *App) getChatbotSettingsCached(orgID uuid.UUID, whatsAppAccount string)
5664
return nil, result.Error
5765
}
5866

59-
// Cache the result
60-
if data, err := json.Marshal(settings); err == nil {
67+
// Cache the result (include AI APIKey explicitly since it has json:"-" tag)
68+
cacheData := chatbotSettingsCache{
69+
ChatbotSettings: settings,
70+
AIAPIKey: settings.AI.APIKey,
71+
}
72+
if data, err := json.Marshal(cacheData); err == nil {
6173
a.Redis.Set(ctx, cacheKey, data, settingsCacheTTL)
6274
}
6375

0 commit comments

Comments
 (0)