Skip to content

Commit

Permalink
Updates test commands
Browse files Browse the repository at this point in the history
  • Loading branch information
CGoodwin90 committed Jul 10, 2024
2 parents ac25389 + 2d045bf commit 7ee52d9
Show file tree
Hide file tree
Showing 168 changed files with 2,513 additions and 1,988 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ deps:
test: gen
GO111MODULE=on $(GOCMD) fmt ./...
GO111MODULE=on $(GOCMD) vet ./...
GO111MODULE=on $(GOCMD) test -v ./...
GO111MODULE=on $(GOCMD) test -v -run '^Test(A[^P].*|[^A].*)' ./...

clean:
$(GOCMD) clean
Expand Down Expand Up @@ -117,7 +117,7 @@ release-major:
api-tests: gen
GO111MODULE=on $(GOCMD) fmt ./...
GO111MODULE=on $(GOCMD) vet ./...
GO111MODULE=on $(GOCMD) test -v -run '(TestEnvironmentCommands|TestProjectCommands)' ./...
GO111MODULE=on $(GOCMD) test -v -run '^(TestAPI)' ./...

# upstream
CI_BUILD_TAG ?= lagoon-cli
Expand Down
10 changes: 10 additions & 0 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,14 @@ var configAddCmd = &cobra.Command{
if lagoonConfig.SSHKey != "" {
lc.SSHKey = lagoonConfig.SSHKey
}
// check identity files flag
identityFiles, err := cmd.Flags().GetStringSlice("publickey-identityfile")
if err != nil {
return err
}
if identityFiles != nil {
lc.PublicKeyIdentities = identityFiles
}
lagoonCLIConfig.Lagoons[lagoonConfig.Lagoon] = lc
if err := writeLagoonConfig(&lagoonCLIConfig, filepath.Join(configFilePath, configName+configExtension)); err != nil {
return fmt.Errorf("couldn't write config: %v", err)
Expand Down Expand Up @@ -316,6 +324,8 @@ func init() {
"Lagoon Kibana URL (https://logs.amazeeio.cloud)")
configAddCmd.Flags().StringVarP(&lagoonSSHKey, "ssh-key", "", "",
"SSH Key to use for this cluster for generating tokens")
configAddCmd.Flags().StringSliceP("publickey-identityfile", "", []string{},
"Specific public key identity files to use when doing ssh-agent checks (support multiple)")
configLagoonsCmd.Flags().BoolVarP(&fullConfigList, "show-full", "", false,
"Show full config output when listing Lagoon configurations")
configFeatureSwitch.Flags().StringVarP(&updateCheck, "disable-update-check", "", "",
Expand Down
36 changes: 18 additions & 18 deletions cmd/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use 'lagoon deploy latest' instead`,
if err != nil {
return err
}
returnData, err := cmd.Flags().GetBool("returnData")
returnData, err := cmd.Flags().GetBool("returndata")
if err != nil {
return err
}
Expand Down Expand Up @@ -109,7 +109,7 @@ var deployPromoteCmd = &cobra.Command{
if err != nil {
return err
}
returnData, err := cmd.Flags().GetBool("returnData")
returnData, err := cmd.Flags().GetBool("returndata")
if err != nil {
return err
}
Expand Down Expand Up @@ -164,7 +164,7 @@ This environment should already exist in lagoon. It is analogous with the 'Deplo
},
RunE: func(cmd *cobra.Command, args []string) error {

returnData, err := cmd.Flags().GetBool("returnData")
returnData, err := cmd.Flags().GetBool("returndata")
if err != nil {
return err
}
Expand Down Expand Up @@ -237,23 +237,23 @@ This pullrequest may not already exist as an environment in lagoon.`,
if err != nil {
return err
}
baseBranchName, err := cmd.Flags().GetString("baseBranchName")
baseBranchName, err := cmd.Flags().GetString("base-branch-name")
if err != nil {
return err
}
baseBranchRef, err := cmd.Flags().GetString("baseBranchRef")
baseBranchRef, err := cmd.Flags().GetString("base-branch-ref")
if err != nil {
return err
}
headBranchName, err := cmd.Flags().GetString("headBranchName")
headBranchName, err := cmd.Flags().GetString("head-branch-name")
if err != nil {
return err
}
headBranchRef, err := cmd.Flags().GetString("headBranchRef")
headBranchRef, err := cmd.Flags().GetString("head-branch-ref")
if err != nil {
return err
}
if err := requiredInputCheck("Project name", cmdProjectName, "Pullrequest title", prTitle, "Pullrequest number", strconv.Itoa(int(prNumber)), "baseBranchName", baseBranchName, "baseBranchRef", baseBranchRef, "headBranchName", headBranchName, "headBranchRef", headBranchRef); err != nil {
if err := requiredInputCheck("Project name", cmdProjectName, "Pullrequest title", prTitle, "Pullrequest number", strconv.Itoa(int(prNumber)), "Base branch name", baseBranchName, "Base branch ref", baseBranchRef, "Head branch name", headBranchName, "Head branch ref", headBranchRef); err != nil {
return err
}
buildVarStrings, err := cmd.Flags().GetStringArray("buildvar")
Expand All @@ -265,7 +265,7 @@ This pullrequest may not already exist as an environment in lagoon.`,
return err
}

returnData, err := cmd.Flags().GetBool("returnData")
returnData, err := cmd.Flags().GetBool("returndata")
if err != nil {
return err
}
Expand Down Expand Up @@ -309,25 +309,25 @@ func init() {
deployCmd.AddCommand(deployPullrequestCmd)

const returnDataUsageText = "Returns the build name instead of success text"
deployLatestCmd.Flags().Bool("returnData", false, returnDataUsageText)
deployLatestCmd.Flags().Bool("returndata", false, returnDataUsageText)
deployLatestCmd.Flags().StringArray("buildvar", []string{}, "Add one or more build variables to deployment (--buildvar KEY1=VALUE1 [--buildvar KEY2=VALUE2])")

deployBranchCmd.Flags().StringP("branch", "b", "", "Branch name to deploy")
deployBranchCmd.Flags().StringP("branchRef", "r", "", "Branch ref to deploy")
deployBranchCmd.Flags().Bool("returnData", false, returnDataUsageText)
deployBranchCmd.Flags().StringP("branch-ref", "r", "", "Branch ref to deploy")
deployBranchCmd.Flags().Bool("returndata", false, returnDataUsageText)
deployBranchCmd.Flags().StringArray("buildvar", []string{}, "Add one or more build variables to deployment (--buildvar KEY1=VALUE1 [--buildvar KEY2=VALUE2])")

deployPromoteCmd.Flags().StringP("destination", "d", "", "Destination environment name to create")
deployPromoteCmd.Flags().StringP("source", "s", "", "Source environment name to use as the base to deploy from")
deployPromoteCmd.Flags().Bool("returnData", false, returnDataUsageText)
deployPromoteCmd.Flags().Bool("returndata", false, returnDataUsageText)
deployPromoteCmd.Flags().StringArray("buildvar", []string{}, "Add one or more build variables to deployment (--buildvar KEY1=VALUE1 [--buildvar KEY2=VALUE2])")

deployPullrequestCmd.Flags().StringP("title", "t", "", "Pullrequest title")
deployPullrequestCmd.Flags().UintP("number", "n", 0, "Pullrequest number")
deployPullrequestCmd.Flags().StringP("baseBranchName", "N", "", "Pullrequest base branch name")
deployPullrequestCmd.Flags().StringP("baseBranchRef", "R", "", "Pullrequest base branch reference hash")
deployPullrequestCmd.Flags().StringP("headBranchName", "H", "", "Pullrequest head branch name")
deployPullrequestCmd.Flags().StringP("headBranchRef", "M", "", "Pullrequest head branch reference hash")
deployPullrequestCmd.Flags().Bool("returnData", false, returnDataUsageText)
deployPullrequestCmd.Flags().StringP("base-branch-name", "N", "", "Pullrequest base branch name")
deployPullrequestCmd.Flags().StringP("base-branch-ref", "R", "", "Pullrequest base branch reference hash")
deployPullrequestCmd.Flags().StringP("head-branch-name", "H", "", "Pullrequest head branch name")
deployPullrequestCmd.Flags().StringP("head-branch-ref", "M", "", "Pullrequest head branch reference hash")
deployPullrequestCmd.Flags().Bool("returndata", false, returnDataUsageText)
deployPullrequestCmd.Flags().StringArray("buildvar", []string{}, "Add one or more build variables to deployment (--buildvar KEY1=VALUE1 [--buildvar KEY2=VALUE2])")
}
6 changes: 3 additions & 3 deletions cmd/deploytarget.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var addDeployTargetCmd = &cobra.Command{
Use: "deploytarget",
Aliases: []string{"dt"},
Short: "Add a DeployTarget to lagoon",
Long: "Add a DeployTarget (kubernetes or openshift) to lagoon, this requires admin level permissions",
Long: "Add a Deploytarget(Kubernetes) to lagoon, this requires admin level permissions",
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
Expand Down Expand Up @@ -148,7 +148,7 @@ var updateDeployTargetCmd = &cobra.Command{
Use: "deploytarget",
Aliases: []string{"dt"},
Short: "Update a DeployTarget in lagoon",
Long: "Update a DeployTarget (kubernetes or openshift) in lagoon, this requires admin level permissions",
Long: "Update a Deploytarget(Kubernetes) in lagoon, this requires admin level permissions",
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
Expand Down Expand Up @@ -281,7 +281,7 @@ var deleteDeployTargetCmd = &cobra.Command{
Use: "deploytarget",
Aliases: []string{"dt"},
Short: "Delete a DeployTarget from lagoon",
Long: "Delete a DeployTarget (kubernetes or openshift) from lagoon, this requires admin level permissions",
Long: "Delete a Deploytarget(Kubernetes) from lagoon, this requires admin level permissions",
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
Expand Down
6 changes: 3 additions & 3 deletions cmd/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ var updateEnvironmentCmd = &cobra.Command{
if err != nil {
return err
}
openShift, err := cmd.Flags().GetUint("deploytarget")
deploytarget, err := cmd.Flags().GetUint("deploytarget")
if err != nil {
return err
}
Expand Down Expand Up @@ -142,7 +142,7 @@ var updateEnvironmentCmd = &cobra.Command{
Route: nullStrCheck(route),
Routes: nullStrCheck(routes),
DeployTitle: nullStrCheck(deployTitle),
Openshift: nullUintCheck(openShift),
Openshift: nullUintCheck(deploytarget),
}
if environmentAutoIdleProvided {
environmentFlags.AutoIdle = &environmentAutoIdle
Expand Down Expand Up @@ -316,7 +316,7 @@ func init() {
updateEnvironmentCmd.Flags().String("route", "", "Update the route for the selected environment")
updateEnvironmentCmd.Flags().String("routes", "", "Update the routes for the selected environment")
updateEnvironmentCmd.Flags().UintVarP(&environmentAutoIdle, "auto-idle", "a", 1, "Auto idle setting of the environment")
updateEnvironmentCmd.Flags().UintP("deploytarget", "d", 0, "Reference to OpenShift Object this Environment should be deployed to")
updateEnvironmentCmd.Flags().UintP("deploytarget", "d", 0, "Reference to Deploytarget(Kubernetes) this Environment should be deployed to")
updateEnvironmentCmd.Flags().String("environment-type", "", "Update the environment type - production | development")
updateEnvironmentCmd.Flags().String("deploy-type", "", "Update the deploy type - branch | pullrequest | promote")
}
2 changes: 1 addition & 1 deletion cmd/environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra"
)

func TestEnvironmentCommands(t *testing.T) {
func TestAPIEnvironmentCommands(t *testing.T) {
tests := []struct {
name string
cmdArgs []string
Expand Down
2 changes: 1 addition & 1 deletion cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ var getEnvironmentCmd = &cobra.Command{
returnNonEmptyString(fmt.Sprintf("%v", environment.DeployHeadRef)),
})
dataMain := output.Table{
Header: []string{"ID", "EnvironmentName", "EnvironmentType", "DeployType", "Created", "OpenshiftProjectName", "Route", "Routes", "AutoIdle", "DeployTitle", "DeployBaseRef", "DeployHeadRef"},
Header: []string{"ID", "EnvironmentName", "EnvironmentType", "DeployType", "Created", "Namespace", "Route", "Routes", "AutoIdle", "DeployTitle", "DeployBaseRef", "DeployHeadRef"},
Data: data,
}
r := output.RenderOutput(dataMain, outputOptions)
Expand Down
10 changes: 5 additions & 5 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ You can get it to continue anyway with --keep-going. To disable any prompts, use
if err != nil {
return err
}
openshiftID, err := cmd.Flags().GetUint("openshiftID")
deploytargetID, err := cmd.Flags().GetUint("deploytarget-id")
if err != nil {
return err
}
Expand Down Expand Up @@ -62,7 +62,7 @@ You can get it to continue anyway with --keep-going. To disable any prompts, use
return fmt.Errorf("couldn't open file: %w", err)
}

return lagoon.Import(context.TODO(), lc, file, keepGoing, openshiftID)
return lagoon.Import(context.TODO(), lc, file, keepGoing, deploytargetID)
},
}

Expand Down Expand Up @@ -136,9 +136,9 @@ func init() {
"path to the file to import")
importCmd.Flags().Bool("keep-going", false,
"on error, just log and continue instead of aborting")
importCmd.Flags().Uint("openshiftID", 0,
"ID of the openshift to target for import")
for _, flag := range []string{"import-file", "openshiftID"} {
importCmd.Flags().Uint("deploytarget-id", 0,
"ID of the deploytarget to target for import")
for _, flag := range []string{"import-file", "deploytarget-id"} {
if err := importCmd.MarkFlagRequired(flag); err != nil {
panic(err)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ var listDeployTargetsCmd = &cobra.Command{
Use: "deploytargets",
Aliases: []string{"deploytarget", "dt"},
Short: "List all DeployTargets in Lagoon",
Long: "List all DeployTargets (kubernetes or openshift) in lagoon, this requires admin level permissions",
Long: "List all Deploytargets(Kubernetes) in lagoon, this requires admin level permissions",
PreRunE: func(_ *cobra.Command, _ []string) error {
return validateTokenE(cmdLagoon)
},
Expand Down
63 changes: 52 additions & 11 deletions cmd/login.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"bytes"
"fmt"
"net"
"os"
Expand All @@ -10,7 +11,7 @@ import (
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/terminal"
terminal "golang.org/x/term"
)

var loginCmd = &cobra.Command{
Expand All @@ -23,29 +24,71 @@ var loginCmd = &cobra.Command{
},
}

func publicKey(path string, skipAgent bool) (ssh.AuthMethod, func() error) {
func publicKey(path, publicKeyOverride string, publicKeyIdentities []string, skipAgent bool) (ssh.AuthMethod, func() error) {
noopCloseFunc := func() error { return nil }

if !skipAgent {
// Connect to SSH agent to ask for unencrypted private keys
if sshAgentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
sshAgent := agent.NewClient(sshAgentConn)

keys, _ := sshAgent.List()
if len(keys) > 0 {
// There are key(s) in the agent
//defer sshAgentConn.Close()
return ssh.PublicKeysCallback(sshAgent.Signers), sshAgentConn.Close
agentSigners, err := sshAgent.Signers()
handleError(err)
// There are key(s) in the agent
if len(agentSigners) > 0 {
identities := make(map[string]ssh.PublicKey)
if publicKeyOverride == "" {
// check for identify files in the current lagoon config context
for _, identityFile := range publicKeyIdentities {
// append to identityfiles
keybytes, err := os.ReadFile(identityFile)
handleError(err)
pubkey, _, _, _, err := ssh.ParseAuthorizedKey(keybytes)
handleError(err)
identities[identityFile] = pubkey
}
} else {
// append to identityfiles
keybytes, err := os.ReadFile(publicKeyOverride)
handleError(err)
pubkey, _, _, _, err := ssh.ParseAuthorizedKey(keybytes)
handleError(err)
identities[publicKeyOverride] = pubkey
}
// check all keys in the agent to see if there is a matching identity file
for _, signer := range agentSigners {
for file, identity := range identities {
if bytes.Equal(signer.PublicKey().Marshal(), identity.Marshal()) {
if verboseOutput {
fmt.Fprintf(os.Stderr, "ssh: attempting connection using identity file public key: %s\n", file)
}
// only provide this matching key back to the ssh client to use
return ssh.PublicKeys(signer), noopCloseFunc
}
}
}
if publicKeyOverride != "" {
handleError(fmt.Errorf("ssh: no key matching %s in agent", publicKeyOverride))
}
// if no matching identity files, just return all agent keys like previous behaviour
if verboseOutput {
fmt.Fprintf(os.Stderr, "ssh: attempting connection using any keys in ssh-agent\n")
}
return ssh.PublicKeysCallback(sshAgent.Signers), noopCloseFunc
}
}
}

// if no keys in the agent, and a specific private key has been defined, then check the key and use it if possible
if verboseOutput {
fmt.Fprintf(os.Stderr, "ssh: attempting connection using private key: %s\n", path)
}
key, err := os.ReadFile(path)
handleError(err)

// Try to look for an unencrypted private key
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
// if encrypted, prompt for passphrase or error and ask user to add to their agent
fmt.Printf("Enter passphrase for %s:", path)
bytePassword, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
Expand All @@ -60,9 +103,7 @@ func publicKey(path string, skipAgent bool) (ssh.AuthMethod, func() error) {
fmt.Println("Lagoon CLI could not decode private key, you will need to add your private key to your ssh-agent.")
os.Exit(1)
}
return ssh.PublicKeys(signer), noopCloseFunc
}
// return unencrypted private key
return ssh.PublicKeys(signer), noopCloseFunc
}

Expand Down Expand Up @@ -98,7 +139,7 @@ func retrieveTokenViaSsh() (string, error) {
privateKey = cmdSSHKey
skipAgent = true
}
authMethod, closeSSHAgent := publicKey(privateKey, skipAgent)
authMethod, closeSSHAgent := publicKey(privateKey, cmdPubkeyIdentity, lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].PublicKeyIdentities, skipAgent)
config := &ssh.ClientConfig{
User: "lagoon",
Auth: []ssh.AuthMethod{
Expand Down
2 changes: 1 addition & 1 deletion cmd/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func getSSHClientConfig(environmentName string) (*ssh.ClientConfig,
return nil, nil, fmt.Errorf("couldn't get ~/.ssh/known_hosts: %v", err)
}
// configure an SSH client session
authMethod, closeSSHAgent := publicKey(privateKey, skipAgent)
authMethod, closeSSHAgent := publicKey(privateKey, cmdPubkeyIdentity, lagoonCLIConfig.Lagoons[lagoonCLIConfig.Current].PublicKeyIdentities, skipAgent)
return &ssh.ClientConfig{
User: cmdProjectName + "-" + environmentName,
Auth: []ssh.AuthMethod{authMethod},
Expand Down
Loading

0 comments on commit 7ee52d9

Please sign in to comment.