-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.go
More file actions
593 lines (510 loc) · 20.4 KB
/
auth.go
File metadata and controls
593 lines (510 loc) · 20.4 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
package threads
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
// TokenResponse represents the response from token exchange endpoint.
// This structure is returned when exchanging an authorization code for an access token.
// The access token can then be used to authenticate API requests.
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in,omitempty"`
UserID int64 `json:"user_id,omitempty"`
}
// LongLivedTokenResponse represents the response from long-lived token conversion endpoint.
// Long-lived tokens typically last for 60 days compared to short-lived tokens which last 1 hour.
// Convert short-lived tokens to long-lived tokens for better user experience.
type LongLivedTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
}
// AppAccessTokenResponse represents the response from the client_credentials token endpoint.
// Unlike user token responses, app access tokens do not include expires_in or user_id fields.
type AppAccessTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
}
// generateState generates a random state parameter for OAuth security
func generateState() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", fmt.Errorf("failed to generate state: %w", err)
}
return base64.URLEncoding.EncodeToString(b), nil
}
// GetAuthURL generates the authorization URL for the OAuth 2.0 flow along with
// the random state parameter embedded in it. Callers MUST persist the returned
// state in the user's session (e.g. a signed cookie) and pass it as
// expectedState to ExchangeCodeForToken when the provider redirects back,
// comparing it against the state echoed on the callback. This is required by
// RFC 6749 §10.12 and OAuth 2.0 Security BCP §4.7 to prevent login/CSRF and
// authorization-code fixation attacks.
//
// If scopes are not provided, defaults to threads_basic and
// threads_content_publish. Returns an error if the system's secure random
// source is unavailable; in that case no URL is returned so callers cannot
// accidentally issue a flow with a guessable state (fail closed).
func (c *Client) GetAuthURL(scopes []string) (authURL, state string, err error) {
if len(scopes) == 0 {
scopes = []string{"threads_basic", "threads_content_publish"}
}
state, err = generateState()
if err != nil {
return "", "", err
}
params := url.Values{
"client_id": {c.config.ClientID},
"redirect_uri": {c.config.RedirectURI},
"scope": {strings.Join(scopes, ",")}, // Use comma-separated scopes
"response_type": {"code"},
"state": {state},
}
authURL = fmt.Sprintf("https://www.threads.net/oauth/authorize?%s", params.Encode())
return authURL, state, nil
}
// ExchangeCodeForToken exchanges an authorization code for an access token.
// This should be called after the user authorizes your app and the provider
// redirects back with a code and state.
//
// expectedState is the state value that was returned by GetAuthURL and
// persisted in the user's session; receivedState is the state query parameter
// echoed on the callback. Both must be non-empty and must match (compared in
// constant time). A mismatch indicates an OAuth CSRF / authorization-code
// fixation attack and the exchange is refused before any network call.
//
// The resulting token is automatically stored in the client and token storage.
func (c *Client) ExchangeCodeForToken(ctx context.Context, code, expectedState, receivedState string) error {
if code == "" {
return NewValidationError(400, "Authorization code is required", "Code parameter cannot be empty", "code")
}
if expectedState == "" {
return NewValidationError(400, "Expected state is required", "expectedState must be the value returned by GetAuthURL and persisted in the user's session", "expected_state")
}
if receivedState == "" {
return NewValidationError(400, "Received state is required", "receivedState must be the state query parameter echoed by the provider on the callback", "received_state")
}
if subtle.ConstantTimeCompare([]byte(expectedState), []byte(receivedState)) != 1 {
return NewAuthenticationError(400, "OAuth state mismatch", "The state parameter returned by the provider does not match the one issued by GetAuthURL; possible CSRF/code-fixation attempt")
}
data := url.Values{
"client_id": {c.config.ClientID},
"client_secret": {c.config.ClientSecret},
"grant_type": {"authorization_code"},
"redirect_uri": {c.config.RedirectURI},
"code": {code},
}
resp, err := c.httpClient.POST("/oauth/access_token", data, "")
if err != nil {
return NewNetworkError(0, "Failed to exchange code for token", err.Error(), true)
}
if resp.StatusCode != http.StatusOK {
return c.handleTokenError(resp.StatusCode, resp.Body)
}
var tokenResp TokenResponse
if err := json.Unmarshal(resp.Body, &tokenResp); err != nil {
return NewAPIError(resp.StatusCode, "Failed to parse token response", err.Error(), "")
}
// Create token info with expiration
now := time.Now()
var expiresAt time.Time
if tokenResp.ExpiresIn > 0 {
expiresAt = now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
} else {
// Fallback if API doesn't provide expires_in (shouldn't happen but just in case)
expiresAt = now.Add(time.Hour) // Short-lived tokens typically expire in 1 hour
}
tokenInfo := &TokenInfo{
AccessToken: tokenResp.AccessToken,
TokenType: tokenResp.TokenType,
ExpiresAt: expiresAt,
UserID: fmt.Sprintf("%d", tokenResp.UserID),
CreatedAt: now,
}
// Store the token using thread-safe method
if err := c.SetTokenInfo(tokenInfo); err != nil {
if c.config.Logger != nil {
c.config.Logger.Warn("Failed to store token", "error", err.Error())
}
}
// Log successful authentication if logger is available
if c.config.Logger != nil {
c.config.Logger.Info("Successfully exchanged authorization code for access token",
"user_id", fmt.Sprintf("%d", tokenResp.UserID),
"token_type", tokenResp.TokenType,
"expires_at", expiresAt)
}
return nil
}
// GetLongLivedToken converts a short-lived token to a long-lived token.
// Short-lived tokens expire in 1 hour while long-lived tokens last for 60 days.
// This method requires an existing valid short-lived token in the client.
// The long-lived token automatically replaces the short-lived token in storage.
func (c *Client) GetLongLivedToken(ctx context.Context) error {
c.mu.RLock()
currentToken := c.accessToken
c.mu.RUnlock()
if currentToken == "" {
return NewAuthenticationError(401, "No access token available", "Must exchange authorization code for token first")
}
params := url.Values{
"grant_type": {"th_exchange_token"},
"client_secret": {c.config.ClientSecret},
"access_token": {currentToken},
}
resp, err := c.httpClient.GET("/access_token", params, currentToken)
if err != nil {
return NewNetworkError(0, "Failed to get long-lived token", err.Error(), true)
}
if resp.StatusCode != http.StatusOK {
return c.handleTokenError(resp.StatusCode, resp.Body)
}
var tokenResp LongLivedTokenResponse
if err := json.Unmarshal(resp.Body, &tokenResp); err != nil {
return NewAPIError(resp.StatusCode, "Failed to parse long-lived token response", err.Error(), "")
}
// Update token info with long-lived token
now := time.Now()
var expiresAt time.Time
if tokenResp.ExpiresIn > 0 {
expiresAt = now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
} else {
// Fallback if API doesn't provide expires_in (shouldn't happen for long-lived tokens)
expiresAt = now.Add(60 * 24 * time.Hour) // 60 days default
}
// Create new token info with long-lived token
c.mu.RLock()
var userID string
if c.tokenInfo != nil {
userID = c.tokenInfo.UserID
}
c.mu.RUnlock()
tokenInfo := &TokenInfo{
AccessToken: tokenResp.AccessToken,
TokenType: tokenResp.TokenType,
ExpiresAt: expiresAt,
UserID: userID,
CreatedAt: now,
}
// Store the token using thread-safe method
if err := c.SetTokenInfo(tokenInfo); err != nil {
if c.config.Logger != nil {
c.config.Logger.Warn("Failed to store long-lived token", "error", err.Error())
}
}
// Log successful long-lived token conversion if logger is available
if c.config.Logger != nil {
c.config.Logger.Info("Successfully converted to long-lived token",
"expires_in_seconds", tokenResp.ExpiresIn,
"expires_at", expiresAt,
"token_type", tokenResp.TokenType)
}
return nil
}
// RefreshToken refreshes the current access token before it expires.
// This extends the validity of your existing token without requiring user re-authorization.
// The refreshed token automatically replaces the current token in storage.
// Note: Only long-lived tokens can be refreshed.
func (c *Client) RefreshToken(ctx context.Context) error {
c.mu.RLock()
currentToken := c.accessToken
c.mu.RUnlock()
if currentToken == "" {
return NewAuthenticationError(401, "No access token to refresh", "Must have an existing token to refresh")
}
params := url.Values{
"grant_type": {"th_refresh_token"},
"access_token": {currentToken},
}
resp, err := c.httpClient.GET("/refresh_access_token", params, "")
if err != nil {
return NewNetworkError(0, "Failed to refresh token", err.Error(), true)
}
if resp.StatusCode != http.StatusOK {
return c.handleTokenError(resp.StatusCode, resp.Body)
}
var tokenResp LongLivedTokenResponse
if err := json.Unmarshal(resp.Body, &tokenResp); err != nil {
return NewAPIError(resp.StatusCode, "Failed to parse token refresh response", err.Error(), "")
}
// Update token info with refreshed token
now := time.Now()
var expiresAt time.Time
if tokenResp.ExpiresIn > 0 {
expiresAt = now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
} else {
// Fallback if API doesn't provide expires_in (shouldn't happen for refreshed tokens)
expiresAt = now.Add(60 * 24 * time.Hour) // 60 days default
}
// Create new token info with refreshed token
c.mu.RLock()
var userID string
if c.tokenInfo != nil {
userID = c.tokenInfo.UserID
}
c.mu.RUnlock()
tokenInfo := &TokenInfo{
AccessToken: tokenResp.AccessToken,
TokenType: tokenResp.TokenType,
ExpiresAt: expiresAt,
UserID: userID,
CreatedAt: now,
}
// Store the token using thread-safe method
if err := c.SetTokenInfo(tokenInfo); err != nil {
if c.config.Logger != nil {
c.config.Logger.Warn("Failed to store refreshed token", "error", err.Error())
}
}
// Log successful token refresh if logger is available
if c.config.Logger != nil {
c.config.Logger.Info("Successfully refreshed access token",
"expires_in_seconds", tokenResp.ExpiresIn,
"expires_at", expiresAt,
"token_type", tokenResp.TokenType)
}
return nil
}
// handleTokenError processes token-related API errors
func (c *Client) handleTokenError(statusCode int, body []byte) error {
var errorResp struct {
Error struct {
Message string `json:"message"`
Type string `json:"type"`
Code int `json:"code"`
ErrorData struct {
Details string `json:"details"`
} `json:"error_data"`
} `json:"error"`
}
if err := json.Unmarshal(body, &errorResp); err != nil {
// If we can't parse the error response, return a generic error
return NewAuthenticationError(statusCode, "Authentication failed", string(body))
}
message := errorResp.Error.Message
details := errorResp.Error.ErrorData.Details
errorType := errorResp.Error.Type
// Map common error types to appropriate error categories
switch {
case statusCode == 401 || strings.Contains(errorType, "auth") || strings.Contains(message, "token"):
return NewAuthenticationError(statusCode, message, details)
case statusCode == 429 || strings.Contains(errorType, "rate"):
// Try to extract retry-after from headers if available
return NewRateLimitError(statusCode, message, details, 60*time.Second)
case statusCode >= 400 && statusCode < 500:
return NewValidationError(statusCode, message, details, "")
default:
return NewAPIError(statusCode, message, details, "")
}
}
// GetAccessToken returns the current access token in a thread-safe manner.
// This method is primarily intended for debugging and testing purposes.
// For production use, the client handles token management automatically.
func (c *Client) GetAccessToken() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.accessToken
}
// getAccessTokenSafe returns the current access token in a thread-safe manner
// This is an internal method for use by other client methods
func (c *Client) getAccessTokenSafe() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.accessToken
}
// LoadTokenFromStorage attempts to load a previously stored token from the configured storage.
// If a valid token is found, it's automatically set as the active token for the client.
// Returns an error if no token is found, if the token is expired, or if loading fails.
func (c *Client) LoadTokenFromStorage() error {
tokenInfo, err := c.tokenStorage.Load()
if err != nil {
return err
}
// Check if loaded token is expired
if time.Now().After(tokenInfo.ExpiresAt) {
// Token is expired, clear it
err := c.tokenStorage.Delete()
if err != nil {
return err
}
return NewAuthenticationError(401, "Stored token expired", "Token found in storage but expired")
}
// Use thread-safe method to set token
if err := c.SetTokenInfo(tokenInfo); err != nil {
return err
}
if c.config.Logger != nil {
c.config.Logger.Info("Successfully loaded token from storage",
"expires_at", tokenInfo.ExpiresAt,
"user_id", tokenInfo.UserID)
}
return nil
}
// GetTokenDebugInfo returns detailed token information for debugging purposes.
// This method provides comprehensive information about the current token state including
// expiration times, validity checks, and calculated values useful for troubleshooting.
// The returned map contains various fields like has_token, is_authenticated, expires_at, etc.
func (c *Client) GetTokenDebugInfo() map[string]interface{} {
c.mu.RLock()
defer c.mu.RUnlock()
debugInfo := map[string]interface{}{
"has_token": c.accessToken != "",
"is_authenticated": c.IsAuthenticated(),
"is_expired": c.IsTokenExpired(),
}
if c.tokenInfo != nil {
now := time.Now()
timeUntilExpiry := c.tokenInfo.ExpiresAt.Sub(now)
debugInfo["token_type"] = c.tokenInfo.TokenType
debugInfo["user_id"] = c.tokenInfo.UserID
debugInfo["created_at"] = c.tokenInfo.CreatedAt
debugInfo["expires_at"] = c.tokenInfo.ExpiresAt
debugInfo["time_until_expiry"] = timeUntilExpiry.String()
debugInfo["expires_in_hours"] = timeUntilExpiry.Hours()
debugInfo["expires_in_days"] = timeUntilExpiry.Hours() / 24
debugInfo["expiring_soon_1h"] = c.IsTokenExpiringSoon(time.Hour)
debugInfo["expiring_soon_24h"] = c.IsTokenExpiringSoon(24 * time.Hour)
debugInfo["expiring_soon_7d"] = c.IsTokenExpiringSoon(7 * 24 * time.Hour)
}
return debugInfo
}
// DebugTokenResponse represents the response from the debug_token endpoint
type DebugTokenResponse struct {
Data struct {
Type string `json:"type"`
Application string `json:"application"`
DataAccessExpiresAt int64 `json:"data_access_expires_at"`
ExpiresAt int64 `json:"expires_at"`
IsValid bool `json:"is_valid"`
IssuedAt int64 `json:"issued_at"`
Scopes []string `json:"scopes"`
UserID string `json:"user_id"`
} `json:"data"`
}
// DebugToken calls the debug_token endpoint to get detailed token information.
// If inputToken is empty, it will debug the client's current access token.
// This method is useful for validating token status, checking expiration times,
// and retrieving token metadata like scopes and user information.
func (c *Client) DebugToken(ctx context.Context, inputToken string) (*DebugTokenResponse, error) {
c.mu.RLock()
accessToken := c.accessToken
c.mu.RUnlock()
if accessToken == "" {
return nil, NewAuthenticationError(401, "No access token available", "Client must be authenticated to debug tokens")
}
if inputToken == "" {
inputToken = accessToken
}
params := url.Values{
"input_token": {inputToken},
"access_token": {accessToken},
}
resp, err := c.httpClient.GET("/debug_token", params, accessToken)
if err != nil {
return nil, NewNetworkError(0, "Failed to debug token", err.Error(), true)
}
if resp.StatusCode != http.StatusOK {
return nil, c.handleTokenError(resp.StatusCode, resp.Body)
}
var debugResp DebugTokenResponse
if err := json.Unmarshal(resp.Body, &debugResp); err != nil {
return nil, NewAPIError(resp.StatusCode, "Failed to parse debug token response", err.Error(), "")
}
if c.config.Logger != nil {
c.config.Logger.Debug("Debug token response received",
"is_valid", debugResp.Data.IsValid,
"expires_at", debugResp.Data.ExpiresAt,
"issued_at", debugResp.Data.IssuedAt,
"user_id", debugResp.Data.UserID,
"scopes", debugResp.Data.Scopes)
}
return &debugResp, nil
}
// GetAppAccessToken generates an app access token via the client_credentials OAuth flow.
// Unlike user access tokens, the returned token is NOT stored in the client — app tokens
// serve a different purpose and should be managed separately by the caller.
// This requires ClientID and ClientSecret to be set in the client configuration.
//
// NOTE: The Threads API requires GET for this endpoint (not the POST + body
// approach specified in RFC 6749 §4.4). As a result, client_secret appears in
// the request URL. Only call this from a server-side environment.
func (c *Client) GetAppAccessToken(ctx context.Context) (*AppAccessTokenResponse, error) {
params := url.Values{
"client_id": {c.config.ClientID},
"client_secret": {c.config.ClientSecret},
"grant_type": {"client_credentials"},
}
resp, err := c.httpClient.GET("/oauth/access_token", params, "")
if err != nil {
return nil, NewNetworkError(0, "Failed to get app access token", err.Error(), true)
}
if resp.StatusCode != http.StatusOK {
return nil, c.handleTokenError(resp.StatusCode, resp.Body)
}
var tokenResp AppAccessTokenResponse
if err := json.Unmarshal(resp.Body, &tokenResp); err != nil {
return nil, NewAPIError(resp.StatusCode, "Failed to parse app access token response", err.Error(), "")
}
if c.config.Logger != nil {
c.config.Logger.Info("Successfully obtained app access token",
"token_type", tokenResp.TokenType)
}
return &tokenResp, nil
}
// GetAppAccessTokenShorthand returns the shorthand app token in the form TH|<APP_ID>|<APP_SECRET>.
// This can be used directly as an access token for certain API operations without making an API call.
// See the Threads API documentation for which endpoints accept this format.
// Returns an empty string if ClientID or ClientSecret are not configured.
func (c *Client) GetAppAccessTokenShorthand() string {
if c.config.ClientID == "" || c.config.ClientSecret == "" {
return ""
}
return "TH|" + c.config.ClientID + "|" + c.config.ClientSecret
}
// SetTokenFromDebugInfo creates and sets token info from debug token response.
// This method takes the response from the debug_token endpoint and creates a properly
// configured TokenInfo struct with accurate expiration times based on the API response.
// This is useful for setting up tokens when you have the debug information available.
func (c *Client) SetTokenFromDebugInfo(accessToken string, debugResp *DebugTokenResponse) error {
if debugResp == nil {
return fmt.Errorf("debug response cannot be nil")
}
if !debugResp.Data.IsValid {
return NewAuthenticationError(401, "Token is not valid", "Debug token endpoint reports token as invalid")
}
// Convert Unix timestamps to time.Time
expiresAt := time.Unix(debugResp.Data.ExpiresAt, 0)
issuedAt := time.Unix(debugResp.Data.IssuedAt, 0)
tokenInfo := &TokenInfo{
AccessToken: accessToken,
TokenType: "Bearer", // Threads API uses Bearer tokens
ExpiresAt: expiresAt,
UserID: debugResp.Data.UserID,
CreatedAt: issuedAt, // Use the issued_at from the API
}
// Store the token using thread-safe method
if err := c.SetTokenInfo(tokenInfo); err != nil {
return fmt.Errorf("failed to store token info: %w", err)
}
if c.config.Logger != nil {
lifetime := expiresAt.Sub(issuedAt)
c.config.Logger.Info("Token info set from debug response",
"user_id", debugResp.Data.UserID,
"expires_at", expiresAt,
"issued_at", issuedAt,
"lifetime_hours", lifetime.Hours(),
"lifetime_days", lifetime.Hours()/24,
"scopes", debugResp.Data.Scopes)
}
return nil
}