Example #1
0
File: url.go Project: ruflin/beats
// SetURLUser set the user credentials in the given URL. If the username or
// password is not set in the URL then the default is used (if provided).
func SetURLUser(u *url.URL, defaultUser, defaultPass string) {
	var user, pass string
	var userIsSet, passIsSet bool
	if u.User != nil {
		user = u.User.Username()
		if user != "" {
			userIsSet = true
		}
		pass, passIsSet = u.User.Password()
	}

	if !userIsSet && defaultUser != "" {
		userIsSet = true
		user = defaultUser
	}

	if !passIsSet && defaultPass != "" {
		passIsSet = true
		pass = defaultPass
	}

	if userIsSet && passIsSet {
		u.User = url.UserPassword(user, pass)
	} else if userIsSet {
		u.User = url.User(user)
	}
}
Example #2
0
func processOverride(u *url.URL) {
	envUsername := os.Getenv(envUserName)
	envPassword := os.Getenv(envPassword)

	// Override username if provided
	if envUsername != "" {
		var password string
		var ok bool

		if u.User != nil {
			password, ok = u.User.Password()
		}

		if ok {
			u.User = url.UserPassword(envUsername, password)
		} else {
			u.User = url.User(envUsername)
		}
	}

	// Override password if provided
	if envPassword != "" {
		var username string

		if u.User != nil {
			username = u.User.Username()
		}

		u.User = url.UserPassword(username, envPassword)
	}
}
Example #3
0
// Set the API key used for all Get and Push API calls.
func SetAPIKey(apiKey string) {
	pUrl := url.URL{}
	pUrl.Scheme = "https"
	pUrl.User = url.UserPassword(apiKey, "")
	pUrl.Host = "api.pushbullet.com"
	pUrl.Path = "/api/pushes"
	pushUrl = pUrl.String()

	gUrl := url.URL{}
	gUrl.Scheme = "https"
	gUrl.User = url.UserPassword(apiKey, "")
	gUrl.Host = "api.pushbullet.com"
	gUrl.Path = "/api/devices"
	getUrl = gUrl.String()
}
Example #4
0
// ParseURL is wrapper around url.Parse, where Scheme defaults to "https" and Path defaults to "/sdk"
func ParseURL(s string) (*url.URL, error) {
	var err error
	var u *url.URL

	if s != "" {
		// Default the scheme to https
		if !schemeMatch.MatchString(s) {
			s = "https://" + s
		}

		u, err = url.Parse(s)
		if err != nil {
			return nil, err
		}

		// Default the path to /sdk
		if u.Path == "" {
			u.Path = "/sdk"
		}

		if u.User == nil {
			u.User = url.UserPassword("", "")
		}
	}

	return u, nil
}
Example #5
0
func linkArgs(s Service, container string) []string {
	args := []string{}

	prefix := strings.Replace(strings.ToUpper(s.Name), "-", "_", -1)
	env := containerEnv(container)

	scheme := coalesce(env["LINK_SCHEME"], "tcp")
	host := containerHost(container, s.Networks)
	port := containerPort(container)
	path := env["LINK_PATH"]
	username := env["LINK_USERNAME"]
	password := env["LINK_PASSWORD"]

	args = append(args, "--add-host", fmt.Sprintf("%s:%s", s.Name, host))
	args = append(args, "-e", fmt.Sprintf("%s_SCHEME=%s", prefix, scheme))
	args = append(args, "-e", fmt.Sprintf("%s_HOST=%s", prefix, host))
	args = append(args, "-e", fmt.Sprintf("%s_PORT=%s", prefix, port))
	args = append(args, "-e", fmt.Sprintf("%s_PATH=%s", prefix, path))
	args = append(args, "-e", fmt.Sprintf("%s_USERNAME=%s", prefix, username))
	args = append(args, "-e", fmt.Sprintf("%s_PASSWORD=%s", prefix, password))

	u := url.URL{
		Scheme: scheme,
		Host:   fmt.Sprintf("%s:%s", host, port),
		Path:   path,
	}

	if username != "" || password != "" {
		u.User = url.UserPassword(username, password)
	}

	args = append(args, "-e", fmt.Sprintf("%s_URL=%s", prefix, u.String()))

	return args
}
Example #6
0
func (c *ShuttleConfig) OutletURL() string {
	var err error
	var oUrl *url.URL

	if len(c.LogsURL) > 0 {
		oUrl, err = url.Parse(c.LogsURL)
		if err != nil {
			log.Fatalf("Unable to parse logs-url")
		}
	}
	if len(LogplexUrl) > 0 {
		oUrl, err = url.Parse(LogplexUrl)
		if err != nil {
			log.Fatalf("Unable to parse $LOGPLEX_URL")
		}
	}

	if oUrl == nil {
		log.Fatalf("Must set -logs-url or $LOGPLEX_URL.")
	}

	if oUrl.User == nil {
		oUrl.User = url.UserPassword("token", c.Appname)
	}
	return oUrl.String()
}
Example #7
0
// NOTE: this is the simpler approach:
//       build up the ENV from the declared links
//       assuming local dev is done on DOCKER_HOST
func (me *ManifestEntry) ResolvedLinkVars(m *Manifest, cache bool) (map[string]string, error) {
	linkVars := make(map[string]string)

	if m == nil {
		return linkVars, nil
	}

	for _, link := range me.Links {
		linkEntry, ok := (*m)[link]

		if !ok {
			return nil, fmt.Errorf("no such link: %s", link)
		}

		linkEntryEnv, err := getLinkEntryEnv(linkEntry, cache)
		if err != nil {
			return linkVars, err
		}

		// get url parts from various places
		scheme := linkEntryEnv["LINK_SCHEME"]
		if scheme == "" {
			scheme = "tcp"
		}

		host, err := getDockerGateway()
		if err != nil {
			return linkVars, err
		}

		// we don't create a balancer without a port,
		// so we don't create a link url either
		port := resolveOtherPort(link, linkEntry)
		if port == "" {
			continue
		}

		linkUrl := url.URL{
			Scheme: scheme,
			Host:   host + ":" + port,
			Path:   linkEntryEnv["LINK_PATH"],
		}

		if linkEntryEnv["LINK_USERNAME"] != "" || linkEntryEnv["LINK_PASSWORD"] != "" {
			linkUrl.User = url.UserPassword(linkEntryEnv["LINK_USERNAME"], linkEntryEnv["LINK_PASSWORD"])
		}

		prefix := strings.ToUpper(link) + "_"
		prefix = strings.Replace(prefix, "-", "_", -1)
		linkVars[prefix+"URL"] = linkUrl.String()
		linkVars[prefix+"HOST"] = host
		linkVars[prefix+"SCHEME"] = scheme
		linkVars[prefix+"PORT"] = port
		linkVars[prefix+"USERNAME"] = linkEntryEnv["LINK_USERNAME"]
		linkVars[prefix+"PASSWORD"] = linkEntryEnv["LINK_PASSWORD"]
		linkVars[prefix+"PATH"] = linkEntryEnv["LINK_PATH"]
	}

	return linkVars, nil
}
Example #8
0
File: main.go Project: pcn/influxdb
func (c *cli) connect(cmd string) {
	var cl *client.Client

	if cmd != "" {
		// TODO parse out connection string
	}
	u := url.URL{
		Scheme: "http",
	}
	if c.port > 0 {
		u.Host = fmt.Sprintf("%s:%d", c.host, c.port)
	} else {
		u.Host = c.host
	}
	if c.username != "" {
		u.User = url.UserPassword(c.username, c.password)
	}
	cl, err := client.NewClient(
		client.Config{
			URL:      u,
			Username: c.username,
			Password: c.password,
		})
	if err != nil {
		fmt.Printf("Could not create client %s", err)
		return
	}
	c.client = cl
	if _, v, e := c.client.Ping(); e != nil {
		fmt.Printf("Failed to connect to %s\n", c.client.Addr())
	} else {
		c.version = v
		fmt.Printf("Connected to %s version %s\n", c.client.Addr(), c.version)
	}
}
Example #9
0
func (c *CommandLine) connect(cmd string) {
	var cl *client.Client

	if cmd != "" {
		// Remove the "connect" keyword if it exists
		cmd = strings.TrimSpace(strings.Replace(cmd, "connect", "", -1))
		if cmd == "" {
			return
		}
		if strings.Contains(cmd, ":") {
			h := strings.Split(cmd, ":")
			if i, e := strconv.Atoi(h[1]); e != nil {
				fmt.Printf("Connect error: Invalid port number %q: %s\n", cmd, e)
				return
			} else {
				c.Port = i
			}
			if h[0] == "" {
				c.Host = default_host
			} else {
				c.Host = h[0]
			}
		} else {
			c.Host = cmd
			// If they didn't specify a port, always use the default port
			c.Port = default_port
		}
	}

	u := url.URL{
		Scheme: "http",
	}
	if c.Port > 0 {
		u.Host = fmt.Sprintf("%s:%d", c.Host, c.Port)
	} else {
		u.Host = c.Host
	}
	if c.Username != "" {
		u.User = url.UserPassword(c.Username, c.Password)
	}
	cl, err := client.NewClient(
		client.Config{
			URL:       u,
			Username:  c.Username,
			Password:  c.Password,
			UserAgent: "InfluxDBShell/" + version,
		})
	if err != nil {
		fmt.Printf("Could not create client %s", err)
		return
	}
	c.Client = cl
	if _, v, e := c.Client.Ping(); e != nil {
		fmt.Printf("Failed to connect to %s\n", c.Client.Addr())
	} else {
		c.Version = v
		fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.Version)
	}
}
Example #10
0
// redactPassword returns the URL as a string with the password redacted.
func redactPassword(u url.URL) string {

	if u.User == nil {
		return u.String()
	}

	u.User = url.User(u.User.Username())
	return u.String()
}
Example #11
0
// String encodes dsn to a URL string format.
func (dsn *DSN) String() string {
	u := url.URL{
		Host: fmt.Sprintf("tcp(%s)", dsn.Host),
		Path: "/" + dsn.Database,
		RawQuery: url.Values{
			"timeout": {dsn.Timeout.String()},
		}.Encode(),
	}

	// Set password, if available.
	if dsn.Password == "" {
		u.User = url.User(dsn.User)
	} else {
		u.User = url.UserPassword(dsn.User, dsn.Password)
	}

	// Remove leading double-slash.
	return strings.TrimPrefix(u.String(), "//")
}
Example #12
0
File: config.go Project: jwmaag/dex
func (p *Postgres) open(logger logrus.FieldLogger) (*conn, error) {
	v := url.Values{}
	set := func(key, val string) {
		if val != "" {
			v.Set(key, val)
		}
	}
	set("connect_timeout", strconv.Itoa(p.ConnectionTimeout))
	set("sslkey", p.SSL.KeyFile)
	set("sslcert", p.SSL.CertFile)
	set("sslrootcert", p.SSL.CAFile)
	if p.SSL.Mode == "" {
		// Assume the strictest mode if unspecified.
		p.SSL.Mode = sslVerifyFull
	}
	set("sslmode", p.SSL.Mode)

	u := url.URL{
		Scheme:   "postgres",
		Host:     p.Host,
		Path:     "/" + p.Database,
		RawQuery: v.Encode(),
	}

	if p.User != "" {
		if p.Password != "" {
			u.User = url.UserPassword(p.User, p.Password)
		} else {
			u.User = url.User(p.User)
		}
	}
	db, err := sql.Open("postgres", u.String())
	if err != nil {
		return nil, err
	}
	c := &conn{db, flavorPostgres, logger}
	if _, err := c.migrate(); err != nil {
		return nil, fmt.Errorf("failed to perform migrations: %v", err)
	}
	return c, nil
}
Example #13
0
func getURL() url.URL {
	ur := url.URL{
		Scheme: "mongodb",
		Host:   host,
		Path:   db,
	}
	if name != "" {
		u := url.UserPassword(name, password)
		ur.User = u
	}
	return ur
}
Example #14
0
// addAuthFromNetrc adds auth information to the URL from the user's
// netrc file if it can be found. This will only add the auth info
// if the URL doesn't already have auth info specified and the
// the username is blank.
func addAuthFromNetrc(u *url.URL) error {
	// If the URL already has auth information, do nothing
	if u.User != nil && u.User.Username() != "" {
		return nil
	}

	// Get the netrc file path
	path := os.Getenv("NETRC")
	if path == "" {
		filename := ".netrc"
		if runtime.GOOS == "windows" {
			filename = "_netrc"
		}

		var err error
		path, err = homedir.Expand("~/" + filename)
		if err != nil {
			return err
		}
	}

	// If the file is not a file, then do nothing
	if fi, err := os.Stat(path); err != nil {
		// File doesn't exist, do nothing
		if os.IsNotExist(err) {
			return nil
		}

		// Some other error!
		return err
	} else if fi.IsDir() {
		// File is directory, ignore
		return nil
	}

	// Load up the netrc file
	net, err := netrc.ParseFile(path)
	if err != nil {
		return fmt.Errorf("Error parsing netrc file at %q: %s", path, err)
	}

	machine := net.FindMachine(u.Host)
	if machine == nil {
		// Machine not found, no problem
		return nil
	}

	// Set the user info
	u.User = url.UserPassword(machine.Login, machine.Password)
	return nil
}
Example #15
0
// The string representation of a Node is a URL.
// Please see ParseNode for a description of the format.
func (n *Node) String() string {
	u := url.URL{Scheme: "enode"}
	if n.Incomplete() {
		u.Host = fmt.Sprintf("%x", n.ID[:])
	} else {
		addr := net.TCPAddr{IP: n.IP, Port: int(n.TCP)}
		u.User = url.User(fmt.Sprintf("%x", n.ID[:]))
		u.Host = addr.String()
		if n.UDP != n.TCP {
			u.RawQuery = "discport=" + strconv.Itoa(int(n.UDP))
		}
	}
	return u.String()
}
Example #16
0
// MungeNoProtocolURL will take a URL returned from net/url.Parse and make
// corrections to the URL when no protocol is specified in the Scheme, where there
// are valid protocol-less git url spec formats that result in either file:// or ssh:// protocol usage;
// if an explicit protocol is already specified, then the
// URL is left unchaged and the method simply returns with no error reported,
// since the URL is
func (h *stiGit) MungeNoProtocolURL(source string, uri *url.URL) error {
	if uri == nil {
		return nil
	}

	// only deal with protocol-less url's
	if uri.Scheme != "" {
		return nil
	}

	details, mods, err := ParseFile(source)
	if err != nil {
		return err
	}

	if details.BadRef {
		return fmt.Errorf("bad reference following # in %s", source)
	}
	if !details.FileExists {
		mods2, err := ParseSSH(source)
		if err != nil {
			glog.Errorf("ssh git clone spec error: %v", err)
			return err
		}
		mods = mods2
	}

	// update the either file or ssh url accordingly
	if mods != nil {
		if len(mods.User) > 0 {
			uri.User = url.User(mods.User)
		}
		if len(mods.Scheme) > 0 {
			uri.Scheme = mods.Scheme
		}
		if len(mods.Host) > 0 {
			uri.Host = mods.Host
		}
		if len(mods.Path) > 0 {
			uri.Path = mods.Path
		}
		if len(mods.Ref) > 0 {
			uri.Fragment = mods.Ref
		}
	}
	return nil
}
Example #17
0
func Connect(dburl, database, username, password string) {
	DBUrl := url.URL{
		Scheme:   "postgres",
		Host:     dburl,
		Path:     database,
		RawQuery: "sslmode=disable",
	}

	log.Printf("Connecting to DB on %s", DBUrl.String())

	DBUrl.User = url.UserPassword(username, password)
	var err error

	db, err = sql.Open("postgres", DBUrl.String())
	if err != nil {
		log.Fatal(err)
	}
}
Example #18
0
func (uri *URI) String() string {
	u := url.URL{
		Scheme:   uri.Protocol,
		Host:     uri.Canonical,
		Path:     uri.Session,
		Fragment: uri.Token,
	}

	if u.Scheme == "" {
		u.Scheme = "mesh"
	}

	if uri.User != "" {
		u.User = url.User(uri.User)
	}

	return u.String()
}
Example #19
0
func (b *Bucket) parseAPIResponse(path string, out interface{}) error {
	nodes := b.Nodes()
	if len(nodes) == 0 {
		return errors.New("no couch rest URLs")
	}

	var err error
	var u *url.URL

	// Pick a random node to start querying.
	startNode := rand.Intn(len(nodes))
	maxRetries := len(nodes)
	for i := 0; i < maxRetries; i++ {
		node := nodes[(startNode+i)%len(nodes)] // Wrap around the nodes list.
		// Skip non-healthy nodes.
		if node.Status != "healthy" || node.CouchAPIBase == "" {
			continue
		}

		u, err = ParseURL(node.CouchAPIBase)
		// Lock here so pool does not get closed under us.
		b.RLock()
		if err != nil {
			b.RUnlock()
			return fmt.Errorf("config error: Bucket %q node #%d CouchAPIBase=%q: %v",
				b.Name, i, node.CouchAPIBase, err)
		} else if b.pool != nil {
			u.User = b.pool.client.BaseURL.User
		}
		u.Path = path

		// generate the path so that the strings are properly escaped
		// MB-13770
		requestPath := strings.Split(u.String(), u.Host)[1]

		err = queryRestAPI(u, requestPath, b.pool.client.ah, out)
		b.RUnlock()
		if err == nil {
			return err
		}
	}
	return errors.New("All nodes failed to respond or returned error or no healthy nodes for bucket found. Error " + err.Error())
}
Example #20
0
func Connect() {
	DBUrl := url.URL{
		Scheme:   "postgres",
		Host:     config.Constants.DBAddr,
		Path:     config.Constants.DBDatabase,
		RawQuery: "sslmode=disable",
	}

	helpers.Logger.Debug("Connecting to DB on %s", DBUrl.String())

	DBUrl.User = url.UserPassword(config.Constants.DBUsername, config.Constants.DBPassword)
	var err error

	db, err = sql.Open("postgres", DBUrl.String())
	if err != nil {
		helpers.Logger.Fatal(err)
	}
	//db.SetMaxOpenConns(*maxOpen)

	helpers.Logger.Debug("Connected.")
}
Example #21
0
func (d *GitHubDetector) detectSSH(src string) (string, bool, error) {
	idx := strings.Index(src, ":")
	qidx := strings.Index(src, "?")
	if qidx == -1 {
		qidx = len(src)
	}

	var u url.URL
	u.Scheme = "ssh"
	u.User = url.User("git")
	u.Host = "github.com"
	u.Path = src[idx+1 : qidx]
	if qidx < len(src) {
		q, err := url.ParseQuery(src[qidx+1:])
		if err != nil {
			return "", true, fmt.Errorf("error parsing GitHub SSH URL: %s", err)
		}

		u.RawQuery = q.Encode()
	}

	return "git::" + u.String(), true, nil
}
Example #22
0
func TestHttpGetter_auth(t *testing.T) {
	ln := testHttpServer(t)
	defer ln.Close()

	g := new(HttpGetter)
	dst := tempDir(t)

	var u url.URL
	u.Scheme = "http"
	u.Host = ln.Addr().String()
	u.Path = "/meta-auth"
	u.User = url.UserPassword("foo", "bar")

	// Get it!
	if err := g.Get(dst, &u); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Verify the main file exists
	mainPath := filepath.Join(dst, "main.tf")
	if _, err := os.Stat(mainPath); err != nil {
		t.Fatalf("err: %s", err)
	}
}
Example #23
0
File: url.go Project: fcavani/net
// ParseWithSocket parses url like this: mysql://root:pass@unix(/var/run/mysql.socket)/db
// and normal urls.
func ParseWithSocket(url_ string) (*url.URL, error) {
	u := new(url.URL)
	s := strings.SplitN(url_, "://", 2)
	if len(s) != 2 {
		return nil, e.New("invalid url")
	}
	u.Scheme = s[0]
	rest := ""
	s = strings.SplitN(s[1], "@", 2)
	if len(s) == 1 {
		rest = s[0]
	} else if len(s) == 2 {
		userpass := strings.SplitN(s[0], ":", 2)
		if len(userpass) == 1 {
			u.User = url.User(userpass[0])
		} else if len(userpass) == 2 {
			pass, err := url.QueryUnescape(userpass[1])
			if err != nil {
				return nil, e.New(err)
			}
			u.User = url.UserPassword(userpass[0], pass)
		} else {
			return nil, e.New("invalid user password")
		}
		rest = s[1]
	} else {
		return nil, e.New("invalid user string")
	}

	unix := regUnix.FindAllString(rest, 1)
	if len(unix) == 1 {
		u.Host = unix[0]
		rest = strings.TrimSpace(regUnix.ReplaceAllLiteralString(rest, ""))
		q := strings.Index(rest, "?")
		f := strings.Index(rest, "#")
		pend := f
		if q > f {
			pend = q
		}
		i := strings.Index(rest, "/")
		if i != -1 && pend != -1 {
			u.Path = rest[i:pend]
			rest = rest[pend:]
		} else if i == -1 && pend != -1 {
			rest = rest[pend:]
		} else if i != -1 && pend == -1 {
			u.Path = rest[i:]
			pathInHost(u)
			return u, nil
		} else if i == -1 && pend == -1 {
			pathInHost(u)
			return u, nil
		}
	} else if len(unix) == 0 {
		q := strings.Index(rest, "?")
		f := strings.Index(rest, "#")
		pend := f
		ff := f
		if f == -1 {
			ff = math.MaxInt64
		}
		if q < ff && q >= 0 {
			pend = q
		}
		i := strings.Index(rest, "/")
		if i != -1 && pend != -1 {
			u.Host = rest[:i]
			u.Path = rest[i:pend]
			rest = rest[pend:]
		} else if i == -1 && pend != -1 {
			u.Host = rest[:pend]
			rest = rest[pend:]
		} else if i != -1 && pend == -1 {
			u.Host = rest[:i]
			u.Path = rest[i:]
			pathInHost(u)
			return u, nil
		} else if i == -1 && pend == -1 {
			u.Host = rest
			pathInHost(u)
			return u, nil
		}
	} else {
		return nil, e.New("socket address is invalid")
	}

	pathInHost(u)

	q := strings.Index(rest, "?")
	f := strings.Index(rest, "#")

	if q+1 >= len(rest) {
		return nil, e.New("error parsing query")
	}
	if f+1 >= len(rest) {
		return nil, e.New("error parsing fragment")
	}

	if q != -1 && f != -1 && q <= f {
		u.RawQuery = rest[q+1 : f]
		u.Fragment = rest[f+1:]
	} else if q != -1 && f == -1 {
		u.RawQuery = rest[q+1:]
	} else if q == -1 && f != -1 {
		u.Fragment = rest[f+1:]
	} else if q == -1 && f == -1 {
		return u, nil
	} else {
		return nil, e.New("error parsing query and fragment %v, %v", q, f)
	}
	return u, nil
}
Example #24
0
func StripPassword(url url.URL) url.URL {
	url.User = nil
	return url
}
				It("Makes an upload request using that multipart request", func() {
					var uploadRequest *http.Request
					Eventually(uploadRequestChan).Should(Receive(&uploadRequest))
					Expect(uploadRequest.Header.Get("Content-Type")).To(ContainSubstring("multipart/form-data; boundary="))
				})

				It("Forwards Content-MD5 header onto the upload request", func() {
					var uploadRequest *http.Request
					Eventually(uploadRequestChan).Should(Receive(&uploadRequest))
					Expect(uploadRequest.Header.Get("Content-MD5")).To(Equal("the-md5"))
				})

				Context("When the upload URL has basic auth credentials", func() {
					BeforeEach(func() {
						uploadURL.User = url.UserPassword("bob", "cobb")
					})

					It("Forwards the basic auth credentials", func() {
						var uploadRequest *http.Request
						Eventually(uploadRequestChan).Should(Receive(&uploadRequest))
						Expect(uploadRequest.URL.User).To(Equal(url.UserPassword("bob", "cobb")))
					})
				})

				Context("When uploading to the upload URL succeeds", func() {
					It("Returns the respons, and no error", func() {
						Expect(response).To(Equal(responseWithCode(http.StatusOK))) // assumes (*http.Client).do doesn't modify the response from the roundtripper
						Expect(uploadErr).NotTo(HaveOccurred())
					})
				})
			uploadURL.User = url.UserPassword("bob", "password")
			uploadURL.Path = "/staging/droplet/app-guid/upload"
			uploadURL.RawQuery = url.Values{"async": []string{"true"}}.Encode()
		})

		JustBeforeEach(func() {
			u, err := url.Parse("http://cc-uploader.com/v1/droplet/app-guid")
			Expect(err).NotTo(HaveOccurred())

			v := url.Values{cc_messages.CcDropletUploadUriKey: []string{uploadURL.String()}}
			u.RawQuery = v.Encode()
			incomingRequest.URL = u

			outgoingResponse = httptest.NewRecorder()

			startTime = time.Now()
			handler.ServeHTTP(outgoingResponse, incomingRequest)
			endTime = time.Now()
		})

		Context("uploading the file, when all is well", func() {
			BeforeEach(func() {
				postStatusCode = http.StatusCreated
				postResponseBody = pollingResponseBody("my-job-guid", "queued", fakeCloudController.URL())
				fakeCloudController.AppendHandlers(
					verifyPollingRequest("my-job-guid", "queued", timeClicker),
					verifyPollingRequest("my-job-guid", "running", timeClicker),
					verifyPollingRequest("my-job-guid", "finished", timeClicker),
				)
			})

			It("responds with 201 CREATED", func() {
				Expect(outgoingResponse.Code).To(Equal(http.StatusCreated))
			})

			It("forwards the content-md5 header", func() {
				Expect(uploadedHeaders.Get("Content-MD5")).To(Equal("the-md5"))
			})

			It("uploads the correct file", func() {
				Expect(uploadedBytes).To(Equal([]byte("the file I'm uploading")))
				Expect(uploadedFileName).To(Equal("droplet.tgz"))
			})

			It("should wait between polls", func() {
				var firstTime, secondTime, thirdTime time.Time
				Eventually(timeClicker).Should(Receive(&firstTime))
				Eventually(timeClicker).Should(Receive(&secondTime))
				Eventually(timeClicker).Should(Receive(&thirdTime))

				Expect(secondTime.Sub(firstTime)).To(BeNumerically(">", 75*time.Millisecond))
				Expect(thirdTime.Sub(secondTime)).To(BeNumerically(">", 75*time.Millisecond))
			})
		})

		Context("uploading the file, when the job fails", func() {
			BeforeEach(func() {
				postStatusCode = http.StatusCreated
				postResponseBody = pollingResponseBody("my-job-guid", "queued", fakeCloudController.URL())
				fakeCloudController.AppendHandlers(
					verifyPollingRequest("my-job-guid", "queued", timeClicker),
					verifyPollingRequest("my-job-guid", "failed", timeClicker),
				)
			})

			It("stops polling after the first fail", func() {
				Expect(fakeCloudController.ReceivedRequests()).To(HaveLen(3))

				Expect(outgoingResponse.Code).To(Equal(http.StatusInternalServerError))
			})
		})

		Context("uploading the file, when the inbound upload request is missing content length", func() {
			BeforeEach(func() {
				incomingRequest.ContentLength = -1
			})

			It("does not make the request to CC", func() {
				Expect(fakeCloudController.ReceivedRequests()).To(HaveLen(0))
			})

			It("responds with 411", func() {
				Expect(outgoingResponse.Code).To(Equal(http.StatusLengthRequired))
			})
		})

		Context("when CC returns a non-succesful status code", func() {
			BeforeEach(func() {
				postStatusCode = http.StatusForbidden
			})

			It("makes the request to CC", func() {
				Expect(fakeCloudController.ReceivedRequests()).To(HaveLen(1))
			})

			It("responds with the status code from the CC request", func() {
				Expect(outgoingResponse.Code).To(Equal(http.StatusForbidden))

				data, err := ioutil.ReadAll(outgoingResponse.Body)
				Expect(err).NotTo(HaveOccurred())
				Expect(string(data)).To(ContainSubstring(strconv.Itoa(http.StatusForbidden)))
			})
		})
	})

	Describe("Uploading Build Artifacts", func() {
		BeforeEach(func() {
			var err error

			fakeCloudController.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/staging/buildpack_cache/app-guid/upload"),
				ghttp.VerifyBasicAuth("bob", "password"),
				ghttp.RespondWithPtr(&postStatusCode, &postResponseBody),
				func(w http.ResponseWriter, r *http.Request) {
					uploadedHeaders = r.Header
					file, fileHeader, err := r.FormFile(ccclient.FormField)
					Expect(err).NotTo(HaveOccurred())
					uploadedBytes, err = ioutil.ReadAll(file)
					Expect(err).NotTo(HaveOccurred())
					uploadedFileName = fileHeader.Filename
					Expect(r.ContentLength).To(BeNumerically(">", len(uploadedBytes)))
				},
			))

			uploadURL, err = url.Parse(fakeCloudController.URL())
			Expect(err).NotTo(HaveOccurred())

			uploadURL.User = url.UserPassword("bob", "password")
Example #27
0
func TestPGWireAuth(t *testing.T) {
	defer leaktest.AfterTest(t)()

	s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
	defer s.Stopper().Stop()
	{
		unicodeUser := "♫"

		t.Run("RootUserAuth", func(t *testing.T) {
			// Authenticate as root with certificate and expect success.
			rootPgURL, cleanupFn := sqlutils.PGUrl(
				t, s.ServingAddr(), "TestPGWireAuth", url.User(security.RootUser))
			defer cleanupFn()
			if err := trivialQuery(rootPgURL); err != nil {
				t.Fatal(err)
			}

			// Create server.TestUser with a unicode password and a user with a
			// unicode username for later tests.
			// Only root is allowed to create users.
			db, err := gosql.Open("postgres", rootPgURL.String())
			if err != nil {
				t.Fatal(err)
			}
			defer db.Close()

			if _, err := db.Exec(fmt.Sprintf("CREATE USER %s;", server.TestUser)); err != nil {
				t.Fatal(err)
			}

			if _, err := db.Exec(fmt.Sprintf("CREATE USER %s WITH PASSWORD '蟑♫螂';", unicodeUser)); err != nil {
				t.Fatal(err)
			}
		})
		t.Run("UnicodeUserAuth", func(t *testing.T) {
			// Try to perform authentication with unicodeUser and no password.
			// This case is equivalent to supplying a wrong password.
			host, port, err := net.SplitHostPort(s.ServingAddr())
			if err != nil {
				t.Fatal(err)
			}
			unicodeUserPgURL := url.URL{
				Scheme:   "postgres",
				User:     url.User(unicodeUser),
				Host:     net.JoinHostPort(host, port),
				RawQuery: "sslmode=require",
			}
			if err := trivialQuery(unicodeUserPgURL); !testutils.IsError(err, "pq: invalid password") {
				t.Fatalf("unexpected error: %v", err)
			}

			// Supply correct password.
			unicodeUserPgURL.User = url.UserPassword(unicodeUser, "蟑♫螂")
			if err := trivialQuery(unicodeUserPgURL); err != nil {
				t.Fatal(err)
			}
		})
	}

	t.Run("TestUserAuth", func(t *testing.T) {
		testUserPgURL, cleanupFn := sqlutils.PGUrl(
			t, s.ServingAddr(), "TestPGWireAuth", url.User(server.TestUser))
		defer cleanupFn()
		// No password supplied but valid certificate should result in
		// successful authentication.
		if err := trivialQuery(testUserPgURL); err != nil {
			t.Fatal(err)
		}

		// Test case insensitivity for certificate and password authentication.
		testUserPgURL.User = url.User("TesTUser")
		if err := trivialQuery(testUserPgURL); err != nil {
			t.Fatal(err)
		}

		// Remove certificates to default to password authentication.
		testUserPgURL.RawQuery = "sslmode=require"

		// Even though the correct password is supplied (empty string), this
		// should fail because we do not support password authentication for
		// users with empty passwords.
		if err := trivialQuery(testUserPgURL); !testutils.IsError(err, "pq: invalid password") {
			t.Fatalf("unexpected error: %v", err)
		}
	})
}