Skip to content

fix: Modify the terminal connection method#8415

Merged
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@fix_terminal
Apr 17, 2025
Merged

fix: Modify the terminal connection method#8415
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@fix_terminal

Conversation

@ssongliu
Copy link
Copy Markdown
Member

No description provided.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Apr 17, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

}
let title = res.data.user + '@' + res.data.addr + ':' + res.data.port;
if (res.data.name.length !== 0) {
title = res.data.name + '-' + title;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main changes detected are:

  1. The hostInfo object has been renamed to form. This change affects all subsequent references to this data structure, making it consistent and potentially easier to maintain.

  2. A new property isLocal has been added to the form object. This seems unused and might be redundant depending on the current logic of handling local hosts separately from other non-local ones.

  3. The loadLocal method has been introduced to initialize certain fields when opening the dialog with isLocal set to true.

  4. A conditional check (if (form.isLocal)) is used in both setDefault and submitAddHost methods to handle different behaviors based on whether a local host is being configured or edited.

Suggestions for Optimization/Improvement

  1. Remove Redundant Code: If there's no specific reason to keep hostInfo around after moving most of its properties into form, consider removing it entirely.

  2. Ensure that any logic related to setting defaults or initializing fields for different scenarios is clearly documented and easy to follow.

  3. Verify if updating other parts of the application to use the new form consistently would eliminate redundancy elsewhere in the codebase.

  4. Consider adding some form validation checks at runtime during the initial setup phase to ensure all necessary fields are correctly filled out before proceeding further.

These suggested adjustments aim to improve clarity and possibly streamline future maintenance of the component.

connAfterEncrypt, _ := encrypt.StringEncrypt(string(localConn))
_ = settingRepo.Update("LocalSSHConn", connAfterEncrypt)
return nil
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code provided contains several minor improvements and corrections to handle SSH connection encryption, decryption, serialization, and deserialization in addition to setting management:

Minor Changes and Corrections:

  1. Base64 Encoding and Decoding: Added calls to base64.StdEncoding.DecodeString for password and private key fields when updating them after retrieving from the repository.
  2. Error Handling for Base64 Decoding: Included checks for errors when decoding password and private key base64 strings before using them.
  3. Connection Testing Logic: The TestConnByInfo function now correctly handles authentication methods ("password" and "key") by decrypting passwords before attempting SSH connections.

Additional Features:

  • Encrypted Password Management: Ensures passwords are stored encrypted, preventing exposure of sensitive information.
  • SSH Client Configuration: The implementation includes creation and testing of an SSH client based on user-provided connection details.

Overall, these changes improve the security and functionality of the SSH settings management service within your application.

return nil, err
}
return ssh.NewClient(connInDB)
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code changes seem mostly correct, but there are a few areas where improvements can be made:

  1. Error Handling: In loadLocalConn, ensure that all errors are checked immediately after each operation to avoid cascading errors.

  2. Database Error Handling: Make sure database operations return appropriate errors and handle them appropriately.

  3. User Home Dir Check: Ensure that the directory exists before attempting to read from it, especially if it contains sensitive information like SSH keys.

  4. Code DRYness: Consider extracting common logic into utility functions to reduce redundancy and improve readability.

Here's an improved version of the function with some minor corrections:

func loadLocalConn() (*ssh.SSHClient, error) {
	currentInfo, err := user.Current()
	if err != nil {
		return(nil, fmt.Errorf("failed to get current user: %w", err))
	}

	itemPath := "/"
	if len(currentInfo.HomeDir) > 0 {
		itemPath = path.Join(currentInfo.HomeDir, ".ssh/")
	}
	itemPath += "id_ed25519_1panel"

	if _, err := os.Stat(itemPath); os.IsNotExist(err) {
		return generateNewSSHKey(itemPath)
	}

	file, err := os.OpenFile(itemPath, os.O_RDONLY|os.O_CREATE|os.O_EXCL, 0600)
	if err != nil {
		return(nil, fmt.Errorf("failed to open SSH key file: %w", err))
	}
	defer file.Close()

	privateKeyBytes, err := ioutil.ReadAll(file)
	if err != nil {
		return(nil, fmt.Errorf("failed to read SSH key: %w", err))
	}

	connWithKey := ssh.ConnInfo{
		Addr:       "127.0.0.1",
		User:       "root",
		Port:       22,
		AuthMode:   "key",
		PrivateKey: privateKeyBytes,
	}
	client, err := ssh.NewClient(connWithKey)
	if err == nil {
		return client, nil
	}

	connFromDB, err := settingService.GetSSHInfo()
	if err != nil {
		return(nil, fmt.Errorf("failed to get SSH connection info from DB: %w", err))
	}

	var connConfig ssh.ConnInfo
	err = json.Unmarshal([]byte(connFromDB), &connConfig)
	if err != nil {
		return(nil, fmt.Errorf("failed to unmarshal SSH connection info: %w", err))
	}

	return ssh.NewClient(connConfig)
}

func generateNewSSHKey(path string) (*ssh.SSHClient, error) {
	req := dto.GenerateSSH{
		EncryptionMode: "ed25519",
		Name:           "_1panel",
	}

	newPrivateKey, err := sshService.GenerateSSH(req)
	if err != nil {
		return(nil, fmt.Errorf("failed to generate new SSH key: %w", err))
	}

	err = ioutil.WriteFile(path, newPrivateKey.Bytes(), 0600)
	if err != nil {
		return(nil, fmt.Errorf("failed to write new SSH key: %w", err))
	}

	connWithKey := ssh.ConnInfo{
		Addr:       "127.0.0.1",
		User:       "root",
		Port:       22,
		AuthMode:   "key",
		PrivateKey: newPrivateKey.Bytes(),
	}
	client, err := ssh.NewClient(connWithKey)
	if err != nil {
		return	nil, fmt.Errorf("failed to create SSH client: %w", err)
	}

	return client, nil
}

Key Changes Made:

  • Improved error handling throughout the function.
  • Checked for non-existent files before assuming a directory structure.
  • Used context-aware operations for better resource management (defer).
  • Extracted error messages for clarity.
  • Ensured that paths were constructed correctly regardless of whether a home directory was present.

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown
Member

@wanghe-fit2cloud wanghe-fit2cloud left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/lgtm

@wanghe-fit2cloud
Copy link
Copy Markdown
Member

/approve

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Apr 17, 2025

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wanghe-fit2cloud

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@f2c-ci-robot f2c-ci-robot Bot merged commit 5a1e010 into dev-v2 Apr 17, 2025
6 checks passed
@f2c-ci-robot f2c-ci-robot Bot deleted the pr@dev-v2@fix_terminal branch April 17, 2025 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants