plugin_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 htpasswd", func(t *testing.T) {
  106. ctx := setupTest(t)
  107. reg := registry.NewV2(t, registry.Htpasswd)
  108. defer reg.Close()
  109. name := "test-" + strings.ToLower(t.Name())
  110. repo := path.Join(registry.DefaultURL, name+":latest")
  111. auth := &registrytypes.AuthConfig{ServerAddress: registry.DefaultURL, Username: "testuser", Password: "testpassword"}
  112. assert.NilError(t, plugin.CreateInRegistry(ctx, repo, auth))
  113. authEncoded, err := json.Marshal(auth)
  114. assert.NilError(t, err)
  115. rdr, err := client.PluginInstall(ctx, repo, types.PluginInstallOptions{
  116. RegistryAuth: base64.URLEncoding.EncodeToString(authEncoded),
  117. Disabled: true,
  118. RemoteRef: repo,
  119. })
  120. assert.NilError(t, err)
  121. defer rdr.Close()
  122. _, err = io.Copy(io.Discard, rdr)
  123. assert.NilError(t, err)
  124. _, _, err = client.PluginInspectWithRaw(ctx, repo)
  125. assert.NilError(t, err)
  126. })
  127. t.Run("with insecure", func(t *testing.T) {
  128. skip.If(t, !testEnv.IsLocalDaemon())
  129. ctx := testutil.StartSpan(ctx, t)
  130. addrs, err := net.InterfaceAddrs()
  131. assert.NilError(t, err)
  132. var bindTo string
  133. for _, addr := range addrs {
  134. ip, ok := addr.(*net.IPNet)
  135. if !ok {
  136. continue
  137. }
  138. if ip.IP.IsLoopback() || ip.IP.To4() == nil {
  139. continue
  140. }
  141. bindTo = ip.IP.String()
  142. }
  143. if bindTo == "" {
  144. t.Skip("No suitable interface to bind registry to")
  145. }
  146. regURL := bindTo + ":5000"
  147. d := daemon.New(t)
  148. defer d.Stop(t)
  149. d.Start(t, "--insecure-registry="+regURL)
  150. defer d.Stop(t)
  151. reg := registry.NewV2(t, registry.URL(regURL))
  152. defer reg.Close()
  153. name := "test-" + strings.ToLower(t.Name())
  154. repo := path.Join(regURL, name+":latest")
  155. assert.NilError(t, plugin.CreateInRegistry(ctx, repo, nil, plugin.WithInsecureRegistry(regURL)))
  156. client := d.NewClientT(t)
  157. rdr, err := client.PluginInstall(ctx, repo, types.PluginInstallOptions{Disabled: true, RemoteRef: repo})
  158. assert.NilError(t, err)
  159. defer rdr.Close()
  160. _, err = io.Copy(io.Discard, rdr)
  161. assert.NilError(t, err)
  162. _, _, err = client.PluginInspectWithRaw(ctx, repo)
  163. assert.NilError(t, err)
  164. })
  165. // TODO: test insecure registry with https
  166. }
  167. func TestPluginsWithRuntimes(t *testing.T) {
  168. skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
  169. skip.If(t, testEnv.IsRootless, "Test not supported on rootless due to buggy daemon setup in rootless mode due to daemon restart")
  170. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  171. ctx := testutil.StartSpan(baseContext, t)
  172. dir, err := os.MkdirTemp("", t.Name())
  173. assert.NilError(t, err)
  174. defer os.RemoveAll(dir)
  175. d := daemon.New(t)
  176. defer d.Cleanup(t)
  177. d.Start(t)
  178. defer d.Stop(t)
  179. client := d.NewClientT(t)
  180. assert.NilError(t, plugin.Create(ctx, client, "test:latest"))
  181. defer client.PluginRemove(ctx, "test:latest", types.PluginRemoveOptions{Force: true})
  182. assert.NilError(t, client.PluginEnable(ctx, "test:latest", types.PluginEnableOptions{Timeout: 30}))
  183. p := filepath.Join(dir, "myrt")
  184. script := fmt.Sprintf(`#!/bin/sh
  185. file="%s/success"
  186. if [ "$1" = "someArg" ]; then
  187. shift
  188. file="${file}_someArg"
  189. fi
  190. touch $file
  191. exec runc $@
  192. `, dir)
  193. assert.NilError(t, os.WriteFile(p, []byte(script), 0o777))
  194. type config struct {
  195. Runtimes map[string]system.Runtime `json:"runtimes"`
  196. }
  197. cfg, err := json.Marshal(config{
  198. Runtimes: map[string]system.Runtime{
  199. "myrt": {Path: p},
  200. "myrtArgs": {Path: p, Args: []string{"someArg"}},
  201. },
  202. })
  203. configPath := filepath.Join(dir, "config.json")
  204. os.WriteFile(configPath, cfg, 0o644)
  205. t.Run("No Args", func(t *testing.T) {
  206. _ = testutil.StartSpan(ctx, t)
  207. d.Restart(t, "--default-runtime=myrt", "--config-file="+configPath)
  208. _, err = os.Stat(filepath.Join(dir, "success"))
  209. assert.NilError(t, err)
  210. })
  211. t.Run("With Args", func(t *testing.T) {
  212. _ = testutil.StartSpan(ctx, t)
  213. d.Restart(t, "--default-runtime=myrtArgs", "--config-file="+configPath)
  214. _, err = os.Stat(filepath.Join(dir, "success_someArg"))
  215. assert.NilError(t, err)
  216. })
  217. }
  218. func TestPluginBackCompatMediaTypes(t *testing.T) {
  219. skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
  220. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  221. skip.If(t, testEnv.IsRootless, "Rootless has a different view of localhost (needed for test registry access)")
  222. ctx := setupTest(t)
  223. reg := registry.NewV2(t)
  224. defer reg.Close()
  225. reg.WaitReady(t)
  226. repo := path.Join(registry.DefaultURL, strings.ToLower(t.Name())+":latest")
  227. client := testEnv.APIClient()
  228. assert.NilError(t, plugin.Create(ctx, client, repo))
  229. rdr, err := client.PluginPush(ctx, repo, "")
  230. assert.NilError(t, err)
  231. defer rdr.Close()
  232. buf := &strings.Builder{}
  233. assert.NilError(t, jsonmessage.DisplayJSONMessagesStream(rdr, buf, 0, false, nil), buf)
  234. // Use custom header here because older versions of the registry do not
  235. // parse the accept header correctly and does not like the accept header
  236. // that the default resolver code uses. "Older registries" here would be
  237. // like the one currently included in the test suite.
  238. headers := http.Header{}
  239. headers.Add("Accept", images.MediaTypeDockerSchema2Manifest)
  240. resolver := docker.NewResolver(docker.ResolverOptions{
  241. Headers: headers,
  242. })
  243. assert.NilError(t, err)
  244. n, desc, err := resolver.Resolve(ctx, repo)
  245. assert.NilError(t, err, repo)
  246. fetcher, err := resolver.Fetcher(ctx, n)
  247. assert.NilError(t, err)
  248. rdr, err = fetcher.Fetch(ctx, desc)
  249. assert.NilError(t, err)
  250. defer rdr.Close()
  251. var m ocispec.Manifest
  252. assert.NilError(t, json.NewDecoder(rdr).Decode(&m))
  253. assert.Check(t, is.Equal(m.MediaType, images.MediaTypeDockerSchema2Manifest))
  254. assert.Check(t, is.Len(m.Layers, 1))
  255. assert.Check(t, is.Equal(m.Layers[0].MediaType, images.MediaTypeDockerSchema2LayerGzip))
  256. }