-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathauth.go
More file actions
309 lines (252 loc) · 9.61 KB
/
auth.go
File metadata and controls
309 lines (252 loc) · 9.61 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
package cmd
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/timescale/tiger-cli/internal/tiger/api"
"github.com/timescale/tiger-cli/internal/tiger/common"
"github.com/timescale/tiger-cli/internal/tiger/config"
"github.com/timescale/tiger-cli/internal/tiger/util"
)
// validateAPIKey can be overridden for testing
var validateAPIKey = common.ValidateAPIKey
// nextStepsMessage is the message shown after successful login
const nextStepsMessage = `
🎉 Next steps:
• Install MCP server for your favorite AI coding tool: tiger mcp install
• List existing services: tiger service list
• Create a new service: tiger service create
`
type credentials struct {
publicKey string
secretKey string
}
func buildLoginCmd() *cobra.Command {
var flags credentials
cmd := &cobra.Command{
Use: "login",
Short: "Authenticate with Tiger Cloud API",
Long: `Authenticate with Tiger Cloud API using predefined keys or an interactive OAuth flow
By default, the command will launch an interactive OAuth flow in your browser to create new API keys.
The OAuth flow will:
- Open your browser for authentication
- Let you select a project (if you have multiple)
- Create API keys automatically for the selected project
The keys and project ID will be stored securely in the system keyring, or in a fallback file with
restricted permissions.
You may also provide API keys via flags or environment variables, in which case they will be used
directly. The CLI will prompt for any missing information.
You can find your API credentials at: https://console.cloud.timescale.com/dashboard/settings
Examples:
# Interactive login with OAuth (opens browser, creates API keys automatically)
tiger auth login
# Login with keys (project ID will be auto-detected)
tiger auth login --public-key your-public-key --secret-key your-secret-key
# Login using environment variables
export TIGER_PUBLIC_KEY="your-public-key"
export TIGER_SECRET_KEY="your-secret-key"
tiger auth login`,
Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
// Get config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
creds := credentials{
publicKey: flagOrEnvVar(flags.publicKey, "TIGER_PUBLIC_KEY"),
secretKey: flagOrEnvVar(flags.secretKey, "TIGER_SECRET_KEY"),
}
if creds.publicKey == "" && creds.secretKey == "" {
// If no credentials were provided, start interactive OAuth login flow
l := &oauthLogin{
authURL: cfg.ConsoleURL + "/oauth/authorize",
tokenURL: cfg.GatewayURL + "/idp/external/cli/token",
successURL: cfg.ConsoleURL + "/oauth/code/success",
graphql: &GraphQLClient{
URL: cfg.GatewayURL + "/query",
},
out: cmd.OutOrStdout(),
}
creds, err = l.loginWithOAuth(cmd.Context())
if err != nil {
return err
}
} else if creds.publicKey == "" || creds.secretKey == "" {
// If some credentials were provided, prompt for missing ones
creds, err = promptForCredentials(cmd.Context(), cfg.ConsoleURL, creds)
if err != nil {
return fmt.Errorf("failed to get credentials: %w", err)
}
if creds.publicKey == "" || creds.secretKey == "" {
return fmt.Errorf("both public key and secret key are required")
}
}
// Combine the keys in the format "public:secret" for storage
apiKey := fmt.Sprintf("%s:%s", creds.publicKey, creds.secretKey)
// Create API client
client, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return fmt.Errorf("failed to create client: %w", err)
}
// Validate the API key and get auth info by calling the /auth/info endpoint
fmt.Fprintln(cmd.OutOrStdout(), "Validating API key...")
authInfo, err := validateAPIKey(cmd.Context(), cfg, client)
if err != nil {
return fmt.Errorf("API key validation failed: %w", err)
}
// Store the credentials (API key + project ID) together securely
if err := config.StoreCredentials(apiKey, authInfo.ApiKey.Project.Id); err != nil {
return fmt.Errorf("failed to store credentials: %w", err)
}
fmt.Fprintf(cmd.OutOrStdout(), "Successfully logged in (project: %s)\n", authInfo.ApiKey.Project.Id)
// Show helpful next steps
fmt.Fprint(cmd.OutOrStdout(), nextStepsMessage)
return nil
},
}
// Add flags
cmd.Flags().StringVar(&flags.publicKey, "public-key", "", "Public key for authentication")
cmd.Flags().StringVar(&flags.secretKey, "secret-key", "", "Secret key for authentication")
return cmd
}
func buildLogoutCmd() *cobra.Command {
return &cobra.Command{
Use: "logout",
Short: "Remove stored credentials",
Long: `Remove stored API key and clear authentication credentials.`,
Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
if err := config.RemoveCredentials(); err != nil {
return fmt.Errorf("failed to remove credentials: %w", err)
}
fmt.Fprintln(cmd.OutOrStdout(), "Successfully logged out and removed stored credentials")
return nil
},
}
}
func buildStatusCmd() *cobra.Command {
var output string
cmd := &cobra.Command{
Use: "status",
Short: "Show current authentication status and project ID",
Long: "Displays whether you are logged in and shows your currently configured project ID.",
Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
PreRunE: bindFlags("output"),
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
// Load config and API client
cfg, err := common.LoadConfig(cmd.Context())
if err != nil {
if errors.Is(err, config.ErrNotLoggedIn) {
return common.ExitWithCode(common.ExitAuthenticationError, config.ErrNotLoggedIn)
}
return err
}
// Make API call to get auth information
ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
defer cancel()
resp, err := cfg.Client.GetAuthInfoWithResponse(ctx)
if err != nil {
return fmt.Errorf("failed to get auth information: %w", err)
}
// Handle API response
if resp.StatusCode() != 200 {
return common.ExitWithErrorFromStatusCode(resp.StatusCode(), resp.JSON4XX)
}
if resp.JSON200 == nil {
return fmt.Errorf("empty response from API")
}
authInfo := *resp.JSON200
// Output auth info in requested format
return outputAuthInfo(cmd, authInfo, cfg.Output)
},
}
cmd.Flags().VarP((*outputFlag)(&output), "output", "o", "output format (json, yaml, table)")
return cmd
}
func buildAuthCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Manage authentication and credentials",
Long: `Manage authentication and credentials for Tiger Cloud platform.`,
}
cmd.AddCommand(buildLoginCmd())
cmd.AddCommand(buildLogoutCmd())
cmd.AddCommand(buildStatusCmd())
return cmd
}
// outputAuthInfo formats and outputs authentication information based on the specified format
func outputAuthInfo(cmd *cobra.Command, authInfo api.AuthInfo, format string) error {
outputWriter := cmd.OutOrStdout()
switch strings.ToLower(format) {
case "json":
return util.SerializeToJSON(outputWriter, authInfo)
case "yaml":
return util.SerializeToYAML(outputWriter, authInfo)
default: // table format (default)
return outputAuthInfoTable(authInfo, outputWriter)
}
}
// outputAuthInfoTable outputs authentication information in a formatted table
func outputAuthInfoTable(authInfo api.AuthInfo, output io.Writer) error {
table := tablewriter.NewWriter(output)
table.Header("PROPERTY", "VALUE")
// Convert plan type to title case for display
planType := cases.Title(language.English).String(authInfo.ApiKey.Project.PlanType)
table.Append("Status", "Logged in")
table.Append("Credential Name", authInfo.ApiKey.Name)
table.Append("Public Key", authInfo.ApiKey.PublicKey)
table.Append("Created At", authInfo.ApiKey.Created.Format("2006-01-02 15:04:05 MST"))
table.Append("Project", fmt.Sprintf("%s (%s)", authInfo.ApiKey.Project.Name, authInfo.ApiKey.Project.Id))
table.Append("Plan Type", planType)
table.Append("Issuing User", fmt.Sprintf("%s (%s)", authInfo.ApiKey.IssuingUser.Name, authInfo.ApiKey.IssuingUser.Email))
return table.Render()
}
func flagOrEnvVar(flagVal, envVarName string) string {
if flagVal != "" {
return flagVal
}
return os.Getenv(envVarName)
}
// promptForCredentials prompts the user to enter any missing credentials
func promptForCredentials(ctx context.Context, consoleURL string, creds credentials) (credentials, error) {
// Check if we're in a terminal for interactive input
if !util.IsTerminal(os.Stdin) {
return credentials{}, fmt.Errorf("TTY not detected - credentials required. Use flags (--public-key, --secret-key) or environment variables (TIGER_PUBLIC_KEY, TIGER_SECRET_KEY)")
}
fmt.Printf("You can find your API credentials at: %s/dashboard/settings\n\n", consoleURL)
// Prompt for public key if missing
if creds.publicKey == "" {
fmt.Print("Enter your public key: ")
publicKey, err := readLine(ctx, os.Stdin)
if err != nil {
return credentials{}, err
}
creds.publicKey = publicKey
}
// Prompt for secret key if missing
if creds.secretKey == "" {
fmt.Print("Enter your secret key: ")
password, err := readPassword(ctx, os.Stdin)
if err != nil {
return credentials{}, err
}
fmt.Println() // Print newline after hidden input
creds.secretKey = password
}
return creds, nil
}