docker_cli_authz_unix_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. // +build !windows
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "bufio"
  13. "bytes"
  14. "os/exec"
  15. "strconv"
  16. "time"
  17. "net"
  18. "net/http/httputil"
  19. "net/url"
  20. "github.com/docker/docker/integration-cli/checker"
  21. "github.com/docker/docker/integration-cli/daemon"
  22. "github.com/docker/docker/pkg/authorization"
  23. "github.com/docker/docker/pkg/plugins"
  24. "github.com/go-check/check"
  25. )
  26. const (
  27. testAuthZPlugin = "authzplugin"
  28. unauthorizedMessage = "User unauthorized authz plugin"
  29. errorMessage = "something went wrong..."
  30. containerListAPI = "/containers/json"
  31. )
  32. var (
  33. alwaysAllowed = []string{"/_ping", "/info"}
  34. )
  35. func init() {
  36. check.Suite(&DockerAuthzSuite{
  37. ds: &DockerSuite{},
  38. })
  39. }
  40. type DockerAuthzSuite struct {
  41. server *httptest.Server
  42. ds *DockerSuite
  43. d *daemon.Daemon
  44. ctrl *authorizationController
  45. }
  46. type authorizationController struct {
  47. reqRes authorization.Response // reqRes holds the plugin response to the initial client request
  48. resRes authorization.Response // resRes holds the plugin response to the daemon response
  49. psRequestCnt int // psRequestCnt counts the number of calls to list container request api
  50. psResponseCnt int // psResponseCnt counts the number of calls to list containers response API
  51. requestsURIs []string // requestsURIs stores all request URIs that are sent to the authorization controller
  52. reqUser string
  53. resUser string
  54. }
  55. func (s *DockerAuthzSuite) SetUpTest(c *check.C) {
  56. s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
  57. Experimental: testEnv.ExperimentalDaemon(),
  58. })
  59. s.ctrl = &authorizationController{}
  60. }
  61. func (s *DockerAuthzSuite) TearDownTest(c *check.C) {
  62. if s.d != nil {
  63. s.d.Stop(c)
  64. s.ds.TearDownTest(c)
  65. s.ctrl = nil
  66. }
  67. }
  68. func (s *DockerAuthzSuite) SetUpSuite(c *check.C) {
  69. mux := http.NewServeMux()
  70. s.server = httptest.NewServer(mux)
  71. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  72. b, err := json.Marshal(plugins.Manifest{Implements: []string{authorization.AuthZApiImplements}})
  73. c.Assert(err, check.IsNil)
  74. w.Write(b)
  75. })
  76. mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) {
  77. defer r.Body.Close()
  78. body, err := ioutil.ReadAll(r.Body)
  79. c.Assert(err, check.IsNil)
  80. authReq := authorization.Request{}
  81. err = json.Unmarshal(body, &authReq)
  82. c.Assert(err, check.IsNil)
  83. assertBody(c, authReq.RequestURI, authReq.RequestHeaders, authReq.RequestBody)
  84. assertAuthHeaders(c, authReq.RequestHeaders)
  85. // Count only container list api
  86. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  87. s.ctrl.psRequestCnt++
  88. }
  89. s.ctrl.requestsURIs = append(s.ctrl.requestsURIs, authReq.RequestURI)
  90. reqRes := s.ctrl.reqRes
  91. if isAllowed(authReq.RequestURI) {
  92. reqRes = authorization.Response{Allow: true}
  93. }
  94. if reqRes.Err != "" {
  95. w.WriteHeader(http.StatusInternalServerError)
  96. }
  97. b, err := json.Marshal(reqRes)
  98. c.Assert(err, check.IsNil)
  99. s.ctrl.reqUser = authReq.User
  100. w.Write(b)
  101. })
  102. mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) {
  103. defer r.Body.Close()
  104. body, err := ioutil.ReadAll(r.Body)
  105. c.Assert(err, check.IsNil)
  106. authReq := authorization.Request{}
  107. err = json.Unmarshal(body, &authReq)
  108. c.Assert(err, check.IsNil)
  109. assertBody(c, authReq.RequestURI, authReq.ResponseHeaders, authReq.ResponseBody)
  110. assertAuthHeaders(c, authReq.ResponseHeaders)
  111. // Count only container list api
  112. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  113. s.ctrl.psResponseCnt++
  114. }
  115. resRes := s.ctrl.resRes
  116. if isAllowed(authReq.RequestURI) {
  117. resRes = authorization.Response{Allow: true}
  118. }
  119. if resRes.Err != "" {
  120. w.WriteHeader(http.StatusInternalServerError)
  121. }
  122. b, err := json.Marshal(resRes)
  123. c.Assert(err, check.IsNil)
  124. s.ctrl.resUser = authReq.User
  125. w.Write(b)
  126. })
  127. err := os.MkdirAll("/etc/docker/plugins", 0755)
  128. c.Assert(err, checker.IsNil)
  129. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", testAuthZPlugin)
  130. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  131. c.Assert(err, checker.IsNil)
  132. }
  133. // check for always allowed endpoints to not inhibit test framework functions
  134. func isAllowed(reqURI string) bool {
  135. for _, endpoint := range alwaysAllowed {
  136. if strings.HasSuffix(reqURI, endpoint) {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. // assertAuthHeaders validates authentication headers are removed
  143. func assertAuthHeaders(c *check.C, headers map[string]string) error {
  144. for k := range headers {
  145. if strings.Contains(strings.ToLower(k), "auth") || strings.Contains(strings.ToLower(k), "x-registry") {
  146. c.Errorf("Found authentication headers in request '%v'", headers)
  147. }
  148. }
  149. return nil
  150. }
  151. // assertBody asserts that body is removed for non text/json requests
  152. func assertBody(c *check.C, requestURI string, headers map[string]string, body []byte) {
  153. if strings.Contains(strings.ToLower(requestURI), "auth") && len(body) > 0 {
  154. //return fmt.Errorf("Body included for authentication endpoint %s", string(body))
  155. c.Errorf("Body included for authentication endpoint %s", string(body))
  156. }
  157. for k, v := range headers {
  158. if strings.EqualFold(k, "Content-Type") && strings.HasPrefix(v, "text/") || v == "application/json" {
  159. return
  160. }
  161. }
  162. if len(body) > 0 {
  163. c.Errorf("Body included while it should not (Headers: '%v')", headers)
  164. }
  165. }
  166. func (s *DockerAuthzSuite) TearDownSuite(c *check.C) {
  167. if s.server == nil {
  168. return
  169. }
  170. s.server.Close()
  171. err := os.RemoveAll("/etc/docker/plugins")
  172. c.Assert(err, checker.IsNil)
  173. }
  174. func (s *DockerAuthzSuite) TestAuthZPluginAllowRequest(c *check.C) {
  175. // start the daemon and load busybox, --net=none build fails otherwise
  176. // cause it needs to pull busybox
  177. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  178. s.ctrl.reqRes.Allow = true
  179. s.ctrl.resRes.Allow = true
  180. s.d.LoadBusybox(c)
  181. // Ensure command successful
  182. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  183. c.Assert(err, check.IsNil)
  184. id := strings.TrimSpace(out)
  185. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  186. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  187. }
  188. func (s *DockerAuthzSuite) TestAuthZPluginTls(c *check.C) {
  189. const testDaemonHTTPSAddr = "tcp://localhost:4271"
  190. // start the daemon and load busybox, --net=none build fails otherwise
  191. // cause it needs to pull busybox
  192. s.d.Start(c,
  193. "--authorization-plugin="+testAuthZPlugin,
  194. "--tlsverify",
  195. "--tlscacert",
  196. "fixtures/https/ca.pem",
  197. "--tlscert",
  198. "fixtures/https/server-cert.pem",
  199. "--tlskey",
  200. "fixtures/https/server-key.pem",
  201. "-H", testDaemonHTTPSAddr)
  202. s.ctrl.reqRes.Allow = true
  203. s.ctrl.resRes.Allow = true
  204. out, _ := dockerCmd(
  205. c,
  206. "--tlsverify",
  207. "--tlscacert", "fixtures/https/ca.pem",
  208. "--tlscert", "fixtures/https/client-cert.pem",
  209. "--tlskey", "fixtures/https/client-key.pem",
  210. "-H",
  211. testDaemonHTTPSAddr,
  212. "version",
  213. )
  214. if !strings.Contains(out, "Server") {
  215. c.Fatalf("docker version should return information of server side")
  216. }
  217. c.Assert(s.ctrl.reqUser, check.Equals, "client")
  218. c.Assert(s.ctrl.resUser, check.Equals, "client")
  219. }
  220. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  221. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  222. s.ctrl.reqRes.Allow = false
  223. s.ctrl.reqRes.Msg = unauthorizedMessage
  224. // Ensure command is blocked
  225. res, err := s.d.Cmd("ps")
  226. c.Assert(err, check.NotNil)
  227. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  228. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  229. // Ensure unauthorized message appears in response
  230. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  231. }
  232. // TestAuthZPluginAPIDenyResponse validates that when authorization plugin deny the request, the status code is forbidden
  233. func (s *DockerAuthzSuite) TestAuthZPluginAPIDenyResponse(c *check.C) {
  234. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  235. s.ctrl.reqRes.Allow = false
  236. s.ctrl.resRes.Msg = unauthorizedMessage
  237. daemonURL, err := url.Parse(s.d.Sock())
  238. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  239. c.Assert(err, check.IsNil)
  240. client := httputil.NewClientConn(conn, nil)
  241. req, err := http.NewRequest("GET", "/version", nil)
  242. c.Assert(err, check.IsNil)
  243. resp, err := client.Do(req)
  244. c.Assert(err, check.IsNil)
  245. c.Assert(resp.StatusCode, checker.Equals, http.StatusForbidden)
  246. c.Assert(err, checker.IsNil)
  247. }
  248. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  249. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  250. s.ctrl.reqRes.Allow = true
  251. s.ctrl.resRes.Allow = false
  252. s.ctrl.resRes.Msg = unauthorizedMessage
  253. // Ensure command is blocked
  254. res, err := s.d.Cmd("ps")
  255. c.Assert(err, check.NotNil)
  256. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  257. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  258. // Ensure unauthorized message appears in response
  259. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  260. }
  261. // TestAuthZPluginAllowEventStream verifies event stream propagates correctly after request pass through by the authorization plugin
  262. func (s *DockerAuthzSuite) TestAuthZPluginAllowEventStream(c *check.C) {
  263. testRequires(c, DaemonIsLinux)
  264. // start the daemon and load busybox to avoid pulling busybox from Docker Hub
  265. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  266. s.ctrl.reqRes.Allow = true
  267. s.ctrl.resRes.Allow = true
  268. s.d.LoadBusybox(c)
  269. startTime := strconv.FormatInt(daemonTime(c).Unix(), 10)
  270. // Add another command to to enable event pipelining
  271. eventsCmd := exec.Command(dockerBinary, "--host", s.d.Sock(), "events", "--since", startTime)
  272. stdout, err := eventsCmd.StdoutPipe()
  273. if err != nil {
  274. c.Assert(err, check.IsNil)
  275. }
  276. observer := eventObserver{
  277. buffer: new(bytes.Buffer),
  278. command: eventsCmd,
  279. scanner: bufio.NewScanner(stdout),
  280. startTime: startTime,
  281. }
  282. err = observer.Start()
  283. c.Assert(err, checker.IsNil)
  284. defer observer.Stop()
  285. // Create a container and wait for the creation events
  286. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  287. c.Assert(err, check.IsNil, check.Commentf(out))
  288. containerID := strings.TrimSpace(out)
  289. c.Assert(s.d.WaitRun(containerID), checker.IsNil)
  290. events := map[string]chan bool{
  291. "create": make(chan bool, 1),
  292. "start": make(chan bool, 1),
  293. }
  294. matcher := matchEventLine(containerID, "container", events)
  295. processor := processEventMatch(events)
  296. go observer.Match(matcher, processor)
  297. // Ensure all events are received
  298. for event, eventChannel := range events {
  299. select {
  300. case <-time.After(30 * time.Second):
  301. // Fail the test
  302. observer.CheckEventError(c, containerID, event, matcher)
  303. c.FailNow()
  304. case <-eventChannel:
  305. // Ignore, event received
  306. }
  307. }
  308. // Ensure both events and container endpoints are passed to the authorization plugin
  309. assertURIRecorded(c, s.ctrl.requestsURIs, "/events")
  310. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  311. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", containerID))
  312. }
  313. func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) {
  314. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  315. s.ctrl.reqRes.Allow = true
  316. s.ctrl.resRes.Err = errorMessage
  317. // Ensure command is blocked
  318. res, err := s.d.Cmd("ps")
  319. c.Assert(err, check.NotNil)
  320. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  321. }
  322. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  323. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  324. s.ctrl.reqRes.Err = errorMessage
  325. // Ensure command is blocked
  326. res, err := s.d.Cmd("ps")
  327. c.Assert(err, check.NotNil)
  328. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  329. }
  330. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  331. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin)
  332. s.ctrl.reqRes.Allow = true
  333. s.ctrl.resRes.Allow = true
  334. out, err := s.d.Cmd("ps")
  335. c.Assert(err, check.IsNil, check.Commentf(out))
  336. // assert plugin is only called once..
  337. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  338. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  339. }
  340. func (s *DockerAuthzSuite) TestAuthZPluginEnsureLoadImportWorking(c *check.C) {
  341. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin)
  342. s.ctrl.reqRes.Allow = true
  343. s.ctrl.resRes.Allow = true
  344. s.d.LoadBusybox(c)
  345. tmp, err := ioutil.TempDir("", "test-authz-load-import")
  346. c.Assert(err, check.IsNil)
  347. defer os.RemoveAll(tmp)
  348. savedImagePath := filepath.Join(tmp, "save.tar")
  349. out, err := s.d.Cmd("save", "-o", savedImagePath, "busybox")
  350. c.Assert(err, check.IsNil, check.Commentf(out))
  351. out, err = s.d.Cmd("load", "--input", savedImagePath)
  352. c.Assert(err, check.IsNil, check.Commentf(out))
  353. exportedImagePath := filepath.Join(tmp, "export.tar")
  354. out, err = s.d.Cmd("run", "-d", "--name", "testexport", "busybox")
  355. c.Assert(err, check.IsNil, check.Commentf(out))
  356. out, err = s.d.Cmd("export", "-o", exportedImagePath, "testexport")
  357. c.Assert(err, check.IsNil, check.Commentf(out))
  358. out, err = s.d.Cmd("import", exportedImagePath)
  359. c.Assert(err, check.IsNil, check.Commentf(out))
  360. }
  361. func (s *DockerAuthzSuite) TestAuthZPluginHeader(c *check.C) {
  362. s.d.Start(c, "--debug", "--authorization-plugin="+testAuthZPlugin)
  363. s.ctrl.reqRes.Allow = true
  364. s.ctrl.resRes.Allow = true
  365. s.d.LoadBusybox(c)
  366. daemonURL, err := url.Parse(s.d.Sock())
  367. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  368. c.Assert(err, check.IsNil)
  369. client := httputil.NewClientConn(conn, nil)
  370. req, err := http.NewRequest("GET", "/version", nil)
  371. c.Assert(err, check.IsNil)
  372. resp, err := client.Do(req)
  373. c.Assert(err, check.IsNil)
  374. c.Assert(resp.Header["Content-Type"][0], checker.Equals, "application/json")
  375. }
  376. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  377. func assertURIRecorded(c *check.C, uris []string, uri string) {
  378. var found bool
  379. for _, u := range uris {
  380. if strings.Contains(u, uri) {
  381. found = true
  382. break
  383. }
  384. }
  385. if !found {
  386. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  387. }
  388. }