func CreateUaaProtectedServer(manifest string, deployments []models.IndexDeployment, uaaEndpoint string) *ghttp.Server {
	yaml, err := ioutil.ReadFile(manifest)
	Expect(err).ToNot(HaveOccurred())

	diegoDeployment := models.ShowDeployment{
		Manifest: string(yaml),
	}
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/info"),
			ghttp.RespondWith(200, fmt.Sprintf(`{"user_authentication":{"type":"uaa","options":{"url":"%s"}}}`, uaaEndpoint)),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer the token"}}),
			ghttp.RespondWithJSONEncoded(200, deployments),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments/cf-warden-diego"),
			ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer the token"}}),
			ghttp.RespondWithJSONEncoded(200, diegoDeployment),
		),
	)
	return server
}
Exemplo n.º 2
0
func verifyTrackerToken() http.HandlerFunc {
	headers := http.Header{
		"X-TrackerToken": {"api-token"},
	}

	return ghttp.VerifyHeader(headers)
}
Exemplo n.º 3
0
			responseBody, err := ioutil.ReadAll(response.Body)
			Expect(err).ToNot(HaveOccurred())

			Expect(responseBody).To(Equal([]byte("post-response")))
			Expect(response.StatusCode).To(Equal(200))

			Expect(server.ReceivedRequests()).To(HaveLen(1))
		})

		It("allows to override request including payload", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/path"),
					ghttp.VerifyBody([]byte("post-request-override")),
					ghttp.VerifyHeader(http.Header{
						"X-Custom": []string{"custom"},
					}),
					ghttp.RespondWith(http.StatusOK, []byte("post-response")),
				),
			)

			url := server.URL() + "/path"

			setHeaders := func(r *http.Request) {
				r.Header.Add("X-Custom", "custom")
				r.Body = ioutil.NopCloser(bytes.NewBufferString("post-request-override"))
				r.ContentLength = 21
			}

			response, err := httpClient.PostCustomized(url, []byte("post-request"), setHeaders)
			Expect(err).ToNot(HaveOccurred())
Exemplo n.º 4
0
		BeforeEach(func() {
			server = ghttp.NewServer()
			authServer = ghttp.NewServer()
			token = uuid.NewUUID().String()
			responseBody := &token_fetcher.Token{
				AccessToken: token,
				ExpireTime:  20,
			}

			authServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/oauth/token"),
					ghttp.VerifyBasicAuth("some-name", "some-secret"),
					ghttp.VerifyContentType("application/x-www-form-urlencoded; charset=UTF-8"),
					ghttp.VerifyHeader(http.Header{
						"Accept": []string{"application/json; charset=utf-8"},
					}),
					verifyBody("grant_type=client_credentials"),
					ghttp.RespondWithJSONEncoded(http.StatusOK, responseBody),
				))

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/v1/routes"),
					ghttp.VerifyHeader(http.Header{
						"Authorization": []string{"bearer " + token},
					}),
					ghttp.RespondWithJSONEncoded(http.StatusOK, nil),
				),
			)
Exemplo n.º 5
0
			config    core_config.ReadWriter
			authRepo  AuthenticationRepository
		)

		BeforeEach(func() {
			uaaServer = ghttp.NewServer()
			config = testconfig.NewRepository()
			config.SetAuthenticationEndpoint(uaaServer.URL())
			config.SetSSHOAuthClient("ssh-oauth-client")

			gateway = net.NewUAAGateway(config, &testterm.FakeUI{})
			authRepo = NewUAAAuthenticationRepository(gateway, config)

			uaaServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyHeader(http.Header{"authorization": []string{"auth-token"}}),
					ghttp.VerifyRequest("GET", "/oauth/authorize",
						"response_type=code&grant_type=authorization_code&client_id=ssh-oauth-client",
					),
					ghttp.RespondWith(http.StatusFound, ``, http.Header{
						"Location": []string{"https://www.cloudfoundry.example.com?code=F45jH"},
					}),
				),
			)
		})

		AfterEach(func() {
			uaaServer.Close()
		})

		It("requests the one time code", func() {
Exemplo n.º 6
0
		BeforeEach(func() {
			ccServer = ghttp.NewServer()
			config.SetAPIEndpoint(ccServer.URL())
		})

		AfterEach(func() {
			ccServer.Close()
		})

		Context("When CC response with an api error", func() {
			BeforeEach(func() {
				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/some-endpoint"),
						ghttp.VerifyHeader(http.Header{
							"accept": []string{"application/json"},
						}),
						ghttp.RespondWith(http.StatusUnauthorized, `{
  "code": 10003,
  "description": "You are not authorized to perform the requested action",
  "error_code": "CF-NotAuthorized"
}`),
					),
				)
			})

			It("tries to unmarshal error response into provided resource", func() {
				type apiErrResponse struct {
					Code        int    `json:"code,omitempty"`
					Description string `json:"description,omitempty"`
				}
Exemplo n.º 7
0
			fakeUAA.RouteToHandler("POST", "/oauth/token", ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/oauth/token"),
				ghttp.VerifyBasicAuth("amandaplease", "password1"),
				ghttp.VerifyContentType("application/x-www-form-urlencoded"),
				ghttp.VerifyFormKV("grant_type", "authorization_code"),
				ghttp.VerifyFormKV("code", "abc123"),
				ghttp.RespondWithJSONEncoded(http.StatusOK, authenticators.UAAAuthTokenResponse{
					AccessToken: "proxy-token",
					TokenType:   "bearer",
				}),
			))

			fakeCC.RouteToHandler("GET", "/internal/apps/60f0f26e-86b3-4487-8f19-9e94f848f3d2/ssh_access/99", ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/internal/apps/60f0f26e-86b3-4487-8f19-9e94f848f3d2/ssh_access/99"),
				ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer proxy-token"}}),
				ghttp.RespondWithJSONEncoded(http.StatusOK, authenticators.AppSSHResponse{
					ProcessGuid: processGuid,
				}),
			))
		})

		It("provides the access code to the UAA and and gets an access token", func() {
			client, err := ssh.Dial("tcp", address, clientConfig)
			Expect(err).NotTo(HaveOccurred())

			client.Close()

			Expect(fakeUAA.ReceivedRequests()).To(HaveLen(1))
		})
