func errorHandler(statusCode int, body []byte) error {
	response := errorResponse{}
	err := json.Unmarshal(body, &response)
	if err != nil {
		return errors.NewHttpError(http.StatusInternalServerError, "", "")
	}

	return errors.NewHttpError(statusCode, response.Name, response.Message)
}
Exemplo n.º 2
0
func (repo *FakeAppInstancesRepo) GetInstances(appGuid string) (instances []models.AppInstanceFields, apiErr error) {
	repo.GetInstancesAppGuid = appGuid

	if len(repo.GetInstancesResponses) > 0 {
		instances = repo.GetInstancesResponses[0]

		if len(repo.GetInstancesResponses) > 1 {
			repo.GetInstancesResponses = repo.GetInstancesResponses[1:]
		}
	}

	if len(repo.GetInstancesErrorCodes) > 0 {
		errorCode := repo.GetInstancesErrorCodes[0]

		// don't slice away the last one if this is all we have
		if len(repo.GetInstancesErrorCodes) > 1 {
			repo.GetInstancesErrorCodes = repo.GetInstancesErrorCodes[1:]
		}

		if errorCode != "" {
			apiErr = errors.NewHttpError(400, errorCode, "Error staging app")
		}
	}

	return
}
Exemplo n.º 3
0
func (repo *FakeOrgRepository) Create(name string) (apiErr error) {
	if repo.CreateOrgExists {
		apiErr = errors.NewHttpError(400, errors.ORG_EXISTS, "Space already exists")
		return
	}
	repo.CreateName = name
	return
}
Exemplo n.º 4
0
func (repo *FakeBuildpackRepository) Create(name string, position *int, enabled *bool, locked *bool) (createdBuildpack models.Buildpack, apiErr error) {
	if repo.CreateBuildpackExists {
		return repo.CreateBuildpack, errors.NewHttpError(400, errors.BUILDPACK_EXISTS, "Buildpack already exists")
	}

	repo.CreateBuildpack = models.Buildpack{Name: name, Position: position, Enabled: enabled, Locked: locked}
	return repo.CreateBuildpack, repo.CreateApiResponse
}
Exemplo n.º 5
0
func (repo *FakeServiceBindingRepo) Create(instanceGuid, appGuid string) (apiErr error) {
	repo.CreateServiceInstanceGuid = instanceGuid
	repo.CreateApplicationGuid = appGuid

	if repo.CreateErrorCode != "" {
		apiErr = errors.NewHttpError(400, repo.CreateErrorCode, "Error binding service")
	}

	return
}
Exemplo n.º 6
0
func (repo *FakeSpaceRepository) Create(name string, orgGuid string) (space models.Space, apiErr error) {
	if repo.CreateSpaceExists {
		apiErr = errors.NewHttpError(400, errors.SPACE_EXISTS, "Space already exists")
		return
	}
	repo.CreateSpaceName = name
	repo.CreateSpaceOrgGuid = orgGuid
	space = repo.CreateSpaceSpace
	return
}
Exemplo n.º 7
0
func (repo *FakePasswordRepo) UpdatePassword(old string, new string) (apiErr error) {
	repo.UpdateOldPassword = old
	repo.UpdateNewPassword = new

	if repo.UpdateUnauthorized {
		apiErr = errors.NewHttpError(401, "unauthorized", "Authorization Failed")
	}

	return
}
Exemplo n.º 8
0
func (repo *FakeAppSummaryRepo) GetSummary(appGuid string) (summary models.Application, apiErr error) {
	repo.GetSummaryAppGuid = appGuid
	summary = repo.GetSummarySummary

	if repo.GetSummaryErrorCode != "" {
		apiErr = errors.NewHttpError(400, repo.GetSummaryErrorCode, "Error")
	}

	return
}
Exemplo n.º 9
0
func cloudControllerErrorHandler(statusCode int, body []byte) error {
	response := ccErrorResponse{}
	json.Unmarshal(body, &response)

	if response.Code == 1000 { // MAGICKAL NUMBERS AHOY
		return errors.NewInvalidTokenError(response.Description)
	} else {
		return errors.NewHttpError(statusCode, strconv.Itoa(response.Code), response.Description)
	}
}
Exemplo n.º 10
0
func (repo *FakeUserRepository) Create(username, password string) (apiErr error) {
	repo.CreateUserUsername = username
	repo.CreateUserPassword = password

	if repo.CreateUserReturnsHttpError {
		apiErr = errors.NewHttpError(403, "403", "Forbidden")
	}
	if repo.CreateUserExists {
		apiErr = errors.NewModelAlreadyExistsError("User", username)
	}

	return
}
Exemplo n.º 11
0
func (repo *FakeServiceBindingRepo) Create(instanceGuid, appGuid string, paramsMap map[string]interface{}) (apiErr error) {
	repo.CreateServiceInstanceGuid = instanceGuid
	repo.CreateApplicationGuid = appGuid
	repo.CreateParams = paramsMap

	if repo.CreateNonHttpErrCode != "" {
		apiErr = errors.New(repo.CreateNonHttpErrCode)
		return
	}

	if repo.CreateErrorCode != "" {
		apiErr = errors.NewHttpError(400, repo.CreateErrorCode, "Error binding service")
	}

	return
}
Exemplo n.º 12
0
func (repo *FakeAppInstancesRepo) GetInstances(appGuid string) (instances []models.AppInstanceFields, apiErr error) {
	repo.GetInstancesAppGuid = appGuid
	time.Sleep(1 * time.Millisecond) //needed for Windows only, otherwise it thinks error codes are not assigned

	if len(repo.GetInstancesResponses) > 0 {
		instances = repo.GetInstancesResponses[0]
		repo.GetInstancesResponses = repo.GetInstancesResponses[1:]
	}

	if len(repo.GetInstancesErrorCodes) > 0 {
		errorCode := repo.GetInstancesErrorCodes[0]
		repo.GetInstancesErrorCodes = repo.GetInstancesErrorCodes[1:]
		if errorCode != "" {
			apiErr = errors.NewHttpError(400, errorCode, "Error staging app")
		}
	}

	return
}
Exemplo n.º 13
0
func (uaa UAAAuthenticationRepository) getAuthToken(data url.Values) error {
	type uaaErrorResponse struct {
		Code        string `json:"error"`
		Description string `json:"error_description"`
	}

	type AuthenticationResponse struct {
		AccessToken  string           `json:"access_token"`
		TokenType    string           `json:"token_type"`
		RefreshToken string           `json:"refresh_token"`
		Error        uaaErrorResponse `json:"error"`
	}

	path := fmt.Sprintf("%s/oauth/token", uaa.config.AuthenticationEndpoint())
	request, err := uaa.gateway.NewRequest("POST", path, "Basic "+base64.StdEncoding.EncodeToString([]byte("cf:")), strings.NewReader(data.Encode()))
	if err != nil {
		return errors.NewWithError(T("Failed to start oauth request"), err)
	}
	request.HttpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	response := new(AuthenticationResponse)
	_, err = uaa.gateway.PerformRequestForJSONResponse(request, &response)

	switch err.(type) {
	case nil:
	case errors.HttpError:
		return err
	case *errors.InvalidTokenError:
		return errors.New(T("Authentication has expired.  Please log back in to re-authenticate.\n\nTIP: Use `cf login -a <endpoint> -u <user> -o <org> -s <space>` to log back in and re-authenticate."))
	default:
		return errors.NewWithError(T("auth request failed"), err)
	}

	// TODO: get the actual status code
	if response.Error.Code != "" {
		return errors.NewHttpError(0, response.Error.Code, response.Error.Description)
	}

	uaa.config.SetAccessToken(fmt.Sprintf("%s %s", response.TokenType, response.AccessToken))
	uaa.config.SetRefreshToken(response.RefreshToken)

	return nil
}
Exemplo n.º 14
0
				[]string{"instances: 1/1"},
				[]string{"usage: 1G x 1 instances"},
				[]string{"urls: fake-route-host.fake-route-domain-name"},
				[]string{"last uploaded: Thu Nov 19 01:00:15 UTC 2015"},
				[]string{"stack: fake-stack-name"},
				// buildpack tested separately
				[]string{"#0", "running", "2015-11-19 01:01:17 AM", "25.0%", "24M of 32M", "1G of 2G"},
			))
		})

		Context("when getting the application summary fails because the app is stopped", func() {
			BeforeEach(func() {
				getAppSummaryModel.RunningInstances = 0
				getAppSummaryModel.InstanceCount = 1
				getAppSummaryModel.State = "stopped"
				appSummaryRepo.GetSummaryReturns(getAppSummaryModel, errors.NewHttpError(400, errors.APP_STOPPED, "error"))
			})

			It("prints appropriate output", func() {
				cmd.Execute(flagContext)
				Expect(ui.Outputs).To(ContainSubstrings(
					[]string{"Showing health and status", "fake-app-name", "my-org", "my-space", "my-user"},
					[]string{"state", "stopped"},
					[]string{"instances", "0/1"},
					[]string{"usage", "1G x 1 instances"},
					[]string{"There are no running instances of this app."},
				))
			})
		})

		Context("when getting the application summary fails because the app has not yet finished staged", func() {
					Context("when binding the route service succeeds", func() {
						BeforeEach(func() {
							routeServiceBindingRepo.BindReturns(nil)
						})

						It("says OK", func() {
							Expect(ui.Outputs).To(ContainSubstrings(
								[]string{"OK"},
							))
						})
					})

					Context("when binding the route service fails because it is already bound", func() {
						BeforeEach(func() {
							routeServiceBindingRepo.BindReturns(errors.NewHttpError(http.StatusOK, errors.ROUTE_ALREADY_BOUND_TO_SAME_SERVICE, "http-err"))
						})

						It("says OK", func() {
							Expect(ui.Outputs).To(ContainSubstrings(
								[]string{"OK"},
							))
						})
					})

					Context("when binding the route service fails for any other reason", func() {
						BeforeEach(func() {
							routeServiceBindingRepo.BindReturns(errors.New("bind-err"))
						})

						It("fails with the error", func() {
Exemplo n.º 16
0
						Path:    "/v2/service_instances",
						Matcher: testnet.RequestBodyMatcher(`{"name":"my-service","service_plan_guid":"different-plan-guid","space_guid":"my-space-guid","async":true}`),
						Response: testnet.TestResponse{
							Status: http.StatusBadRequest,
							Body:   `{"code":60002,"description":"The service instance name is taken: my-service"}`,
						}}),
					findServiceInstanceReq,
					serviceOfferingReq)
			})

			It("fails if the plan is different", func() {
				err := repo.CreateServiceInstance("my-service", "different-plan-guid")

				Expect(testHandler).To(testnet.HaveAllRequestsCalled())
				Expect(err).To(HaveOccurred())
				Expect(err).To(BeAssignableToTypeOf(errors.NewHttpError(400, "", "")))
			})
		})
	})

	Describe("finding service instances by name", func() {
		It("returns the service instance", func() {
			setupTestServer(findServiceInstanceReq, serviceOfferingReq)

			instance, err := repo.FindInstanceByName("my-service")

			Expect(testHandler).To(testnet.HaveAllRequestsCalled())
			Expect(err).NotTo(HaveOccurred())

			Expect(instance.Name).To(Equal("my-service"))
			Expect(instance.Guid).To(Equal("my-service-instance-guid"))
Exemplo n.º 17
0
					[]string{"Binding service", "global-service", "app1", "my-org", "my-space", "my-user"},
					[]string{"OK"},
					[]string{"Creating", "app2"},
					[]string{"OK"},
					[]string{"Binding service", "app2-service", "app2", "my-org", "my-space", "my-user"},
					[]string{"OK"},
					[]string{"Binding service", "global-service", "app2", "my-org", "my-space", "my-user"},
					[]string{"OK"},
				))
			})
		})

		Context("when the app is already bound to the service", func() {
			BeforeEach(func() {
				appRepo.ReadReturns.App = maker.NewApp(maker.Overrides{})
				serviceBinder.BindApplicationReturns.Error = errors.NewHttpError(500, "90003", "it don't work")
			})

			It("gracefully continues", func() {
				callPush()
				Expect(len(serviceBinder.AppsToBind)).To(Equal(4))
				Expect(ui.Outputs).ToNot(ContainSubstrings([]string{"FAILED"}))
			})
		})

		Context("when the service instance can't be found", func() {
			BeforeEach(func() {
				//				routeRepo.FindByHostAndDomainReturns.Error = errors.new("can't find service instance")
				serviceRepo.FindInstanceByNameErr = true
				manifestRepo.ReadManifestReturns.Manifest = manifestWithServicesAndEnv()
			})
Exemplo n.º 18
0
package net

import (
	"encoding/json"

	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/errors"
	"github.com/cloudfoundry/cli/cf/terminal"
)

type uaaErrorResponse struct {
	Code        string `json:"error"`
	Description string `json:"error_description"`
}

var uaaErrorHandler = func(statusCode int, body []byte) error {
	response := uaaErrorResponse{}
	json.Unmarshal(body, &response)

	if response.Code == "invalid_token" {
		return errors.NewInvalidTokenError(response.Description)
	}

	return errors.NewHttpError(statusCode, response.Code, response.Description)
}

func NewUAAGateway(config core_config.Reader, ui terminal.UI) Gateway {
	return newGateway(uaaErrorHandler, config, ui)
}
Exemplo n.º 19
0
	Context("when logged in and provided the name of an org to create", func() {
		BeforeEach(func() {
			orgRepo.CreateReturns(nil)
			requirementsFactory.LoginSuccess = true
		})

		It("creates an org", func() {
			runCommand("my-org")

			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Creating org", "my-org", "my-user"},
				[]string{"OK"},
			))
			Expect(orgRepo.CreateArgsForCall(0)).To(Equal("my-org"))
		})

		It("fails and warns the user when the org already exists", func() {
			err := errors.NewHttpError(400, errors.ORG_EXISTS, "org already exists")
			orgRepo.CreateReturns(err)
			runCommand("my-org")

			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Creating org", "my-org"},
				[]string{"OK"},
				[]string{"my-org", "already exists"},
			))
		})
	})
})
Exemplo n.º 20
0
	Context("when creating the user returns an error", func() {
		It("prints a warning when the given user already exists", func() {
			userRepo.CreateReturns(errors.NewModelAlreadyExistsError("User", "my-user"))

			runCommand("my-user", "my-password")

			Expect(ui.WarnOutputs).To(ContainSubstrings(
				[]string{"already exists"},
			))

			Expect(ui.Outputs).ToNot(ContainSubstrings([]string{"FAILED"}))
		})

		It("fails when any error other than alreadyExists is returned", func() {
			userRepo.CreateReturns(errors.NewHttpError(403, "403", "Forbidden"))

			runCommand("my-user", "my-password")

			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Forbidden"},
			))

			Expect(ui.Outputs).To(ContainSubstrings([]string{"FAILED"}))

		})
	})

	It("fails when no arguments are passed", func() {
		Expect(runCommand()).To(BeFalse())
	})
