Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: Add config-ssh command#735

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
kylecarbs merged 2 commits intomainfromconfig-ssh
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions.vscode/settings.json
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
{
"cSpell.words": [
"cliflag",
"cliui",
"coderd",
"coderdtest",
Expand Down
91 changes: 41 additions & 50 deletionsagent/agent.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,24 +56,24 @@ type agent struct {
sshServer *ssh.Server
}

func (s *agent) run(ctx context.Context) {
func (a *agent) run(ctx context.Context) {
var peerListener *peerbroker.Listener
var err error
// An exponential back-off occurs when the connection is failing to dial.
// This is to prevent server spam in case of a coderd outage.
for retrier := retry.New(50*time.Millisecond, 10*time.Second); retrier.Wait(ctx); {
peerListener, err =s.clientDialer(ctx,s.options)
peerListener, err =a.clientDialer(ctx,a.options)
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
ifs.isClosed() {
ifa.isClosed() {
return
}
s.options.Logger.Warn(context.Background(), "failed to dial", slog.Error(err))
a.options.Logger.Warn(context.Background(), "failed to dial", slog.Error(err))
continue
}
s.options.Logger.Info(context.Background(), "connected")
a.options.Logger.Info(context.Background(), "connected")
break
}
select {
Expand All@@ -85,48 +85,48 @@ func (s *agent) run(ctx context.Context) {
for {
conn, err := peerListener.Accept()
if err != nil {
ifs.isClosed() {
ifa.isClosed() {
return
}
s.options.Logger.Debug(ctx, "peer listener accept exited; restarting connection", slog.Error(err))
s.run(ctx)
a.options.Logger.Debug(ctx, "peer listener accept exited; restarting connection", slog.Error(err))
a.run(ctx)
return
}
s.closeMutex.Lock()
s.connCloseWait.Add(1)
s.closeMutex.Unlock()
gos.handlePeerConn(ctx, conn)
a.closeMutex.Lock()
a.connCloseWait.Add(1)
a.closeMutex.Unlock()
goa.handlePeerConn(ctx, conn)
}
}

func (s *agent) handlePeerConn(ctx context.Context, conn *peer.Conn) {
func (a *agent) handlePeerConn(ctx context.Context, conn *peer.Conn) {
go func() {
<-conn.Closed()
s.connCloseWait.Done()
a.connCloseWait.Done()
}()
for {
channel, err := conn.Accept(ctx)
if err != nil {
if errors.Is(err, peer.ErrClosed) ||s.isClosed() {
if errors.Is(err, peer.ErrClosed) ||a.isClosed() {
return
}
s.options.Logger.Debug(ctx, "accept channel from peer connection", slog.Error(err))
a.options.Logger.Debug(ctx, "accept channel from peer connection", slog.Error(err))
return
}

switch channel.Protocol() {
case "ssh":
s.sshServer.HandleConn(channel.NetConn())
a.sshServer.HandleConn(channel.NetConn())
default:
s.options.Logger.Warn(ctx, "unhandled protocol from channel",
a.options.Logger.Warn(ctx, "unhandled protocol from channel",
slog.F("protocol", channel.Protocol()),
slog.F("label", channel.Label()),
)
}
}
}

func (s *agent) init(ctx context.Context) {
func (a *agent) init(ctx context.Context) {
// Clients' should ignore the host key when connecting.
// The agent needs to authenticate with coderd to SSH,
// so SSH authentication doesn't improve security.
Expand All@@ -138,17 +138,17 @@ func (s *agent) init(ctx context.Context) {
if err != nil {
panic(err)
}
sshLogger :=s.options.Logger.Named("ssh-server")
sshLogger :=a.options.Logger.Named("ssh-server")
forwardHandler := &ssh.ForwardedTCPHandler{}
s.sshServer = &ssh.Server{
a.sshServer = &ssh.Server{
ChannelHandlers: ssh.DefaultChannelHandlers,
ConnectionFailedCallback: func(conn net.Conn, err error) {
sshLogger.Info(ctx, "ssh connection ended", slog.Error(err))
},
Handler: func(session ssh.Session) {
err :=s.handleSSHSession(session)
err :=a.handleSSHSession(session)
if err != nil {
s.options.Logger.Debug(ctx, "ssh session failed", slog.Error(err))
a.options.Logger.Warn(ctx, "ssh session failed", slog.Error(err))
_ = session.Exit(1)
return
}
Expand DownExpand Up@@ -177,35 +177,26 @@ func (s *agent) init(ctx context.Context) {
},
ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig {
return &gossh.ServerConfig{
Config: gossh.Config{
// "arcfour" is the fastest SSH cipher. We prioritize throughput
// over encryption here, because the WebRTC connection is already
// encrypted. If possible, we'd disable encryption entirely here.
Ciphers: []string{"arcfour"},
},
NoClientAuth: true,
}
},
}

gos.run(ctx)
goa.run(ctx)
}

func (*agent) handleSSHSession(session ssh.Session) error {
func (a*agent) handleSSHSession(session ssh.Session) error {
var (
command string
args = []string{}
err error
)

username := session.User()
if username == "" {
currentUser, err := user.Current()
if err != nil {
return xerrors.Errorf("get current user: %w", err)
}
username = currentUser.Username
currentUser, err := user.Current()
if err != nil {
return xerrors.Errorf("get current user: %w", err)
}
username := currentUser.Username

// gliderlabs/ssh returns a command slice of zero
// when a shell is requested.
Expand DownExpand Up@@ -249,9 +240,9 @@ func (*agent) handleSSHSession(session ssh.Session) error {
}
go func() {
for win := range windowSize {
err:= ptty.Resize(uint16(win.Width), uint16(win.Height))
err = ptty.Resize(uint16(win.Width), uint16(win.Height))
if err != nil {
panic(err)
a.options.Logger.Warn(context.Background(), "failed to resize tty", slog.Error(err))
}
}
}()
Expand DownExpand Up@@ -286,24 +277,24 @@ func (*agent) handleSSHSession(session ssh.Session) error {
}

// isClosed returns whether the API is closed or not.
func (s *agent) isClosed() bool {
func (a *agent) isClosed() bool {
select {
case <-s.closed:
case <-a.closed:
return true
default:
return false
}
}

func (s *agent) Close() error {
s.closeMutex.Lock()
defers.closeMutex.Unlock()
ifs.isClosed() {
func (a *agent) Close() error {
a.closeMutex.Lock()
defera.closeMutex.Unlock()
ifa.isClosed() {
return nil
}
close(s.closed)
s.closeCancel()
_ =s.sshServer.Close()
s.connCloseWait.Wait()
close(a.closed)
a.closeCancel()
_ =a.sshServer.Close()
a.connCloseWait.Wait()
return nil
}
3 changes: 0 additions & 3 deletionsagent/conn.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,9 +39,6 @@ func (c *Conn) SSHClient() (*ssh.Client, error) {
return nil, xerrors.Errorf("ssh: %w", err)
}
sshConn, channels, requests, err := ssh.NewClientConn(netConn, "localhost:22", &ssh.ClientConfig{
Config: ssh.Config{
Ciphers: []string{"arcfour"},
},
// SSH host validation isn't helpful, because obtaining a peer
// connection already signifies user-intent to dial a workspace.
// #nosec
Expand Down
2 changes: 1 addition & 1 deletionagent/usershell/usershell_other.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,5 +27,5 @@ func Get(username string) (string, error) {
}
return parts[6], nil
}
return "", xerrors.New("user not found in /etc/passwd and $SHELL not set")
return "", xerrors.Errorf("user%qnot found in /etc/passwd", username)
}
21 changes: 11 additions & 10 deletionscli/cliui/agent.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,11 +3,11 @@ package cliui
import (
"context"
"fmt"
"io"
"sync"
"time"

"github.com/briandowns/spinner"
"github.com/spf13/cobra"
"golang.org/x/xerrors"

"github.com/coder/coder/codersdk"
Expand All@@ -21,15 +21,15 @@ type AgentOptions struct {
}

// Agent displays a spinning indicator that waits for a workspace agent to connect.
func Agent(cmd *cobra.Command, opts AgentOptions) error {
func Agent(ctx context.Context, writer io.Writer, opts AgentOptions) error {
if opts.FetchInterval == 0 {
opts.FetchInterval = 500 * time.Millisecond
}
if opts.WarnInterval == 0 {
opts.WarnInterval = 30 * time.Second
}
var resourceMutex sync.Mutex
resource, err := opts.Fetch(cmd.Context())
resource, err := opts.Fetch(ctx)
if err != nil {
return xerrors.Errorf("fetch: %w", err)
}
Expand All@@ -40,7 +40,8 @@ func Agent(cmd *cobra.Command, opts AgentOptions) error {
opts.WarnInterval = 0
}
spin := spinner.New(spinner.CharSets[78], 100*time.Millisecond, spinner.WithColor("fgHiGreen"))
spin.Writer = cmd.OutOrStdout()
spin.Writer = writer
spin.ForceOutput = true
spin.Suffix = " Waiting for connection from " + Styles.Field.Render(resource.Type+"."+resource.Name) + "..."
spin.Start()
defer spin.Stop()
Expand All@@ -51,7 +52,7 @@ func Agent(cmd *cobra.Command, opts AgentOptions) error {
defer timer.Stop()
go func() {
select {
case <-cmd.Context().Done():
case <-ctx.Done():
return
case <-timer.C:
}
Expand All@@ -63,17 +64,17 @@ func Agent(cmd *cobra.Command, opts AgentOptions) error {
}
// This saves the cursor position, then defers clearing from the cursor
// position to the end of the screen.
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "\033[s\r\033[2K%s\n\n", Styles.Paragraph.Render(Styles.Prompt.String()+message))
defer fmt.Fprintf(cmd.OutOrStdout(), "\033[u\033[J")
_, _ = fmt.Fprintf(writer, "\033[s\r\033[2K%s\n\n", Styles.Paragraph.Render(Styles.Prompt.String()+message))
defer fmt.Fprintf(writer, "\033[u\033[J")
}()
for {
select {
case <-cmd.Context().Done():
returncmd.Context().Err()
case <-ctx.Done():
returnctx.Err()
case <-ticker.C:
}
resourceMutex.Lock()
resource, err = opts.Fetch(cmd.Context())
resource, err = opts.Fetch(ctx)
if err != nil {
return xerrors.Errorf("fetch: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletioncli/cliui/agent_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ func TestAgent(t *testing.T) {
ptty := ptytest.New(t)
cmd := &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
err := cliui.Agent(cmd, cliui.AgentOptions{
err := cliui.Agent(cmd.Context(), cmd.OutOrStdout(), cliui.AgentOptions{
WorkspaceName: "example",
Fetch: func(ctx context.Context) (codersdk.WorkspaceResource, error) {
resource := codersdk.WorkspaceResource{
Expand Down
38 changes: 38 additions & 0 deletionscli/cliui/log.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
package cliui

import (
"fmt"
"io"
"strings"

"github.com/charmbracelet/lipgloss"
)

// cliMessage provides a human-readable message for CLI errors and messages.
type cliMessage struct {
Level string
Style lipgloss.Style
Header string
Lines []string
}

// String formats the CLI message for consumption by a human.
func (m cliMessage) String() string {
var str strings.Builder
_, _ = fmt.Fprintf(&str, "%s\r\n",
Styles.Bold.Render(m.Header))
for _, line := range m.Lines {
_, _ = fmt.Fprintf(&str, " %s %s\r\n", m.Style.Render("|"), line)
}
return str.String()
}

// Warn writes a log to the writer provided.
func Warn(wtr io.Writer, header string, lines ...string) {
_, _ = fmt.Fprint(wtr, cliMessage{
Level: "warning",
Style: Styles.Warn,
Header: header,
Lines: lines,
}.String())
}
7 changes: 6 additions & 1 deletioncli/cliui/prompt.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@ package cliui

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
Expand DownExpand Up@@ -62,7 +63,11 @@ func Prompt(cmd *cobra.Command, opts PromptOptions) (string, error) {
var rawMessage json.RawMessage
err := json.NewDecoder(pipeReader).Decode(&rawMessage)
if err == nil {
line = string(rawMessage)
var buf bytes.Buffer
err = json.Compact(&buf, rawMessage)
if err == nil {
line = buf.String()
}
}
}
}
Expand Down
4 changes: 1 addition & 3 deletionscli/cliui/prompt_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -93,9 +93,7 @@ func TestPrompt(t *testing.T) {
ptty.WriteLine(`{
"test": "wow"
}`)
require.Equal(t, `{
"test": "wow"
}`, <-doneChan)
require.Equal(t, `{"test":"wow"}`, <-doneChan)
})
}

Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp