-
Notifications
You must be signed in to change notification settings - Fork 15
Add oadp setup command with RBAC detection and refactor builders #147
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
Merged
Joeavaikath
merged 6 commits into
migtools:oadp-dev
from
Joeavaikath:issue-141-design-nonadmin-config
Mar 6, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8bca7b7
Add oadp setup command to auto-detect admin vs non-admin mode
Joeavaikath 8531faf
Refactor: Rename builder constructors to follow Go naming conventions
Joeavaikath 12786d6
Add debug message for non-admin mode setup
Joeavaikath 046fe65
Remove unused param
Joeavaikath 99cea29
Change detection logic to use can-i command
Joeavaikath b518487
Fix config overwrite issue
Joeavaikath 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,68 @@ | ||
| /* | ||
| Copyright 2025 The OADP CLI Contributors. | ||
|
|
||
| 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 setup | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os/exec" | ||
| "strings" | ||
| ) | ||
|
|
||
| // DetectionResult holds the result of detecting user mode | ||
| type DetectionResult struct { | ||
| IsAdmin bool | ||
| Error error | ||
| } | ||
|
|
||
| // detectUserMode detects whether the user has admin permissions by checking | ||
| // if they can create Velero Backup resources across all namespaces. | ||
| // Admin users can create backups.velero.io cluster-wide, while non-admin users | ||
| // can only create nonadminbackups.oadp.openshift.io in their own namespace. | ||
| func detectUserMode() DetectionResult { | ||
| // Check if user can create Velero Backups across all namespaces | ||
| // This is the core permission difference between admin and non-admin modes | ||
| cmd := exec.Command("oc", "auth", "can-i", "create", "backups.velero.io", "--all-namespaces") | ||
| output, err := cmd.CombinedOutput() | ||
|
|
||
| if err != nil { | ||
| // Check if this is because oc command failed vs permission check | ||
| if exitErr, ok := err.(*exec.ExitError); ok { | ||
| // Exit code 1 typically means "no" for can-i | ||
| if exitErr.ExitCode() == 1 { | ||
| return DetectionResult{IsAdmin: false} | ||
| } | ||
| } | ||
| // Check if output indicates not logged in | ||
| outputStr := string(output) | ||
| if strings.Contains(outputStr, "Unauthorized") || strings.Contains(outputStr, "not logged in") { | ||
| return DetectionResult{Error: fmt.Errorf("not logged in to cluster")} | ||
| } | ||
| // Other errors (oc not found, cluster unreachable, etc.) | ||
| return DetectionResult{Error: fmt.Errorf("failed to check permissions: %w", err)} | ||
| } | ||
|
|
||
| // Parse the output | ||
| result := strings.TrimSpace(string(output)) | ||
|
|
||
| // "yes" means user can create backups cluster-wide (admin mode) | ||
| if result == "yes" { | ||
| return DetectionResult{IsAdmin: true} | ||
| } | ||
|
|
||
| // "no" means user cannot (non-admin mode) | ||
| return DetectionResult{IsAdmin: false} | ||
| } |
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,207 @@ | ||
| /* | ||
| Copyright 2025 The OADP CLI Contributors. | ||
|
|
||
| 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 setup | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
|
|
||
| "github.com/migtools/oadp-cli/cmd/shared" | ||
| "github.com/spf13/cobra" | ||
| "github.com/spf13/pflag" | ||
| "github.com/vmware-tanzu/velero/pkg/client" | ||
| ) | ||
|
|
||
| // SetupOptions holds the options for the setup command | ||
| type SetupOptions struct { | ||
| Force bool // Re-run detection even if already configured | ||
|
|
||
| // Internal state | ||
| detectionResult DetectionResult | ||
| } | ||
|
|
||
| // BindFlags binds the flags to the command | ||
| func (o *SetupOptions) BindFlags(flags *pflag.FlagSet) { | ||
| flags.BoolVar(&o.Force, "force", false, "Re-run detection even if already configured") | ||
| } | ||
|
|
||
| // Complete completes the options | ||
| func (o *SetupOptions) Complete(args []string, f client.Factory) error { | ||
| // No setup needed - detection uses oc CLI directly | ||
| return nil | ||
| } | ||
|
|
||
| // Validate validates the options | ||
| func (o *SetupOptions) Validate(c *cobra.Command, args []string, f client.Factory) error { | ||
| // No validation needed for setup command | ||
| return nil | ||
| } | ||
|
|
||
| // Run executes the setup command | ||
| func (o *SetupOptions) Run(c *cobra.Command, f client.Factory) error { | ||
| fmt.Println("Detecting user permissions...") | ||
| fmt.Println() | ||
|
|
||
| // Silence usage help on errors during Run (we provide clear error messages) | ||
| c.SilenceUsage = true | ||
|
|
||
| // Check if already configured (unless --force flag set) | ||
| if !o.Force { | ||
| existingConfig, err := shared.ReadVeleroClientConfig() | ||
| if err != nil { | ||
| return fmt.Errorf("failed to read existing config: %w", err) | ||
| } | ||
|
|
||
| // Check if nonadmin field is explicitly set (not nil) | ||
| if existingConfig.NonAdmin != nil { | ||
| fmt.Println("OADP CLI is already configured.") | ||
| fmt.Println() | ||
| o.printCurrentConfig(existingConfig) | ||
| fmt.Println() | ||
| fmt.Println("To reconfigure, run: oc oadp setup --force") | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| // Run detection | ||
| o.detectionResult = detectUserMode() | ||
|
|
||
| // Handle detection errors | ||
| if o.detectionResult.Error != nil { | ||
| // Provide specific guidance based on error type | ||
| errMsg := o.detectionResult.Error.Error() | ||
| if strings.Contains(errMsg, "not logged in") || strings.Contains(errMsg, "Unauthorized") { | ||
| fmt.Println("Error: Not logged in to cluster") | ||
| fmt.Println() | ||
| fmt.Println("Please log in to your cluster:") | ||
| fmt.Println(" oc login <cluster-url>") | ||
| return fmt.Errorf("not logged in to cluster") | ||
| } else { | ||
| fmt.Printf("Error: %v\n", o.detectionResult.Error) | ||
| fmt.Println() | ||
| fmt.Println("This could mean:") | ||
| fmt.Println(" - Your cluster is not accessible") | ||
| fmt.Println(" - Your kubeconfig is invalid") | ||
| fmt.Println(" - Network connectivity issues") | ||
| return o.detectionResult.Error | ||
| } | ||
| } | ||
|
|
||
| // Read existing config to preserve fields like default-nabsl | ||
| config, err := shared.ReadVeleroClientConfig() | ||
| if err != nil { | ||
| return fmt.Errorf("failed to read existing config: %w", err) | ||
| } | ||
|
|
||
| // Update config based on detection result | ||
| if o.detectionResult.IsAdmin { | ||
| config.NonAdmin = false | ||
| } else { | ||
| config.NonAdmin = true | ||
| } | ||
|
|
||
| // Write config file | ||
| if err := shared.WriteVeleroClientConfig(config); err != nil { | ||
|
Joeavaikath marked this conversation as resolved.
|
||
| return fmt.Errorf("failed to write config: %w", err) | ||
| } | ||
|
|
||
| // Print success message | ||
| o.printSetupSuccess() | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // printCurrentConfig prints the current configuration | ||
| func (o *SetupOptions) printCurrentConfig(config *shared.ClientConfig) { | ||
| homeDir, _ := os.UserHomeDir() | ||
| configPath := filepath.Join(homeDir, ".config", "velero", "config.json") | ||
|
Joeavaikath marked this conversation as resolved.
|
||
|
|
||
| if config.IsNonAdmin() { | ||
| fmt.Println("Current mode: non-admin") | ||
| } else { | ||
| fmt.Println("Current mode: admin") | ||
| } | ||
| fmt.Printf("Configuration file: %s\n", configPath) | ||
| } | ||
|
|
||
| // printSetupSuccess prints a success message after setup | ||
| func (o *SetupOptions) printSetupSuccess() { | ||
| homeDir, _ := os.UserHomeDir() | ||
| configPath := filepath.Join(homeDir, ".config", "velero", "config.json") | ||
|
|
||
| if o.detectionResult.IsAdmin { | ||
| fmt.Println("✓ Admin mode enabled") | ||
| fmt.Println() | ||
| fmt.Printf("Configuration saved to: %s\n", configPath) | ||
| fmt.Println() | ||
| fmt.Println("You can now use OADP admin commands:") | ||
| fmt.Println(" oc oadp backup create my-backup") | ||
| fmt.Println(" oc oadp restore create my-restore") | ||
| } else { | ||
| fmt.Println("✓ Non-admin mode enabled") | ||
| fmt.Println() | ||
| fmt.Printf("Configuration saved to: %s\n", configPath) | ||
| fmt.Println() | ||
| fmt.Println("You can now use OADP non-admin commands:") | ||
| fmt.Println(" oc oadp nonadmin backup create my-backup") | ||
| fmt.Println(" oc oadp nonadmin restore create my-restore") | ||
| } | ||
| } | ||
|
|
||
| // NewSetupCommand creates the setup command | ||
| func NewSetupCommand(f client.Factory) *cobra.Command { | ||
| o := &SetupOptions{} | ||
|
|
||
| c := &cobra.Command{ | ||
| Use: "setup", | ||
|
Joeavaikath marked this conversation as resolved.
|
||
| Short: "Auto-detect and configure admin vs non-admin mode", | ||
| Long: `Auto-detect and configure admin vs non-admin mode. | ||
|
|
||
| This command detects whether you have cluster-wide admin permissions and | ||
| automatically configures the OADP CLI to use the appropriate mode: | ||
|
|
||
| - Admin mode: Can create Velero Backup resources across all namespaces | ||
| - Non-admin mode: Can only create NonAdminBackup resources in current namespace | ||
|
|
||
| The detection works by checking RBAC permissions: oc auth can-i create backups.velero.io --all-namespaces | ||
|
|
||
| Configuration is saved to: ~/.config/velero/config.json | ||
|
|
||
| Examples: | ||
| # Auto-detect and configure OADP CLI | ||
| oc oadp setup | ||
|
|
||
| # Re-run detection (reconfigure) | ||
| oc oadp setup --force`, | ||
| Args: cobra.ExactArgs(0), | ||
| RunE: func(c *cobra.Command, args []string) error { | ||
| if err := o.Complete(args, f); err != nil { | ||
| return err | ||
| } | ||
| if err := o.Validate(c, args, f); err != nil { | ||
| return err | ||
| } | ||
| return o.Run(c, f) | ||
| }, | ||
| } | ||
|
|
||
| o.BindFlags(c.Flags()) | ||
|
|
||
| return c | ||
| } | ||
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.