plugin_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package common // import "github.com/docker/docker/integration/plugin/common"
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strings"
  13. "testing"
  14. "github.com/containerd/containerd/images"
  15. "github.com/containerd/containerd/remotes/docker"
  16. "github.com/docker/docker/api/types"
  17. registrytypes "github.com/docker/docker/api/types/registry"
  18. "github.com/docker/docker/api/types/system"
  19. "github.com/docker/docker/pkg/jsonmessage"
  20. "github.com/docker/docker/testutil"
  21. "github.com/docker/docker/testutil/daemon"
  22. "github.com/docker/docker/testutil/fixtures/plugin"
  23. "github.com/docker/docker/testutil/registry"
  24. "github.com/docker/docker/testutil/request"
  25. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  26. "gotest.tools/v3/assert"
  27. is "gotest.tools/v3/assert/cmp"
  28. "gotest.tools/v3/skip"
  29. )
  30. // TestPluginInvalidJSON tests that POST endpoints that expect a body return
  31. // the correct error when sending invalid JSON requests.
  32. func TestPluginInvalidJSON(t *testing.T) {
  33. ctx := setupTest(t)
  34. // POST endpoints that accept / expect a JSON body;
  35. endpoints := []string{
  36. "/plugins/foobar/set",
  37. "/plugins/foobar/upgrade",
  38. "/plugins/pull",
  39. }
  40. for _, ep := range endpoints {
  41. ep := ep
  42. t.Run(ep[1:], func(t *testing.T) {
  43. t.Parallel()
  44. ctx := testutil.StartSpan(ctx, t)
  45. t.Run("invalid content type", func(t *testing.T) {
  46. ctx := testutil.StartSpan(ctx, t)
  47. res, body, err := request.Post(ctx, ep, request.RawString("[]"), request.ContentType("text/plain"))
  48. assert.NilError(t, err)
  49. assert.Check(t, is.Equal(res.StatusCode, http.StatusBadRequest))
  50. buf, err := request.ReadBody(body)
  51. assert.NilError(t, err)
  52. assert.Check(t, is.Contains(string(buf), "unsupported Content-Type header (text/plain): must be 'application/json'"))
  53. })
  54. t.Run("invalid JSON", func(t *testing.T) {
  55. ctx := testutil.StartSpan(ctx, t)
  56. res, body, err := request.Post(ctx, ep, request.RawString("{invalid json"), request.JSON)
  57. assert.NilError(t, err)
  58. assert.Check(t, is.Equal(res.StatusCode, http.StatusBadRequest))
  59. buf, err := request.ReadBody(body)
  60. assert.NilError(t, err)
  61. assert.Check(t, is.Contains(string(buf), "invalid JSON: invalid character 'i' looking for beginning of object key string"))
  62. })
  63. t.Run("extra content after JSON", func(t *testing.T) {
  64. ctx := testutil.StartSpan(ctx, t)
  65. res, body, err := request.Post(ctx, ep, request.RawString(`[] trailing content`), request.JSON)
  66. assert.NilError(t, err)
  67. assert.Check(t, is.Equal(res.StatusCode, http.StatusBadRequest))
  68. buf, err := request.ReadBody(body)
  69. assert.NilError(t, err)
  70. assert.Check(t, is.Contains(string(buf), "unexpected content after JSON"))
  71. })
  72. t.Run("empty body", func(t *testing.T) {
  73. ctx := testutil.StartSpan(ctx, t)
  74. // empty body should not produce an 500 internal server error, or
  75. // any 5XX error (this is assuming the request does not produce
  76. // an internal server error for another reason, but it shouldn't)
  77. res, _, err := request.Post(ctx, ep, request.RawString(``), request.JSON)
  78. assert.NilError(t, err)
  79. assert.Check(t, res.StatusCode < http.StatusInternalServerError)
  80. })
  81. })
  82. }
  83. }
  84. func TestPluginInstall(t *testing.T) {
  85. skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
  86. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  87. skip.If(t, testEnv.IsRootless, "rootless mode has different view of localhost")
  88. ctx := testutil.StartSpan(baseContext, t)
  89. client := testEnv.APIClient()
  90. t.Run("no auth", func(t *testing.T) {
  91. ctx := setupTest(t)
  92. reg := registry.NewV2(t)
  93. defer reg.Close()
  94. name := "test-" + strings.ToLower(t.Name())
  95. repo := path.Join(registry.DefaultURL, name+":latest")
  96. assert.NilError(t, plugin.CreateInRegistry(ctx, repo, nil))
  97. rdr, err := client.PluginInstall(ctx, repo, types.PluginInstallOptions{Disabled: true, RemoteRef: repo})
  98. assert.NilError(t, err)
  99. defer rdr.Close()
  100. _, err = io.Copy(io.Discard, rdr)
  101. assert.NilError(t, err)
  102. _, _, err = client.PluginInspectWithRaw(ctx, repo)
  103. assert.NilError(t, err)
  104. })
  105. t.Run("with digest", func(t *testing.T) {
  106. ctx := setupTest(t)
  107. reg := registry.NewV2(t)
  108. defer reg.Close()
  109. name := "test-" + strings.ToLower(t.Name())
  110. repo := path.Join(registry.DefaultURL, name+":latest")
  111. err := plugin.Create(ctx, client, repo)
  112. assert.NilError(t, err)
  113. rdr, err := client.PluginPush(ctx, repo, "")
  114. assert.NilError(t, err)
  115. defer rdr.Close()
  116. buf := &strings.Builder{}
  117. assert.NilError(t, err)
  118. var digest string
  119. assert.NilError(t, jsonmessage.DisplayJSONMessagesStream(rdr, buf, 0, false, func(j jsonmessage.JSONMessage) {
  120. if j.Aux != nil {
  121. var r types.PushResult
  122. assert.NilError(t, json.Unmarshal(*j.Aux, &r))
  123. digest = r.Digest
  124. }
  125. }), buf)
  126. err = client.PluginRemove(ctx, repo, types.PluginRemoveOptions{Force: true})
  127. assert.NilError(t, err)
  128. rdr, err = client.PluginInstall(ctx, repo, types.PluginInstallOptions{
  129. Disabled: true,
  130. RemoteRef: repo + "@" + digest,
  131. })
  132. assert.NilError(t, err)
  133. defer rdr.Close()
  134. _, err = io.Copy(io.Discard, rdr)
  135. assert.NilError(t, err)
  136. _, _, err = client.PluginInspectWithRaw(ctx, repo)
  137. assert.NilError(t, err)
  138. })
  139. t.Run("with htpasswd", func(t *testing.T) {
  140. ctx := setupTest(t)
  141. reg := registry.NewV2(t, registry.Htpasswd)
  142. defer reg.Close()
  143. name := "test-" + strings.ToLower(t.Name())
  144. repo := path.Join(registry.DefaultURL, name+":latest")
  145. auth := &registrytypes.AuthConfig{ServerAddress: registry.DefaultURL, Username: "testuser", Password: "testpassword"}
  146. assert.NilError(t, plugin.CreateInRegistry(ctx, repo, auth))
  147. authEncoded, err := json.Marshal(auth)
  148. assert.NilError(t, err)
  149. rdr, err := client.PluginInstall(ctx, repo, types.PluginInstallOptions{
  150. RegistryAuth: base64.URLEncoding.EncodeToString(authEncoded),
  151. Disabled: true,
  152. RemoteRef: repo,
  153. })
  154. assert.NilError(t, err)
  155. defer rdr.Close()
  156. _, err = io.Copy(io.Discard, rdr)
  157. assert.NilError(t, err)
  158. _, _, err = client.PluginInspectWithRaw(ctx, repo)
  159. assert.NilError(t, err)
  160. })
  161. t.Run("with insecure", func(t *testing.T) {
  162. skip.If(t, !testEnv.IsLocalDaemon())
  163. ctx := testutil.StartSpan(ctx, t)
  164. addrs, err := net.InterfaceAddrs()
  165. assert.NilError(t, err)
  166. var bindTo string
  167. for _, addr := range addrs {
  168. ip, ok := addr.(*net.IPNet)
  169. if !ok {
  170. continue
  171. }
  172. if ip.IP.IsLoopback() || ip.IP.To4() == nil {
  173. continue
  174. }
  175. bindTo = ip.IP.String()
  176. }
  177. if bindTo == "" {
  178. t.Skip("No suitable interface to bind registry to")
  179. }
  180. regURL := bindTo + ":5000"
  181. d := daemon.New(t)
  182. defer d.Stop(t)
  183. d.Start(t, "--insecure-registry="+regURL)
  184. defer d.Stop(t)
  185. reg := registry.NewV2(t, registry.URL(regURL))
  186. defer reg.Close()
  187. name := "test-" + strings.ToLower(t.Name())
  188. repo := path.Join(regURL, name+":latest")
  189. assert.NilError(t, plugin.CreateInRegistry(ctx, repo, nil, plugin.WithInsecureRegistry(regURL)))
  190. client := d.NewClientT(t)
  191. rdr, err := client.PluginInstall(ctx, repo, types.PluginInstallOptions{Disabled: true, RemoteRef: repo})
  192. assert.NilError(t, err)
  193. defer rdr.Close()
  194. _, err = io.Copy(io.Discard, rdr)
  195. assert.NilError(t, err)
  196. _, _, err = client.PluginInspectWithRaw(ctx, repo)
  197. assert.NilError(t, err)
  198. })
  199. // TODO: test insecure registry with https
  200. }
  201. func TestPluginsWithRuntimes(t *testing.T) {
  202. skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
  203. skip.If(t, testEnv.IsRootless, "Test not supported on rootless due to buggy daemon setup in rootless mode due to daemon restart")
  204. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  205. ctx := testutil.StartSpan(baseContext, t)
  206. dir, err := os.MkdirTemp("", t.Name())
  207. assert.NilError(t, err)
  208. defer os.RemoveAll(dir)
  209. d := daemon.New(t)
  210. defer d.Cleanup(t)
  211. d.Start(t)
  212. defer d.Stop(t)
  213. client := d.NewClientT(t)
  214. assert.NilError(t, plugin.Create(ctx, client, "test:latest"))
  215. defer client.PluginRemove(ctx, "test:latest", types.PluginRemoveOptions{Force: true})
  216. assert.NilError(t, client.PluginEnable(ctx, "test:latest", types.PluginEnableOptions{Timeout: 30}))
  217. p := filepath.Join(dir, "myrt")
  218. script := fmt.Sprintf(`#!/bin/sh
  219. file="%s/success"
  220. if [ "$1" = "someArg" ]; then
  221. shift
  222. file="${file}_someArg"
  223. fi
  224. touch $file
  225. exec runc $@
  226. `, dir)
  227. assert.NilError(t, os.WriteFile(p, []byte(script), 0o777))
  228. type config struct {
  229. Runtimes map[string]system.Runtime `json:"runtimes"`
  230. }
  231. cfg, err := json.Marshal(config{
  232. Runtimes: map[string]system.Runtime{
  233. "myrt": {Path: p},
  234. "myrtArgs": {Path: p, Args: []string{"someArg"}},
  235. },
  236. })
  237. configPath := filepath.Join(dir, "config.json")
  238. os.WriteFile(configPath, cfg, 0o644)
  239. t.Run("No Args", func(t *testing.T) {
  240. _ = testutil.StartSpan(ctx, t)
  241. d.Restart(t, "--default-runtime=myrt", "--config-file="+configPath)
  242. _, err = os.Stat(filepath.Join(dir, "success"))
  243. assert.NilError(t, err)
  244. })
  245. t.Run("With Args", func(t *testing.T) {
  246. _ = testutil.StartSpan(ctx, t)
  247. d.Restart(t, "--default-runtime=myrtArgs", "--config-file="+configPath)
  248. _, err = os.Stat(filepath.Join(dir, "success_someArg"))
  249. assert.NilError(t, err)
  250. })
  251. }
  252. func TestPluginBackCompatMediaTypes(t *testing.T) {
  253. skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
  254. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  255. skip.If(t, testEnv.IsRootless, "Rootless has a different view of localhost (needed for test registry access)")
  256. ctx := setupTest(t)
  257. reg := registry.NewV2(t)
  258. defer reg.Close()
  259. reg.WaitReady(t)
  260. repo := path.Join(registry.DefaultURL, strings.ToLower(t.Name())+":latest")
  261. client := testEnv.APIClient()
  262. assert.NilError(t, plugin.Create(ctx, client, repo))
  263. rdr, err := client.PluginPush(ctx, repo, "")
  264. assert.NilError(t, err)
  265. defer rdr.Close()
  266. buf := &strings.Builder{}
  267. assert.NilError(t, jsonmessage.DisplayJSONMessagesStream(rdr, buf, 0, false, nil), buf)
  268. // Use custom header here because older versions of the registry do not
  269. // parse the accept header correctly and does not like the accept header
  270. // that the default resolver code uses. "Older registries" here would be
  271. // like the one currently included in the test suite.
  272. headers := http.Header{}
  273. headers.Add("Accept", images.MediaTypeDockerSchema2Manifest)
  274. resolver := docker.NewResolver(docker.ResolverOptions{
  275. Headers: headers,
  276. })
  277. assert.NilError(t, err)
  278. n, desc, err := resolver.Resolve(ctx, repo)
  279. assert.NilError(t, err, repo)
  280. fetcher, err := resolver.Fetcher(ctx, n)
  281. assert.NilError(t, err)
  282. rdr, err = fetcher.Fetch(ctx, desc)
  283. assert.NilError(t, err)
  284. defer rdr.Close()
  285. var m ocispec.Manifest
  286. assert.NilError(t, json.NewDecoder(rdr).Decode(&m))
  287. assert.Check(t, is.Equal(m.MediaType, images.MediaTypeDockerSchema2Manifest))
  288. assert.Check(t, is.Len(m.Layers, 1))
  289. assert.Check(t, is.Equal(m.Layers[0].MediaType, images.MediaTypeDockerSchema2LayerGzip))
  290. }