-
Notifications
You must be signed in to change notification settings - Fork 16
core: Add STACKIT CLI Auth flow #2179
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
Closed
Closed
Changes from 8 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
8b757b1
core: Add STACKIT CLI Auth flow
jkroepke c5f71ab
Merge branch 'main' into stackit-cli-flow
jkroepke 0575554
fix merge conflicts
jkroepke 47d007f
add test, if token not present
jkroepke df57b26
fix lint
jkroepke 762b5c8
Add test for CLI
jkroepke 2a71390
Update CHANGELOG.md
jkroepke 992fae7
Merge branch 'main' into stackit-cli-flow
jkroepke 765f60b
Replace jkroepke/setup-stackit-cli
jkroepke ff92b61
Update core/CHANGELOG.md
jkroepke a1154da
Update CHANGELOG.md
jkroepke 57a45bb
Merge branch 'main' into stackit-cli-flow
jkroepke 60aea17
Replace DisableCLIAuthFlow with CLIAuthFlow
jkroepke 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
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,78 @@ | ||
package clients | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"errors" | ||
"net/http" | ||
"os" | ||
"os/exec" | ||
"runtime" | ||
"strings" | ||
) | ||
|
||
// STACKITCLIFlow invoke the STACKIT CLI from PATH to get the access token. | ||
// If successful, then token is passed to clients.TokenFlow. | ||
type STACKITCLIFlow struct { | ||
TokenFlow | ||
} | ||
|
||
// STACKITCLIFlowConfig is the flow config | ||
type STACKITCLIFlowConfig struct { | ||
HTTPTransport http.RoundTripper | ||
} | ||
|
||
// GetConfig returns the flow configuration | ||
func (c *STACKITCLIFlow) GetConfig() STACKITCLIFlowConfig { | ||
return STACKITCLIFlowConfig{} | ||
} | ||
|
||
func (c *STACKITCLIFlow) Init(cfg *STACKITCLIFlowConfig) error { | ||
token, err := c.getTokenFromCLI() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return c.TokenFlow.Init(&TokenFlowConfig{ | ||
ServiceAccountToken: strings.TrimSpace(token), | ||
HTTPTransport: cfg.HTTPTransport, | ||
}) | ||
} | ||
|
||
func (c *STACKITCLIFlow) getTokenFromCLI() (string, error) { | ||
return RunSTACKITCLICommand(context.TODO(), "stackit auth get-access-token") | ||
} | ||
|
||
// RunSTACKITCLICommand executes the command line and returns the output. | ||
func RunSTACKITCLICommand(ctx context.Context, commandLine string) (string, error) { | ||
var cliCmd *exec.Cmd | ||
if runtime.GOOS == "windows" { | ||
dir := os.Getenv("SYSTEMROOT") | ||
if dir == "" { | ||
return "", errors.New("environment variable 'SYSTEMROOT' has no value") | ||
} | ||
cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine) | ||
cliCmd.Dir = dir | ||
} else { | ||
cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine) | ||
cliCmd.Dir = "/bin" | ||
} | ||
cliCmd.Env = os.Environ() | ||
var stderr bytes.Buffer | ||
cliCmd.Stderr = &stderr | ||
|
||
output, err := cliCmd.Output() | ||
if err != nil { | ||
msg := stderr.String() | ||
var exErr *exec.ExitError | ||
if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'stackit' is not recognized") { | ||
msg = "STACKIT CLI not found on path" | ||
} | ||
if msg == "" { | ||
msg = err.Error() | ||
} | ||
return "", errors.New(msg) | ||
} | ||
|
||
return string(output), nil | ||
} |
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,166 @@ | ||
package clients | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"net/url" | ||
"testing" | ||
) | ||
|
||
//nolint:gosec // testServiceAccountToken is a test token | ||
const testServiceAccountToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImR1bW15QGV4YW1wbGUuY29tIiwiZXhwIjo5MDA3MTkyNTQ3NDA5OTF9.sM2yd5GL9kK4h8IKHbr_fA2XmrzEsLOeLTIPrU0VfMg" | ||
|
||
func TestSTACKITCLIFlow_Init(t *testing.T) { | ||
type args struct { | ||
cfg *STACKITCLIFlowConfig | ||
confFn func(t *testing.T) | ||
} | ||
tests := []struct { | ||
name string | ||
args args | ||
wantErr bool | ||
}{ | ||
{"ok", args{ | ||
cfg: &STACKITCLIFlowConfig{}, | ||
confFn: func(t *testing.T) { | ||
_, err := RunSTACKITCLICommand(context.TODO(), "stackit auth activate-service-account --service-account-token="+testServiceAccountToken) | ||
if err != nil { | ||
t.Errorf("RunSTACKITCLICommand() error = %v", err) | ||
return | ||
} | ||
}, | ||
}, false}, | ||
{"no-token", args{ | ||
cfg: &STACKITCLIFlowConfig{}, | ||
confFn: func(_ *testing.T) {}, | ||
}, true}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
ctx := context.TODO() | ||
|
||
c := &STACKITCLIFlow{} | ||
|
||
cliProfileName := "test-stackit-cli-flow-init" + tt.name | ||
|
||
_, _ = RunSTACKITCLICommand(ctx, fmt.Sprintf("stackit config profile delete %s -y", cliProfileName)) | ||
_, err := RunSTACKITCLICommand(ctx, "stackit config profile create "+cliProfileName) | ||
if err != nil { | ||
t.Errorf("RunSTACKITCLICommand() error = %v", err) | ||
return | ||
} | ||
|
||
tt.args.confFn(t) | ||
|
||
defer func() { | ||
_, _ = RunSTACKITCLICommand(ctx, fmt.Sprintf("stackit config profile delete %s -y", cliProfileName)) | ||
}() | ||
|
||
if err := c.Init(tt.args.cfg); err != nil { | ||
if (err != nil) != tt.wantErr { | ||
t.Errorf("TokenFlow.Init() error = %v, wantErr %v", err, tt.wantErr) | ||
} | ||
|
||
return | ||
} | ||
|
||
if c.config == nil { | ||
t.Error("config is nil") | ||
} | ||
}) | ||
} | ||
} | ||
|
||
func TestSTACKITCLIFlow_Do(t *testing.T) { | ||
type fields struct { | ||
client *http.Client | ||
config *STACKITCLIFlowConfig | ||
} | ||
type args struct{} | ||
tests := []struct { | ||
name string | ||
fields fields | ||
args args | ||
want int | ||
wantErr bool | ||
}{ | ||
{"success", fields{&http.Client{}, &STACKITCLIFlowConfig{}}, args{}, http.StatusOK, false}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
ctx := context.TODO() | ||
|
||
_, _ = RunSTACKITCLICommand(ctx, "stackit config profile delete test-stackit-cli-flow-do -y") | ||
_, err := RunSTACKITCLICommand(ctx, "stackit config profile create test-stackit-cli-flow-do") | ||
if err != nil { | ||
t.Errorf("RunSTACKITCLICommand() error = %v", err) | ||
return | ||
} | ||
|
||
_, err = RunSTACKITCLICommand(ctx, "stackit auth activate-service-account --service-account-token="+testServiceAccountToken) | ||
if err != nil { | ||
t.Errorf("RunSTACKITCLICommand() error = %v", err) | ||
return | ||
} | ||
|
||
defer func() { | ||
_, _ = RunSTACKITCLICommand(ctx, "stackit config profile delete test-stackit-cli-flow-do -y") | ||
}() | ||
|
||
c := &STACKITCLIFlow{} | ||
err = c.Init(tt.fields.config) | ||
if err != nil { | ||
t.Errorf("Init() error = %v", err) | ||
return | ||
} | ||
|
||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
authorization := r.Header.Get("Authorization") | ||
if authorization != "Bearer "+testServiceAccountToken { | ||
w.WriteHeader(http.StatusUnauthorized) | ||
_, _ = fmt.Fprintln(w, `{"error":"missing authorization header"}`) | ||
return | ||
} | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(http.StatusOK) | ||
_, _ = fmt.Fprintln(w, `{"status":"ok"}`) | ||
}) | ||
server := httptest.NewServer(handler) | ||
defer server.Close() | ||
|
||
u, err := url.Parse(server.URL) | ||
if err != nil { | ||
t.Error(err) | ||
return | ||
} | ||
req, err := http.NewRequest(http.MethodGet, u.String(), http.NoBody) | ||
if err != nil { | ||
t.Error(err) | ||
return | ||
} | ||
got, err := c.RoundTrip(req) | ||
if err == nil { | ||
// Defer discard and close the body | ||
defer func() { | ||
if _, discardErr := io.Copy(io.Discard, got.Body); discardErr != nil && err == nil { | ||
err = discardErr | ||
} | ||
if closeErr := got.Body.Close(); closeErr != nil && err == nil { | ||
err = closeErr | ||
} | ||
}() | ||
} | ||
if (err != nil) != tt.wantErr { | ||
t.Errorf("STACKITCLIFlow.Do() error = %v, wantErr %v", err, tt.wantErr) | ||
return | ||
} | ||
if got != nil && got.StatusCode != tt.want { | ||
t.Errorf("STACKITCLIFlow.Do() = %v, want %v", got.StatusCode, tt.want) | ||
} | ||
}) | ||
} | ||
} |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.