Repository navigation
Expand file tree
/
Copy pathinvocation_preflight.go
More file actions
422 lines (389 loc) · 14.2 KB
/
Copy pathinvocation_preflight.go
File metadata and controls
422 lines (389 loc) · 14.2 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
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/rest-sh/restish/cli"
"github.com/spf13/viper"
"golang.org/x/term"
)
type invocationPreflightError struct {
detail structuredError
exitCode int
}
func (preflightError invocationPreflightError) Error() string {
return preflightError.detail.Message
}
func (preflightError invocationPreflightError) ExitCode() int {
return preflightError.exitCode
}
func (preflightError invocationPreflightError) StructuredError() structuredError {
return preflightError.detail
}
var loadInvocationAPI = loadDCIOperationAPI
var invocationCredentialsAvailable = credentialsAvailableForInvocation
var invocationCachedSpecAvailable = cachedSpecAvailableForInvocation
var invocationInteractive = func() bool {
return invocationCanAuthenticateInteractively(term.IsTerminal(int(os.Stdin.Fd())))
}
func invocationCanAuthenticateInteractively(stdinTTY bool) bool {
return agentUAMode != uaModeAgent && stdinTTY
}
func preflightAPIInvocation(args []string) error {
if len(args) < 3 || args[1] != "dci" {
return nil
}
commandName := apiInvocationCommandName(args)
if commandName == "" {
return nil
}
if commandName == "beta" {
// Beta commands validate against the embedded beta surface, not the
// GA spec — beta_commands.go owns that preflight.
return preflightBetaInvocation(args)
}
if localDCICommandRegistered(commandName) {
// Hand-registered local commands (question_commands.go and similar)
// are not GA-spec operations, so the unknown-command check below does
// not apply. They still fall through to the ordinary authentication
// check just below.
return preflightLocalDCICommand(commandName, args)
}
if invocationRequestsHelp(args) {
// Help needs the API description and nothing else — no request of
// its own ever carries credentials. run() warms the spec cache from
// the public description before restish loads it (help_spec.go), so
// help renders on a fresh install and with an expired session alike,
// and skips both the credential gate below and operation validation.
return nil
}
authenticated := invocationCredentialsAvailable()
interactive := invocationInteractive()
if !authenticated && !interactive && !invocationCachedSpecAvailable() {
return authenticationRequiredPreflightError()
}
api, err := loadInvocationAPI()
if err != nil || len(api.Operations) == 0 {
var loginError headlessLoginError
if errors.As(err, &loginError) {
// The stored session could not authenticate the description
// fetch (expired, refresh rejected, no browser): that is the
// invocation's answer, in the contract's shape — retrying the
// same fetch inside cli.Run would only fail the same way.
return err
}
if !authenticated && !interactive {
return authenticationRequiredPreflightError()
}
return nil
}
setOperationMetadata(api.Operations)
operation := invocationOperation(api, commandName)
if operation == nil {
return unknownAPICommandPreflightError(api, commandName)
}
if err := validateMaxResults(operation.Name, args[2:]); err != nil {
return err
}
if err := validateAllPagesFlags(args[2:]); err != nil {
return err
}
if err := validateSearchFlags(args[2:]); err != nil {
return err
}
if err := validatePagingFlagsSupported(operation, args[2:]); err != nil {
return err
}
if err := validateExportWindow(operation.Name, args[2:]); err != nil {
return err
}
if err := validateReimportFlag(operation.Name, args[2:]); err != nil {
return err
}
if err := validateSearchOnFileExport(operation.Name, args[2:]); err != nil {
return err
}
if authenticated || interactive || invocationHasFlag(args, "--dry-run") {
return nil
}
return authenticationRequiredPreflightError()
}
// questionCommandNames lists the hand-registered local commands under dciCmd
// that are not GA-spec operations (question_commands.go). "beta" is handled
// by its own preflightBetaInvocation branch above and does not belong here.
var questionCommandNames = map[string]bool{
"budgets-at-risk": true,
"anomalies-recent": true,
}
func localDCICommandRegistered(commandName string) bool {
return questionCommandNames[commandName]
}
// preflightLocalDCICommand validates a hand-registered local command the way
// preflightAPIInvocation validates a GA one, minus the GA spec load and
// unknown-command lookup: the command's own existence is already known by
// construction. Help is checked first, matching preflightAPIInvocation's
// order, so an out-of-range flag value never hides the help text. The flag
// validations below it still apply: --all/--search are persistent dciCmd
// flags budgets-at-risk/anomalies-recent inherit like every GA command, and
// validateMaxResults protects the same silent-clamp hazard it protects for
// list-budgets — budgets-at-risk wraps it directly and inherits its 250 cap
// (pagingCaps).
func preflightLocalDCICommand(commandName string, args []string) error {
if invocationRequestsHelp(args) {
return nil
}
if err := validateMaxResults(commandName, args[2:]); err != nil {
return err
}
if err := validateAllPagesFlags(args[2:]); err != nil {
return err
}
if err := validateSearchFlags(args[2:]); err != nil {
return err
}
if err := validateReimportFlag(commandName, args[2:]); err != nil {
return err
}
if invocationCredentialsAvailable() || invocationInteractive() || invocationHasFlag(args, "--dry-run") {
return nil
}
return authenticationRequiredPreflightError()
}
func invocationRequestsHelp(args []string) bool {
for _, argument := range args[2:] {
if argument == "--help" || argument == "-h" {
return true
}
}
return false
}
func apiInvocationCommandName(args []string) string {
if cli.Root == nil {
return commandArg(args, 2)
}
rootFlags := cli.Root.PersistentFlags()
dciCommand := findDCICommand()
if dciCommand != nil {
return commandArg(args, 2, rootFlags, dciCommand.PersistentFlags())
}
return commandArg(args, 2, rootFlags)
}
func invocationOperation(api cli.API, name string) *cli.Operation {
for index := range api.Operations {
operation := &api.Operations[index]
if operation.Name == name {
return operation
}
for _, alias := range operation.Aliases {
if alias == name {
return operation
}
}
}
return nil
}
func unknownAPICommandPreflightError(api cli.API, name string) error {
suggestion := closestAPICommand(api, name)
message := fmt.Sprintf("unknown command %q", name)
hint := "Run dci --help to list available commands"
if suggestion != "" {
message = fmt.Sprintf("unknown command %q (did you mean %q?)", name, suggestion)
hint = fmt.Sprintf("Did you mean %q? Run dci --help to list available commands", suggestion)
}
if tuiActive() {
// Humans only (agents never pass the gate): a mistyped command is the
// natural moment to learn the plain-English spelling — the error stays
// an error, never a silent AI fallback (AI-DEFAULT-SPEC §5).
message += "\nTo ask in plain English instead: dci ai \"<your question>\""
}
return invocationPreflightError{
detail: structuredError{Code: "USAGE_ERROR", Message: message, Hint: hint, Retryable: false},
exitCode: exitUsage,
}
}
func closestAPICommand(api cli.API, name string) string {
closest := ""
closestDistance := 3
prefix := ""
for _, operation := range api.Operations {
for _, candidate := range append([]string{operation.Name}, operation.Aliases...) {
if prefix == "" && strings.HasPrefix(candidate, name) {
prefix = candidate
}
distance := editDistance(name, candidate)
if distance < closestDistance {
closestDistance = distance
closest = candidate
}
}
}
if closest == "" {
return prefix
}
return closest
}
func editDistance(left, right string) int {
leftRunes := []rune(left)
rightRunes := []rune(right)
previous := make([]int, len(rightRunes)+1)
current := make([]int, len(rightRunes)+1)
for index := range previous {
previous[index] = index
}
for leftIndex := 1; leftIndex <= len(leftRunes); leftIndex++ {
current[0] = leftIndex
for rightIndex := 1; rightIndex <= len(rightRunes); rightIndex++ {
changeCost := 1
if leftRunes[leftIndex-1] == rightRunes[rightIndex-1] {
changeCost = 0
}
current[rightIndex] = min(
previous[rightIndex]+1,
current[rightIndex-1]+1,
previous[rightIndex-1]+changeCost,
)
}
previous, current = current, previous
}
return previous[len(rightRunes)]
}
func credentialsAvailableForInvocation() bool {
if os.Getenv("DCI_API_KEY") != "" {
return true
}
return cachedOAuthSession().usable()
}
// cachedOAuthSessionState describes the OAuth session restish has on disk
// — in cache.json under the cache directory (DCI_CACHE_DIR, default
// os.UserCacheDir()/dci), NOT under DCI_CONFIG_DIR. One reading shared by
// the credential gate above and `dci status`, so the two never disagree
// about whether a stored token counts: before this, status reported any
// token string as a live session while the gate (correctly) discounted an
// expired one with no refresh token.
type cachedOAuthSessionState struct {
present bool
expiresAt time.Time
refreshable bool
}
func (session cachedOAuthSessionState) expired() bool {
return !session.expiresAt.IsZero() && !session.expiresAt.After(time.Now())
}
// usable reports whether the session can still authenticate a request: the
// access token is current, or a refresh token is stored for the OAuth
// handler to try first. A refresh the server rejects still ends in the
// headless login error (login_page.go) — only an actual request can tell.
func (session cachedOAuthSessionState) usable() bool {
return session.present && (!session.expired() || session.refreshable)
}
func cachedOAuthSession() cachedOAuthSessionState {
if cli.Cache == nil || cli.Cache.GetString("dci:default.token") == "" {
return cachedOAuthSessionState{}
}
return cachedOAuthSessionState{
present: true,
expiresAt: cli.Cache.GetTime("dci:default.expires"),
refreshable: cli.Cache.GetString("dci:default.refresh") != "",
}
}
// cachedSpecAvailableForInvocation reports whether a warm, unexpired
// OpenAPI spec cache exists — checked against realCacheDir(), the REAL
// cache directory, not whatever DCI_CACHE_DIR currently resolves to. An
// active DCI_API_BASE_URL override points DCI_CACHE_DIR at
// applyAPIBaseOverride's throwaway temp dir, which never gets a copy of
// dci.cbor (so a stale spec from a different host can never leak in) — so
// checking the current env var here would always report "not cached" and
// permanently disable Tab completion for the whole override session, even
// with a fully warm real cache for that same host. Completion only reads
// local cache state; it makes no routed API call, so consulting the real
// directory here carries none of the cross-host-leak risk the temp dir
// exists to prevent elsewhere.
func cachedSpecAvailableForInvocation() bool {
return specCacheWarm(realCacheDir())
}
// specCacheWarm reports whether cacheDir holds a spec cache cli.Load will
// accept without fetching: the CBOR document plus an unexpired dci.expires
// stamp in that directory's cache.json.
func specCacheWarm(cacheDir string) bool {
if cacheDir == "" {
return false
}
if _, err := os.Stat(filepath.Join(cacheDir, "dci.cbor")); err != nil {
return false
}
expiresAt := readCacheExpiry(cacheDir, "dci.expires")
return !expiresAt.IsZero() && expiresAt.After(time.Now())
}
// readCacheExpiry reads a viper-style dotted timestamp key directly out of
// cacheDir's cache.json, bypassing cli.Cache — which, during an active
// DCI_API_BASE_URL override, is restish's in-memory view of the isolated
// temp dir's copy, not necessarily the same file cachedSpecAvailableForInvocation
// needs to check here (the real one).
//
// Uses a scratch viper instance rather than plain json.Unmarshal into a
// flat map: viper's Set("dci.expires", ...) (restish cli/api.go's cacheAPI)
// nests the dot into a real JSON object — {"dci":{"expires":"..."}}, not a
// flat {"dci.expires":"..."} key — so a flat-map unmarshal fails outright
// whenever any other top-level key (e.g. "dci:default" holding the OAuth
// token object) is present, which it always is on a real cache.json.
func readCacheExpiry(cacheDir, key string) time.Time {
v := viper.New()
v.SetConfigName("cache")
v.SetConfigType("json")
v.AddConfigPath(cacheDir)
if err := v.ReadInConfig(); err != nil {
return time.Time{}
}
return v.GetTime(key)
}
func authenticationRequiredPreflightError() error {
message := "no credentials available and this session cannot open a browser to log in"
hint := "Set DCI_API_KEY to a DoiT API token, or run dci login from an interactive terminal"
if sessionRenderActive() {
// This child really cannot open a browser, but the `dci ai` session it
// renders for can: /login suspends the session and hands the browser
// flow the real terminal. Say that, not the shell-shaped remedy — the
// human-mode error prints only the message, so it must carry the fix.
message = "you're not signed in — run /login to sign in"
hint = "Run /login to sign in"
}
return invocationPreflightError{
detail: structuredError{
Code: "AUTHENTICATION_REQUIRED",
Message: message,
Hint: hint,
Retryable: false,
},
exitCode: exitAuthentication,
}
}
// apiRejectedTokenError reports a 401 from the API itself: credentials exist
// but the server refused them. Distinct from authenticationRequiredPreflightError
// (no credentials at all) — and it names the API base, because the most
// confusing cause is the CLI talking to an API the stored token is not valid
// for (a dev base left behind in apis.json or DCI_API_BASE_URL).
func apiRejectedTokenError(base string) error {
hint := "Run dci login to re-authenticate"
if base != defaultAPIBase {
hint += fmt.Sprintf("; note the API base is %s, not the default %s — check DCI_API_BASE_URL and the base in apis.json", base, defaultAPIBase)
}
return invocationPreflightError{
detail: structuredError{
Code: "AUTHENTICATION_REQUIRED",
Message: fmt.Sprintf("the API at %s rejected the stored credentials (HTTP 401)", base),
Hint: hint,
Retryable: false,
},
exitCode: exitAuthentication,
}
}
func invocationHasFlag(args []string, name string) bool {
for _, argument := range args {
if argument == name || strings.HasPrefix(argument, name+"=") {
return true
}
}
return false
}