func MakeWorkflowHandlers(workflow string, requestID string, nodeID string) []http.HandlerFunc {
	taskStubData := []byte(fmt.Sprintf("[{\"injectableName\": \"Task.BOSH.%s.Node.%s\"}]", workflow, requestID))
	workflowStubData := []byte(fmt.Sprintf("[{\"injectableName\": \"Graph.BOSH.%sNode.%s\"}]", workflow, requestID))
	nodeStubData := []byte(`{"obmSettings": [{"service": "fake-obm-service"}]}`)
	completedWorkflowResponse := []byte(fmt.Sprintf("{\"id\": \"%s\", \"_status\": \"succeeded\"}", requestID))

	return []http.HandlerFunc{
		ghttp.VerifyRequest("PUT", "/api/1.1/workflows/tasks"),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/api/1.1/workflows/tasks/library"),
			ghttp.RespondWith(http.StatusOK, taskStubData),
		),
		ghttp.VerifyRequest("PUT", "/api/1.1/workflows"),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/api/1.1/workflows/library"),
			ghttp.RespondWith(http.StatusOK, workflowStubData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/nodes/%s", nodeID)),
			ghttp.RespondWith(http.StatusOK, nodeStubData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("POST", fmt.Sprintf("/api/1.1/nodes/%s/workflows/", nodeID)),
			ghttp.RespondWith(http.StatusCreated, completedWorkflowResponse),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/workflows/%s", requestID)),
			ghttp.RespondWith(http.StatusOK, completedWorkflowResponse),
		),
	}
}
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
}
func CreateServer(manifest string, deployments []models.IndexDeployment) *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, `{"user_authentication":{"type":"basic"}}`),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWithJSONEncoded(200, deployments),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments/cf-warden-diego"),
			ghttp.RespondWithJSONEncoded(200, diegoDeployment),
		),
	)

	return server
}
Example #4
0
func listStoriesHandler(trackerToken string) http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("GET", "/services/v5/projects/1234/stories"),
		ghttp.VerifyHeaderKV("X-TrackerToken", trackerToken),
		ghttp.RespondWith(http.StatusOK, Fixture("stories.json")),
	)
}
Example #5
0
func NewTestServer(server *ghttp.Server) *ghttp.Server {
	sampleSuccessTokenStringFormat := `{"access_token":"%s","token_type":"bearer","refresh_token":"%s","expires_in":599,"scope":"password.write cloud_controller.write openid cloud_controller.read","jti":"%s"}`
	loginTokenResponse := fmt.Sprintf(sampleSuccessTokenStringFormat, "access-token", "refresh-token", "jti")
	aiBasicResponse, _ := ioutil.ReadFile("fixtures/ai_basic_response.json")
	aiInfoHandler := ghttp.RespondWith(http.StatusOK, aiBasicResponse)
	aiDeleteHandler := ghttp.RespondWith(http.StatusNoContent, "")
	aiInfoPath, _ := regexp.Compile("/v2/apps/.*/instances")
	aiDeletePath, _ := regexp.Compile("/v2/apps/.*/instances/.*")
	server.RouteToHandler("GET", aiInfoPath, aiInfoHandler)
	server.RouteToHandler("DELETE", aiDeletePath, aiDeleteHandler)
	server.RouteToHandler("POST", "/oauth/token", ghttp.RespondWith(http.StatusOK, "{}"))
	server.AppendHandlers(
		ghttp.RespondWith(http.StatusOK, loginTokenResponse),
	)
	return server
}
Example #6
0
func RespondWithProto(message proto.Message) http.HandlerFunc {
	data, err := proto.Marshal(message)
	Expect(err).ToNot(HaveOccurred())

	var headers = make(http.Header)
	headers["Content-Type"] = []string{"application/x-protobuf"}
	return ghttp.RespondWith(200, string(data), headers)
}
func verifyPollingRequest(jobGuid, status string, timeClicker chan time.Time) http.HandlerFunc {
	return ghttp.CombineHandlers(
		ghttp.VerifyRequest("GET", urljoiner.Join("/v2/jobs/", jobGuid)),
		ghttp.RespondWith(http.StatusOK, pollingResponseBody(jobGuid, status, "")),
		func(w http.ResponseWriter, r *http.Request) {
			timeClicker <- time.Now()
		},
	)
}
func Create401Server() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWith(401, "Not authorized"),
		),
	)

	return server
}
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
}
func MakeTryReservationHandlers(requestID string, nodeID string, expectedNodesPath string, expectedNodeCatalogPath string) []http.HandlerFunc {
	expectedNodes := LoadNodes(expectedNodesPath)
	expectedNodesData, err := json.Marshal(expectedNodes)
	Expect(err).ToNot(HaveOccurred())
	var expectedNode rackhdapi.Node
	for n := range expectedNodes {
		if expectedNodes[n].ID == nodeID {
			expectedNode = expectedNodes[n]
		}
	}
	Expect(expectedNode).ToNot(BeNil())
	expectedNodeData, err := json.Marshal(expectedNode)
	Expect(err).ToNot(HaveOccurred())
	expectedNodeCatalog := LoadNodeCatalog(expectedNodeCatalogPath)
	expectedNodeCatalogData, err := json.Marshal(expectedNodeCatalog)
	Expect(err).ToNot(HaveOccurred())

	reservationHandlers := []http.HandlerFunc{
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/api/common/nodes"),
			ghttp.RespondWith(http.StatusOK, expectedNodesData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/nodes/%s/catalogs/ohai", nodeID)),
			ghttp.RespondWith(http.StatusOK, expectedNodeCatalogData),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/1.1/nodes/%s/workflows/active", nodeID)),
			ghttp.RespondWith(http.StatusOK, nil),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", fmt.Sprintf("/api/common/nodes/%s", nodeID)),
			ghttp.RespondWith(http.StatusOK, expectedNodeData),
		),
	}

	return append(reservationHandlers, MakeWorkflowHandlers("Reserve", requestID, nodeID)...)
}
func Create401Server() *ghttp.Server {
	server := ghttp.NewServer()
	server.AppendHandlers(
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/info"),
			ghttp.RespondWithJSONEncoded(200, `{"user_authentication":{"type":"basic"}}`),
		),
		ghttp.CombineHandlers(
			ghttp.VerifyRequest("GET", "/deployments"),
			ghttp.RespondWith(401, "Not authorized"),
		),
	)

	return server
}
Example #12
0
				}),
			),
		)
		atcServer.RouteToHandler("POST", "/api/v1/builds",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("POST", "/api/v1/builds"),
				VerifyPlan(expectedPlan),
				func(w http.ResponseWriter, r *http.Request) {
					http.SetCookie(w, &http.Cookie{
						Name:    "Some-Cookie",
						Value:   "some-cookie-data",
						Path:    "/",
						Expires: time.Now().Add(1 * time.Minute),
					})
				},
				ghttp.RespondWith(201, `{"id":128}`),
			),
		)
		atcServer.RouteToHandler("GET", "/api/v1/builds/128/events",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/api/v1/builds/128/events"),
				func(w http.ResponseWriter, r *http.Request) {
					flusher := w.(http.Flusher)

					w.Header().Add("Content-Type", "text/event-stream; charset=utf-8")
					w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
					w.Header().Add("Connection", "keep-alive")

					w.WriteHeader(http.StatusOK)

					flusher.Flush()
Example #13
0
		Context("when the pipeline name is specified", func() {
			var (
				path string
				err  error
			)
			BeforeEach(func() {
				path, err = atc.Routes.CreatePathForRoute(atc.PausePipeline, rata.Params{"pipeline_name": "awesome-pipeline"})
				Expect(err).NotTo(HaveOccurred())
			})

			Context("when the pipeline exists", func() {
				BeforeEach(func() {
					atcServer.AppendHandlers(
						ghttp.CombineHandlers(
							ghttp.VerifyRequest("PUT", path),
							ghttp.RespondWith(http.StatusOK, nil),
						),
					)
				})

				It("pauses the pipeline", func() {
					flyCmd := exec.Command(flyPath, "-t", atcServer.URL(), "pause-pipeline", "-p", "awesome-pipeline")

					sess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)
					Expect(err).NotTo(HaveOccurred())

					Eventually(sess).Should(gbytes.Say(`paused 'awesome-pipeline'`))

					<-sess.Exited
					Expect(sess.ExitCode()).To(Equal(0))
					Expect(atcServer.ReceivedRequests()).To(HaveLen(1))
		Expect(err).ToNot(HaveOccurred())

		client = &http.Client{
			Transport: &http.Transport{},
			Jar:       cookieJar,
		}
	})

	Describe("GET /auth/:provider", func() {
		var redirectTarget *ghttp.Server
		var request *http.Request
		var response *http.Response

		BeforeEach(func() {
			redirectTarget = ghttp.NewServer()
			redirectTarget.RouteToHandler("GET", "/", ghttp.RespondWith(http.StatusOK, "sup"))

			var err error

			request, err = http.NewRequest("GET", server.URL, nil)
			Expect(err).NotTo(HaveOccurred())
		})

		JustBeforeEach(func() {
			var err error

			response, err = client.Do(request)
			Expect(err).NotTo(HaveOccurred())
		})

		Context("to a known provider", func() {
Example #15
0
				Expect(err).ToNot(HaveOccurred())

				sseEvent := sse.Event{
					Name: event.Action,
					Data: routeString,
				}

				headers := make(http.Header)
				headers.Set("Content-Type", "text/event-stream; charset=utf-8")

				command := buildCommand("events", flags, []string{})

				server.SetHandler(0,
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v1/events"),
						ghttp.RespondWith(http.StatusOK, sseEvent.Encode(), headers),
					),
				)

				session := routeRegistrar(command...)

				eventString, err := json.Marshal(event)
				Expect(err).ToNot(HaveOccurred())
				eventString = append(eventString, '\n')

				Eventually(session, "2s").Should(Exit(0))
				Expect(server.ReceivedRequests()).To(HaveLen(1))
				Expect(string(session.Out.Contents())).To(ContainSubstring(string(eventString)))
			})

			It("emits an error message on server termination", func() {
Example #16
0
					"execution_metadata": "execution-metadata-3",
					"health_check_timeout_in_seconds": 123456,
					"etag": "3.1"
				}`,
		}

		fakeCC.RouteToHandler("GET", "/internal/bulk/apps",
			ghttp.RespondWith(200, `{
					"token": {},
					"fingerprints": [
							{
								"process_guid": "process-guid-1",
								"etag": "1.1"
							},
							{
								"process_guid": "process-guid-2",
								"etag": "2.1"
							},
							{
								"process_guid": "process-guid-3",
								"etag": "3.1"
							}
					]
				}`),
		)

		fakeCC.RouteToHandler("POST", "/internal/bulk/apps",
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				var processGuids []string
				decoder := json.NewDecoder(req.Body)
				err := decoder.Decode(&processGuids)
Example #17
0
		configRepo.SetApiEndpoint(ccServer.URL())

		gateway := net.NewCloudControllerGateway(configRepo, time.Now, &testterm.FakeUI{})
		repo = NewCloudControllerServiceKeyRepository(configRepo, gateway)
	})

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

	Describe("CreateServiceKey", func() {
		It("tries to create the service key", func() {
			ccServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/v2/service_keys"),
					ghttp.RespondWith(http.StatusCreated, nil),
					ghttp.VerifyJSON(`{"service_instance_guid": "fake-instance-guid", "name": "fake-key-name"}`),
				),
			)

			err := repo.CreateServiceKey("fake-instance-guid", "fake-key-name", nil)
			Expect(err).NotTo(HaveOccurred())
			Expect(ccServer.ReceivedRequests()).To(HaveLen(1))
		})

		Context("when the service key exists", func() {
			BeforeEach(func() {
				ccServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("POST", "/v2/service_keys"),
						ghttp.RespondWith(http.StatusBadRequest, `{"code":360001,"description":"The service key name is taken: exist-service-key"}`),
Example #18
0
				context := map[string]interface{}{
					"id": "test",
				}
				Expect(env.HandleEvent("test_event", context)).To(Succeed())
				Expect(context["person"]).ToNot(BeNil())
			})
		})

		Context("When extension URL uses http:// protocol", func() {
			It("should download and run the extension", func() {
				server := ghttp.NewServer()
				server.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/extension.yaml"),
					ghttp.RespondWith(200, `tasks:
                         - vars:
                             person: John
                         `),
				))

				extension, err := schema.NewExtension(map[string]interface{}{
					"id":   "test_extension",
					"url":  server.URL() + "/extension.yaml",
					"path": ".*",
				})
				Expect(err).ToNot(HaveOccurred())
				extensions := []*schema.Extension{extension}
				env := gohanscript.NewEnvironment(timelimit)
				Expect(env.LoadExtensionsForPath(extensions, "test_path")).To(Succeed())

				context := map[string]interface{}{
					"id": "test",
Example #19
0
		c = &client.JSONClient{
			BaseURL: server.URL(),
		}

		route = "/some/route"
	})
	AfterEach(func() {
		server.Close()
	})

	Describe("Get", func() {
		BeforeEach(func() {
			serverHandler = ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", route),
				ghttp.RespondWith(http.StatusOK, `{ "SomeResponseField": "some value" }`),
			)
			server.AppendHandlers(serverHandler)
		})

		It("should make a get request to the given route", func() {
			err := c.Get(route, &responseStruct)
			Expect(err).NotTo(HaveOccurred())
			Expect(server.ReceivedRequests()).To(HaveLen(1))
			Expect(responseStruct.SomeResponseField).To(Equal("some value"))
		})

		Context("when the request cannot be created", func() {
			It("should return an error", func() {
				err := c.Get("%%%", &responseStruct)
				Expect(err).To(MatchError(ContainSubstring("parse")))
			cid := "vm-5678"
			metadata := map[string]interface{}{
				"stuff":  "definitely",
				"thing1": 3563456,
				"thing2": "bloop",
			}

			var metadataInput bosh.MethodArguments
			metadataInput = append(metadataInput, cid)
			metadataInput = append(metadataInput, metadata)

			expectedNodes := helpers.LoadNodes("../spec_assets/dummy_all_nodes_are_vms.json")
			expectedNodesData, err := json.Marshal(expectedNodes)
			Expect(err).ToNot(HaveOccurred())

			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/api/common/nodes"),
					ghttp.RespondWith(http.StatusOK, expectedNodesData),
				),
				ghttp.VerifyRequest("PATCH", fmt.Sprintf("/api/common/nodes/%s", id)),
			)

			err = cpi.SetVMMetadata(cpiConfig, metadataInput)
			Expect(err).ToNot(HaveOccurred())

			Expect(server.ReceivedRequests()).To(HaveLen(2))
		})
	})
})
Example #21
0
		}, &logger)

		server = ghttp.NewServer()
	})

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

	Describe("Post/PostCustomized", func() {
		It("makes a POST request with given payload", func() {
			server.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("POST", "/path"),
					ghttp.VerifyBody([]byte("post-request")),
					ghttp.RespondWith(http.StatusOK, []byte("post-response")),
				),
			)

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

			response, err := httpClient.Post(url, []byte("post-request"))
			Expect(err).ToNot(HaveOccurred())

			defer response.Body.Close()

			responseBody, err := ioutil.ReadAll(response.Body)
			Expect(err).ToNot(HaveOccurred())

			Expect(responseBody).To(Equal([]byte("post-response")))
			Expect(response.StatusCode).To(Equal(200))
		configRepo = testconfig.NewRepositoryWithDefaults()
		configRepo.SetAPIEndpoint(ccServer.URL())
		gateway := net.NewCloudControllerGateway(configRepo, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter), "")
		repo = environmentvariablegroups.NewCloudControllerRepository(configRepo, gateway)
	})

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

	Describe("ListRunning", func() {
		BeforeEach(func() {
			ccServer.AppendHandlers(
				ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/v2/config/environment_variable_groups/running"),
					ghttp.RespondWith(http.StatusOK, `{ "abc": 123, "do-re-mi": "fa-sol-la-ti" }`),
				),
			)
		})

		It("lists the environment variables in the running group", func() {
			envVars, err := repo.ListRunning()
			Expect(err).NotTo(HaveOccurred())

			Expect(envVars).To(ConsistOf([]models.EnvironmentVariable{
				{Name: "abc", Value: "123"},
				{Name: "do-re-mi", Value: "fa-sol-la-ti"},
			}))
		})
	})
Example #23
0
	// Perform the test by running main() with the command line args set
	It("Errors non-existing tunnels", func() {
		resp, err := http.Get(wstunUrl + "/_token/badtokenbadtoken/hello")
		Ω(err).ShouldNot(HaveOccurred())
		respBody, err := ioutil.ReadAll(resp.Body)
		Ω(err).ShouldNot(HaveOccurred())
		Ω(string(respBody)).Should(ContainSubstring("long time"))
		Ω(resp.Header.Get("Content-Type")).Should(ContainSubstring("text/plain"))
		Ω(resp.StatusCode).Should(Equal(404))
	})

	It("Reconnects the websocket", func() {
		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/hello"),
				ghttp.RespondWith(200, `WORLD`,
					http.Header{"Content-Type": []string{"text/world"}}),
			),
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/hello"),
				ghttp.RespondWith(200, `AGAIN`,
					http.Header{"Content-Type": []string{"text/world"}}),
			),
		)

		// first request
		resp, err := http.Get(wstunUrl + "/_token/" + wstunToken + "/hello")
		Ω(err).ShouldNot(HaveOccurred())
		respBody, err := ioutil.ReadAll(resp.Body)
		Ω(err).ShouldNot(HaveOccurred())
		Ω(string(respBody)).Should(Equal("WORLD"))
		Ω(resp.Header.Get("Content-Type")).Should(Equal("text/world"))
		Context("when call to receptor fails", func() {
			It("should return the error", func() {
				err := errors.New("error")
				fakeReceptorClient.GetVersionReturns(receptor.VersionResponse{}, err)

				_, actualError := versionManager.ServerVersions("")
				Expect(actualError).To(Equal(err))
			})
		})
	})

	Describe("#SyncLTC", func() {
		It("should download ltc from the target and swap it with ltc", func() {
			fakeServer.RouteToHandler("GET", "/v1/sync/amiga/ltc", ghttp.CombineHandlers(
				ghttp.RespondWith(200, []byte{0x01, 0x02, 0x03}, http.Header{
					"Content-Type":   []string{"application/octet-stream"},
					"Content-Length": []string{"3"},
				}),
			))

			tmpFile, err := ioutil.TempFile("", "")
			Expect(err).NotTo(HaveOccurred())
			defer os.Remove(tmpFile.Name())

			fakeFileSwapper.GetTempFileReturns(tmpFile, nil)

			versionManager.SyncLTC(ltcTempFile.Name(), "amiga", config)

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

			Expect(fakeFileSwapper.GetTempFileCallCount()).To(Equal(1))
Example #25
0
			Nofile:     rlimits.Nofile,
			Nproc:      rlimits.Nproc,
			Rss:        rlimits.Rss,
			Rtprio:     rlimits.Rtprio,
			Sigpending: rlimits.Sigpending,
			Stack:      rlimits.Stack,
		}
	})

	Describe("Ping", func() {
		Context("when the response is successful", func() {
			BeforeEach(func() {
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/ping"),
						ghttp.RespondWith(200, "{}"),
					),
				)
			})

			It("should ping the server", func() {
				err := connection.Ping()
				Ω(err).ShouldNot(HaveOccurred())
			})
		})

		Context("when the request fails", func() {
			BeforeEach(func() {
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/ping"),
Example #26
0
	AfterEach(func() {
		wstuncli.Stop()
		wstunsrv.Stop()
		server.Close()
	})

	It("Respects x-host header", func() {
		wstuncli = cliStart("http://localhost:123", `http://127\.0\.0\.[0-9]:[0-9]+`)
		server.AppendHandlers(
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/hello"),
				func(w http.ResponseWriter, req *http.Request) {
					Ω(req.Header.Get("Host")).Should(Equal(""))
					Ω(req.Host).Should(Equal(strings.TrimPrefix(server.URL(), "http://")))
				},
				ghttp.RespondWith(200, `HOSTED`,
					http.Header{"Content-Type": []string{"text/world"}}),
			),
		)

		req, err := http.NewRequest("GET", wstunUrl+"/_token/"+wstunToken+"/hello", nil)
		Ω(err).ShouldNot(HaveOccurred())
		req.Header.Set("X-Host", server.URL())
		resp, err := http.DefaultClient.Do(req)
		Ω(err).ShouldNot(HaveOccurred())
		respBody, err := ioutil.ReadAll(resp.Body)
		Ω(err).ShouldNot(HaveOccurred())
		Ω(string(respBody)).Should(Equal("HOSTED"))
		Ω(resp.Header.Get("Content-Type")).Should(Equal("text/world"))
	})

	It("Rejects partial host regexp matches", func() {
Example #27
0
					"authorization_endpoint":"https://login.APISERVER",
					"token_endpoint":"https://uaa.APISERVER",
					"min_cli_version":null,
					"min_recommended_cli_version":null,
					"api_version":"2.59.0",
					"app_ssh_endpoint":"ssh.APISERVER",
					"app_ssh_host_key_fingerprint":"a6:d1:08:0b:b0:cb:9b:5f:c4:ba:44:2a:97:26:19:8a",
					"app_ssh_oauth_client":"ssh-proxy",
					"logging_endpoint":"wss://loggregator.APISERVER",
					"doppler_logging_endpoint":"wss://doppler.APISERVER"
				}`
				response = strings.Replace(response, "APISERVER", serverAPIURL, -1)
				server.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/v2/info"),
						ghttp.RespondWith(http.StatusOK, response),
					),
				)
			})

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

			It("falls back to http and gives a warning", func() {
				command := exec.Command("cf", "api", server.URL(), "--skip-ssl-validation")
				session, err := Start(command, GinkgoWriter, GinkgoWriter)
				Expect(err).NotTo(HaveOccurred())

				Eventually(session.Out).Should(Say("Setting api endpoint to %s...", server.URL()))
				Eventually(session.Out).Should(Say("Warning: Insecure http API endpoint detected: secure https API endpoints are recommended"))
Example #28
0
		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"`
				}

				errResponse := new(apiErrResponse)
				request, _ := ccGateway.NewRequest("GET", config.APIEndpoint()+"/v2/some-endpoint", config.AccessToken(), nil)
				_, apiErr := ccGateway.PerformRequestForJSONResponse(request, errResponse)
Example #29
0
					Data: []ui.TableRow{
						{{Contents: "early-handle"}, {Contents: "git-repo"}, {Contents: "pipeline-name"}, {Contents: "get"}, {Contents: "123"}, {Contents: "worker-name-1"}},
						{{Contents: "handle-1"}, {Contents: "git-repo"}, {Contents: "pipeline-name"}, {Contents: "check"}, {Contents: "none", Color: color.New(color.Faint)}, {Contents: "worker-name-1"}},
						{{Contents: "other-handle"}, {Contents: "unit-tests"}, {Contents: "pipeline-name"}, {Contents: "task"}, {Contents: "122"}, {Contents: "worker-name-2"}},
					},
				}))

				Expect(flyCmd).To(HaveExited(0))
			})
		})

		Context("and the api returns an internal server error", func() {
			BeforeEach(func() {
				atcServer.AppendHandlers(
					ghttp.CombineHandlers(
						ghttp.VerifyRequest("GET", "/api/v1/containers"),
						ghttp.RespondWith(500, ""),
					),
				)
			})

			It("writes an error message to stderr", func() {
				sess, err := gexec.Start(flyCmd, nil, nil)
				Expect(err).ToNot(HaveOccurred())
				Eventually(sess.Err).Should(gbytes.Say("Unexpected Response"))
				Eventually(sess).Should(gexec.Exit(1))
			})
		})
	})
})
Example #30
0
			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() {
			_, err := authRepo.Authorize("auth-token")
			Expect(err).NotTo(HaveOccurred())
			Expect(uaaServer.ReceivedRequests()).To(HaveLen(1))
		})