-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopen_command.go
More file actions
259 lines (237 loc) · 7.24 KB
/
Copy pathopen_command.go
File metadata and controls
259 lines (237 loc) · 7.24 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
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"time"
"github.com/rest-sh/restish/cli"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/term"
)
// consoleBaseURL is where deep links land. The API host is configurable via
// DCI_API_BASE_URL for testing, but console links always target production.
const consoleBaseURL = "https://console.doit.com"
var consoleResourcePaths = map[string]string{
"report": "analyze/reports",
"budget": "monitor/budgets",
"allocation": "operate/allocations",
}
var consoleCustomerIDResolver = resolveConsoleCustomerID
var consoleHTTPClient = &http.Client{Timeout: 10 * time.Second}
func registerOpenCommand(configDir string) {
cmd := &cobra.Command{
Use: "open [resource] [id]",
Short: "Open the DoiT console (optionally a specific report, budget, or allocation)",
Long: "Deep-links into the DoiT console for the active customer: `dci open` lands on the console home, " +
"`dci open report <id>` (also: budget, allocation) opens the resource. " +
"Opens a browser in interactive use; prints the URL in agent or non-interactive mode.",
Args: func(cmd *cobra.Command, args []string) error {
// An unquoted multi-word resource name arrives word-split by the
// shell; accept the surplus words when they can only be a name.
if openJoinableArgs(args) {
return nil
}
return cobra.RangeArgs(0, 2)(cmd, args)
},
RunE: func(cmd *cobra.Command, args []string) error {
consoleURL, err := consoleURLForArgs(configDir, args)
if err != nil {
return err
}
if agentMode || !term.IsTerminal(int(os.Stdout.Fd())) {
_, err := fmt.Fprintln(cmd.OutOrStdout(), consoleURL)
return err
}
if err := openInBrowser(consoleURL); err != nil {
_, writeErr := fmt.Fprintln(cmd.OutOrStdout(), consoleURL)
return writeErr
}
return nil
},
}
cli.Root.AddCommand(cmd)
}
func consoleURLForArgs(configDir string, args []string) (string, error) {
if len(args) == 0 {
return consoleBaseURL, nil
}
resources := make([]string, 0, len(consoleResourcePaths))
for resource := range consoleResourcePaths {
resources = append(resources, resource)
}
sort.Strings(resources)
if len(args) == 1 {
// One-argument interactive invocation: pick the resource by name
// (TUI-SPEC F1); everything else keeps the usage error.
id, err, handled := pickOpenResourceID(strings.ToLower(args[0]))
if !handled {
return "", fmt.Errorf("usage: dci open <%s> <id>", strings.Join(resources, "|"))
}
if err != nil {
return "", err
}
args = []string{args[0], id}
}
customerID, err := consoleCustomerID(configDir)
if err != nil {
return "", err
}
resourceID, err := resolveOpenResourceID(args[0], openResourceArgument(args), configDir)
if err != nil {
return "", err
}
resourceURL, ok := consoleResourceURL(customerID, args[0], resourceID)
if !ok {
return "", fmt.Errorf("unknown resource %q (supported: %s)", args[0], strings.Join(resources, ", "))
}
return resourceURL, nil
}
func consoleResourceURL(customerID, resource, resourceID string) (string, bool) {
path, ok := consoleResourcePaths[strings.ToLower(resource)]
if !ok {
return "", false
}
return fmt.Sprintf("%s/customers/%s/%s/%s", consoleBaseURL, customerID, path, resourceID), true
}
func consoleCustomerID(configDir string) (string, error) {
context := activeCustomerContext()
if context == "" {
context = readCustomerContext(configDir)
}
if context != "" {
if looksLikeCustomerID(context) {
return context, nil
}
return consoleCustomerIDResolver(context)
}
if customerID := tokenCustomerID(); customerID != "" {
return customerID, nil
}
return consoleCustomerIDResolver("")
}
func looksLikeCustomerID(s string) bool {
return len(s) >= 16 && !strings.Contains(s, ".")
}
func tokenCustomerID() string {
token := authenticationToken()
parts := strings.Split(token, ".")
if len(parts) != 3 {
return ""
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return ""
}
var claims struct {
CustomerID string `json:"customerId"`
LegacyCustomerID string `json:"CustomerID"`
}
if err := json.Unmarshal(payload, &claims); err != nil {
return ""
}
if claims.CustomerID == "" {
return claims.LegacyCustomerID
}
return claims.CustomerID
}
func authenticationToken() string {
if token := os.Getenv("DCI_API_KEY"); token != "" {
return token
}
if cli.Cache == nil {
return ""
}
profile := viper.GetString("rsh-profile")
if profile == "" {
profile = "default"
}
return cli.Cache.GetString("dci:" + profile + ".token")
}
func resolveConsoleCustomerID(context string) (string, error) {
token := authenticationToken()
if token == "" {
return "", fmt.Errorf("cannot determine the customer for console links: authenticate first")
}
base, err := apiBase()
if err != nil {
return "", err
}
requestURL, err := url.Parse(base + "/auth/v1/validate")
if err != nil {
return "", err
}
query := requestURL.Query()
if context != "" {
query.Set("customerContext", context)
}
requestURL.RawQuery = query.Encode()
request, err := http.NewRequest(http.MethodGet, requestURL.String(), nil)
if err != nil {
return "", err
}
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("User-Agent", buildUserAgent(agentUAMode))
if context != "" {
request.Header.Set("X-Tenant-Id", context)
}
response, err := consoleHTTPClient.Do(request)
if err != nil {
return "", fmt.Errorf("cannot resolve the active customer: %w", err)
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return "", consoleCustomerResolutionError(response)
}
if customerID := strings.TrimSpace(response.Header.Get("X-DoiT-Customer-ID")); looksLikeCustomerID(customerID) {
return customerID, nil
}
return "", fmt.Errorf("cannot resolve the active customer: the API did not return a customer ID; set a customer-ID context with dci customer-context set <customer-id>")
}
type consoleAPIError struct {
status int
message string
headers map[string]string
}
func (err consoleAPIError) Error() string {
return err.message
}
func (err consoleAPIError) ExitCode() int {
return exitCodeForHTTPStatus(err.status)
}
func (err consoleAPIError) StructuredError() structuredError {
return structuredErrorForStatus(err.status, err.message, err.headers)
}
func diagnosticResponseHeaders(response *http.Response) map[string]string {
headers := make(map[string]string)
for _, name := range []string{"X-Request-Id", "X-Doit-Trace", "Cf-Ray", "X-Cloud-Trace-Context", "Traceparent", "Retry-After", "X-Retry-In"} {
if value := response.Header.Get(name); value != "" {
headers[name] = value
}
}
return headers
}
func consoleCustomerResolutionError(response *http.Response) error {
return consoleAPIError{
status: response.StatusCode,
message: fmt.Sprintf("cannot resolve the active customer: API returned %s", response.Status),
headers: diagnosticResponseHeaders(response),
}
}
func openInBrowser(url string) error {
switch runtime.GOOS {
case "darwin":
return exec.Command("open", url).Start()
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
default:
return exec.Command("xdg-open", url).Start()
}
}