plugin_test.go 9.2 KB

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