plugin_test.go 8.0 KB

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