func testAccStepReadUser(t *testing.T, name string) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.ReadOperation, Path: "creds/" + name, Check: func(resp *logical.Response) error { var d struct { AccessKey string `mapstructure:"access_key"` SecretKey string `mapstructure:"secret_key"` } if err := mapstructure.Decode(resp.Data, &d); err != nil { return err } log.Printf("[WARN] Generated credentials: %v", d) // Sleep sometime because AWS is eventually consistent log.Println("[WARN] Sleeping for 10 seconds waiting for AWS...") time.Sleep(10 * time.Second) // Build a client and verify that the credentials work creds := aws.Creds(d.AccessKey, d.SecretKey, "") client := ec2.New(creds, "us-east-1", nil) log.Printf("[WARN] Verifying that the generated credentials work...") _, err := client.DescribeInstances(&ec2.DescribeInstancesRequest{}) if err != nil { return err } return nil }, } }
func TestRestRequestXMLError(t *testing.T) { var m sync.Mutex var httpReq *http.Request server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { m.Lock() defer m.Unlock() httpReq = r w.Header().Set("Content-Type", "application/xml") w.WriteHeader(500) fmt.Fprintln(w, `<Error> <Code>bonus</Code> <BucketName>bingo</BucketName> <Message>the bad thing</Message> <RequestId>woo woo</RequestId> <HostId>woo woo</HostId> </Error>`) }, )) defer server.Close() client := aws.RestClient{ Context: aws.Context{ Service: "animals", Region: "us-west-2", Credentials: aws.Creds( "accessKeyID", "secretAccessKey", "securityToken", ), }, Client: http.DefaultClient, } req, err := http.NewRequest("GET", server.URL+"/yay", nil) if err != nil { t.Fatal(err) } _, err = client.Do(req) if err == nil { t.Fatal("Expected an error but none was returned") } if err, ok := err.(aws.APIError); ok { if v, want := err.Code, "bonus"; v != want { t.Errorf("Error code was %v, but expected %v", v, want) } if v, want := err.Message, "the bad thing"; v != want { t.Errorf("Error message was %v, but expected %v", v, want) } } else { t.Errorf("Unknown error returned: %#v", err) } }
// Client configures and returns a fully initailized AWSClient func (c *Config) Client() (interface{}, error) { var client AWSClient // Get the auth and region. This can fail if keys/regions were not // specified and we're attempting to use the environment. var errs []error log.Println("[INFO] Building AWS region structure") err := c.ValidateRegion() if err != nil { errs = append(errs, err) } if len(errs) == 0 { // store AWS region in client struct, for region specific operations such as // bucket storage in S3 client.region = c.Region log.Println("[INFO] Building AWS auth structure") creds := aws.Creds(c.AccessKey, c.SecretKey, c.Token) log.Println("[INFO] Initializing ELB connection") client.elbconn = elb.New(creds, c.Region, nil) log.Println("[INFO] Initializing AutoScaling connection") client.autoscalingconn = autoscaling.New(creds, c.Region, nil) log.Println("[INFO] Initializing S3 connection") client.s3conn = s3.New(creds, c.Region, nil) log.Println("[INFO] Initializing RDS connection") client.rdsconn = rds.New(creds, c.Region, nil) // aws-sdk-go uses v4 for signing requests, which requires all global // endpoints to use 'us-east-1'. // See http://docs.aws.amazon.com/general/latest/gr/sigv4_changes.html log.Println("[INFO] Initializing Route53 connection") client.r53conn = route53.New(creds, "us-east-1", nil) log.Println("[INFO] Initializing EC2 Connection") client.ec2conn = ec2.New(creds, c.Region, nil) client.iamconn = iam.New(creds, c.Region, nil) } if len(errs) > 0 { return nil, &multierror.Error{Errors: errs} } return &client, nil }
func TestJSONRequestError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) fmt.Fprintln(w, `{"__type":"Problem", "message":"What even"}`) }, )) defer server.Close() client := aws.JSONClient{ Context: aws.Context{ Service: "animals", Region: "us-west-2", Credentials: aws.Creds( "accessKeyID", "secretAccessKey", "securityToken", ), }, Client: http.DefaultClient, Endpoint: server.URL, TargetPrefix: "Animals", JSONVersion: "1.1", } req := fakeJSONRequest{Name: "Penny"} var resp fakeJSONResponse err := client.Do("PetTheDog", "POST", "/", req, &resp) if err == nil { t.Fatal("Expected an error but none was returned") } if err, ok := err.(aws.APIError); ok { if v, want := err.Type, "Problem"; v != want { t.Errorf("Error type was %v, but expected %v", v, want) } if v, want := err.Message, "What even"; v != want { t.Errorf("Error message was %v, but expected %v", v, want) } } else { t.Errorf("Unknown error returned: %#v", err) } }
func clientIAM(s logical.Storage) (*iam.IAM, error) { entry, err := s.Get("config/root") if err != nil { return nil, err } if entry == nil { return nil, fmt.Errorf( "root credentials haven't been configured. Please configure\n" + "them at the 'config/root' endpoint") } var config rootConfig if err := entry.DecodeJSON(&config); err != nil { return nil, fmt.Errorf("error reading root configuration: %s", err) } creds := aws.Creds(config.AccessKey, config.SecretKey, "") return iam.New(creds, config.Region, nil), nil }
func TestJSONRequest(t *testing.T) { var m sync.Mutex var httpReq *http.Request var body []byte server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { m.Lock() defer m.Unlock() b, err := ioutil.ReadAll(r.Body) if err != nil { t.Fatal(err) } defer r.Body.Close() httpReq = r body = b fmt.Fprintln(w, `{"TailWagged":true}`) }, )) defer server.Close() client := aws.JSONClient{ Context: aws.Context{ Service: "animals", Region: "us-west-2", Credentials: aws.Creds( "accessKeyID", "secretAccessKey", "securityToken", ), }, Client: http.DefaultClient, Endpoint: server.URL, TargetPrefix: "Animals", JSONVersion: "1.1", } req := fakeJSONRequest{Name: "Penny"} var resp fakeJSONResponse if err := client.Do("PetTheDog", "POST", "/", req, &resp); err != nil { t.Fatal(err) } m.Lock() defer m.Unlock() if v, want := httpReq.Method, "POST"; v != want { t.Errorf("Method was %v but expected %v", v, want) } if httpReq.Header.Get("Authorization") == "" { t.Error("Authorization header is missing") } if v, want := httpReq.Header.Get("Content-Type"), "application/x-amz-json-1.1"; v != want { t.Errorf("Content-Type was %v but expected %v", v, want) } if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want { t.Errorf("User-Agent was %v but expected %v", v, want) } if v, want := httpReq.Header.Get("X-Amz-Target"), "Animals.PetTheDog"; v != want { t.Errorf("X-Amz-Target was %v but expected %v", v, want) } if v, want := string(body), `{"Name":"Penny"}`; v != want { t.Errorf("Body was %v but expected %v", v, want) } if v, want := resp, (fakeJSONResponse{TailWagged: true}); v != want { t.Errorf("Response was %#v but expected %#v", v, want) } }
func TestQueryRequest(t *testing.T) { var m sync.Mutex var httpReq *http.Request var form url.Values server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { m.Lock() defer m.Unlock() httpReq = r if err := r.ParseForm(); err != nil { t.Fatal(err) } form = r.Form fmt.Fprintln(w, `<Thing><IpAddress>woo</IpAddress></Thing>`) }, )) defer server.Close() client := aws.QueryClient{ Context: aws.Context{ Service: "animals", Region: "us-west-2", Credentials: aws.Creds( "accessKeyID", "secretAccessKey", "securityToken", ), }, Client: http.DefaultClient, Endpoint: server.URL, APIVersion: "1.1", } req := fakeQueryRequest{ PresentString: aws.String("string"), PresentBoolean: aws.True(), PresentInteger: aws.Integer(1), PresentLong: aws.Long(2), PresentDouble: aws.Double(1.2), PresentFloat: aws.Float(2.3), PresentTime: time.Date(2001, 1, 1, 2, 1, 1, 0, time.FixedZone("UTC+1", 3600)), PresentSlice: []string{"one", "two"}, PresentStruct: &EmbeddedStruct{Value: aws.String("v")}, PresentStructSlice: []EmbeddedStruct{ {Value: aws.String("p")}, {Value: aws.String("q")}, }, PresentMap: map[string]EmbeddedStruct{ "aa": EmbeddedStruct{Value: aws.String("AA")}, "bb": EmbeddedStruct{Value: aws.String("BB")}, }, } var resp fakeQueryResponse if err := client.Do("GetIP", "POST", "/", &req, &resp); err != nil { t.Fatal(err) } m.Lock() defer m.Unlock() if v, want := httpReq.Method, "POST"; v != want { t.Errorf("Method was %v but expected %v", v, want) } if httpReq.Header.Get("Authorization") == "" { t.Error("Authorization header is missing") } if v, want := httpReq.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; v != want { t.Errorf("Content-Type was %v but expected %v", v, want) } if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want { t.Errorf("User-Agent was %v but expected %v", v, want) } if err := httpReq.ParseForm(); err != nil { t.Fatal(err) } expectedForm := url.Values{ "Action": []string{"GetIP"}, "Version": []string{"1.1"}, "PresentString": []string{"string"}, "PresentBoolean": []string{"true"}, "PresentInteger": []string{"1"}, "PresentLong": []string{"2"}, "PresentDouble": []string{"1.2"}, "PresentFloat": []string{"2.3"}, "PresentTime": []string{"2001-01-01T01:01:01Z"}, "PresentSlice.1": []string{"one"}, "PresentSlice.2": []string{"two"}, "PresentStruct.Value": []string{"v"}, "PresentStructSlice.1.Value": []string{"p"}, "PresentStructSlice.2.Value": []string{"q"}, "PresentMap.1.Name": []string{"aa"}, "PresentMap.1.Value.Value": []string{"AA"}, "PresentMap.2.Name": []string{"bb"}, "PresentMap.2.Value.Value": []string{"BB"}, } if !reflect.DeepEqual(form, expectedForm) { t.Errorf("Post body was \n%s\n but expected \n%s", form.Encode(), expectedForm.Encode()) } if want := (fakeQueryResponse{IPAddress: "woo"}); want != resp { t.Errorf("Response was %#v, but expected %#v", resp, want) } }
func TestQueryRequestError(t *testing.T) { var m sync.Mutex var httpReq *http.Request var form url.Values server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { m.Lock() defer m.Unlock() httpReq = r if err := r.ParseForm(); err != nil { t.Fatal(err) } form = r.Form w.WriteHeader(400) fmt.Fprintln(w, `<ErrorResponse> <RequestId>woo</RequestId> <Error> <Type>Problem</Type> <Code>Uh Oh</Code> <Message>You done did it</Message> </Error> </ErrorResponse>`) }, )) defer server.Close() client := aws.QueryClient{ Context: aws.Context{ Service: "animals", Region: "us-west-2", Credentials: aws.Creds( "accessKeyID", "secretAccessKey", "securityToken", ), }, Client: http.DefaultClient, Endpoint: server.URL, APIVersion: "1.1", } req := fakeQueryRequest{} var resp fakeQueryResponse err := client.Do("GetIP", "POST", "/", &req, &resp) if err == nil { t.Fatal("Expected an error but none was returned") } if err, ok := err.(aws.APIError); ok { if v, want := err.Type, "Problem"; v != want { t.Errorf("Error type was %v, but expected %v", v, want) } if v, want := err.Code, "Uh Oh"; v != want { t.Errorf("Error type was %v, but expected %v", v, want) } if v, want := err.Message, "You done did it"; v != want { t.Errorf("Error message was %v, but expected %v", v, want) } } else { t.Errorf("Unknown error returned: %#v", err) } }
func TestRestRequest(t *testing.T) { var m sync.Mutex var httpReq *http.Request server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { m.Lock() defer m.Unlock() httpReq = r fmt.Fprintln(w, `woo`) }, )) defer server.Close() client := aws.RestClient{ Context: aws.Context{ Service: "animals", Region: "us-west-2", Credentials: aws.Creds( "accessKeyID", "secretAccessKey", "securityToken", ), }, Client: http.DefaultClient, } req, err := http.NewRequest("GET", server.URL+"/yay", nil) if err != nil { t.Fatal(err) } resp, err := client.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatal(err) } if v, want := string(body), "woo\n"; v != want { t.Errorf("Response entity was %q, but expected %q", v, want) } m.Lock() defer m.Unlock() if v, want := httpReq.Method, "GET"; v != want { t.Errorf("Method was %v but expected %v", v, want) } if httpReq.Header.Get("Authorization") == "" { t.Error("Authorization header is missing") } if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want { t.Errorf("User-Agent was %v but expected %v", v, want) } if v, want := httpReq.URL.String(), "/yay"; v != want { t.Errorf("URL was %v but expected %v", v, want) } }