-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
326 lines (279 loc) · 9.13 KB
/
Copy pathclient.go
File metadata and controls
326 lines (279 loc) · 9.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package tama
import (
"encoding/base64"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/go-resty/resty/v2"
)
const (
// DefaultTimeout is the default timeout for API requests.
DefaultTimeout = 30 * time.Second
)
// TokenResponse represents the OAuth2 token response from /auth/tokens.
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
ExpiresIn int64 `json:"expires_in"`
}
// Token represents an OAuth2 access token with expiration tracking.
type Token struct {
AccessToken string
TokenType string
Scope string
ExpiresAt time.Time
}
// IsExpired checks if the token is expired or will expire within 30 seconds.
func (t *Token) IsExpired() bool {
if t.ExpiresAt.IsZero() {
return true
}
// Consider token expired if it expires within 30 seconds to account for request time.
// Split for readability and to satisfy linters.
expiryCheck := time.Now().
Add(30 * time.Second). //nolint:mnd // 30-second grace window to account for request time
After(t.ExpiresAt)
return expiryCheck
}
// Client represents the main Tama API client.
type Client struct {
httpClient *resty.Client
baseURL string
clientID string
clientSecret string
token *Token
tokenMutex sync.RWMutex
skipTokenFetch bool
scopes []string
Neural *NeuralService
Sensory *SensoryService
Memory *MemoryService
Perception *PerceptionService
Motor *MotorService
Contexts *ContextsService
Tools *ToolsService
System *SystemService
}
// Config holds configuration options for the client.
type Config struct {
BaseURL string
ClientID string
ClientSecret string
APIKey string
Timeout time.Duration
SkipTokenFetch bool // For testing - skips initial token fetch
Scopes []string // OAuth2 scopes to request
}
// NewClient creates a new Tama API client with OAuth2 authentication.
func NewClient(config Config) (*Client, error) {
if config.Timeout == 0 {
config.Timeout = DefaultTimeout
}
// Require client credentials only if APIKey is not provided (backwards compatibility for tests)
if config.APIKey == "" {
if config.ClientID == "" {
return nil, errors.New("client_id is required")
}
if config.ClientSecret == "" {
return nil, errors.New("client_secret is required")
}
}
httpClient := resty.New().
SetBaseURL(config.BaseURL).
SetTimeout(config.Timeout).
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json")
client := &Client{
httpClient: httpClient,
baseURL: config.BaseURL,
clientID: config.ClientID,
clientSecret: config.ClientSecret,
skipTokenFetch: config.SkipTokenFetch,
scopes: config.Scopes,
}
// If APIKey is provided without client credentials, enable test mode and set token directly
if config.APIKey != "" && (config.ClientID == "" || config.ClientSecret == "") {
client.skipTokenFetch = true
client.httpClient.SetAuthToken(config.APIKey)
} else if !config.SkipTokenFetch {
// Get initial OAuth2 token (unless skipped for testing)
if err := client.refreshToken(config.Scopes...); err != nil {
return nil, fmt.Errorf("failed to obtain initial token: %w", err)
}
}
// Set up request interceptor to ensure token validity on each request.
httpClient.OnBeforeRequest(func(_ *resty.Client, _ *resty.Request) error {
// Skip token validation if SkipTokenFetch is enabled (for testing)
if client.skipTokenFetch {
return nil
}
// Ensure valid token before each request
if err := client.ensureValidToken(); err != nil {
return fmt.Errorf("failed to refresh token: %w", err)
}
return nil
})
// Initialize services
client.Neural = newNeuralService(client)
client.Sensory = newSensoryService(client)
client.Memory = newMemoryService(client)
client.Perception = newPerceptionService(client)
client.Motor = newMotorService(client)
client.Contexts = newContextsService(client)
client.Tools = newToolsService(client)
client.System = newSystemService(client)
return client, nil
}
// refreshToken obtains a new OAuth2 access token using client credentials flow.
func (c *Client) refreshToken(scopes ...string) error {
c.tokenMutex.Lock()
defer c.tokenMutex.Unlock()
// Determine scope - use provided scopes or default to "provision.all"
requestScope := "provision.all"
if len(scopes) > 0 {
// Join multiple scopes with spaces (OAuth2 standard)
requestScope = strings.Join(scopes, " ")
}
// Create Basic Auth credentials: base64(client_id:client_secret)
credentials := base64.StdEncoding.EncodeToString([]byte(c.clientID + ":" + c.clientSecret))
// Create a separate HTTP client for token requests to avoid circular dependency
tokenClient := resty.New().
SetBaseURL(c.baseURL).
SetTimeout(c.httpClient.GetClient().Timeout).
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json").
SetHeader("Authorization", "Bearer "+credentials)
// Create JSON body for the token request
requestBody := map[string]string{
"grant_type": "client_credentials",
"scope": requestScope,
}
var tokenResponse TokenResponse
resp, err := tokenClient.R().
SetBody(requestBody).
SetResult(&tokenResponse).
Post("/auth/tokens")
if err != nil {
return fmt.Errorf("token request failed: %w", err)
}
if resp.IsError() {
return fmt.Errorf("token request failed with status %d: %s", resp.StatusCode(), resp.String())
}
// Calculate expiration time
expiresAt := time.Now().Add(time.Duration(tokenResponse.ExpiresIn) * time.Second)
// Store the new token
c.token = &Token{
AccessToken: tokenResponse.AccessToken,
TokenType: tokenResponse.TokenType,
Scope: tokenResponse.Scope,
ExpiresAt: expiresAt,
}
// Update the HTTP client with the new token
c.httpClient.SetAuthToken(c.token.AccessToken)
return nil
}
// ensureValidToken ensures that we have a valid, non-expired token.
func (c *Client) ensureValidToken() error {
// Skip token validation if SkipTokenFetch is enabled (for testing)
if c.skipTokenFetch {
return nil
}
c.tokenMutex.RLock()
if c.token != nil && !c.token.IsExpired() {
c.tokenMutex.RUnlock()
return nil
}
c.tokenMutex.RUnlock()
// Token is expired or missing, refresh it
return c.refreshToken(c.scopes...)
}
// SetDebug enables or disables debug mode for HTTP requests.
func (c *Client) SetDebug(debug bool) {
c.httpClient.SetDebug(debug)
}
// SetHeader sets a header on the HTTP client.
func (c *Client) SetHeader(header, value string) {
c.httpClient.SetHeader(header, value)
}
// GetHTTPClient returns the underlying HTTP client for use by services.
func (c *Client) GetHTTPClient() *resty.Client {
// Ensure we have a valid token before returning the client
// If token refresh fails, we'll let the individual API calls handle the error
_ = c.ensureValidToken()
return c.httpClient
}
// TestOAuth2Authentication tests actual OAuth2 authentication flow
// This test requires a real server with valid client credentials.
// Run with: go test -run TestOAuth2Authentication -tags=oauth2.
func TestOAuth2Authentication(clientID, clientSecret, baseURL string) error {
config := Config{
BaseURL: baseURL,
ClientID: clientID,
ClientSecret: clientSecret,
Timeout: 30 * time.Second, //nolint:mnd // default timeout for this auth test
// SkipTokenFetch is false by default, so it will attempt real authentication
}
client, err := NewClient(config)
if err != nil {
return fmt.Errorf("failed to create OAuth2 client: %w", err)
}
// Test that we have a valid token
token := client.GetToken()
if token == nil {
return errors.New("no token available after authentication")
}
if token.AccessToken == "" {
return errors.New("empty access token")
}
if token.TokenType != "Bearer" {
return fmt.Errorf("expected Bearer token type, got %s", token.TokenType)
}
return nil
}
// GetToken returns the current access token information.
func (c *Client) GetToken() *Token {
c.tokenMutex.RLock()
defer c.tokenMutex.RUnlock()
if c.token == nil {
return nil
}
// Return a copy to prevent external modification
return &Token{
AccessToken: c.token.AccessToken,
TokenType: c.token.TokenType,
Scope: c.token.Scope,
ExpiresAt: c.token.ExpiresAt,
}
}
// Error represents an API error response.
type Error struct {
StatusCode int `json:"status_code"`
Errors map[string][]string `json:"errors,omitempty"`
}
func (e *Error) Error() string {
if len(e.Errors) > 0 {
var errorParts []string
for field, messages := range e.Errors {
for _, message := range messages {
errorParts = append(errorParts, fmt.Sprintf("%s %s", field, message))
}
}
if e.StatusCode > 0 {
return fmt.Sprintf("API error %d: %s", e.StatusCode, strings.Join(errorParts, ", "))
}
return fmt.Sprintf("API error: %s", strings.Join(errorParts, ", "))
}
if e.StatusCode > 0 {
return fmt.Sprintf("API error %d", e.StatusCode)
}
return "API error"
}
// Response represents a standard API response wrapper.
type Response struct {
Success bool `json:"success"`
Data any `json:"data,omitempty"`
Error *Error `json:"error,omitempty"`
}