docker_cli_authz_unix_test.go 14 KB

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