authz_unix_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // +build !windows
  2. // TODO Windows: This uses a Unix socket for testing. This might be possible
  3. // to port to Windows using a named pipe instead.
  4. package authorization
  5. import (
  6. "encoding/json"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "path"
  13. "reflect"
  14. "testing"
  15. "bytes"
  16. "strings"
  17. "github.com/docker/docker/pkg/plugins"
  18. "github.com/docker/go-connections/tlsconfig"
  19. "github.com/gorilla/mux"
  20. )
  21. const pluginAddress = "authzplugin.sock"
  22. func TestAuthZRequestPluginError(t *testing.T) {
  23. server := authZPluginTestServer{t: t}
  24. go server.start()
  25. defer server.stop()
  26. authZPlugin := createTestPlugin(t)
  27. request := Request{
  28. User: "user",
  29. RequestBody: []byte("sample body"),
  30. RequestURI: "www.authz.com",
  31. RequestMethod: "GET",
  32. RequestHeaders: map[string]string{"header": "value"},
  33. }
  34. server.replayResponse = Response{
  35. Err: "an error",
  36. }
  37. actualResponse, err := authZPlugin.AuthZRequest(&request)
  38. if err != nil {
  39. t.Fatalf("Failed to authorize request %v", err)
  40. }
  41. if !reflect.DeepEqual(server.replayResponse, *actualResponse) {
  42. t.Fatalf("Response must be equal")
  43. }
  44. if !reflect.DeepEqual(request, server.recordedRequest) {
  45. t.Fatalf("Requests must be equal")
  46. }
  47. }
  48. func TestAuthZRequestPlugin(t *testing.T) {
  49. server := authZPluginTestServer{t: t}
  50. go server.start()
  51. defer server.stop()
  52. authZPlugin := createTestPlugin(t)
  53. request := Request{
  54. User: "user",
  55. RequestBody: []byte("sample body"),
  56. RequestURI: "www.authz.com",
  57. RequestMethod: "GET",
  58. RequestHeaders: map[string]string{"header": "value"},
  59. }
  60. server.replayResponse = Response{
  61. Allow: true,
  62. Msg: "Sample message",
  63. }
  64. actualResponse, err := authZPlugin.AuthZRequest(&request)
  65. if err != nil {
  66. t.Fatalf("Failed to authorize request %v", err)
  67. }
  68. if !reflect.DeepEqual(server.replayResponse, *actualResponse) {
  69. t.Fatalf("Response must be equal")
  70. }
  71. if !reflect.DeepEqual(request, server.recordedRequest) {
  72. t.Fatalf("Requests must be equal")
  73. }
  74. }
  75. func TestAuthZResponsePlugin(t *testing.T) {
  76. server := authZPluginTestServer{t: t}
  77. go server.start()
  78. defer server.stop()
  79. authZPlugin := createTestPlugin(t)
  80. request := Request{
  81. User: "user",
  82. RequestBody: []byte("sample body"),
  83. }
  84. server.replayResponse = Response{
  85. Allow: true,
  86. Msg: "Sample message",
  87. }
  88. actualResponse, err := authZPlugin.AuthZResponse(&request)
  89. if err != nil {
  90. t.Fatalf("Failed to authorize request %v", err)
  91. }
  92. if !reflect.DeepEqual(server.replayResponse, *actualResponse) {
  93. t.Fatalf("Response must be equal")
  94. }
  95. if !reflect.DeepEqual(request, server.recordedRequest) {
  96. t.Fatalf("Requests must be equal")
  97. }
  98. }
  99. func TestResponseModifier(t *testing.T) {
  100. r := httptest.NewRecorder()
  101. m := NewResponseModifier(r)
  102. m.Header().Set("h1", "v1")
  103. m.Write([]byte("body"))
  104. m.WriteHeader(500)
  105. m.FlushAll()
  106. if r.Header().Get("h1") != "v1" {
  107. t.Fatalf("Header value must exists %s", r.Header().Get("h1"))
  108. }
  109. if !reflect.DeepEqual(r.Body.Bytes(), []byte("body")) {
  110. t.Fatalf("Body value must exists %s", r.Body.Bytes())
  111. }
  112. if r.Code != 500 {
  113. t.Fatalf("Status code must be correct %d", r.Code)
  114. }
  115. }
  116. func TestDrainBody(t *testing.T) {
  117. tests := []struct {
  118. length int // length is the message length send to drainBody
  119. expectedBodyLength int // expectedBodyLength is the expected body length after drainBody is called
  120. }{
  121. {10, 10}, // Small message size
  122. {maxBodySize - 1, maxBodySize - 1}, // Max message size
  123. {maxBodySize * 2, 0}, // Large message size (skip copying body)
  124. }
  125. for _, test := range tests {
  126. msg := strings.Repeat("a", test.length)
  127. body, closer, err := drainBody(ioutil.NopCloser(bytes.NewReader([]byte(msg))))
  128. if err != nil {
  129. t.Fatal(err)
  130. }
  131. if len(body) != test.expectedBodyLength {
  132. t.Fatalf("Body must be copied, actual length: '%d'", len(body))
  133. }
  134. if closer == nil {
  135. t.Fatalf("Closer must not be nil")
  136. }
  137. modified, err := ioutil.ReadAll(closer)
  138. if err != nil {
  139. t.Fatalf("Error must not be nil: '%v'", err)
  140. }
  141. if len(modified) != len(msg) {
  142. t.Fatalf("Result should not be truncated. Original length: '%d', new length: '%d'", len(msg), len(modified))
  143. }
  144. }
  145. }
  146. func TestResponseModifierOverride(t *testing.T) {
  147. r := httptest.NewRecorder()
  148. m := NewResponseModifier(r)
  149. m.Header().Set("h1", "v1")
  150. m.Write([]byte("body"))
  151. m.WriteHeader(500)
  152. overrideHeader := make(http.Header)
  153. overrideHeader.Add("h1", "v2")
  154. overrideHeaderBytes, err := json.Marshal(overrideHeader)
  155. if err != nil {
  156. t.Fatalf("override header failed %v", err)
  157. }
  158. m.OverrideHeader(overrideHeaderBytes)
  159. m.OverrideBody([]byte("override body"))
  160. m.OverrideStatusCode(404)
  161. m.FlushAll()
  162. if r.Header().Get("h1") != "v2" {
  163. t.Fatalf("Header value must exists %s", r.Header().Get("h1"))
  164. }
  165. if !reflect.DeepEqual(r.Body.Bytes(), []byte("override body")) {
  166. t.Fatalf("Body value must exists %s", r.Body.Bytes())
  167. }
  168. if r.Code != 404 {
  169. t.Fatalf("Status code must be correct %d", r.Code)
  170. }
  171. }
  172. // createTestPlugin creates a new sample authorization plugin
  173. func createTestPlugin(t *testing.T) *authorizationPlugin {
  174. plugin := &plugins.Plugin{Name: "authz"}
  175. pwd, err := os.Getwd()
  176. if err != nil {
  177. t.Fatal(err)
  178. }
  179. plugin.Client, err = plugins.NewClient("unix:///"+path.Join(pwd, pluginAddress), tlsconfig.Options{InsecureSkipVerify: true})
  180. if err != nil {
  181. t.Fatalf("Failed to create client %v", err)
  182. }
  183. return &authorizationPlugin{name: "plugin", plugin: plugin}
  184. }
  185. // AuthZPluginTestServer is a simple server that implements the authZ plugin interface
  186. type authZPluginTestServer struct {
  187. listener net.Listener
  188. t *testing.T
  189. // request stores the request sent from the daemon to the plugin
  190. recordedRequest Request
  191. // response stores the response sent from the plugin to the daemon
  192. replayResponse Response
  193. }
  194. // start starts the test server that implements the plugin
  195. func (t *authZPluginTestServer) start() {
  196. r := mux.NewRouter()
  197. os.Remove(pluginAddress)
  198. l, _ := net.ListenUnix("unix", &net.UnixAddr{Name: pluginAddress, Net: "unix"})
  199. t.listener = l
  200. r.HandleFunc("/Plugin.Activate", t.activate)
  201. r.HandleFunc("/"+AuthZApiRequest, t.auth)
  202. r.HandleFunc("/"+AuthZApiResponse, t.auth)
  203. server := http.Server{Handler: r, Addr: pluginAddress}
  204. server.Serve(l)
  205. }
  206. // stop stops the test server that implements the plugin
  207. func (t *authZPluginTestServer) stop() {
  208. os.Remove(pluginAddress)
  209. if t.listener != nil {
  210. t.listener.Close()
  211. }
  212. }
  213. // auth is a used to record/replay the authentication api messages
  214. func (t *authZPluginTestServer) auth(w http.ResponseWriter, r *http.Request) {
  215. t.recordedRequest = Request{}
  216. body, _ := ioutil.ReadAll(r.Body)
  217. r.Body.Close()
  218. json.Unmarshal(body, &t.recordedRequest)
  219. b, _ := json.Marshal(t.replayResponse)
  220. w.Write(b)
  221. }
  222. func (t *authZPluginTestServer) activate(w http.ResponseWriter, r *http.Request) {
  223. b, _ := json.Marshal(plugins.Manifest{Implements: []string{AuthZApiImplements}})
  224. w.Write(b)
  225. }