-
-
Notifications
You must be signed in to change notification settings - Fork 67
feat: add microcks validate command for pre-flight config verification #495
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
A-d-i-t-y
wants to merge
2
commits into
microcks:master
Choose a base branch
from
A-d-i-t-y:feat/validate-command
base: master
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.
+297
−0
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| /* | ||
| * Copyright The Microcks Authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
|
|
||
| "github.com/microcks/microcks-cli/pkg/config" | ||
| "github.com/microcks/microcks-cli/pkg/connectors" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| // NewValidateCommand builds the "validate" command which runs pre-flight | ||
| // checks on configuration and connectivity to a Microcks server, without | ||
| // performing any import or test action. | ||
| func NewValidateCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command { | ||
|
|
||
| var validateCmd = &cobra.Command{ | ||
|
|
||
| Use: "validate", | ||
| Short: "Validate current Microcks CLI configuration and connectivity", | ||
| Long: `Runs pre-flight checks before running imports/tests: | ||
| - config/credentials are resolvable, either via a local context or via | ||
| --microcksURL together with --keycloakClientId/--keycloakClientSecret | ||
| for CI/CD (service account) usage | ||
| - the auth token is valid (refreshed / retrieved as needed) | ||
| - the target Microcks server is reachable | ||
|
|
||
| Exits with code 0 if all checks pass, or 1 if any check fails. | ||
|
|
||
| Note: this command validates connectivity and authentication only. It | ||
| does not check service-account authorization scopes or Async API Minion | ||
| connectivity, which are tracked as a follow-up.`, | ||
| Example: `microcks validate | ||
| microcks validate --microcks-context staging | ||
| microcks validate --microcksURL http://microcks.example.com/api --keycloakClientId my-sa --keycloakClientSecret my-secret`, | ||
|
|
||
| Run: func(cmd *cobra.Command, args []string) { | ||
| os.Exit(runValidate(globalClientOpts)) | ||
| }, | ||
| } | ||
|
|
||
| return validateCmd | ||
| } | ||
|
|
||
| // runValidate executes the pre-flight checks and returns a process exit | ||
| // code (0 if everything passed, 1 otherwise). Extracted from Run so it can | ||
| // be unit tested without the test process itself exiting. | ||
| func runValidate(globalClientOpts *connectors.ClientOptions) int { | ||
| ok := true | ||
|
|
||
| directMode := globalClientOpts.ServerAddr != "" && | ||
| globalClientOpts.ClientId != "" && | ||
| globalClientOpts.ClientSecret != "" | ||
|
|
||
| var mc connectors.MicrocksClient | ||
| var serverAddr string | ||
|
|
||
| if directMode { | ||
| // CI/CD direct-connection mode: no local config file involved, | ||
| // mirrors the pattern used by `test`/`import` for --microcksURL. | ||
| serverAddr = globalClientOpts.ServerAddr | ||
| mc = connectors.NewMicrocksClient(serverAddr) | ||
| fmt.Printf("✓ Using direct connection: %s\n", serverAddr) | ||
|
|
||
| keycloakURL, err := mc.GetKeycloakURL() | ||
| if err != nil { | ||
| fmt.Printf("✗ Server reachability: %v\n", err) | ||
| return 1 | ||
| } | ||
| fmt.Printf("✓ Server reachable: %s\n", serverAddr) | ||
|
|
||
| oauthToken := "unauthenticated-token" | ||
| if keycloakURL != "null" { | ||
| kc := connectors.NewKeycloakClient(keycloakURL, globalClientOpts.ClientId, globalClientOpts.ClientSecret) | ||
| oauthToken, err = kc.ConnectAndGetToken() | ||
| if err != nil { | ||
| fmt.Printf("✗ Authentication: %v\n", err) | ||
| return 1 | ||
| } | ||
| } | ||
| mc.SetOAuthToken(oauthToken) | ||
| fmt.Println("✓ Authentication: service account token obtained") | ||
|
|
||
| } else { | ||
| // Local config / context mode. | ||
| localConfig, err := config.ReadLocalConfig(globalClientOpts.ConfigPath) | ||
| if err != nil { | ||
| fmt.Printf("✗ Config file: invalid — %v\n", err) | ||
| return 1 | ||
| } | ||
| if localConfig == nil || localConfig.IsEmpty() { | ||
| fmt.Println("✗ No contexts configured. Run 'microcks login <server>', or pass --microcksURL with --keycloakClientId/--keycloakClientSecret for CI/CD.") | ||
| return 1 | ||
| } | ||
| fmt.Println("✓ Config file: parsed successfully") | ||
|
|
||
| ctx, err := localConfig.ResolveContext(globalClientOpts.Context) | ||
| if err != nil { | ||
| fmt.Printf("✗ Context resolution: %v\n", err) | ||
| return 1 | ||
| } | ||
| fmt.Printf("✓ Context resolved: %q (server: %s)\n", ctx.Name, ctx.Server.Server) | ||
| serverAddr = ctx.Server.Server | ||
|
|
||
| mc, err = connectors.NewClient(*globalClientOpts) | ||
| if err != nil { | ||
| fmt.Printf("✗ Authentication: %v\n", err) | ||
| ok = false | ||
| } else { | ||
| fmt.Println("✓ Authentication: token is valid") | ||
| } | ||
|
|
||
| if mc != nil { | ||
| if _, err := mc.GetKeycloakURL(); err != nil { | ||
| fmt.Printf("✗ Server reachability: %v\n", err) | ||
| ok = false | ||
| } else { | ||
| fmt.Printf("✓ Server reachable: %s\n", serverAddr) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if !ok { | ||
| fmt.Println("\nOne or more checks failed.") | ||
| return 1 | ||
| } | ||
| fmt.Println("\nAll checks passed ✓ — ready to run imports/tests.") | ||
| return 0 | ||
| } |
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,152 @@ | ||
| /* | ||
| * Copyright The Microcks Authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "os" | ||
| "testing" | ||
|
|
||
| "github.com/microcks/microcks-cli/pkg/connectors" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| const validateTestConfigFilePath = "./testdata/validate.config" | ||
|
|
||
| // setupValidateTestConfig writes the shared testConfig (defined in | ||
| // context_test.go) to disk so ReadLocalConfig can load it, and returns | ||
| // a cleanup func to remove it afterwards. | ||
| func setupValidateTestConfig(t *testing.T) func() { | ||
| t.Helper() | ||
| err := os.MkdirAll("./testdata", 0755) | ||
| require.NoError(t, err) | ||
| err = os.WriteFile(validateTestConfigFilePath, []byte(testConfig), 0644) | ||
| require.NoError(t, err) | ||
| return func() { | ||
| _ = os.Remove(validateTestConfigFilePath) | ||
| } | ||
| } | ||
|
|
||
| // captureStdout redirects os.Stdout for the duration of fn and returns | ||
| // everything that was printed, so we can assert on runValidate's output. | ||
| func captureStdout(t *testing.T, fn func()) string { | ||
| t.Helper() | ||
| old := os.Stdout | ||
| r, w, err := os.Pipe() | ||
| require.NoError(t, err) | ||
| os.Stdout = w | ||
|
|
||
| fn() | ||
|
|
||
| require.NoError(t, w.Close()) | ||
| os.Stdout = old | ||
|
|
||
| var buf bytes.Buffer | ||
| _, err = io.Copy(&buf, r) | ||
| require.NoError(t, err) | ||
| return buf.String() | ||
| } | ||
|
|
||
| func TestRunValidate_NoConfigFile_ReturnsFailureAndMessage(t *testing.T) { | ||
| opts := &connectors.ClientOptions{ | ||
| ConfigPath: "./testdata/does-not-exist.config", | ||
| } | ||
|
|
||
| var exitCode int | ||
| output := captureStdout(t, func() { | ||
| exitCode = runValidate(opts) | ||
| }) | ||
|
|
||
| require.Equal(t, 1, exitCode) | ||
| require.Contains(t, output, "No contexts configured") | ||
| } | ||
|
|
||
| func TestRunValidate_InvalidConfigFile_ReturnsFailure(t *testing.T) { | ||
| // current-context points to a context name that doesn't exist in the | ||
| // contexts list — this is what ValidateLocalConfig() actually rejects. | ||
| badConfig := `current-context: ghost-context | ||
| contexts: | ||
| - name: http://localhost:8080 | ||
| server: http://localhost:8080 | ||
| user: http://localhost:8080 | ||
| instance: "" | ||
| servers: | ||
| - name: "" | ||
| server: http://localhost:8080 | ||
| insecureTLS: true | ||
| keycloakEnable: true | ||
| users: | ||
| - name: http://localhost:8080 | ||
| auth-token: "" | ||
| refresh-token: ""` | ||
|
|
||
| badConfigPath := "./testdata/invalid.config" | ||
| err := os.MkdirAll("./testdata", 0755) | ||
| require.NoError(t, err) | ||
| err = os.WriteFile(badConfigPath, []byte(badConfig), 0644) | ||
| require.NoError(t, err) | ||
| defer os.Remove(badConfigPath) | ||
|
|
||
| opts := &connectors.ClientOptions{ | ||
| ConfigPath: badConfigPath, | ||
| } | ||
|
|
||
| var exitCode int | ||
| output := captureStdout(t, func() { | ||
| exitCode = runValidate(opts) | ||
| }) | ||
|
|
||
| require.Equal(t, 1, exitCode) | ||
| require.Contains(t, output, "Config file: invalid") | ||
| } | ||
|
|
||
| func TestRunValidate_ValidConfigButUnreachableServer_ReturnsFailure(t *testing.T) { | ||
| cleanup := setupValidateTestConfig(t) | ||
| defer cleanup() | ||
|
|
||
| opts := &connectors.ClientOptions{ | ||
| ConfigPath: validateTestConfigFilePath, | ||
| } | ||
|
|
||
| var exitCode int | ||
| output := captureStdout(t, func() { | ||
| exitCode = runValidate(opts) | ||
| }) | ||
|
|
||
| // The current context (localhost:8083) is not actually running, so the | ||
| // reachability (or auth) check must fail and the command must report it. | ||
| require.Equal(t, 1, exitCode) | ||
| require.Contains(t, output, "Context resolved") | ||
| require.Contains(t, output, "One or more checks failed") | ||
| } | ||
|
|
||
| func TestRunValidate_DirectModeIncomplete_FallsBackToLocalConfigPath(t *testing.T) { | ||
| // Only --microcksURL set, missing client id/secret: direct mode must | ||
| // NOT engage, and behavior should fall back to local config handling. | ||
| opts := &connectors.ClientOptions{ | ||
| ConfigPath: "./testdata/does-not-exist.config", | ||
| ServerAddr: "http://localhost:9999", | ||
| } | ||
|
|
||
| var exitCode int | ||
| output := captureStdout(t, func() { | ||
| exitCode = runValidate(opts) | ||
| }) | ||
|
|
||
| require.Equal(t, 1, exitCode) | ||
| require.Contains(t, output, "No contexts configured") | ||
| } |
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.
These tests do not actually exercise
NewValidateCommand()or the command output/exit behavior.They mostly re-test
config.ReadLocalConfig()andResolveContext(), which are existing helpers. Please add command-level tests for the new behavior itself: success path, missing config/context, and a failing auth/reachability path if possible.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.
Add a copyright block