-
Notifications
You must be signed in to change notification settings - Fork 9
feat: Add --token options to caib login #305
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
bkhizgiy
wants to merge
1
commit into
centos-automotive-suite:main
Choose a base branch
from
bkhizgiy:auth
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.
Open
Changes from all commits
Commits
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
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
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
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,141 @@ | ||
| package caibcommon | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/centos-automotive-suite/automotive-dev-operator/cmd/caib/config" | ||
| buildapiclient "github.com/centos-automotive-suite/automotive-dev-operator/internal/buildapi/client" | ||
| ) | ||
|
|
||
| // setupTempConfig redirects config reads/writes to a temp HOME directory. | ||
| // Returns a cleanup function. | ||
| func setupTempConfig(t *testing.T) func() { | ||
| t.Helper() | ||
| dir, err := os.MkdirTemp("", "caib-api-client-test-*") | ||
| if err != nil { | ||
| t.Fatalf("MkdirTemp: %v", err) | ||
| } | ||
| origHome := os.Getenv("HOME") | ||
| origXDG := os.Getenv("XDG_CONFIG_HOME") | ||
| _ = os.Setenv("HOME", dir) | ||
| _ = os.Unsetenv("XDG_CONFIG_HOME") | ||
| return func() { | ||
| _ = os.Setenv("HOME", origHome) | ||
| if origXDG != "" { | ||
| _ = os.Setenv("XDG_CONFIG_HOME", origXDG) | ||
| } else { | ||
| _ = os.Unsetenv("XDG_CONFIG_HOME") | ||
| } | ||
| _ = os.RemoveAll(dir) | ||
| } | ||
| } | ||
|
|
||
| // always401Handler is a handler that unconditionally returns 401. | ||
| var always401Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
| w.WriteHeader(http.StatusUnauthorized) | ||
| }) | ||
|
|
||
| // authErrorFn is an ExecuteWithReauth callback that always returns a 401 error. | ||
| func authErrorFn(_ *buildapiclient.Client) error { | ||
| return &fakeAuthError{} | ||
| } | ||
|
|
||
| // fakeAuthError satisfies the auth.IsAuthError check (its message contains "401"). | ||
| type fakeAuthError struct{} | ||
|
|
||
| func (e *fakeAuthError) Error() string { return "401 Unauthorized" } | ||
|
|
||
| func TestExecuteWithReauth_SavedTokenRejected(t *testing.T) { | ||
| cleanup := setupTempConfig(t) | ||
| defer cleanup() | ||
|
|
||
| srv := httptest.NewServer(always401Handler) | ||
| defer srv.Close() | ||
|
|
||
| if err := config.SaveToken("sha256~fakesavedtoken"); err != nil { | ||
| t.Fatalf("SaveToken: %v", err) | ||
| } | ||
|
|
||
| // Empty --token flag (zero value) so CreateBuildAPIClient loads the saved token. | ||
| tok := "" | ||
| err := ExecuteWithReauth(srv.URL, &tok, false, authErrorFn) | ||
|
|
||
| if err == nil { | ||
| t.Fatal("expected error, got nil") | ||
| } | ||
| if !strings.Contains(err.Error(), "saved token was rejected") { | ||
| t.Errorf("expected 'saved token was rejected' in error, got: %v", err) | ||
| } | ||
| } | ||
|
|
||
| func TestExecuteWithReauth_ExplicitTokenRejected(t *testing.T) { | ||
| cleanup := setupTempConfig(t) | ||
| defer cleanup() | ||
|
|
||
| srv := httptest.NewServer(always401Handler) | ||
| defer srv.Close() | ||
|
|
||
| // No saved token — user passed an explicit --token flag value. | ||
| tok := "sha256~explicit-flag-token" | ||
| err := ExecuteWithReauth(srv.URL, &tok, false, authErrorFn) | ||
|
|
||
| if err == nil { | ||
| t.Fatal("expected error, got nil") | ||
| } | ||
| if !strings.Contains(err.Error(), "provided token was rejected") { | ||
| t.Errorf("expected 'provided token was rejected' in error, got: %v", err) | ||
| } | ||
| } | ||
|
|
||
| func TestExecuteWithReauth_NoTokenTriesOIDCFallback(t *testing.T) { | ||
| cleanup := setupTempConfig(t) | ||
| defer cleanup() | ||
|
|
||
| // Server returns 401 for API calls and 404 for OIDC config (no OIDC configured). | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| if strings.Contains(r.URL.Path, "authconfig") { | ||
| w.WriteHeader(http.StatusNotFound) | ||
| return | ||
| } | ||
| w.WriteHeader(http.StatusUnauthorized) | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| // No saved token, no explicit token — should attempt OIDC (non-interactively | ||
| // since no OIDC config) and return some error rather than panicking or opening | ||
| // a browser. | ||
| tok := "" | ||
| err := ExecuteWithReauth(srv.URL, &tok, false, authErrorFn) | ||
| if err == nil { | ||
| t.Fatal("expected error when no token and no OIDC available, got nil") | ||
| } | ||
| } | ||
|
|
||
| func TestSanitizeToken(t *testing.T) { | ||
| cases := []struct { | ||
| input string | ||
| want string | ||
| }{ | ||
| {"sha256~abc", "sha256~abc"}, | ||
| {"Bearer sha256~abc", "sha256~abc"}, | ||
| {"bearer sha256~abc", "sha256~abc"}, | ||
| {"BEARER sha256~abc", "sha256~abc"}, | ||
| {" Bearer sha256~abc ", "sha256~abc"}, | ||
| {"eyJhbGciOiJSUzI1NiJ9.e.sig", "eyJhbGciOiJSUzI1NiJ9.e.sig"}, | ||
| {"Bearer eyJhbGciOiJSUzI1NiJ9.e.sig", "eyJhbGciOiJSUzI1NiJ9.e.sig"}, | ||
| {"", ""}, | ||
| {" ", ""}, | ||
| // Single word "Bearer" with no token — treated as an opaque token, not a prefix. | ||
| {"Bearer", "Bearer"}, | ||
| } | ||
| for _, tc := range cases { | ||
| got := sanitizeToken(tc.input) | ||
| if got != tc.want { | ||
| t.Errorf("sanitizeToken(%q) = %q, want %q", tc.input, got, tc.want) | ||
| } | ||
| } | ||
| } |
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
Oops, something went wrong.
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.
This heuristic is clever but fragile: if a user explicitly passes
--token XwhereXhappens to equalCAIB_TOKEN, the saved token silently wins over their explicit flag value.A more robust approach would be to thread a
tokenExplicit boolparameter (or usecmd.Flags().Changed("token")at the call site) soCreateBuildAPIClientcan distinguish "user typed it" from "cobra set the default." That said, the current approach works for the common case — just worth a// CAVEAT:note for future maintainers.