1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
|
//go:build !windows
// +build !windows
// TODO Windows: This uses a Unix socket for testing. This might be possible
// to port to Windows using a named pipe instead.
package authorization // import "github.com/docker/docker/pkg/authorization"
import (
"bytes"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path"
"reflect"
"strings"
"testing"
"github.com/docker/docker/pkg/plugins"
"github.com/docker/go-connections/tlsconfig"
"github.com/gorilla/mux"
)
const (
pluginAddress = "authz-test-plugin.sock"
)
func TestAuthZRequestPluginError(t *testing.T) {
server := authZPluginTestServer{t: t}
server.start()
defer server.stop()
authZPlugin := createTestPlugin(t, server.socketAddress())
request := Request{
User: "user",
RequestBody: []byte("sample body"),
RequestURI: "www.authz.com/auth",
RequestMethod: http.MethodGet,
RequestHeaders: map[string]string{"header": "value"},
}
server.replayResponse = Response{
Err: "an error",
}
actualResponse, err := authZPlugin.AuthZRequest(&request)
if err != nil {
t.Fatalf("Failed to authorize request %v", err)
}
if !reflect.DeepEqual(server.replayResponse, *actualResponse) {
t.Fatal("Response must be equal")
}
if !reflect.DeepEqual(request, server.recordedRequest) {
t.Fatal("Requests must be equal")
}
}
func TestAuthZRequestPlugin(t *testing.T) {
server := authZPluginTestServer{t: t}
server.start()
defer server.stop()
authZPlugin := createTestPlugin(t, server.socketAddress())
request := Request{
User: "user",
RequestBody: []byte("sample body"),
RequestURI: "www.authz.com/auth",
RequestMethod: http.MethodGet,
RequestHeaders: map[string]string{"header": "value"},
}
server.replayResponse = Response{
Allow: true,
Msg: "Sample message",
}
actualResponse, err := authZPlugin.AuthZRequest(&request)
if err != nil {
t.Fatalf("Failed to authorize request %v", err)
}
if !reflect.DeepEqual(server.replayResponse, *actualResponse) {
t.Fatal("Response must be equal")
}
if !reflect.DeepEqual(request, server.recordedRequest) {
t.Fatal("Requests must be equal")
}
}
func TestAuthZResponsePlugin(t *testing.T) {
server := authZPluginTestServer{t: t}
server.start()
defer server.stop()
authZPlugin := createTestPlugin(t, server.socketAddress())
request := Request{
User: "user",
RequestURI: "something.com/auth",
RequestBody: []byte("sample body"),
}
server.replayResponse = Response{
Allow: true,
Msg: "Sample message",
}
actualResponse, err := authZPlugin.AuthZResponse(&request)
if err != nil {
t.Fatalf("Failed to authorize request %v", err)
}
if !reflect.DeepEqual(server.replayResponse, *actualResponse) {
t.Fatal("Response must be equal")
}
if !reflect.DeepEqual(request, server.recordedRequest) {
t.Fatal("Requests must be equal")
}
}
func TestResponseModifier(t *testing.T) {
r := httptest.NewRecorder()
m := NewResponseModifier(r)
m.Header().Set("h1", "v1")
m.Write([]byte("body"))
m.WriteHeader(http.StatusInternalServerError)
m.FlushAll()
if r.Header().Get("h1") != "v1" {
t.Fatalf("Header value must exists %s", r.Header().Get("h1"))
}
if !reflect.DeepEqual(r.Body.Bytes(), []byte("body")) {
t.Fatalf("Body value must exists %s", r.Body.Bytes())
}
if r.Code != http.StatusInternalServerError {
t.Fatalf("Status code must be correct %d", r.Code)
}
}
func TestDrainBody(t *testing.T) {
tests := []struct {
length int // length is the message length send to drainBody
expectedBodyLength int // expectedBodyLength is the expected body length after drainBody is called
}{
{10, 10}, // Small message size
{maxBodySize - 1, maxBodySize - 1}, // Max message size
{maxBodySize * 2, 0}, // Large message size (skip copying body)
}
for _, test := range tests {
msg := strings.Repeat("a", test.length)
body, closer, err := drainBody(io.NopCloser(bytes.NewReader([]byte(msg))))
if err != nil {
t.Fatal(err)
}
if len(body) != test.expectedBodyLength {
t.Fatalf("Body must be copied, actual length: '%d'", len(body))
}
if closer == nil {
t.Fatal("Closer must not be nil")
}
modified, err := io.ReadAll(closer)
if err != nil {
t.Fatalf("Error must not be nil: '%v'", err)
}
if len(modified) != len(msg) {
t.Fatalf("Result should not be truncated. Original length: '%d', new length: '%d'", len(msg), len(modified))
}
}
}
func TestSendBody(t *testing.T) {
var (
testcases = []struct {
url string
contentType string
expected bool
}{
{
contentType: "application/json",
expected: true,
},
{
contentType: "Application/json",
expected: true,
},
{
contentType: "application/JSON",
expected: true,
},
{
contentType: "APPLICATION/JSON",
expected: true,
},
{
contentType: "application/json; charset=utf-8",
expected: true,
},
{
contentType: "application/json;charset=utf-8",
expected: true,
},
{
contentType: "application/json; charset=UTF8",
expected: true,
},
{
contentType: "application/json;charset=UTF8",
expected: true,
},
{
contentType: "text/html",
expected: false,
},
{
contentType: "",
expected: false,
},
{
url: "nothing.com/auth",
contentType: "",
expected: false,
},
{
url: "nothing.com/auth",
contentType: "application/json;charset=UTF8",
expected: false,
},
{
url: "nothing.com/auth?p1=test",
contentType: "application/json;charset=UTF8",
expected: false,
},
{
url: "nothing.com/test?p1=/auth",
contentType: "application/json;charset=UTF8",
expected: true,
},
{
url: "nothing.com/something/auth",
contentType: "application/json;charset=UTF8",
expected: true,
},
{
url: "nothing.com/auth/test",
contentType: "application/json;charset=UTF8",
expected: false,
},
{
url: "nothing.com/v1.24/auth/test",
contentType: "application/json;charset=UTF8",
expected: false,
},
{
url: "nothing.com/v1/auth/test",
contentType: "application/json;charset=UTF8",
expected: false,
},
}
)
for _, testcase := range testcases {
header := http.Header{}
header.Set("Content-Type", testcase.contentType)
if testcase.url == "" {
testcase.url = "nothing.com"
}
if b := sendBody(testcase.url, header); b != testcase.expected {
t.Fatalf("sendBody failed: url: %s, content-type: %s; Expected: %t, Actual: %t", testcase.url, testcase.contentType, testcase.expected, b)
}
}
}
func TestResponseModifierOverride(t *testing.T) {
r := httptest.NewRecorder()
m := NewResponseModifier(r)
m.Header().Set("h1", "v1")
m.Write([]byte("body"))
m.WriteHeader(http.StatusInternalServerError)
overrideHeader := make(http.Header)
overrideHeader.Add("h1", "v2")
overrideHeaderBytes, err := json.Marshal(overrideHeader)
if err != nil {
t.Fatalf("override header failed %v", err)
}
m.OverrideHeader(overrideHeaderBytes)
m.OverrideBody([]byte("override body"))
m.OverrideStatusCode(http.StatusNotFound)
m.FlushAll()
if r.Header().Get("h1") != "v2" {
t.Fatalf("Header value must exists %s", r.Header().Get("h1"))
}
if !reflect.DeepEqual(r.Body.Bytes(), []byte("override body")) {
t.Fatalf("Body value must exists %s", r.Body.Bytes())
}
if r.Code != http.StatusNotFound {
t.Fatalf("Status code must be correct %d", r.Code)
}
}
// createTestPlugin creates a new sample authorization plugin
func createTestPlugin(t *testing.T, socketAddress string) *authorizationPlugin {
client, err := plugins.NewClient("unix:///"+socketAddress, &tlsconfig.Options{InsecureSkipVerify: true})
if err != nil {
t.Fatalf("Failed to create client %v", err)
}
return &authorizationPlugin{name: "plugin", plugin: client}
}
// AuthZPluginTestServer is a simple server that implements the authZ plugin interface
type authZPluginTestServer struct {
listener net.Listener
t *testing.T
// request stores the request sent from the daemon to the plugin
recordedRequest Request
// response stores the response sent from the plugin to the daemon
replayResponse Response
server *httptest.Server
tmpDir string
}
func (t *authZPluginTestServer) socketAddress() string {
return path.Join(t.tmpDir, pluginAddress)
}
// start starts the test server that implements the plugin
func (t *authZPluginTestServer) start() {
var err error
t.tmpDir, err = os.MkdirTemp("", "authz")
if err != nil {
t.t.Fatal(err)
}
r := mux.NewRouter()
l, err := net.Listen("unix", t.socketAddress())
if err != nil {
t.t.Fatal(err)
}
t.listener = l
r.HandleFunc("/Plugin.Activate", t.activate)
r.HandleFunc("/"+AuthZApiRequest, t.auth)
r.HandleFunc("/"+AuthZApiResponse, t.auth)
t.server = &httptest.Server{
Listener: l,
Config: &http.Server{
Handler: r,
Addr: pluginAddress,
},
}
t.server.Start()
}
// stop stops the test server that implements the plugin
func (t *authZPluginTestServer) stop() {
t.server.Close()
_ = os.RemoveAll(t.tmpDir)
if t.listener != nil {
t.listener.Close()
}
}
// auth is a used to record/replay the authentication api messages
func (t *authZPluginTestServer) auth(w http.ResponseWriter, r *http.Request) {
t.recordedRequest = Request{}
body, err := io.ReadAll(r.Body)
if err != nil {
t.t.Fatal(err)
}
r.Body.Close()
json.Unmarshal(body, &t.recordedRequest)
b, err := json.Marshal(t.replayResponse)
if err != nil {
t.t.Fatal(err)
}
w.Write(b)
}
func (t *authZPluginTestServer) activate(w http.ResponseWriter, r *http.Request) {
b, err := json.Marshal(plugins.Manifest{Implements: []string{AuthZApiImplements}})
if err != nil {
t.t.Fatal(err)
}
w.Write(b)
}
|