Esempio n. 1
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `expvar`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	c = caddy.NewTestController("http", `expvar /d/v`)
	err = setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids = httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(ExpVar)
	if !ok {
		t.Fatalf("Expected handler to be type ExpVar, got: %#v", handler)
	}
	if myHandler.Resource != "/d/v" {
		t.Errorf("Expected /d/v as expvar resource")
	}
	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}
}
Esempio n. 2
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `mime .txt text/plain`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, but got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, but had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Mime)
	if !ok {
		t.Fatalf("Expected handler to be type Mime, got: %#v", handler)
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	tests := []struct {
		input     string
		shouldErr bool
	}{
		{`mime {`, true},
		{`mime {}`, true},
		{`mime a b`, true},
		{`mime a {`, true},
		{`mime { txt f } `, true},
		{`mime { html } `, true},
		{`mime {
		 .html text/html
		 .txt text/plain
		} `, false},
		{`mime {
		 .foo text/foo
		 .bar text/bar
		 .foo text/foobar
		} `, true},
		{`mime { .html text/html } `, false},
		{`mime { .html
		} `, true},
		{`mime .txt text/plain`, false},
	}
	for i, test := range tests {
		m, err := mimeParse(caddy.NewTestController("http", test.input))
		if test.shouldErr && err == nil {
			t.Errorf("Test %v: Expected error but found nil %v", i, m)
		} else if !test.shouldErr && err != nil {
			t.Errorf("Test %v: Expected no error but found error: %v", i, err)
		}
	}
}
Esempio n. 3
0
func TestSetupParseWithWrongOptionalParams(t *testing.T) {
	// Test protocols wrong params
	params := `tls ` + certFile + ` ` + keyFile + ` {
			protocols ssl tls
		}`
	cfg := new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c := caddy.NewTestController("", params)
	err := setupTLS(c)
	if err == nil {
		t.Errorf("Expected errors, but no error returned")
	}

	// Test ciphers wrong params
	params = `tls ` + certFile + ` ` + keyFile + ` {
			ciphers not-valid-cipher
		}`
	cfg = new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c = caddy.NewTestController("", params)
	err = setupTLS(c)
	if err == nil {
		t.Errorf("Expected errors, but no error returned")
	}

	// Test key_type wrong params
	params = `tls {
			key_type ab123
		}`
	cfg = new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c = caddy.NewTestController("", params)
	err = setupTLS(c)
	if err == nil {
		t.Errorf("Expected errors, but no error returned")
	}

	// Test curves wrong params
	params = `tls {
			curves ab123, cd456, ef789
		}`
	cfg = new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c = caddy.NewTestController("", params)
	err = setupTLS(c)
	if err == nil {
		t.Errorf("Expected errors, but no error returned")
	}
}
Esempio n. 4
0
func TestSetup(t *testing.T) {
	err := setup(caddy.NewTestController(`errors`))
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig("").Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middlewares, was nil instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(*ErrorHandler)
	if !ok {
		t.Fatalf("Expected handler to be type ErrorHandler, got: %#v", handler)
	}

	if myHandler.LogFile != "" {
		t.Errorf("Expected '%s' as the default LogFile", "")
	}
	if myHandler.LogRoller != nil {
		t.Errorf("Expected LogRoller to be nil, got: %v", *myHandler.LogRoller)
	}
	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	// Test Startup function -- TODO
	// if len(c.Startup) == 0 {
	// 	t.Fatal("Expected 1 startup function, had 0")
	// }
	// c.Startup[0]()
	// if myHandler.Log == nil {
	// 	t.Error("Expected Log to be non-nil after startup because Debug is not enabled")
	// }
}
Esempio n. 5
0
func TestSetup(t *testing.T) {
	err := setup(caddy.NewTestController(`templates`))
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig("").Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Templates)

	if !ok {
		t.Fatalf("Expected handler to be type Templates, got: %#v", handler)
	}

	if myHandler.Rules[0].Path != defaultTemplatePath {
		t.Errorf("Expected / as the default Path")
	}
	if fmt.Sprint(myHandler.Rules[0].Extensions) != fmt.Sprint(defaultTemplateExtensions) {
		t.Errorf("Expected %v to be the Default Extensions", defaultTemplateExtensions)
	}
	var indexFiles []string
	for _, extension := range defaultTemplateExtensions {
		indexFiles = append(indexFiles, "index"+extension)
	}
	if fmt.Sprint(myHandler.Rules[0].IndexFiles) != fmt.Sprint(indexFiles) {
		t.Errorf("Expected %v to be the Default Index files", indexFiles)
	}
	if myHandler.Rules[0].Delims != [2]string{} {
		t.Errorf("Expected %v to be the Default Delims", [2]string{})
	}
}
Esempio n. 6
0
func TestSetupMaxRequestBody(t *testing.T) {
	cases := []struct {
		input    string
		hasError bool
	}{
		// Format: { <path> <limit> ... }
		{input: "maxrequestbody / 20MB", hasError: false},
		// Format: <limit>
		{input: "maxrequestbody 999KB", hasError: false},
		// Format: { <path> <limit> ... }
		{input: "maxrequestbody { /images 50MB /upload 10MB\n/test 10KB }", hasError: false},

		// Wrong formats
		{input: "maxrequestbody typo { /images 50MB }", hasError: true},
		{input: "maxrequestbody 999MB /home 20KB", hasError: true},
	}
	for caseNum, c := range cases {
		controller := caddy.NewTestController("", c.input)
		err := setupMaxRequestBody(controller)

		if c.hasError && (err == nil) {
			t.Errorf("Expecting error for case %v but none encountered", caseNum)
		}
		if !c.hasError && (err != nil) {
			t.Errorf("Expecting no error for case %v but encountered %v", caseNum, err)
		}
	}
}
Esempio n. 7
0
func TestExtParse(t *testing.T) {
	tests := []struct {
		inputExts    string
		shouldErr    bool
		expectedExts []string
	}{
		{`ext .html .htm .php`, false, []string{".html", ".htm", ".php"}},
		{`ext .php .html .xml`, false, []string{".php", ".html", ".xml"}},
		{`ext .txt .php .xml`, false, []string{".txt", ".php", ".xml"}},
	}
	for i, test := range tests {
		actualExts, err := extParse(caddy.NewTestController("http", test.inputExts))

		if err == nil && test.shouldErr {
			t.Errorf("Test %d didn't error, but it should have", i)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
		}

		if len(actualExts) != len(test.expectedExts) {
			t.Fatalf("Test %d expected %d rules, but got %d",
				i, len(test.expectedExts), len(actualExts))
		}
		for j, actualExt := range actualExts {
			if actualExt != test.expectedExts[j] {
				t.Fatalf("Test %d expected %dth extension to be  %s  , but got %s",
					i, j, test.expectedExts[j], actualExt)
			}
		}
	}

}
Esempio n. 8
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `fastcgi / 127.0.0.1:9000`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Handler)

	if !ok {
		t.Fatalf("Expected handler to be type , got: %#v", handler)
	}

	if myHandler.Rules[0].Path != "/" {
		t.Errorf("Expected / as the Path")
	}
	if myHandler.Rules[0].Address != "127.0.0.1:9000" {
		t.Errorf("Expected 127.0.0.1:9000 as the Address")
	}

}
Esempio n. 9
0
func TestSetupParseWithCurves(t *testing.T) {
	params := `tls {
            curves p256 p384 p521
        }`
	cfg := new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c := caddy.NewTestController("", params)

	err := setupTLS(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}

	if len(cfg.CurvePreferences) != 3 {
		t.Errorf("Expected 3 curves, got %v", len(cfg.CurvePreferences))
	}

	expectedCurves := []tls.CurveID{tls.CurveP256, tls.CurveP384, tls.CurveP521}

	// Ensure ordering is correct
	for i, actual := range cfg.CurvePreferences {
		if actual != expectedCurves[i] {
			t.Errorf("Expected curve in position %d to be %v, got %v", i, expectedCurves[i], actual)
		}
	}
}
Esempio n. 10
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `rewrite /from /to`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, but got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Rewrite)
	if !ok {
		t.Fatalf("Expected handler to be type Rewrite, got: %#v", handler)
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	if len(myHandler.Rules) != 1 {
		t.Errorf("Expected handler to have %d rule, has %d instead", 1, len(myHandler.Rules))
	}
}
Esempio n. 11
0
func TestConfigLoadPGPKeyHDD(t *testing.T) {

	tests := []struct {
		config    string
		expectErr error
		keyNil    bool
	}{
		{
			`mailout`,
			nil,
			true,
		},
		{
			`mailout {
				[email protected] testdata/B06469EE_nopw.pub.asc
			}`,
			nil,
			false,
		},
		{
			`mailout {
				[email protected] testdata/B06469EE_nopw.priv.asc
			}`,
			errors.New("Cannot load PGP key for email address \"[email protected]\" with error: PrivateKey found. Not allowed. Please remove it from resouce: \"testdata/B06469EE_nopw.priv.asc\""),
			true,
		},
		{
			`mailout {
				[email protected] xhttp://keybase.io/cyrill/key.asc
			}`,
			errors.New("Cannot load PGP key for email address \"[email protected]\" with error: File \"xhttp://keybase.io/cyrill/key.asc\" not found"),
			true,
		},
	}
	for i, test := range tests {

		c := caddy.NewTestController("http", test.config)
		mc, err := parse(c)
		if err != nil {
			t.Fatal("Index", i, "Error:", err)
		}

		err = mc.loadPGPKeys()
		if test.keyNil && test.expectErr == nil {
			assert.NoError(t, err, "Index %d", i)
			assert.Empty(t, mc.pgpEmailKeyEntities, "Index %d", i)
			continue
		}

		if test.expectErr != nil {
			assert.Empty(t, mc.pgpEmailKeyEntities, "Index %d", i)
			assert.EqualError(t, err, test.expectErr.Error(), "Index %d", i)
			continue
		}
		assert.NoError(t, err, "Index %d", i)
		assert.NotNil(t, mc.pgpEmailKeyEntities, "Index %d", i)
		assert.NotNil(t, mc.pgpEmailKeyEntities["*****@*****.**"].PrimaryKey, "Index %d", i)
		assert.Nil(t, mc.pgpEmailKeyEntities["*****@*****.**"].PrivateKey, "Index %d", i)
	}
}
Esempio n. 12
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `markdown /blog`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Markdown)

	if !ok {
		t.Fatalf("Expected handler to be type Markdown, got: %#v", handler)
	}

	if myHandler.Configs[0].PathScope != "/blog" {
		t.Errorf("Expected /blog as the Path Scope")
	}
	if len(myHandler.Configs[0].Extensions) != 3 {
		t.Error("Expected 3 markdown extensions")
	}
	for _, key := range []string{".md", ".markdown", ".mdown"} {
		if ext, ok := myHandler.Configs[0].Extensions[key]; !ok {
			t.Errorf("Expected extensions to contain %v", ext)
		}
	}
}
Esempio n. 13
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `ext .html .htm .php`)
	err := setup(c)
	if err != nil {
		t.Fatalf("Expected no errors, got: %v", err)
	}

	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Ext)

	if !ok {
		t.Fatalf("Expected handler to be type Ext, got: %#v", handler)
	}

	if myHandler.Extensions[0] != ".html" {
		t.Errorf("Expected .html in the list of Extensions")
	}
	if myHandler.Extensions[1] != ".htm" {
		t.Errorf("Expected .htm in the list of Extensions")
	}
	if myHandler.Extensions[2] != ".php" {
		t.Errorf("Expected .php in the list of Extensions")
	}
	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

}
Esempio n. 14
0
func TestSetup(t *testing.T) {

	for j, test := range []struct {
		input         string
		shouldErr     bool
		expectedRules []Rule
	}{
		// test case #0 tests the recognition of a valid HTTP status code defined outside of block statement
		{"redir 300 {\n/ /foo\n}", false, []Rule{{FromPath: "/", To: "/foo", Code: 300}}},

		// test case #1 tests the recognition of an invalid HTTP status code defined outside of block statement
		{"redir 9000 {\n/ /foo\n}", true, []Rule{{}}},

		// test case #2 tests the detection of a valid HTTP status code outside of a block statement being overriden by an invalid HTTP status code inside statement of a block statement
		{"redir 300 {\n/ /foo 9000\n}", true, []Rule{{}}},

		// test case #3 tests the detection of an invalid HTTP status code outside of a block statement being overriden by a valid HTTP status code inside statement of a block statement
		{"redir 9000 {\n/ /foo 300\n}", true, []Rule{{}}},

		// test case #4 tests the recognition of a TO redirection in a block statement.The HTTP status code is set to the default of 301 - MovedPermanently
		{"redir 302 {\n/foo\n}", false, []Rule{{FromPath: "/", To: "/foo", Code: 302}}},

		// test case #5 tests the recognition of a TO and From redirection in a block statement
		{"redir {\n/bar /foo 303\n}", false, []Rule{{FromPath: "/bar", To: "/foo", Code: 303}}},

		// test case #6 tests the recognition of a TO redirection in a non-block statement. The HTTP status code is set to the default of 301 - MovedPermanently
		{"redir /foo", false, []Rule{{FromPath: "/", To: "/foo", Code: 301}}},

		// test case #7 tests the recognition of a TO and From redirection in a non-block statement
		{"redir /bar /foo 303", false, []Rule{{FromPath: "/bar", To: "/foo", Code: 303}}},

		// test case #8 tests the recognition of multiple redirections
		{"redir {\n / /foo 304 \n} \n redir {\n /bar /foobar 305 \n}", false, []Rule{{FromPath: "/", To: "/foo", Code: 304}, {FromPath: "/bar", To: "/foobar", Code: 305}}},

		// test case #9 tests the detection of duplicate redirections
		{"redir {\n /bar /foo 304 \n} redir {\n /bar /foo 304 \n}", true, []Rule{{}}},
	} {
		err := setup(caddy.NewTestController(test.input))
		if err != nil && !test.shouldErr {
			t.Errorf("Test case #%d recieved an error of %v", j, err)
		} else if test.shouldErr {
			continue
		}
		mids := httpserver.GetConfig("").Middleware()
		recievedRules := mids[len(mids)-1](nil).(Redirect).Rules

		for i, recievedRule := range recievedRules {
			if recievedRule.FromPath != test.expectedRules[i].FromPath {
				t.Errorf("Test case #%d.%d expected a from path of %s, but recieved a from path of %s", j, i, test.expectedRules[i].FromPath, recievedRule.FromPath)
			}
			if recievedRule.To != test.expectedRules[i].To {
				t.Errorf("Test case #%d.%d expected a TO path of %s, but recieved a TO path of %s", j, i, test.expectedRules[i].To, recievedRule.To)
			}
			if recievedRule.Code != test.expectedRules[i].Code {
				t.Errorf("Test case #%d.%d expected a HTTP status code of %d, but recieved a code of %d", j, i, test.expectedRules[i].Code, recievedRule.Code)
			}
		}
	}

}
Esempio n. 15
0
func TestSetupParseWithOptionalParams(t *testing.T) {
	params := `tls ` + certFile + ` ` + keyFile + ` {
            protocols tls1.0 tls1.2
            ciphers RSA-AES256-CBC-SHA ECDHE-RSA-AES128-GCM-SHA256 ECDHE-ECDSA-AES256-GCM-SHA384
        }`
	cfg := new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c := caddy.NewTestController("", params)

	err := setupTLS(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}

	if cfg.ProtocolMinVersion != tls.VersionTLS10 {
		t.Errorf("Expected 'tls1.0 (0x0301)' as ProtocolMinVersion, got %#v", cfg.ProtocolMinVersion)
	}

	if cfg.ProtocolMaxVersion != tls.VersionTLS12 {
		t.Errorf("Expected 'tls1.2 (0x0303)' as ProtocolMaxVersion, got %#v", cfg.ProtocolMaxVersion)
	}

	if len(cfg.Ciphers)-1 != 3 {
		t.Errorf("Expected 3 Ciphers (not including TLS_FALLBACK_SCSV), got %v", len(cfg.Ciphers)-1)
	}
}
Esempio n. 16
0
func TestLoadFromEnv(t *testing.T) {

	const testCaddyConfig = `mailout {
	[email protected]		ENV:CADDY_MAILOUT_KEY
	username				ENV:CADDY_MAILOUT_USER
	password				ENV:CADDY_MAILOUT_PW
	host            		ENV:CADDY_MAILOUT_HOST
	port            		1030
}`

	assert.NoError(t, os.Setenv("CADDY_MAILOUT_KEY", "testdata/B06469EE_nopw.pub.asc"))
	assert.NoError(t, os.Setenv("CADDY_MAILOUT_USER", "luser"))
	assert.NoError(t, os.Setenv("CADDY_MAILOUT_PW", "123456"))
	assert.NoError(t, os.Setenv("CADDY_MAILOUT_HOST", "127.0.0.4"))

	wantConfig := newConfig()
	wantConfig.pgpEmailKeys = []string{`[email protected]`, `testdata/B06469EE_nopw.pub.asc`}
	wantConfig.username = "******"
	wantConfig.password = "******"
	wantConfig.host = "127.0.0.4"
	wantConfig.portRaw = "1030"
	wantConfig.port = 1030
	wantConfig.messageCount = 0

	c := caddy.NewTestController("http", testCaddyConfig)
	mc, err := parse(c)
	if err != nil {
		t.Fatal(err)
	}
	if err := mc.loadFromEnv(); err != nil {
		t.Fatal(err)
	}
	assert.Exactly(t, wantConfig, mc)
}
Esempio n. 17
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `internal /internal`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Internal)

	if !ok {
		t.Fatalf("Expected handler to be type Internal, got: %#v", handler)
	}

	if myHandler.Paths[0] != "/internal" {
		t.Errorf("Expected internal in the list of internal Paths")
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

}
Esempio n. 18
0
func TestInternalParse(t *testing.T) {
	tests := []struct {
		inputInternalPaths    string
		shouldErr             bool
		expectedInternalPaths []string
	}{
		{`internal /internal`, false, []string{"/internal"}},

		{`internal /internal1
		  internal /internal2`, false, []string{"/internal1", "/internal2"}},
	}
	for i, test := range tests {
		actualInternalPaths, err := internalParse(caddy.NewTestController("http", test.inputInternalPaths))

		if err == nil && test.shouldErr {
			t.Errorf("Test %d didn't error, but it should have", i)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
		}

		if len(actualInternalPaths) != len(test.expectedInternalPaths) {
			t.Fatalf("Test %d expected %d InternalPaths, but got %d",
				i, len(test.expectedInternalPaths), len(actualInternalPaths))
		}
		for j, actualInternalPath := range actualInternalPaths {
			if actualInternalPath != test.expectedInternalPaths[j] {
				t.Fatalf("Test %d expected %dth Internal Path to be  %s  , but got %s",
					i, j, test.expectedInternalPaths[j], actualInternalPath)
			}
		}
	}

}
Esempio n. 19
0
func TestWebSocket(t *testing.T) {
	err := setup(caddy.NewTestController(`websocket cat`))
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig("").Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(WebSocket)

	if !ok {
		t.Fatalf("Expected handler to be type WebSocket, got: %#v", handler)
	}

	if myHandler.Sockets[0].Path != "/" {
		t.Errorf("Expected / as the default Path")
	}
	if myHandler.Sockets[0].Command != "cat" {
		t.Errorf("Expected %s as the command", "cat")
	}

}
Esempio n. 20
0
func TestSetupParseIncompleteParams(t *testing.T) {
	// Using tls without args is an error because it's unnecessary.
	c := caddy.NewTestController("", `tls`)
	err := setupTLS(c)
	if err == nil {
		t.Error("Expected an error, but didn't get one")
	}
}
Esempio n. 21
0
func TestSetupParseBasic(t *testing.T) {
	cfg := new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c := caddy.NewTestController("", `tls `+certFile+` `+keyFile+``)

	err := setupTLS(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}

	// Basic checks
	if !cfg.Manual {
		t.Error("Expected TLS Manual=true, but was false")
	}
	if !cfg.Enabled {
		t.Error("Expected TLS Enabled=true, but was false")
	}

	// Security defaults
	if cfg.ProtocolMinVersion != tls.VersionTLS11 {
		t.Errorf("Expected 'tls1.1 (0x0302)' as ProtocolMinVersion, got %#v", cfg.ProtocolMinVersion)
	}
	if cfg.ProtocolMaxVersion != tls.VersionTLS12 {
		t.Errorf("Expected 'tls1.2 (0x0303)' as ProtocolMaxVersion, got %v", cfg.ProtocolMaxVersion)
	}

	// Cipher checks
	expectedCiphers := []uint16{
		tls.TLS_FALLBACK_SCSV,
		tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
		tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
		tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
		tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
		tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
		tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
		tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
		tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
		tls.TLS_RSA_WITH_AES_256_CBC_SHA,
		tls.TLS_RSA_WITH_AES_128_CBC_SHA,
	}

	// Ensure count is correct (plus one for TLS_FALLBACK_SCSV)
	if len(cfg.Ciphers) != len(expectedCiphers) {
		t.Errorf("Expected %v Ciphers (including TLS_FALLBACK_SCSV), got %v",
			len(expectedCiphers), len(cfg.Ciphers))
	}

	// Ensure ordering is correct
	for i, actual := range cfg.Ciphers {
		if actual != expectedCiphers[i] {
			t.Errorf("Expected cipher in position %d to be %0x, got %0x", i, expectedCiphers[i], actual)
		}
	}

	if !cfg.PreferServerCipherSuites {
		t.Error("Expected PreferServerCipherSuites = true, but was false")
	}
}
Esempio n. 22
0
func TestSetup(t *testing.T) {
	tempDirPath := os.TempDir()
	_, err := os.Stat(tempDirPath)
	if err != nil {
		t.Fatalf("BeforeTest: Failed to find an existing directory for testing! Error was: %v", err)
	}
	nonExistantDirPath := filepath.Join(tempDirPath, strconv.Itoa(int(time.Now().UnixNano())))

	tempTemplate, err := ioutil.TempFile(".", "tempTemplate")
	if err != nil {
		t.Fatalf("BeforeTest: Failed to create a temporary file in the working directory! Error was: %v", err)
	}
	defer os.Remove(tempTemplate.Name())

	tempTemplatePath := filepath.Join(".", tempTemplate.Name())

	for i, test := range []struct {
		input             string
		expectedPathScope []string
		shouldErr         bool
	}{
		// test case #0 tests handling of multiple pathscopes
		{"browse " + tempDirPath + "\n browse .", []string{tempDirPath, "."}, false},

		// test case #1 tests instantiation of Config with default values
		{"browse /", []string{"/"}, false},

		// test case #2 tests detectaction of custom template
		{"browse . " + tempTemplatePath, []string{"."}, false},

		// test case #3 tests detection of non-existent template
		{"browse . " + nonExistantDirPath, nil, true},

		// test case #4 tests detection of duplicate pathscopes
		{"browse " + tempDirPath + "\n browse " + tempDirPath, nil, true},
	} {

		c := caddy.NewTestController("http", test.input)
		err := setup(c)
		if err != nil && !test.shouldErr {
			t.Errorf("Test case #%d recieved an error of %v", i, err)
		}
		if test.expectedPathScope == nil {
			continue
		}
		mids := httpserver.GetConfig(c).Middleware()
		mid := mids[len(mids)-1]
		recievedConfigs := mid(nil).(Browse).Configs
		for j, config := range recievedConfigs {
			if config.PathScope != test.expectedPathScope[j] {
				t.Errorf("Test case #%d expected a pathscope of %v, but got %v", i, test.expectedPathScope, config.PathScope)
			}
		}
	}
}
Esempio n. 23
0
func TestHeadersParse(t *testing.T) {
	tests := []struct {
		input     string
		shouldErr bool
		expected  []Rule
	}{
		{`header /foo Foo "Bar Baz"`,
			false, []Rule{
				{Path: "/foo", Headers: http.Header{
					"Foo": []string{"Bar Baz"},
				}},
			}},
		{`header /bar { Foo "Bar Baz" Baz Qux }`,
			false, []Rule{
				{Path: "/bar", Headers: http.Header{
					"Foo": []string{"Bar Baz"},
					"Baz": []string{"Qux"},
				}},
			}},
	}

	for i, test := range tests {
		actual, err := headersParse(caddy.NewTestController("http", test.input))

		if err == nil && test.shouldErr {
			t.Errorf("Test %d didn't error, but it should have", i)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
		}

		if len(actual) != len(test.expected) {
			t.Fatalf("Test %d expected %d rules, but got %d",
				i, len(test.expected), len(actual))
		}

		for j, expectedRule := range test.expected {
			actualRule := actual[j]

			if actualRule.Path != expectedRule.Path {
				t.Errorf("Test %d, rule %d: Expected path %s, but got %s",
					i, j, expectedRule.Path, actualRule.Path)
			}

			expectedHeaders := fmt.Sprintf("%v", expectedRule.Headers)
			actualHeaders := fmt.Sprintf("%v", actualRule.Headers)

			if !reflect.DeepEqual(actualRule.Headers, expectedRule.Headers) {
				t.Errorf("Test %d, rule %d: Expected headers %s, but got %s",
					i, j, expectedHeaders, actualHeaders)
			}
		}
	}
}
Esempio n. 24
0
func newTestHandler(t *testing.T, caddyFile string) *handler {
	c := caddy.NewTestController("http", caddyFile)
	mc, err := parse(c)
	if err != nil {
		t.Fatal(err)
	}
	h := newHandler(mc, nil)
	h.Next = httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
		return http.StatusTeapot, nil
	})
	return h
}
Esempio n. 25
0
// The Startup function's tests are symmetrical to Shutdown tests,
// because the Startup and Shutdown functions share virtually the
// same functionality
func TestStartup(t *testing.T) {
	tempDirPath := os.TempDir()

	testDir := filepath.Join(tempDirPath, "temp_dir_for_testing_startupshutdown")
	defer func() {
		// clean up after non-blocking startup function quits
		time.Sleep(500 * time.Millisecond)
		os.RemoveAll(testDir)
	}()
	osSenitiveTestDir := filepath.FromSlash(testDir)
	os.RemoveAll(osSenitiveTestDir) // start with a clean slate

	var registeredFunction func() error
	fakeRegister := func(fn func() error) {
		registeredFunction = fn
	}

	tests := []struct {
		input              string
		shouldExecutionErr bool
		shouldRemoveErr    bool
	}{
		// test case #0 tests proper functionality blocking commands
		{"startup mkdir " + osSenitiveTestDir, false, false},

		// test case #1 tests proper functionality of non-blocking commands
		{"startup mkdir " + osSenitiveTestDir + " &", false, true},

		// test case #2 tests handling of non-existent commands
		{"startup " + strconv.Itoa(int(time.Now().UnixNano())), true, true},
	}

	for i, test := range tests {
		c := caddy.NewTestController("", test.input)
		err := registerCallback(c, fakeRegister)
		if err != nil {
			t.Errorf("Expected no errors, got: %v", err)
		}
		if registeredFunction == nil {
			t.Fatalf("Expected function to be registered, but it wasn't")
		}
		err = registeredFunction()
		if err != nil && !test.shouldExecutionErr {
			t.Errorf("Test %d recieved an error of:\n%v", i, err)
		}
		err = os.Remove(osSenitiveTestDir)
		if err != nil && !test.shouldRemoveErr {
			t.Errorf("Test %d recieved an error of:\n%v", i, err)
		}
	}
}
Esempio n. 26
0
func TestSetupBind(t *testing.T) {
	err := setupBind(caddy.NewTestController(`bind 1.2.3.4`))
	if err != nil {
		t.Fatalf("Expected no errors, but got: %v", err)
	}

	cfg := httpserver.GetConfig("")
	if got, want := cfg.ListenHost, "1.2.3.4"; got != want {
		t.Errorf("Expected the config's ListenHost to be %s, was %s", want, got)
	}
	if got, want := cfg.TLS.ListenHost, "1.2.3.4"; got != want {
		t.Errorf("Expected the TLS config's ListenHost to be %s, was %s", want, got)
	}
}
Esempio n. 27
0
func TestLoadTemplate(t *testing.T) {

	tests := []struct {
		caddyfile string
		wantErr   error
	}{
		{
			`mailout {
				body            testdata/mail_tpl_NOTFOUND.html
			}`,
			errors.New("File \"testdata/mail_tpl_NOTFOUND.html\" not found"),
		},
		{
			`mailout {
				body            testdata/mail_tpl.phtml
			}`,
			errors.New("Incorrect file extension. Neither .txt nor .html: \"testdata/mail_tpl.phtml\""),
		},
		{
			`mailout {
				body            testdata/mail_tpl.html
			}`,
			nil,
		},
		{
			`mailout {
				body            testdata/mail_tpl.txt
			}`,
			nil,
		},
	}
	for i, test := range tests {
		c := caddy.NewTestController("http", test.caddyfile)
		mc, err := parse(c)
		if err != nil {
			t.Fatal(err)
		}

		tplErr := mc.loadTemplate()

		if test.wantErr != nil {
			assert.Nil(t, mc.bodyTpl)
			assert.EqualError(t, tplErr, test.wantErr.Error(), "Index %d ", i)
			continue
		}
		assert.NoError(t, tplErr, "Index %d ", i)
		assert.NotNil(t, mc.bodyTpl, "Index %d ", i)
	}
}
Esempio n. 28
0
func TestSearchSetup(t *testing.T) {
	for _, kase := range configCases {
		Convey("Given a Caddy controller with the search middleware", t, func() {
			c := caddy.NewTestController(kase.config)
			cnf := httpserver.GetConfig("")
			result, err := search.ParseSearchConfig(c, cnf)
			Convey("Should not receive an error when parsing", func() {
				So(err, ShouldBeNil)
			})
			Convey(kase.expectMsg, func() {
				kase.expectMatch(kase.expectConf, *result)
			})
		})
	}
}
Esempio n. 29
0
func TestSetupDefaultWithOptionalParams(t *testing.T) {
	params := `tls {
            ciphers RSA-3DES-EDE-CBC-SHA
        }`
	cfg := new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c := caddy.NewTestController("", params)

	err := setupTLS(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	if len(cfg.Ciphers)-1 != 1 {
		t.Errorf("Expected 1 ciphers (not including TLS_FALLBACK_SCSV), got %v", len(cfg.Ciphers)-1)
	}
}
Esempio n. 30
0
func TestSetupParseWithKeyType(t *testing.T) {
	params := `tls {
            key_type p384
        }`
	cfg := new(Config)
	RegisterConfigGetter("", func(c *caddy.Controller) *Config { return cfg })
	c := caddy.NewTestController("", params)

	err := setupTLS(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}

	if cfg.KeyType != acme.EC384 {
		t.Errorf("Expected 'P384' as KeyType, got %#v", cfg.KeyType)
	}
}