Beispiel #1
0
func (f *FakeCC) handleBuildArtifactsCacheDownloadRequest(w http.ResponseWriter, r *http.Request) {
	basicAuthVerifier := ghttp.VerifyBasicAuth(CC_USERNAME, CC_PASSWORD)
	basicAuthVerifier(w, r)

	re := regexp.MustCompile("/staging/buildpack_cache/(.*)/download")
	appGuid := re.FindStringSubmatch(r.URL.Path)[1]

	fmt.Fprintf(ginkgo.GinkgoWriter, "[FAKE CC] Received request to download build artifacts cache for app-guid %s\n", appGuid)

	buildArtifactsCache := f.UploadedBuildArtifactsCaches[appGuid]
	if buildArtifactsCache == nil {
		fmt.Fprintf(ginkgo.GinkgoWriter, "[FAKE CC] No matching build artifacts cache for app-guid %s\n", appGuid)

		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte("File Not Found"))
		return
	}

	w.WriteHeader(http.StatusOK)

	contentLength := len(buildArtifactsCache)
	w.Header().Set("Content-Length", strconv.Itoa(contentLength))
	fmt.Fprintf(ginkgo.GinkgoWriter, "[FAKE CC] Responding with build artifacts cache for app-guid %s. Content-Length: %d\n", appGuid, contentLength)

	buffer := bytes.NewBuffer(buildArtifactsCache)
	io.Copy(w, buffer)
}
func CreateOAuthServer() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("POST", "/oauth/token"),
			ghttp.VerifyBasicAuth("bosh_cli", ""),
			ghttp.RespondWith(200, `{"access_token":"the token","expires_in":3600}`,
				http.Header{"Content-Type": []string{"application/json"}}),
		),
	)
	return server
}
Beispiel #3
0
func (f *FakeCC) newHandleStagingRequest() http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("POST", MatchRegexp("/internal/staging/(.*)/completed")),
		ghttp.VerifyBasicAuth(CC_USERNAME, CC_PASSWORD),
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			var msg cc_messages.StagingResponseForCC
			err := json.NewDecoder(r.Body).Decode(&msg)
			Expect(err).NotTo(HaveOccurred())
			r.Body.Close()
			f.lock.Lock()
			defer f.lock.Unlock()
			guid := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/internal/staging/"), "/completed")
			f.stagingGuids = append(f.stagingGuids, guid)
			f.stagingResponses = append(f.stagingResponses, msg)
		}),
		ghttp.RespondWithPtr(&f.stagingResponseStatusCode, &f.stagingResponseBody),
	)
}
Beispiel #4
0
func (f *FakeCC) handleBuildArtifactsCacheUploadRequest(w http.ResponseWriter, r *http.Request) {
	basicAuthVerifier := ghttp.VerifyBasicAuth(CC_USERNAME, CC_PASSWORD)
	basicAuthVerifier(w, r)

	key := getFileUploadKey(r)
	file, _, err := r.FormFile(key)
	Expect(err).NotTo(HaveOccurred())

	uploadedBytes, err := ioutil.ReadAll(file)
	Expect(err).NotTo(HaveOccurred())

	re := regexp.MustCompile("/staging/buildpack_cache/(.*)/upload")
	appGuid := re.FindStringSubmatch(r.URL.Path)[1]

	f.UploadedBuildArtifactsCaches[appGuid] = uploadedBytes
	fmt.Fprintf(ginkgo.GinkgoWriter, "[FAKE CC] Received %d bytes for build artifacts cache for app-guid %s\n", len(uploadedBytes), appGuid)

	w.WriteHeader(http.StatusOK)
}
Beispiel #5
0
	})

	AfterEach(func() {
		if fakeCC.HTTPTestServer != nil {
			fakeCC.Close()
		}
	})

	Describe("Successfully calling the Cloud Controller", func() {
		var expectedBody = []byte(`{ "key": "value" }`)

		BeforeEach(func() {
			fakeCC.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", fmt.Sprintf("/internal/staging/%s/completed", stagingGuid)),
					ghttp.VerifyBasicAuth("username", "password"),
					ghttp.RespondWith(200, `{}`),
					func(w http.ResponseWriter, req *http.Request) {
						body, err := ioutil.ReadAll(req.Body)
						defer req.Body.Close()

						Expect(err).NotTo(HaveOccurred())
						Expect(body).To(Equal(expectedBody))
					},
				),
			)
		})

		It("sends the request payload to the CC without modification", func() {
			err := ccClient.StagingComplete(stagingGuid, expectedBody, logger)
			Expect(err).NotTo(HaveOccurred())
			Expect(config.InsecureSkipVerify).To(BeFalse())
		})
	})

	Describe("Token Acquisition", func() {
		var server *ghttp.Server
		var statusCode int
		var responseBody UAATokenResponse

		BeforeEach(func() {
			server = ghttp.NewTLSServer()
			url, _ = url.Parse(server.URL())
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/oauth/token", "grant_type=client_credentials"),
					ghttp.VerifyBasicAuth("client_id", "client_secret"),
					ghttp.RespondWithJSONEncodedPtr(&statusCode, &responseBody),
				),
			)
			uaaCC, _ = New(url, true, "client_id", "client_secret")
		})

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

		Context("when the request is all good", func() {
			BeforeEach(func() {
				statusCode = http.StatusOK
				responseBody = UAATokenResponse{
					AccessToken: "test_token",
		registrationPath = "/organizations/testorg/devices"
		registrar = newIotfHttpRegistrar(&credentials, "test")

	})

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

	Describe("registerDevice", func() {
		It("sends credentials", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", registrationPath),
					ghttp.VerifyBasicAuth("testuser", "testpass"),
					ghttp.RespondWith(http.StatusCreated, nil, nil),
				),
			)
			err := registrar.registerDevice("")
			Expect(err).To(Succeed())
		})

		It("POSTs the device information", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", registrationPath),
					ghttp.VerifyJSON(`{"id":"123456789", "type": "test"}`),
					ghttp.RespondWith(http.StatusCreated, nil, nil),
				),
			)
Beispiel #8
0
				Expect(err).To(MatchError(ContainSubstring("ssh: handshake failed")))
				Expect(fakeBBS.ReceivedRequests()).To(HaveLen(0))
			})
		})
	})

	Describe("authenticating with the cf realm with a one time code", func() {
		BeforeEach(func() {
			clientConfig = &ssh.ClientConfig{
				User: "******",
				Auth: []ssh.AuthMethod{ssh.Password("abc123")},
			}

			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,
				}),
		)

		BeforeEach(func() {
			metadata.UserReturns("cf:app-guid/1")
			password = []byte(expectedOneTimeCode)

			uaaTokenResponseCode = http.StatusOK
			uaaTokenResponse = &authenticators.UAAAuthTokenResponse{
				AccessToken: "exchanged-token",
				TokenType:   "bearer",
			}

			fakeUAA.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/oauth/token"),
					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.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"text/xml"}}),
				))

				config.SetBlobStore(serverHost, serverPort, "", "")
				authorized, err := verifier.Verify(config)
				Expect(err).NotTo(HaveOccurred())
				Expect(authorized).To(BeTrue())

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

		Context("when the DAV blob store requires auth", func() {
			It("should return authorized for proper credentials", func() {
				fakeServer.RouteToHandler("PROPFIND", "/blobs/", ghttp.CombineHandlers(
					ghttp.VerifyBasicAuth("good-user", "good-pass"),
					ghttp.VerifyHeaderKV("Depth", "1"),
					ghttp.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"text/xml"}}),
				))

				config.SetBlobStore(serverHost, serverPort, "good-user", "good-pass")
				authorized, err := verifier.Verify(config)
				Expect(err).NotTo(HaveOccurred())
				Expect(authorized).To(BeTrue())

				Expect(fakeServer.ReceivedRequests()).To(HaveLen(1))
			})
			It("should return unauthorized for invalid credentials", func() {
				fakeServer.RouteToHandler("PROPFIND", "/blobs/",
					ghttp.CombineHandlers(
						ghttp.VerifyBasicAuth("bad-user", "bad-pass"),
		)

		BeforeEach(func() {
			metadata.UserReturns("cf:app-guid/1")
			password = []byte(expectedOneTimeCode)

			uaaTokenResponseCode = http.StatusOK
			uaaTokenResponse = &authenticators.UAAAuthTokenResponse{
				AccessToken: "exchanged-token",
				TokenType:   "bearer",
			}

			fakeUAA.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/oauth/token"),
					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"}}),
			})
		})

		Context("when the ops manager being created is targeting a foundation which uses PEM keys for auth", func() {
			var (
				server   *ghttp.Server
				fakeUser = "******"
				fakePass = "******"
			)

			BeforeEach(func() {
				fileBytes, _ := ioutil.ReadFile("../../fixtures/installation-settings-1-6-aws.json")
				server = ghttp.NewTLSServer()
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyBasicAuth(fakeUser, fakePass),
						ghttp.RespondWith(http.StatusOK, string(fileBytes[:])),
					),
				)
			})

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

			It("then it should return a opsmanager which has an executer which uses a pem", func() {
				opsManager, err := new(OpsManagerBuilder).New(tileregistry.TileSpec{
					OpsManagerHost:   strings.Replace(server.URL(), "https://", "", 1),
					AdminUser:        fakeUser,
					AdminPass:        fakePass,
					OpsManagerUser:   "******",
	})

	Describe("UploadDroplet", func() {
		var (
			timeClicker chan time.Time
			startTime   time.Time
			endTime     time.Time
		)

		BeforeEach(func() {
			var err error

			timeClicker = make(chan time.Time, 4)
			fakeCloudController.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/staging/droplet/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())
			slUsername = os.Getenv("SL_USERNAME")
			slAPIKey = os.Getenv("SL_API_KEY")
			client = slclient.NewHttpClient(slUsername, slAPIKey, server.Addr(), "templates", false)
		})

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

		Context("#DoRawHttpRequest", func() {
			Context("when a successful request", func() {
				BeforeEach(func() {
					server.CloseClientConnections()
					server.AppendHandlers(
						ghttp.VerifyRequest("GET", "/test"),
						ghttp.VerifyBasicAuth(slUsername, slAPIKey),
					)
				})

				It("make a request to access /test", func() {
					client.DoRawHttpRequest("test", "GET", bytes.NewBufferString("random text"))
					Ω(err).ShouldNot(HaveOccurred())
					Ω(server.ReceivedRequests()).Should(HaveLen(1))
				})
			})
		})
	})

	Context("when the target HTTP server is not stable", func() {
		BeforeEach(func() {
			os.Setenv("SL_API_RETRY_COUNT", "10")
Beispiel #15
0
							<-sess.Exited

							Expect(sess).To(gbytes.Say("pipeline-1"))

							Expect(sess.ExitCode()).To(Equal(0))
						})
					})
				})
			})

			Context("when a Basic method is chosen", func() {
				BeforeEach(func() {
					atcServer.AppendHandlers(
						ghttp.CombineHandlers(
							ghttp.VerifyRequest("GET", "/api/v1/auth/token"),
							ghttp.VerifyBasicAuth("some_username", "some_password"),
							ghttp.RespondWithJSONEncoded(200, atc.AuthToken{
								Type:  "Bearer",
								Value: "some-token",
							}),
						),
					)
				})

				It("asks for username and password for basic methods", func() {
					sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
					Expect(err).NotTo(HaveOccurred())

					Eventually(sess.Out).Should(gbytes.Say("1. Basic"))
					Eventually(sess.Out).Should(gbytes.Say("2. OAuth Type 1"))
					Eventually(sess.Out).Should(gbytes.Say("3. OAuth Type 2"))
Beispiel #16
0
						  <D:collection/>
						</D:resourcetype>
					  </D:prop>
					  <D:status>HTTP/1.1 200 OK</D:status>
					</D:propstat>
				  </D:response>
				</D:multistatus>
			`

			responseBodyA = strings.Replace(responseBodyA, "http://192.168.11.11:8444", fakeServer.URL(), -1)
			responseBodyB = strings.Replace(responseBodyB, "http://192.168.11.11:8444", fakeServer.URL(), -1)
			responseBodyC = strings.Replace(responseBodyC, "http://192.168.11.11:8444", fakeServer.URL(), -1)

			fakeServer.RouteToHandler("PROPFIND", "/blobs", ghttp.CombineHandlers(
				ghttp.VerifyHeaderKV("Depth", "1"),
				ghttp.VerifyBasicAuth("user", "pass"),
				ghttp.RespondWith(207, responseBodyRoot, http.Header{"Content-Type": []string{"application/xml"}}),
			))

			fakeServer.RouteToHandler("PROPFIND", "/blobs/a", ghttp.CombineHandlers(
				ghttp.VerifyHeaderKV("Depth", "1"),
				ghttp.VerifyBasicAuth("user", "pass"),
				ghttp.RespondWith(207, responseBodyA, http.Header{"Content-Type": []string{"application/xml"}}),
			))

			fakeServer.RouteToHandler("PROPFIND", "/blobs/b", ghttp.CombineHandlers(
				ghttp.VerifyHeaderKV("Depth", "1"),
				ghttp.VerifyBasicAuth("user", "pass"),
				ghttp.RespondWith(207, responseBodyB, http.Header{"Content-Type": []string{"application/xml"}}),
			))
Beispiel #17
0
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(Equal("status code: 400, body: you messed up"))
				Expect(server.ReceivedRequests()).Should(HaveLen(1))
			})
		})

		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))
		})
			token      string
		)

		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),
Beispiel #19
0
		JustBeforeEach(func() {
			resultsChan, errorsChan = fetcher.FetchFingerprints(logger, cancel, httpClient)
		})

		AfterEach(func() {
			Eventually(resultsChan).Should(BeClosed())
			Eventually(errorsChan).Should(BeClosed())
		})

		Context("when retrieving fingerprints", func() {
			BeforeEach(func() {
				fakeCC.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/internal/bulk/apps", "batch_size=2&format=fingerprint&token={}"),
						ghttp.VerifyBasicAuth("the-username", "the-password"),
						ghttp.RespondWith(200, `{
						"token": {"id":"the-token-id"},
						"fingerprints": [
							{
								"process_guid": "process-guid-1",
								"etag": "1234567.890"
							},
							{
								"process_guid": "process-guid-2",
								"etag": "2345678.901"
							}
						]
					}`),
					),
					ghttp.CombineHandlers(