Skip to content

Commit

Permalink
New test for system connection add
Browse files Browse the repository at this point in the history
The e2e test introduced by this PR verifies that
the command `system connection add`, run against an
SSH server, parses and updates correctly the local
`known_hosts` file.

Depends on containers/common#2212
Fixes containers#23575

Signed-off-by: Mario Loriedo <[email protected]>
  • Loading branch information
l0rd committed Oct 24, 2024
1 parent 2155438 commit 8313a0e
Show file tree
Hide file tree
Showing 12 changed files with 1,075 additions and 109 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ repos:
- id: check-yaml
- repo: https://github.com/codespell-project/codespell
# Configuration for codespell is in .codespellrc
rev: v2.2.6
rev: v2.3.0
hooks:
- id: codespell
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ require (
github.com/sigstore/fulcio v1.6.4 // indirect
github.com/sigstore/rekor v1.3.6 // indirect
github.com/sigstore/sigstore v1.8.9 // indirect
github.com/skeema/knownhosts v1.3.0 // indirect
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 // indirect
github.com/sylabs/sif/v2 v2.19.1 // indirect
Expand Down Expand Up @@ -226,3 +227,5 @@ require (
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
tags.cncf.io/container-device-interface/specs-go v0.8.0 // indirect
)

replace github.com/containers/common v0.60.1-0.20241018183244-7e6f2b4d6de7 => github.com/l0rd/containers-common v0.0.0-20241022154342-ca63ba0b720f
6 changes: 4 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,6 @@ github.com/containernetworking/plugins v1.5.1 h1:T5ji+LPYjjgW0QM+KyrigZbLsZ8jaX+
github.com/containernetworking/plugins v1.5.1/go.mod h1:MIQfgMayGuHYs0XdNudf31cLLAC+i242hNm6KuDGqCM=
github.com/containers/buildah v1.37.1-0.20241018144937-2551c8f3d110 h1:YcrjUM1CwDTEnaPHgpVmjid/R3zAVXRRHcgknQsajlI=
github.com/containers/buildah v1.37.1-0.20241018144937-2551c8f3d110/go.mod h1:SVyERMThmMXGTdle/9MdRuX2Ae7eVY9qDVartYXIx7E=
github.com/containers/common v0.60.1-0.20241018183244-7e6f2b4d6de7 h1:EFzq3sjwy0vBr9RoZPzTbtoGZR4hoZsmgxuIs5Uc5FA=
github.com/containers/common v0.60.1-0.20241018183244-7e6f2b4d6de7/go.mod h1:T8vpUWd7AspK7CMELf/c+NCZB6bKrRkLriRCspdFGyQ=
github.com/containers/conmon v2.0.20+incompatible h1:YbCVSFSCqFjjVwHTPINGdMX1F6JXHGTUje2ZYobNrkg=
github.com/containers/conmon v2.0.20+incompatible/go.mod h1:hgwZ2mtuDrppv78a/cOBNiCm6O0UMWGx1mu7P00nu5I=
github.com/containers/gvisor-tap-vsock v0.7.5 h1:bTy4u3DOmmUPwurL6me2rsgfypAFDhyeJleUcQmBR/E=
Expand Down Expand Up @@ -322,6 +320,8 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/l0rd/containers-common v0.0.0-20241022154342-ca63ba0b720f h1:/b+0pAwLqPPsNMjIkJmVzCNjQI4vVrwH5QOL/u8mpJE=
github.com/l0rd/containers-common v0.0.0-20241022154342-ca63ba0b720f/go.mod h1:YJ/JrTD8ZjvR5FjHfM/7HjwN6O5zjO/oRTLohw1mwtg=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec h1:2tTW6cDth2TSgRbAhD7yjZzTQmcN25sDRPEeinR51yQ=
Expand Down Expand Up @@ -462,6 +462,8 @@ github.com/sigstore/sigstore v1.8.9 h1:NiUZIVWywgYuVTxXmRoTT4O4QAGiTEKup4N1wdxFa
github.com/sigstore/sigstore v1.8.9/go.mod h1:d9ZAbNDs8JJfxJrYmulaTazU3Pwr8uLL9+mii4BNR3w=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/skeema/knownhosts v1.3.0 h1:AM+y0rI04VksttfwjkSTNQorvGqmwATnvnAHpSgc0LY=
github.com/skeema/knownhosts v1.3.0/go.mod h1:sPINvnADmT/qYH1kfv+ePMmOBTH6Tbl7b5LvTDjFK7M=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
Expand Down
136 changes: 131 additions & 5 deletions test/e2e/system_connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package integration

import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
Expand Down Expand Up @@ -422,20 +424,29 @@ qe ssh://[email protected]:2222/run/podman/podman.sock ~/.ssh/id_rsa false true
})
})