Exemplo n.º 8
0
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/ghttp"
	"github.com/robdimsdale/wl"
	"github.com/robdimsdale/wl/oauth"
)

var _ = Describe("client - Root operations", func() {
	Describe("getting root", func() {
		It("performs GET requests with correct headers to /root", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/root"),
					ghttp.VerifyHeader(http.Header{
						"X-Access-Token": []string{dummyAccessToken},
						"X-Client-ID":    []string{dummyClientID},
					}),
				),
			)

			client.Root()

			Expect(server.ReceivedRequests()).Should(HaveLen(1))
		})

		Context("when the request is valid", func() {
			It("returns successfully", func() {
				expectedRoot := wl.Root{ID: 2345}

				// Marshal and unmarshal to ensure exact object is returned
				// - this avoids odd behavior with the time fields
		})

		It("sends one", func() {
			_, err := client.ListReleases()
			Ω(err).ShouldNot(HaveOccurred())
		})
	})

	Context("without an OAuth Token", func() {
		BeforeEach(func() {
			source = Source{
				User:       "******",
				Repository: "concourse",
			}

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/repos/concourse/concourse/releases"),
					ghttp.RespondWith(200, "[]"),
					ghttp.VerifyHeader(http.Header{"Authorization": nil}),
				),
			)
		})

		It("sends one", func() {
			_, err := client.ListReleases()
			Ω(err).ShouldNot(HaveOccurred())
		})
	})
})
Exemplo n.º 10
0
			})
		})

		It("returns a new token", func() {
			responseBody := &Token{
				AccessToken: "the token",
				ExpireTime:  20,
			}

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/oauth/token"),
					ghttp.VerifyBasicAuth("client-name", "client-secret"),
					ghttp.VerifyContentType("application/x-www-form-urlencoded; charset=UTF-8"),
					ghttp.VerifyHeader(http.Header{
						"Accept": []string{"application/json; charset=utf-8"},
					}),
					verifyBody("grant_type=client_credentials"),
					ghttp.RespondWithJSONEncoded(http.StatusOK, responseBody),
				))

			fetcher := NewTokenFetcher(cfg)
			token, err := fetcher.FetchToken()
			Expect(err).NotTo(HaveOccurred())
			Expect(server.ReceivedRequests()).Should(HaveLen(1))
			Expect(token.AccessToken).To(Equal("the token"))
			Expect(token.ExpireTime).To(Equal(20))
		})

		It("logs requests and responses", func() {
			stdout := bytes.NewBuffer([]byte{})
Exemplo n.º 11
0
		var err error
		var event sse.Event

		BeforeEach(func() {
			data, _ := json.Marshal(route1)
			event = sse.Event{
				ID:   "1",
				Name: "Upsert",
				Data: data,
			}

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v1/events"),
					ghttp.VerifyHeader(http.Header{
						"Authorization": []string{"bearer"},
					}),
					func(w http.ResponseWriter, req *http.Request) {
						event.Write(w)
					},
				),
			)
		})

		JustBeforeEach(func() {
			eventSource, err = client.SubscribeToEvents()
		})

		It("Starts an SSE connection to the server", func() {
			Expect(server.ReceivedRequests()).Should(HaveLen(1))
		})
					ghttp.VerifyBasicAuth("diego-ssh", "diego-ssh-secret-$\"^&'"),
					ghttp.VerifyFormKV("grant_type", "authorization_code"),
					ghttp.VerifyFormKV("code", expectedOneTimeCode),
					ghttp.RespondWithJSONEncodedPtr(&uaaTokenResponseCode, uaaTokenResponse),
				),
			)

			sshAccessResponseCode = http.StatusOK
			sshAccessResponse = &authenticators.AppSSHResponse{
				ProcessGuid: "app-guid-app-version",
			}

			fakeCC.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/internal/apps/app-guid/ssh_access/1"),
					ghttp.VerifyHeader(http.Header{"Authorization": []string{"bearer exchanged-token"}}),
					ghttp.RespondWithJSONEncodedPtr(&sshAccessResponseCode, sshAccessResponse),
				),
			)
		})

		It("uses the client password as a one time code with the UAA", func() {
			Expect(fakeUAA.ReceivedRequests()).To(HaveLen(1))
		})

		It("fetches the app from CC using the bearer token", func() {
			Expect(authenErr).NotTo(HaveOccurred())
			Expect(fakeCC.ReceivedRequests()).To(HaveLen(1))
		})

		It("builds permissions from the process guid of the app", func() {
Exemplo n.º 13
0
		It("returns an error when we fail to retrieve the objects from S3", func() {
			fakeServer.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/bucket"),
				ghttp.RespondWith(http.StatusInternalServerError, nil, http.Header{"Content-Type": []string{"application/xml"}}),
			))

			_, err := blobStore.List()
			Expect(err).To(MatchError(ContainSubstring("500 Internal Server Error")))
		})
	})

	Describe("#Upload", func() {
		It("uploads the provided reader into the bucket", func() {
			fakeServer.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("PUT", "/bucket/some-path/some-object"),
				ghttp.VerifyHeader(http.Header{"X-Amz-Acl": []string{"private"}}),
				func(_ http.ResponseWriter, request *http.Request) {
					Expect(ioutil.ReadAll(request.Body)).To(Equal([]byte("some data")))
				},
				ghttp.RespondWith(http.StatusOK, "", http.Header{}),
			))

			Expect(blobStore.Upload("some-path/some-object", strings.NewReader("some data"))).To(Succeed())

			Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
		})

		It("returns an error when S3 fail to receive the object", func() {
			fakeServer.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("PUT", "/bucket/some-path/some-object"),
				ghttp.RespondWith(http.StatusInternalServerError, "", http.Header{}),
Exemplo n.º 14
0
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/ghttp"

	"encoding/base64"
	"fmt"
	"net/http"
	"os"
	"strings"
)

var _ = Describe("sources actions", func() {
	var apiKey string = "abc123"
	var authHeaderValue string = base64.StdEncoding.EncodeToString([]byte(strings.Join([]string{apiKey, ":"}, "")))

	var correctUserAgent = ghttp.VerifyHeader(http.Header{"User-Agent": []string{"imgix-cli v0.1.0"}})
	var correctAuthHeader = ghttp.VerifyHeader(http.Header{"Authorization": []string{"Basic " + authHeaderValue}})

	var app *cli.App

	BeforeEach(func() {
		app = main.NewApp()
		os.Setenv("IMGIX_API_KEY", apiKey)
	})

	AfterEach(func() {
		app = nil
	})

	Describe("#GetSource", func() {
		var server *ghttp.Server
Exemplo n.º 15
0
	client := NewClient(nil, subdomain, apiKey)
	url, _ := url.Parse(server.URL())
	client.BaseURL = url
	client.EventsURL = url

	return &TestEnvironment{
		Server: server,
		Client: client,
	}
}

// verifyContentHeaderHandler is an http.HandlerFunc that verifies that a
// request has the proper values for the 'Accept' and 'Content-Type' headers.
var verifyContentHeaderHandler = ghttp.CombineHandlers(
	ghttp.VerifyHeader(http.Header{
		"Accept": []string{"application/json"},
	}),
	ghttp.VerifyContentType("application/json"),
)

// verifyAuthorizationHeaderHandler is an http.HandlerFunc that verifies that a
// request has the proper values for the 'Authorization' header, so it can
// authenticate with the PagerDuty API.
var verifyAuthorizationHeaderHandler = ghttp.VerifyHeader(http.Header{
	"Authorization": []string{"Token token=" + apiKey},
})

// verifyHeaderHandler is an http.HandlerFunc that verifies for the proper
// headers in a request to the PagerDuty API.
var verifyHeaderHandler = ghttp.CombineHandlers(
	verifyContentHeaderHandler,
Exemplo n.º 16
0
		var password string = "somekillerpassword"
		var apiKey string = "S0m3Ap1K3y"
		var accountId string = "123abc"
		auth := &main.Auth{
			Email:    email,
			Password: password,
		}

		BeforeEach(func() {
			server = ghttp.NewServer()
			main.BaseUrl = server.URL()

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/auth"),
					ghttp.VerifyHeader(http.Header{"User-Agent": []string{"imgix-cli v0.1.0"}}),
					ghttp.VerifyJSON(fmt.Sprintf(`{ "password": "******", "email": "%s" }`, password, email)),
					ghttp.RespondWith(http.StatusOK, fmt.Sprintf(`{
						"account_id": "%s",
						"api_key": "%s",
						"email": "%s"
					}`, accountId, apiKey, email)),
				),
			)
		})

		AfterEach(func() {
			server.Close()
		})

		It("sends off the request", func() {