daemon_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package daemon // import "github.com/docker/docker/integration/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "syscall"
  13. "testing"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/daemon/config"
  16. "github.com/docker/docker/testutil/daemon"
  17. "gotest.tools/v3/assert"
  18. is "gotest.tools/v3/assert/cmp"
  19. "gotest.tools/v3/env"
  20. "gotest.tools/v3/skip"
  21. )
  22. func TestConfigDaemonLibtrustID(t *testing.T) {
  23. skip.If(t, runtime.GOOS == "windows")
  24. d := daemon.New(t)
  25. defer d.Stop(t)
  26. trustKey := filepath.Join(d.RootDir(), "key.json")
  27. err := os.WriteFile(trustKey, []byte(`{"crv":"P-256","d":"dm28PH4Z4EbyUN8L0bPonAciAQa1QJmmyYd876mnypY","kid":"WTJ3:YSIP:CE2E:G6KJ:PSBD:YX2Y:WEYD:M64G:NU2V:XPZV:H2CR:VLUB","kty":"EC","x":"Mh5-JINSjaa_EZdXDttri255Z5fbCEOTQIZjAcScFTk","y":"eUyuAjfxevb07hCCpvi4Zi334Dy4GDWQvEToGEX4exQ"}`), 0644)
  28. assert.NilError(t, err)
  29. config := filepath.Join(d.RootDir(), "daemon.json")
  30. err = os.WriteFile(config, []byte(`{"deprecated-key-path": "`+trustKey+`"}`), 0644)
  31. assert.NilError(t, err)
  32. d.Start(t, "--config-file", config)
  33. info := d.Info(t)
  34. assert.Equal(t, info.ID, "WTJ3:YSIP:CE2E:G6KJ:PSBD:YX2Y:WEYD:M64G:NU2V:XPZV:H2CR:VLUB")
  35. }
  36. func TestDaemonConfigValidation(t *testing.T) {
  37. skip.If(t, runtime.GOOS == "windows")
  38. d := daemon.New(t)
  39. dockerBinary, err := d.BinaryPath()
  40. assert.NilError(t, err)
  41. params := []string{"--validate", "--config-file"}
  42. dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
  43. if dest == "" {
  44. dest = os.Getenv("DEST")
  45. }
  46. testdata := filepath.Join(dest, "..", "..", "integration", "daemon", "testdata")
  47. const (
  48. validOut = "configuration OK"
  49. failedOut = "unable to configure the Docker daemon with file"
  50. )
  51. tests := []struct {
  52. name string
  53. args []string
  54. expectedOut string
  55. }{
  56. {
  57. name: "config with no content",
  58. args: append(params, filepath.Join(testdata, "empty-config-1.json")),
  59. expectedOut: validOut,
  60. },
  61. {
  62. name: "config with {}",
  63. args: append(params, filepath.Join(testdata, "empty-config-2.json")),
  64. expectedOut: validOut,
  65. },
  66. {
  67. name: "invalid config",
  68. args: append(params, filepath.Join(testdata, "invalid-config-1.json")),
  69. expectedOut: failedOut,
  70. },
  71. {
  72. name: "malformed config",
  73. args: append(params, filepath.Join(testdata, "malformed-config.json")),
  74. expectedOut: failedOut,
  75. },
  76. {
  77. name: "valid config",
  78. args: append(params, filepath.Join(testdata, "valid-config-1.json")),
  79. expectedOut: validOut,
  80. },
  81. }
  82. for _, tc := range tests {
  83. tc := tc
  84. t.Run(tc.name, func(t *testing.T) {
  85. t.Parallel()
  86. cmd := exec.Command(dockerBinary, tc.args...)
  87. out, err := cmd.CombinedOutput()
  88. assert.Check(t, is.Contains(string(out), tc.expectedOut))
  89. if tc.expectedOut == failedOut {
  90. assert.ErrorContains(t, err, "", "expected an error, but got none")
  91. } else {
  92. assert.NilError(t, err)
  93. }
  94. })
  95. }
  96. }
  97. func TestConfigDaemonSeccompProfiles(t *testing.T) {
  98. skip.If(t, runtime.GOOS == "windows")
  99. d := daemon.New(t)
  100. defer d.Stop(t)
  101. tests := []struct {
  102. doc string
  103. profile string
  104. expectedProfile string
  105. }{
  106. {
  107. doc: "empty profile set",
  108. profile: "",
  109. expectedProfile: config.SeccompProfileDefault,
  110. },
  111. {
  112. doc: "default profile",
  113. profile: config.SeccompProfileDefault,
  114. expectedProfile: config.SeccompProfileDefault,
  115. },
  116. {
  117. doc: "unconfined profile",
  118. profile: config.SeccompProfileUnconfined,
  119. expectedProfile: config.SeccompProfileUnconfined,
  120. },
  121. }
  122. for _, tc := range tests {
  123. tc := tc
  124. t.Run(tc.doc, func(t *testing.T) {
  125. d.Start(t, "--seccomp-profile="+tc.profile)
  126. info := d.Info(t)
  127. assert.Assert(t, is.Contains(info.SecurityOptions, "name=seccomp,profile="+tc.expectedProfile))
  128. d.Stop(t)
  129. cfg := filepath.Join(d.RootDir(), "daemon.json")
  130. err := os.WriteFile(cfg, []byte(`{"seccomp-profile": "`+tc.profile+`"}`), 0644)
  131. assert.NilError(t, err)
  132. d.Start(t, "--config-file", cfg)
  133. info = d.Info(t)
  134. assert.Assert(t, is.Contains(info.SecurityOptions, "name=seccomp,profile="+tc.expectedProfile))
  135. d.Stop(t)
  136. })
  137. }
  138. }
  139. func TestDaemonProxy(t *testing.T) {
  140. skip.If(t, runtime.GOOS == "windows", "cannot start multiple daemons on windows")
  141. skip.If(t, os.Getenv("DOCKER_ROOTLESS") != "", "cannot connect to localhost proxy in rootless environment")
  142. var received string
  143. proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  144. received = r.Host
  145. w.Header().Set("Content-Type", "application/json")
  146. _, _ = w.Write([]byte("OK"))
  147. }))
  148. defer proxyServer.Close()
  149. const userPass = "myuser:mypassword@"
  150. // Configure proxy through env-vars
  151. t.Run("environment variables", func(t *testing.T) {
  152. defer env.Patch(t, "HTTP_PROXY", proxyServer.URL)()
  153. defer env.Patch(t, "HTTPS_PROXY", proxyServer.URL)()
  154. defer env.Patch(t, "NO_PROXY", "example.com")()
  155. d := daemon.New(t)
  156. c := d.NewClientT(t)
  157. defer func() { _ = c.Close() }()
  158. ctx := context.Background()
  159. d.Start(t)
  160. _, err := c.ImagePull(ctx, "example.org:5000/some/image:latest", types.ImagePullOptions{})
  161. assert.ErrorContains(t, err, "", "pulling should have failed")
  162. assert.Equal(t, received, "example.org:5000")
  163. // Test NoProxy: example.com should not hit the proxy, and "received" variable should not be changed.
  164. _, err = c.ImagePull(ctx, "example.com/some/image:latest", types.ImagePullOptions{})
  165. assert.ErrorContains(t, err, "", "pulling should have failed")
  166. assert.Equal(t, received, "example.org:5000", "should not have used proxy")
  167. info := d.Info(t)
  168. assert.Equal(t, info.HTTPProxy, proxyServer.URL)
  169. assert.Equal(t, info.HTTPSProxy, proxyServer.URL)
  170. assert.Equal(t, info.NoProxy, "example.com")
  171. d.Stop(t)
  172. })
  173. // Configure proxy through command-line flags
  174. t.Run("command-line options", func(t *testing.T) {
  175. defer env.Patch(t, "HTTP_PROXY", "http://"+userPass+"from-env-http.invalid")()
  176. defer env.Patch(t, "http_proxy", "http://"+userPass+"from-env-http.invalid")()
  177. defer env.Patch(t, "HTTPS_PROXY", "https://"+userPass+"myuser:mypassword@from-env-https.invalid")()
  178. defer env.Patch(t, "https_proxy", "https://"+userPass+"myuser:mypassword@from-env-https.invalid")()
  179. defer env.Patch(t, "NO_PROXY", "ignore.invalid")()
  180. defer env.Patch(t, "no_proxy", "ignore.invalid")()
  181. d := daemon.New(t)
  182. d.Start(t, "--http-proxy", proxyServer.URL, "--https-proxy", proxyServer.URL, "--no-proxy", "example.com")
  183. logs, err := d.ReadLogFile()
  184. assert.NilError(t, err)
  185. assert.Assert(t, is.Contains(string(logs), "overriding existing proxy variable with value from configuration"))
  186. for _, v := range []string{"http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "no_proxy", "NO_PROXY"} {
  187. assert.Assert(t, is.Contains(string(logs), "name="+v))
  188. assert.Assert(t, !strings.Contains(string(logs), userPass), "logs should not contain the non-sanitized proxy URL: %s", string(logs))
  189. }
  190. c := d.NewClientT(t)
  191. defer func() { _ = c.Close() }()
  192. ctx := context.Background()
  193. _, err = c.ImagePull(ctx, "example.org:5001/some/image:latest", types.ImagePullOptions{})
  194. assert.ErrorContains(t, err, "", "pulling should have failed")
  195. assert.Equal(t, received, "example.org:5001")
  196. // Test NoProxy: example.com should not hit the proxy, and "received" variable should not be changed.
  197. _, err = c.ImagePull(ctx, "example.com/some/image:latest", types.ImagePullOptions{})
  198. assert.ErrorContains(t, err, "", "pulling should have failed")
  199. assert.Equal(t, received, "example.org:5001", "should not have used proxy")
  200. info := d.Info(t)
  201. assert.Equal(t, info.HTTPProxy, proxyServer.URL)
  202. assert.Equal(t, info.HTTPSProxy, proxyServer.URL)
  203. assert.Equal(t, info.NoProxy, "example.com")
  204. d.Stop(t)
  205. })
  206. // Configure proxy through configuration file
  207. t.Run("configuration file", func(t *testing.T) {
  208. defer env.Patch(t, "HTTP_PROXY", "http://"+userPass+"from-env-http.invalid")()
  209. defer env.Patch(t, "http_proxy", "http://"+userPass+"from-env-http.invalid")()
  210. defer env.Patch(t, "HTTPS_PROXY", "https://"+userPass+"myuser:mypassword@from-env-https.invalid")()
  211. defer env.Patch(t, "https_proxy", "https://"+userPass+"myuser:mypassword@from-env-https.invalid")()
  212. defer env.Patch(t, "NO_PROXY", "ignore.invalid")()
  213. defer env.Patch(t, "no_proxy", "ignore.invalid")()
  214. d := daemon.New(t)
  215. c := d.NewClientT(t)
  216. defer func() { _ = c.Close() }()
  217. ctx := context.Background()
  218. configFile := filepath.Join(d.RootDir(), "daemon.json")
  219. configJSON := fmt.Sprintf(`{"http-proxy":%[1]q, "https-proxy": %[1]q, "no-proxy": "example.com"}`, proxyServer.URL)
  220. assert.NilError(t, os.WriteFile(configFile, []byte(configJSON), 0644))
  221. d.Start(t, "--config-file", configFile)
  222. logs, err := d.ReadLogFile()
  223. assert.NilError(t, err)
  224. assert.Assert(t, is.Contains(string(logs), "overriding existing proxy variable with value from configuration"))
  225. for _, v := range []string{"http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "no_proxy", "NO_PROXY"} {
  226. assert.Assert(t, is.Contains(string(logs), "name="+v))
  227. assert.Assert(t, !strings.Contains(string(logs), userPass), "logs should not contain the non-sanitized proxy URL: %s", string(logs))
  228. }
  229. _, err = c.ImagePull(ctx, "example.org:5002/some/image:latest", types.ImagePullOptions{})
  230. assert.ErrorContains(t, err, "", "pulling should have failed")
  231. assert.Equal(t, received, "example.org:5002")
  232. // Test NoProxy: example.com should not hit the proxy, and "received" variable should not be changed.
  233. _, err = c.ImagePull(ctx, "example.com/some/image:latest", types.ImagePullOptions{})
  234. assert.ErrorContains(t, err, "", "pulling should have failed")
  235. assert.Equal(t, received, "example.org:5002", "should not have used proxy")
  236. info := d.Info(t)
  237. assert.Equal(t, info.HTTPProxy, proxyServer.URL)
  238. assert.Equal(t, info.HTTPSProxy, proxyServer.URL)
  239. assert.Equal(t, info.NoProxy, "example.com")
  240. d.Stop(t)
  241. })
  242. // Conflicting options (passed both through command-line options and config file)
  243. t.Run("conflicting options", func(t *testing.T) {
  244. const (
  245. proxyRawURL = "https://" + userPass + "example.org"
  246. proxyURL = "https://xxxxx:xxxxx@example.org"
  247. )
  248. d := daemon.New(t)
  249. configFile := filepath.Join(d.RootDir(), "daemon.json")
  250. configJSON := fmt.Sprintf(`{"http-proxy":%[1]q, "https-proxy": %[1]q, "no-proxy": "example.com"}`, proxyRawURL)
  251. assert.NilError(t, os.WriteFile(configFile, []byte(configJSON), 0644))
  252. err := d.StartWithError("--http-proxy", proxyRawURL, "--https-proxy", proxyRawURL, "--no-proxy", "example.com", "--config-file", configFile, "--validate")
  253. assert.ErrorContains(t, err, "daemon exited during startup")
  254. logs, err := d.ReadLogFile()
  255. assert.NilError(t, err)
  256. expected := fmt.Sprintf(
  257. `the following directives are specified both as a flag and in the configuration file: http-proxy: (from flag: %[1]s, from file: %[1]s), https-proxy: (from flag: %[1]s, from file: %[1]s), no-proxy: (from flag: example.com, from file: example.com)`,
  258. proxyURL,
  259. )
  260. assert.Assert(t, is.Contains(string(logs), expected))
  261. })
  262. // Make sure values are sanitized when reloading the daemon-config
  263. t.Run("reload sanitized", func(t *testing.T) {
  264. const (
  265. proxyRawURL = "https://" + userPass + "example.org"
  266. proxyURL = "https://xxxxx:xxxxx@example.org"
  267. )
  268. d := daemon.New(t)
  269. d.Start(t, "--http-proxy", proxyRawURL, "--https-proxy", proxyRawURL, "--no-proxy", "example.com")
  270. defer d.Stop(t)
  271. err := d.Signal(syscall.SIGHUP)
  272. assert.NilError(t, err)
  273. logs, err := d.ReadLogFile()
  274. assert.NilError(t, err)
  275. // FIXME: there appears to ba a race condition, which causes ReadLogFile
  276. // to not contain the full logs after signaling the daemon to reload,
  277. // causing the test to fail here. As a workaround, check if we
  278. // received the "reloaded" message after signaling, and only then
  279. // check that it's sanitized properly. For more details on this
  280. // issue, see https://github.com/moby/moby/pull/42835/files#r713120315
  281. if !strings.Contains(string(logs), "Reloaded configuration:") {
  282. t.Skip("Skipping test, because we did not find 'Reloaded configuration' in the logs")
  283. }
  284. assert.Assert(t, is.Contains(string(logs), proxyURL))
  285. assert.Assert(t, !strings.Contains(string(logs), userPass), "logs should not contain the non-sanitized proxy URL: %s", string(logs))
  286. })
  287. }