-
Notifications
You must be signed in to change notification settings - Fork 928
chore: add unit test for X11 eviction #18565
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
+165
−3
Merged
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 |
---|---|---|
|
@@ -5,6 +5,7 @@ import ( | |
"bytes" | ||
"encoding/hex" | ||
"fmt" | ||
"io" | ||
"net" | ||
"os" | ||
"path/filepath" | ||
|
@@ -127,3 +128,162 @@ func TestServer_X11(t *testing.T) { | |
_, err = fs.Stat(filepath.Join(home, ".Xauthority")) | ||
require.NoError(t, err) | ||
} | ||
|
||
func TestServer_X11_EvictionLRU(t *testing.T) { | ||
t.Parallel() | ||
if runtime.GOOS != "linux" { | ||
t.Skip("X11 forwarding is only supported on Linux") | ||
} | ||
|
||
ctx := testutil.Context(t, testutil.WaitLong) | ||
logger := testutil.Logger(t) | ||
fs := afero.NewMemMapFs() | ||
|
||
// Use in-process networking for X11 forwarding. | ||
inproc := testutil.NewInProcNet() | ||
|
||
cfg := &agentssh.Config{ | ||
X11Net: inproc, | ||
} | ||
|
||
s, err := agentssh.NewServer(ctx, logger, prometheus.NewRegistry(), fs, agentexec.DefaultExecer, cfg) | ||
require.NoError(t, err) | ||
defer s.Close() | ||
err = s.UpdateHostSigner(42) | ||
require.NoError(t, err) | ||
|
||
ln, err := net.Listen("tcp", "127.0.0.1:0") | ||
require.NoError(t, err) | ||
|
||
done := testutil.Go(t, func() { | ||
err := s.Serve(ln) | ||
assert.Error(t, err) | ||
}) | ||
|
||
c := sshClient(t, ln.Addr().String()) | ||
|
||
// Calculate how many simultaneous X11 sessions we can create given the | ||
// configured port range. | ||
startPort := agentssh.X11StartPort + agentssh.X11DefaultDisplayOffset | ||
maxSessions := agentssh.X11MaxPort - startPort + 1 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: If we made |
||
require.Greater(t, maxSessions, 0, "expected a positive maxSessions value") | ||
|
||
// shellSession holds references to the session and its standard streams so | ||
// that the test can keep them open (and optionally interact with them) for | ||
// the lifetime of the test. If we don't start the Shell with pipes in place, | ||
// the session will be torn down asynchronously during the test. | ||
type shellSession struct { | ||
sess *gossh.Session | ||
stdin io.WriteCloser | ||
stdout io.Reader | ||
stderr io.Reader | ||
// scanner is used to read the output of the session, line by line. | ||
scanner *bufio.Scanner | ||
} | ||
|
||
sessions := make([]shellSession, 0, maxSessions) | ||
for i := 0; i < maxSessions; i++ { | ||
sess, err := c.NewSession() | ||
require.NoError(t, err) | ||
|
||
_, err = sess.SendRequest("x11-req", true, gossh.Marshal(ssh.X11{ | ||
AuthProtocol: "MIT-MAGIC-COOKIE-1", | ||
AuthCookie: hex.EncodeToString([]byte(fmt.Sprintf("cookie%d", i))), | ||
ScreenNumber: uint32(0), | ||
})) | ||
require.NoError(t, err) | ||
|
||
stdin, err := sess.StdinPipe() | ||
require.NoError(t, err) | ||
stdout, err := sess.StdoutPipe() | ||
require.NoError(t, err) | ||
stderr, err := sess.StderrPipe() | ||
require.NoError(t, err) | ||
require.NoError(t, sess.Shell()) | ||
|
||
// The SSH server lazily starts the session. We need to write a command | ||
// and read back to ensure the X11 forwarding is started. | ||
scanner := bufio.NewScanner(stdout) | ||
msg := fmt.Sprintf("ready-%d", i) | ||
_, err = stdin.Write([]byte("echo " + msg + "\n")) | ||
require.NoError(t, err) | ||
// Read until we get the message (first token may be empty due to shell prompt) | ||
for scanner.Scan() { | ||
line := strings.TrimSpace(scanner.Text()) | ||
if strings.Contains(line, msg) { | ||
break | ||
} | ||
} | ||
require.NoError(t, scanner.Err()) | ||
|
||
sessions = append(sessions, shellSession{ | ||
sess: sess, | ||
stdin: stdin, | ||
stdout: stdout, | ||
stderr: stderr, | ||
scanner: scanner, | ||
}) | ||
} | ||
|
||
// Create one more session which should evict the first (LRU) session and | ||
// therefore reuse the very first display/port. | ||
extraSess, err := c.NewSession() | ||
require.NoError(t, err) | ||
|
||
_, err = extraSess.SendRequest("x11-req", true, gossh.Marshal(ssh.X11{ | ||
AuthProtocol: "MIT-MAGIC-COOKIE-1", | ||
AuthCookie: hex.EncodeToString([]byte("extra")), | ||
ScreenNumber: uint32(0), | ||
})) | ||
require.NoError(t, err) | ||
|
||
// Ask the remote side for the DISPLAY value so we can extract the display | ||
// number that was assigned to this session. | ||
out, err := extraSess.Output("echo DISPLAY=$DISPLAY") | ||
require.NoError(t, err) | ||
|
||
// Example output line: "DISPLAY=localhost:10.0". | ||
var newDisplayNumber int | ||
{ | ||
sc := bufio.NewScanner(bytes.NewReader(out)) | ||
for sc.Scan() { | ||
line := strings.TrimSpace(sc.Text()) | ||
if strings.HasPrefix(line, "DISPLAY=") { | ||
parts := strings.SplitN(line, ":", 2) | ||
require.Len(t, parts, 2) | ||
displayPart := parts[1] | ||
if strings.Contains(displayPart, ".") { | ||
displayPart = strings.SplitN(displayPart, ".", 2)[0] | ||
} | ||
var convErr error | ||
newDisplayNumber, convErr = strconv.Atoi(displayPart) | ||
require.NoError(t, convErr) | ||
break | ||
} | ||
} | ||
require.NoError(t, sc.Err()) | ||
} | ||
|
||
// The display number should have wrapped around to the starting value. | ||
assert.Equal(t, agentssh.X11DefaultDisplayOffset, newDisplayNumber, "expected display number to be reused after eviction") | ||
|
||
// validate that the first session was torn down. | ||
_, err = sessions[0].stdin.Write([]byte("echo DISPLAY=$DISPLAY\n")) | ||
require.ErrorIs(t, err, io.EOF) | ||
err = sessions[0].sess.Wait() | ||
require.Error(t, err) | ||
|
||
// Cleanup. | ||
for _, sh := range sessions[1:] { | ||
err = sh.stdin.Close() | ||
require.NoError(t, err) | ||
err = sh.sess.Wait() | ||
require.NoError(t, err) | ||
} | ||
err = extraSess.Close() | ||
require.ErrorIs(t, err, io.EOF) | ||
|
||
err = s.Close() | ||
require.NoError(t, err) | ||
_ = testutil.TryReceive(ctx, t, done) | ||
} |
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.
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.
This is an under-appreciated feature of slog, nice to see it in action!