plugin_test.go 7.9 KB

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