docker_cli_authz_unix_test.go 15 KB

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