func unmarshalChangeResourceRecordSetsError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	responseBody, err := ioutil.ReadAll(r.HTTPResponse.Body)

	if err != nil {
		r.Error = awserr.New("SerializationError", "failed to read Route53 XML error response", err)
		return
	}

	baseError := &baseXMLErrorResponse{}

	if err := xml.Unmarshal(responseBody, baseError); err != nil {
		r.Error = awserr.New("SerializationError", "failed to decode Route53 XML error response", err)
		return
	}

	switch baseError.XMLName.Local {
	case "InvalidChangeBatch":
		unmarshalInvalidChangeBatchError(r, responseBody)
	default:
		r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader(responseBody))
		restxml.UnmarshalError(r)
	}
}
Beispiel #2
0
// UnmarshalError unmarshals a response error for the REST JSON protocol.
func UnmarshalError(r *request.Request) {
	code := r.HTTPResponse.Header.Get("X-Amzn-Errortype")
	bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body)
	if err != nil {
		r.Error = awserr.New("SerializationError", "failed reading REST JSON error response", err)
		return
	}
	if len(bodyBytes) == 0 {
		r.Error = awserr.NewRequestFailure(
			awserr.New("SerializationError", r.HTTPResponse.Status, nil),
			r.HTTPResponse.StatusCode,
			"",
		)
		return
	}
	var jsonErr jsonErrorResponse
	if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
		r.Error = awserr.New("SerializationError", "failed decoding REST JSON error response", err)
		return
	}

	if code == "" {
		code = jsonErr.Code
	}

	code = strings.SplitN(code, ":", 2)[0]
	r.Error = awserr.NewRequestFailure(
		awserr.New(code, jsonErr.Message, nil),
		r.HTTPResponse.StatusCode,
		r.RequestID,
	)
}
Beispiel #3
0
func unmarshalError(r *aws.Request) {
	defer r.HTTPResponse.Body.Close()

	if r.HTTPResponse.ContentLength == int64(0) {
		// No body, use status code to generate an awserr.Error
		r.Error = awserr.NewRequestFailure(
			awserr.New(strings.Replace(r.HTTPResponse.Status, " ", "", -1), r.HTTPResponse.Status, nil),
			r.HTTPResponse.StatusCode,
			"",
		)
		return
	}

	resp := &xmlErrorResponse{}
	err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
	if err != nil && err != io.EOF {
		r.Error = awserr.New("SerializationError", "failed to decode S3 XML error response", nil)
	} else {
		r.Error = awserr.NewRequestFailure(
			awserr.New(resp.Code, resp.Message, nil),
			r.HTTPResponse.StatusCode,
			"",
		)
	}
}
// loadProfiles loads from the file pointed to by shared credentials filename for profile.
// The credentials retrieved from the profile will be returned or error. Error will be
// returned if it fails to read from the file, or the data is invalid.
func loadProfile(filename, profile string) (Value, error) {
	config, err := ini.Load(filename)
	if err != nil {
		return Value{}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err)
	}
	iniProfile, err := config.GetSection(profile)
	if err != nil {
		return Value{}, awserr.New("SharedCredsLoad", "failed to get profile", err)
	}

	id, err := iniProfile.GetKey("aws_access_key_id")
	if err != nil {
		return Value{}, awserr.New("SharedCredsAccessKey",
			fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename),
			err)
	}

	secret, err := iniProfile.GetKey("aws_secret_access_key")
	if err != nil {
		return Value{}, awserr.New("SharedCredsSecret",
			fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename),
			nil)
	}

	// Default to empty string if not found
	token := iniProfile.Key("aws_session_token")

	return Value{
		AccessKeyID:     id.String(),
		SecretAccessKey: secret.String(),
		SessionToken:    token.String(),
	}, nil
}
Beispiel #5
0
func TestAfterRetryRefreshCreds(t *testing.T) {
	os.Clearenv()
	credProvider := &mockCredsProvider{}

	svc := awstesting.NewClient(&aws.Config{
		Credentials: credentials.NewCredentials(credProvider),
		MaxRetries:  aws.Int(1),
	})

	svc.Handlers.Clear()
	svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) {
		r.Error = awserr.New("UnknownError", "", nil)
		r.HTTPResponse = &http.Response{StatusCode: 400}
	})
	svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) {
		r.Error = awserr.New("ExpiredTokenException", "", nil)
	})
	svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler)

	assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
	assert.False(t, credProvider.retrieveCalled)

	req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
	req.Send()

	assert.True(t, svc.Config.Credentials.IsExpired())
	assert.False(t, credProvider.retrieveCalled)

	_, err := svc.Config.Credentials.Get()
	assert.NoError(t, err)
	assert.True(t, credProvider.retrieveCalled)
}
func TestConvertFromListError(t *testing.T) {
	// Test that we get an error using ConvertFromList to convert to a map.
	var actual map[string]interface{}
	expected := awserr.New("SerializationError", `v must be a non-nil pointer to an array or slice, got *map[string]interface {}`, nil).Error()
	if err := ConvertFromList(nil, &actual); err == nil {
		t.Errorf("ConvertFromList with input %#v returned no error, expected error `%s`", nil, expected)
	} else if err.Error() != expected {
		t.Errorf("ConvertFromList with input %#v returned error `%s`, expected error `%s`", nil, err, expected)
	}

	// Test that we get an error using ConvertFromList to convert to a struct.
	var actual2 myComplexStruct
	expected = awserr.New("SerializationError", `v must be a non-nil pointer to an array or slice, got *dynamodbattribute.myComplexStruct`, nil).Error()
	if err := ConvertFromList(nil, &actual2); err == nil {
		t.Errorf("ConvertFromList with input %#v returned no error, expected error `%s`", nil, expected)
	} else if err.Error() != expected {
		t.Errorf("ConvertFromList with input %#v returned error `%s`, expected error `%s`", nil, err, expected)
	}

	// Test that we get an error using ConvertFromList to convert to an interface{}.
	var actual3 interface{}
	expected = awserr.New("SerializationError", `v must be a non-nil pointer to an array or slice, got *interface {}`, nil).Error()
	if err := ConvertFromList(nil, &actual3); err == nil {
		t.Errorf("ConvertFromList with input %#v returned no error, expected error `%s`", nil, expected)
	} else if err.Error() != expected {
		t.Errorf("ConvertFromList with input %#v returned error `%s`, expected error `%s`", nil, err, expected)
	}
}
func unmarshalError(req *request.Request) {
	bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body)
	if err != nil {
		req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err)
		return
	}
	if len(bodyBytes) == 0 {
		req.Error = awserr.NewRequestFailure(
			awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")),
			req.HTTPResponse.StatusCode,
			"",
		)
		return
	}
	var jsonErr jsonErrorResponse
	if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
		req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err)
		return
	}
	req.Error = awserr.NewRequestFailure(
		awserr.New(jsonErr.Code, jsonErr.Message, nil),
		req.HTTPResponse.StatusCode,
		"",
	)
}
func unmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	if r.HTTPResponse.ContentLength == int64(0) {
		// No body, use status code to generate an awserr.Error
		r.Error = awserr.NewRequestFailure(
			awserr.New(strings.Replace(r.HTTPResponse.Status, " ", "", -1), r.HTTPResponse.Status, nil),
			r.HTTPResponse.StatusCode,
			"",
		)
		return
	}

	resp := &xmlErrorResponse{}
	err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
	if err != nil && err != io.EOF {
		r.Error = awserr.New("SerializationError", "failed to decode SimpleDB XML error response", nil)
	} else if len(resp.Errors) == 0 {
		r.Error = awserr.New("MissingError", "missing error code in SimpleDB XML error response", nil)
	} else {
		// If there are multiple error codes, return only the first as the aws.Error interface only supports
		// one error code.
		r.Error = awserr.NewRequestFailure(
			awserr.New(resp.Errors[0].Code, resp.Errors[0].Message, nil),
			r.HTTPResponse.StatusCode,
			resp.RequestID,
		)
	}
}
// loadProfiles loads from the file pointed to by shared credentials filename for profile.
// The credentials retrieved from the profile will be returned or error. Error will be
// returned if it fails to read from the file, or the data is invalid.
func loadProfile(filename, profile string) (Value, error) {
	config, err := ini.LoadFile(filename)
	if err != nil {
		return Value{}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err)
	}
	iniProfile := config.Section(profile)

	id, ok := iniProfile["aws_access_key_id"]
	if !ok {
		return Value{}, awserr.New("SharedCredsAccessKey",
			fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename),
			nil)
	}

	secret, ok := iniProfile["aws_secret_access_key"]
	if !ok {
		return Value{}, awserr.New("SharedCredsSecret",
			fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename),
			nil)
	}

	token := iniProfile["aws_session_token"]

	return Value{
		AccessKeyID:     id,
		SecretAccessKey: secret,
		SessionToken:    token,
	}, nil
}
Beispiel #10
0
func unmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	if r.HTTPResponse.StatusCode == http.StatusMovedPermanently {
		r.Error = awserr.New("BucketRegionError",
			fmt.Sprintf("incorrect region, the bucket is not in '%s' region", aws.StringValue(r.Service.Config.Region)), nil)
		return
	}

	if r.HTTPResponse.ContentLength == int64(0) {
		// No body, use status code to generate an awserr.Error
		r.Error = awserr.NewRequestFailure(
			awserr.New(strings.Replace(r.HTTPResponse.Status, " ", "", -1), r.HTTPResponse.Status, nil),
			r.HTTPResponse.StatusCode,
			"",
		)
		return
	}

	resp := &xmlErrorResponse{}
	err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
	if err != nil && err != io.EOF {
		r.Error = awserr.New("SerializationError", "failed to decode S3 XML error response", nil)
	} else {
		r.Error = awserr.NewRequestFailure(
			awserr.New(resp.Code, resp.Message, nil),
			r.HTTPResponse.StatusCode,
			"",
		)
	}
}
func TestChainProviderWithNames(t *testing.T) {
	p := &ChainProvider{
		Providers: []Provider{
			&stubProvider{err: awserr.New("FirstError", "first provider error", nil)},
			&stubProvider{err: awserr.New("SecondError", "second provider error", nil)},
			&secondStubProvider{
				creds: Value{
					AccessKeyID:     "AKIF",
					SecretAccessKey: "NOSECRET",
					SessionToken:    "",
				},
			},
			&stubProvider{
				creds: Value{
					AccessKeyID:     "AKID",
					SecretAccessKey: "SECRET",
					SessionToken:    "",
				},
			},
		},
	}

	creds, err := p.Retrieve()
	assert.Nil(t, err, "Expect no error")
	assert.Equal(t, "secondStubProvider", creds.ProviderName, "Expect provider name to match")

	// Also check credentials
	assert.Equal(t, "AKIF", creds.AccessKeyID, "Expect access key ID to match")
	assert.Equal(t, "NOSECRET", creds.SecretAccessKey, "Expect secret access key to match")
	assert.Empty(t, creds.SessionToken, "Expect session token to be empty")

}
Beispiel #12
0
// UnmarshalError unmarshals an error response for a JSON RPC service.
func UnmarshalError(req *service.Request) {
	defer req.HTTPResponse.Body.Close()
	bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body)
	if err != nil {
		req.Error = awserr.New("SerializationError", "failed reading JSON RPC error response", err)
		return
	}
	if len(bodyBytes) == 0 {
		req.Error = awserr.NewRequestFailure(
			awserr.New("SerializationError", req.HTTPResponse.Status, nil),
			req.HTTPResponse.StatusCode,
			"",
		)
		return
	}
	var jsonErr jsonErrorResponse
	if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
		req.Error = awserr.New("SerializationError", "failed decoding JSON RPC error response", err)
		return
	}

	codes := strings.SplitN(jsonErr.Code, "#", 2)
	req.Error = awserr.NewRequestFailure(
		awserr.New(codes[len(codes)-1], jsonErr.Message, nil),
		req.HTTPResponse.StatusCode,
		"",
	)
}
Beispiel #13
0
func serveTags(tags map[string]string) func(*request.Request) {
	return func(r *request.Request) {
		input, ok := r.Params.(*ec2.DescribeTagsInput)
		if !ok {
			r.Error = awserr.NewRequestFailure(
				awserr.New("UnknownError", "500 Internal Server Error", fmt.Errorf("unsupported request")), 500, "",
			)
			return
		}

		restrictToKey := []*string{}
		for _, filter := range input.Filters {
			switch *filter.Name {
			case "resource-id":
			case "key":
				restrictToKey = filter.Values
			default:
				r.Error = awserr.NewRequestFailure(
					awserr.New("UnknownError", "500 Internal Server Error", fmt.Errorf("unsupported filter %s", *filter.Name)), 500, "",
				)
			}
		}

		data := r.Data.(*ec2.DescribeTagsOutput)
		for key, value := range tags {
			if len(restrictToKey) > 0 && !includesString(restrictToKey, key) {
				continue
			}
			data.Tags = append(data.Tags, &ec2.TagDescription{Key: aws.String(key), Value: aws.String(value)})
		}
	}
}
Beispiel #14
0
func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) {
	// Merge in user provided configuration
	cfg.MergeIn(userCfg)

	// Region if not already set by user
	if len(aws.StringValue(cfg.Region)) == 0 {
		if len(envCfg.Region) > 0 {
			cfg.WithRegion(envCfg.Region)
		} else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
			cfg.WithRegion(sharedCfg.Region)
		}
	}

	// Configure credentials if not already set
	if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
		if len(envCfg.Creds.AccessKeyID) > 0 {
			cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
				envCfg.Creds,
			)
		} else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
			cfgCp := *cfg
			cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
				sharedCfg.AssumeRoleSource.Creds,
			)
			cfg.Credentials = stscreds.NewCredentials(
				&Session{
					Config:   &cfgCp,
					Handlers: handlers.Copy(),
				},
				sharedCfg.AssumeRole.RoleARN,
				func(opt *stscreds.AssumeRoleProvider) {
					opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName

					if len(sharedCfg.AssumeRole.ExternalID) > 0 {
						opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
					}

					// MFA not supported
				},
			)
		} else if len(sharedCfg.Creds.AccessKeyID) > 0 {
			cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
				sharedCfg.Creds,
			)
		} else {
			// Fallback to default credentials provider, include mock errors
			// for the credential chain so user can identify why credentials
			// failed to be retrieved.
			cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{
				VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
				Providers: []credentials.Provider{
					&credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)},
					&credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)},
					defaults.RemoteCredProvider(*cfg, handlers),
				},
			})
		}
	}
}
Beispiel #15
0
func unmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()
	b := &bytes.Buffer{}
	if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil {
		r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata error respose", err)
		return
	}

	// Response body format is not consistent between metadata endpoints.
	// Grab the error message as a string and include that as the source error
	r.Error = awserr.New("EC2MetadataError", "failed to make EC2Metadata request", errors.New(b.String()))
}
Beispiel #16
0
func TestChainProviderWithNoValidProvider(t *testing.T) {
	p := &ChainProvider{
		Providers: []Provider{
			&stubProvider{err: awserr.New("FirstError", "first provider error", nil)},
			&stubProvider{err: awserr.New("SecondError", "second provider error", nil)},
		},
	}

	assert.True(t, p.IsExpired(), "Expect expired with no providers")
	_, err := p.Retrieve()
	assert.Equal(t, ErrNoValidProvidersFoundInChain, err, "Expect no providers error returned")
}
Beispiel #17
0
func unmarshalBody(r *request.Request, v reflect.Value) {
	if field, ok := v.Type().FieldByName("_"); ok {
		if payloadName := field.Tag.Get("payload"); payloadName != "" {
			pfield, _ := v.Type().FieldByName(payloadName)
			if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
				payload := v.FieldByName(payloadName)
				if payload.IsValid() {
					switch payload.Interface().(type) {
					case []byte:
						defer r.HTTPResponse.Body.Close()
						b, err := ioutil.ReadAll(r.HTTPResponse.Body)
						if err != nil {
							r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
						} else {
							payload.Set(reflect.ValueOf(b))
						}
					case *string:
						defer r.HTTPResponse.Body.Close()
						b, err := ioutil.ReadAll(r.HTTPResponse.Body)
						if err != nil {
							r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
						} else {
							str := string(b)
							payload.Set(reflect.ValueOf(&str))
						}
					default:
						switch payload.Type().String() {
						case "io.ReadCloser":
							payload.Set(reflect.ValueOf(r.HTTPResponse.Body))
						case "io.ReadSeeker":
							b, err := ioutil.ReadAll(r.HTTPResponse.Body)
							if err != nil {
								r.Error = awserr.New("SerializationError",
									"failed to read response body", err)
								return
							}
							payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b))))
						default:
							io.Copy(ioutil.Discard, r.HTTPResponse.Body)
							defer r.HTTPResponse.Body.Close()
							r.Error = awserr.New("SerializationError",
								"failed to decode REST response",
								fmt.Errorf("unknown payload type %s", payload.Type()))
						}
					}
				}
			}
		}
	}
}
Beispiel #18
0
// UnmarshalError unmarshals a response error for the EC2 protocol.
func UnmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	resp := &xmlErrorResponse{}
	err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
	if err != nil && err != io.EOF {
		r.Error = awserr.New("SerializationError", "failed decoding EC2 Query error response", err)
	} else {
		r.Error = awserr.NewRequestFailure(
			awserr.New(resp.Code, resp.Message, nil),
			r.HTTPResponse.StatusCode,
			resp.RequestID,
		)
	}
}
Beispiel #19
0
func unmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	var errOut errorOutput
	if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&errOut); err != nil {
		r.Error = awserr.New("SerializationError",
			"failed to decode endpoint credentials",
			err,
		)
	}

	// Response body format is not consistent between metadata endpoints.
	// Grab the error message as a string and include that as the source error
	r.Error = awserr.New(errOut.Code, errOut.Message, nil)
}
Beispiel #20
0
func TestECSServiceResource_Delete_NotActive(t *testing.T) {
	e := new(mockECS)
	p := &ECSServiceResource{
		ecs: e,
	}

	e.On("UpdateService", &ecs.UpdateServiceInput{
		Service:      aws.String("arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web"),
		Cluster:      aws.String("cluster"),
		DesiredCount: aws.Int64(0),
	}).Return(&ecs.UpdateServiceOutput{}, awserr.New("ServiceNotActiveException", "Service was not ACTIVE", errors.New("")))

	id, data, err := p.Provision(ctx, Request{
		RequestType:        Delete,
		PhysicalResourceId: "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web",
		ResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: intValue(1),
		},
		OldResourceProperties: &ECSServiceProperties{
			Cluster:      aws.String("cluster"),
			ServiceName:  aws.String("acme-inc-web"),
			DesiredCount: intValue(1),
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, "arn:aws:ecs:us-east-1:012345678901:service/acme-inc-web", id)
	assert.Nil(t, data)

	e.AssertExpectations(t)
}
Beispiel #21
0
func buildQueryString(query url.Values, v reflect.Value, name string) error {
	switch value := v.Interface().(type) {
	case []*string:
		for _, item := range value {
			query.Add(name, *item)
		}
	case map[string]*string:
		for key, item := range value {
			query.Add(key, *item)
		}
	case map[string][]*string:
		for key, items := range value {
			for _, item := range items {
				query.Add(key, *item)
			}
		}
	default:
		str, err := convertType(v)
		if err == errValueNotSet {
			return nil
		} else if err != nil {
			return awserr.New("SerializationError", "failed to encode REST request", err)
		}
		query.Set(name, str)
	}

	return nil
}
Beispiel #22
0
// Retrieve retrieves credentials from the EC2 service.
// Error will be returned if the request fails, or unable to extract
// the desired credentials.
func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) {
	credsList, err := requestCredList(m.Client)
	if err != nil {
		return credentials.Value{ProviderName: ProviderName}, err
	}

	if len(credsList) == 0 {
		return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil)
	}
	credsName := credsList[0]

	roleCreds, err := requestCred(m.Client, credsName)
	if err != nil {
		return credentials.Value{ProviderName: ProviderName}, err
	}

	m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow)

	return credentials.Value{
		AccessKeyID:     roleCreds.AccessKeyID,
		SecretAccessKey: roleCreds.SecretAccessKey,
		SessionToken:    roleCreds.Token,
		ProviderName:    ProviderName,
	}, nil
}
Beispiel #23
0
func TestScheduler_Remove_NoCFStack(t *testing.T) {
	db := newDB(t)
	defer db.Close()

	x := new(mockS3Client)
	c := new(mockCloudFormationClient)
	s := &Scheduler{
		Template:       template.Must(template.New("t").Parse("{}")),
		Bucket:         "bucket",
		Cluster:        "cluster",
		cloudformation: c,
		s3:             x,
		db:             db,
		after:          fakeAfter,
	}

	_, err := db.Exec(`INSERT INTO stacks (app_id, stack_name) VALUES ($1, $2)`, "c9366591-ab68-4d49-a333-95ce5a23df68", "acme-inc")
	assert.NoError(t, err)

	c.On("DescribeStacks", &cloudformation.DescribeStacksInput{
		StackName: aws.String("acme-inc"),
	}).Return(&cloudformation.DescribeStacksOutput{}, awserr.New("400", "Stack with id acme-inc does not exist", errors.New("")))

	err = s.Remove(context.Background(), "c9366591-ab68-4d49-a333-95ce5a23df68")
	assert.NoError(t, err)

	c.AssertExpectations(t)
	x.AssertExpectations(t)
}
Beispiel #24
0
func TestKinesumerBeginEnd(t *testing.T) {
	k, kin, sssm, prov := makeTestKinesumer(t)
	k.Stream = "c"

	kin.On("DescribeStreamPages", mock.Anything, mock.Anything).Return(awserr.New("bad", "bad", nil)).Once()
	_, err := k.Begin()
	assert.Error(t, err)

	prov.On("TTL").Return(time.Millisecond * 10)
	prov.On("TryAcquire", mock.Anything).Return(nil)
	prov.On("Heartbeat", mock.Anything).Return(nil)
	prov.On("Release", mock.Anything).Return(nil)
	kin.On("DescribeStreamPages", mock.Anything, mock.Anything).Return(awserr.Error(nil))
	sssm.On("Begin", mock.Anything).Return(nil)
	sssm.On("GetStartSequence", mock.Anything).Return("0").Once()
	sssm.On("GetStartSequence", mock.Anything).Return("")
	sssm.On("TryAcquire", mock.Anything).Return(nil)
	kin.On("GetShardIterator", mock.Anything).Return(&kinesis.GetShardIteratorOutput{
		ShardIterator: aws.String("0"),
	}, awserr.Error(nil))
	kin.On("GetRecords", mock.Anything).Return(&kinesis.GetRecordsOutput{
		MillisBehindLatest: aws.Int64(0),
		NextShardIterator:  aws.String("AAAAA"),
		Records:            []*kinesis.Record{},
	}, awserr.Error(nil))
	sssm.On("End").Return()
	_, err = k.Begin()
	assert.Nil(t, err)
	assert.Equal(t, 2, k.nRunning)
	k.End()
}
Beispiel #25
0
func TestSQSDispatcher_Handle_ChangeMessageVisibility(t *testing.T) {
	s := new(mockSQSClient)
	q := &SQSDispatcher{
		VisibilityHeartbeat: defaultVisibilityHeartbeat,
		QueueURL:            "https://sqs.amazonaws.com",
		sqs:                 s,
		after: func(d time.Duration) <-chan time.Time {
			return nil
		},
	}

	awsErr := awserr.New("AccessDenied", "Stack with id acme-inc does not exist", errors.New(""))
	s.On("ChangeMessageVisibility", &sqs.ChangeMessageVisibilityInput{
		QueueUrl:          aws.String("https://sqs.amazonaws.com"),
		VisibilityTimeout: aws.Int64(60),
		ReceiptHandle:     aws.String("MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+CwLj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QEauMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0="),
	}).Return(&sqs.ChangeMessageVisibilityOutput{}, awsErr).Once()

	handle := func(ctx context.Context, message *sqs.Message) error {
		return nil
	}
	err := q.handle(ctx, handle, &sqs.Message{
		ReceiptHandle: aws.String("MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+CwLj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QEauMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0="),
	})
	assert.Equal(t, awsErr, err)

	s.AssertExpectations(t)
}
Beispiel #26
0
func (client *DecryptionClient) cekFromEnvelope(env Envelope, decrypter CipherDataDecrypter) (ContentCipher, error) {
	f, ok := client.CEKRegistry[env.CEKAlg]
	if !ok || f == nil {
		return nil, awserr.New(
			"InvalidCEKAlgorithmError",
			"cek algorithm isn't supported, "+env.CEKAlg,
			nil,
		)
	}

	key, err := base64.StdEncoding.DecodeString(env.CipherKey)
	if err != nil {
		return nil, err
	}

	iv, err := base64.StdEncoding.DecodeString(env.IV)
	if err != nil {
		return nil, err
	}
	key, err = decrypter.DecryptKey(key)
	if err != nil {
		return nil, err
	}

	cd := CipherData{
		Key: key,
		IV:  iv,
	}
	return f(cd)
}
Beispiel #27
0
// Build builds a JSON payload for a JSON RPC request.
func Build(req *service.Request) {
	var buf []byte
	var err error
	if req.ParamsFilled() {
		buf, err = jsonutil.BuildJSON(req.Params)
		if err != nil {
			req.Error = awserr.New("SerializationError", "failed encoding JSON RPC request", err)
			return
		}
	} else {
		buf = emptyJSON
	}

	if req.Service.TargetPrefix != "" || string(buf) != "{}" {
		req.SetBufferBody(buf)
	}

	if req.Service.TargetPrefix != "" {
		target := req.Service.TargetPrefix + "." + req.Operation.Name
		req.HTTPRequest.Header.Add("X-Amz-Target", target)
	}
	if req.Service.JSONVersion != "" {
		jsonVersion := req.Service.JSONVersion
		req.HTTPRequest.Header.Add("Content-Type", "application/x-amz-json-"+jsonVersion)
	}
}
// Retrieve retrieves credentials from the EC2 service.
// Error will be returned if the request fails, or unable to extract
// the desired credentials.
func (m *EC2RoleProvider) Retrieve() (Value, error) {
	if m.Client == nil {
		m.Client = http.DefaultClient
	}
	if m.Endpoint == "" {
		m.Endpoint = metadataCredentialsEndpoint
	}

	credsList, err := requestCredList(m.Client, m.Endpoint)
	if err != nil {
		return Value{}, err
	}

	if len(credsList) == 0 {
		return Value{}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil)
	}
	credsName := credsList[0]

	roleCreds, err := requestCred(m.Client, m.Endpoint, credsName)
	if err != nil {
		return Value{}, err
	}

	m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow)

	return Value{
		AccessKeyID:     roleCreds.AccessKeyID,
		SecretAccessKey: roleCreds.SecretAccessKey,
		SessionToken:    roleCreds.Token,
	}, nil
}
// SendHandler is a request handler to send service request using HTTP client.
func SendHandler(r *Request) {
	var err error
	r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest)
	if err != nil {
		// Capture the case where url.Error is returned for error processing
		// response. e.g. 301 without location header comes back as string
		// error and r.HTTPResponse is nil. Other url redirect errors will
		// comeback in a similar method.
		if e, ok := err.(*url.Error); ok {
			if s := reStatusCode.FindStringSubmatch(e.Error()); s != nil {
				code, _ := strconv.ParseInt(s[1], 10, 64)
				r.HTTPResponse = &http.Response{
					StatusCode: int(code),
					Status:     http.StatusText(int(code)),
					Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
				}
				return
			}
		}
		if r.HTTPRequest == nil {
			// Add a dummy request response object to ensure the HTTPResponse
			// value is consistent.
			r.HTTPResponse = &http.Response{
				StatusCode: int(0),
				Status:     http.StatusText(int(0)),
				Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
			}
		}
		// Catch all other request errors.
		r.Error = awserr.New("RequestError", "send request failed", err)
		r.Retryable = Bool(true) // network errors are retryable
	}
}
Beispiel #30
0
// Wait waits for an operation to complete, expire max attempts, or fail. Error
// is returned if the operation fails.
func (w *Waiter) Wait() error {
	client := reflect.ValueOf(w.Client)
	in := reflect.ValueOf(w.Input)
	method := client.MethodByName(w.Config.Operation + "Request")

	for i := 0; i < w.MaxAttempts; i++ {
		res := method.Call([]reflect.Value{in})
		req := res[0].Interface().(*request.Request)
		req.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Waiter"))
		if err := req.Send(); err != nil {
			return err
		}

		for _, a := range w.Acceptors {
			result := false
			switch a.Matcher {
			case "pathAll":
				if vals, _ := awsutil.ValuesAtPath(req.Data, a.Argument); req.Error == nil && vals != nil {
					result = true
					for _, val := range vals {
						if !reflect.DeepEqual(val, a.Expected) {
							result = false
							break
						}
					}
				}
			case "pathAny":
				if vals, _ := awsutil.ValuesAtPath(req.Data, a.Argument); req.Error == nil && vals != nil {
					for _, val := range vals {
						if reflect.DeepEqual(val, a.Expected) {
							result = true
							break
						}
					}
				}
			case "status":
				s := a.Expected.(int)
				result = s == req.HTTPResponse.StatusCode
			}

			if result {
				switch a.State {
				case "success":
					return nil // waiter completed
				case "failure":
					return req.Error // waiter failed
				case "retry":
					// do nothing, just retry
				}
				break
			}
		}

		time.Sleep(time.Second * time.Duration(w.Delay))
	}

	return awserr.New("ResourceNotReady",
		fmt.Sprintf("exceeded %d wait attempts", w.MaxAttempts), nil)
}