Exemplo n.º 21
0
			It("creates the quota with paid service plans allowed", func() {
				runCommand("--allow-paid-service-plans", "my-for-profit-quota")
				Expect(quotaRepo.CreateArgsForCall(0).NonBasicServicesAllowed).To(BeTrue())
			})
		})

		Context("when creating a quota returns an error", func() {
			It("alerts the user when creating the quota fails", func() {
				quotaRepo.CreateReturns(errors.New("WHOOP THERE IT IS"))
				runCommand("my-quota")

				Expect(ui.Outputs).To(ContainSubstrings(
					[]string{"Creating space quota", "my-quota", "my-org"},
					[]string{"FAILED"},
				))
			})

			It("warns the user when quota already exists", func() {
				quotaRepo.CreateReturns(errors.NewHttpError(400, "240002", "Quota Definition is taken: quota-sct"))
				runCommand("Banana")

				Expect(ui.Outputs).ToNot(ContainSubstrings(
					[]string{"FAILED"},
				))
				Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"already exists"}))
			})

		})
	})
})
Exemplo n.º 22
0
		Context("when the API returns an error", func() {
			Context("some sort of awful terrible error that we were not prescient enough to anticipate", func() {
				It("fails loudly", func() {
					securityGroupRepo.CreateReturns(errors.New("Wops I failed"))
					runCommand("my-group")

					Expect(ui.Outputs).To(ContainSubstrings(
						[]string{"Creating security group", "my-group"},
						[]string{"FAILED"},
					))
				})
			})

			Context("when the group already exists", func() {
				It("warns the user when group already exists", func() {
					securityGroupRepo.CreateReturns(errors.NewHttpError(400, "300005", "The security group is taken: my-group"))
					runCommand("my-group")

					Expect(ui.Outputs).ToNot(ContainSubstrings([]string{"FAILED"}))
					Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"already exists"}))
				})
			})
		})

		Context("when the user specifies a space that does not exist", func() {
			It("Fails", func() {
				runCommand(
					"-space",
					"space-does-not-exist",
					"why-would-this-ever-work",
				)
Exemplo n.º 23
0
	var mutex = &sync.Mutex{}

	getInstance := func(appGuid string) (instances []models.AppInstanceFields, apiErr error) {
		if len(defaultInstanceResponses) > 0 {
			instances = defaultInstanceResponses[0]
			if len(defaultInstanceResponses) > 1 {
				defaultInstanceResponses = defaultInstanceResponses[1:]
			}
		}
		if len(defaultInstanceErrorCodes) > 0 {
			errorCode := defaultInstanceErrorCodes[0]
			if len(defaultInstanceErrorCodes) > 1 {
				defaultInstanceErrorCodes = defaultInstanceErrorCodes[1:]
			}
			if errorCode != "" {
				apiErr = errors.NewHttpError(400, errorCode, "Error staging app")
			}
		}
		return
	}

	AfterEach(func() {
		command_registry.Register(OriginalAppCommand)
	})

	BeforeEach(func() {
		deps = command_registry.NewDependency()
		ui = new(testterm.FakeUI)
		requirementsFactory = &testreq.FakeReqFactory{}

		configRepo = testconfig.NewRepository()
Exemplo n.º 24
0
			[]string{"TIP"},
		))

		name, orgGUID, _ := spaceRepo.CreateArgsForCall(0)
		Expect(name).To(Equal("my-space"))
		Expect(orgGUID).To(Equal("my-org-guid"))

		userGuid, spaceGuid, orgGuid, role := userRepo.SetSpaceRoleByGuidArgsForCall(0)
		Expect(userGuid).To(Equal("my-user-guid"))
		Expect(spaceGuid).To(Equal("my-space-guid"))
		Expect(orgGuid).To(Equal("my-org-guid"))
		Expect(role).To(Equal(models.SPACE_MANAGER))
	})

	It("warns the user when a space with that name already exists", func() {
		spaceRepo.CreateReturns(models.Space{}, errors.NewHttpError(400, errors.SPACE_EXISTS, "Space already exists"))
		runCommand("my-space")

		Expect(ui.Outputs).To(ContainSubstrings(
			[]string{"Creating space", "my-space"},
			[]string{"OK"},
		))
		Expect(ui.WarnOutputs).To(ContainSubstrings([]string{"my-space", "already exists"}))
		Expect(ui.Outputs).ToNot(ContainSubstrings(
			[]string{"Assigning", "my-user", "my-space", models.SpaceRoleToUserInput[models.SPACE_MANAGER]},
		))

		Expect(spaceRepo.CreateCallCount()).To(Equal(1))
		actualSpaceName, _, _ := spaceRepo.CreateArgsForCall(0)
		Expect(actualSpaceName).To(Equal("my-space"))
		Expect(userRepo.SetSpaceRoleByGuidCallCount()).To(BeZero())
			Expect(ui.FailedWithUsage).To(BeTrue())
		})
	})

	Describe("when logged in", func() {
		BeforeEach(func() {
			requirementsFactory.LoginSuccess = true
		})

		It("Sets the running environment variable group", func() {
			runCommand(`{"abc":"123", "def": "456"}`)

			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Setting the contents of the running environment variable group as my-user..."},
				[]string{"OK"},
			))
			Expect(environmentVariableGroupRepo.SetRunningArgsForCall(0)).To(Equal(`{"abc":"123", "def": "456"}`))
		})

		It("Fails with a reasonable message when invalid JSON is passed", func() {
			environmentVariableGroupRepo.SetRunningReturns(cf_errors.NewHttpError(400, cf_errors.PARSE_ERROR, "Request invalid due to parse error"))
			runCommand(`{"abc":"123", "invalid : "json"}`)
			Expect(ui.Outputs).To(ContainSubstrings(
				[]string{"Setting the contents of the running environment variable group as my-user..."},
				[]string{"FAILED"},
				[]string{`Your JSON string syntax is invalid.  Proper syntax is this:  cf set-running-environment-variable-group '{"name":"value","name":"value"}'`},
			))
		})
	})
})
Exemplo n.º 26
0
				Context("when unbinding the route service succeeds", func() {
					BeforeEach(func() {
						routeServiceBindingRepo.UnbindReturns(nil)
					})

					It("says OK", func() {
						Expect(ui.Outputs).To(ContainSubstrings(
							[]string{"OK"},
						))
					})
				})

				Context("when unbinding the route service fails because it was not bound", func() {
					BeforeEach(func() {
						routeServiceBindingRepo.UnbindReturns(errors.NewHttpError(http.StatusOK, errors.ROUTE_WAS_NOT_BOUND, "http-err"))
					})

					It("says OK", func() {
						Expect(ui.Outputs).To(ContainSubstrings(
							[]string{"OK"},
						))
					})

					It("warns", func() {
						Expect(ui.Outputs).To(ContainSubstrings(
							[]string{"Route", "was not bound to service instance"},
						))
					})
				})