plugin_test.go 9.2 KB

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