Context("sshd and API services required", func() {
BeforeEach(func() {
// Using "Ordered" or tests would concurrently access
// the ~/.ssh/know_host file with unexpected results
Context("sshd and API services required", Ordered, func() {
var khCopyPath, khPath string
var u *user.User

BeforeAll(func() {
// These tests are unique in as much as they require podman, podman-remote, systemd and sshd.
// podman-remote commands will be executed by ginkgo directly.
SkipIfContainerized("sshd is not available when running in a container")
SkipIfRemote("connection heuristic requires both podman and podman-remote binaries")
SkipIfNotRootless(fmt.Sprintf("FIXME: set up ssh keys when root. uid(%d) euid(%d)", os.Getuid(), os.Geteuid()))
SkipIfSystemdNotRunning("cannot test connection heuristic if systemd is not running")
SkipIfNotActive("sshd", "cannot test connection heuristic if sshd is not running")
})

It("add ssh:// socket path using connection heuristic", func() {
u, err := user.Current()
// If the file ~/.ssh/known_host exists, temporarily remove it so that the tests are deterministics
var err error
u, err = user.Current()
Expect(err).ShouldNot(HaveOccurred())
khPath = filepath.Join(u.HomeDir, ".ssh", "known_hosts")
khCopyPath = khPath + ".copy"
err = os.Rename(khPath, khCopyPath)
Expect(err == nil || errors.Is(err, os.ErrNotExist)).To(BeTrue(), fmt.Sprintf("failed to rename %s to %s", khPath, khCopyPath))

// Ensure that the remote end uses our built podman
if os.Getenv("PODMAN_BINARY") == "" {
Expand All @@ -446,7 +457,14 @@ qe ssh://[email protected]:2222/run/podman/podman.sock ~/.ssh/id_rsa false true
os.Unsetenv("PODMAN_BINARY")
}()
}
})

AfterAll(func() { // codespell:ignore afterall
err = os.Rename(khCopyPath, khPath)
Expect(err == nil || errors.Is(err, os.ErrNotExist)).To(BeTrue(), fmt.Sprintf("failed to rename %s to %s", khCopyPath, khPath))
})

It("add ssh:// socket path using connection heuristic", func() {
cmd := exec.Command(podmanTest.RemotePodmanBinary,
"system", "connection", "add",
"--default",
Expand Down Expand Up @@ -488,5 +506,113 @@ qe ssh://[email protected]:2222/run/podman/podman.sock ~/.ssh/id_rsa false true
Expect(lsSession).Should(Exit(0))
Expect(string(lsSession.Out.Contents())).To(Equal("QA " + uri.String() + " " + filepath.Join(u.HomeDir, ".ssh", "id_ed25519") + " true true\n"))
})

Describe("add ssh:// with known_hosts", func() {
var (
initialKnownHostFilesLines map[string][]string
currentSSHServerHostname string
)

BeforeAll(func() {
currentSSHServerHostname = "localhost"

// Retrieve current SSH server first two public keys
// with the command `ssh-keyscan localhost`
cmd := exec.Command("ssh-keyscan", currentSSHServerHostname)
session, err := Start(cmd, GinkgoWriter, GinkgoWriter)
Expect(err).ToNot(HaveOccurred(), fmt.Sprintf("ssh-keyscan %s failed to execute", currentSSHServerHostname))
Eventually(session, DefaultWaitTimeout).Should(Exit(0))
Expect(session.Out.Contents()).ShouldNot(BeEmpty())
// Even if no error occurs, ssh-keyscan writes the
// list of hosts to stderr
Expect(session.Err.Contents()).ShouldNot(BeEmpty())
serverKeys := bytes.Split(session.Out.Contents(), []byte("\n"))
Expect(len(serverKeys)).Should(BeNumerically(">=", 2), fmt.Sprintf("ssh-keyscan %s returned less then 2 keys", currentSSHServerHostname))

initialKnownHostFilesLines = map[string][]string{
"serverFirstKey": {string(serverKeys[0])},
"serverSecondKey": {string(serverKeys[1])},
"fakeKey": {currentSSHServerHostname + " ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGnBlHlwqleAtyzT01mLa+DXQFyxX8T0oa8odcEZ2/07"},
"differentHostKey": {"differentserver ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGnBlHlwqleAtyzT01mLa+DXQFyxX8T0oa8odcEZ2/07"},
"empty": {},
}
})

DescribeTable("->",
func(label string, shouldFail bool, shouldAddKey bool) {
initialKhLines, ok := initialKnownHostFilesLines[label]
Expect(ok).To(BeTrue(), fmt.Sprintf("label %q not found in kh", label))
// Create known_hosts file if needed
if len(initialKhLines) > 0 {
khFile, err := os.Create(khPath)
Expect(err).ToNot(HaveOccurred(), fmt.Sprintf("failed to create %s", khPath))
defer khFile.Close()
err = os.WriteFile(khPath, []byte(strings.Join(initialKhLines, "\n")), 0600)
Expect(err).ToNot(HaveOccurred(), fmt.Sprintf("failed to write to %s", khPath))
}
// Run podman system connection add
cmd := exec.Command(podmanTest.RemotePodmanBinary,
"system", "connection", "add",
"--default",
"--identity", filepath.Join(u.HomeDir, ".ssh", "id_ed25519"),
"QA",
fmt.Sprintf("ssh://%s@%s", u.Username, currentSSHServerHostname))
session, err := Start(cmd, GinkgoWriter, GinkgoWriter)
Expect(err).ToNot(HaveOccurred(), fmt.Sprintf("%q failed to execute", podmanTest.RemotePodmanBinary))
Expect(session.Out.Contents()).Should(BeEmpty())
if shouldFail {
Eventually(session, DefaultWaitTimeout).Should(Exit(125))
Expect(session.Err.Contents()).ShouldNot(BeEmpty())
} else {
Eventually(session, DefaultWaitTimeout).Should(Exit(0))
Expect(session.Err.Contents()).Should(BeEmpty())
}
// If the known_hosts file didn't exist, it should
// have been created
if len(initialKhLines) == 0 {
Expect(khPath).To(BeAnExistingFile())
defer os.Remove(khPath)
}
// If the known_hosts file didn't contain the SSH server
// public key it should have been added
if shouldAddKey {
khFileContent, err := os.ReadFile(khPath)
Expect(err).ToNot(HaveOccurred())
khLines := bytes.Split(khFileContent, []byte("\n"))
Expect(len(khLines)).To(BeNumerically(">", len(initialKhLines)))
}
},
Entry(
"with a public key of the SSH server that matches the SSH server first key",
"serverFirstKey",
false,
false,
),
Entry(
"with a public key of the SSH server that matches SSH server second key",
"serverSecondKey",
false,
false,
),
Entry(
"with a fake public key of the SSH server that doesn't match any of the SSH server keys (should fail)",
"fakeKey",
true,
false,
),
Entry(
"with no public key for the SSH server (new key should be added)",
"differentHostKey",
false,
true,
),
Entry(
"not existing (should be created and a new key should be added)",
"empty",
false,
true,
),
)
})
})
})
Loading

0 comments on commit 8313a0e

Please sign in to comment.