plugin_test.go 10 KB

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