-
Notifications
You must be signed in to change notification settings - Fork 6
Fix/auth status 401 diagnostics #94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
brandonc
wants to merge
5
commits into
main
Choose a base branch
from
fix/auth-status-401-diagnostics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+143
−11
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
213cd0a
auth status: explain why authentication failed instead of a bare "Una…
jordanenglish acbb812
Update internal/commands/auth/status.go
brandonc bfc164f
Merge branch 'main' into fix/auth-status-401-diagnostics
brandonc 51d93d0
Update status.go
brandonc 45c4712
Update status_test.go
brandonc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| kind: ENHANCEMENTS | ||
| body: '`tfctl auth status` now explains why authentication failed instead of printing a bare "Unauthorized". It distinguishes a missing token, a token the server rejected (401), and a request that never reached the server, and prints the matching remedy. On SSO-protected Terraform Enterprise the 401 message also calls out a lapsed browser SSO session. JSON and agent output gain a machine-readable `reason` field.' | ||
| time: 2026-07-17T01:56:13-04:00 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,11 +6,15 @@ package auth | |
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
|
|
||
| tfe "github.com/hashicorp/go-tfe/v2" | ||
|
|
||
| "github.com/hashicorp/tfctl-cli/internal/pkg/client" | ||
| "github.com/hashicorp/tfctl-cli/internal/pkg/cmd" | ||
| "github.com/hashicorp/tfctl-cli/internal/pkg/format" | ||
|
|
@@ -73,22 +77,25 @@ type StatusResult struct { | |
| TokenType string `json:"token_type,omitempty"` | ||
| ExpiresAt *time.Time `json:"expires_at,omitempty"` | ||
| Active bool `json:"active"` | ||
| // Reason is a machine-readable cause when Active is false: one of | ||
| // "no_token", "rejected", "server_error", or "unreachable". | ||
| Reason string `json:"reason,omitempty"` | ||
| } | ||
|
|
||
| func runStatus(ctx context.Context, opts *StatusOpts) error { | ||
| hostname := opts.Profile.GetHostname() | ||
|
|
||
| // No token configured at all. | ||
| if opts.Profile.GetToken() == "" { | ||
| return displayUnauthorized(opts, hostname) | ||
| return displayAuthFailure(opts, hostname, &authFailure{reason: reasonNoToken}) | ||
| } | ||
|
|
||
| apiClient := opts.APIClient | ||
|
|
||
| // Call /account/details. | ||
| resp, err := apiClient.TFE.API.Account().Details().Get(ctx, nil) | ||
| if err != nil { | ||
| return displayUnauthorized(opts, hostname) | ||
| return displayAuthFailure(opts, hostname, classifyAuthError(err)) | ||
| } | ||
|
|
||
| data := resp.GetData() | ||
|
|
@@ -146,17 +153,77 @@ func runStatus(ctx context.Context, opts *StatusOpts) error { | |
| return opts.Output.Display(&statusDisplayer{result: result, io: opts.IO}) | ||
| } | ||
|
|
||
| // displayUnauthorized emits a machine-readable inactive result for JSON/agent | ||
| // consumers and writes the human-readable failure message to stderr. It always | ||
| // Machine-readable failure reasons surfaced in StatusResult.Reason. | ||
| const ( | ||
| reasonNoToken = "no_token" | ||
| reasonRejected = "rejected" | ||
| reasonServerError = "server_error" | ||
| reasonUnreachable = "unreachable" | ||
| ) | ||
|
|
||
| // authFailure describes why `auth status` could not confirm an active session. | ||
| type authFailure struct { | ||
| reason string // one of the reason* constants | ||
| status int // HTTP status when known (0 otherwise) | ||
| err error // underlying transport/server error, when relevant | ||
| } | ||
|
|
||
| // classifyAuthError turns an /account/details error into an authFailure. A 401 | ||
| // means the token was rejected — expired or revoked, or (on SAML-SSO-protected | ||
| // Terraform Enterprise) a browser SSO session that has lapsed. Any other HTTP | ||
| // status is a server-side problem, and an error carrying no HTTP status is a | ||
| // connectivity problem; neither of those is an authentication failure, so we | ||
| // say so rather than reporting a misleading "unauthorized". | ||
| // | ||
| // The go-tfe *APIError is wrapped in a *url.Error, so we rely on errors.As to | ||
| // walk the chain rather than matching the concrete top-level type. | ||
| func classifyAuthError(err error) *authFailure { | ||
| var apiErr *tfe.APIError | ||
| if errors.As(err, &apiErr) { | ||
| if apiErr.StatusCode == http.StatusUnauthorized { | ||
| return &authFailure{reason: reasonRejected, status: apiErr.StatusCode} | ||
| } | ||
| return &authFailure{reason: reasonServerError, status: apiErr.StatusCode, err: err} | ||
| } | ||
| return &authFailure{reason: reasonUnreachable, err: err} | ||
| } | ||
|
|
||
| // displayAuthFailure emits a machine-readable inactive result for JSON/agent | ||
| // consumers and writes a cause-specific, actionable message to stderr. It always | ||
| // returns cmd.ErrUnderlyingError so callers can tail-call it. | ||
| func displayUnauthorized(opts *StatusOpts, hostname string) error { | ||
| func displayAuthFailure(opts *StatusOpts, hostname string, f *authFailure) error { | ||
| if opts.Output.GetFormat().IsJSONOrAgent() { | ||
| result := &StatusResult{Active: false, Hostname: hostname} | ||
| result := &StatusResult{Active: false, Hostname: hostname, Reason: f.reason} | ||
| // Best-effort: ignore display errors since we are already in a failure path. | ||
| _ = opts.Output.Display(&statusDisplayer{result: result, io: opts.IO}) | ||
| } | ||
|
|
||
| cs := opts.IO.ColorScheme() | ||
| fmt.Fprintf(opts.IO.Err(), "%s Unauthorized for %s\n", cs.FailureIcon(), hostname) | ||
| w := opts.IO.Err() | ||
| icon := cs.FailureIcon() | ||
|
|
||
| switch f.reason { | ||
| case reasonNoToken: | ||
| fmt.Fprintf(w, "%s No token configured for %s. Run '%s auth login' to authenticate.\n", | ||
| icon, hostname, version.Name) | ||
| case reasonRejected: | ||
| fmt.Fprintf(w, "%s Token for %s was invalid (HTTP 401).\n", icon, hostname) | ||
| fmt.Fprintf(w, " - The token may be expired, revoked, or disabled: run '%s auth login' to create a new one.\n", version.Name) | ||
| if !strings.HasSuffix(opts.Profile.GetHostname(), ".terraform.io") { | ||
| fmt.Fprintf(w, " - Your Terraform Enterprise SSO session may have expired: sign in again, then retry.\n") | ||
| } | ||
| fmt.Fprintf(w, " - Ensure you are using the intended token configuration by adding '--debug' to this command") | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Missing a newline at the end here, looks possible that lines later appended here would be glued right next to this one. |
||
| case reasonServerError: | ||
| fmt.Fprintf(w, "%s %s returned HTTP %d (not an authentication problem). Retry, or check the instance status.\n", | ||
| icon, hostname, f.status) | ||
| default: // reasonUnreachable | ||
| if f.err != nil { | ||
| fmt.Fprintf(w, "%s Could not reach %s: %v\n", icon, hostname, f.err) | ||
| } else { | ||
| fmt.Fprintf(w, "%s Could not reach %s.\n", icon, hostname) | ||
| } | ||
| } | ||
|
|
||
| return cmd.ErrUnderlyingError | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: Looks like we could just use the passed
hostnameparam, correct me if I'm missing a nuance here.