repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
session-manager-plugin
aws
Go
// +build go1.7 package session import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "path/filepath" "reflect" "runtime" "strconv" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/sdktesting" "github.com/aws/aws-sdk-go/internal/shareddefaults" "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/service/sts" ) func newEc2MetadataServer(key, secret string, closeAfterGetCreds bool) *httptest.Server { var server *httptest.Server server = httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/latest/meta-data/iam/security-credentials/RoleName" { w.Write([]byte(fmt.Sprintf(ec2MetadataResponse, key, secret))) if closeAfterGetCreds { go server.Close() } } else if r.URL.Path == "/latest/meta-data/iam/security-credentials/" { w.Write([]byte("RoleName")) } else { w.Write([]byte("")) } })) return server } func setupCredentialsEndpoints(t *testing.T) (endpoints.Resolver, func()) { origECSEndpoint := shareddefaults.ECSContainerCredentialsURI ecsMetadataServer := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/ECS" { w.Write([]byte(ecsResponse)) } else { w.Write([]byte("")) } })) shareddefaults.ECSContainerCredentialsURI = ecsMetadataServer.URL ec2MetadataServer := newEc2MetadataServer("ec2_key", "ec2_secret", false) stsServer := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { w.WriteHeader(500) return } form := r.Form switch form.Get("Action") { case "AssumeRole": w.Write([]byte(fmt.Sprintf( assumeRoleRespMsg, time.Now(). Add(15*time.Minute). Format(protocol.ISO8601TimeFormat)))) return case "AssumeRoleWithWebIdentity": w.Write([]byte(fmt.Sprintf(assumeRoleWithWebIdentityResponse, time.Now(). Add(15*time.Minute). Format(protocol.ISO8601TimeFormat)))) return default: w.WriteHeader(404) return } })) ssoServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(fmt.Sprintf( getRoleCredentialsResponse, time.Now(). Add(15*time.Minute). UnixNano()/int64(time.Millisecond)))) })) resolver := endpoints.ResolverFunc( func(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { switch service { case "ec2metadata": return endpoints.ResolvedEndpoint{ URL: ec2MetadataServer.URL, }, nil case "sts": return endpoints.ResolvedEndpoint{ URL: stsServer.URL, }, nil case "portal.sso": return endpoints.ResolvedEndpoint{ URL: ssoServer.URL, }, nil default: return endpoints.ResolvedEndpoint{}, fmt.Errorf("unknown service endpoint, %s", service) } }) return resolver, func() { shareddefaults.ECSContainerCredentialsURI = origECSEndpoint ecsMetadataServer.Close() ec2MetadataServer.Close() ssoServer.Close() stsServer.Close() } } func TestSharedConfigCredentialSource(t *testing.T) { const configFileForWindows = "testdata/credential_source_config_for_windows" const configFile = "testdata/credential_source_config" cases := []struct { name string profile string sessOptProfile string sessOptEC2IMDSEndpoint string expectedError error expectedAccessKey string expectedSecretKey string expectedSessionToken string expectedChain []string init func() (func(), error) dependentOnOS bool }{ { name: "credential source and source profile", profile: "invalid_source_and_credential_source", expectedError: ErrSharedConfigSourceCollision, init: func() (func(), error) { os.Setenv("AWS_ACCESS_KEY", "access_key") os.Setenv("AWS_SECRET_KEY", "secret_key") return func() {}, nil }, }, { name: "env var credential source", sessOptProfile: "env_var_credential_source", expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "assume_role_w_creds_role_arn_env", }, init: func() (func(), error) { os.Setenv("AWS_ACCESS_KEY", "access_key") os.Setenv("AWS_SECRET_KEY", "secret_key") return func() {}, nil }, }, { name: "ec2metadata credential source", profile: "ec2metadata", expectedChain: []string{ "assume_role_w_creds_role_arn_ec2", }, expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", }, { name: "ec2metadata custom EC2 IMDS endpoint, env var", profile: "not-exists-profile", expectedAccessKey: "ec2_custom_key", expectedSecretKey: "ec2_custom_secret", expectedSessionToken: "token", init: func() (func(), error) { altServer := newEc2MetadataServer("ec2_custom_key", "ec2_custom_secret", true) os.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", altServer.URL) return func() {}, nil }, }, { name: "ecs container credential source", profile: "ecscontainer", expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "assume_role_w_creds_role_arn_ecs", }, init: func() (func(), error) { os.Setenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "/ECS") return func() {}, nil }, }, { name: "chained assume role with env creds", profile: "chained_assume_role", expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "assume_role_w_creds_role_arn_chain", "assume_role_w_creds_role_arn_ec2", }, }, { name: "credential process with no ARN set", profile: "cred_proc_no_arn_set", dependentOnOS: true, expectedAccessKey: "cred_proc_akid", expectedSecretKey: "cred_proc_secret", }, { name: "credential process with ARN set", profile: "cred_proc_arn_set", dependentOnOS: true, expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "assume_role_w_creds_proc_role_arn", }, }, { name: "chained assume role with credential process", profile: "chained_cred_proc", dependentOnOS: true, expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "assume_role_w_creds_proc_source_prof", }, }, { name: "sso credentials", profile: "sso_creds", expectedAccessKey: "SSO_AKID", expectedSecretKey: "SSO_SECRET_KEY", expectedSessionToken: "SSO_SESSION_TOKEN", init: func() (func(), error) { return ssoTestSetup() }, }, { name: "chained assume role with sso credentials", profile: "source_sso_creds", expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "source_sso_creds_arn", }, init: func() (func(), error) { return ssoTestSetup() }, }, { name: "chained assume role with sso and static credentials", profile: "assume_sso_and_static", expectedAccessKey: "AKID", expectedSecretKey: "SECRET", expectedSessionToken: "SESSION_TOKEN", expectedChain: []string{ "assume_sso_and_static_arn", }, }, { name: "invalid sso configuration", profile: "sso_invalid", expectedError: fmt.Errorf("profile \"sso_invalid\" is configured to use SSO but is missing required configuration: sso_region, sso_start_url"), }, { name: "environment credentials with invalid sso", profile: "sso_invalid", expectedAccessKey: "access_key", expectedSecretKey: "secret_key", init: func() (func(), error) { os.Setenv("AWS_ACCESS_KEY", "access_key") os.Setenv("AWS_SECRET_KEY", "secret_key") return func() {}, nil }, }, { name: "sso mixed with credential process provider", profile: "sso_mixed_credproc", expectedAccessKey: "SSO_AKID", expectedSecretKey: "SSO_SECRET_KEY", expectedSessionToken: "SSO_SESSION_TOKEN", init: func() (func(), error) { return ssoTestSetup() }, }, { name: "sso mixed with web identity token provider", profile: "sso_mixed_webident", expectedAccessKey: "WEB_IDENTITY_AKID", expectedSecretKey: "WEB_IDENTITY_SECRET", expectedSessionToken: "WEB_IDENTITY_SESSION_TOKEN", }, } for i, c := range cases { t.Run(strconv.Itoa(i)+"_"+c.name, func(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() if c.dependentOnOS && runtime.GOOS == "windows" { os.Setenv("AWS_CONFIG_FILE", configFileForWindows) } else { os.Setenv("AWS_CONFIG_FILE", configFile) } os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_SDK_LOAD_CONFIG", "1") if len(c.profile) != 0 { os.Setenv("AWS_PROFILE", c.profile) } endpointResolver, cleanupFn := setupCredentialsEndpoints(t) defer cleanupFn() if c.init != nil { cleanup, err := c.init() if err != nil { t.Fatalf("expect no error, got %v", err) } defer cleanup() } var credChain []string handlers := defaults.Handlers() handlers.Sign.PushBack(func(r *request.Request) { if r.Config.Credentials == credentials.AnonymousCredentials { return } params := r.Params.(*sts.AssumeRoleInput) credChain = append(credChain, *params.RoleArn) }) sess, err := NewSessionWithOptions(Options{ Profile: c.sessOptProfile, Config: aws.Config{ Logger: t, EndpointResolver: endpointResolver, }, Handlers: handlers, EC2IMDSEndpoint: c.sessOptEC2IMDSEndpoint, }) if c.expectedError != nil { var errStr string if err != nil { errStr = err.Error() } if e, a := c.expectedError.Error(), errStr; !strings.Contains(a, e) { t.Fatalf("expected %v, but received %v", e, a) } } if c.expectedError != nil { return } creds, err := sess.Config.Credentials.Get() if err != nil { t.Fatalf("expected no error, but received %v", err) } if e, a := c.expectedChain, credChain; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.expectedAccessKey, creds.AccessKeyID; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.expectedSecretKey, creds.SecretAccessKey; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.expectedSessionToken, creds.SessionToken; e != a { t.Errorf("expected %v, but received %v", e, a) } }) } } const ecsResponse = `{ "Code": "Success", "Type": "AWS-HMAC", "AccessKeyId" : "ecs-access-key", "SecretAccessKey" : "ecs-secret-key", "Token" : "token", "Expiration" : "2100-01-01T00:00:00Z", "LastUpdated" : "2009-11-23T0:00:00Z" }` const ec2MetadataResponse = `{ "Code": "Success", "Type": "AWS-HMAC", "AccessKeyId" : "%s", "SecretAccessKey" : "%s", "Token" : "token", "Expiration" : "2100-01-01T00:00:00Z", "LastUpdated" : "2009-11-23T0:00:00Z" }` const assumeRoleRespMsg = ` <AssumeRoleResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> <AssumeRoleResult> <AssumedRoleUser> <Arn>arn:aws:sts::account_id:assumed-role/role/session_name</Arn> <AssumedRoleId>AKID:session_name</AssumedRoleId> </AssumedRoleUser> <Credentials> <AccessKeyId>AKID</AccessKeyId> <SecretAccessKey>SECRET</SecretAccessKey> <SessionToken>SESSION_TOKEN</SessionToken> <Expiration>%s</Expiration> </Credentials> </AssumeRoleResult> <ResponseMetadata> <RequestId>request-id</RequestId> </ResponseMetadata> </AssumeRoleResponse> ` var assumeRoleWithWebIdentityResponse = `<AssumeRoleWithWebIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> <AssumeRoleWithWebIdentityResult> <SubjectFromWebIdentityToken>amzn1.account.AF6RHO7KZU5XRVQJGXK6HB56KR2A</SubjectFromWebIdentityToken> <Audience>client.5498841531868486423.1548@apps.example.com</Audience> <AssumedRoleUser> <Arn>arn:aws:sts::123456789012:assumed-role/FederatedWebIdentityRole/app1</Arn> <AssumedRoleId>AROACLKWSDQRAOEXAMPLE:app1</AssumedRoleId> </AssumedRoleUser> <Credentials> <AccessKeyId>WEB_IDENTITY_AKID</AccessKeyId> <SecretAccessKey>WEB_IDENTITY_SECRET</SecretAccessKey> <SessionToken>WEB_IDENTITY_SESSION_TOKEN</SessionToken> <Expiration>%s</Expiration> </Credentials> <Provider>www.amazon.com</Provider> </AssumeRoleWithWebIdentityResult> <ResponseMetadata> <RequestId>request-id</RequestId> </ResponseMetadata> </AssumeRoleWithWebIdentityResponse> ` const getRoleCredentialsResponse = `{ "roleCredentials": { "accessKeyId": "SSO_AKID", "secretAccessKey": "SSO_SECRET_KEY", "sessionToken": "SSO_SESSION_TOKEN", "expiration": %d } }` const ssoTokenCacheFile = `{ "accessToken": "ssoAccessToken", "expiresAt": "%s" }` func TestSessionAssumeRole(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_w_creds") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(fmt.Sprintf( assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) })) defer server.Close() s, err := NewSession(&aws.Config{ Endpoint: aws.String(server.URL), DisableSSL: aws.Bool(true), }) if err != nil { t.Fatalf("expect no error, got %v", err) } creds, err := s.Config.Credentials.Get() if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := "AKID", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SECRET", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SESSION_TOKEN", creds.SessionToken; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "AssumeRoleProvider", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestSessionAssumeRole_WithMFA(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_w_creds") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if e, a := r.FormValue("SerialNumber"), "0123456789"; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := r.FormValue("TokenCode"), "tokencode"; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "900", r.FormValue("DurationSeconds"); e != a { t.Errorf("expect %v, got %v", e, a) } w.Write([]byte(fmt.Sprintf( assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) })) defer server.Close() customProviderCalled := false sess, err := NewSessionWithOptions(Options{ Profile: "assume_role_w_mfa", Config: aws.Config{ Region: aws.String("us-east-1"), Endpoint: aws.String(server.URL), DisableSSL: aws.Bool(true), }, SharedConfigState: SharedConfigEnable, AssumeRoleTokenProvider: func() (string, error) { customProviderCalled = true return "tokencode", nil }, }) if err != nil { t.Fatalf("expect no error, got %v", err) } creds, err := sess.Config.Credentials.Get() if err != nil { t.Fatalf("expect no error, got %v", err) } if !customProviderCalled { t.Errorf("expect true") } if e, a := "AKID", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SECRET", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SESSION_TOKEN", creds.SessionToken; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "AssumeRoleProvider", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestSessionAssumeRole_WithMFA_NoTokenProvider(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_w_creds") _, err := NewSessionWithOptions(Options{ Profile: "assume_role_w_mfa", SharedConfigState: SharedConfigEnable, }) if e, a := (AssumeRoleTokenProviderNotSetError{}), err; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSessionAssumeRole_DisableSharedConfig(t *testing.T) { // Backwards compatibility with Shared config disabled // assume role should not be built into the config. restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "0") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_w_creds") s, err := NewSession(&aws.Config{ CredentialsChainVerboseErrors: aws.Bool(true), }) if err != nil { t.Fatalf("expect no error, got %v", err) } creds, err := s.Config.Credentials.Get() if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := "assume_role_w_creds_akid", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "assume_role_w_creds_secret", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SharedConfigCredentials", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestSessionAssumeRole_InvalidSourceProfile(t *testing.T) { // Backwards compatibility with Shared config disabled // assume role should not be built into the config. restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_invalid_source_profile") s, err := NewSession() if err == nil { t.Fatalf("expect error, got none") } expectMsg := "SharedConfigAssumeRoleError: failed to load assume role" if e, a := expectMsg, err.Error(); !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } if s != nil { t.Errorf("expect nil, %v", err) } } func TestSessionAssumeRole_ExtendedDuration(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() cases := []struct { profile string optionDuration time.Duration expectedDuration string }{ { profile: "assume_role_w_creds", expectedDuration: "900", }, { profile: "assume_role_w_creds", optionDuration: 30 * time.Minute, expectedDuration: "1800", }, { profile: "assume_role_w_creds_w_duration", expectedDuration: "1800", }, { profile: "assume_role_w_creds_w_invalid_duration", expectedDuration: "900", }, } for _, tt := range cases { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if e, a := tt.expectedDuration, r.FormValue("DurationSeconds"); e != a { t.Errorf("expect %v, got %v", e, a) } w.Write([]byte(fmt.Sprintf( assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) })) os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_w_creds") opts := Options{ Profile: tt.profile, Config: aws.Config{ Endpoint: aws.String(server.URL), DisableSSL: aws.Bool(true), }, SharedConfigState: SharedConfigEnable, } if tt.optionDuration != 0 { opts.AssumeRoleDuration = tt.optionDuration } s, err := NewSessionWithOptions(opts) if err != nil { server.Close() t.Fatalf("expect no error, got %v", err) } creds, err := s.Config.Credentials.Get() if err != nil { server.Close() t.Fatalf("expect no error, got %v", err) } if e, a := "AKID", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SECRET", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SESSION_TOKEN", creds.SessionToken; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "AssumeRoleProvider", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } server.Close() } } func TestSessionAssumeRole_WithMFA_ExtendedDuration(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_w_creds") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if e, a := "0123456789", r.FormValue("SerialNumber"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "tokencode", r.FormValue("TokenCode"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "1800", r.FormValue("DurationSeconds"); e != a { t.Errorf("expect %v, got %v", e, a) } w.Write([]byte(fmt.Sprintf( assumeRoleRespMsg, time.Now().Add(30*time.Minute).Format("2006-01-02T15:04:05Z")))) })) defer server.Close() customProviderCalled := false sess, err := NewSessionWithOptions(Options{ Profile: "assume_role_w_mfa", Config: aws.Config{ Region: aws.String("us-east-1"), Endpoint: aws.String(server.URL), DisableSSL: aws.Bool(true), }, SharedConfigState: SharedConfigEnable, AssumeRoleDuration: 30 * time.Minute, AssumeRoleTokenProvider: func() (string, error) { customProviderCalled = true return "tokencode", nil }, }) if err != nil { t.Fatalf("expect no error, got %v", err) } creds, err := sess.Config.Credentials.Get() if err != nil { t.Fatalf("expect no error, got %v", err) } if !customProviderCalled { t.Errorf("expect true") } if e, a := "AKID", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SECRET", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "SESSION_TOKEN", creds.SessionToken; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "AssumeRoleProvider", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func ssoTestSetup() (func(), error) { dir, err := ioutil.TempDir("", "sso-test") if err != nil { return nil, err } cacheDir := filepath.Join(dir, ".aws", "sso", "cache") err = os.MkdirAll(cacheDir, 0750) if err != nil { os.RemoveAll(dir) return nil, err } tokenFile, err := os.Create(filepath.Join(cacheDir, "eb5e43e71ce87dd92ec58903d76debd8ee42aefd.json")) if err != nil { os.RemoveAll(dir) return nil, err } defer tokenFile.Close() _, err = tokenFile.WriteString(fmt.Sprintf(ssoTokenCacheFile, time.Now(). Add(15*time.Minute). Format(time.RFC3339))) if err != nil { os.RemoveAll(dir) return nil, err } if runtime.GOOS == "windows" { os.Setenv("USERPROFILE", dir) } else { os.Setenv("HOME", dir) } return func() { os.RemoveAll(dir) }, nil }
854
session-manager-plugin
aws
Go
// +build go1.7 package session import ( "os" "path/filepath" "strings" "testing" "github.com/aws/aws-sdk-go/internal/sdktesting" ) func TestSession_loadCSMConfig(t *testing.T) { defConfigFiles := []string{ filepath.Join("testdata", "csm_shared_config"), } cases := map[string]struct { Envs map[string]string ConfigFiles []string CSMProfile string Expect csmConfig Err string }{ "no config": { Envs: map[string]string{}, Expect: csmConfig{}, ConfigFiles: defConfigFiles, CSMProfile: "aws_csm_empty", }, "env enabled": { Envs: map[string]string{ "AWS_CSM_ENABLED": "true", "AWS_CSM_PORT": "4321", "AWS_CSM_HOST": "ahost", "AWS_CSM_CLIENT_ID": "client id", }, Expect: csmConfig{ Enabled: true, Port: "4321", Host: "ahost", ClientID: "client id", }, }, "shared cfg enabled": { ConfigFiles: defConfigFiles, Expect: csmConfig{ Enabled: true, Port: "1234", Host: "bar", ClientID: "foo", }, }, "mixed cfg, use env": { Envs: map[string]string{ "AWS_CSM_ENABLED": "true", }, ConfigFiles: defConfigFiles, Expect: csmConfig{ Enabled: true, }, }, "mixed cfg, use env disabled": { Envs: map[string]string{ "AWS_CSM_ENABLED": "false", }, ConfigFiles: defConfigFiles, Expect: csmConfig{ Enabled: false, }, }, "mixed cfg, use shared config": { Envs: map[string]string{ "AWS_CSM_PORT": "4321", }, ConfigFiles: defConfigFiles, Expect: csmConfig{ Enabled: true, Port: "1234", Host: "bar", ClientID: "foo", }, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { restoreFn := sdktesting.StashEnv() defer restoreFn() if len(c.CSMProfile) != 0 { csmProfile := csmProfileName defer func() { csmProfileName = csmProfile }() csmProfileName = c.CSMProfile } for name, v := range c.Envs { os.Setenv(name, v) } envCfg, err := loadEnvConfig() if err != nil { t.Fatalf("failed to load the envcfg, %v", err) } csmCfg, err := loadCSMConfig(envCfg, c.ConfigFiles) if len(c.Err) != 0 { if err == nil { t.Fatalf("expect error, got none") } if e, a := c.Err, err.Error(); !strings.Contains(a, e) { t.Errorf("expect %v in error %v", e, a) } return } if e, a := c.Expect, csmCfg; e != a { t.Errorf("expect %v CSM config got %v", e, a) } }) } }
125
session-manager-plugin
aws
Go
package session import ( "bytes" "fmt" "net" "net/http" "os" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/awstesting" ) var TLSBundleCertFile string var TLSBundleKeyFile string var TLSBundleCAFile string func TestMain(m *testing.M) { var err error TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile, err = awstesting.CreateTLSBundleFiles() if err != nil { panic(err) } fmt.Println("TestMain", TLSBundleCertFile, TLSBundleKeyFile) code := m.Run() err = awstesting.CleanupTLSBundleFiles(TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile) if err != nil { panic(err) } os.Exit(code) } func TestNewSession_WithCustomCABundle_Env(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) if err != nil { t.Fatalf("expect no error, got %v", err) } os.Setenv("AWS_CA_BUNDLE", TLSBundleCAFile) s, err := NewSession(&aws.Config{ HTTPClient: &http.Client{}, Endpoint: aws.String(endpoint), Region: aws.String("mock-region"), Credentials: credentials.AnonymousCredentials, }) if err != nil { t.Fatalf("expect no error, got %v", err) } if s == nil { t.Fatalf("expect session to be created, got none") } req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) resp, err := s.Config.HTTPClient.Do(req) if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := http.StatusOK, resp.StatusCode; e != a { t.Errorf("expect %d status code, got %d", e, a) } } func TestNewSession_WithCustomCABundle_EnvNotExists(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_CA_BUNDLE", "file-not-exists") s, err := NewSession() if err == nil { t.Fatalf("expect error, got none") } if e, a := "LoadCustomCABundleError", err.(awserr.Error).Code(); e != a { t.Errorf("expect %s error code, got %s", e, a) } if s != nil { t.Errorf("expect nil session, got %v", s) } } func TestNewSession_WithCustomCABundle_Option(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) if err != nil { t.Fatalf("expect no error, got %v", err) } s, err := NewSessionWithOptions(Options{ Config: aws.Config{ HTTPClient: &http.Client{}, Endpoint: aws.String(endpoint), Region: aws.String("mock-region"), Credentials: credentials.AnonymousCredentials, }, CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), }) if err != nil { t.Fatalf("expect no error, got %v", err) } if s == nil { t.Fatalf("expect session to be created, got none") } req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) resp, err := s.Config.HTTPClient.Do(req) if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := http.StatusOK, resp.StatusCode; e != a { t.Errorf("expect %d status code, got %d", e, a) } } func TestNewSession_WithCustomCABundle_HTTPProxyAvailable(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() s, err := NewSessionWithOptions(Options{ Config: aws.Config{ HTTPClient: &http.Client{}, Region: aws.String("mock-region"), Credentials: credentials.AnonymousCredentials, }, CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), }) if err != nil { t.Fatalf("expect no error, got %v", err) } if s == nil { t.Fatalf("expect session to be created, got none") } tr := s.Config.HTTPClient.Transport.(*http.Transport) if tr.Proxy == nil { t.Fatalf("expect transport proxy, was nil") } if tr.TLSClientConfig.RootCAs == nil { t.Fatalf("expect TLS config to have root CAs") } } func TestNewSession_WithCustomCABundle_OptionPriority(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) if err != nil { t.Fatalf("expect no error, got %v", err) } os.Setenv("AWS_CA_BUNDLE", "file-not-exists") s, err := NewSessionWithOptions(Options{ Config: aws.Config{ HTTPClient: &http.Client{}, Endpoint: aws.String(endpoint), Region: aws.String("mock-region"), Credentials: credentials.AnonymousCredentials, }, CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), }) if err != nil { t.Fatalf("expect no error, got %v", err) } if s == nil { t.Fatalf("expect session to be created, got none") } req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) resp, err := s.Config.HTTPClient.Do(req) if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := http.StatusOK, resp.StatusCode; e != a { t.Errorf("expect %d status code, got %d", e, a) } } type mockRoundTripper struct{} func (m *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return nil, nil } func TestNewSession_WithCustomCABundle_UnsupportedTransport(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() s, err := NewSessionWithOptions(Options{ Config: aws.Config{ HTTPClient: &http.Client{ Transport: &mockRoundTripper{}, }, }, CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), }) if err == nil { t.Fatalf("expect error, got none") } if e, a := "LoadCustomCABundleError", err.(awserr.Error).Code(); e != a { t.Errorf("expect %s error code, got %s", e, a) } if s != nil { t.Errorf("expect nil session, got %v", s) } aerrMsg := err.(awserr.Error).Message() if e, a := "transport unsupported type", aerrMsg; !strings.Contains(a, e) { t.Errorf("expect %s to be in %s", e, a) } } func TestNewSession_WithCustomCABundle_TransportSet(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) if err != nil { t.Fatalf("expect no error, got %v", err) } s, err := NewSessionWithOptions(Options{ Config: aws.Config{ Endpoint: aws.String(endpoint), Region: aws.String("mock-region"), Credentials: credentials.AnonymousCredentials, HTTPClient: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).Dial, TLSHandshakeTimeout: 2 * time.Second, }, }, }, CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), }) if err != nil { t.Fatalf("expect no error, got %v", err) } if s == nil { t.Fatalf("expect session to be created, got none") } req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) resp, err := s.Config.HTTPClient.Do(req) if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := http.StatusOK, resp.StatusCode; e != a { t.Errorf("expect %d status code, got %d", e, a) } }
272
session-manager-plugin
aws
Go
// +build go1.13 package session import ( "net" "net/http" "time" ) // Transport that should be used when a custom CA bundle is specified with the // SDK. func getCustomTransport() *http.Transport { return &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } }
28
session-manager-plugin
aws
Go
// +build !go1.13,go1.7 package session import ( "net" "net/http" "time" ) // Transport that should be used when a custom CA bundle is specified with the // SDK. func getCustomTransport() *http.Transport { return &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } }
27
session-manager-plugin
aws
Go
// +build !go1.6,go1.5 package session import ( "net" "net/http" "time" ) // Transport that should be used when a custom CA bundle is specified with the // SDK. func getCustomTransport() *http.Transport { return &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } }
23
session-manager-plugin
aws
Go
// +build !go1.7,go1.6 package session import ( "net" "net/http" "time" ) // Transport that should be used when a custom CA bundle is specified with the // SDK. func getCustomTransport() *http.Transport { return &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } }
24
session-manager-plugin
aws
Go
/* Package session provides configuration for the SDK's service clients. Sessions can be shared across service clients that share the same base configuration. Sessions are safe to use concurrently as long as the Session is not being modified. Sessions should be cached when possible, because creating a new Session will load all configuration values from the environment, and config files each time the Session is created. Sharing the Session value across all of your service clients will ensure the configuration is loaded the fewest number of times possible. Sessions options from Shared Config By default NewSession will only load credentials from the shared credentials file (~/.aws/credentials). If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value the Session will be created from the configuration values from the shared config (~/.aws/config) and shared credentials (~/.aws/credentials) files. Using the NewSessionWithOptions with SharedConfigState set to SharedConfigEnable will create the session as if the AWS_SDK_LOAD_CONFIG environment variable was set. Credential and config loading order The Session will attempt to load configuration and credentials from the environment, configuration files, and other credential sources. The order configuration is loaded in is: * Environment Variables * Shared Credentials file * Shared Configuration file (if SharedConfig is enabled) * EC2 Instance Metadata (credentials only) The Environment variables for credentials will have precedence over shared config even if SharedConfig is enabled. To override this behavior, and use shared config credentials instead specify the session.Options.Profile, (e.g. when using credential_source=Environment to assume a role). sess, err := session.NewSessionWithOptions(session.Options{ Profile: "myProfile", }) Creating Sessions Creating a Session without additional options will load credentials region, and profile loaded from the environment and shared config automatically. See, "Environment Variables" section for information on environment variables used by Session. // Create Session sess, err := session.NewSession() When creating Sessions optional aws.Config values can be passed in that will override the default, or loaded, config values the Session is being created with. This allows you to provide additional, or case based, configuration as needed. // Create a Session with a custom region sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2"), }) Use NewSessionWithOptions to provide additional configuration driving how the Session's configuration will be loaded. Such as, specifying shared config profile, or override the shared config state, (AWS_SDK_LOAD_CONFIG). // Equivalent to session.NewSession() sess, err := session.NewSessionWithOptions(session.Options{ // Options }) sess, err := session.NewSessionWithOptions(session.Options{ // Specify profile to load for the session's config Profile: "profile_name", // Provide SDK Config options, such as Region. Config: aws.Config{ Region: aws.String("us-west-2"), }, // Force enable Shared Config support SharedConfigState: session.SharedConfigEnable, }) Adding Handlers You can add handlers to a session to decorate API operation, (e.g. adding HTTP headers). All clients that use the Session receive a copy of the Session's handlers. For example, the following request handler added to the Session logs every requests made. // Create a session, and add additional handlers for all service // clients created with the Session to inherit. Adds logging handler. sess := session.Must(session.NewSession()) sess.Handlers.Send.PushFront(func(r *request.Request) { // Log every request made and its payload logger.Printf("Request: %s/%s, Params: %s", r.ClientInfo.ServiceName, r.Operation, r.Params) }) Shared Config Fields By default the SDK will only load the shared credentials file's (~/.aws/credentials) credentials values, and all other config is provided by the environment variables, SDK defaults, and user provided aws.Config values. If the AWS_SDK_LOAD_CONFIG environment variable is set, or SharedConfigEnable option is used to create the Session the full shared config values will be loaded. This includes credentials, region, and support for assume role. In addition the Session will load its configuration from both the shared config file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both files have the same format. If both config files are present the configuration from both files will be read. The Session will be created from configuration values from the shared credentials file (~/.aws/credentials) over those in the shared config file (~/.aws/config). Credentials are the values the SDK uses to authenticating requests with AWS Services. When specified in a file, both aws_access_key_id and aws_secret_access_key must be provided together in the same file to be considered valid. They will be ignored if both are not present. aws_session_token is an optional field that can be provided in addition to the other two fields. aws_access_key_id = AKID aws_secret_access_key = SECRET aws_session_token = TOKEN ; region only supported if SharedConfigEnabled. region = us-east-1 Assume Role configuration The role_arn field allows you to configure the SDK to assume an IAM role using a set of credentials from another source. Such as when paired with static credentials, "profile_source", "credential_process", or "credential_source" fields. If "role_arn" is provided, a source of credentials must also be specified, such as "source_profile", "credential_source", or "credential_process". role_arn = arn:aws:iam::<account_number>:role/<role_name> source_profile = profile_with_creds external_id = 1234 mfa_serial = <serial or mfa arn> role_session_name = session_name The SDK supports assuming a role with MFA token. If "mfa_serial" is set, you must also set the Session Option.AssumeRoleTokenProvider. The Session will fail to load if the AssumeRoleTokenProvider is not specified. sess := session.Must(session.NewSessionWithOptions(session.Options{ AssumeRoleTokenProvider: stscreds.StdinTokenProvider, })) To setup Assume Role outside of a session see the stscreds.AssumeRoleProvider documentation. Environment Variables When a Session is created several environment variables can be set to adjust how the SDK functions, and what configuration data it loads when creating Sessions. All environment values are optional, but some values like credentials require multiple of the values to set or the partial values will be ignored. All environment variable values are strings unless otherwise noted. Environment configuration values. If set both Access Key ID and Secret Access Key must be provided. Session Token and optionally also be provided, but is not required. # Access Key ID AWS_ACCESS_KEY_ID=AKID AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. # Secret Access Key AWS_SECRET_ACCESS_KEY=SECRET AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. # Session Token AWS_SESSION_TOKEN=TOKEN Region value will instruct the SDK where to make service API requests to. If is not provided in the environment the region must be provided before a service client request is made. AWS_REGION=us-east-1 # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, # and AWS_REGION is not also set. AWS_DEFAULT_REGION=us-east-1 Profile name the SDK should load use when loading shared config from the configuration files. If not provided "default" will be used as the profile name. AWS_PROFILE=my_profile # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, # and AWS_PROFILE is not also set. AWS_DEFAULT_PROFILE=my_profile SDK load config instructs the SDK to load the shared config in addition to shared credentials. This also expands the configuration loaded so the shared credentials will have parity with the shared config file. This also enables Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE env values as well. AWS_SDK_LOAD_CONFIG=1 Custom Shared Config and Credential Files Shared credentials file path can be set to instruct the SDK to use an alternative file for the shared credentials. If not set the file will be loaded from $HOME/.aws/credentials on Linux/Unix based systems, and %USERPROFILE%\.aws\credentials on Windows. AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials Shared config file path can be set to instruct the SDK to use an alternative file for the shared config. If not set the file will be loaded from $HOME/.aws/config on Linux/Unix based systems, and %USERPROFILE%\.aws\config on Windows. AWS_CONFIG_FILE=$HOME/my_shared_config Custom CA Bundle Path to a custom Credentials Authority (CA) bundle PEM file that the SDK will use instead of the default system's root CA bundle. Use this only if you want to replace the CA bundle the SDK uses for TLS requests. AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle Enabling this option will attempt to merge the Transport into the SDK's HTTP client. If the client's Transport is not a http.Transport an error will be returned. If the Transport's TLS config is set this option will cause the SDK to overwrite the Transport's TLS config's RootCAs value. If the CA bundle file contains multiple certificates all of them will be loaded. The Session option CustomCABundle is also available when creating sessions to also enable this feature. CustomCABundle session option field has priority over the AWS_CA_BUNDLE environment variable, and will be used if both are set. Setting a custom HTTPClient in the aws.Config options will override this setting. To use this option and custom HTTP client, the HTTP client needs to be provided when creating the session. Not the service client. Custom Client TLS Certificate The SDK supports the environment and session option being configured with Client TLS certificates that are sent as a part of the client's TLS handshake for client authentication. If used, both Cert and Key values are required. If one is missing, or either fail to load the contents of the file an error will be returned. HTTP Client's Transport concrete implementation must be a http.Transport or creating the session will fail. AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert This can also be configured via the session.Options ClientTLSCert and ClientTLSKey. sess, err := session.NewSessionWithOptions(session.Options{ ClientTLSCert: myCertFile, ClientTLSKey: myKeyFile, }) Custom EC2 IMDS Endpoint The endpoint of the EC2 IMDS client can be configured via the environment variable, AWS_EC2_METADATA_SERVICE_ENDPOINT when creating the client with a Session. See Options.EC2IMDSEndpoint for more details. AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 If using an URL with an IPv6 address literal, the IPv6 address component must be enclosed in square brackets. AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] The custom EC2 IMDS endpoint can also be specified via the Session options. sess, err := session.NewSessionWithOptions(session.Options{ EC2MetadataEndpoint: "http://[::1]", }) */ package session
290
session-manager-plugin
aws
Go
package session import ( "fmt" "os" "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" ) // EnvProviderName provides a name of the provider when config is loaded from environment. const EnvProviderName = "EnvConfigCredentials" // envConfig is a collection of environment values the SDK will read // setup config from. All environment values are optional. But some values // such as credentials require multiple values to be complete or the values // will be ignored. type envConfig struct { // Environment configuration values. If set both Access Key ID and Secret Access // Key must be provided. Session Token and optionally also be provided, but is // not required. // // # Access Key ID // AWS_ACCESS_KEY_ID=AKID // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. // // # Secret Access Key // AWS_SECRET_ACCESS_KEY=SECRET // AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. // // # Session Token // AWS_SESSION_TOKEN=TOKEN Creds credentials.Value // Region value will instruct the SDK where to make service API requests to. If is // not provided in the environment the region must be provided before a service // client request is made. // // AWS_REGION=us-east-1 // // # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, // # and AWS_REGION is not also set. // AWS_DEFAULT_REGION=us-east-1 Region string // Profile name the SDK should load use when loading shared configuration from the // shared configuration files. If not provided "default" will be used as the // profile name. // // AWS_PROFILE=my_profile // // # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, // # and AWS_PROFILE is not also set. // AWS_DEFAULT_PROFILE=my_profile Profile string // SDK load config instructs the SDK to load the shared config in addition to // shared credentials. This also expands the configuration loaded from the shared // credentials to have parity with the shared config file. This also enables // Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE // env values as well. // // AWS_SDK_LOAD_CONFIG=1 EnableSharedConfig bool // Shared credentials file path can be set to instruct the SDK to use an alternate // file for the shared credentials. If not set the file will be loaded from // $HOME/.aws/credentials on Linux/Unix based systems, and // %USERPROFILE%\.aws\credentials on Windows. // // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials SharedCredentialsFile string // Shared config file path can be set to instruct the SDK to use an alternate // file for the shared config. If not set the file will be loaded from // $HOME/.aws/config on Linux/Unix based systems, and // %USERPROFILE%\.aws\config on Windows. // // AWS_CONFIG_FILE=$HOME/my_shared_config SharedConfigFile string // Sets the path to a custom Credentials Authority (CA) Bundle PEM file // that the SDK will use instead of the system's root CA bundle. // Only use this if you want to configure the SDK to use a custom set // of CAs. // // Enabling this option will attempt to merge the Transport // into the SDK's HTTP client. If the client's Transport is // not a http.Transport an error will be returned. If the // Transport's TLS config is set this option will cause the // SDK to overwrite the Transport's TLS config's RootCAs value. // // Setting a custom HTTPClient in the aws.Config options will override this setting. // To use this option and custom HTTP client, the HTTP client needs to be provided // when creating the session. Not the service client. // // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle CustomCABundle string // Sets the TLC client certificate that should be used by the SDK's HTTP transport // when making requests. The certificate must be paired with a TLS client key file. // // AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert ClientTLSCert string // Sets the TLC client key that should be used by the SDK's HTTP transport // when making requests. The key must be paired with a TLS client certificate file. // // AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key ClientTLSKey string csmEnabled string CSMEnabled *bool CSMPort string CSMHost string CSMClientID string // Enables endpoint discovery via environment variables. // // AWS_ENABLE_ENDPOINT_DISCOVERY=true EnableEndpointDiscovery *bool enableEndpointDiscovery string // Specifies the WebIdentity token the SDK should use to assume a role // with. // // AWS_WEB_IDENTITY_TOKEN_FILE=file_path WebIdentityTokenFilePath string // Specifies the IAM role arn to use when assuming an role. // // AWS_ROLE_ARN=role_arn RoleARN string // Specifies the IAM role session name to use when assuming a role. // // AWS_ROLE_SESSION_NAME=session_name RoleSessionName string // Specifies the STS Regional Endpoint flag for the SDK to resolve the endpoint // for a service. // // AWS_STS_REGIONAL_ENDPOINTS=regional // This can take value as `regional` or `legacy` STSRegionalEndpoint endpoints.STSRegionalEndpoint // Specifies the S3 Regional Endpoint flag for the SDK to resolve the // endpoint for a service. // // AWS_S3_US_EAST_1_REGIONAL_ENDPOINT=regional // This can take value as `regional` or `legacy` S3UsEast1RegionalEndpoint endpoints.S3UsEast1RegionalEndpoint // Specifies if the S3 service should allow ARNs to direct the region // the client's requests are sent to. // // AWS_S3_USE_ARN_REGION=true S3UseARNRegion bool // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode. // // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] EC2IMDSEndpoint string // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) // // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState } var ( csmEnabledEnvKey = []string{ "AWS_CSM_ENABLED", } csmHostEnvKey = []string{ "AWS_CSM_HOST", } csmPortEnvKey = []string{ "AWS_CSM_PORT", } csmClientIDEnvKey = []string{ "AWS_CSM_CLIENT_ID", } credAccessEnvKey = []string{ "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", } credSecretEnvKey = []string{ "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", } credSessionEnvKey = []string{ "AWS_SESSION_TOKEN", } enableEndpointDiscoveryEnvKey = []string{ "AWS_ENABLE_ENDPOINT_DISCOVERY", } regionEnvKeys = []string{ "AWS_REGION", "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set } profileEnvKeys = []string{ "AWS_PROFILE", "AWS_DEFAULT_PROFILE", // Only read if AWS_SDK_LOAD_CONFIG is also set } sharedCredsFileEnvKey = []string{ "AWS_SHARED_CREDENTIALS_FILE", } sharedConfigFileEnvKey = []string{ "AWS_CONFIG_FILE", } webIdentityTokenFilePathEnvKey = []string{ "AWS_WEB_IDENTITY_TOKEN_FILE", } roleARNEnvKey = []string{ "AWS_ROLE_ARN", } roleSessionNameEnvKey = []string{ "AWS_ROLE_SESSION_NAME", } stsRegionalEndpointKey = []string{ "AWS_STS_REGIONAL_ENDPOINTS", } s3UsEast1RegionalEndpoint = []string{ "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT", } s3UseARNRegionEnvKey = []string{ "AWS_S3_USE_ARN_REGION", } ec2IMDSEndpointEnvKey = []string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT", } ec2IMDSEndpointModeEnvKey = []string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE", } useCABundleKey = []string{ "AWS_CA_BUNDLE", } useClientTLSCert = []string{ "AWS_SDK_GO_CLIENT_TLS_CERT", } useClientTLSKey = []string{ "AWS_SDK_GO_CLIENT_TLS_KEY", } ) // loadEnvConfig retrieves the SDK's environment configuration. // See `envConfig` for the values that will be retrieved. // // If the environment variable `AWS_SDK_LOAD_CONFIG` is set to a truthy value // the shared SDK config will be loaded in addition to the SDK's specific // configuration values. func loadEnvConfig() (envConfig, error) { enableSharedConfig, _ := strconv.ParseBool(os.Getenv("AWS_SDK_LOAD_CONFIG")) return envConfigLoad(enableSharedConfig) } // loadEnvSharedConfig retrieves the SDK's environment configuration, and the // SDK shared config. See `envConfig` for the values that will be retrieved. // // Loads the shared configuration in addition to the SDK's specific configuration. // This will load the same values as `loadEnvConfig` if the `AWS_SDK_LOAD_CONFIG` // environment variable is set. func loadSharedEnvConfig() (envConfig, error) { return envConfigLoad(true) } func envConfigLoad(enableSharedConfig bool) (envConfig, error) { cfg := envConfig{} cfg.EnableSharedConfig = enableSharedConfig // Static environment credentials var creds credentials.Value setFromEnvVal(&creds.AccessKeyID, credAccessEnvKey) setFromEnvVal(&creds.SecretAccessKey, credSecretEnvKey) setFromEnvVal(&creds.SessionToken, credSessionEnvKey) if creds.HasKeys() { // Require logical grouping of credentials creds.ProviderName = EnvProviderName cfg.Creds = creds } // Role Metadata setFromEnvVal(&cfg.RoleARN, roleARNEnvKey) setFromEnvVal(&cfg.RoleSessionName, roleSessionNameEnvKey) // Web identity environment variables setFromEnvVal(&cfg.WebIdentityTokenFilePath, webIdentityTokenFilePathEnvKey) // CSM environment variables setFromEnvVal(&cfg.csmEnabled, csmEnabledEnvKey) setFromEnvVal(&cfg.CSMHost, csmHostEnvKey) setFromEnvVal(&cfg.CSMPort, csmPortEnvKey) setFromEnvVal(&cfg.CSMClientID, csmClientIDEnvKey) if len(cfg.csmEnabled) != 0 { v, _ := strconv.ParseBool(cfg.csmEnabled) cfg.CSMEnabled = &v } regionKeys := regionEnvKeys profileKeys := profileEnvKeys if !cfg.EnableSharedConfig { regionKeys = regionKeys[:1] profileKeys = profileKeys[:1] } setFromEnvVal(&cfg.Region, regionKeys) setFromEnvVal(&cfg.Profile, profileKeys) // endpoint discovery is in reference to it being enabled. setFromEnvVal(&cfg.enableEndpointDiscovery, enableEndpointDiscoveryEnvKey) if len(cfg.enableEndpointDiscovery) > 0 { cfg.EnableEndpointDiscovery = aws.Bool(cfg.enableEndpointDiscovery != "false") } setFromEnvVal(&cfg.SharedCredentialsFile, sharedCredsFileEnvKey) setFromEnvVal(&cfg.SharedConfigFile, sharedConfigFileEnvKey) if len(cfg.SharedCredentialsFile) == 0 { cfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() } if len(cfg.SharedConfigFile) == 0 { cfg.SharedConfigFile = defaults.SharedConfigFilename() } setFromEnvVal(&cfg.CustomCABundle, useCABundleKey) setFromEnvVal(&cfg.ClientTLSCert, useClientTLSCert) setFromEnvVal(&cfg.ClientTLSKey, useClientTLSKey) var err error // STS Regional Endpoint variable for _, k := range stsRegionalEndpointKey { if v := os.Getenv(k); len(v) != 0 { cfg.STSRegionalEndpoint, err = endpoints.GetSTSRegionalEndpoint(v) if err != nil { return cfg, fmt.Errorf("failed to load, %v from env config, %v", k, err) } } } // S3 Regional Endpoint variable for _, k := range s3UsEast1RegionalEndpoint { if v := os.Getenv(k); len(v) != 0 { cfg.S3UsEast1RegionalEndpoint, err = endpoints.GetS3UsEast1RegionalEndpoint(v) if err != nil { return cfg, fmt.Errorf("failed to load, %v from env config, %v", k, err) } } } var s3UseARNRegion string setFromEnvVal(&s3UseARNRegion, s3UseARNRegionEnvKey) if len(s3UseARNRegion) != 0 { switch { case strings.EqualFold(s3UseARNRegion, "false"): cfg.S3UseARNRegion = false case strings.EqualFold(s3UseARNRegion, "true"): cfg.S3UseARNRegion = true default: return envConfig{}, fmt.Errorf( "invalid value for environment variable, %s=%s, need true or false", s3UseARNRegionEnvKey[0], s3UseARNRegion) } } setFromEnvVal(&cfg.EC2IMDSEndpoint, ec2IMDSEndpointEnvKey) if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, ec2IMDSEndpointModeEnvKey); err != nil { return envConfig{}, err } return cfg, nil } func setFromEnvVal(dst *string, keys []string) { for _, k := range keys { if v := os.Getenv(k); len(v) != 0 { *dst = v break } } } func setEC2IMDSEndpointMode(mode *endpoints.EC2IMDSEndpointModeState, keys []string) error { for _, k := range keys { value := os.Getenv(k) if len(value) == 0 { continue } if err := mode.SetFromString(value); err != nil { return fmt.Errorf("invalid value for environment variable, %s=%s, %v", k, value, err) } return nil } return nil }
404
session-manager-plugin
aws
Go
// +build go1.7 package session import ( "os" "reflect" "strconv" "testing" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/awstesting" "github.com/aws/aws-sdk-go/internal/sdktesting" "github.com/aws/aws-sdk-go/internal/shareddefaults" ) func TestLoadEnvConfig_Creds(t *testing.T) { cases := []struct { Env map[string]string Val credentials.Value }{ { Env: map[string]string{ "AWS_ACCESS_KEY": "AKID", }, Val: credentials.Value{}, }, { Env: map[string]string{ "AWS_ACCESS_KEY_ID": "AKID", }, Val: credentials.Value{}, }, { Env: map[string]string{ "AWS_SECRET_KEY": "SECRET", }, Val: credentials.Value{}, }, { Env: map[string]string{ "AWS_SECRET_ACCESS_KEY": "SECRET", }, Val: credentials.Value{}, }, { Env: map[string]string{ "AWS_ACCESS_KEY_ID": "AKID", "AWS_SECRET_ACCESS_KEY": "SECRET", }, Val: credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", ProviderName: "EnvConfigCredentials", }, }, { Env: map[string]string{ "AWS_ACCESS_KEY": "AKID", "AWS_SECRET_KEY": "SECRET", }, Val: credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", ProviderName: "EnvConfigCredentials", }, }, { Env: map[string]string{ "AWS_ACCESS_KEY": "AKID", "AWS_SECRET_KEY": "SECRET", "AWS_SESSION_TOKEN": "TOKEN", }, Val: credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "TOKEN", ProviderName: "EnvConfigCredentials", }, }, } for i, c := range cases { t.Run(strconv.Itoa(i), func(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() for k, v := range c.Env { os.Setenv(k, v) } cfg, err := loadEnvConfig() if err != nil { t.Fatalf("failed to load env config, %v", err) } if !reflect.DeepEqual(c.Val, cfg.Creds) { t.Errorf("expect credentials to match.\n%s", awstesting.SprintExpectActual(c.Val, cfg.Creds)) } }) } } func TestLoadEnvConfig(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() cases := []struct { Env map[string]string UseSharedConfigCall bool Config envConfig WantErr bool }{ 0: { Env: map[string]string{ "AWS_REGION": "region", "AWS_PROFILE": "profile", }, Config: envConfig{ Region: "region", Profile: "profile", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 1: { Env: map[string]string{ "AWS_REGION": "region", "AWS_DEFAULT_REGION": "default_region", "AWS_PROFILE": "profile", "AWS_DEFAULT_PROFILE": "default_profile", }, Config: envConfig{ Region: "region", Profile: "profile", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 2: { Env: map[string]string{ "AWS_REGION": "region", "AWS_DEFAULT_REGION": "default_region", "AWS_PROFILE": "profile", "AWS_DEFAULT_PROFILE": "default_profile", "AWS_SDK_LOAD_CONFIG": "1", }, Config: envConfig{ Region: "region", Profile: "profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 3: { Env: map[string]string{ "AWS_DEFAULT_REGION": "default_region", "AWS_DEFAULT_PROFILE": "default_profile", }, Config: envConfig{ SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 4: { Env: map[string]string{ "AWS_DEFAULT_REGION": "default_region", "AWS_DEFAULT_PROFILE": "default_profile", "AWS_SDK_LOAD_CONFIG": "1", }, Config: envConfig{ Region: "default_region", Profile: "default_profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 5: { Env: map[string]string{ "AWS_REGION": "region", "AWS_PROFILE": "profile", }, Config: envConfig{ Region: "region", Profile: "profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 6: { Env: map[string]string{ "AWS_REGION": "region", "AWS_DEFAULT_REGION": "default_region", "AWS_PROFILE": "profile", "AWS_DEFAULT_PROFILE": "default_profile", }, Config: envConfig{ Region: "region", Profile: "profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 7: { Env: map[string]string{ "AWS_REGION": "region", "AWS_DEFAULT_REGION": "default_region", "AWS_PROFILE": "profile", "AWS_DEFAULT_PROFILE": "default_profile", "AWS_SDK_LOAD_CONFIG": "1", }, Config: envConfig{ Region: "region", Profile: "profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 8: { Env: map[string]string{ "AWS_DEFAULT_REGION": "default_region", "AWS_DEFAULT_PROFILE": "default_profile", }, Config: envConfig{ Region: "default_region", Profile: "default_profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 9: { Env: map[string]string{ "AWS_DEFAULT_REGION": "default_region", "AWS_DEFAULT_PROFILE": "default_profile", "AWS_SDK_LOAD_CONFIG": "1", }, Config: envConfig{ Region: "default_region", Profile: "default_profile", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 10: { Env: map[string]string{ "AWS_CA_BUNDLE": "custom_ca_bundle", }, Config: envConfig{ CustomCABundle: "custom_ca_bundle", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 11: { Env: map[string]string{ "AWS_CA_BUNDLE": "custom_ca_bundle", }, Config: envConfig{ CustomCABundle: "custom_ca_bundle", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 12: { Env: map[string]string{ "AWS_SDK_GO_CLIENT_TLS_CERT": "client_tls_cert", }, Config: envConfig{ ClientTLSCert: "client_tls_cert", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 13: { Env: map[string]string{ "AWS_SDK_GO_CLIENT_TLS_CERT": "client_tls_cert", }, Config: envConfig{ ClientTLSCert: "client_tls_cert", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 14: { Env: map[string]string{ "AWS_SDK_GO_CLIENT_TLS_KEY": "client_tls_key", }, Config: envConfig{ ClientTLSKey: "client_tls_key", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 15: { Env: map[string]string{ "AWS_SDK_GO_CLIENT_TLS_KEY": "client_tls_key", }, Config: envConfig{ ClientTLSKey: "client_tls_key", EnableSharedConfig: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, UseSharedConfigCall: true, }, 16: { Env: map[string]string{ "AWS_SHARED_CREDENTIALS_FILE": "/path/to/credentials/file", "AWS_CONFIG_FILE": "/path/to/config/file", }, Config: envConfig{ SharedCredentialsFile: "/path/to/credentials/file", SharedConfigFile: "/path/to/config/file", }, }, 17: { Env: map[string]string{ "AWS_STS_REGIONAL_ENDPOINTS": "regional", }, Config: envConfig{ STSRegionalEndpoint: endpoints.RegionalSTSEndpoint, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 18: { Env: map[string]string{ "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT": "regional", }, Config: envConfig{ S3UsEast1RegionalEndpoint: endpoints.RegionalS3UsEast1Endpoint, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 19: { Env: map[string]string{ "AWS_S3_USE_ARN_REGION": "true", }, Config: envConfig{ S3UseARNRegion: true, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 20: { Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://example.aws", }, Config: envConfig{ EC2IMDSEndpoint: "http://example.aws", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 21: { Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv6", }, Config: envConfig{ EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv6, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 22: { Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv4", }, Config: envConfig{ EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv4, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 23: { Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "foobar", }, WantErr: true, }, 24: { Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://endpoint.localhost", }, Config: envConfig{ EC2IMDSEndpoint: "http://endpoint.localhost", SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 25: { Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv6", "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://endpoint.localhost", }, Config: envConfig{ EC2IMDSEndpoint: "http://endpoint.localhost", EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv6, SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, 26: { Env: map[string]string{ "AWS_EC2_METADATA_DISABLED": "false", }, Config: envConfig{ SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), SharedConfigFile: shareddefaults.SharedConfigFilename(), }, }, } for i, c := range cases { t.Run(strconv.Itoa(i), func(t *testing.T) { restoreEnvFn = sdktesting.StashEnv() defer restoreEnvFn() for k, v := range c.Env { os.Setenv(k, v) } var cfg envConfig var err error if c.UseSharedConfigCall { cfg, err = loadSharedEnvConfig() if (err != nil) != c.WantErr { t.Errorf("WantErr=%v, got err=%v", c.WantErr, err) return } } else { cfg, err = loadEnvConfig() if (err != nil) != c.WantErr { t.Errorf("WantErr=%v, got err=%v", c.WantErr, err) return } } if !reflect.DeepEqual(c.Config, cfg) { t.Errorf("expect config to match.\n%s", awstesting.SprintExpectActual(c.Config, cfg)) } }) } } func TestSetEnvValue(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() os.Setenv("empty_key", "") os.Setenv("second_key", "2") os.Setenv("third_key", "3") var dst string setFromEnvVal(&dst, []string{ "empty_key", "first_key", "second_key", "third_key", }) if e, a := "2", dst; e != a { t.Errorf("expect %s value from environment, got %s", e, a) } }
468
session-manager-plugin
aws
Go
package session import ( "crypto/tls" "crypto/x509" "fmt" "io" "io/ioutil" "net/http" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/csm" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" ) const ( // ErrCodeSharedConfig represents an error that occurs in the shared // configuration logic ErrCodeSharedConfig = "SharedConfigErr" // ErrCodeLoadCustomCABundle error code for unable to load custom CA bundle. ErrCodeLoadCustomCABundle = "LoadCustomCABundleError" // ErrCodeLoadClientTLSCert error code for unable to load client TLS // certificate or key ErrCodeLoadClientTLSCert = "LoadClientTLSCertError" ) // ErrSharedConfigSourceCollision will be returned if a section contains both // source_profile and credential_source var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only one credential type may be specified per profile: source profile, credential source, credential process, web identity token, or sso", nil) // ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment // variables are empty and Environment was set as the credential source var ErrSharedConfigECSContainerEnvVarEmpty = awserr.New(ErrCodeSharedConfig, "EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set", nil) // ErrSharedConfigInvalidCredSource will be returned if an invalid credential source was provided var ErrSharedConfigInvalidCredSource = awserr.New(ErrCodeSharedConfig, "credential source values must be EcsContainer, Ec2InstanceMetadata, or Environment", nil) // A Session provides a central location to create service clients from and // store configurations and request handlers for those services. // // Sessions are safe to create service clients concurrently, but it is not safe // to mutate the Session concurrently. // // The Session satisfies the service client's client.ConfigProvider. type Session struct { Config *aws.Config Handlers request.Handlers options Options } // New creates a new instance of the handlers merging in the provided configs // on top of the SDK's default configurations. Once the Session is created it // can be mutated to modify the Config or Handlers. The Session is safe to be // read concurrently, but it should not be written to concurrently. // // If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New // method could now encounter an error when loading the configuration. When // The environment variable is set, and an error occurs, New will return a // session that will fail all requests reporting the error that occurred while // loading the session. Use NewSession to get the error when creating the // session. // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded, in addition to // the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. // // Deprecated: Use NewSession functions to create sessions instead. NewSession // has the same functionality as New except an error can be returned when the // func is called instead of waiting to receive an error until a request is made. func New(cfgs ...*aws.Config) *Session { // load initial config from environment envCfg, envErr := loadEnvConfig() if envCfg.EnableSharedConfig { var cfg aws.Config cfg.MergeIn(cfgs...) s, err := NewSessionWithOptions(Options{ Config: cfg, SharedConfigState: SharedConfigEnable, }) if err != nil { // Old session.New expected all errors to be discovered when // a request is made, and would report the errors then. This // needs to be replicated if an error occurs while creating // the session. msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " + "Use session.NewSession to handle errors occurring during session creation." // Session creation failed, need to report the error and prevent // any requests from succeeding. s = &Session{Config: defaults.Config()} s.logDeprecatedNewSessionError(msg, err, cfgs) } return s } s := deprecatedNewSession(envCfg, cfgs...) if envErr != nil { msg := "failed to load env config" s.logDeprecatedNewSessionError(msg, envErr, cfgs) } if csmCfg, err := loadCSMConfig(envCfg, []string{}); err != nil { if l := s.Config.Logger; l != nil { l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err)) } } else if csmCfg.Enabled { err := enableCSM(&s.Handlers, csmCfg, s.Config.Logger) if err != nil { msg := "failed to enable CSM" s.logDeprecatedNewSessionError(msg, err, cfgs) } } return s } // NewSession returns a new Session created from SDK defaults, config files, // environment, and user provided config files. Once the Session is created // it can be mutated to modify the Config or Handlers. The Session is safe to // be read concurrently, but it should not be written to concurrently. // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded in addition to // the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. Enabling the Shared Config will also allow the Session // to be built with retrieving credentials with AssumeRole set in the config. // // See the NewSessionWithOptions func for information on how to override or // control through code how the Session will be created, such as specifying the // config profile, and controlling if shared config is enabled or not. func NewSession(cfgs ...*aws.Config) (*Session, error) { opts := Options{} opts.Config.MergeIn(cfgs...) return NewSessionWithOptions(opts) } // SharedConfigState provides the ability to optionally override the state // of the session's creation based on the shared config being enabled or // disabled. type SharedConfigState int const ( // SharedConfigStateFromEnv does not override any state of the // AWS_SDK_LOAD_CONFIG env var. It is the default value of the // SharedConfigState type. SharedConfigStateFromEnv SharedConfigState = iota // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value // and disables the shared config functionality. SharedConfigDisable // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value // and enables the shared config functionality. SharedConfigEnable ) // Options provides the means to control how a Session is created and what // configuration values will be loaded. // type Options struct { // Provides config values for the SDK to use when creating service clients // and making API requests to services. Any value set in with this field // will override the associated value provided by the SDK defaults, // environment or config files where relevant. // // If not set, configuration values from from SDK defaults, environment, // config will be used. Config aws.Config // Overrides the config profile the Session should be created from. If not // set the value of the environment variable will be loaded (AWS_PROFILE, // or AWS_DEFAULT_PROFILE if the Shared Config is enabled). // // If not set and environment variables are not set the "default" // (DefaultSharedConfigProfile) will be used as the profile to load the // session config from. Profile string // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG // environment variable. By default a Session will be created using the // value provided by the AWS_SDK_LOAD_CONFIG environment variable. // // Setting this value to SharedConfigEnable or SharedConfigDisable // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable // and enable or disable the shared config functionality. SharedConfigState SharedConfigState // Ordered list of files the session will load configuration from. // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE. SharedConfigFiles []string // When the SDK's shared config is configured to assume a role with MFA // this option is required in order to provide the mechanism that will // retrieve the MFA token. There is no default value for this field. If // it is not set an error will be returned when creating the session. // // This token provider will be called when ever the assumed role's // credentials need to be refreshed. Within the context of service clients // all sharing the same session the SDK will ensure calls to the token // provider are atomic. When sharing a token provider across multiple // sessions additional synchronization logic is needed to ensure the // token providers do not introduce race conditions. It is recommend to // share the session where possible. // // stscreds.StdinTokenProvider is a basic implementation that will prompt // from stdin for the MFA token code. // // This field is only used if the shared configuration is enabled, and // the config enables assume role wit MFA via the mfa_serial field. AssumeRoleTokenProvider func() (string, error) // When the SDK's shared config is configured to assume a role this option // may be provided to set the expiry duration of the STS credentials. // Defaults to 15 minutes if not set as documented in the // stscreds.AssumeRoleProvider. AssumeRoleDuration time.Duration // Reader for a custom Credentials Authority (CA) bundle in PEM format that // the SDK will use instead of the default system's root CA bundle. Use this // only if you want to replace the CA bundle the SDK uses for TLS requests. // // HTTP Client's Transport concrete implementation must be a http.Transport // or creating the session will fail. // // If the Transport's TLS config is set this option will cause the SDK // to overwrite the Transport's TLS config's RootCAs value. If the CA // bundle reader contains multiple certificates all of them will be loaded. // // Can also be specified via the environment variable: // // AWS_CA_BUNDLE=$HOME/ca_bundle // // Can also be specified via the shared config field: // // ca_bundle = $HOME/ca_bundle CustomCABundle io.Reader // Reader for the TLC client certificate that should be used by the SDK's // HTTP transport when making requests. The certificate must be paired with // a TLS client key file. Will be ignored if both are not provided. // // HTTP Client's Transport concrete implementation must be a http.Transport // or creating the session will fail. // // Can also be specified via the environment variable: // // AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert ClientTLSCert io.Reader // Reader for the TLC client key that should be used by the SDK's HTTP // transport when making requests. The key must be paired with a TLS client // certificate file. Will be ignored if both are not provided. // // HTTP Client's Transport concrete implementation must be a http.Transport // or creating the session will fail. // // Can also be specified via the environment variable: // // AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key ClientTLSKey io.Reader // The handlers that the session and all API clients will be created with. // This must be a complete set of handlers. Use the defaults.Handlers() // function to initialize this value before changing the handlers to be // used by the SDK. Handlers request.Handlers // Allows specifying a custom endpoint to be used by the EC2 IMDS client // when making requests to the EC2 IMDS API. The endpoint value should // include the URI scheme. If the scheme is not present it will be defaulted to http. // // If unset, will the EC2 IMDS client will use its default endpoint. // // Can also be specified via the environment variable, // AWS_EC2_METADATA_SERVICE_ENDPOINT. // // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 // // If using an URL with an IPv6 address literal, the IPv6 address // component must be enclosed in square brackets. // // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] EC2IMDSEndpoint string // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) // // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState } // NewSessionWithOptions returns a new Session created from SDK defaults, config files, // environment, and user provided config files. This func uses the Options // values to configure how the Session is created. // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded in addition to // the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. Enabling the Shared Config will also allow the Session // to be built with retrieving credentials with AssumeRole set in the config. // // // Equivalent to session.New // sess := session.Must(session.NewSessionWithOptions(session.Options{})) // // // Specify profile to load for the session's config // sess := session.Must(session.NewSessionWithOptions(session.Options{ // Profile: "profile_name", // })) // // // Specify profile for config and region for requests // sess := session.Must(session.NewSessionWithOptions(session.Options{ // Config: aws.Config{Region: aws.String("us-east-1")}, // Profile: "profile_name", // })) // // // Force enable Shared Config support // sess := session.Must(session.NewSessionWithOptions(session.Options{ // SharedConfigState: session.SharedConfigEnable, // })) func NewSessionWithOptions(opts Options) (*Session, error) { var envCfg envConfig var err error if opts.SharedConfigState == SharedConfigEnable { envCfg, err = loadSharedEnvConfig() if err != nil { return nil, fmt.Errorf("failed to load shared config, %v", err) } } else { envCfg, err = loadEnvConfig() if err != nil { return nil, fmt.Errorf("failed to load environment config, %v", err) } } if len(opts.Profile) != 0 { envCfg.Profile = opts.Profile } switch opts.SharedConfigState { case SharedConfigDisable: envCfg.EnableSharedConfig = false case SharedConfigEnable: envCfg.EnableSharedConfig = true } return newSession(opts, envCfg, &opts.Config) } // Must is a helper function to ensure the Session is valid and there was no // error when calling a NewSession function. // // This helper is intended to be used in variable initialization to load the // Session and configuration at startup. Such as: // // var sess = session.Must(session.NewSession()) func Must(sess *Session, err error) *Session { if err != nil { panic(err) } return sess } // Wraps the endpoint resolver with a resolver that will return a custom // endpoint for EC2 IMDS. func wrapEC2IMDSEndpoint(resolver endpoints.Resolver, endpoint string, mode endpoints.EC2IMDSEndpointModeState) endpoints.Resolver { return endpoints.ResolverFunc( func(service, region string, opts ...func(*endpoints.Options)) ( endpoints.ResolvedEndpoint, error, ) { if service == ec2MetadataServiceID && len(endpoint) > 0 { return endpoints.ResolvedEndpoint{ URL: endpoint, SigningName: ec2MetadataServiceID, SigningRegion: region, }, nil } else if service == ec2MetadataServiceID { opts = append(opts, func(o *endpoints.Options) { o.EC2MetadataEndpointMode = mode }) } return resolver.EndpointFor(service, region, opts...) }) } func deprecatedNewSession(envCfg envConfig, cfgs ...*aws.Config) *Session { cfg := defaults.Config() handlers := defaults.Handlers() // Apply the passed in configs so the configuration can be applied to the // default credential chain cfg.MergeIn(cfgs...) if cfg.EndpointResolver == nil { // An endpoint resolver is required for a session to be able to provide // endpoints for service client configurations. cfg.EndpointResolver = endpoints.DefaultResolver() } if !(len(envCfg.EC2IMDSEndpoint) == 0 && envCfg.EC2IMDSEndpointMode == endpoints.EC2IMDSEndpointModeStateUnset) { cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint, envCfg.EC2IMDSEndpointMode) } cfg.Credentials = defaults.CredChain(cfg, handlers) // Reapply any passed in configs to override credentials if set cfg.MergeIn(cfgs...) s := &Session{ Config: cfg, Handlers: handlers, options: Options{ EC2IMDSEndpoint: envCfg.EC2IMDSEndpoint, }, } initHandlers(s) return s } func enableCSM(handlers *request.Handlers, cfg csmConfig, logger aws.Logger) error { if logger != nil { logger.Log("Enabling CSM") } r, err := csm.Start(cfg.ClientID, csm.AddressWithDefaults(cfg.Host, cfg.Port)) if err != nil { return err } r.InjectHandlers(handlers) return nil } func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { cfg := defaults.Config() handlers := opts.Handlers if handlers.IsEmpty() { handlers = defaults.Handlers() } // Get a merged version of the user provided config to determine if // credentials were. userCfg := &aws.Config{} userCfg.MergeIn(cfgs...) cfg.MergeIn(userCfg) // Ordered config files will be loaded in with later files overwriting // previous config file values. var cfgFiles []string if opts.SharedConfigFiles != nil { cfgFiles = opts.SharedConfigFiles } else { cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile} if !envCfg.EnableSharedConfig { // The shared config file (~/.aws/config) is only loaded if instructed // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG). cfgFiles = cfgFiles[1:] } } // Load additional config from file(s) sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles, envCfg.EnableSharedConfig) if err != nil { if len(envCfg.Profile) == 0 && !envCfg.EnableSharedConfig && (envCfg.Creds.HasKeys() || userCfg.Credentials != nil) { // Special case where the user has not explicitly specified an AWS_PROFILE, // or session.Options.profile, shared config is not enabled, and the // environment has credentials, allow the shared config file to fail to // load since the user has already provided credentials, and nothing else // is required to be read file. Github(aws/aws-sdk-go#2455) } else if _, ok := err.(SharedConfigProfileNotExistsError); !ok { return nil, err } } if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { return nil, err } if err := setTLSOptions(&opts, cfg, envCfg, sharedCfg); err != nil { return nil, err } s := &Session{ Config: cfg, Handlers: handlers, options: opts, } initHandlers(s) if csmCfg, err := loadCSMConfig(envCfg, cfgFiles); err != nil { if l := s.Config.Logger; l != nil { l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err)) } } else if csmCfg.Enabled { err = enableCSM(&s.Handlers, csmCfg, s.Config.Logger) if err != nil { return nil, err } } return s, nil } type csmConfig struct { Enabled bool Host string Port string ClientID string } var csmProfileName = "aws_csm" func loadCSMConfig(envCfg envConfig, cfgFiles []string) (csmConfig, error) { if envCfg.CSMEnabled != nil { if *envCfg.CSMEnabled { return csmConfig{ Enabled: true, ClientID: envCfg.CSMClientID, Host: envCfg.CSMHost, Port: envCfg.CSMPort, }, nil } return csmConfig{}, nil } sharedCfg, err := loadSharedConfig(csmProfileName, cfgFiles, false) if err != nil { if _, ok := err.(SharedConfigProfileNotExistsError); !ok { return csmConfig{}, err } } if sharedCfg.CSMEnabled != nil && *sharedCfg.CSMEnabled == true { return csmConfig{ Enabled: true, ClientID: sharedCfg.CSMClientID, Host: sharedCfg.CSMHost, Port: sharedCfg.CSMPort, }, nil } return csmConfig{}, nil } func setTLSOptions(opts *Options, cfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig) error { // CA Bundle can be specified in both environment variable shared config file. var caBundleFilename = envCfg.CustomCABundle if len(caBundleFilename) == 0 { caBundleFilename = sharedCfg.CustomCABundle } // Only use environment value if session option is not provided. customTLSOptions := map[string]struct { filename string field *io.Reader errCode string }{ "custom CA bundle PEM": {filename: caBundleFilename, field: &opts.CustomCABundle, errCode: ErrCodeLoadCustomCABundle}, "custom client TLS cert": {filename: envCfg.ClientTLSCert, field: &opts.ClientTLSCert, errCode: ErrCodeLoadClientTLSCert}, "custom client TLS key": {filename: envCfg.ClientTLSKey, field: &opts.ClientTLSKey, errCode: ErrCodeLoadClientTLSCert}, } for name, v := range customTLSOptions { if len(v.filename) != 0 && *v.field == nil { f, err := os.Open(v.filename) if err != nil { return awserr.New(v.errCode, fmt.Sprintf("failed to open %s file", name), err) } defer f.Close() *v.field = f } } // Setup HTTP client with custom cert bundle if enabled if opts.CustomCABundle != nil { if err := loadCustomCABundle(cfg.HTTPClient, opts.CustomCABundle); err != nil { return err } } // Setup HTTP client TLS certificate and key for client TLS authentication. if opts.ClientTLSCert != nil && opts.ClientTLSKey != nil { if err := loadClientTLSCert(cfg.HTTPClient, opts.ClientTLSCert, opts.ClientTLSKey); err != nil { return err } } else if opts.ClientTLSCert == nil && opts.ClientTLSKey == nil { // Do nothing if neither values are available. } else { return awserr.New(ErrCodeLoadClientTLSCert, fmt.Sprintf("client TLS cert(%t) and key(%t) must both be provided", opts.ClientTLSCert != nil, opts.ClientTLSKey != nil), nil) } return nil } func getHTTPTransport(client *http.Client) (*http.Transport, error) { var t *http.Transport switch v := client.Transport.(type) { case *http.Transport: t = v default: if client.Transport != nil { return nil, fmt.Errorf("unsupported transport, %T", client.Transport) } } if t == nil { // Nil transport implies `http.DefaultTransport` should be used. Since // the SDK cannot modify, nor copy the `DefaultTransport` specifying // the values the next closest behavior. t = getCustomTransport() } return t, nil } func loadCustomCABundle(client *http.Client, bundle io.Reader) error { t, err := getHTTPTransport(client) if err != nil { return awserr.New(ErrCodeLoadCustomCABundle, "unable to load custom CA bundle, HTTPClient's transport unsupported type", err) } p, err := loadCertPool(bundle) if err != nil { return err } if t.TLSClientConfig == nil { t.TLSClientConfig = &tls.Config{} } t.TLSClientConfig.RootCAs = p client.Transport = t return nil } func loadCertPool(r io.Reader) (*x509.CertPool, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, awserr.New(ErrCodeLoadCustomCABundle, "failed to read custom CA bundle PEM file", err) } p := x509.NewCertPool() if !p.AppendCertsFromPEM(b) { return nil, awserr.New(ErrCodeLoadCustomCABundle, "failed to load custom CA bundle PEM file", err) } return p, nil } func loadClientTLSCert(client *http.Client, certFile, keyFile io.Reader) error { t, err := getHTTPTransport(client) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to get usable HTTP transport from client", err) } cert, err := ioutil.ReadAll(certFile) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to get read client TLS cert file", err) } key, err := ioutil.ReadAll(keyFile) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to get read client TLS key file", err) } clientCert, err := tls.X509KeyPair(cert, key) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to load x509 key pair from client cert", err) } tlsCfg := t.TLSClientConfig if tlsCfg == nil { tlsCfg = &tls.Config{} } tlsCfg.Certificates = append(tlsCfg.Certificates, clientCert) t.TLSClientConfig = tlsCfg client.Transport = t return nil } func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options, ) error { // 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) } } if cfg.EnableEndpointDiscovery == nil { if envCfg.EnableEndpointDiscovery != nil { cfg.WithEndpointDiscovery(*envCfg.EnableEndpointDiscovery) } else if envCfg.EnableSharedConfig && sharedCfg.EnableEndpointDiscovery != nil { cfg.WithEndpointDiscovery(*sharedCfg.EnableEndpointDiscovery) } } // Regional Endpoint flag for STS endpoint resolving mergeSTSRegionalEndpointConfig(cfg, []endpoints.STSRegionalEndpoint{ userCfg.STSRegionalEndpoint, envCfg.STSRegionalEndpoint, sharedCfg.STSRegionalEndpoint, endpoints.LegacySTSEndpoint, }) // Regional Endpoint flag for S3 endpoint resolving mergeS3UsEast1RegionalEndpointConfig(cfg, []endpoints.S3UsEast1RegionalEndpoint{ userCfg.S3UsEast1RegionalEndpoint, envCfg.S3UsEast1RegionalEndpoint, sharedCfg.S3UsEast1RegionalEndpoint, endpoints.LegacyS3UsEast1Endpoint, }) var ec2IMDSEndpoint string for _, v := range []string{ sessOpts.EC2IMDSEndpoint, envCfg.EC2IMDSEndpoint, sharedCfg.EC2IMDSEndpoint, } { if len(v) != 0 { ec2IMDSEndpoint = v break } } var endpointMode endpoints.EC2IMDSEndpointModeState for _, v := range []endpoints.EC2IMDSEndpointModeState{ sessOpts.EC2IMDSEndpointMode, envCfg.EC2IMDSEndpointMode, sharedCfg.EC2IMDSEndpointMode, } { if v != endpoints.EC2IMDSEndpointModeStateUnset { endpointMode = v break } } if len(ec2IMDSEndpoint) != 0 || endpointMode != endpoints.EC2IMDSEndpointModeStateUnset { cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint, endpointMode) } // Configure credentials if not already set by the user when creating the // Session. if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { creds, err := resolveCredentials(cfg, envCfg, sharedCfg, handlers, sessOpts) if err != nil { return err } cfg.Credentials = creds } cfg.S3UseARNRegion = userCfg.S3UseARNRegion if cfg.S3UseARNRegion == nil { cfg.S3UseARNRegion = &envCfg.S3UseARNRegion } if cfg.S3UseARNRegion == nil { cfg.S3UseARNRegion = &sharedCfg.S3UseARNRegion } return nil } func mergeSTSRegionalEndpointConfig(cfg *aws.Config, values []endpoints.STSRegionalEndpoint) { for _, v := range values { if v != endpoints.UnsetSTSEndpoint { cfg.STSRegionalEndpoint = v break } } } func mergeS3UsEast1RegionalEndpointConfig(cfg *aws.Config, values []endpoints.S3UsEast1RegionalEndpoint) { for _, v := range values { if v != endpoints.UnsetS3UsEast1Endpoint { cfg.S3UsEast1RegionalEndpoint = v break } } } func initHandlers(s *Session) { // Add the Validate parameter handler if it is not disabled. s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) if !aws.BoolValue(s.Config.DisableParamValidation) { s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) } } // Copy creates and returns a copy of the current Session, copying the config // and handlers. If any additional configs are provided they will be merged // on top of the Session's copied config. // // // Create a copy of the current Session, configured for the us-west-2 region. // sess.Copy(&aws.Config{Region: aws.String("us-west-2")}) func (s *Session) Copy(cfgs ...*aws.Config) *Session { newSession := &Session{ Config: s.Config.Copy(cfgs...), Handlers: s.Handlers.Copy(), options: s.options, } initHandlers(newSession) return newSession } // ClientConfig satisfies the client.ConfigProvider interface and is used to // configure the service client instances. Passing the Session to the service // client's constructor (New) will use this method to configure the client. func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config { s = s.Copy(cfgs...) region := aws.StringValue(s.Config.Region) resolved, err := s.resolveEndpoint(service, region, s.Config) if err != nil { s.Handlers.Validate.PushBack(func(r *request.Request) { if len(r.ClientInfo.Endpoint) != 0 { // Error occurred while resolving endpoint, but the request // being invoked has had an endpoint specified after the client // was created. return } r.Error = err }) } return client.Config{ Config: s.Config, Handlers: s.Handlers, PartitionID: resolved.PartitionID, Endpoint: resolved.URL, SigningRegion: resolved.SigningRegion, SigningNameDerived: resolved.SigningNameDerived, SigningName: resolved.SigningName, } } const ec2MetadataServiceID = "ec2metadata" func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) { if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 { return endpoints.ResolvedEndpoint{ URL: endpoints.AddScheme(ep, aws.BoolValue(cfg.DisableSSL)), SigningRegion: region, }, nil } resolved, err := cfg.EndpointResolver.EndpointFor(service, region, func(opt *endpoints.Options) { opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) // Support for STSRegionalEndpoint where the STSRegionalEndpoint is // provided in envConfig or sharedConfig with envConfig getting // precedence. opt.STSRegionalEndpoint = cfg.STSRegionalEndpoint // Support for S3UsEast1RegionalEndpoint where the S3UsEast1RegionalEndpoint is // provided in envConfig or sharedConfig with envConfig getting // precedence. opt.S3UsEast1RegionalEndpoint = cfg.S3UsEast1RegionalEndpoint // Support the condition where the service is modeled but its // endpoint metadata is not available. opt.ResolveUnknownService = true }, ) if err != nil { return endpoints.ResolvedEndpoint{}, err } return resolved, nil } // ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception // that the EndpointResolver will not be used to resolve the endpoint. The only // endpoint set must come from the aws.Config.Endpoint field. func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { s = s.Copy(cfgs...) var resolved endpoints.ResolvedEndpoint if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) resolved.SigningRegion = aws.StringValue(s.Config.Region) } return client.Config{ Config: s.Config, Handlers: s.Handlers, Endpoint: resolved.URL, SigningRegion: resolved.SigningRegion, SigningNameDerived: resolved.SigningNameDerived, SigningName: resolved.SigningName, } } // logDeprecatedNewSessionError function enables error handling for session func (s *Session) logDeprecatedNewSessionError(msg string, err error, cfgs []*aws.Config) { // Session creation failed, need to report the error and prevent // any requests from succeeding. s.Config.MergeIn(cfgs...) s.Config.Logger.Log("ERROR:", msg, "Error:", err) s.Handlers.Validate.PushBack(func(r *request.Request) { r.Error = err }) }
942
session-manager-plugin
aws
Go
// +build go1.7 package session import ( "bytes" "fmt" "net/http" "os" "path/filepath" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/s3" ) func TestNewDefaultSession(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() s := New(&aws.Config{Region: aws.String("region")}) if e, a := "region", *s.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := http.DefaultClient, s.Config.HTTPClient; e != a { t.Errorf("expect %v, got %v", e, a) } if s.Config.Logger == nil { t.Errorf("expect not nil") } if e, a := aws.LogOff, *s.Config.LogLevel; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestNew_WithCustomCreds(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() customCreds := credentials.NewStaticCredentials("AKID", "SECRET", "TOKEN") s := New(&aws.Config{Credentials: customCreds}) if e, a := customCreds, s.Config.Credentials; e != a { t.Errorf("expect %v, got %v", e, a) } } type mockLogger struct { *bytes.Buffer } func (w mockLogger) Log(args ...interface{}) { fmt.Fprintln(w, args...) } func TestNew_WithSessionLoadError(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_CONFIG_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "assume_role_invalid_source_profile") logger := bytes.Buffer{} s := New(&aws.Config{ Region: aws.String("us-west-2"), Logger: &mockLogger{&logger}, }) if s == nil { t.Errorf("expect not nil") } svc := s3.New(s) _, err := svc.ListBuckets(&s3.ListBucketsInput{}) if err == nil { t.Errorf("expect not nil") } if e, a := "ERROR: failed to create session with AWS_SDK_LOAD_CONFIG enabled", logger.String(); !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } expectErr := SharedConfigAssumeRoleError{ RoleARN: "assume_role_invalid_source_profile_role_arn", SourceProfile: "profile_not_exists", } if e, a := expectErr.Error(), err.Error(); !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestSessionCopy(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_REGION", "orig_region") s := Session{ Config: defaults.Config(), Handlers: defaults.Handlers(), } newSess := s.Copy(&aws.Config{Region: aws.String("new_region")}) if e, a := "orig_region", *s.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "new_region", *newSess.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSessionClientConfig(t *testing.T) { s, err := NewSession(&aws.Config{ Credentials: credentials.AnonymousCredentials, Region: aws.String("orig_region"), EndpointResolver: endpoints.ResolverFunc( func(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { if e, a := "mock-service", service; e != a { t.Errorf("expect %q service, got %q", e, a) } if e, a := "other-region", region; e != a { t.Errorf("expect %q region, got %q", e, a) } return endpoints.ResolvedEndpoint{ URL: "https://" + service + "." + region + ".amazonaws.com", SigningRegion: region, }, nil }, ), }) if err != nil { t.Errorf("expect nil, %v", err) } cfg := s.ClientConfig("mock-service", &aws.Config{Region: aws.String("other-region")}) if e, a := "https://mock-service.other-region.amazonaws.com", cfg.Endpoint; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "other-region", cfg.SigningRegion; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "other-region", *cfg.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestNewSession_ResolveEndpointError(t *testing.T) { logger := mockLogger{Buffer: bytes.NewBuffer(nil)} sess, err := NewSession(defaults.Config(), &aws.Config{ Region: aws.String(""), Logger: logger, EndpointResolver: endpoints.ResolverFunc( func(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { return endpoints.ResolvedEndpoint{}, fmt.Errorf("mock error") }, ), }) if err != nil { t.Fatalf("expect no error got %v", err) } cfg := sess.ClientConfig("mock service") var r request.Request cfg.Handlers.Validate.Run(&r) if r.Error == nil { t.Fatalf("expect validation error, got none") } if e, a := aws.ErrMissingRegion.Error(), r.Error.Error(); !strings.Contains(a, e) { t.Errorf("expect %v validation error, got %v", e, a) } if v := logger.Buffer.String(); len(v) != 0 { t.Errorf("expect nothing logged, got %s", v) } } func TestNewSession_NoCredentials(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() s, err := NewSession() if err != nil { t.Errorf("expect nil, %v", err) } if s.Config.Credentials == nil { t.Errorf("expect not nil") } if e, a := credentials.AnonymousCredentials, s.Config.Credentials; e == a { t.Errorf("expect different credentials, %v", e) } } func TestNewSessionWithOptions_OverrideProfile(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "other_profile") s, err := NewSessionWithOptions(Options{ Profile: "full_profile", }) if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "full_profile_region", *s.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } creds, err := s.Config.Credentials.Get() if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "full_profile_akid", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "full_profile_secret", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("expect empty, got %v", v) } if e, a := "SharedConfigCredentials", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestNewSessionWithOptions_OverrideSharedConfigEnable(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "0") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "full_profile") s, err := NewSessionWithOptions(Options{ SharedConfigState: SharedConfigEnable, }) if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "full_profile_region", *s.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } creds, err := s.Config.Credentials.Get() if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "full_profile_akid", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "full_profile_secret", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("expect empty, got %v", v) } if e, a := "SharedConfigCredentials", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestNewSessionWithOptions_OverrideSharedConfigDisable(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "full_profile") s, err := NewSessionWithOptions(Options{ SharedConfigState: SharedConfigDisable, }) if err != nil { t.Errorf("expect nil, %v", err) } if v := *s.Config.Region; len(v) != 0 { t.Errorf("expect empty, got %v", v) } creds, err := s.Config.Credentials.Get() if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "full_profile_akid", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "full_profile_secret", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("expect empty, got %v", v) } if e, a := "SharedConfigCredentials", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestNewSessionWithOptions_OverrideSharedConfigFiles(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() os.Setenv("AWS_SDK_LOAD_CONFIG", "1") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) os.Setenv("AWS_PROFILE", "config_file_load_order") s, err := NewSessionWithOptions(Options{ SharedConfigFiles: []string{testConfigOtherFilename}, }) if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "shared_config_other_region", *s.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } creds, err := s.Config.Credentials.Get() if err != nil { t.Errorf("expect nil, %v", err) } if e, a := "shared_config_other_akid", creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "shared_config_other_secret", creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("expect empty, got %v", v) } if e, a := "SharedConfigCredentials", creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } } func TestNewSessionWithOptions_Overrides(t *testing.T) { cases := map[string]struct { InEnvs map[string]string InProfile string OutRegion string OutCreds credentials.Value }{ "env profile with opt profile": { InEnvs: map[string]string{ "AWS_SDK_LOAD_CONFIG": "0", "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, "AWS_PROFILE": "other_profile", }, InProfile: "full_profile", OutRegion: "full_profile_region", OutCreds: credentials.Value{ AccessKeyID: "full_profile_akid", SecretAccessKey: "full_profile_secret", ProviderName: "SharedConfigCredentials", }, }, "env creds with env profile": { InEnvs: map[string]string{ "AWS_SDK_LOAD_CONFIG": "0", "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, "AWS_REGION": "env_region", "AWS_ACCESS_KEY": "env_akid", "AWS_SECRET_ACCESS_KEY": "env_secret", "AWS_PROFILE": "other_profile", }, OutRegion: "env_region", OutCreds: credentials.Value{ AccessKeyID: "env_akid", SecretAccessKey: "env_secret", ProviderName: "EnvConfigCredentials", }, }, "env creds with opt profile": { InEnvs: map[string]string{ "AWS_SDK_LOAD_CONFIG": "0", "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, "AWS_REGION": "env_region", "AWS_ACCESS_KEY": "env_akid", "AWS_SECRET_ACCESS_KEY": "env_secret", "AWS_PROFILE": "other_profile", }, InProfile: "full_profile", OutRegion: "env_region", OutCreds: credentials.Value{ AccessKeyID: "full_profile_akid", SecretAccessKey: "full_profile_secret", ProviderName: "SharedConfigCredentials", }, }, "cfg and cred file with opt profile": { InEnvs: map[string]string{ "AWS_SDK_LOAD_CONFIG": "0", "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, "AWS_CONFIG_FILE": testConfigOtherFilename, "AWS_PROFILE": "other_profile", }, InProfile: "config_file_load_order", OutRegion: "shared_config_region", OutCreds: credentials.Value{ AccessKeyID: "shared_config_akid", SecretAccessKey: "shared_config_secret", ProviderName: "SharedConfigCredentials", }, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() for k, v := range c.InEnvs { os.Setenv(k, v) } s, err := NewSessionWithOptions(Options{ Profile: c.InProfile, SharedConfigState: SharedConfigEnable, }) if err != nil { t.Fatalf("expect no error, got %v", err) } creds, err := s.Config.Credentials.Get() if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := c.OutRegion, *s.Config.Region; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := c.OutCreds.AccessKeyID, creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := c.OutCreds.SecretAccessKey, creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := c.OutCreds.SessionToken, creds.SessionToken; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := c.OutCreds.ProviderName, creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } }) } } func TestNewSession_EnvCredsWithInvalidConfigFile(t *testing.T) { cases := map[string]struct { AccessKey, SecretKey string Profile string Options Options ExpectCreds credentials.Value Err string }{ "no options": { Err: "SharedConfigLoadError", }, "env only": { AccessKey: "env_akid", SecretKey: "env_secret", ExpectCreds: credentials.Value{ AccessKeyID: "env_akid", SecretAccessKey: "env_secret", ProviderName: "EnvConfigCredentials", }, }, "static credentials only": { Options: Options{ Config: aws.Config{ Credentials: credentials.NewStaticCredentials( "AKID", "SECRET", ""), }, }, ExpectCreds: credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", ProviderName: "StaticProvider", }, }, "env profile and env": { AccessKey: "env_akid", SecretKey: "env_secret", Profile: "env_profile", Err: "SharedConfigLoadError", }, "opt profile and env": { AccessKey: "env_akid", SecretKey: "env_secret", Options: Options{ Profile: "someProfile", }, Err: "SharedConfigLoadError", }, "cfg enabled": { AccessKey: "env_akid", SecretKey: "env_secret", Options: Options{ SharedConfigState: SharedConfigEnable, }, Err: "SharedConfigLoadError", }, } var cfgFile = filepath.Join("testdata", "shared_config_invalid_ini") for name, c := range cases { t.Run(name, func(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() if v := c.AccessKey; len(v) != 0 { os.Setenv("AWS_ACCESS_KEY", v) } if v := c.SecretKey; len(v) != 0 { os.Setenv("AWS_SECRET_ACCESS_KEY", v) } if v := c.Profile; len(v) != 0 { os.Setenv("AWS_PROFILE", v) } opts := c.Options opts.SharedConfigFiles = []string{cfgFile} s, err := NewSessionWithOptions(opts) if len(c.Err) != 0 { if err == nil { t.Fatalf("expect session error, got none") } if e, a := c.Err, err.Error(); !strings.Contains(a, e) { t.Fatalf("expect session error to contain %q, got %v", e, a) } return } if err != nil { t.Fatalf("expect no error, got %v", err) } creds, err := s.Config.Credentials.Get() if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := c.ExpectCreds.AccessKeyID, creds.AccessKeyID; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := c.ExpectCreds.SecretAccessKey, creds.SecretAccessKey; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := c.ExpectCreds.ProviderName, creds.ProviderName; !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } }) } } func TestSession_RegionalEndpoints(t *testing.T) { cases := map[string]struct { Env map[string]string Config aws.Config ExpectErr string ExpectSTS endpoints.STSRegionalEndpoint ExpectS3UsEast1 endpoints.S3UsEast1RegionalEndpoint }{ "default": { ExpectSTS: endpoints.LegacySTSEndpoint, ExpectS3UsEast1: endpoints.LegacyS3UsEast1Endpoint, }, "enable regional": { Config: aws.Config{ STSRegionalEndpoint: endpoints.RegionalSTSEndpoint, S3UsEast1RegionalEndpoint: endpoints.RegionalS3UsEast1Endpoint, }, ExpectSTS: endpoints.RegionalSTSEndpoint, ExpectS3UsEast1: endpoints.RegionalS3UsEast1Endpoint, }, "sts env enable": { Env: map[string]string{ "AWS_STS_REGIONAL_ENDPOINTS": "regional", }, ExpectSTS: endpoints.RegionalSTSEndpoint, ExpectS3UsEast1: endpoints.LegacyS3UsEast1Endpoint, }, "sts us-east-1 env merge enable": { Env: map[string]string{ "AWS_STS_REGIONAL_ENDPOINTS": "legacy", }, Config: aws.Config{ STSRegionalEndpoint: endpoints.RegionalSTSEndpoint, }, ExpectSTS: endpoints.RegionalSTSEndpoint, ExpectS3UsEast1: endpoints.LegacyS3UsEast1Endpoint, }, "s3 us-east-1 env enable": { Env: map[string]string{ "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT": "regional", }, ExpectSTS: endpoints.LegacySTSEndpoint, ExpectS3UsEast1: endpoints.RegionalS3UsEast1Endpoint, }, "s3 us-east-1 env merge enable": { Env: map[string]string{ "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT": "legacy", }, Config: aws.Config{ S3UsEast1RegionalEndpoint: endpoints.RegionalS3UsEast1Endpoint, }, ExpectSTS: endpoints.LegacySTSEndpoint, ExpectS3UsEast1: endpoints.RegionalS3UsEast1Endpoint, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() for k, v := range c.Env { os.Setenv(k, v) } s, err := NewSession(&c.Config) if len(c.ExpectErr) != 0 { if err == nil { t.Fatalf("expect session error, got none") } if e, a := c.ExpectErr, err.Error(); !strings.Contains(a, e) { t.Fatalf("expect session error to contain %q, got %v", e, a) } return } if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := c.ExpectSTS, s.Config.STSRegionalEndpoint; e != a { t.Errorf("expect %v STSRegionalEndpoint, got %v", e, a) } if e, a := c.ExpectS3UsEast1, s.Config.S3UsEast1RegionalEndpoint; e != a { t.Errorf("expect %v S3UsEast1RegionalEndpoint, got %v", e, a) } // Asserts }) } } func TestSession_ClientConfig_ResolveEndpoint(t *testing.T) { cases := map[string]struct { Service string Region string Env map[string]string Options Options ExpectEndpoint string }{ "IMDS custom endpoint from env": { Service: ec2MetadataServiceID, Region: "ignored", Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://example.aws", }, ExpectEndpoint: "http://example.aws", }, "IMDS custom endpoint from aws.Config": { Service: ec2MetadataServiceID, Region: "ignored", Options: Options{ EC2IMDSEndpoint: "http://example.aws", }, ExpectEndpoint: "http://example.aws", }, "IMDS custom endpoint from aws.Config and env": { Service: ec2MetadataServiceID, Region: "ignored", Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://wrong.example.aws", }, Options: Options{ EC2IMDSEndpoint: "http://correct.example.aws", }, ExpectEndpoint: "http://correct.example.aws", }, "IMDS custom endpoint from profile": { Service: ec2MetadataServiceID, Options: Options{ SharedConfigState: SharedConfigEnable, SharedConfigFiles: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpoint", }, Region: "ignored", ExpectEndpoint: "http://endpoint.localhost", }, "IMDS custom endpoint from profile and env": { Service: ec2MetadataServiceID, Options: Options{ SharedConfigFiles: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpoint", }, Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://endpoint-env.localhost", }, Region: "ignored", ExpectEndpoint: "http://endpoint-env.localhost", }, "IMDS IPv6 mode from profile": { Service: ec2MetadataServiceID, Options: Options{ SharedConfigState: SharedConfigEnable, SharedConfigFiles: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointModeIPv6", }, Region: "ignored", ExpectEndpoint: "http://[fd00:ec2::254]/latest", }, "IMDS IPv4 mode from profile": { Service: ec2MetadataServiceID, Options: Options{ SharedConfigFiles: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointModeIPv4", }, Region: "ignored", ExpectEndpoint: "http://169.254.169.254/latest", }, "IMDS IPv6 mode in env": { Service: ec2MetadataServiceID, Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv6", }, Region: "ignored", ExpectEndpoint: "http://[fd00:ec2::254]/latest", }, "IMDS IPv4 mode in env": { Service: ec2MetadataServiceID, Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv4", }, Region: "ignored", ExpectEndpoint: "http://169.254.169.254/latest", }, "IMDS mode in env and profile": { Service: ec2MetadataServiceID, Options: Options{ SharedConfigFiles: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointModeIPv4", }, Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv6", }, Region: "ignored", ExpectEndpoint: "http://[fd00:ec2::254]/latest", }, "IMDS mode and endpoint profile": { Service: ec2MetadataServiceID, Options: Options{ SharedConfigState: SharedConfigEnable, SharedConfigFiles: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointAndModeMixed", }, Region: "ignored", ExpectEndpoint: "http://endpoint.localhost", }, "IMDS mode session option and env": { Service: ec2MetadataServiceID, Options: Options{ EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv6, }, Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE": "IPv4", }, Region: "ignored", ExpectEndpoint: "http://[fd00:ec2::254]/latest", }, "IMDS endpoint session option and env": { Service: ec2MetadataServiceID, Options: Options{ EC2IMDSEndpoint: "http://endpoint.localhost", }, Env: map[string]string{ "AWS_EC2_METADATA_SERVICE_ENDPOINT": "http://endpoint-env.localhost", }, Region: "ignored", ExpectEndpoint: "http://endpoint.localhost", }, } for name, c := range cases { t.Run(name, func(t *testing.T) { restoreEnvFn := initSessionTestEnv() defer restoreEnvFn() for k, v := range c.Env { os.Setenv(k, v) } s, err := NewSessionWithOptions(c.Options) if err != nil { t.Fatalf("expect no error, got %v", err) } clientCfg := s.ClientConfig(c.Service, &aws.Config{ Region: aws.String(c.Region), }) if e, a := c.ExpectEndpoint, clientCfg.Endpoint; e != a { t.Errorf("expect %v, got %v", e, a) } }) } }
829
session-manager-plugin
aws
Go
package session import ( "fmt" "strings" "time" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/internal/ini" ) const ( // Static Credentials group accessKeyIDKey = `aws_access_key_id` // group required secretAccessKey = `aws_secret_access_key` // group required sessionTokenKey = `aws_session_token` // optional // Assume Role Credentials group roleArnKey = `role_arn` // group required sourceProfileKey = `source_profile` // group required (or credential_source) credentialSourceKey = `credential_source` // group required (or source_profile) externalIDKey = `external_id` // optional mfaSerialKey = `mfa_serial` // optional roleSessionNameKey = `role_session_name` // optional roleDurationSecondsKey = "duration_seconds" // optional // AWS Single Sign-On (AWS SSO) group ssoAccountIDKey = "sso_account_id" ssoRegionKey = "sso_region" ssoRoleNameKey = "sso_role_name" ssoStartURL = "sso_start_url" // CSM options csmEnabledKey = `csm_enabled` csmHostKey = `csm_host` csmPortKey = `csm_port` csmClientIDKey = `csm_client_id` // Additional Config fields regionKey = `region` // custom CA Bundle filename customCABundleKey = `ca_bundle` // endpoint discovery group enableEndpointDiscoveryKey = `endpoint_discovery_enabled` // optional // External Credential Process credentialProcessKey = `credential_process` // optional // Web Identity Token File webIdentityTokenFileKey = `web_identity_token_file` // optional // Additional config fields for regional or legacy endpoints stsRegionalEndpointSharedKey = `sts_regional_endpoints` // Additional config fields for regional or legacy endpoints s3UsEast1RegionalSharedKey = `s3_us_east_1_regional_endpoint` // DefaultSharedConfigProfile is the default profile to be used when // loading configuration from the config files if another profile name // is not provided. DefaultSharedConfigProfile = `default` // S3 ARN Region Usage s3UseARNRegionKey = "s3_use_arn_region" // EC2 IMDS Endpoint Mode ec2MetadataServiceEndpointModeKey = "ec2_metadata_service_endpoint_mode" // EC2 IMDS Endpoint ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint" ) // sharedConfig represents the configuration fields of the SDK config files. type sharedConfig struct { Profile string // Credentials values from the config file. Both aws_access_key_id and // aws_secret_access_key must be provided together in the same file to be // considered valid. The values will be ignored if not a complete group. // aws_session_token is an optional field that can be provided if both of // the other two fields are also provided. // // aws_access_key_id // aws_secret_access_key // aws_session_token Creds credentials.Value CredentialSource string CredentialProcess string WebIdentityTokenFile string SSOAccountID string SSORegion string SSORoleName string SSOStartURL string RoleARN string RoleSessionName string ExternalID string MFASerial string AssumeRoleDuration *time.Duration SourceProfileName string SourceProfile *sharedConfig // Region is the region the SDK should use for looking up AWS service // endpoints and signing requests. // // region Region string // CustomCABundle is the file path to a PEM file the SDK will read and // use to configure the HTTP transport with additional CA certs that are // not present in the platforms default CA store. // // This value will be ignored if the file does not exist. // // ca_bundle CustomCABundle string // EnableEndpointDiscovery can be enabled in the shared config by setting // endpoint_discovery_enabled to true // // endpoint_discovery_enabled = true EnableEndpointDiscovery *bool // CSM Options CSMEnabled *bool CSMHost string CSMPort string CSMClientID string // Specifies the Regional Endpoint flag for the SDK to resolve the endpoint for a service // // sts_regional_endpoints = regional // This can take value as `LegacySTSEndpoint` or `RegionalSTSEndpoint` STSRegionalEndpoint endpoints.STSRegionalEndpoint // Specifies the Regional Endpoint flag for the SDK to resolve the endpoint for a service // // s3_us_east_1_regional_endpoint = regional // This can take value as `LegacyS3UsEast1Endpoint` or `RegionalS3UsEast1Endpoint` S3UsEast1RegionalEndpoint endpoints.S3UsEast1RegionalEndpoint // Specifies if the S3 service should allow ARNs to direct the region // the client's requests are sent to. // // s3_use_arn_region=true S3UseARNRegion bool // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) // // ec2_metadata_service_endpoint_mode=IPv6 EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode. // // ec2_metadata_service_endpoint=http://fd00:ec2::254 EC2IMDSEndpoint string } type sharedConfigFile struct { Filename string IniData ini.Sections } // loadSharedConfig retrieves the configuration from the list of files using // the profile provided. The order the files are listed will determine // precedence. Values in subsequent files will overwrite values defined in // earlier files. // // For example, given two files A and B. Both define credentials. If the order // of the files are A then B, B's credential values will be used instead of // A's. // // See sharedConfig.setFromFile for information how the config files // will be loaded. func loadSharedConfig(profile string, filenames []string, exOpts bool) (sharedConfig, error) { if len(profile) == 0 { profile = DefaultSharedConfigProfile } files, err := loadSharedConfigIniFiles(filenames) if err != nil { return sharedConfig{}, err } cfg := sharedConfig{} profiles := map[string]struct{}{} if err = cfg.setFromIniFiles(profiles, profile, files, exOpts); err != nil { return sharedConfig{}, err } return cfg, nil } func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { files := make([]sharedConfigFile, 0, len(filenames)) for _, filename := range filenames { sections, err := ini.OpenFile(filename) if aerr, ok := err.(awserr.Error); ok && aerr.Code() == ini.ErrCodeUnableToReadFile { // Skip files which can't be opened and read for whatever reason continue } else if err != nil { return nil, SharedConfigLoadError{Filename: filename, Err: err} } files = append(files, sharedConfigFile{ Filename: filename, IniData: sections, }) } return files, nil } func (cfg *sharedConfig) setFromIniFiles(profiles map[string]struct{}, profile string, files []sharedConfigFile, exOpts bool) error { cfg.Profile = profile // Trim files from the list that don't exist. var skippedFiles int var profileNotFoundErr error for _, f := range files { if err := cfg.setFromIniFile(profile, f, exOpts); err != nil { if _, ok := err.(SharedConfigProfileNotExistsError); ok { // Ignore profiles not defined in individual files. profileNotFoundErr = err skippedFiles++ continue } return err } } if skippedFiles == len(files) { // If all files were skipped because the profile is not found, return // the original profile not found error. return profileNotFoundErr } if _, ok := profiles[profile]; ok { // if this is the second instance of the profile the Assume Role // options must be cleared because they are only valid for the // first reference of a profile. The self linked instance of the // profile only have credential provider options. cfg.clearAssumeRoleOptions() } else { // First time a profile has been seen, It must either be a assume role // credentials, or SSO. Assert if the credential type requires a role ARN, // the ARN is also set, or validate that the SSO configuration is complete. if err := cfg.validateCredentialsConfig(profile); err != nil { return err } } profiles[profile] = struct{}{} if err := cfg.validateCredentialType(); err != nil { return err } // Link source profiles for assume roles if len(cfg.SourceProfileName) != 0 { // Linked profile via source_profile ignore credential provider // options, the source profile must provide the credentials. cfg.clearCredentialOptions() srcCfg := &sharedConfig{} err := srcCfg.setFromIniFiles(profiles, cfg.SourceProfileName, files, exOpts) if err != nil { // SourceProfile that doesn't exist is an error in configuration. if _, ok := err.(SharedConfigProfileNotExistsError); ok { err = SharedConfigAssumeRoleError{ RoleARN: cfg.RoleARN, SourceProfile: cfg.SourceProfileName, } } return err } if !srcCfg.hasCredentials() { return SharedConfigAssumeRoleError{ RoleARN: cfg.RoleARN, SourceProfile: cfg.SourceProfileName, } } cfg.SourceProfile = srcCfg } return nil } // setFromFile loads the configuration from the file using the profile // provided. A sharedConfig pointer type value is used so that multiple config // file loadings can be chained. // // Only loads complete logically grouped values, and will not set fields in cfg // for incomplete grouped values in the config. Such as credentials. For // example if a config file only includes aws_access_key_id but no // aws_secret_access_key the aws_access_key_id will be ignored. func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, exOpts bool) error { section, ok := file.IniData.GetSection(profile) if !ok { // Fallback to to alternate profile name: profile <name> section, ok = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) if !ok { return SharedConfigProfileNotExistsError{Profile: profile, Err: nil} } } if exOpts { // Assume Role Parameters updateString(&cfg.RoleARN, section, roleArnKey) updateString(&cfg.ExternalID, section, externalIDKey) updateString(&cfg.MFASerial, section, mfaSerialKey) updateString(&cfg.RoleSessionName, section, roleSessionNameKey) updateString(&cfg.SourceProfileName, section, sourceProfileKey) updateString(&cfg.CredentialSource, section, credentialSourceKey) updateString(&cfg.Region, section, regionKey) updateString(&cfg.CustomCABundle, section, customCABundleKey) if section.Has(roleDurationSecondsKey) { d := time.Duration(section.Int(roleDurationSecondsKey)) * time.Second cfg.AssumeRoleDuration = &d } if v := section.String(stsRegionalEndpointSharedKey); len(v) != 0 { sre, err := endpoints.GetSTSRegionalEndpoint(v) if err != nil { return fmt.Errorf("failed to load %s from shared config, %s, %v", stsRegionalEndpointSharedKey, file.Filename, err) } cfg.STSRegionalEndpoint = sre } if v := section.String(s3UsEast1RegionalSharedKey); len(v) != 0 { sre, err := endpoints.GetS3UsEast1RegionalEndpoint(v) if err != nil { return fmt.Errorf("failed to load %s from shared config, %s, %v", s3UsEast1RegionalSharedKey, file.Filename, err) } cfg.S3UsEast1RegionalEndpoint = sre } // AWS Single Sign-On (AWS SSO) updateString(&cfg.SSOAccountID, section, ssoAccountIDKey) updateString(&cfg.SSORegion, section, ssoRegionKey) updateString(&cfg.SSORoleName, section, ssoRoleNameKey) updateString(&cfg.SSOStartURL, section, ssoStartURL) if err := updateEC2MetadataServiceEndpointMode(&cfg.EC2IMDSEndpointMode, section, ec2MetadataServiceEndpointModeKey); err != nil { return fmt.Errorf("failed to load %s from shared config, %s, %v", ec2MetadataServiceEndpointModeKey, file.Filename, err) } updateString(&cfg.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey) } updateString(&cfg.CredentialProcess, section, credentialProcessKey) updateString(&cfg.WebIdentityTokenFile, section, webIdentityTokenFileKey) // Shared Credentials creds := credentials.Value{ AccessKeyID: section.String(accessKeyIDKey), SecretAccessKey: section.String(secretAccessKey), SessionToken: section.String(sessionTokenKey), ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename), } if creds.HasKeys() { cfg.Creds = creds } // Endpoint discovery updateBoolPtr(&cfg.EnableEndpointDiscovery, section, enableEndpointDiscoveryKey) // CSM options updateBoolPtr(&cfg.CSMEnabled, section, csmEnabledKey) updateString(&cfg.CSMHost, section, csmHostKey) updateString(&cfg.CSMPort, section, csmPortKey) updateString(&cfg.CSMClientID, section, csmClientIDKey) updateBool(&cfg.S3UseARNRegion, section, s3UseARNRegionKey) return nil } func updateEC2MetadataServiceEndpointMode(endpointMode *endpoints.EC2IMDSEndpointModeState, section ini.Section, key string) error { if !section.Has(key) { return nil } value := section.String(key) return endpointMode.SetFromString(value) } func (cfg *sharedConfig) validateCredentialsConfig(profile string) error { if err := cfg.validateCredentialsRequireARN(profile); err != nil { return err } return nil } func (cfg *sharedConfig) validateCredentialsRequireARN(profile string) error { var credSource string switch { case len(cfg.SourceProfileName) != 0: credSource = sourceProfileKey case len(cfg.CredentialSource) != 0: credSource = credentialSourceKey case len(cfg.WebIdentityTokenFile) != 0: credSource = webIdentityTokenFileKey } if len(credSource) != 0 && len(cfg.RoleARN) == 0 { return CredentialRequiresARNError{ Type: credSource, Profile: profile, } } return nil } func (cfg *sharedConfig) validateCredentialType() error { // Only one or no credential type can be defined. if !oneOrNone( len(cfg.SourceProfileName) != 0, len(cfg.CredentialSource) != 0, len(cfg.CredentialProcess) != 0, len(cfg.WebIdentityTokenFile) != 0, ) { return ErrSharedConfigSourceCollision } return nil } func (cfg *sharedConfig) validateSSOConfiguration() error { if !cfg.hasSSOConfiguration() { return nil } var missing []string if len(cfg.SSOAccountID) == 0 { missing = append(missing, ssoAccountIDKey) } if len(cfg.SSORegion) == 0 { missing = append(missing, ssoRegionKey) } if len(cfg.SSORoleName) == 0 { missing = append(missing, ssoRoleNameKey) } if len(cfg.SSOStartURL) == 0 { missing = append(missing, ssoStartURL) } if len(missing) > 0 { return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", cfg.Profile, strings.Join(missing, ", ")) } return nil } func (cfg *sharedConfig) hasCredentials() bool { switch { case len(cfg.SourceProfileName) != 0: case len(cfg.CredentialSource) != 0: case len(cfg.CredentialProcess) != 0: case len(cfg.WebIdentityTokenFile) != 0: case cfg.hasSSOConfiguration(): case cfg.Creds.HasKeys(): default: return false } return true } func (cfg *sharedConfig) clearCredentialOptions() { cfg.CredentialSource = "" cfg.CredentialProcess = "" cfg.WebIdentityTokenFile = "" cfg.Creds = credentials.Value{} cfg.SSOAccountID = "" cfg.SSORegion = "" cfg.SSORoleName = "" cfg.SSOStartURL = "" } func (cfg *sharedConfig) clearAssumeRoleOptions() { cfg.RoleARN = "" cfg.ExternalID = "" cfg.MFASerial = "" cfg.RoleSessionName = "" cfg.SourceProfileName = "" } func (cfg *sharedConfig) hasSSOConfiguration() bool { switch { case len(cfg.SSOAccountID) != 0: case len(cfg.SSORegion) != 0: case len(cfg.SSORoleName) != 0: case len(cfg.SSOStartURL) != 0: default: return false } return true } func oneOrNone(bs ...bool) bool { var count int for _, b := range bs { if b { count++ if count > 1 { return false } } } return true } // updateString will only update the dst with the value in the section key, key // is present in the section. func updateString(dst *string, section ini.Section, key string) { if !section.Has(key) { return } *dst = section.String(key) } // updateBool will only update the dst with the value in the section key, key // is present in the section. func updateBool(dst *bool, section ini.Section, key string) { if !section.Has(key) { return } *dst = section.Bool(key) } // updateBoolPtr will only update the dst with the value in the section key, // key is present in the section. func updateBoolPtr(dst **bool, section ini.Section, key string) { if !section.Has(key) { return } *dst = new(bool) **dst = section.Bool(key) } // SharedConfigLoadError is an error for the shared config file failed to load. type SharedConfigLoadError struct { Filename string Err error } // Code is the short id of the error. func (e SharedConfigLoadError) Code() string { return "SharedConfigLoadError" } // Message is the description of the error func (e SharedConfigLoadError) Message() string { return fmt.Sprintf("failed to load config file, %s", e.Filename) } // OrigErr is the underlying error that caused the failure. func (e SharedConfigLoadError) OrigErr() error { return e.Err } // Error satisfies the error interface. func (e SharedConfigLoadError) Error() string { return awserr.SprintError(e.Code(), e.Message(), "", e.Err) } // SharedConfigProfileNotExistsError is an error for the shared config when // the profile was not find in the config file. type SharedConfigProfileNotExistsError struct { Profile string Err error } // Code is the short id of the error. func (e SharedConfigProfileNotExistsError) Code() string { return "SharedConfigProfileNotExistsError" } // Message is the description of the error func (e SharedConfigProfileNotExistsError) Message() string { return fmt.Sprintf("failed to get profile, %s", e.Profile) } // OrigErr is the underlying error that caused the failure. func (e SharedConfigProfileNotExistsError) OrigErr() error { return e.Err } // Error satisfies the error interface. func (e SharedConfigProfileNotExistsError) Error() string { return awserr.SprintError(e.Code(), e.Message(), "", e.Err) } // SharedConfigAssumeRoleError is an error for the shared config when the // profile contains assume role information, but that information is invalid // or not complete. type SharedConfigAssumeRoleError struct { RoleARN string SourceProfile string } // Code is the short id of the error. func (e SharedConfigAssumeRoleError) Code() string { return "SharedConfigAssumeRoleError" } // Message is the description of the error func (e SharedConfigAssumeRoleError) Message() string { return fmt.Sprintf( "failed to load assume role for %s, source profile %s has no shared credentials", e.RoleARN, e.SourceProfile, ) } // OrigErr is the underlying error that caused the failure. func (e SharedConfigAssumeRoleError) OrigErr() error { return nil } // Error satisfies the error interface. func (e SharedConfigAssumeRoleError) Error() string { return awserr.SprintError(e.Code(), e.Message(), "", nil) } // CredentialRequiresARNError provides the error for shared config credentials // that are incorrectly configured in the shared config or credentials file. type CredentialRequiresARNError struct { // type of credentials that were configured. Type string // Profile name the credentials were in. Profile string } // Code is the short id of the error. func (e CredentialRequiresARNError) Code() string { return "CredentialRequiresARNError" } // Message is the description of the error func (e CredentialRequiresARNError) Message() string { return fmt.Sprintf( "credential type %s requires role_arn, profile %s", e.Type, e.Profile, ) } // OrigErr is the underlying error that caused the failure. func (e CredentialRequiresARNError) OrigErr() error { return nil } // Error satisfies the error interface. func (e CredentialRequiresARNError) Error() string { return awserr.SprintError(e.Code(), e.Message(), "", nil) }
676
session-manager-plugin
aws
Go
// +build go1.7 package session import ( "fmt" "path/filepath" "reflect" "strconv" "strings" "testing" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/internal/ini" ) var ( testConfigFilename = filepath.Join("testdata", "shared_config") testConfigOtherFilename = filepath.Join("testdata", "shared_config_other") ) func TestLoadSharedConfig(t *testing.T) { cases := []struct { Filenames []string Profile string Expected sharedConfig Err error }{ { Filenames: []string{"file_not_exists"}, Profile: "default", Expected: sharedConfig{ Profile: "default", }, }, { Filenames: []string{testConfigFilename}, Expected: sharedConfig{ Profile: "default", Region: "default_region", }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "config_file_load_order", Expected: sharedConfig{ Profile: "config_file_load_order", Region: "shared_config_region", Creds: credentials.Value{ AccessKeyID: "shared_config_akid", SecretAccessKey: "shared_config_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, }, }, { Filenames: []string{testConfigFilename, testConfigOtherFilename}, Profile: "config_file_load_order", Expected: sharedConfig{ Profile: "config_file_load_order", Region: "shared_config_other_region", Creds: credentials.Value{ AccessKeyID: "shared_config_other_akid", SecretAccessKey: "shared_config_other_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigOtherFilename), }, }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "assume_role", Expected: sharedConfig{ Profile: "assume_role", RoleARN: "assume_role_role_arn", SourceProfileName: "complete_creds", SourceProfile: &sharedConfig{ Profile: "complete_creds", Creds: credentials.Value{ AccessKeyID: "complete_creds_akid", SecretAccessKey: "complete_creds_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, }, }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "assume_role_invalid_source_profile", Expected: sharedConfig{ Profile: "assume_role_invalid_source_profile", RoleARN: "assume_role_invalid_source_profile_role_arn", SourceProfileName: "profile_not_exists", }, Err: SharedConfigAssumeRoleError{ RoleARN: "assume_role_invalid_source_profile_role_arn", SourceProfile: "profile_not_exists", }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "assume_role_w_creds", Expected: sharedConfig{ Profile: "assume_role_w_creds", RoleARN: "assume_role_w_creds_role_arn", ExternalID: "1234", RoleSessionName: "assume_role_w_creds_session_name", SourceProfileName: "assume_role_w_creds", SourceProfile: &sharedConfig{ Profile: "assume_role_w_creds", Creds: credentials.Value{ AccessKeyID: "assume_role_w_creds_akid", SecretAccessKey: "assume_role_w_creds_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, }, }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "assume_role_wo_creds", Expected: sharedConfig{ Profile: "assume_role_wo_creds", RoleARN: "assume_role_wo_creds_role_arn", SourceProfileName: "assume_role_wo_creds", }, Err: SharedConfigAssumeRoleError{ RoleARN: "assume_role_wo_creds_role_arn", SourceProfile: "assume_role_wo_creds", }, }, { Filenames: []string{filepath.Join("testdata", "shared_config_invalid_ini")}, Profile: "profile_name", Err: SharedConfigLoadError{Filename: filepath.Join("testdata", "shared_config_invalid_ini")}, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "assume_role_with_credential_source", Expected: sharedConfig{ Profile: "assume_role_with_credential_source", RoleARN: "assume_role_with_credential_source_role_arn", CredentialSource: credSourceEc2Metadata, }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "multiple_assume_role", Expected: sharedConfig{ Profile: "multiple_assume_role", RoleARN: "multiple_assume_role_role_arn", SourceProfileName: "assume_role", SourceProfile: &sharedConfig{ Profile: "assume_role", RoleARN: "assume_role_role_arn", SourceProfileName: "complete_creds", SourceProfile: &sharedConfig{ Profile: "complete_creds", Creds: credentials.Value{ AccessKeyID: "complete_creds_akid", SecretAccessKey: "complete_creds_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, }, }, }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "multiple_assume_role_with_credential_source", Expected: sharedConfig{ Profile: "multiple_assume_role_with_credential_source", RoleARN: "multiple_assume_role_with_credential_source_role_arn", SourceProfileName: "assume_role_with_credential_source", SourceProfile: &sharedConfig{ Profile: "assume_role_with_credential_source", RoleARN: "assume_role_with_credential_source_role_arn", CredentialSource: credSourceEc2Metadata, }, }, }, { Filenames: []string{testConfigOtherFilename, testConfigFilename}, Profile: "multiple_assume_role_with_credential_source2", Expected: sharedConfig{ Profile: "multiple_assume_role_with_credential_source2", RoleARN: "multiple_assume_role_with_credential_source2_role_arn", SourceProfileName: "multiple_assume_role_with_credential_source", SourceProfile: &sharedConfig{ Profile: "multiple_assume_role_with_credential_source", RoleARN: "multiple_assume_role_with_credential_source_role_arn", SourceProfileName: "assume_role_with_credential_source", SourceProfile: &sharedConfig{ Profile: "assume_role_with_credential_source", RoleARN: "assume_role_with_credential_source_role_arn", CredentialSource: credSourceEc2Metadata, }, }, }, }, { Filenames: []string{testConfigFilename}, Profile: "with_sts_regional", Expected: sharedConfig{ Profile: "with_sts_regional", STSRegionalEndpoint: endpoints.RegionalSTSEndpoint, }, }, { Filenames: []string{testConfigFilename}, Profile: "with_s3_us_east_1_regional", Expected: sharedConfig{ Profile: "with_s3_us_east_1_regional", S3UsEast1RegionalEndpoint: endpoints.RegionalS3UsEast1Endpoint, }, }, { Filenames: []string{testConfigFilename}, Profile: "sso_creds", Expected: sharedConfig{ Profile: "sso_creds", SSOAccountID: "012345678901", SSORegion: "us-west-2", SSORoleName: "TestRole", SSOStartURL: "https://127.0.0.1/start", }, }, { Filenames: []string{testConfigFilename}, Profile: "source_sso_creds", Expected: sharedConfig{ Profile: "source_sso_creds", RoleARN: "source_sso_creds_arn", SourceProfileName: "sso_creds", SourceProfile: &sharedConfig{ Profile: "sso_creds", SSOAccountID: "012345678901", SSORegion: "us-west-2", SSORoleName: "TestRole", SSOStartURL: "https://127.0.0.1/start", }, }, }, { Filenames: []string{testConfigFilename}, Profile: "sso_and_static", Expected: sharedConfig{ Profile: "sso_and_static", Creds: credentials.Value{ AccessKeyID: "sso_and_static_akid", SecretAccessKey: "sso_and_static_secret", SessionToken: "sso_and_static_token", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, SSOAccountID: "012345678901", SSORegion: "us-west-2", SSORoleName: "TestRole", SSOStartURL: "https://THIS_SHOULD_NOT_BE_IN_TESTDATA_CACHE/start", }, }, { Filenames: []string{testConfigFilename}, Profile: "source_sso_and_assume", Expected: sharedConfig{ Profile: "source_sso_and_assume", RoleARN: "source_sso_and_assume_arn", SourceProfileName: "sso_and_assume", SourceProfile: &sharedConfig{ Profile: "sso_and_assume", RoleARN: "sso_with_assume_role_arn", SourceProfileName: "multiple_assume_role_with_credential_source", SourceProfile: &sharedConfig{ Profile: "multiple_assume_role_with_credential_source", RoleARN: "multiple_assume_role_with_credential_source_role_arn", SourceProfileName: "assume_role_with_credential_source", SourceProfile: &sharedConfig{ Profile: "assume_role_with_credential_source", RoleARN: "assume_role_with_credential_source_role_arn", CredentialSource: credSourceEc2Metadata, }, }, }, }, }, { Filenames: []string{testConfigFilename}, Profile: "sso_mixed_credproc", Expected: sharedConfig{ Profile: "sso_mixed_credproc", SSOAccountID: "012345678901", SSORegion: "us-west-2", SSORoleName: "TestRole", SSOStartURL: "https://127.0.0.1/start", CredentialProcess: "/path/to/process", }, }, { Filenames: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpoint", Expected: sharedConfig{ Profile: "EC2MetadataServiceEndpoint", EC2IMDSEndpoint: "http://endpoint.localhost", }, }, { Filenames: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointModeIPv6", Expected: sharedConfig{ Profile: "EC2MetadataServiceEndpointModeIPv6", EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv6, }, }, { Filenames: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointModeIPv4", Expected: sharedConfig{ Profile: "EC2MetadataServiceEndpointModeIPv4", EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv4, }, }, { Filenames: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointModeUnknown", Expected: sharedConfig{ Profile: "EC2MetadataServiceEndpointModeUnknown", }, Err: fmt.Errorf("failed to load ec2_metadata_service_endpoint_mode from shared config"), }, { Filenames: []string{testConfigFilename}, Profile: "EC2MetadataServiceEndpointAndModeMixed", Expected: sharedConfig{ Profile: "EC2MetadataServiceEndpointAndModeMixed", EC2IMDSEndpoint: "http://endpoint.localhost", EC2IMDSEndpointMode: endpoints.EC2IMDSEndpointModeStateIPv6, }, }, } for i, c := range cases { t.Run(strconv.Itoa(i)+"_"+c.Profile, func(t *testing.T) { cfg, err := loadSharedConfig(c.Profile, c.Filenames, true) if c.Err != nil { if err == nil { t.Fatalf("expect error, got none") } if e, a := c.Err.Error(), err.Error(); !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } return } if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := c.Expected, cfg; !reflect.DeepEqual(e, a) { t.Errorf("expect %v, got %v", e, a) } }) } } func TestLoadSharedConfigFromFile(t *testing.T) { filename := testConfigFilename f, err := ini.OpenFile(filename) if err != nil { t.Fatalf("failed to load test config file, %s, %v", filename, err) } iniFile := sharedConfigFile{IniData: f, Filename: filename} cases := []struct { Profile string Expected sharedConfig Err error }{ { Profile: "default", Expected: sharedConfig{Region: "default_region"}, }, { Profile: "alt_profile_name", Expected: sharedConfig{Region: "alt_profile_name_region"}, }, { Profile: "short_profile_name_first", Expected: sharedConfig{Region: "short_profile_name_first_short"}, }, { Profile: "partial_creds", Expected: sharedConfig{}, }, { Profile: "complete_creds", Expected: sharedConfig{ Creds: credentials.Value{ AccessKeyID: "complete_creds_akid", SecretAccessKey: "complete_creds_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, }, }, { Profile: "complete_creds_with_token", Expected: sharedConfig{ Creds: credentials.Value{ AccessKeyID: "complete_creds_with_token_akid", SecretAccessKey: "complete_creds_with_token_secret", SessionToken: "complete_creds_with_token_token", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, }, }, { Profile: "full_profile", Expected: sharedConfig{ Creds: credentials.Value{ AccessKeyID: "full_profile_akid", SecretAccessKey: "full_profile_secret", ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), }, Region: "full_profile_region", }, }, { Profile: "partial_assume_role", Expected: sharedConfig{ RoleARN: "partial_assume_role_role_arn", }, }, { Profile: "assume_role", Expected: sharedConfig{ RoleARN: "assume_role_role_arn", SourceProfileName: "complete_creds", }, }, { Profile: "assume_role_w_mfa", Expected: sharedConfig{ RoleARN: "assume_role_role_arn", SourceProfileName: "complete_creds", MFASerial: "0123456789", }, }, { Profile: "does_not_exists", Err: SharedConfigProfileNotExistsError{Profile: "does_not_exists"}, }, { Profile: "valid_arn_region", Expected: sharedConfig{ S3UseARNRegion: true, }, }, } for i, c := range cases { t.Run(strconv.Itoa(i)+"_"+c.Profile, func(t *testing.T) { cfg := sharedConfig{} err := cfg.setFromIniFile(c.Profile, iniFile, true) if c.Err != nil { if err == nil { t.Fatalf("expect error, got none") } if e, a := c.Err.Error(), err.Error(); !strings.Contains(a, e) { t.Errorf("expect %v, to be in %v", e, a) } return } if err != nil { t.Errorf("expect no error, got %v", err) } if e, a := c.Expected, cfg; !reflect.DeepEqual(e, a) { t.Errorf("expect %v, got %v", e, a) } }) } } func TestLoadSharedConfigIniFiles(t *testing.T) { cases := []struct { Filenames []string Expected []sharedConfigFile }{ { Filenames: []string{"not_exists", testConfigFilename}, Expected: []sharedConfigFile{ {Filename: testConfigFilename}, }, }, { Filenames: []string{testConfigFilename, testConfigOtherFilename}, Expected: []sharedConfigFile{ {Filename: testConfigFilename}, {Filename: testConfigOtherFilename}, }, }, } for i, c := range cases { t.Run(strconv.Itoa(i), func(t *testing.T) { files, err := loadSharedConfigIniFiles(c.Filenames) if err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := len(c.Expected), len(files); e != a { t.Errorf("expect %v, got %v", e, a) } for i, expectedFile := range c.Expected { if e, a := expectedFile.Filename, files[i].Filename; e != a { t.Errorf("expect %v, got %v", e, a) } } }) } }
520
session-manager-plugin
aws
Go
package session import ( "os" "github.com/aws/aws-sdk-go/internal/sdktesting" ) func initSessionTestEnv() (oldEnv func()) { oldEnv = sdktesting.StashEnv() os.Setenv("AWS_CONFIG_FILE", "file_not_exists") os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "file_not_exists") return oldEnv }
16
session-manager-plugin
aws
Go
// +build go1.5 package v4_test import ( "fmt" "net/http" "testing" "time" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/awstesting/unit" ) func TestStandaloneSign(t *testing.T) { creds := unit.Session.Config.Credentials signer := v4.NewSigner(creds) for _, c := range standaloneSignCases { host := fmt.Sprintf("https://%s.%s.%s.amazonaws.com", c.SubDomain, c.Region, c.Service) req, err := http.NewRequest("GET", host, nil) if err != nil { t.Errorf("expected no error, but received %v", err) } // URL.EscapedPath() will be used by the signer to get the // escaped form of the request's URI path. req.URL.Path = c.OrigURI req.URL.RawQuery = c.OrigQuery _, err = signer.Sign(req, nil, c.Service, c.Region, time.Unix(0, 0)) if err != nil { t.Errorf("expected no error, but received %v", err) } actual := req.Header.Get("Authorization") if e, a := c.ExpSig, actual; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.OrigURI, req.URL.Path; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.EscapedURI, req.URL.EscapedPath(); e != a { t.Errorf("expected %v, but received %v", e, a) } } } func TestStandaloneSign_RawPath(t *testing.T) { creds := unit.Session.Config.Credentials signer := v4.NewSigner(creds) for _, c := range standaloneSignCases { host := fmt.Sprintf("https://%s.%s.%s.amazonaws.com", c.SubDomain, c.Region, c.Service) req, err := http.NewRequest("GET", host, nil) if err != nil { t.Errorf("expected no error, but received %v", err) } // URL.EscapedPath() will be used by the signer to get the // escaped form of the request's URI path. req.URL.Path = c.OrigURI req.URL.RawPath = c.EscapedURI req.URL.RawQuery = c.OrigQuery _, err = signer.Sign(req, nil, c.Service, c.Region, time.Unix(0, 0)) if err != nil { t.Errorf("expected no error, but received %v", err) } actual := req.Header.Get("Authorization") if e, a := c.ExpSig, actual; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.OrigURI, req.URL.Path; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := c.EscapedURI, req.URL.EscapedPath(); e != a { t.Errorf("expected %v, but received %v", e, a) } } }
87
session-manager-plugin
aws
Go
package v4_test import ( "net/http" "net/url" "reflect" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/awstesting/unit" "github.com/aws/aws-sdk-go/service/s3" ) var standaloneSignCases = []struct { OrigURI string OrigQuery string Region, Service, SubDomain string ExpSig string EscapedURI string }{ { OrigURI: `/logs-*/_search`, OrigQuery: `pretty=true`, Region: "us-west-2", Service: "es", SubDomain: "hostname-clusterkey", EscapedURI: `/logs-%2A/_search`, ExpSig: `AWS4-HMAC-SHA256 Credential=AKID/19700101/us-west-2/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=79d0760751907af16f64a537c1242416dacf51204a7dd5284492d15577973b91`, }, } func epochTime() time.Time { return time.Unix(0, 0) } func TestPresignHandler(t *testing.T) { svc := s3.New(unit.Session) svc.Handlers.Sign.SwapNamed(request.NamedHandler{ Name: v4.SignRequestHandler.Name, Fn: func(r *request.Request) { v4.SignSDKRequestWithCurrentTime(r, epochTime) }, }) req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ Bucket: aws.String("bucket"), Key: aws.String("key"), ContentDisposition: aws.String("a+b c$d"), ACL: aws.String("public-read"), }) req.Time = epochTime() urlstr, err := req.Presign(5 * time.Minute) if err != nil { t.Fatalf("expect no error, got %v", err) } expectedHost := "bucket.s3.mock-region.amazonaws.com" expectedDate := "19700101T000000Z" expectedHeaders := "content-disposition;host;x-amz-acl" expectedSig := "2d76a414208c0eac2a23ef9c834db9635ecd5a0fbb447a00ad191f82d854f55b" expectedCred := "AKID/19700101/mock-region/s3/aws4_request" u, _ := url.Parse(urlstr) urlQ := u.Query() if e, a := expectedHost, u.Host; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedSig, urlQ.Get("X-Amz-Signature"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedCred, urlQ.Get("X-Amz-Credential"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedDate, urlQ.Get("X-Amz-Date"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "300", urlQ.Get("X-Amz-Expires"); e != a { t.Errorf("expect %v, got %v", e, a) } if a := urlQ.Get("X-Amz-Content-Sha256"); len(a) != 0 { t.Errorf("expect no content sha256 got %v", a) } if e, a := "+", urlstr; strings.Contains(a, e) { // + encoded as %20 t.Errorf("expect %v not to be in %v", e, a) } } func TestPresignRequest(t *testing.T) { svc := s3.New(unit.Session) svc.Handlers.Sign.SwapNamed(request.NamedHandler{ Name: v4.SignRequestHandler.Name, Fn: func(r *request.Request) { v4.SignSDKRequestWithCurrentTime(r, epochTime) }, }) req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ Bucket: aws.String("bucket"), Key: aws.String("key"), ContentDisposition: aws.String("a+b c$d"), ACL: aws.String("public-read"), }) req.Time = epochTime() urlstr, headers, err := req.PresignRequest(5 * time.Minute) if err != nil { t.Fatalf("expect no error, got %v", err) } expectedHost := "bucket.s3.mock-region.amazonaws.com" expectedDate := "19700101T000000Z" expectedHeaders := "content-disposition;host;x-amz-acl" expectedSig := "2d76a414208c0eac2a23ef9c834db9635ecd5a0fbb447a00ad191f82d854f55b" expectedCred := "AKID/19700101/mock-region/s3/aws4_request" expectedHeaderMap := http.Header{ "x-amz-acl": []string{"public-read"}, "content-disposition": []string{"a+b c$d"}, } u, _ := url.Parse(urlstr) urlQ := u.Query() if e, a := expectedHost, u.Host; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedSig, urlQ.Get("X-Amz-Signature"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedCred, urlQ.Get("X-Amz-Credential"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedDate, urlQ.Get("X-Amz-Date"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedHeaderMap, headers; !reflect.DeepEqual(e, a) { t.Errorf("expect %v, got %v", e, a) } if e, a := "300", urlQ.Get("X-Amz-Expires"); e != a { t.Errorf("expect %v, got %v", e, a) } if a := urlQ.Get("X-Amz-Content-Sha256"); len(a) != 0 { t.Errorf("expect no content sha256 got %v", a) } if e, a := "+", urlstr; strings.Contains(a, e) { // + encoded as %20 t.Errorf("expect %v not to be in %v", e, a) } } func TestStandaloneSign_CustomURIEscape(t *testing.T) { var expectSig = `AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=6601e883cc6d23871fd6c2a394c5677ea2b8c82b04a6446786d64cd74f520967` creds := unit.Session.Config.Credentials signer := v4.NewSigner(creds, func(s *v4.Signer) { s.DisableURIPathEscaping = true }) host := "https://subdomain.us-east-1.es.amazonaws.com" req, err := http.NewRequest("GET", host, nil) if err != nil { t.Fatalf("expect no error, got %v", err) } req.URL.Path = `/log-*/_search` req.URL.Opaque = "//subdomain.us-east-1.es.amazonaws.com/log-%2A/_search" _, err = signer.Sign(req, nil, "es", "us-east-1", epochTime()) if err != nil { t.Fatalf("expect no error, got %v", err) } actual := req.Header.Get("Authorization") if e, a := expectSig, actual; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestStandaloneSign_WithPort(t *testing.T) { cases := []struct { description string url string expectedSig string }{ { "default HTTPS port", "https://estest.us-east-1.es.amazonaws.com:443/_search", "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=e573fc9aa3a156b720976419319be98fb2824a3abc2ddd895ecb1d1611c6a82d", }, { "default HTTP port", "http://example.com:80/_search", "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=54ebe60c4ae03a40948b849e13c333523235f38002e2807059c64a9a8c7cb951", }, { "non-standard HTTP port", "http://example.com:9200/_search", "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=cd9d926a460f8d3b58b57beadbd87666dc667e014c0afaa4cea37b2867f51b4f", }, { "non-standard HTTPS port", "https://example.com:9200/_search", "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=cd9d926a460f8d3b58b57beadbd87666dc667e014c0afaa4cea37b2867f51b4f", }, } for _, c := range cases { signer := v4.NewSigner(unit.Session.Config.Credentials) req, _ := http.NewRequest("GET", c.url, nil) _, err := signer.Sign(req, nil, "es", "us-east-1", epochTime()) if err != nil { t.Fatalf("expect no error, got %v", err) } actual := req.Header.Get("Authorization") if e, a := c.expectedSig, actual; e != a { t.Errorf("%s, expect %v, got %v", c.description, e, a) } } } func TestStandalonePresign_WithPort(t *testing.T) { cases := []struct { description string url string expectedSig string }{ { "default HTTPS port", "https://estest.us-east-1.es.amazonaws.com:443/_search", "0abcf61a351063441296febf4b485734d780634fba8cf1e7d9769315c35255d6", }, { "default HTTP port", "http://example.com:80/_search", "fce9976dd6c849c21adfa6d3f3e9eefc651d0e4a2ccd740d43efddcccfdc8179", }, { "non-standard HTTP port", "http://example.com:9200/_search", "f33c25a81c735e42bef35ed5e9f720c43940562e3e616ff0777bf6dde75249b0", }, { "non-standard HTTPS port", "https://example.com:9200/_search", "f33c25a81c735e42bef35ed5e9f720c43940562e3e616ff0777bf6dde75249b0", }, } for _, c := range cases { signer := v4.NewSigner(unit.Session.Config.Credentials) req, _ := http.NewRequest("GET", c.url, nil) _, err := signer.Presign(req, nil, "es", "us-east-1", 5*time.Minute, epochTime()) if err != nil { t.Fatalf("expect no error, got %v", err) } actual := req.URL.Query().Get("X-Amz-Signature") if e, a := c.expectedSig, actual; e != a { t.Errorf("%s, expect %v, got %v", c.description, e, a) } } }
272
session-manager-plugin
aws
Go
// +build go1.7 package v4 import "testing" func TestAllowedQueryHoisting(t *testing.T) { cases := map[string]struct { Header string ExpectHoist bool }{ "object-lock": { Header: "X-Amz-Object-Lock-Mode", ExpectHoist: false, }, "s3 metadata": { Header: "X-Amz-Meta-SomeName", ExpectHoist: false, }, "another header": { Header: "X-Amz-SomeOtherHeader", ExpectHoist: true, }, "non X-AMZ header": { Header: "X-SomeOtherHeader", ExpectHoist: false, }, } for name, c := range cases { t.Run(name, func(t *testing.T) { if e, a := c.ExpectHoist, allowedQueryHoisting.IsValid(c.Header); e != a { t.Errorf("expect hoist %v, was %v", e, a) } }) } }
38
session-manager-plugin
aws
Go
package v4 import ( "github.com/aws/aws-sdk-go/internal/strings" ) // validator houses a set of rule needed for validation of a // string value type rules []rule // rule interface allows for more flexible rules and just simply // checks whether or not a value adheres to that rule type rule interface { IsValid(value string) bool } // IsValid will iterate through all rules and see if any rules // apply to the value and supports nested rules func (r rules) IsValid(value string) bool { for _, rule := range r { if rule.IsValid(value) { return true } } return false } // mapRule generic rule for maps type mapRule map[string]struct{} // IsValid for the map rule satisfies whether it exists in the map func (m mapRule) IsValid(value string) bool { _, ok := m[value] return ok } // allowList is a generic rule for allow listing type allowList struct { rule } // IsValid for allow list checks if the value is within the allow list func (w allowList) IsValid(value string) bool { return w.rule.IsValid(value) } // excludeList is a generic rule for exclude listing type excludeList struct { rule } // IsValid for exclude list checks if the value is within the exclude list func (b excludeList) IsValid(value string) bool { return !b.rule.IsValid(value) } type patterns []string // IsValid for patterns checks each pattern and returns if a match has // been found func (p patterns) IsValid(value string) bool { for _, pattern := range p { if strings.HasPrefixFold(value, pattern) { return true } } return false } // inclusiveRules rules allow for rules to depend on one another type inclusiveRules []rule // IsValid will return true if all rules are true func (r inclusiveRules) IsValid(value string) bool { for _, rule := range r { if !rule.IsValid(value) { return false } } return true }
82
session-manager-plugin
aws
Go
package v4 import ( "testing" ) func TestRuleCheckWhitelist(t *testing.T) { w := allowList{ mapRule{ "Cache-Control": struct{}{}, }, } if !w.IsValid("Cache-Control") { t.Error("expected true value") } if w.IsValid("Cache-") { t.Error("expected false value") } } func TestRuleCheckBlacklist(t *testing.T) { b := excludeList{ mapRule{ "Cache-Control": struct{}{}, }, } if b.IsValid("Cache-Control") { t.Error("expected false value") } if !b.IsValid("Cache-") { t.Error("expected true value") } } func TestRuleCheckPattern(t *testing.T) { p := patterns{"X-Amz-Meta-"} if !p.IsValid("X-Amz-Meta-") { t.Error("expected true value") } if !p.IsValid("X-Amz-Meta-Star") { t.Error("expected true value") } if p.IsValid("Cache-") { t.Error("expected false value") } } func TestRuleComplexWhitelist(t *testing.T) { w := rules{ allowList{ mapRule{ "Cache-Control": struct{}{}, }, }, patterns{"X-Amz-Meta-"}, } r := rules{ inclusiveRules{patterns{"X-Amz-"}, excludeList{w}}, } if !r.IsValid("X-Amz-Blah") { t.Error("expected true value") } if r.IsValid("X-Amz-Meta-") { t.Error("expected false value") } if r.IsValid("X-Amz-Meta-Star") { t.Error("expected false value") } if r.IsValid("Cache-Control") { t.Error("expected false value") } }
78
session-manager-plugin
aws
Go
package v4 // WithUnsignedPayload will enable and set the UnsignedPayload field to // true of the signer. func WithUnsignedPayload(v4 *Signer) { v4.UnsignedPayload = true }
8
session-manager-plugin
aws
Go
// +build !go1.7 package v4 import ( "net/http" "github.com/aws/aws-sdk-go/aws" ) func requestContext(r *http.Request) aws.Context { return aws.BackgroundContext() }
14
session-manager-plugin
aws
Go
// +build go1.7 package v4 import ( "net/http" "github.com/aws/aws-sdk-go/aws" ) func requestContext(r *http.Request) aws.Context { return r.Context() }
14
session-manager-plugin
aws
Go
package v4 import ( "encoding/hex" "strings" "time" "github.com/aws/aws-sdk-go/aws/credentials" ) type credentialValueProvider interface { Get() (credentials.Value, error) } // StreamSigner implements signing of event stream encoded payloads type StreamSigner struct { region string service string credentials credentialValueProvider prevSig []byte } // NewStreamSigner creates a SigV4 signer used to sign Event Stream encoded messages func NewStreamSigner(region, service string, seedSignature []byte, credentials *credentials.Credentials) *StreamSigner { return &StreamSigner{ region: region, service: service, credentials: credentials, prevSig: seedSignature, } } // GetSignature takes an event stream encoded headers and payload and returns a signature func (s *StreamSigner) GetSignature(headers, payload []byte, date time.Time) ([]byte, error) { credValue, err := s.credentials.Get() if err != nil { return nil, err } sigKey := deriveSigningKey(s.region, s.service, credValue.SecretAccessKey, date) keyPath := buildSigningScope(s.region, s.service, date) stringToSign := buildEventStreamStringToSign(headers, payload, s.prevSig, keyPath, date) signature := hmacSHA256(sigKey, []byte(stringToSign)) s.prevSig = signature return signature, nil } func buildEventStreamStringToSign(headers, payload, prevSig []byte, scope string, date time.Time) string { return strings.Join([]string{ "AWS4-HMAC-SHA256-PAYLOAD", formatTime(date), scope, hex.EncodeToString(prevSig), hex.EncodeToString(hashSHA256(headers)), hex.EncodeToString(hashSHA256(payload)), }, "\n") }
64
session-manager-plugin
aws
Go
// +build go1.7 package v4 import ( "encoding/hex" "fmt" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws/credentials" ) type periodicBadCredentials struct { call int credentials *credentials.Credentials } func (p *periodicBadCredentials) Get() (credentials.Value, error) { defer func() { p.call++ }() if p.call%2 == 0 { return credentials.Value{}, fmt.Errorf("credentials error") } return p.credentials.Get() } type chunk struct { headers, payload []byte } func mustDecodeHex(b []byte, err error) []byte { if err != nil { panic(err) } return b } func TestStreamingChunkSigner(t *testing.T) { const ( region = "us-east-1" service = "transcribe" seedSignature = "9d9ab996c81f32c9d4e6fc166c92584f3741d1cb5ce325cd11a77d1f962c8de2" ) staticCredentials := credentials.NewStaticCredentials("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "") currentTime := time.Date(2019, 1, 27, 22, 37, 54, 0, time.UTC) cases := map[string]struct { credentials credentialValueProvider chunks []chunk expectedSignatures map[int]string expectedErrors map[int]string }{ "signature calculation": { credentials: staticCredentials, chunks: []chunk{ {headers: []byte("headers"), payload: []byte("payload")}, {headers: []byte("more headers"), payload: []byte("more payload")}, }, expectedSignatures: map[int]string{ 0: "681a7eaa82891536f24af7ec7e9219ee251ccd9bac2f1b981eab7c5ec8579115", 1: "07633d9d4ab4d81634a2164934d1f648c7cbc6839a8cf0773d818127a267e4d6", }, }, "signature calculation errors": { credentials: &periodicBadCredentials{credentials: staticCredentials}, chunks: []chunk{ {headers: []byte("headers"), payload: []byte("payload")}, {headers: []byte("headers"), payload: []byte("payload")}, {headers: []byte("more headers"), payload: []byte("more payload")}, {headers: []byte("more headers"), payload: []byte("more payload")}, }, expectedSignatures: map[int]string{ 1: "681a7eaa82891536f24af7ec7e9219ee251ccd9bac2f1b981eab7c5ec8579115", 3: "07633d9d4ab4d81634a2164934d1f648c7cbc6839a8cf0773d818127a267e4d6", }, expectedErrors: map[int]string{ 0: "credentials error", 2: "credentials error", }, }, } for name, tt := range cases { t.Run(name, func(t *testing.T) { chunkSigner := &StreamSigner{ region: region, service: service, credentials: tt.credentials, prevSig: mustDecodeHex(hex.DecodeString(seedSignature)), } for i, chunk := range tt.chunks { var expectedError string if len(tt.expectedErrors) != 0 { _, ok := tt.expectedErrors[i] if ok { expectedError = tt.expectedErrors[i] } } signature, err := chunkSigner.GetSignature(chunk.headers, chunk.payload, currentTime) if err == nil && len(expectedError) > 0 { t.Errorf("expected error, but got nil") continue } else if err != nil && len(expectedError) == 0 { t.Errorf("expected no error, but got %v", err) continue } else if err != nil && len(expectedError) > 0 && !strings.Contains(err.Error(), expectedError) { t.Errorf("expected %v, but got %v", expectedError, err) continue } else if len(expectedError) > 0 { continue } expectedSignature, ok := tt.expectedSignatures[i] if !ok { t.Fatalf("expected signature not provided for test case") } if e, a := expectedSignature, hex.EncodeToString(signature); e != a { t.Errorf("expected %v, got %v", e, a) } } }) } }
134
session-manager-plugin
aws
Go
// +build go1.5 package v4 import ( "net/url" "strings" ) func getURIPath(u *url.URL) string { var uri string if len(u.Opaque) > 0 { uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") } else { uri = u.EscapedPath() } if len(uri) == 0 { uri = "/" } return uri }
25
session-manager-plugin
aws
Go
// Package v4 implements signing for AWS V4 signer // // Provides request signing for request that need to be signed with // AWS V4 Signatures. // // Standalone Signer // // Generally using the signer outside of the SDK should not require any additional // logic when using Go v1.5 or higher. The signer does this by taking advantage // of the URL.EscapedPath method. If your request URI requires additional escaping // you many need to use the URL.Opaque to define what the raw URI should be sent // to the service as. // // The signer will first check the URL.Opaque field, and use its value if set. // The signer does require the URL.Opaque field to be set in the form of: // // "//<hostname>/<path>" // // // e.g. // "//example.com/some/path" // // The leading "//" and hostname are required or the URL.Opaque escaping will // not work correctly. // // If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() // method and using the returned value. If you're using Go v1.4 you must set // URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with // Go v1.5 the signer will fallback to URL.Path. // // AWS v4 signature validation requires that the canonical string's URI path // element must be the URI escaped form of the HTTP request's path. // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html // // The Go HTTP client will perform escaping automatically on the request. Some // of these escaping may cause signature validation errors because the HTTP // request differs from the URI path or query that the signature was generated. // https://golang.org/pkg/net/url/#URL.EscapedPath // // Because of this, it is recommended that when using the signer outside of the // SDK that explicitly escaping the request prior to being signed is preferable, // and will help prevent signature validation errors. This can be done by setting // the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then // call URL.EscapedPath() if Opaque is not set. // // If signing a request intended for HTTP2 server, and you're using Go 1.6.2 // through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the // request URL. https://github.com/golang/go/issues/16847 points to a bug in // Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP // message. URL.Opaque generally will force Go to make requests with absolute URL. // URL.RawPath does not do this, but RawPath must be a valid escaping of Path // or url.EscapedPath will ignore the RawPath escaping. // // Test `TestStandaloneSign` provides a complete example of using the signer // outside of the SDK and pre-escaping the URI path. package v4 import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "net/http" "net/url" "sort" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/sdkio" "github.com/aws/aws-sdk-go/private/protocol/rest" ) const ( authorizationHeader = "Authorization" authHeaderSignatureElem = "Signature=" signatureQueryKey = "X-Amz-Signature" authHeaderPrefix = "AWS4-HMAC-SHA256" timeFormat = "20060102T150405Z" shortTimeFormat = "20060102" awsV4Request = "aws4_request" // emptyStringSHA256 is a SHA256 of an empty string emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` ) var ignoredHeaders = rules{ excludeList{ mapRule{ authorizationHeader: struct{}{}, "User-Agent": struct{}{}, "X-Amzn-Trace-Id": struct{}{}, }, }, } // requiredSignedHeaders is a allow list for build canonical headers. var requiredSignedHeaders = rules{ allowList{ mapRule{ "Cache-Control": struct{}{}, "Content-Disposition": struct{}{}, "Content-Encoding": struct{}{}, "Content-Language": struct{}{}, "Content-Md5": struct{}{}, "Content-Type": struct{}{}, "Expires": struct{}{}, "If-Match": struct{}{}, "If-Modified-Since": struct{}{}, "If-None-Match": struct{}{}, "If-Unmodified-Since": struct{}{}, "Range": struct{}{}, "X-Amz-Acl": struct{}{}, "X-Amz-Copy-Source": struct{}{}, "X-Amz-Copy-Source-If-Match": struct{}{}, "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, "X-Amz-Copy-Source-If-None-Match": struct{}{}, "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, "X-Amz-Copy-Source-Range": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Grant-Full-control": struct{}{}, "X-Amz-Grant-Read": struct{}{}, "X-Amz-Grant-Read-Acp": struct{}{}, "X-Amz-Grant-Write": struct{}{}, "X-Amz-Grant-Write-Acp": struct{}{}, "X-Amz-Metadata-Directive": struct{}{}, "X-Amz-Mfa": struct{}{}, "X-Amz-Request-Payer": struct{}{}, "X-Amz-Server-Side-Encryption": struct{}{}, "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Storage-Class": struct{}{}, "X-Amz-Tagging": struct{}{}, "X-Amz-Website-Redirect-Location": struct{}{}, "X-Amz-Content-Sha256": struct{}{}, }, }, patterns{"X-Amz-Meta-"}, patterns{"X-Amz-Object-Lock-"}, } // allowedHoisting is a allow list for build query headers. The boolean value // represents whether or not it is a pattern. var allowedQueryHoisting = inclusiveRules{ excludeList{requiredSignedHeaders}, patterns{"X-Amz-"}, } // Signer applies AWS v4 signing to given request. Use this to sign requests // that need to be signed with AWS V4 Signatures. type Signer struct { // The authentication credentials the request will be signed against. // This value must be set to sign requests. Credentials *credentials.Credentials // Sets the log level the signer should use when reporting information to // the logger. If the logger is nil nothing will be logged. See // aws.LogLevelType for more information on available logging levels // // By default nothing will be logged. Debug aws.LogLevelType // The logger loging information will be written to. If there the logger // is nil, nothing will be logged. Logger aws.Logger // Disables the Signer's moving HTTP header key/value pairs from the HTTP // request header to the request's query string. This is most commonly used // with pre-signed requests preventing headers from being added to the // request's query string. DisableHeaderHoisting bool // Disables the automatic escaping of the URI path of the request for the // siganture's canonical string's path. For services that do not need additional // escaping then use this to disable the signer escaping the path. // // S3 is an example of a service that does not need additional escaping. // // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html DisableURIPathEscaping bool // Disables the automatical setting of the HTTP request's Body field with the // io.ReadSeeker passed in to the signer. This is useful if you're using a // custom wrapper around the body for the io.ReadSeeker and want to preserve // the Body value on the Request.Body. // // This does run the risk of signing a request with a body that will not be // sent in the request. Need to ensure that the underlying data of the Body // values are the same. DisableRequestBodyOverwrite bool // currentTimeFn returns the time value which represents the current time. // This value should only be used for testing. If it is nil the default // time.Now will be used. currentTimeFn func() time.Time // UnsignedPayload will prevent signing of the payload. This will only // work for services that have support for this. UnsignedPayload bool } // NewSigner returns a Signer pointer configured with the credentials and optional // option values provided. If not options are provided the Signer will use its // default configuration. func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { v4 := &Signer{ Credentials: credentials, } for _, option := range options { option(v4) } return v4 } type signingCtx struct { ServiceName string Region string Request *http.Request Body io.ReadSeeker Query url.Values Time time.Time ExpireTime time.Duration SignedHeaderVals http.Header DisableURIPathEscaping bool credValues credentials.Value isPresign bool unsignedPayload bool bodyDigest string signedHeaders string canonicalHeaders string canonicalString string credentialString string stringToSign string signature string authorization string } // Sign signs AWS v4 requests with the provided body, service name, region the // request is made to, and time the request is signed at. The signTime allows // you to specify that a request is signed for the future, and cannot be // used until then. // // Returns a list of HTTP headers that were included in the signature or an // error if signing the request failed. Generally for signed requests this value // is not needed as the full request context will be captured by the http.Request // value. It is included for reference though. // // Sign will set the request's Body to be the `body` parameter passed in. If // the body is not already an io.ReadCloser, it will be wrapped within one. If // a `nil` body parameter passed to Sign, the request's Body field will be // also set to nil. Its important to note that this functionality will not // change the request's ContentLength of the request. // // Sign differs from Presign in that it will sign the request using HTTP // header values. This type of signing is intended for http.Request values that // will not be shared, or are shared in a way the header values on the request // will not be lost. // // The requests body is an io.ReadSeeker so the SHA256 of the body can be // generated. To bypass the signer computing the hash you can set the // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { return v4.signWithBody(r, body, service, region, 0, false, signTime) } // Presign signs AWS v4 requests with the provided body, service name, region // the request is made to, and time the request is signed at. The signTime // allows you to specify that a request is signed for the future, and cannot // be used until then. // // Returns a list of HTTP headers that were included in the signature or an // error if signing the request failed. For presigned requests these headers // and their values must be included on the HTTP request when it is made. This // is helpful to know what header values need to be shared with the party the // presigned request will be distributed to. // // Presign differs from Sign in that it will sign the request using query string // instead of header values. This allows you to share the Presigned Request's // URL with third parties, or distribute it throughout your system with minimal // dependencies. // // Presign also takes an exp value which is the duration the // signed request will be valid after the signing time. This is allows you to // set when the request will expire. // // The requests body is an io.ReadSeeker so the SHA256 of the body can be // generated. To bypass the signer computing the hash you can set the // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. // // Presigning a S3 request will not compute the body's SHA256 hash by default. // This is done due to the general use case for S3 presigned URLs is to share // PUT/GET capabilities. If you would like to include the body's SHA256 in the // presigned request's signature you can set the "X-Amz-Content-Sha256" // HTTP header and that will be included in the request's signature. func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { return v4.signWithBody(r, body, service, region, exp, true, signTime) } func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { currentTimeFn := v4.currentTimeFn if currentTimeFn == nil { currentTimeFn = time.Now } ctx := &signingCtx{ Request: r, Body: body, Query: r.URL.Query(), Time: signTime, ExpireTime: exp, isPresign: isPresign, ServiceName: service, Region: region, DisableURIPathEscaping: v4.DisableURIPathEscaping, unsignedPayload: v4.UnsignedPayload, } for key := range ctx.Query { sort.Strings(ctx.Query[key]) } if ctx.isRequestSigned() { ctx.Time = currentTimeFn() ctx.handlePresignRemoval() } var err error ctx.credValues, err = v4.Credentials.GetWithContext(requestContext(r)) if err != nil { return http.Header{}, err } ctx.sanitizeHostForHeader() ctx.assignAmzQueryValues() if err := ctx.build(v4.DisableHeaderHoisting); err != nil { return nil, err } // If the request is not presigned the body should be attached to it. This // prevents the confusion of wanting to send a signed request without // the body the request was signed for attached. if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { var reader io.ReadCloser if body != nil { var ok bool if reader, ok = body.(io.ReadCloser); !ok { reader = ioutil.NopCloser(body) } } r.Body = reader } if v4.Debug.Matches(aws.LogDebugWithSigning) { v4.logSigningInfo(ctx) } return ctx.SignedHeaderVals, nil } func (ctx *signingCtx) sanitizeHostForHeader() { request.SanitizeHostForHeader(ctx.Request) } func (ctx *signingCtx) handlePresignRemoval() { if !ctx.isPresign { return } // The credentials have expired for this request. The current signing // is invalid, and needs to be request because the request will fail. ctx.removePresign() // Update the request's query string to ensure the values stays in // sync in the case retrieving the new credentials fails. ctx.Request.URL.RawQuery = ctx.Query.Encode() } func (ctx *signingCtx) assignAmzQueryValues() { if ctx.isPresign { ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) if ctx.credValues.SessionToken != "" { ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) } else { ctx.Query.Del("X-Amz-Security-Token") } return } if ctx.credValues.SessionToken != "" { ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) } } // SignRequestHandler is a named request handler the SDK will use to sign // service client request with using the V4 signature. var SignRequestHandler = request.NamedHandler{ Name: "v4.SignRequestHandler", Fn: SignSDKRequest, } // SignSDKRequest signs an AWS request with the V4 signature. This // request handler should only be used with the SDK's built in service client's // API operation requests. // // This function should not be used on its own, but in conjunction with // an AWS service client's API operation call. To sign a standalone request // not created by a service client's API operation method use the "Sign" or // "Presign" functions of the "Signer" type. // // If the credentials of the request's config are set to // credentials.AnonymousCredentials the request will not be signed. func SignSDKRequest(req *request.Request) { SignSDKRequestWithCurrentTime(req, time.Now) } // BuildNamedHandler will build a generic handler for signing. func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { return request.NamedHandler{ Name: name, Fn: func(req *request.Request) { SignSDKRequestWithCurrentTime(req, time.Now, opts...) }, } } // SignSDKRequestWithCurrentTime will sign the SDK's request using the time // function passed in. Behaves the same as SignSDKRequest with the exception // the request is signed with the value returned by the current time function. func SignSDKRequestWithCurrentTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Config.Credentials == credentials.AnonymousCredentials { return } region := req.ClientInfo.SigningRegion if region == "" { region = aws.StringValue(req.Config.Region) } name := req.ClientInfo.SigningName if name == "" { name = req.ClientInfo.ServiceName } v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { v4.Debug = req.Config.LogLevel.Value() v4.Logger = req.Config.Logger v4.DisableHeaderHoisting = req.NotHoist v4.currentTimeFn = curTimeFn if name == "s3" { // S3 service should not have any escaping applied v4.DisableURIPathEscaping = true } // Prevents setting the HTTPRequest's Body. Since the Body could be // wrapped in a custom io.Closer that we do not want to be stompped // on top of by the signer. v4.DisableRequestBodyOverwrite = true }) for _, opt := range opts { opt(v4) } curTime := curTimeFn() signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), name, region, req.ExpireTime, req.ExpireTime > 0, curTime, ) if err != nil { req.Error = err req.SignedHeaderVals = nil return } req.SignedHeaderVals = signedHeaders req.LastSignedAt = curTime } const logSignInfoMsg = `DEBUG: Request Signature: ---[ CANONICAL STRING ]----------------------------- %s ---[ STRING TO SIGN ]-------------------------------- %s%s -----------------------------------------------------` const logSignedURLMsg = ` ---[ SIGNED URL ]------------------------------------ %s` func (v4 *Signer) logSigningInfo(ctx *signingCtx) { signedURLMsg := "" if ctx.isPresign { signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) } msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) v4.Logger.Log(msg) } func (ctx *signingCtx) build(disableHeaderHoisting bool) error { ctx.buildTime() // no depends ctx.buildCredentialString() // no depends if err := ctx.buildBodyDigest(); err != nil { return err } unsignedHeaders := ctx.Request.Header if ctx.isPresign { if !disableHeaderHoisting { urlValues := url.Values{} urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends for k := range urlValues { ctx.Query[k] = urlValues[k] } } } ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) ctx.buildCanonicalString() // depends on canon headers / signed headers ctx.buildStringToSign() // depends on canon string ctx.buildSignature() // depends on string to sign if ctx.isPresign { ctx.Request.URL.RawQuery += "&" + signatureQueryKey + "=" + ctx.signature } else { parts := []string{ authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, "SignedHeaders=" + ctx.signedHeaders, authHeaderSignatureElem + ctx.signature, } ctx.Request.Header.Set(authorizationHeader, strings.Join(parts, ", ")) } return nil } // GetSignedRequestSignature attempts to extract the signature of the request. // Returning an error if the request is unsigned, or unable to extract the // signature. func GetSignedRequestSignature(r *http.Request) ([]byte, error) { if auth := r.Header.Get(authorizationHeader); len(auth) != 0 { ps := strings.Split(auth, ", ") for _, p := range ps { if idx := strings.Index(p, authHeaderSignatureElem); idx >= 0 { sig := p[len(authHeaderSignatureElem):] if len(sig) == 0 { return nil, fmt.Errorf("invalid request signature authorization header") } return hex.DecodeString(sig) } } } if sig := r.URL.Query().Get("X-Amz-Signature"); len(sig) != 0 { return hex.DecodeString(sig) } return nil, fmt.Errorf("request not signed") } func (ctx *signingCtx) buildTime() { if ctx.isPresign { duration := int64(ctx.ExpireTime / time.Second) ctx.Query.Set("X-Amz-Date", formatTime(ctx.Time)) ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) } else { ctx.Request.Header.Set("X-Amz-Date", formatTime(ctx.Time)) } } func (ctx *signingCtx) buildCredentialString() { ctx.credentialString = buildSigningScope(ctx.Region, ctx.ServiceName, ctx.Time) if ctx.isPresign { ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) } } func buildQuery(r rule, header http.Header) (url.Values, http.Header) { query := url.Values{} unsignedHeaders := http.Header{} for k, h := range header { if r.IsValid(k) { query[k] = h } else { unsignedHeaders[k] = h } } return query, unsignedHeaders } func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { var headers []string headers = append(headers, "host") for k, v := range header { if !r.IsValid(k) { continue // ignored header } if ctx.SignedHeaderVals == nil { ctx.SignedHeaderVals = make(http.Header) } lowerCaseKey := strings.ToLower(k) if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { // include additional values ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) continue } headers = append(headers, lowerCaseKey) ctx.SignedHeaderVals[lowerCaseKey] = v } sort.Strings(headers) ctx.signedHeaders = strings.Join(headers, ";") if ctx.isPresign { ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) } headerValues := make([]string, len(headers)) for i, k := range headers { if k == "host" { if ctx.Request.Host != "" { headerValues[i] = "host:" + ctx.Request.Host } else { headerValues[i] = "host:" + ctx.Request.URL.Host } } else { headerValues[i] = k + ":" + strings.Join(ctx.SignedHeaderVals[k], ",") } } stripExcessSpaces(headerValues) ctx.canonicalHeaders = strings.Join(headerValues, "\n") } func (ctx *signingCtx) buildCanonicalString() { ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) uri := getURIPath(ctx.Request.URL) if !ctx.DisableURIPathEscaping { uri = rest.EscapePath(uri, false) } ctx.canonicalString = strings.Join([]string{ ctx.Request.Method, uri, ctx.Request.URL.RawQuery, ctx.canonicalHeaders + "\n", ctx.signedHeaders, ctx.bodyDigest, }, "\n") } func (ctx *signingCtx) buildStringToSign() { ctx.stringToSign = strings.Join([]string{ authHeaderPrefix, formatTime(ctx.Time), ctx.credentialString, hex.EncodeToString(hashSHA256([]byte(ctx.canonicalString))), }, "\n") } func (ctx *signingCtx) buildSignature() { creds := deriveSigningKey(ctx.Region, ctx.ServiceName, ctx.credValues.SecretAccessKey, ctx.Time) signature := hmacSHA256(creds, []byte(ctx.stringToSign)) ctx.signature = hex.EncodeToString(signature) } func (ctx *signingCtx) buildBodyDigest() error { hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") if hash == "" { includeSHA256Header := ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "s3-object-lambda" || ctx.ServiceName == "glacier" s3Presign := ctx.isPresign && (ctx.ServiceName == "s3" || ctx.ServiceName == "s3-object-lambda") if ctx.unsignedPayload || s3Presign { hash = "UNSIGNED-PAYLOAD" includeSHA256Header = !s3Presign } else if ctx.Body == nil { hash = emptyStringSHA256 } else { if !aws.IsReaderSeekable(ctx.Body) { return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) } hashBytes, err := makeSha256Reader(ctx.Body) if err != nil { return err } hash = hex.EncodeToString(hashBytes) } if includeSHA256Header { ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) } } ctx.bodyDigest = hash return nil } // isRequestSigned returns if the request is currently signed or presigned func (ctx *signingCtx) isRequestSigned() bool { if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { return true } if ctx.Request.Header.Get("Authorization") != "" { return true } return false } // unsign removes signing flags for both signed and presigned requests. func (ctx *signingCtx) removePresign() { ctx.Query.Del("X-Amz-Algorithm") ctx.Query.Del("X-Amz-Signature") ctx.Query.Del("X-Amz-Security-Token") ctx.Query.Del("X-Amz-Date") ctx.Query.Del("X-Amz-Expires") ctx.Query.Del("X-Amz-Credential") ctx.Query.Del("X-Amz-SignedHeaders") } func hmacSHA256(key []byte, data []byte) []byte { hash := hmac.New(sha256.New, key) hash.Write(data) return hash.Sum(nil) } func hashSHA256(data []byte) []byte { hash := sha256.New() hash.Write(data) return hash.Sum(nil) } func makeSha256Reader(reader io.ReadSeeker) (hashBytes []byte, err error) { hash := sha256.New() start, err := reader.Seek(0, sdkio.SeekCurrent) if err != nil { return nil, err } defer func() { // ensure error is return if unable to seek back to start of payload. _, err = reader.Seek(start, sdkio.SeekStart) }() // Use CopyN to avoid allocating the 32KB buffer in io.Copy for bodies // smaller than 32KB. Fall back to io.Copy if we fail to determine the size. size, err := aws.SeekerLen(reader) if err != nil { io.Copy(hash, reader) } else { io.CopyN(hash, reader, size) } return hash.Sum(nil), nil } const doubleSpace = " " // stripExcessSpaces will rewrite the passed in slice's string values to not // contain multiple side-by-side spaces. func stripExcessSpaces(vals []string) { var j, k, l, m, spaces int for i, str := range vals { // Trim trailing spaces for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { } // Trim leading spaces for k = 0; k < j && str[k] == ' '; k++ { } str = str[k : j+1] // Strip multiple spaces. j = strings.Index(str, doubleSpace) if j < 0 { vals[i] = str continue } buf := []byte(str) for k, m, l = j, j, len(buf); k < l; k++ { if buf[k] == ' ' { if spaces == 0 { // First space. buf[m] = buf[k] m++ } spaces++ } else { // End of multiple spaces. spaces = 0 buf[m] = buf[k] m++ } } vals[i] = string(buf[:m]) } } func buildSigningScope(region, service string, dt time.Time) string { return strings.Join([]string{ formatShortTime(dt), region, service, awsV4Request, }, "/") } func deriveSigningKey(region, service, secretKey string, dt time.Time) []byte { kDate := hmacSHA256([]byte("AWS4"+secretKey), []byte(formatShortTime(dt))) kRegion := hmacSHA256(kDate, []byte(region)) kService := hmacSHA256(kRegion, []byte(service)) signingKey := hmacSHA256(kService, []byte(awsV4Request)) return signingKey } func formatShortTime(dt time.Time) string { return dt.UTC().Format(shortTimeFormat) } func formatTime(dt time.Time) string { return dt.UTC().Format(timeFormat) }
851
session-manager-plugin
aws
Go
package v4 import ( "bytes" "io" "io/ioutil" "net/http" "net/http/httptest" "reflect" "strconv" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/awstesting" ) func epochTime() time.Time { return time.Unix(0, 0) } func TestStripExcessHeaders(t *testing.T) { vals := []string{ "", "123", "1 2 3", "1 2 3 ", " 1 2 3", "1 2 3", "1 23", "1 2 3", "1 2 ", " 1 2 ", "12 3", "12 3 1", "12 3 1", "12 3 1abc123", } expected := []string{ "", "123", "1 2 3", "1 2 3", "1 2 3", "1 2 3", "1 23", "1 2 3", "1 2", "1 2", "12 3", "12 3 1", "12 3 1", "12 3 1abc123", } stripExcessSpaces(vals) for i := 0; i < len(vals); i++ { if e, a := expected[i], vals[i]; e != a { t.Errorf("%d, expect %v, got %v", i, e, a) } } } func buildRequest(serviceName, region, body string) (*http.Request, io.ReadSeeker) { reader := strings.NewReader(body) return buildRequestWithBodyReader(serviceName, region, reader) } func buildRequestReaderSeeker(serviceName, region, body string) (*http.Request, io.ReadSeeker) { reader := &readerSeekerWrapper{strings.NewReader(body)} return buildRequestWithBodyReader(serviceName, region, reader) } func buildRequestWithBodyReader(serviceName, region string, body io.Reader) (*http.Request, io.ReadSeeker) { var bodyLen int type lenner interface { Len() int } if lr, ok := body.(lenner); ok { bodyLen = lr.Len() } endpoint := "https://" + serviceName + "." + region + ".amazonaws.com" req, _ := http.NewRequest("POST", endpoint, body) req.URL.Opaque = "//example.org/bucket/key-._~,!@#$%^&*()" req.Header.Set("X-Amz-Target", "prefix.Operation") req.Header.Set("Content-Type", "application/x-amz-json-1.0") if bodyLen > 0 { req.Header.Set("Content-Length", strconv.Itoa(bodyLen)) } req.Header.Set("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* (+)") req.Header.Add("X-Amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)") req.Header.Add("X-amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)") var seeker io.ReadSeeker if sr, ok := body.(io.ReadSeeker); ok { seeker = sr } else { seeker = aws.ReadSeekCloser(body) } return req, seeker } func buildSigner() Signer { return Signer{ Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), } } func removeWS(text string) string { text = strings.Replace(text, " ", "", -1) text = strings.Replace(text, "\n", "", -1) text = strings.Replace(text, "\t", "", -1) return text } func assertEqual(t *testing.T, expected, given string) { if removeWS(expected) != removeWS(given) { t.Errorf("\nExpected: %s\nGiven: %s", expected, given) } } func TestPresignRequest(t *testing.T) { req, body := buildRequest("dynamodb", "us-east-1", "{}") signer := buildSigner() signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, epochTime()) expectedDate := "19700101T000000Z" expectedHeaders := "content-length;content-type;host;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore" expectedSig := "122f0b9e091e4ba84286097e2b3404a1f1f4c4aad479adda95b7dff0ccbe5581" expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" expectedTarget := "prefix.Operation" q := req.URL.Query() if e, a := expectedSig, q.Get("X-Amz-Signature"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedCred, q.Get("X-Amz-Credential"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedHeaders, q.Get("X-Amz-SignedHeaders"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { t.Errorf("expect %v, got %v", e, a) } if a := q.Get("X-Amz-Meta-Other-Header"); len(a) != 0 { t.Errorf("expect %v to be empty", a) } if e, a := expectedTarget, q.Get("X-Amz-Target"); e != a { t.Errorf("expect %v, got %v", e, a) } } func TestPresignBodyWithArrayRequest(t *testing.T) { req, body := buildRequest("dynamodb", "us-east-1", "{}") req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" signer := buildSigner() signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, epochTime()) expectedDate := "19700101T000000Z" expectedHeaders := "content-length;content-type;host;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore" expectedSig := "e3ac55addee8711b76c6d608d762cff285fe8b627a057f8b5ec9268cf82c08b1" expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" expectedTarget := "prefix.Operation" q := req.URL.Query() if e, a := expectedSig, q.Get("X-Amz-Signature"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedCred, q.Get("X-Amz-Credential"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedHeaders, q.Get("X-Amz-SignedHeaders"); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { t.Errorf("expect %v, got %v", e, a) } if a := q.Get("X-Amz-Meta-Other-Header"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } if e, a := expectedTarget, q.Get("X-Amz-Target"); e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSignRequest(t *testing.T) { req, body := buildRequest("dynamodb", "us-east-1", "{}") signer := buildSigner() signer.Sign(req, body, "dynamodb", "us-east-1", epochTime()) expectedDate := "19700101T000000Z" expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore;x-amz-security-token;x-amz-target, Signature=a518299330494908a70222cec6899f6f32f297f8595f6df1776d998936652ad9" q := req.Header if e, a := expectedSig, q.Get("Authorization"); e != a { t.Errorf("expect\n%v\nactual\n%v\n", e, a) } if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { t.Errorf("expect\n%v\nactual\n%v\n", e, a) } } func TestSignBodyS3(t *testing.T) { req, body := buildRequest("s3", "us-east-1", "hello") signer := buildSigner() signer.Sign(req, body, "s3", "us-east-1", time.Now()) hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSignBodyGlacier(t *testing.T) { req, body := buildRequest("glacier", "us-east-1", "hello") signer := buildSigner() signer.Sign(req, body, "glacier", "us-east-1", time.Now()) hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestPresign_SignedPayload(t *testing.T) { req, body := buildRequest("glacier", "us-east-1", "hello") signer := buildSigner() signer.Presign(req, body, "glacier", "us-east-1", 5*time.Minute, time.Now()) hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestPresign_UnsignedPayload(t *testing.T) { req, body := buildRequest("service-name", "us-east-1", "hello") signer := buildSigner() signer.UnsignedPayload = true signer.Presign(req, body, "service-name", "us-east-1", 5*time.Minute, time.Now()) hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "UNSIGNED-PAYLOAD", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestPresign_UnsignedPayload_S3(t *testing.T) { req, body := buildRequest("s3", "us-east-1", "hello") signer := buildSigner() signer.Presign(req, body, "s3", "us-east-1", 5*time.Minute, time.Now()) if a := req.Header.Get("X-Amz-Content-Sha256"); len(a) != 0 { t.Errorf("expect no content sha256 got %v", a) } } func TestSignUnseekableBody(t *testing.T) { req, body := buildRequestWithBodyReader("mock-service", "mock-region", bytes.NewBuffer([]byte("hello"))) signer := buildSigner() _, err := signer.Sign(req, body, "mock-service", "mock-region", time.Now()) if err == nil { t.Fatalf("expect error signing request") } if e, a := "unseekable request body", err.Error(); !strings.Contains(a, e) { t.Errorf("expect %q to be in %q", e, a) } } func TestSignUnsignedPayloadUnseekableBody(t *testing.T) { req, body := buildRequestWithBodyReader("mock-service", "mock-region", bytes.NewBuffer([]byte("hello"))) signer := buildSigner() signer.UnsignedPayload = true _, err := signer.Sign(req, body, "mock-service", "mock-region", time.Now()) if err != nil { t.Fatalf("expect no error, got %v", err) } hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "UNSIGNED-PAYLOAD", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSignPreComputedHashUnseekableBody(t *testing.T) { req, body := buildRequestWithBodyReader("mock-service", "mock-region", bytes.NewBuffer([]byte("hello"))) signer := buildSigner() req.Header.Set("X-Amz-Content-Sha256", "some-content-sha256") _, err := signer.Sign(req, body, "mock-service", "mock-region", time.Now()) if err != nil { t.Fatalf("expect no error, got %v", err) } hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "some-content-sha256", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSignPrecomputedBodyChecksum(t *testing.T) { req, body := buildRequest("dynamodb", "us-east-1", "hello") req.Header.Set("X-Amz-Content-Sha256", "PRECOMPUTED") signer := buildSigner() signer.Sign(req, body, "dynamodb", "us-east-1", time.Now()) hash := req.Header.Get("X-Amz-Content-Sha256") if e, a := "PRECOMPUTED", hash; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestAnonymousCredentials(t *testing.T) { svc := awstesting.NewClient(&aws.Config{Credentials: credentials.AnonymousCredentials}) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) SignSDKRequest(r) urlQ := r.HTTPRequest.URL.Query() if a := urlQ.Get("X-Amz-Signature"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } if a := urlQ.Get("X-Amz-Credential"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } if a := urlQ.Get("X-Amz-SignedHeaders"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } if a := urlQ.Get("X-Amz-Date"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } hQ := r.HTTPRequest.Header if a := hQ.Get("Authorization"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } if a := hQ.Get("X-Amz-Date"); len(a) != 0 { t.Errorf("expect %v to be empty, was not", a) } } func TestIgnoreResignRequestWithValidCreds(t *testing.T) { svc := awstesting.NewClient(&aws.Config{ Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), Region: aws.String("us-west-2"), }) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) SignSDKRequest(r) sig := r.HTTPRequest.Header.Get("Authorization") SignSDKRequestWithCurrentTime(r, func() time.Time { // Simulate one second has passed so that signature's date changes // when it is resigned. return time.Now().Add(1 * time.Second) }) if e, a := sig, r.HTTPRequest.Header.Get("Authorization"); e == a { t.Errorf("expect %v to be %v, but was not", e, a) } } func TestIgnorePreResignRequestWithValidCreds(t *testing.T) { svc := awstesting.NewClient(&aws.Config{ Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), Region: aws.String("us-west-2"), }) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) r.ExpireTime = time.Minute * 10 SignSDKRequest(r) sig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") SignSDKRequestWithCurrentTime(r, func() time.Time { // Simulate one second has passed so that signature's date changes // when it is resigned. return time.Now().Add(1 * time.Second) }) if e, a := sig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"); e == a { t.Errorf("expect %v to be %v, but was not", e, a) } } func TestResignRequestExpiredCreds(t *testing.T) { creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") svc := awstesting.NewClient(&aws.Config{Credentials: creds}) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) SignSDKRequest(r) querySig := r.HTTPRequest.Header.Get("Authorization") var origSignedHeaders string for _, p := range strings.Split(querySig, ", ") { if strings.HasPrefix(p, "SignedHeaders=") { origSignedHeaders = p[len("SignedHeaders="):] break } } if a := origSignedHeaders; len(a) == 0 { t.Errorf("expect not to be empty, but was") } if e, a := origSignedHeaders, "authorization"; strings.Contains(a, e) { t.Errorf("expect %v to not be in %v, but was", e, a) } origSignedAt := r.LastSignedAt creds.Expire() SignSDKRequestWithCurrentTime(r, func() time.Time { // Simulate one second has passed so that signature's date changes // when it is resigned. return time.Now().Add(1 * time.Second) }) updatedQuerySig := r.HTTPRequest.Header.Get("Authorization") if e, a := querySig, updatedQuerySig; e == a { t.Errorf("expect %v to be %v, was not", e, a) } var updatedSignedHeaders string for _, p := range strings.Split(updatedQuerySig, ", ") { if strings.HasPrefix(p, "SignedHeaders=") { updatedSignedHeaders = p[len("SignedHeaders="):] break } } if a := updatedSignedHeaders; len(a) == 0 { t.Errorf("expect not to be empty, but was") } if e, a := updatedQuerySig, "authorization"; strings.Contains(a, e) { t.Errorf("expect %v to not be in %v, but was", e, a) } if e, a := origSignedAt, r.LastSignedAt; e == a { t.Errorf("expect %v to be %v, was not", e, a) } } func TestPreResignRequestExpiredCreds(t *testing.T) { provider := &credentials.StaticProvider{Value: credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "SESSION", }} creds := credentials.NewCredentials(provider) svc := awstesting.NewClient(&aws.Config{Credentials: creds}) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) r.ExpireTime = time.Minute * 10 SignSDKRequest(r) querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") signedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") if a := signedHeaders; len(a) == 0 { t.Errorf("expect not to be empty, but was") } origSignedAt := r.LastSignedAt creds.Expire() SignSDKRequestWithCurrentTime(r, func() time.Time { // Simulate the request occurred 15 minutes in the past return time.Now().Add(-48 * time.Hour) }) if e, a := querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"); e == a { t.Errorf("expect %v to be %v, was not", e, a) } resignedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") if e, a := signedHeaders, resignedHeaders; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := signedHeaders, "x-amz-signedHeaders"; strings.Contains(a, e) { t.Errorf("expect %v to not be in %v, but was", e, a) } if e, a := origSignedAt, r.LastSignedAt; e == a { t.Errorf("expect %v to be %v, was not", e, a) } } func TestResignRequestExpiredRequest(t *testing.T) { creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") svc := awstesting.NewClient(&aws.Config{Credentials: creds}) r := svc.NewRequest( &request.Operation{ Name: "BatchGetItem", HTTPMethod: "POST", HTTPPath: "/", }, nil, nil, ) SignSDKRequest(r) querySig := r.HTTPRequest.Header.Get("Authorization") origSignedAt := r.LastSignedAt SignSDKRequestWithCurrentTime(r, func() time.Time { // Simulate the request occurred 15 minutes in the past return time.Now().Add(15 * time.Minute) }) if e, a := querySig, r.HTTPRequest.Header.Get("Authorization"); e == a { t.Errorf("expect %v to be %v, was not", e, a) } if e, a := origSignedAt, r.LastSignedAt; e == a { t.Errorf("expect %v to be %v, was not", e, a) } } func TestSignWithRequestBody(t *testing.T) { creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") signer := NewSigner(creds) expectBody := []byte("abc123") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { t.Errorf("expect no error, got %v", err) } if e, a := expectBody, b; !reflect.DeepEqual(e, a) { t.Errorf("expect %v, got %v", e, a) } w.WriteHeader(http.StatusOK) })) defer server.Close() req, err := http.NewRequest("POST", server.URL, nil) if err != nil { t.Errorf("expect not no error, got %v", err) } _, err = signer.Sign(req, bytes.NewReader(expectBody), "service", "region", time.Now()) if err != nil { t.Errorf("expect not no error, got %v", err) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("expect not no error, got %v", err) } if e, a := http.StatusOK, resp.StatusCode; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSignWithRequestBody_Overwrite(t *testing.T) { creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") signer := NewSigner(creds) var expectBody []byte server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { t.Errorf("expect not no error, got %v", err) } if e, a := len(expectBody), len(b); e != a { t.Errorf("expect %v, got %v", e, a) } w.WriteHeader(http.StatusOK) })) defer server.Close() req, err := http.NewRequest("GET", server.URL, strings.NewReader("invalid body")) if err != nil { t.Errorf("expect not no error, got %v", err) } _, err = signer.Sign(req, nil, "service", "region", time.Now()) req.ContentLength = 0 if err != nil { t.Errorf("expect not no error, got %v", err) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("expect not no error, got %v", err) } if e, a := http.StatusOK, resp.StatusCode; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestBuildCanonicalRequest(t *testing.T) { req, body := buildRequest("dynamodb", "us-east-1", "{}") req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" ctx := &signingCtx{ ServiceName: "dynamodb", Region: "us-east-1", Request: req, Body: body, Query: req.URL.Query(), Time: time.Now(), ExpireTime: 5 * time.Second, } ctx.buildCanonicalString() expected := "https://example.org/bucket/key-._~,!@#$%^&*()?Foo=z&Foo=o&Foo=m&Foo=a" if e, a := expected, ctx.Request.URL.String(); e != a { t.Errorf("expect %v, got %v", e, a) } } func TestSignWithBody_ReplaceRequestBody(t *testing.T) { creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") req, seekerBody := buildRequest("dynamodb", "us-east-1", "{}") req.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) s := NewSigner(creds) origBody := req.Body _, err := s.Sign(req, seekerBody, "dynamodb", "us-east-1", time.Now()) if err != nil { t.Fatalf("expect no error, got %v", err) } if req.Body == origBody { t.Errorf("expeect request body to not be origBody") } if req.Body == nil { t.Errorf("expect request body to be changed but was nil") } } func TestSignWithBody_NoReplaceRequestBody(t *testing.T) { creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") req, seekerBody := buildRequest("dynamodb", "us-east-1", "{}") req.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) s := NewSigner(creds, func(signer *Signer) { signer.DisableRequestBodyOverwrite = true }) origBody := req.Body _, err := s.Sign(req, seekerBody, "dynamodb", "us-east-1", time.Now()) if err != nil { t.Fatalf("expect no error, got %v", err) } if req.Body != origBody { t.Errorf("expect request body to not be chagned") } } func TestRequestHost(t *testing.T) { req, body := buildRequest("dynamodb", "us-east-1", "{}") req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" req.Host = "myhost" ctx := &signingCtx{ ServiceName: "dynamodb", Region: "us-east-1", Request: req, Body: body, Query: req.URL.Query(), Time: time.Now(), ExpireTime: 5 * time.Second, } ctx.buildCanonicalHeaders(ignoredHeaders, ctx.Request.Header) if !strings.Contains(ctx.canonicalHeaders, "host:"+req.Host) { t.Errorf("canonical host header invalid") } } func BenchmarkPresignRequest(b *testing.B) { signer := buildSigner() req, body := buildRequestReaderSeeker("dynamodb", "us-east-1", "{}") for i := 0; i < b.N; i++ { signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Now()) } } func BenchmarkSignRequest(b *testing.B) { signer := buildSigner() req, body := buildRequestReaderSeeker("dynamodb", "us-east-1", "{}") for i := 0; i < b.N; i++ { signer.Sign(req, body, "dynamodb", "us-east-1", time.Now()) } } var stripExcessSpaceCases = []string{ `AWS4-HMAC-SHA256 Credential=AKIDFAKEIDFAKEID/20160628/us-west-2/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef1234567890abcdef1234567890abcdef`, `123 321 123 321`, ` 123 321 123 321 `, ` 123 321 123 321 `, "123", "1 2 3", " 1 2 3", "1 2 3", "1 23", "1 2 3", "1 2 ", " 1 2 ", "12 3", "12 3 1", "12 3 1", "12 3 1abc123", } func BenchmarkStripExcessSpaces(b *testing.B) { for i := 0; i < b.N; i++ { // Make sure to start with a copy of the cases cases := append([]string{}, stripExcessSpaceCases...) stripExcessSpaces(cases) } } // readerSeekerWrapper mimics the interface provided by request.offsetReader type readerSeekerWrapper struct { r *strings.Reader } func (r *readerSeekerWrapper) Read(p []byte) (n int, err error) { return r.r.Read(p) } func (r *readerSeekerWrapper) Seek(offset int64, whence int) (int64, error) { return r.r.Seek(offset, whence) } func (r *readerSeekerWrapper) Len() int { return r.r.Len() }
770
session-manager-plugin
aws
Go
package awstesting import ( "encoding/json" "fmt" "net/url" "reflect" "regexp" "sort" "strings" "testing" "github.com/aws/aws-sdk-go/internal/smithytesting" ) // Match is a testing helper to test for testing error by comparing expected // with a regular expression. func Match(t *testing.T, regex, expected string) { if !regexp.MustCompile(regex).Match([]byte(expected)) { t.Errorf("%q\n\tdoes not match /%s/", expected, regex) } } // AssertURL verifies the expected URL is matches the actual. func AssertURL(t *testing.T, expect, actual string, msgAndArgs ...interface{}) bool { expectURL, err := url.Parse(expect) if err != nil { t.Errorf(errMsg("unable to parse expected URL", err, msgAndArgs)) return false } actualURL, err := url.Parse(actual) if err != nil { t.Errorf(errMsg("unable to parse actual URL", err, msgAndArgs)) return false } equal(t, expectURL.Host, actualURL.Host, msgAndArgs...) equal(t, expectURL.Scheme, actualURL.Scheme, msgAndArgs...) equal(t, expectURL.Path, actualURL.Path, msgAndArgs...) return AssertQuery(t, expectURL.Query().Encode(), actualURL.Query().Encode(), msgAndArgs...) } var queryMapKey = regexp.MustCompile("(.*?)\\.[0-9]+\\.key") // AssertQuery verifies the expect HTTP query string matches the actual. func AssertQuery(t *testing.T, expect, actual string, msgAndArgs ...interface{}) bool { expectQ, err := url.ParseQuery(expect) if err != nil { t.Errorf(errMsg("unable to parse expected Query", err, msgAndArgs)) return false } actualQ, err := url.ParseQuery(actual) if err != nil { t.Errorf(errMsg("unable to parse actual Query", err, msgAndArgs)) return false } // Make sure the keys are the same if !equal(t, queryValueKeys(expectQ), queryValueKeys(actualQ), msgAndArgs...) { return false } keys := map[string][]string{} for key, v := range expectQ { if queryMapKey.Match([]byte(key)) { submatch := queryMapKey.FindStringSubmatch(key) keys[submatch[1]] = append(keys[submatch[1]], v...) } } for k, v := range keys { // clear all keys that have prefix for key := range expectQ { if strings.HasPrefix(key, k) { delete(expectQ, key) } } sort.Strings(v) for i, value := range v { expectQ[fmt.Sprintf("%s.%d.key", k, i+1)] = []string{value} } } for k, expectQVals := range expectQ { sort.Strings(expectQVals) actualQVals := actualQ[k] sort.Strings(actualQVals) if !equal(t, expectQVals, actualQVals, msgAndArgs...) { return false } } return true } // AssertJSON verifies that the expect json string matches the actual. func AssertJSON(t *testing.T, expect, actual string, msgAndArgs ...interface{}) bool { expectVal := map[string]interface{}{} if err := json.Unmarshal([]byte(expect), &expectVal); err != nil { t.Errorf(errMsg("unable to parse expected JSON", err, msgAndArgs...)) return false } actualVal := map[string]interface{}{} if err := json.Unmarshal([]byte(actual), &actualVal); err != nil { t.Errorf(errMsg("unable to parse actual JSON", err, msgAndArgs...)) return false } return equal(t, expectVal, actualVal, msgAndArgs...) } // AssertXML verifies that the expect XML string matches the actual. func AssertXML(t *testing.T, expect, actual string, msgAndArgs ...interface{}) bool { if err := smithytesting.XMLEqual([]byte(expect), []byte(actual)); err != nil { t.Error("expect XML match", err, messageFromMsgAndArgs(msgAndArgs)) return false } return true } // DidPanic returns if the function paniced and returns true if the function paniced. func DidPanic(fn func()) (bool, interface{}) { var paniced bool var msg interface{} func() { defer func() { if msg = recover(); msg != nil { paniced = true } }() fn() }() return paniced, msg } // objectsAreEqual determines if two objects are considered equal. // // This function does no assertion of any kind. // // Based on github.com/stretchr/testify/assert.ObjectsAreEqual // Copied locally to prevent non-test build dependencies on testify func objectsAreEqual(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } return reflect.DeepEqual(expected, actual) } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123, "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). // // Based on github.com/stretchr/testify/assert.Equal // Copied locally to prevent non-test build dependencies on testify func equal(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool { if !objectsAreEqual(expected, actual) { t.Errorf("%s\n%s", messageFromMsgAndArgs(msgAndArgs), SprintExpectActual(expected, actual)) return false } return true } func errMsg(baseMsg string, err error, msgAndArgs ...interface{}) string { message := messageFromMsgAndArgs(msgAndArgs) if message != "" { message += ", " } return fmt.Sprintf("%s%s, %v", message, baseMsg, err) } // Based on github.com/stretchr/testify/assert.messageFromMsgAndArgs // Copied locally to prevent non-test build dependencies on testify func messageFromMsgAndArgs(msgAndArgs []interface{}) string { if len(msgAndArgs) == 0 || msgAndArgs == nil { return "" } if len(msgAndArgs) == 1 { return msgAndArgs[0].(string) } if len(msgAndArgs) > 1 { return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) } return "" } func queryValueKeys(v url.Values) []string { keys := make([]string, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Strings(keys) return keys } // SprintExpectActual returns a string for test failure cases when the actual // value is not the same as the expected. func SprintExpectActual(expect, actual interface{}) string { return fmt.Sprintf("expect: %+v\nactual: %+v\n", expect, actual) }
210
session-manager-plugin
aws
Go
package awstesting_test import ( "encoding/xml" "testing" "github.com/aws/aws-sdk-go/awstesting" ) func TestAssertJSON(t *testing.T) { cases := []struct { e, a string asserts bool }{ { e: `{"RecursiveStruct":{"RecursiveMap":{"foo":{"NoRecurse":"foo"},"bar":{"NoRecurse":"bar"}}}}`, a: `{"RecursiveStruct":{"RecursiveMap":{"bar":{"NoRecurse":"bar"},"foo":{"NoRecurse":"foo"}}}}`, asserts: true, }, } for i, c := range cases { mockT := &testing.T{} if awstesting.AssertJSON(mockT, c.e, c.a) != c.asserts { t.Error("Assert JSON result was not expected.", i) } } } func TestAssertXML(t *testing.T) { cases := []struct { e, a string asserts bool container struct { XMLName xml.Name `xml:"OperationRequest"` NS string `xml:"xmlns,attr"` RecursiveStruct struct { XMLName xml.Name RecursiveMap struct { XMLName xml.Name Entries []struct { Key string `xml:"key"` Value struct { XMLName xml.Name `xml:"value"` NoRecurse string } } `xml:"entry"` } } } }{ { e: `<OperationRequest xmlns="https://foo/"><RecursiveStruct xmlns="https://foo/"><RecursiveMap xmlns="https://foo/"><entry xmlns="https://foo/"><key xmlns="https://foo/">foo</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">foo</NoRecurse></value></entry><entry xmlns="https://foo/"><key xmlns="https://foo/">bar</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">bar</NoRecurse></value></entry></RecursiveMap></RecursiveStruct></OperationRequest>`, a: `<OperationRequest xmlns="https://foo/"><RecursiveStruct xmlns="https://foo/"><RecursiveMap xmlns="https://foo/"><entry xmlns="https://foo/"><key xmlns="https://foo/">foo</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">foo</NoRecurse></value></entry><entry xmlns="https://foo/"><key xmlns="https://foo/">bar</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">bar</NoRecurse></value></entry></RecursiveMap></RecursiveStruct></OperationRequest>`, asserts: true, }, { e: `<OperationRequest xmlns="https://foo/"><RecursiveStruct xmlns="https://foo/"><RecursiveMap xmlns="https://foo/"><entry xmlns="https://foo/"><key xmlns="https://foo/">foo</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">foo</NoRecurse></value></entry><entry xmlns="https://foo/"><key xmlns="https://foo/">bar</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">bar</NoRecurse></value></entry></RecursiveMap></RecursiveStruct></OperationRequest>`, a: `<OperationRequest xmlns="https://foo/"><RecursiveStruct xmlns="https://foo/"><RecursiveMap xmlns="https://foo/"><entry xmlns="https://foo/"><key xmlns="https://foo/">baz</key><value xmlns="https://foo/"><NoRecurse xmlns="https://foo/">baz</NoRecurse></value></entry></RecursiveMap></RecursiveStruct></OperationRequest>`, asserts: false, }, } for i, c := range cases { mockT := &testing.T{} if awstesting.AssertXML(mockT, c.e, c.a) != c.asserts { t.Error("Assert XML result was not expected.", i) } } } func TestAssertQuery(t *testing.T) { cases := []struct { e, a string asserts bool }{ { e: `Action=OperationName&Version=2014-01-01&Foo=val1&Bar=val2`, a: `Action=OperationName&Version=2014-01-01&Foo=val2&Bar=val3`, asserts: false, }, { e: `Action=OperationName&Version=2014-01-01&Foo=val1&Bar=val2`, a: `Action=OperationName&Version=2014-01-01&Foo=val1&Bar=val2`, asserts: true, }, } for i, c := range cases { mockT := &testing.T{} if awstesting.AssertQuery(mockT, c.e, c.a) != c.asserts { t.Error("Assert Query result was not expected.", i) } } }
96
session-manager-plugin
aws
Go
package awstesting import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/defaults" ) // NewClient creates and initializes a generic service client for testing. func NewClient(cfgs ...*aws.Config) *client.Client { info := metadata.ClientInfo{ Endpoint: "http://endpoint", SigningName: "", } def := defaults.Get() def.Config.MergeIn(cfgs...) if v := aws.StringValue(def.Config.Endpoint); len(v) > 0 { info.Endpoint = v } return client.New(*def.Config, info, def.Handlers) }
25
session-manager-plugin
aws
Go
package awstesting import ( "crypto/tls" "crypto/x509" "fmt" "net/http" "net/http/httptest" ) // NewTLSClientCertServer creates a new HTTP test server initialize to require // HTTP clients authenticate with TLS client certificates. func NewTLSClientCertServer(handler http.Handler) (*httptest.Server, error) { server := httptest.NewUnstartedServer(handler) if server.TLS == nil { server.TLS = &tls.Config{} } server.TLS.ClientAuth = tls.RequireAndVerifyClientCert if server.TLS.ClientCAs == nil { server.TLS.ClientCAs = x509.NewCertPool() } certPem := append(ClientTLSCert, ClientTLSKey...) if ok := server.TLS.ClientCAs.AppendCertsFromPEM(certPem); !ok { return nil, fmt.Errorf("failed to append client certs") } return server, nil } // CreateClientTLSCertFiles returns a set of temporary files for the client // certificate and key files. func CreateClientTLSCertFiles() (cert, key string, err error) { cert, err = createTmpFile(ClientTLSCert) if err != nil { return "", "", err } key, err = createTmpFile(ClientTLSKey) if err != nil { return "", "", err } return cert, key, nil } /* Client certificate generation # Create CA openssl genrsa -aes256 -passout pass:xxxx -out ca.pass.key 4096 openssl rsa -passin pass:xxxx -in ca.pass.key -out ca.key rm ca.pass.key openssl req -new -x509 -days 3650 -key ca.key -out ca.pem # Create key for client openssl genrsa -aes256 -passout pass:xxxx -out 01-client.pass.key 4096 openssl rsa -passin pass:xxxx -in 01-client.pass.key -out 01-client.key rm 01-client.pass.key # create csr for client openssl req -new -key 01-client.key -out 01-client.csr openssl x509 -req -days 3650 -in 01-client.csr -CA ca.pem -CAkey ca.key -set_serial 01 -out 01-client.pem cat 01-client.key 01-client.pem ca.pem > 01-client.full.pem */ var ( // ClientTLSCert 01-client.pem ClientTLSCert = []byte(`-----BEGIN CERTIFICATE----- MIIEjjCCAnYCAQEwDQYJKoZIhvcNAQEFBQAwDTELMAkGA1UEBhMCVVMwHhcNMjAx MTI0MDAyODI5WhcNMzAxMTIyMDAyODI5WjANMQswCQYDVQQGEwJVUzCCAiIwDQYJ KoZIhvcNAQEBBQADggIPADCCAgoCggIBAN8gy1UtBR73fCJ9JWIREfBtqW/+hfNn ZyIu7bc4MTWoP1dYG3CVV+HALijfVNeFQaohXjWaUIaXAa4idtM1AAf+J8GADqHp z4qnAoIWLqfWRwtFJyggB2tnzmFA/yxR2jlpe3yT/OL0aXtYgS9bVeH6nWWjNuAo D6qlTGSB/7ns8iDUK0WRJsodRGPi8OHNm4q5Pxqbzfvzu2vmF66NcvNb/96yIngl Sjv6CSTz16hbbmqQQJAXurjkOLbSFCYZ76D2pYmqS/hLpUlFH/Bd/BcVP/3H5INA fodY9Rx1oXETNuC69QgLA+2zlhGmbICh+OexIqNb2RH6vwi7EV5/Y4v7CKwzypre OgOtkYQiDjhG3CxB+8E4q5t43SKpft7KFUXWmTaxOxZr7gmuBZGV5Lxzg+NgnFnV tkPCVxKYsSSdhs11z0Ne/BBsGXCw0YoJ7HacFuVCf//C/vqT7y2ivhao3oMlv3ae HjfHi9WIsZbDBB37Kk4UFXlXO0WXijrH09wILDW3IQ65fYMUBIyKFt9hKGjWKfcg BWuTgJ98eG+BmxP6PIWgZTo1XdWKcxPblidLkwU4OzzuHONSsoGL8eeTBC0WcUT0 5H3bSVbkYQObKHe4fxCVUC/xEPgQga0NBlXLq0Zr8UnNPio7Vip5pzJ99ma4t4PN TnP6f2B1zrjLAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAB2ei7140M68glYQk9vp oOUz+8Ibg9ogo7LCk95jsFxGvBJu62mFfa1s1NMsWq4QHK5XG5nkq4ZUues6dl/B LpSv8uwIwV7aNgZathJLxb2M4s32xPUodGbfaeVbk08qyEGMCo4QE000Hace/iFZ jbNT6rkU6Edv/gsvHkVkCouMTsZhpMHezyrnSBAyxwqU82QVHbC2ByEQFNJ+0rCJ gAzcXuWI/6X3+LQSQ44Y0n7nj7Rx6YidtwCoFoQ1oIAdlt6LyUKTtEUa3uN9Cdb6 nO4VGNC5p4URImHTMdqxDn0xpTYw0q9P+hierZYViuCaEokNlaWNk2wGHBqRlgxv ci2qox1GCtabhRGyWEUzC9N6coVQPh1xuay8oQB/oXzcwk8LnUaOdVgwhKya1fEt MQrlS/Vsv6e18UQXN0OM3V6mUFa+5wu+C4Ly7XQJ6EUwYZ6LYqO5ypsfXr8GrS0p 32l5nB7r80Q6mjKCG6MB827rIqWQvfadUX5q0xizb/RDKk+SmqxnffY38WpqLWec WpEghlkp2IYQFdg7WxoKXCpz1rv+BI28rowRkVeW6chGqO9zx6Sk/twosiamgRK1 s2MhHZnvl1x4h+uPsST2b4FAyzuDXB39g7pUnAq9XVhWA6J4ndFduIh8jmVWdZBg KJTU5ZEXpuI0w7WDrPwaIUbU -----END CERTIFICATE----- `) // ClientTLSKey 01-client.key ClientTLSKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIIJKQIBAAKCAgEA3yDLVS0FHvd8In0lYhER8G2pb/6F82dnIi7ttzgxNag/V1gb cJVX4cAuKN9U14VBqiFeNZpQhpcBriJ20zUAB/4nwYAOoenPiqcCghYup9ZHC0Un KCAHa2fOYUD/LFHaOWl7fJP84vRpe1iBL1tV4fqdZaM24CgPqqVMZIH/uezyINQr RZEmyh1EY+Lw4c2birk/GpvN+/O7a+YXro1y81v/3rIieCVKO/oJJPPXqFtuapBA kBe6uOQ4ttIUJhnvoPaliapL+EulSUUf8F38FxU//cfkg0B+h1j1HHWhcRM24Lr1 CAsD7bOWEaZsgKH457Eio1vZEfq/CLsRXn9ji/sIrDPKmt46A62RhCIOOEbcLEH7 wTirm3jdIql+3soVRdaZNrE7FmvuCa4FkZXkvHOD42CcWdW2Q8JXEpixJJ2GzXXP Q178EGwZcLDRignsdpwW5UJ//8L++pPvLaK+FqjegyW/dp4eN8eL1YixlsMEHfsq ThQVeVc7RZeKOsfT3AgsNbchDrl9gxQEjIoW32EoaNYp9yAFa5OAn3x4b4GbE/o8 haBlOjVd1YpzE9uWJ0uTBTg7PO4c41KygYvx55MELRZxRPTkfdtJVuRhA5sod7h/ EJVQL/EQ+BCBrQ0GVcurRmvxSc0+KjtWKnmnMn32Zri3g81Oc/p/YHXOuMsCAwEA AQKCAgA2SHwvVKySRBNnMJsPqKd8nrFCFeHwvY9RuakLkhgmva/rR/wk/7BJs7+H Ig46AKlhAo0w7UH5/HLkMm5GI/bF+wchBE6LBZ8AVHE/xLXFD1RpYYGNOX2Um8SR 1IY/+gnlPcxVGovDi0K+R2Hma4oRWC9Cstp+3kAxe9WB/j6AtSyS4AtG+XE+arBg vK1twd+9eCPqDU2npjxKm8fXJ4J3wkIVo7DPGgNdZA8ldk1ZICVUt5N9eshqgttp XuKYAmdR+a98NnoVBhJIKREEIVlbJEhVLXRimiYuN24qZlPIdqw7MEC8nDFweuhf kuWCxeUQOP/8TjQZM6+WKCypmMRWrUqKjPUMuCSLLjAtAMYwKB7MzImsu44ZTUxM Xw3YV1h8Sd2TeueY/Ln9ixxl9FxRMDl7wKOjPG8ZE4Ew/3WNgpi/mqHiadAtCfq4 +XFRT9fxp7hZ08ylHSz4X4lbhY5B7FzX8O9x7MtNUA+p/xuFLEYiwb5sNpXWq4Lr LyzZgTA42ukzM5mabSFaQ3y0lQ41Fx9ytutQceGu3NdeLdkhlhv8zDYuXOhN2ZNs m2gctiGq3C69Z+A3RQ/VnE+lE7Jxb/EOJZVT+tZmdSmFlPa8OubcjCVB5Sa+dQL3 52PSUOSnKwphui0f7Z+K0ojjFXBAbkBDB4oITnxO243hPDOwgQKCAQEA/xNUBAy+ yMNeRlcA1Zqw4PAvHCJAe2QW3xtkfdF+G5MbJDZxkSmwv6E08aKD3SWn2/M2amBM ZbW/s0c3fFjCEn9XG/HjZ26dM11ScBMm4muOU405xCGnaR83Qh8Ahoy0JILejsKz O9qLSMn8e3diQRCE5yEtwgIRC0wtSUQe+ypRnEHwkHA8qWkxh92gaHUuCxmX6yL6 5mqZGOxIVjQJqhHek4zzvFmr+DjhhNFyhIP+kndggViYbOjgTJVG/pWvHWr5QeU7 caF7wfbwbmF378nW/0H5p2wF/20XEZIhQZm/waikGUK8SV+85f0NxIY3FNbmWMyy iXL35uO6rNvyCQKCAQEA3+/S3Ses3Aa2klVvoW8EqeNupMhFLulqNsK+X6nrUukf /2z1zMiA9p/mw+8sy1XKiDybEsKa/N+sOMWKLVLpBwLNg5ZC4MaACC9KPoX0J72C 8SjsKmMVRWrI5iUIQzaH+3NWRW6GC5r8Vjc3vR1dGdqxvhV9fp1oBJ5zFgMs6i2N 1uFv+enBYnu67UbG2kwcYKV1OzYi7vD/+UJXUpfmLN2NpIz5wcU/2rtEtQSI1Z6q v6IayCLArcogX01gAXyB5OyY0ECctpp2KP44wde1AP7xFbF/EC1SeUKQSqlBu2Jw BeABLIz+YM+FEC7DE506HjnQJSJwRv6YFLAfZK25MwKCAQEA2oVjd6i3lWUSEe6d T2Gb4MjDgzWwykTf9zkPaV6cy+DF4ssllfgCbNkdc1kH4OBOovcEijN/n68J0PvV BBlCAfjH1q/uYoD3+bYcVtmBeX4tS1T0xRsTwdI1U9cdayeFeLYJFoKkbEV5B93L CLcpHJabVSsueUOt+GDFdzv90qzZh6VSA1u0DGqLPVtX/cVNscK2TIIGMnnmONzL x9YC5YkzhnK9qIGl+xw3z8JjejVeVXoh2g3dX4hOCC3myVnQ0MIBUjuhJmLylCQK rHWh+3KOVtXdnFnF9aIuniXzibC+/5iLJPzwM2fqe5nEPrXA4ICOjEqpNWmiCVLV bRtsiQKCAQAKfzNjKnjv12C3e0nAR3PwgritALY9fLN93aMO2Ogu+r6FOpZLAxsI dHZcuNlgrqTPvgeG2ZhqQhHQl3HirgA+U+NOR7zazHMz7wOL6ruHIVsB8ukfE4Xr uxWvtAyvGd9F6iIhHw0pfhpV8ECsnLPAgn/SaS94v+ggT00VuxBf6cK8T9Tv4gUu mJ4qgSbRFMA/x4G3RNJeYO2ewX1WYchoUfpRvEn4y0Yy+pQ95/iCCu32DaMzvm1J uC/MR9Q4PZ3ZHT4MhPrTlGn1gfUnIPVbFpg2bBuIppc3F+ermEN8hSC7JcToUbOa 1h9mosqCINyYjh0zoGmi6kw2rArMrVgBAoIBAQD05BZmo3q2zuKYQG5sa9+6G6tl 8hkKBhMZCPuHTaA64NcGgf0/B0pZeOL+HfTvTzv78PdRq4XWKh3EvAlMvjX4MSUt 2QB8aVlIClsqqg+C8/ORhVNoWz9NREt8cp7ZvnxYlUGwQAf93UEQR2FSLe762IAJ kb9qdYAw2wndjjB9J4iYh/nBeyJ1q4KNBrFlwwEkPTPeEhEVxZX7ieOj+bX1/quX s3Rw19uz8o1KwYb950Doo8hygUlR1ElITLTnzw84M4okua3vlmM5+870w06QV6rP 6taQFy5Kh9PAc+RtbtczrMQX5PFUA8N/NE2PNgmpfwwgU2kPg4xEKVuvADoE -----END RSA PRIVATE KEY----- `) // ClientCA ca.pem ClientCA = []byte(`-----BEGIN CERTIFICATE----- MIIEljCCAn4CCQDzkVB8uGX1GDANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJV UzAeFw0yMDExMjQwMDI3NDlaFw0zMDExMjIwMDI3NDlaMA0xCzAJBgNVBAYTAlVT MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA6gfPPxYl/6n/GuPkQwiT RTnH0mohDgBT8vA9RpE3ffI/qY8zO0rD/bHJIsN2neus+bFIciro5S/LxaZ2amx5 Y1WZPOeNKW2r73FfwlhyhQ6a9noiXJYnMqcT3Hn7FLeEMtt3kYkXJw+9k230mBhn L1vWP0KXNoi0B3T0SCJGhJAdjV/tTsTOKVnzaxaRfeXH//+S7McbEAA6m902+VDy tLGjyjB4Ed+AKeQg59FOn6/Q+NBaCDCGPK1+R0NgVreT8yI0tIgDaApZUuKl6Iid QNEHuGt77o8jgxKh93PDiVsgbnfRIkpHLwrJM8aDEMI34lSTt21MH6hbvBq6nA84 HkK4oAhYhV+qK5/I3INjP6cEIuIgxYqxYpIY31zmqkF0g0BtDy20zIwLohNVdxiB 1tMBRl1c4A1G2E1oZG+0BhO10xCWvk3pR5cdOsJCB7SnwQV895V3R1R12HqKNW11 8e5e5Vef7GnAbACgZKQwZGRnpa7BiClC4j5BOUgN33G8mUK1j19/8fo7HOg+qOLk WTp+u0Dr/12WKrJc+p413ltwhbbxtpTsBKnqeRvp628pT3YY1aUP5iC4Ph7bAN/1 ziMgaKA/97A3UWgTEmLwzrhIAPsMU/zDa3FhI0cY3dDHD10iz303mZRfC97F6c8C 25VXx8/3pqpoLfYHhh9HtR8CAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAANq6OnTW xzxzcjB4UY0+XlXtgqSUy9DAmAAgfbFy+dgBtsYb45vvkKWLVrDov/spYch3S61I Ba7bNWoqTkuOVVXcZtvG8zA8oH8xrU/Fgt+MIDCEFxuWttvroVEsomWyBh903fSB y5c+gj4XvM5aYuLfljEi0R6qJNANIyyfSZkj6qR2yYm+Q7zK6SBCTlEfNdwuJfzy ef4GJLotvx2+my8/DnUN4isDCQIdndXXhk2jlkQX839J84xOdGg2LtfjJPv/yDoY ZkXcZF939jgg1Y7ppMg0BwhgqgfYCEf063O0C3elX41TL53hEIpu6/Qc9BbfkuxD OO4mH2fGNXOGFo/liU+vQ9WNYHfPur1DcaMF2cKkaiK8EU53i+INU/94infU57fE o2q6Wyzk82ozuyFsauKpXIUY5AiP2ovoMPcIE9Rfg38LpNtRLW/mFPuPK8hoQYdl BKI5TeWiX0SvzsqlrMP814uwhFe/0l7heVuiDTIh4+rzXew5v8JmsPjFWAQvaNL8 tCTTIWUmJSMLbnQeZocDgp/vQUrCgj0OUgt9ScfZfevnhsUz1KvKO6gXyJamcs0S zPTgPDpOZoBCbJdkM3J02ypSyQou2HYW+6C2CRZF+E3/Ef98RUembqiu2djP03ma qhpIGyqpydp464PMJJsCSGEwGA3SDMFhc5E= -----END CERTIFICATE----- `) )
183
session-manager-plugin
aws
Go
package awstesting import ( "io/ioutil" "net" "net/http" "os" "strings" "time" ) func availableLocalAddr(ip string) (string, error) { l, err := net.Listen("tcp", ip+":0") if err != nil { return "", err } defer l.Close() return l.Addr().String(), nil } // CreateTLSServer will create the TLS server on an open port using the // certificate and key. The address will be returned that the server is running on. func CreateTLSServer(cert, key string, mux *http.ServeMux) (string, error) { addr, err := availableLocalAddr("127.0.0.1") if err != nil { return "", err } if mux == nil { mux = http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {}) } go func() { if err := http.ListenAndServeTLS(addr, cert, key, mux); err != nil { panic(err) } }() for i := 0; i < 60; i++ { if _, err := http.Get("https://" + addr); err != nil && !strings.Contains(err.Error(), "connection refused") { break } time.Sleep(1 * time.Second) } return "https://" + addr, nil } // CreateTLSBundleFiles returns the temporary filenames for the certificate // key, and CA PEM content. These files should be deleted when no longer // needed. CleanupTLSBundleFiles can be used for this cleanup. func CreateTLSBundleFiles() (cert, key, ca string, err error) { cert, err = createTmpFile(TLSBundleCert) if err != nil { return "", "", "", err } key, err = createTmpFile(TLSBundleKey) if err != nil { return "", "", "", err } ca, err = createTmpFile(TLSBundleCA) if err != nil { return "", "", "", err } return cert, key, ca, nil } // CleanupTLSBundleFiles takes variadic list of files to be deleted. func CleanupTLSBundleFiles(files ...string) error { for _, file := range files { if err := os.Remove(file); err != nil { return err } } return nil } func createTmpFile(b []byte) (string, error) { bundleFile, err := ioutil.TempFile(os.TempDir(), "aws-sdk-go-session-test") if err != nil { return "", err } _, err = bundleFile.Write(b) if err != nil { return "", err } defer bundleFile.Close() return bundleFile.Name(), nil } /* Cert generation steps # Create the CA key openssl genrsa -des3 -out ca.key 1024 # Create the CA Cert openssl req -new -sha256 -x509 -days 3650 \ -subj "/C=GO/ST=Gopher/O=Testing ROOT CA" \ -key ca.key -out ca.crt # Create config cat > csr_details.txt <<-EOF [req] default_bits = 1024 prompt = no default_md = sha256 req_extensions = SAN distinguished_name = dn [ dn ] C=GO ST=Gopher O=Testing Certificate OU=Testing IP [SAN] subjectAltName = IP:127.0.0.1 EOF # Create certificate signing request openssl req -new -sha256 -nodes -newkey rsa:1024 \ -config <( cat csr_details.txt ) \ -keyout ia.key -out ia.csr # Create a signed certificate openssl x509 -req -days 3650 \ -CAcreateserial \ -extfile <( cat csr_details.txt ) \ -extensions SAN \ -CA ca.crt -CAkey ca.key -in ia.csr -out ia.crt # Verify openssl req -noout -text -in ia.csr openssl x509 -noout -text -in ia.crt */ var ( // TLSBundleCA ca.crt TLSBundleCA = []byte(`-----BEGIN CERTIFICATE----- MIICiTCCAfKgAwIBAgIJAJ5X1olt05XjMA0GCSqGSIb3DQEBCwUAMDgxCzAJBgNV BAYTAkdPMQ8wDQYDVQQIEwZHb3BoZXIxGDAWBgNVBAoTD1Rlc3RpbmcgUk9PVCBD QTAeFw0xNzAzMDkwMDAyMDZaFw0yNzAzMDcwMDAyMDZaMDgxCzAJBgNVBAYTAkdP MQ8wDQYDVQQIEwZHb3BoZXIxGDAWBgNVBAoTD1Rlc3RpbmcgUk9PVCBDQTCBnzAN BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw/8DN+t9XQR60jx42rsQ2WE2Dx85rb3n GQxnKZZLNddsT8rDyxJNP18aFalbRbFlyln5fxWxZIblu9Xkm/HRhOpbSimSqo1y uDx21NVZ1YsOvXpHby71jx3gPrrhSc/t/zikhi++6D/C6m1CiIGuiJ0GBiJxtrub UBMXT0QtI2ECAwEAAaOBmjCBlzAdBgNVHQ4EFgQU8XG3X/YHBA6T04kdEkq6+4GV YykwaAYDVR0jBGEwX4AU8XG3X/YHBA6T04kdEkq6+4GVYymhPKQ6MDgxCzAJBgNV BAYTAkdPMQ8wDQYDVQQIEwZHb3BoZXIxGDAWBgNVBAoTD1Rlc3RpbmcgUk9PVCBD QYIJAJ5X1olt05XjMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADgYEAeILv z49+uxmPcfOZzonuOloRcpdvyjiXblYxbzz6ch8GsE7Q886FTZbvwbgLhzdwSVgG G8WHkodDUsymVepdqAamS3f8PdCUk8xIk9mop8LgaB9Ns0/TssxDvMr3sOD2Grb3 xyWymTWMcj6uCiEBKtnUp4rPiefcvCRYZ17/hLE= -----END CERTIFICATE----- `) // TLSBundleCert ai.crt TLSBundleCert = []byte(`-----BEGIN CERTIFICATE----- MIICGjCCAYOgAwIBAgIJAIIu+NOoxxM0MA0GCSqGSIb3DQEBBQUAMDgxCzAJBgNV BAYTAkdPMQ8wDQYDVQQIEwZHb3BoZXIxGDAWBgNVBAoTD1Rlc3RpbmcgUk9PVCBD QTAeFw0xNzAzMDkwMDAzMTRaFw0yNzAzMDcwMDAzMTRaMFExCzAJBgNVBAYTAkdP MQ8wDQYDVQQIDAZHb3BoZXIxHDAaBgNVBAoME1Rlc3RpbmcgQ2VydGlmaWNhdGUx EzARBgNVBAsMClRlc3RpbmcgSVAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB AN1hWHeioo/nASvbrjwCQzXCiWiEzGkw353NxsAB54/NqDL3LXNATtiSJu8kJBrm Ah12IFLtWLGXjGjjYlHbQWnOR6awveeXnQZukJyRWh7m/Qlt9Ho0CgZE1U+832ac 5GWVldNxW1Lz4I+W9/ehzqe8I80RS6eLEKfUFXGiW+9RAgMBAAGjEzARMA8GA1Ud EQQIMAaHBH8AAAEwDQYJKoZIhvcNAQEFBQADgYEAdF4WQHfVdPCbgv9sxgJjcR1H Hgw9rZ47gO1IiIhzglnLXQ6QuemRiHeYFg4kjcYBk1DJguxzDTGnUwhUXOibAB+S zssmrkdYYvn9aUhjc3XK3tjAoDpsPpeBeTBamuUKDHoH/dNRXxerZ8vu6uPR3Pgs 5v/KCV6IAEcvNyOXMPo= -----END CERTIFICATE----- `) // TLSBundleKey ai.key TLSBundleKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDdYVh3oqKP5wEr2648AkM1wolohMxpMN+dzcbAAeePzagy9y1z QE7YkibvJCQa5gIddiBS7Vixl4xo42JR20FpzkemsL3nl50GbpCckVoe5v0JbfR6 NAoGRNVPvN9mnORllZXTcVtS8+CPlvf3oc6nvCPNEUunixCn1BVxolvvUQIDAQAB AoGBAMISrcirddGrlLZLLrKC1ULS2T0cdkqdQtwHYn4+7S5+/z42vMx1iumHLsSk rVY7X41OWkX4trFxhvEIrc/O48bo2zw78P7flTxHy14uxXnllU8cLThE29SlUU7j AVBNxJZMsXMlS/DowwD4CjFe+x4Pu9wZcReF2Z9ntzMpySABAkEA+iWoJCPE2JpS y78q3HYYgpNY3gF3JqQ0SI/zTNkb3YyEIUffEYq0Y9pK13HjKtdsSuX4osTIhQkS +UgRp6tCAQJBAOKPYTfQ2FX8ijgUpHZRuEAVaxASAS0UATiLgzXxLvOh/VC2at5x wjOX6sD65pPz/0D8Qj52Cq6Q1TQ+377SDVECQAIy0od+yPweXxvrUjUd1JlRMjbB TIrKZqs8mKbUQapw0bh5KTy+O1elU4MRPS3jNtBxtP25PQnuSnxmZcFTgAECQFzg DiiFcsn9FuRagfkHExMiNJuH5feGxeFaP9WzI144v9GAllrOI6Bm3JNzx2ZLlg4b 20Qju8lIEj6yr6JYFaECQHM1VSojGRKpOl9Ox/R4yYSA9RV5Gyn00/aJNxVYyPD5 i3acL2joQm2kLD/LO8paJ4+iQdRXCOMMIpjxSNjGQjQ= -----END RSA PRIVATE KEY----- `) )
200
session-manager-plugin
aws
Go
package awstesting // DiscardAt is an io.WriteAt that discards // the requested bytes to be written type DiscardAt struct{} // WriteAt discards the given []byte slice and returns len(p) bytes // as having been written at the given offset. It will never return an error. func (d DiscardAt) WriteAt(p []byte, off int64) (n int, err error) { return len(p), nil }
12
session-manager-plugin
aws
Go
package awstesting // EndlessReader is an io.Reader that will always return // that bytes have been read. type EndlessReader struct{} // Read will report that it has read len(p) bytes in p. // The content in the []byte will be unmodified. // This will never return an error. func (e EndlessReader) Read(p []byte) (int, error) { return len(p), nil }
13
session-manager-plugin
aws
Go
package awstesting import ( "io" "os" "strings" "time" "github.com/aws/aws-sdk-go/private/util" ) // ZeroReader is a io.Reader which will always write zeros to the byte slice provided. type ZeroReader struct{} // Read fills the provided byte slice with zeros returning the number of bytes written. func (r *ZeroReader) Read(b []byte) (int, error) { for i := 0; i < len(b); i++ { b[i] = 0 } return len(b), nil } // ReadCloser is a io.ReadCloser for unit testing. // Designed to test for leaks and whether a handle has // been closed type ReadCloser struct { Size int Closed bool set bool FillData func(bool, []byte, int, int) } // Read will call FillData and fill it with whatever data needed. // Decrements the size until zero, then return io.EOF. func (r *ReadCloser) Read(b []byte) (int, error) { if r.Closed { return 0, io.EOF } delta := len(b) if delta > r.Size { delta = r.Size } r.Size -= delta for i := 0; i < delta; i++ { b[i] = 'a' } if r.FillData != nil { r.FillData(r.set, b, r.Size, delta) } r.set = true if r.Size > 0 { return delta, nil } return delta, io.EOF } // Close sets Closed to true and returns no error func (r *ReadCloser) Close() error { r.Closed = true return nil } // SortedKeys returns a sorted slice of keys of a map. func SortedKeys(m map[string]interface{}) []string { return util.SortedKeys(m) } // A FakeContext provides a simple stub implementation of a Context type FakeContext struct { Error error DoneCh chan struct{} } // Deadline always will return not set func (c *FakeContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, false } // Done returns a read channel for listening to the Done event func (c *FakeContext) Done() <-chan struct{} { return c.DoneCh } // Err returns the error, is nil if not set. func (c *FakeContext) Err() error { return c.Error } // Value ignores the Value and always returns nil func (c *FakeContext) Value(key interface{}) interface{} { return nil } // StashEnv stashes the current environment variables and returns an array of // all environment values as key=val strings. // // Deprecated: StashEnv exists for backward compatibility and may be removed from the future iterations. // It is not `internal` so that if you really need to use its functionality, and understand breaking // changes will be made, you are able to. func StashEnv() []string { env := os.Environ() os.Clearenv() return env } // PopEnv takes the list of the environment values and injects them into the // process's environment variable data. Clears any existing environment values // that may already exist. // // Deprecated: PopEnv exists for backward compatibility and may be removed from the future iterations. // It is not `internal` so that if you really need to use its functionality, and understand breaking // changes will be made, you are able to. func PopEnv(env []string) { os.Clearenv() for _, e := range env { p := strings.SplitN(e, "=", 2) k, v := p[0], "" if len(p) > 1 { v = p[1] } os.Setenv(k, v) } }
129
session-manager-plugin
aws
Go
package awstesting_test import ( "io" "testing" "github.com/aws/aws-sdk-go/awstesting" ) func TestReadCloserClose(t *testing.T) { rc := awstesting.ReadCloser{Size: 1} err := rc.Close() if err != nil { t.Errorf("expect nil, got %v", err) } if !rc.Closed { t.Errorf("expect closed, was not") } if e, a := rc.Size, 1; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestReadCloserRead(t *testing.T) { rc := awstesting.ReadCloser{Size: 5} b := make([]byte, 2) n, err := rc.Read(b) if err != nil { t.Errorf("expect nil, got %v", err) } if e, a := n, 2; e != a { t.Errorf("expect %v, got %v", e, a) } if rc.Closed { t.Errorf("expect not to be closed") } if e, a := rc.Size, 3; e != a { t.Errorf("expect %v, got %v", e, a) } err = rc.Close() if err != nil { t.Errorf("expect nil, got %v", err) } n, err = rc.Read(b) if e, a := err, io.EOF; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := n, 0; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestReadCloserReadAll(t *testing.T) { rc := awstesting.ReadCloser{Size: 5} b := make([]byte, 5) n, err := rc.Read(b) if e, a := err, io.EOF; e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := n, 5; e != a { t.Errorf("expect %v, got %v", e, a) } if rc.Closed { t.Errorf("expect not to be closed") } if e, a := rc.Size, 0; e != a { t.Errorf("expect %v, got %v", e, a) } }
76
session-manager-plugin
aws
Go
// +build integration package main import ( "fmt" "os" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) // Searches the buckets of an account that match the prefix, and deletes // those buckets, and all objects within. Before deleting will prompt user // to confirm bucket should be deleted. Positive confirmation is required. // // Usage: // go run deleteBuckets.go <bucketPrefix> func main() { sess := session.Must(session.NewSession()) svc := s3.New(sess) buckets, err := svc.ListBuckets(&s3.ListBucketsInput{}) if err != nil { panic(fmt.Sprintf("failed to list buckets, %v", err)) } if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "bucket prefix required") os.Exit(1) } bucketPrefix := os.Args[1] var failed bool for _, b := range buckets.Buckets { bucket := aws.StringValue(b.Name) if !strings.HasPrefix(bucket, bucketPrefix) { continue } fmt.Printf("Delete bucket %q? [y/N]: ", bucket) var v string if _, err := fmt.Scanln(&v); err != nil || !(v == "Y" || v == "y") { fmt.Println("\tSkipping") continue } fmt.Println("\tDeleting") if err := deleteBucket(svc, bucket); err != nil { fmt.Fprintf(os.Stderr, "failed to delete bucket %q, %v", bucket, err) failed = true } } if failed { os.Exit(1) } } func deleteBucket(svc *s3.S3, bucket string) error { bucketName := &bucket objs, err := svc.ListObjects(&s3.ListObjectsInput{Bucket: bucketName}) if err != nil { return fmt.Errorf("failed to list bucket %q objects, %v", *bucketName, err) } for _, o := range objs.Contents { svc.DeleteObject(&s3.DeleteObjectInput{Bucket: bucketName, Key: o.Key}) } uploads, err := svc.ListMultipartUploads(&s3.ListMultipartUploadsInput{Bucket: bucketName}) if err != nil { return fmt.Errorf("failed to list bucket %q multipart objects, %v", *bucketName, err) } for _, u := range uploads.Uploads { svc.AbortMultipartUpload(&s3.AbortMultipartUploadInput{ Bucket: bucketName, Key: u.Key, UploadId: u.UploadId, }) } _, err = svc.DeleteBucket(&s3.DeleteBucketInput{Bucket: bucketName}) if err != nil { return fmt.Errorf("failed to delete bucket %q, %v", *bucketName, err) } return nil }
95
session-manager-plugin
aws
Go
// +build integration // Package integration performs initialization and validation for integration // tests. package integration import ( "crypto/rand" "fmt" "io" "io/ioutil" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" ) // Session is a shared session for all integration tests to use. var Session = session.Must(session.NewSession(&aws.Config{ CredentialsChainVerboseErrors: aws.Bool(true), })) func init() { logLevel := Session.Config.LogLevel if os.Getenv("DEBUG") != "" { logLevel = aws.LogLevel(aws.LogDebug) } if os.Getenv("DEBUG_SIGNING") != "" { logLevel = aws.LogLevel(aws.LogDebugWithSigning) } if os.Getenv("DEBUG_BODY") != "" { logLevel = aws.LogLevel(aws.LogDebugWithSigning | aws.LogDebugWithHTTPBody) } Session.Config.LogLevel = logLevel } // UniqueID returns a unique UUID-like identifier for use in generating // resources for integration tests. func UniqueID() string { uuid := make([]byte, 16) io.ReadFull(rand.Reader, uuid) return fmt.Sprintf("%x", uuid) } // CreateFileOfSize will return an *os.File that is of size bytes func CreateFileOfSize(dir string, size int64) (*os.File, error) { file, err := ioutil.TempFile(dir, "s3Bench") if err != nil { return nil, err } err = file.Truncate(size) if err != nil { file.Close() os.Remove(file.Name()) return nil, err } return file, nil } // SizeToName returns a human-readable string for the given size bytes func SizeToName(size int) string { units := []string{"B", "KB", "MB", "GB"} i := 0 for size >= 1024 { size /= 1024 i++ } if i > len(units)-1 { i = len(units) - 1 } return fmt.Sprintf("%d%s", size, units[i]) } // SessionWithDefaultRegion returns a copy of the integration session with the // region set if one was not already provided. func SessionWithDefaultRegion(region string) *session.Session { sess := Session.Copy() if v := aws.StringValue(sess.Config.Region); len(v) == 0 { sess.Config.Region = aws.String(region) } return sess }
88
session-manager-plugin
aws
Go
// +build go1.13,integration,perftest package main import ( "net" "net/http" "time" ) func NewClient(cfg ClientConfig) *http.Client { tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: cfg.Timeouts.Connect, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: cfg.MaxIdleConns, MaxIdleConnsPerHost: cfg.MaxIdleConnsPerHost, IdleConnTimeout: 90 * time.Second, DisableKeepAlives: !cfg.KeepAlive, TLSHandshakeTimeout: cfg.Timeouts.TLSHandshake, ExpectContinueTimeout: cfg.Timeouts.ExpectContinue, ResponseHeaderTimeout: cfg.Timeouts.ResponseHeader, ReadBufferSize: cfg.ReadBufferSize, WriteBufferSize: cfg.WriteBufferSize, } return &http.Client{ Transport: tr, } }
36
session-manager-plugin
aws
Go
// +build go1.13,integration,perftest package main import ( "flag" "fmt" "net/http" "strings" "time" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) type Config struct { Bucket string Size int64 Key string LogVerbose bool UploadPartSize int64 SDK SDKConfig Client ClientConfig Profiler Profiler } func (c *Config) SetupFlags(prefix string, flagset *flag.FlagSet) { flagset.StringVar(&c.Bucket, "bucket", "", "The S3 bucket `name` to download the object from.") flagset.Int64Var(&c.Size, "size", 0, "The S3 object size in bytes to be first uploaded then downloaded") flagset.StringVar(&c.Key, "key", "", "The S3 object key to download") flagset.BoolVar(&c.LogVerbose, "verbose", false, "The output log will include verbose request information") flagset.Int64Var(&c.UploadPartSize, "upload-part-size", 0, "the upload part size when uploading a file to s3") c.SDK.SetupFlags(prefix, flagset) c.Client.SetupFlags(prefix, flagset) c.Profiler.SetupFlags(prefix, flagset) } func (c *Config) Validate() error { var errs Errors if len(c.Bucket) == 0 || (c.Size <= 0 && len(c.Key) == 0) { errs = append(errs, fmt.Errorf("bucket and filename/size are required")) } if err := c.SDK.Validate(); err != nil { errs = append(errs, err) } if err := c.Client.Validate(); err != nil { errs = append(errs, err) } if len(errs) != 0 { return errs } return nil } type SDKConfig struct { PartSize int64 Concurrency int BufferProvider s3manager.WriterReadFromProvider } func (c *SDKConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "sdk." flagset.Int64Var(&c.PartSize, prefix+"part-size", s3manager.DefaultDownloadPartSize, "Specifies the `size` of parts of the object to download.") flagset.IntVar(&c.Concurrency, prefix+"concurrency", s3manager.DefaultDownloadConcurrency, "Specifies the number of parts to download `at once`.") } func (c *SDKConfig) Validate() error { return nil } type ClientConfig struct { KeepAlive bool Timeouts Timeouts MaxIdleConns int MaxIdleConnsPerHost int // Go 1.13 ReadBufferSize int WriteBufferSize int } func (c *ClientConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "client." flagset.BoolVar(&c.KeepAlive, prefix+"http-keep-alive", true, "Specifies if HTTP keep alive is enabled.") defTR := http.DefaultTransport.(*http.Transport) flagset.IntVar(&c.MaxIdleConns, prefix+"idle-conns", defTR.MaxIdleConns, "Specifies max idle connection pool size.") flagset.IntVar(&c.MaxIdleConnsPerHost, prefix+"idle-conns-host", http.DefaultMaxIdleConnsPerHost, "Specifies max idle connection pool per host, will be truncated by idle-conns.") flagset.IntVar(&c.ReadBufferSize, prefix+"read-buffer", defTR.ReadBufferSize, "size of the transport read buffer used") flagset.IntVar(&c.WriteBufferSize, prefix+"writer-buffer", defTR.WriteBufferSize, "size of the transport write buffer used") c.Timeouts.SetupFlags(prefix, flagset) } func (c *ClientConfig) Validate() error { var errs Errors if err := c.Timeouts.Validate(); err != nil { errs = append(errs, err) } if len(errs) != 0 { return errs } return nil } type Timeouts struct { Connect time.Duration TLSHandshake time.Duration ExpectContinue time.Duration ResponseHeader time.Duration } func (c *Timeouts) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "timeout." flagset.DurationVar(&c.Connect, prefix+"connect", 30*time.Second, "The `timeout` connecting to the remote host.") defTR := http.DefaultTransport.(*http.Transport) flagset.DurationVar(&c.TLSHandshake, prefix+"tls", defTR.TLSHandshakeTimeout, "The `timeout` waiting for the TLS handshake to complete.") flagset.DurationVar(&c.ExpectContinue, prefix+"expect-continue", defTR.ExpectContinueTimeout, "The `timeout` waiting for the TLS handshake to complete.") flagset.DurationVar(&c.ResponseHeader, prefix+"response-header", defTR.ResponseHeaderTimeout, "The `timeout` waiting for the TLS handshake to complete.") } func (c *Timeouts) Validate() error { return nil } type Errors []error func (es Errors) Error() string { var buf strings.Builder for _, e := range es { buf.WriteString(e.Error()) } return buf.String() }
166
session-manager-plugin
aws
Go
// +build go1.13,integration,perftest package main import ( "flag" "fmt" "io" "log" "os" "path/filepath" "runtime" "runtime/pprof" "runtime/trace" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/awstesting" "github.com/aws/aws-sdk-go/awstesting/integration" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) var config Config func main() { parseCommandLine() log.SetOutput(os.Stderr) config.Profiler.Start() defer config.Profiler.Stop() var err error key := config.Key size := config.Size if len(key) == 0 { uploadPartSize := getUploadPartSize(size, config.UploadPartSize, config.SDK.PartSize) log.Printf("uploading %s file to s3://%s\n", integration.SizeToName(int(config.Size)), config.Bucket) key, err = setupDownloadTest(config.Bucket, config.Size, uploadPartSize) if err != nil { log.Fatalf("failed to setup download testing: %v", err) } defer func() { log.Printf("cleaning up s3://%s/%s\n", config.Bucket, key) if err = teardownDownloadTest(config.Bucket, key); err != nil { log.Fatalf("failed to teardwn test artifacts: %v", err) } }() } else { size, err = getObjectSize(config.Bucket, key) if err != nil { log.Fatalf("failed to get object size: %v", err) } } traces := make(chan *RequestTrace, config.SDK.Concurrency) requestTracer := downloadRequestTracer(traces) downloader := newDownloader(config.Client, config.SDK, requestTracer) metricReportDone := startTraceReceiver(traces) log.Println("starting download...") start := time.Now() _, err = downloader.Download(&awstesting.DiscardAt{}, &s3.GetObjectInput{ Bucket: &config.Bucket, Key: &key, }) if err != nil { log.Fatalf("failed to download object, %v", err) } close(traces) dur := time.Since(start) log.Printf("Download finished, Size: %d, Dur: %s, Throughput: %.5f GB/s", size, dur, (float64(size)/(float64(dur)/float64(time.Second)))/float64(1e9), ) <-metricReportDone } func parseCommandLine() { config.SetupFlags("", flag.CommandLine) if err := flag.CommandLine.Parse(os.Args[1:]); err != nil { flag.CommandLine.PrintDefaults() log.Fatalf("failed to parse CLI commands") } if err := config.Validate(); err != nil { flag.CommandLine.PrintDefaults() log.Fatalf("invalid arguments: %v", err) } } func setupDownloadTest(bucket string, fileSize, partSize int64) (key string, err error) { er := &awstesting.EndlessReader{} lr := io.LimitReader(er, fileSize) key = integration.UniqueID() sess := session.Must(session.NewSession(&aws.Config{ S3DisableContentMD5Validation: aws.Bool(true), S3Disable100Continue: aws.Bool(true), })) uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = partSize u.Concurrency = runtime.NumCPU() * 2 u.RequestOptions = append(u.RequestOptions, func(r *request.Request) { if r.Operation.Name != "UploadPart" && r.Operation.Name != "PutObject" { return } r.HTTPRequest.Header.Set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD") }) }) _, err = uploader.Upload(&s3manager.UploadInput{ Bucket: &bucket, Body: lr, Key: &key, }) if err != nil { err = fmt.Errorf("failed to upload test object to s3: %v", err) } return } func teardownDownloadTest(bucket, key string) error { sess := session.Must(session.NewSession()) svc := s3.New(sess) _, err := svc.DeleteObject(&s3.DeleteObjectInput{Bucket: &bucket, Key: &key}) return err } func startTraceReceiver(traces <-chan *RequestTrace) <-chan struct{} { metricReportDone := make(chan struct{}) go func() { defer close(metricReportDone) metrics := map[string]*RequestTrace{} for trace := range traces { curTrace, ok := metrics[trace.Operation] if !ok { curTrace = trace } else { curTrace.attempts = append(curTrace.attempts, trace.attempts...) if len(trace.errs) != 0 { curTrace.errs = append(curTrace.errs, trace.errs...) } curTrace.finish = trace.finish } metrics[trace.Operation] = curTrace } for _, name := range []string{ "GetObject", } { if trace, ok := metrics[name]; ok { printAttempts(name, trace, config.LogVerbose) } } }() return metricReportDone } func printAttempts(op string, trace *RequestTrace, verbose bool) { if !verbose { return } log.Printf("%s: latency:%s requests:%d errors:%d", op, trace.finish.Sub(trace.start), len(trace.attempts), len(trace.errs), ) for _, a := range trace.attempts { log.Printf(" * %s", a) } if err := trace.Err(); err != nil { log.Printf("Operation Errors: %v", err) } log.Println() } func downloadRequestTracer(traces chan<- *RequestTrace) request.Option { tracerOption := func(r *request.Request) { id := "op" if v, ok := r.Params.(*s3.GetObjectInput); ok { if v.Range != nil { id = *v.Range } } tracer := NewRequestTrace(r.Context(), r.Operation.Name, id) r.SetContext(tracer) r.Handlers.Send.PushFront(tracer.OnSendAttempt) r.Handlers.CompleteAttempt.PushBack(tracer.OnCompleteAttempt) r.Handlers.Complete.PushBack(tracer.OnComplete) r.Handlers.Complete.PushBack(func(rr *request.Request) { traces <- tracer }) } return tracerOption } func newDownloader(clientConfig ClientConfig, sdkConfig SDKConfig, options ...request.Option) *s3manager.Downloader { client := NewClient(clientConfig) sess, err := session.NewSessionWithOptions(session.Options{ Config: aws.Config{HTTPClient: client}, SharedConfigState: session.SharedConfigEnable, }) if err != nil { log.Fatalf("failed to load session, %v", err) } downloader := s3manager.NewDownloader(sess, func(d *s3manager.Downloader) { d.PartSize = sdkConfig.PartSize d.Concurrency = sdkConfig.Concurrency d.BufferProvider = sdkConfig.BufferProvider d.RequestOptions = append(d.RequestOptions, options...) }) return downloader } func getObjectSize(bucket, key string) (int64, error) { sess := session.Must(session.NewSession()) svc := s3.New(sess) resp, err := svc.HeadObject(&s3.HeadObjectInput{ Bucket: &bucket, Key: &key, }) if err != nil { return 0, err } return *resp.ContentLength, nil } type Profiler struct { outputDir string enableCPU bool enableTrace bool cpuFile *os.File traceFile *os.File } func (p *Profiler) SetupFlags(prefix string, flagSet *flag.FlagSet) { prefix += "profiler." flagSet.StringVar(&p.outputDir, prefix+"output-dir", os.TempDir(), "output directory to write profiling data") flagSet.BoolVar(&p.enableCPU, prefix+"cpu", false, "enable CPU profiling") flagSet.BoolVar(&p.enableTrace, prefix+"trace", false, "enable tracing") } func (p *Profiler) Start() { var err error uuid := integration.UniqueID() if p.enableCPU { p.cpuFile, err = p.createFile(uuid, "cpu") if err != nil { panic(fmt.Sprintf("failed to create cpu profile file: %v", err)) } err = pprof.StartCPUProfile(p.cpuFile) if err != nil { panic(fmt.Sprintf("failed to start cpu profile: %v", err)) } } if p.enableTrace { p.traceFile, err = p.createFile(uuid, "trace") if err != nil { panic(fmt.Sprintf("failed to create trace file: %v", err)) } err = trace.Start(p.traceFile) if err != nil { panic(fmt.Sprintf("failed to tracing: %v", err)) } } } func (p *Profiler) logAndCloseFile(profile string, file *os.File) { info, err := file.Stat() if err != nil { log.Printf("failed to stat %s profile: %v", profile, err) } else { log.Printf("writing %s profile to: %v", profile, filepath.Join(p.outputDir, info.Name())) } file.Close() } func (p *Profiler) Stop() { if p.enableCPU { pprof.StopCPUProfile() p.logAndCloseFile("cpu", p.cpuFile) } if p.enableTrace { trace.Stop() p.logAndCloseFile("trace", p.traceFile) } } func (p *Profiler) createFile(prefix, name string) (*os.File, error) { return os.OpenFile(filepath.Join(p.outputDir, prefix+"."+name+".profile"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) } func getUploadPartSize(fileSize, uploadPartSize, downloadPartSize int64) int64 { partSize := uploadPartSize if partSize == 0 { partSize = downloadPartSize } if fileSize/partSize > s3manager.MaxUploadParts { partSize = (fileSize / s3manager.MaxUploadParts) + 1 } return partSize }
335
session-manager-plugin
aws
Go
// +build go1.13,integration,perftest package main import ( "flag" "fmt" "io" "os" "strconv" "strings" "testing" "github.com/aws/aws-sdk-go/awstesting" "github.com/aws/aws-sdk-go/awstesting/integration" "github.com/aws/aws-sdk-go/internal/sdkio" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) var benchConfig BenchmarkConfig type BenchmarkConfig struct { bucket string tempdir string clientConfig ClientConfig sizes string parts string concurrency string bufferSize string uploadPartSize int64 } func (b *BenchmarkConfig) SetupFlags(prefix string, flagSet *flag.FlagSet) { flagSet.StringVar(&b.bucket, "bucket", "", "Bucket to use for benchmark") flagSet.StringVar(&b.tempdir, "temp", os.TempDir(), "location to create temporary files") flagSet.StringVar(&b.sizes, "size", fmt.Sprintf("%d,%d", 5*sdkio.MebiByte, 1*sdkio.GibiByte), "file sizes to benchmark separated by comma") flagSet.StringVar(&b.parts, "part", fmt.Sprintf("%d,%d,%d", s3manager.DefaultDownloadPartSize, 25*sdkio.MebiByte, 100*sdkio.MebiByte), "part sizes to benchmark separated by comma") flagSet.StringVar(&b.concurrency, "concurrency", fmt.Sprintf("%d,%d,%d", s3manager.DefaultDownloadConcurrency, 2*s3manager.DefaultDownloadConcurrency, 100), "part sizes to benchmark separated comma") flagSet.StringVar(&b.bufferSize, "buffer", fmt.Sprintf("%d,%d", 0, 1*sdkio.MebiByte), "part sizes to benchmark separated comma") flagSet.Int64Var(&b.uploadPartSize, "upload-part-size", 0, "upload part size, defaults to download part size if not specified") b.clientConfig.SetupFlags(prefix, flagSet) } func (b *BenchmarkConfig) BufferSizes() []int { ints, err := b.stringToInt(b.bufferSize) if err != nil { panic(fmt.Sprintf("failed to parse file sizes: %v", err)) } return ints } func (b *BenchmarkConfig) FileSizes() []int64 { ints, err := b.stringToInt64(b.sizes) if err != nil { panic(fmt.Sprintf("failed to parse file sizes: %v", err)) } return ints } func (b *BenchmarkConfig) PartSizes() []int64 { ints, err := b.stringToInt64(b.parts) if err != nil { panic(fmt.Sprintf("failed to parse part sizes: %v", err)) } return ints } func (b *BenchmarkConfig) Concurrences() []int { ints, err := b.stringToInt(b.concurrency) if err != nil { panic(fmt.Sprintf("failed to parse part sizes: %v", err)) } return ints } func (b *BenchmarkConfig) stringToInt(s string) ([]int, error) { int64s, err := b.stringToInt64(s) if err != nil { return nil, err } var ints []int for i := range int64s { ints = append(ints, int(int64s[i])) } return ints, nil } func (b *BenchmarkConfig) stringToInt64(s string) ([]int64, error) { var sizes []int64 split := strings.Split(s, ",") for _, size := range split { size = strings.Trim(size, " ") i, err := strconv.ParseInt(size, 10, 64) if err != nil { return nil, fmt.Errorf("invalid integer %s: %v", size, err) } sizes = append(sizes, i) } return sizes, nil } func BenchmarkDownload(b *testing.B) { baseSdkConfig := SDKConfig{} for _, fileSize := range benchConfig.FileSizes() { b.Run(fmt.Sprintf("%s File", integration.SizeToName(int(fileSize))), func(b *testing.B) { for _, partSize := range benchConfig.PartSizes() { if partSize > fileSize { continue } uploadPartSize := getUploadPartSize(fileSize, benchConfig.uploadPartSize, partSize) b.Run(fmt.Sprintf("%s PartSize", integration.SizeToName(int(partSize))), func(b *testing.B) { b.Logf("setting up s3 file size") key, err := setupDownloadTest(benchConfig.bucket, fileSize, uploadPartSize) if err != nil { b.Fatalf("failed to setup download test: %v", err) } for _, concurrency := range benchConfig.Concurrences() { b.Run(fmt.Sprintf("%d Concurrency", concurrency), func(b *testing.B) { for _, bufferSize := range benchConfig.BufferSizes() { var name string if bufferSize == 0 { name = "unbuffered" } else { name = fmt.Sprintf("%s buffer", integration.SizeToName(bufferSize)) } b.Run(name, func(b *testing.B) { sdkConfig := baseSdkConfig sdkConfig.Concurrency = concurrency sdkConfig.PartSize = partSize if bufferSize > 0 { sdkConfig.BufferProvider = s3manager.NewPooledBufferedWriterReadFromProvider(bufferSize) } b.ResetTimer() for i := 0; i < b.N; i++ { benchDownload(b, benchConfig.bucket, key, &awstesting.DiscardAt{}, sdkConfig, benchConfig.clientConfig) } }) } }) } b.Log("removing test file") err = teardownDownloadTest(benchConfig.bucket, key) if err != nil { b.Fatalf("failed to cleanup test file: %v", err) } }) } }) } } func benchDownload(b *testing.B, bucket, key string, body io.WriterAt, sdkConfig SDKConfig, clientConfig ClientConfig) { downloader := newDownloader(clientConfig, sdkConfig) _, err := downloader.Download(body, &s3.GetObjectInput{ Bucket: &bucket, Key: &key, }) if err != nil { b.Fatalf("failed to download object, %v", err) } } func TestMain(m *testing.M) { benchConfig.SetupFlags("", flag.CommandLine) flag.Parse() os.Exit(m.Run()) }
197
session-manager-plugin
aws
Go
// +build go1.13,integration,perftest package main import ( "context" "crypto/tls" "fmt" "net/http/httptrace" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws/request" ) type RequestTrace struct { Operation string ID string context.Context start, finish time.Time errs Errors attempts []RequestAttempt curAttempt RequestAttempt } func NewRequestTrace(ctx context.Context, op, id string) *RequestTrace { rt := &RequestTrace{ Operation: op, ID: id, start: time.Now(), attempts: []RequestAttempt{}, curAttempt: RequestAttempt{ ID: id, }, } trace := &httptrace.ClientTrace{ GetConn: rt.getConn, GotConn: rt.gotConn, PutIdleConn: rt.putIdleConn, GotFirstResponseByte: rt.gotFirstResponseByte, Got100Continue: rt.got100Continue, DNSStart: rt.dnsStart, DNSDone: rt.dnsDone, ConnectStart: rt.connectStart, ConnectDone: rt.connectDone, TLSHandshakeStart: rt.tlsHandshakeStart, TLSHandshakeDone: rt.tlsHandshakeDone, WroteHeaders: rt.wroteHeaders, Wait100Continue: rt.wait100Continue, WroteRequest: rt.wroteRequest, } rt.Context = httptrace.WithClientTrace(ctx, trace) return rt } func (rt *RequestTrace) AppendError(err error) { rt.errs = append(rt.errs, err) } func (rt *RequestTrace) OnSendAttempt(r *request.Request) { rt.curAttempt.SendStart = time.Now() } func (rt *RequestTrace) OnCompleteAttempt(r *request.Request) { rt.curAttempt.Start = r.AttemptTime rt.curAttempt.Finish = time.Now() rt.curAttempt.Err = r.Error if r.Error != nil { rt.AppendError(r.Error) } rt.attempts = append(rt.attempts, rt.curAttempt) rt.curAttempt = RequestAttempt{ ID: rt.curAttempt.ID, AttemptNum: rt.curAttempt.AttemptNum + 1, } } func (rt *RequestTrace) OnComplete(r *request.Request) { rt.finish = time.Now() // Last attempt includes reading the response body if len(rt.attempts) > 0 { rt.attempts[len(rt.attempts)-1].Finish = rt.finish } } func (rt *RequestTrace) Err() error { if len(rt.errs) != 0 { return rt.errs } return nil } func (rt *RequestTrace) TotalLatency() time.Duration { return rt.finish.Sub(rt.start) } func (rt *RequestTrace) Attempts() []RequestAttempt { return rt.attempts } func (rt *RequestTrace) Retries() int { return len(rt.attempts) - 1 } func (rt *RequestTrace) getConn(hostPort string) {} func (rt *RequestTrace) gotConn(info httptrace.GotConnInfo) { rt.curAttempt.Reused = info.Reused } func (rt *RequestTrace) putIdleConn(err error) {} func (rt *RequestTrace) gotFirstResponseByte() { rt.curAttempt.FirstResponseByte = time.Now() } func (rt *RequestTrace) got100Continue() {} func (rt *RequestTrace) dnsStart(info httptrace.DNSStartInfo) { rt.curAttempt.DNSStart = time.Now() } func (rt *RequestTrace) dnsDone(info httptrace.DNSDoneInfo) { rt.curAttempt.DNSDone = time.Now() } func (rt *RequestTrace) connectStart(network, addr string) { rt.curAttempt.ConnectStart = time.Now() } func (rt *RequestTrace) connectDone(network, addr string, err error) { rt.curAttempt.ConnectDone = time.Now() } func (rt *RequestTrace) tlsHandshakeStart() { rt.curAttempt.TLSHandshakeStart = time.Now() } func (rt *RequestTrace) tlsHandshakeDone(state tls.ConnectionState, err error) { rt.curAttempt.TLSHandshakeDone = time.Now() } func (rt *RequestTrace) wroteHeaders() { rt.curAttempt.WroteHeaders = time.Now() } func (rt *RequestTrace) wait100Continue() { rt.curAttempt.Read100Continue = time.Now() } func (rt *RequestTrace) wroteRequest(info httptrace.WroteRequestInfo) { rt.curAttempt.RequestWritten = time.Now() } type RequestAttempt struct { Start, Finish time.Time SendStart time.Time Err error Reused bool ID string AttemptNum int DNSStart, DNSDone time.Time ConnectStart, ConnectDone time.Time TLSHandshakeStart, TLSHandshakeDone time.Time WroteHeaders time.Time RequestWritten time.Time Read100Continue time.Time FirstResponseByte time.Time } func (a RequestAttempt) String() string { const sep = ", " var w strings.Builder w.WriteString(a.ID + "-" + strconv.Itoa(a.AttemptNum) + sep) w.WriteString("Latency:" + durToMSString(a.Finish.Sub(a.Start)) + sep) w.WriteString("SDKPreSend:" + durToMSString(a.SendStart.Sub(a.Start)) + sep) writeStart := a.SendStart fmt.Fprintf(&w, "ConnReused:%t"+sep, a.Reused) if !a.Reused { w.WriteString("DNS:" + durToMSString(a.DNSDone.Sub(a.DNSStart)) + sep) w.WriteString("Connect:" + durToMSString(a.ConnectDone.Sub(a.ConnectStart)) + sep) w.WriteString("TLS:" + durToMSString(a.TLSHandshakeDone.Sub(a.TLSHandshakeStart)) + sep) writeStart = a.TLSHandshakeDone } writeHeader := a.WroteHeaders.Sub(writeStart) w.WriteString("WriteHeader:" + durToMSString(writeHeader) + sep) if !a.Read100Continue.IsZero() { // With 100-continue w.WriteString("Read100Cont:" + durToMSString(a.Read100Continue.Sub(a.WroteHeaders)) + sep) w.WriteString("WritePayload:" + durToMSString(a.FirstResponseByte.Sub(a.RequestWritten)) + sep) w.WriteString("RespRead:" + durToMSString(a.Finish.Sub(a.RequestWritten)) + sep) } else { // No 100-continue w.WriteString("WritePayload:" + durToMSString(a.RequestWritten.Sub(a.WroteHeaders)) + sep) if !a.FirstResponseByte.IsZero() { w.WriteString("RespFirstByte:" + durToMSString(a.FirstResponseByte.Sub(a.RequestWritten)) + sep) w.WriteString("RespRead:" + durToMSString(a.Finish.Sub(a.FirstResponseByte)) + sep) } } return w.String() } func durToMSString(v time.Duration) string { ms := float64(v) / float64(time.Millisecond) return fmt.Sprintf("%0.6f", ms) }
205
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "net" "net/http" "time" ) func NewClient(cfg ClientConfig) *http.Client { tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: cfg.Timeouts.Connect, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, DisableKeepAlives: !cfg.KeepAlive, TLSHandshakeTimeout: cfg.Timeouts.TLSHandshake, ExpectContinueTimeout: cfg.Timeouts.ExpectContinue, ResponseHeaderTimeout: cfg.Timeouts.ResponseHeader, } return &http.Client{ Transport: tr, } }
32
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "flag" "fmt" "net/http" "strings" "time" ) type Config struct { RequestDuration time.Duration RequestCount int64 RequestDelay time.Duration Endpoint string Bucket, Key string SDK SDKConfig Client ClientConfig } func (c *Config) SetupFlags(prefix string, flagset *flag.FlagSet) { flagset.DurationVar(&c.RequestDuration, "duration", 0, "The duration to make requests for. Use instead of count for specific running duration.") flagset.Int64Var(&c.RequestCount, "count", 0, "The total `number` of requests to make. Use instead of duration for specific count.") flagset.DurationVar(&c.RequestDelay, "delay", 0, "The detail between sequential requests.") flagset.StringVar(&c.Endpoint, prefix+"endpoint", "", "Optional overridden endpoint S3 client will connect to.") flagset.StringVar(&c.Bucket, "bucket", "", "The S3 bucket `name` to request the object from.") flagset.StringVar(&c.Key, "key", "", "The S3 object key `name` to request the object from.") c.SDK.SetupFlags(prefix, flagset) c.Client.SetupFlags(prefix, flagset) } func (c *Config) Validate() error { var errs Errors if c.RequestDuration != 0 && c.RequestCount != 0 { errs = append(errs, fmt.Errorf("duration and count canot be used together")) } if c.RequestDuration == 0 && c.RequestCount == 0 { errs = append(errs, fmt.Errorf("duration or count must be provided")) } if len(c.Bucket) == 0 || len(c.Key) == 0 { errs = append(errs, fmt.Errorf("bucket and key are required")) } if err := c.SDK.Validate(); err != nil { errs = append(errs, err) } if err := c.Client.Validate(); err != nil { errs = append(errs, err) } if len(errs) != 0 { return errs } return nil } type SDKConfig struct { Anonymous bool ExpectContinue bool } func (c *SDKConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "sdk." flagset.BoolVar(&c.Anonymous, prefix+"anonymous", false, "Specifies if the SDK will make requests anonymously, and unsigned.") c.ExpectContinue = true // flagset.BoolVar(&c.ExpectContinue, prefix+"100-continue", true, // "Specifies if the SDK requests will wait for the 100 continue response before sending request payload.") } func (c *SDKConfig) Validate() error { return nil } type ClientConfig struct { KeepAlive bool Timeouts Timeouts } func (c *ClientConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "client." flagset.BoolVar(&c.KeepAlive, prefix+"http-keep-alive", true, "Specifies if HTTP keep alive is enabled.") c.Timeouts.SetupFlags(prefix, flagset) } func (c *ClientConfig) Validate() error { var errs Errors if err := c.Timeouts.Validate(); err != nil { errs = append(errs, err) } if len(errs) != 0 { return errs } return nil } type Timeouts struct { Connect time.Duration TLSHandshake time.Duration ExpectContinue time.Duration ResponseHeader time.Duration } func (c *Timeouts) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "timeout." flagset.DurationVar(&c.Connect, prefix+"connect", 30*time.Second, "The `timeout` connecting to the remote host.") defTR := http.DefaultTransport.(*http.Transport) flagset.DurationVar(&c.TLSHandshake, prefix+"tls", defTR.TLSHandshakeTimeout, "The `timeout` waiting for the TLS handshake to complete.") c.ExpectContinue = defTR.ExpectContinueTimeout // flagset.DurationVar(&c.ExpectContinue, prefix+"expect-continue", defTR.ExpectContinueTimeout, // "The `timeout` waiting for the TLS handshake to complete.") flagset.DurationVar(&c.ResponseHeader, prefix+"response-header", defTR.ResponseHeaderTimeout, "The `timeout` waiting for the TLS handshake to complete.") } func (c *Timeouts) Validate() error { return nil } type Errors []error func (es Errors) Error() string { var buf strings.Builder for _, e := range es { buf.WriteString(e.Error()) } return buf.String() }
157
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "encoding/csv" "fmt" "io" "os" "strconv" "strings" "time" ) type Logger struct { out *csv.Writer } func NewLogger(writer io.Writer) *Logger { l := &Logger{ out: csv.NewWriter(writer), } err := l.out.Write([]string{ "ID", "Attempt", "Latency", "DNSStart", "DNSDone", "DNSDur", "ConnectStart", "ConnectDone", "ConnectDur", "TLSStart", "TLSDone", "TLSDur", "WriteReq", "RespFirstByte", "WaitRespFirstByte", "Error", }) if err != nil { fmt.Fprintf(os.Stderr, "failed to write header trace, %v\n", err) } return l } func (l *Logger) RecordTrace(trace *RequestTrace) { req := RequestReport{ ID: trace.ID, TotalLatency: durToMSString(trace.TotalLatency()), Retries: trace.Retries(), } for i, a := range trace.Attempts() { attempt := AttemptReport{ Reused: a.Reused, SDKMarshal: durToMSString(a.SendStart.Sub(a.Start)), ReqWritten: durToMSString(a.RequestWritten.Sub(a.SendStart)), Latency: durToMSString(a.Finish.Sub(a.Start)), Err: a.Err, } if !a.FirstResponseByte.IsZero() { attempt.RespFirstByte = durToMSString(a.FirstResponseByte.Sub(a.SendStart)) attempt.WaitRespFirstByte = durToMSString(a.FirstResponseByte.Sub(a.RequestWritten)) } if !a.Reused { attempt.DNSStart = durToMSString(a.DNSStart.Sub(a.SendStart)) attempt.DNSDone = durToMSString(a.DNSDone.Sub(a.SendStart)) attempt.DNS = durToMSString(a.DNSDone.Sub(a.DNSStart)) attempt.ConnectStart = durToMSString(a.ConnectStart.Sub(a.SendStart)) attempt.ConnectDone = durToMSString(a.ConnectDone.Sub(a.SendStart)) attempt.Connect = durToMSString(a.ConnectDone.Sub(a.ConnectStart)) attempt.TLSHandshakeStart = durToMSString(a.TLSHandshakeStart.Sub(a.SendStart)) attempt.TLSHandshakeDone = durToMSString(a.TLSHandshakeDone.Sub(a.SendStart)) attempt.TLSHandshake = durToMSString(a.TLSHandshakeDone.Sub(a.TLSHandshakeStart)) } req.Attempts = append(req.Attempts, attempt) var reqErr string if attempt.Err != nil { reqErr = strings.Replace(attempt.Err.Error(), "\n", `\n`, -1) } err := l.out.Write([]string{ strconv.Itoa(int(req.ID)), strconv.Itoa(i + 1), attempt.Latency, attempt.DNSStart, attempt.DNSDone, attempt.DNS, attempt.ConnectStart, attempt.ConnectDone, attempt.Connect, attempt.TLSHandshakeStart, attempt.TLSHandshakeDone, attempt.TLSHandshake, attempt.ReqWritten, attempt.RespFirstByte, attempt.WaitRespFirstByte, reqErr, }) if err != nil { fmt.Fprintf(os.Stderr, "failed to write request trace, %v\n", err) } l.out.Flush() } } func durToMSString(v time.Duration) string { ms := float64(v) / float64(time.Millisecond) return fmt.Sprintf("%0.6f", ms) } type RequestReport struct { ID int64 TotalLatency string Retries int Attempts []AttemptReport } type AttemptReport struct { Reused bool Err error SDKMarshal string `json:",omitempty"` DNSStart string `json:",omitempty"` DNSDone string `json:",omitempty"` DNS string `json:",omitempty"` ConnectStart string `json:",omitempty"` ConnectDone string `json:",omitempty"` Connect string `json:",omitempty"` TLSHandshakeStart string `json:",omitempty"` TLSHandshakeDone string `json:",omitempty"` TLSHandshake string `json:",omitempty"` ReqWritten string `json:",omitempty"` RespFirstByte string `json:",omitempty"` WaitRespFirstByte string `json:",omitempty"` Latency string `json:",omitempty"` }
135
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "context" "flag" "fmt" "io" "io/ioutil" "os" "os/signal" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) var config Config func init() { config.SetupFlags("", flag.CommandLine) } func main() { if err := flag.CommandLine.Parse(os.Args[1:]); err != nil { flag.CommandLine.PrintDefaults() exitErrorf(err, "failed to parse CLI commands") } if err := config.Validate(); err != nil { flag.CommandLine.PrintDefaults() exitErrorf(err, "invalid arguments") } client := NewClient(config.Client) var creds *credentials.Credentials if config.SDK.Anonymous { creds = credentials.AnonymousCredentials } var endpoint *string if v := config.Endpoint; len(v) != 0 { endpoint = &v } sess, err := session.NewSession(&aws.Config{ HTTPClient: client, Endpoint: endpoint, Credentials: creds, S3Disable100Continue: aws.Bool(!config.SDK.ExpectContinue), }) if err != nil { exitErrorf(err, "failed to load config") } // Create context cancel for Ctrl+C/Interrupt ctx, cancelFn := context.WithCancel(context.Background()) defer cancelFn() sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt) go func() { <-sigCh cancelFn() }() // Use the request duration timeout if specified. if config.RequestDuration != 0 { var timeoutFn func() ctx, timeoutFn = context.WithTimeout(ctx, config.RequestDuration) defer timeoutFn() } logger := NewLogger(os.Stdout) // Start making the requests. svc := s3.New(sess) var reqCount int64 errCount := 0 for { trace := doRequest(ctx, reqCount, svc, config) select { case <-ctx.Done(): return default: } logger.RecordTrace(trace) if err := trace.Err(); err != nil { fmt.Fprintf(os.Stderr, err.Error()) errCount++ } else { errCount = 0 } if config.RequestCount > 0 && reqCount == config.RequestCount { return } reqCount++ // If the first several requests fail, exist, something is broken. if errCount == 5 && reqCount == 5 { exitErrorf(trace.Err(), "unable to make requests") } if config.RequestDelay > 0 { time.Sleep(config.RequestDelay) } } } func doRequest(ctx context.Context, id int64, svc *s3.S3, config Config) *RequestTrace { traceCtx := NewRequestTrace(ctx, id) defer traceCtx.RequestDone() resp, err := svc.GetObjectWithContext(traceCtx, &s3.GetObjectInput{ Bucket: &config.Bucket, Key: &config.Key, }, func(r *request.Request) { r.Handlers.Send.PushFront(traceCtx.OnSendAttempt) r.Handlers.Complete.PushBack(traceCtx.OnCompleteRequest) r.Handlers.CompleteAttempt.PushBack(traceCtx.OnCompleteAttempt) }) if err != nil { traceCtx.AppendError(fmt.Errorf("request failed, %v", err)) return traceCtx } defer resp.Body.Close() if n, err := io.Copy(ioutil.Discard, resp.Body); err != nil { traceCtx.AppendError(fmt.Errorf("read request body failed, read %v, %v", n, err)) return traceCtx } return traceCtx } func exitErrorf(err error, msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, "FAILED: %v\n"+msg+"\n", append([]interface{}{err}, args...)...) os.Exit(1) }
146
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "context" "crypto/tls" "net/http/httptrace" "time" "github.com/aws/aws-sdk-go/aws/request" ) type RequestTrace struct { ID int64 context.Context start, finish time.Time errs Errors attempts []RequestAttempt curAttempt RequestAttempt } func NewRequestTrace(ctx context.Context, id int64) *RequestTrace { rt := &RequestTrace{ ID: id, start: time.Now(), attempts: []RequestAttempt{}, } trace := &httptrace.ClientTrace{ GetConn: rt.getConn, GotConn: rt.gotConn, PutIdleConn: rt.putIdleConn, GotFirstResponseByte: rt.gotFirstResponseByte, Got100Continue: rt.got100Continue, DNSStart: rt.dnsStart, DNSDone: rt.dnsDone, ConnectStart: rt.connectStart, ConnectDone: rt.connectDone, TLSHandshakeStart: rt.tlsHandshakeStart, TLSHandshakeDone: rt.tlsHandshakeDone, WroteHeaders: rt.wroteHeaders, Wait100Continue: rt.wait100Continue, WroteRequest: rt.wroteRequest, } rt.Context = httptrace.WithClientTrace(ctx, trace) return rt } func (rt *RequestTrace) AppendError(err error) { rt.errs = append(rt.errs, err) } func (rt *RequestTrace) OnCompleteAttempt(r *request.Request) { rt.curAttempt.Start = r.AttemptTime rt.curAttempt.Finish = time.Now() rt.curAttempt.Err = r.Error rt.attempts = append(rt.attempts, rt.curAttempt) rt.curAttempt = RequestAttempt{} } func (rt *RequestTrace) OnSendAttempt(r *request.Request) { rt.curAttempt.SendStart = time.Now() } func (rt *RequestTrace) OnCompleteRequest(r *request.Request) {} func (rt *RequestTrace) RequestDone() { rt.finish = time.Now() // Last attempt includes reading the response body rt.attempts[len(rt.attempts)-1].Finish = rt.finish } func (rt *RequestTrace) Err() error { return rt.errs } func (rt *RequestTrace) TotalLatency() time.Duration { return rt.finish.Sub(rt.start) } func (rt *RequestTrace) Attempts() []RequestAttempt { return rt.attempts } func (rt *RequestTrace) Retries() int { return len(rt.attempts) - 1 } func (rt *RequestTrace) getConn(hostPort string) {} func (rt *RequestTrace) gotConn(info httptrace.GotConnInfo) { rt.curAttempt.Reused = info.Reused } func (rt *RequestTrace) putIdleConn(err error) {} func (rt *RequestTrace) gotFirstResponseByte() { rt.curAttempt.FirstResponseByte = time.Now() } func (rt *RequestTrace) got100Continue() {} func (rt *RequestTrace) dnsStart(info httptrace.DNSStartInfo) { rt.curAttempt.DNSStart = time.Now() } func (rt *RequestTrace) dnsDone(info httptrace.DNSDoneInfo) { rt.curAttempt.DNSDone = time.Now() } func (rt *RequestTrace) connectStart(network, addr string) { rt.curAttempt.ConnectStart = time.Now() } func (rt *RequestTrace) connectDone(network, addr string, err error) { rt.curAttempt.ConnectDone = time.Now() } func (rt *RequestTrace) tlsHandshakeStart() { rt.curAttempt.TLSHandshakeStart = time.Now() } func (rt *RequestTrace) tlsHandshakeDone(state tls.ConnectionState, err error) { rt.curAttempt.TLSHandshakeDone = time.Now() } func (rt *RequestTrace) wroteHeaders() {} func (rt *RequestTrace) wait100Continue() {} func (rt *RequestTrace) wroteRequest(info httptrace.WroteRequestInfo) { rt.curAttempt.RequestWritten = time.Now() } type RequestAttempt struct { Start, Finish time.Time SendStart time.Time Err error Reused bool DNSStart, DNSDone time.Time ConnectStart, ConnectDone time.Time TLSHandshakeStart, TLSHandshakeDone time.Time RequestWritten time.Time FirstResponseByte time.Time }
135
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "net" "net/http" "time" ) func NewClient(cfg ClientConfig) *http.Client { tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: cfg.Timeouts.Connect, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: cfg.MaxIdleConns, MaxIdleConnsPerHost: cfg.MaxIdleConnsPerHost, IdleConnTimeout: 90 * time.Second, DisableKeepAlives: !cfg.KeepAlive, TLSHandshakeTimeout: cfg.Timeouts.TLSHandshake, ExpectContinueTimeout: cfg.Timeouts.ExpectContinue, ResponseHeaderTimeout: cfg.Timeouts.ResponseHeader, } return &http.Client{ Transport: tr, } }
33
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "flag" "fmt" "net/http" "os" "strings" "time" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) type Config struct { Bucket string Filename string Size int64 TempDir string LogVerbose bool SDK SDKConfig Client ClientConfig } func (c *Config) SetupFlags(prefix string, flagset *flag.FlagSet) { flagset.StringVar(&c.Bucket, "bucket", "", "The S3 bucket `name` to upload the object to.") flagset.StringVar(&c.Filename, "file", "", "The `path` of the local file to upload.") flagset.Int64Var(&c.Size, "size", 0, "The S3 object size in bytes to upload") flagset.StringVar(&c.TempDir, "temp", os.TempDir(), "location to create temporary files") flagset.BoolVar(&c.LogVerbose, "verbose", false, "The output log will include verbose request information") c.SDK.SetupFlags(prefix, flagset) c.Client.SetupFlags(prefix, flagset) } func (c *Config) Validate() error { var errs Errors if len(c.Bucket) == 0 || (c.Size <= 0 && c.Filename == "") { errs = append(errs, fmt.Errorf("bucket and filename/size are required")) } if err := c.SDK.Validate(); err != nil { errs = append(errs, err) } if err := c.Client.Validate(); err != nil { errs = append(errs, err) } if len(errs) != 0 { return errs } return nil } type SDKConfig struct { PartSize int64 Concurrency int WithUnsignedPayload bool WithContentMD5 bool ExpectContinue bool BufferProvider s3manager.ReadSeekerWriteToProvider } func (c *SDKConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "sdk." flagset.Int64Var(&c.PartSize, prefix+"part-size", s3manager.DefaultUploadPartSize, "Specifies the `size` of parts of the object to upload.") flagset.IntVar(&c.Concurrency, prefix+"concurrency", s3manager.DefaultUploadConcurrency, "Specifies the number of parts to upload `at once`.") flagset.BoolVar(&c.WithUnsignedPayload, prefix+"unsigned", false, "Specifies if the SDK will use UNSIGNED_PAYLOAD for part SHA256 in request signature.") flagset.BoolVar(&c.WithContentMD5, prefix+"content-md5", true, "Specifies if the SDK should compute the content md5 header for S3 uploads.") flagset.BoolVar(&c.ExpectContinue, prefix+"100-continue", true, "Specifies if the SDK requests will wait for the 100 continue response before sending request payload.") } func (c *SDKConfig) Validate() error { return nil } type ClientConfig struct { KeepAlive bool Timeouts Timeouts MaxIdleConns int MaxIdleConnsPerHost int } func (c *ClientConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "client." flagset.BoolVar(&c.KeepAlive, prefix+"http-keep-alive", true, "Specifies if HTTP keep alive is enabled.") defTR := http.DefaultTransport.(*http.Transport) flagset.IntVar(&c.MaxIdleConns, prefix+"idle-conns", defTR.MaxIdleConns, "Specifies max idle connection pool size.") flagset.IntVar(&c.MaxIdleConnsPerHost, prefix+"idle-conns-host", http.DefaultMaxIdleConnsPerHost, "Specifies max idle connection pool per host, will be truncated by idle-conns.") c.Timeouts.SetupFlags(prefix, flagset) } func (c *ClientConfig) Validate() error { var errs Errors if err := c.Timeouts.Validate(); err != nil { errs = append(errs, err) } if len(errs) != 0 { return errs } return nil } type Timeouts struct { Connect time.Duration TLSHandshake time.Duration ExpectContinue time.Duration ResponseHeader time.Duration } func (c *Timeouts) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "timeout." flagset.DurationVar(&c.Connect, prefix+"connect", 30*time.Second, "The `timeout` connecting to the remote host.") defTR := http.DefaultTransport.(*http.Transport) flagset.DurationVar(&c.TLSHandshake, prefix+"tls", defTR.TLSHandshakeTimeout, "The `timeout` waiting for the TLS handshake to complete.") flagset.DurationVar(&c.ExpectContinue, prefix+"expect-continue", defTR.ExpectContinueTimeout, "The `timeout` waiting for the TLS handshake to complete.") flagset.DurationVar(&c.ResponseHeader, prefix+"response-header", defTR.ResponseHeaderTimeout, "The `timeout` waiting for the TLS handshake to complete.") } func (c *Timeouts) Validate() error { return nil } type Errors []error func (es Errors) Error() string { var buf strings.Builder for _, e := range es { buf.WriteString(e.Error()) } return buf.String() }
169
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "flag" "log" "os" "path/filepath" "strconv" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/awstesting/integration" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) var config Config func main() { parseCommandLine() log.SetOutput(os.Stderr) var ( file *os.File err error ) if config.Filename != "" { file, err = os.Open(config.Filename) if err != nil { log.Fatalf("failed to open file: %v", err) } } else { file, err = integration.CreateFileOfSize(config.TempDir, config.Size) if err != nil { log.Fatalf("failed to create file: %v", err) } defer os.Remove(file.Name()) } defer file.Close() traces := make(chan *RequestTrace, config.SDK.Concurrency) requestTracer := uploadRequestTracer(traces) uploader := newUploader(config.Client, config.SDK, requestTracer) metricReportDone := make(chan struct{}) go func() { defer close(metricReportDone) metrics := map[string]*RequestTrace{} for trace := range traces { curTrace, ok := metrics[trace.Operation] if !ok { curTrace = trace } else { curTrace.attempts = append(curTrace.attempts, trace.attempts...) if len(trace.errs) != 0 { curTrace.errs = append(curTrace.errs, trace.errs...) } curTrace.finish = trace.finish } metrics[trace.Operation] = curTrace } for _, name := range []string{ "CreateMultipartUpload", "CompleteMultipartUpload", "UploadPart", "PutObject", } { if trace, ok := metrics[name]; ok { printAttempts(name, trace, config.LogVerbose) } } }() log.Println("starting upload...") start := time.Now() _, err = uploader.Upload(&s3manager.UploadInput{ Bucket: &config.Bucket, Key: aws.String(filepath.Base(file.Name())), Body: file, }) if err != nil { log.Fatalf("failed to upload object, %v", err) } close(traces) fileInfo, _ := file.Stat() size := fileInfo.Size() dur := time.Since(start) log.Printf("Upload finished, Size: %d, Dur: %s, Throughput: %.5f GB/s", size, dur, (float64(size)/(float64(dur)/float64(time.Second)))/float64(1e9), ) <-metricReportDone } func parseCommandLine() { config.SetupFlags("", flag.CommandLine) if err := flag.CommandLine.Parse(os.Args[1:]); err != nil { flag.CommandLine.PrintDefaults() log.Fatalf("failed to parse CLI commands") } if err := config.Validate(); err != nil { flag.CommandLine.PrintDefaults() log.Fatalf("invalid arguments: %v", err) } } func printAttempts(op string, trace *RequestTrace, verbose bool) { if !verbose { return } log.Printf("%s: latency:%s requests:%d errors:%d", op, trace.finish.Sub(trace.start), len(trace.attempts), len(trace.errs), ) for _, a := range trace.attempts { log.Printf(" * %s", a) } if err := trace.Err(); err != nil { log.Printf("Operation Errors: %v", err) } log.Println() } func uploadRequestTracer(traces chan<- *RequestTrace) request.Option { tracerOption := func(r *request.Request) { id := "op" if v, ok := r.Params.(*s3.UploadPartInput); ok { id = strconv.FormatInt(*v.PartNumber, 10) } tracer := NewRequestTrace(r.Context(), r.Operation.Name, id) r.SetContext(tracer) r.Handlers.Send.PushFront(tracer.OnSendAttempt) r.Handlers.CompleteAttempt.PushBack(tracer.OnCompleteAttempt) r.Handlers.Complete.PushBack(tracer.OnComplete) r.Handlers.Complete.PushBack(func(rr *request.Request) { traces <- tracer }) } return tracerOption } func SetUnsignedPayload(r *request.Request) { if r.Operation.Name != "UploadPart" && r.Operation.Name != "PutObject" { return } r.HTTPRequest.Header.Set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD") } func newUploader(clientConfig ClientConfig, sdkConfig SDKConfig, options ...request.Option) *s3manager.Uploader { client := NewClient(clientConfig) if sdkConfig.WithUnsignedPayload { options = append(options, SetUnsignedPayload) } sess, err := session.NewSessionWithOptions(session.Options{ Config: aws.Config{ HTTPClient: client, S3Disable100Continue: aws.Bool(!sdkConfig.ExpectContinue), S3DisableContentMD5Validation: aws.Bool(!sdkConfig.WithContentMD5), }, SharedConfigState: session.SharedConfigEnable, }) if err != nil { log.Fatalf("failed to load session, %v", err) } uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = sdkConfig.PartSize u.Concurrency = sdkConfig.Concurrency u.BufferProvider = sdkConfig.BufferProvider u.RequestOptions = append(u.RequestOptions, options...) }) return uploader } func getUploadPartSize(fileSize, uploadPartSize int64) int64 { partSize := uploadPartSize if fileSize/partSize > s3manager.MaxUploadParts { partSize = (fileSize / s3manager.MaxUploadParts) + 1 } return partSize }
205
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "flag" "fmt" "io" "os" "strconv" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/awstesting" "github.com/aws/aws-sdk-go/awstesting/integration" "github.com/aws/aws-sdk-go/internal/sdkio" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) var benchConfig BenchmarkConfig type BenchmarkConfig struct { bucket string tempdir string clientConfig ClientConfig sizes string parts string concurrency string bufferSize string } func (b *BenchmarkConfig) SetupFlags(prefix string, flagSet *flag.FlagSet) { flagSet.StringVar(&b.bucket, "bucket", "", "Bucket to use for benchmark") flagSet.StringVar(&b.tempdir, "temp", os.TempDir(), "location to create temporary files") flagSet.StringVar(&b.sizes, "size", fmt.Sprintf("%d,%d", 5*sdkio.MebiByte, 1*sdkio.GibiByte), "file sizes to benchmark separated by comma") flagSet.StringVar(&b.parts, "part", fmt.Sprintf("%d,%d,%d", s3manager.DefaultUploadPartSize, 25*sdkio.MebiByte, 100*sdkio.MebiByte), "part sizes to benchmark separated by comma") flagSet.StringVar(&b.concurrency, "concurrency", fmt.Sprintf("%d,%d,%d", s3manager.DefaultUploadConcurrency, 2*s3manager.DefaultUploadConcurrency, 100), "concurrences to benchmark separated comma") flagSet.StringVar(&b.bufferSize, "buffer", fmt.Sprintf("%d,%d", 0, 1*sdkio.MebiByte), "part sizes to benchmark separated comma") b.clientConfig.SetupFlags(prefix, flagSet) } func (b *BenchmarkConfig) BufferSizes() []int { ints, err := b.stringToInt(b.bufferSize) if err != nil { panic(fmt.Sprintf("failed to parse file sizes: %v", err)) } return ints } func (b *BenchmarkConfig) FileSizes() []int64 { ints, err := b.stringToInt64(b.sizes) if err != nil { panic(fmt.Sprintf("failed to parse file sizes: %v", err)) } return ints } func (b *BenchmarkConfig) PartSizes() []int64 { ints, err := b.stringToInt64(b.parts) if err != nil { panic(fmt.Sprintf("failed to parse part sizes: %v", err)) } return ints } func (b *BenchmarkConfig) Concurrences() []int { ints, err := b.stringToInt(b.concurrency) if err != nil { panic(fmt.Sprintf("failed to parse part sizes: %v", err)) } return ints } func (b *BenchmarkConfig) stringToInt(s string) ([]int, error) { int64s, err := b.stringToInt64(s) if err != nil { return nil, err } var ints []int for i := range int64s { ints = append(ints, int(int64s[i])) } return ints, nil } func (b *BenchmarkConfig) stringToInt64(s string) ([]int64, error) { var sizes []int64 split := strings.Split(s, ",") for _, size := range split { size = strings.Trim(size, " ") i, err := strconv.ParseInt(size, 10, 64) if err != nil { return nil, fmt.Errorf("invalid integer %s: %v", size, err) } sizes = append(sizes, i) } return sizes, nil } func BenchmarkUpload(b *testing.B) { baseSdkConfig := SDKConfig{WithUnsignedPayload: true} for _, fileSize := range benchConfig.FileSizes() { b.Run(fmt.Sprintf("%s File", integration.SizeToName(int(fileSize))), func(b *testing.B) { for _, concurrency := range benchConfig.Concurrences() { b.Run(fmt.Sprintf("%d Concurrency", concurrency), func(b *testing.B) { for _, partSize := range benchConfig.PartSizes() { if partSize > fileSize { continue } partSize = getUploadPartSize(fileSize, partSize) b.Run(fmt.Sprintf("%s PartSize", integration.SizeToName(int(partSize))), func(b *testing.B) { for _, bufferSize := range benchConfig.BufferSizes() { var name string if bufferSize == 0 { name = "Unbuffered" } else { name = fmt.Sprintf("%s Buffer", integration.SizeToName(bufferSize)) } b.Run(name, func(b *testing.B) { sdkConfig := baseSdkConfig sdkConfig.Concurrency = concurrency sdkConfig.PartSize = partSize if bufferSize > 0 { sdkConfig.BufferProvider = s3manager.NewBufferedReadSeekerWriteToPool(bufferSize) } for i := 0; i < b.N; i++ { for { b.ResetTimer() reader := aws.ReadSeekCloser(io.LimitReader(&awstesting.EndlessReader{}, fileSize)) err := benchUpload(b, benchConfig.bucket, integration.UniqueID(), reader, sdkConfig, benchConfig.clientConfig) if err != nil { b.Logf("upload failed, retrying: %v", err) continue } break } } }) } }) } }) } }) } } func benchUpload(b *testing.B, bucket, key string, reader io.ReadSeeker, sdkConfig SDKConfig, clientConfig ClientConfig) error { uploader := newUploader(clientConfig, sdkConfig, SetUnsignedPayload) _, err := uploader.Upload(&s3manager.UploadInput{ Bucket: &bucket, Key: &key, Body: reader, }) if err != nil { return err } return nil } func TestMain(m *testing.M) { benchConfig.SetupFlags("", flag.CommandLine) flag.Parse() os.Exit(m.Run()) }
196
session-manager-plugin
aws
Go
// +build integration,perftest package main import ( "context" "crypto/tls" "fmt" "net/http/httptrace" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws/request" ) type RequestTrace struct { Operation string ID string context.Context start, finish time.Time errs Errors attempts []RequestAttempt curAttempt RequestAttempt } func NewRequestTrace(ctx context.Context, op, id string) *RequestTrace { rt := &RequestTrace{ Operation: op, ID: id, start: time.Now(), attempts: []RequestAttempt{}, curAttempt: RequestAttempt{ ID: id, }, } trace := &httptrace.ClientTrace{ GetConn: rt.getConn, GotConn: rt.gotConn, PutIdleConn: rt.putIdleConn, GotFirstResponseByte: rt.gotFirstResponseByte, Got100Continue: rt.got100Continue, DNSStart: rt.dnsStart, DNSDone: rt.dnsDone, ConnectStart: rt.connectStart, ConnectDone: rt.connectDone, TLSHandshakeStart: rt.tlsHandshakeStart, TLSHandshakeDone: rt.tlsHandshakeDone, WroteHeaders: rt.wroteHeaders, Wait100Continue: rt.wait100Continue, WroteRequest: rt.wroteRequest, } rt.Context = httptrace.WithClientTrace(ctx, trace) return rt } func (rt *RequestTrace) AppendError(err error) { rt.errs = append(rt.errs, err) } func (rt *RequestTrace) OnSendAttempt(r *request.Request) { rt.curAttempt.SendStart = time.Now() } func (rt *RequestTrace) OnCompleteAttempt(r *request.Request) { rt.curAttempt.Start = r.AttemptTime rt.curAttempt.Finish = time.Now() rt.curAttempt.Err = r.Error if r.Error != nil { rt.AppendError(r.Error) } rt.attempts = append(rt.attempts, rt.curAttempt) rt.curAttempt = RequestAttempt{ ID: rt.curAttempt.ID, AttemptNum: rt.curAttempt.AttemptNum + 1, } } func (rt *RequestTrace) OnComplete(r *request.Request) { rt.finish = time.Now() // Last attempt includes reading the response body if len(rt.attempts) > 0 { rt.attempts[len(rt.attempts)-1].Finish = rt.finish } } func (rt *RequestTrace) Err() error { if len(rt.errs) != 0 { return rt.errs } return nil } func (rt *RequestTrace) TotalLatency() time.Duration { return rt.finish.Sub(rt.start) } func (rt *RequestTrace) Attempts() []RequestAttempt { return rt.attempts } func (rt *RequestTrace) Retries() int { return len(rt.attempts) - 1 } func (rt *RequestTrace) getConn(hostPort string) {} func (rt *RequestTrace) gotConn(info httptrace.GotConnInfo) { rt.curAttempt.Reused = info.Reused } func (rt *RequestTrace) putIdleConn(err error) {} func (rt *RequestTrace) gotFirstResponseByte() { rt.curAttempt.FirstResponseByte = time.Now() } func (rt *RequestTrace) got100Continue() {} func (rt *RequestTrace) dnsStart(info httptrace.DNSStartInfo) { rt.curAttempt.DNSStart = time.Now() } func (rt *RequestTrace) dnsDone(info httptrace.DNSDoneInfo) { rt.curAttempt.DNSDone = time.Now() } func (rt *RequestTrace) connectStart(network, addr string) { rt.curAttempt.ConnectStart = time.Now() } func (rt *RequestTrace) connectDone(network, addr string, err error) { rt.curAttempt.ConnectDone = time.Now() } func (rt *RequestTrace) tlsHandshakeStart() { rt.curAttempt.TLSHandshakeStart = time.Now() } func (rt *RequestTrace) tlsHandshakeDone(state tls.ConnectionState, err error) { rt.curAttempt.TLSHandshakeDone = time.Now() } func (rt *RequestTrace) wroteHeaders() { rt.curAttempt.WroteHeaders = time.Now() } func (rt *RequestTrace) wait100Continue() { rt.curAttempt.Read100Continue = time.Now() } func (rt *RequestTrace) wroteRequest(info httptrace.WroteRequestInfo) { rt.curAttempt.RequestWritten = time.Now() } type RequestAttempt struct { Start, Finish time.Time SendStart time.Time Err error Reused bool ID string AttemptNum int DNSStart, DNSDone time.Time ConnectStart, ConnectDone time.Time TLSHandshakeStart, TLSHandshakeDone time.Time WroteHeaders time.Time RequestWritten time.Time Read100Continue time.Time FirstResponseByte time.Time } func (a RequestAttempt) String() string { const sep = ", " var w strings.Builder w.WriteString(a.ID + "-" + strconv.Itoa(a.AttemptNum) + sep) w.WriteString("Latency:" + durToMSString(a.Finish.Sub(a.Start)) + sep) w.WriteString("SDKPreSend:" + durToMSString(a.SendStart.Sub(a.Start)) + sep) writeStart := a.SendStart fmt.Fprintf(&w, "ConnReused:%t"+sep, a.Reused) if !a.Reused { w.WriteString("DNS:" + durToMSString(a.DNSDone.Sub(a.DNSStart)) + sep) w.WriteString("Connect:" + durToMSString(a.ConnectDone.Sub(a.ConnectStart)) + sep) w.WriteString("TLS:" + durToMSString(a.TLSHandshakeDone.Sub(a.TLSHandshakeStart)) + sep) writeStart = a.TLSHandshakeDone } writeHeader := a.WroteHeaders.Sub(writeStart) w.WriteString("WriteHeader:" + durToMSString(writeHeader) + sep) if !a.Read100Continue.IsZero() { // With 100-continue w.WriteString("Read100Cont:" + durToMSString(a.Read100Continue.Sub(a.WroteHeaders)) + sep) w.WriteString("WritePayload:" + durToMSString(a.FirstResponseByte.Sub(a.RequestWritten)) + sep) w.WriteString("RespRead:" + durToMSString(a.Finish.Sub(a.RequestWritten)) + sep) } else { // No 100-continue w.WriteString("WritePayload:" + durToMSString(a.RequestWritten.Sub(a.WroteHeaders)) + sep) if !a.FirstResponseByte.IsZero() { w.WriteString("RespFirstByte:" + durToMSString(a.FirstResponseByte.Sub(a.RequestWritten)) + sep) w.WriteString("RespRead:" + durToMSString(a.Finish.Sub(a.FirstResponseByte)) + sep) } } return w.String() } func durToMSString(v time.Duration) string { ms := float64(v) / float64(time.Millisecond) return fmt.Sprintf("%0.6f", ms) }
205
session-manager-plugin
aws
Go
// +build integration package s3integ import ( "fmt" "github.com/aws/aws-sdk-go/awstesting/integration" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3iface" "github.com/aws/aws-sdk-go/service/s3control" "github.com/aws/aws-sdk-go/service/s3control/s3controliface" ) // BucketPrefix is the root prefix of integration test buckets. const BucketPrefix = "aws-sdk-go-integration" // GenerateBucketName returns a unique bucket name. func GenerateBucketName() string { return fmt.Sprintf("%s-%s", BucketPrefix, integration.UniqueID()) } // SetupBucket returns a test bucket created for the integration tests. func SetupBucket(svc s3iface.S3API, bucketName string) (err error) { fmt.Println("Setup: Creating test bucket,", bucketName) _, err = svc.CreateBucket(&s3.CreateBucketInput{Bucket: &bucketName}) if err != nil { return fmt.Errorf("failed to create bucket %s, %v", bucketName, err) } fmt.Println("Setup: Waiting for bucket to exist,", bucketName) err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{Bucket: &bucketName}) if err != nil { return fmt.Errorf("failed waiting for bucket %s to be created, %v", bucketName, err) } return nil } // CleanupBucket deletes the contents of a S3 bucket, before deleting the bucket // it self. func CleanupBucket(svc s3iface.S3API, bucketName string) error { errs := []error{} fmt.Println("TearDown: Deleting objects from test bucket,", bucketName) err := svc.ListObjectsPages( &s3.ListObjectsInput{Bucket: &bucketName}, func(page *s3.ListObjectsOutput, lastPage bool) bool { for _, o := range page.Contents { _, err := svc.DeleteObject(&s3.DeleteObjectInput{ Bucket: &bucketName, Key: o.Key, }) if err != nil { errs = append(errs, err) } } return true }, ) if err != nil { return fmt.Errorf("failed to list objects, %s, %v", bucketName, err) } fmt.Println("TearDown: Deleting partial uploads from test bucket,", bucketName) err = svc.ListMultipartUploadsPages( &s3.ListMultipartUploadsInput{Bucket: &bucketName}, func(page *s3.ListMultipartUploadsOutput, lastPage bool) bool { for _, u := range page.Uploads { svc.AbortMultipartUpload(&s3.AbortMultipartUploadInput{ Bucket: &bucketName, Key: u.Key, UploadId: u.UploadId, }) } return true }, ) if err != nil { return fmt.Errorf("failed to list multipart objects, %s, %v", bucketName, err) } if len(errs) != 0 { return fmt.Errorf("failed to delete objects, %s", errs) } fmt.Println("TearDown: Deleting test bucket,", bucketName) if _, err = svc.DeleteBucket(&s3.DeleteBucketInput{Bucket: &bucketName}); err != nil { return fmt.Errorf("failed to delete test bucket, %s", bucketName) } return nil } // SetupAccessPoint returns an access point for the given bucket for testing func SetupAccessPoint(svc s3controliface.S3ControlAPI, account, bucket, accessPoint string) error { fmt.Printf("Setup: creating access point %q for bucket %q\n", accessPoint, bucket) _, err := svc.CreateAccessPoint(&s3control.CreateAccessPointInput{ AccountId: &account, Bucket: &bucket, Name: &accessPoint, }) if err != nil { return fmt.Errorf("failed to create access point: %v", err) } return nil } // CleanupAccessPoint deletes the given access point func CleanupAccessPoint(svc s3controliface.S3ControlAPI, account, accessPoint string) error { fmt.Printf("TearDown: Deleting access point %q\n", accessPoint) _, err := svc.DeleteAccessPoint(&s3control.DeleteAccessPointInput{ AccountId: &account, Name: &accessPoint, }) if err != nil { return fmt.Errorf("failed to delete access point: %v", err) } return nil }
124
session-manager-plugin
aws
Go
package mock import ( "crypto/rsa" "math/big" "net/http" "net/http/httptest" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/session" ) // Session is a mock session which is used to hit the mock server var Session = func() *session.Session { // server is the mock server that simply writes a 200 status back to the client server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) return session.Must(session.NewSession(&aws.Config{ DisableSSL: aws.Bool(true), Endpoint: aws.String(server.URL), })) }() // NewMockClient creates and initializes a client that will connect to the // mock server func NewMockClient(cfgs ...*aws.Config) *client.Client { c := Session.ClientConfig("Mock", cfgs...) svc := client.New( *c.Config, metadata.ClientInfo{ ServiceName: "Mock", SigningRegion: c.SigningRegion, Endpoint: c.Endpoint, APIVersion: "2015-12-08", JSONVersion: "1.1", TargetPrefix: "MockServer", }, c.Handlers, ) return svc } // RSAPrivateKey is used for testing functionality that requires some // sort of private key. Taken from crypto/rsa/rsa_test.go // // Credit to golang 1.11 var RSAPrivateKey = &rsa.PrivateKey{ PublicKey: rsa.PublicKey{ N: fromBase10("14314132931241006650998084889274020608918049032671858325988396851334124245188214251956198731333464217832226406088020736932173064754214329009979944037640912127943488972644697423190955557435910767690712778463524983667852819010259499695177313115447116110358524558307947613422897787329221478860907963827160223559690523660574329011927531289655711860504630573766609239332569210831325633840174683944553667352219670930408593321661375473885147973879086994006440025257225431977751512374815915392249179976902953721486040787792801849818254465486633791826766873076617116727073077821584676715609985777563958286637185868165868520557"), E: 3, }, D: fromBase10("9542755287494004433998723259516013739278699355114572217325597900889416163458809501304132487555642811888150937392013824621448709836142886006653296025093941418628992648429798282127303704957273845127141852309016655778568546006839666463451542076964744073572349705538631742281931858219480985907271975884773482372966847639853897890615456605598071088189838676728836833012254065983259638538107719766738032720239892094196108713378822882383694456030043492571063441943847195939549773271694647657549658603365629458610273821292232646334717612674519997533901052790334279661754176490593041941863932308687197618671528035670452762731"), Primes: []*big.Int{ fromBase10("130903255182996722426771613606077755295583329135067340152947172868415809027537376306193179624298874215608270802054347609836776473930072411958753044562214537013874103802006369634761074377213995983876788718033850153719421695468704276694983032644416930879093914927146648402139231293035971427838068945045019075433"), fromBase10("109348945610485453577574767652527472924289229538286649661240938988020367005475727988253438647560958573506159449538793540472829815903949343191091817779240101054552748665267574271163617694640513549693841337820602726596756351006149518830932261246698766355347898158548465400674856021497190430791824869615170301029"), }, } // Taken from crypto/rsa/rsa_test.go // // Credit to golang 1.11 func fromBase10(base10 string) *big.Int { i, ok := new(big.Int).SetString(base10, 10) if !ok { panic("bad number: " + base10) } return i }
75
session-manager-plugin
aws
Go
// Package unit performs initialization and validation for unit tests package unit import ( "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" ) // Session is a shared session for unit tests to use. var Session = session.Must(session.NewSession(&aws.Config{ Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), Region: aws.String("mock-region"), SleepDelay: func(time.Duration) {}, }))
18
session-manager-plugin
aws
Go
// +build example,go18 package main import ( "context" "fmt" "os" "plugin" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials/plugincreds" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // Example application which loads a Go Plugin file, and uses the credential // provider defined within the plugin to get credentials for making a S3 // request. // // The example will derive the bucket's region automatically if a AWS_REGION // environment variable is not defined. // // Build: // go build -tags example -o myApp main.go // // Usage: // ./myApp <compiled plugin> <bucket> <object key> func main() { if len(os.Args) < 4 { exitErrorf("Usage: myApp <compiled plugin>, <bucket> <object key>") } pluginFilename := os.Args[1] bucket := os.Args[2] key := os.Args[3] // Open plugin, and load it into the process. p, err := plugin.Open(pluginFilename) if err != nil { exitErrorf("failed to open plugin, %s, %v", pluginFilename, err) } // Create a new Credentials value which will source the provider's Retrieve // and IsExpired functions from the plugin. creds, err := plugincreds.NewCredentials(p) if err != nil { exitErrorf("failed to load plugin provider, %v", err) } // Example to configure a Session with the newly created credentials that // will be sourced using the plugin's functionality. sess := session.Must(session.NewSession(&aws.Config{ Credentials: creds, })) // If the region is not available attempt to derive the bucket's region // from a query to S3 for the bucket's metadata region := aws.StringValue(sess.Config.Region) if len(region) == 0 { region, err = s3manager.GetBucketRegion(context.Background(), sess, bucket, endpoints.UsEast1RegionID) if err != nil { exitErrorf("failed to get bucket region, %v", err) } } // Create the S3 service client for the target region svc := s3.New(sess, aws.NewConfig().WithRegion(region)) // Get the object's details result, err := svc.HeadObject(&s3.HeadObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), }) fmt.Println(result, err) } func exitErrorf(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format+"\n", args...) os.Exit(1) }
84
session-manager-plugin
aws
Go
// +build example,go18 package main import ( "encoding/json" "os" "github.com/pkg/errors" ) // Example plugin that will retrieve credentials from a JSON file that the // "PLUGIN_CREDS_FILE" environment variable points to // // Build with: // go build -tags example -o plugin.so -buildmode=plugin plugin.go func main() {} var myCredProvider provider func init() { // Initialize a mock credential provider with stubs myCredProvider = provider{Filename: os.Getenv("PLUGIN_CREDS_FILE")} } // GetAWSSDKCredentialProvider is the symbol SDK will lookup and use to // get the credential provider's retrieve and isExpired functions. func GetAWSSDKCredentialProvider() (func() (key, secret, token string, err error), func() bool) { return myCredProvider.Retrieve, myCredProvider.IsExpired } // mock implementation of a type that returns retrieves credentials and // returns if they have expired. type provider struct { Filename string loaded bool } func (p *provider) Retrieve() (key, secret, token string, err error) { f, err := os.Open(p.Filename) if err != nil { return "", "", "", errors.Wrapf(err, "failed to open credentials file, %q", p.Filename) } decoder := json.NewDecoder(f) creds := struct { Key, Secret, Token string }{} if err := decoder.Decode(&creds); err != nil { return "", "", "", errors.Wrap(err, "failed to decode credentials file") } p.loaded = true return creds.Key, creds.Secret, creds.Token, nil } func (p *provider) IsExpired() bool { return !p.loaded }
62
session-manager-plugin
aws
Go
// +build example package main import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/sqs" ) func main() { defaultResolver := endpoints.DefaultResolver() s3CustResolverFn := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { if service == "s3" { return endpoints.ResolvedEndpoint{ URL: "https://s3.custom.endpoint.com", SigningRegion: "custom-signing-region", }, nil } return defaultResolver.EndpointFor(service, region, optFns...) } sess := session.Must(session.NewSessionWithOptions(session.Options{ Config: aws.Config{ Region: aws.String("us-west-2"), EndpointResolver: endpoints.ResolverFunc(s3CustResolverFn), }, })) // Create the S3 service client with the shared session. This will // automatically use the S3 custom endpoint configured in the custom // endpoint resolver wrapping the default endpoint resolver. s3Svc := s3.New(sess) // Operation calls will be made to the custom endpoint. s3Svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String("myBucket"), Key: aws.String("myObjectKey"), }) // Create the SQS service client with the shared session. This will // fallback to the default endpoint resolver because the customization // passes any non S3 service endpoint resolve to the default resolver. sqsSvc := sqs.New(sess) // Operation calls will be made to the default endpoint for SQS for the // region configured. sqsSvc.ReceiveMessage(&sqs.ReceiveMessageInput{ QueueUrl: aws.String("my-queue-url"), }) // Create a DynamoDB service client that will use a custom endpoint // resolver that overrides the shared session's. This is useful when // custom endpoints are generated, or multiple endpoints are switched on // by a region value. ddbCustResolverFn := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { return endpoints.ResolvedEndpoint{ URL: "dynamodb.custom.endpoint", SigningRegion: "custom-signing-region", }, nil } ddbSvc := dynamodb.New(sess, &aws.Config{ EndpointResolver: endpoints.ResolverFunc(ddbCustResolverFn), }) // Operation calls will be made to the custom endpoint set in the // ddCustResolverFn. ddbSvc.ListTables(&dynamodb.ListTablesInput{}) // Setting Config's Endpoint will override the EndpointResolver. Forcing // the service client to make all operation to the endpoint specified // the in the config. ddbSvcLocal := dynamodb.New(sess, &aws.Config{ Endpoint: aws.String("http://localhost:8088"), }) ddbSvcLocal.ListTables(&dynamodb.ListTablesInput{}) }
78
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "os" "github.com/aws/aws-sdk-go/aws/endpoints" ) // Demostrates how the SDK's endpoints can be enumerated over to discover // regions, services, and endpoints defined by the SDK's Regions and Endpoints // metadata. // // Usage: // -p=id partition id, e.g: aws // -r=id region id, e.g: us-west-2 // -s=id service id, e.g: s3 // // -partitions Lists all partitions. // -regions Lists all regions in a partition. Requires partition ID. // If service ID is also provided will show endpoints for a service. // -services Lists all services in a partition. Requires partition ID. // If region ID is also provided, will show services available in that region. // // Example: // go run enumEndpoints.go -p aws -services -r us-west-2 // // Output: // Services with endpoint us-west-2 in aws: // ... func main() { var partitionID, regionID, serviceID string flag.StringVar(&partitionID, "p", "", "Partition ID") flag.StringVar(&regionID, "r", "", "Region ID") flag.StringVar(&serviceID, "s", "", "Service ID") var cmdPartitions, cmdRegions, cmdServices bool flag.BoolVar(&cmdPartitions, "partitions", false, "Lists partitions.") flag.BoolVar(&cmdRegions, "regions", false, "Lists regions of a partition. Requires partition ID to be provided. Will filter by a service if '-s' is set.") flag.BoolVar(&cmdServices, "services", false, "Lists services for a partition. Requires partition ID to be provided. Will filter by a region if '-r' is set.") flag.Parse() partitions := endpoints.DefaultResolver().(endpoints.EnumPartitions).Partitions() if cmdPartitions { printPartitions(partitions) } if !(cmdRegions || cmdServices) { return } p, ok := findPartition(partitions, partitionID) if !ok { fmt.Fprintf(os.Stderr, "Partition %q not found", partitionID) os.Exit(1) } if cmdRegions { printRegions(p, serviceID) } if cmdServices { printServices(p, regionID) } } func printPartitions(ps []endpoints.Partition) { fmt.Println("Partitions:") for _, p := range ps { fmt.Println(p.ID()) } } func printRegions(p endpoints.Partition, serviceID string) { if len(serviceID) != 0 { s, ok := p.Services()[serviceID] if !ok { fmt.Fprintf(os.Stderr, "service %q does not exist in partition %q", serviceID, p.ID()) os.Exit(1) } es := s.Endpoints() fmt.Printf("Endpoints for %s in %s:\n", serviceID, p.ID()) for _, e := range es { r, _ := e.ResolveEndpoint() fmt.Printf("%s: %s\n", e.ID(), r.URL) } } else { rs := p.Regions() fmt.Printf("Regions in %s:\n", p.ID()) for _, r := range rs { fmt.Println(r.ID()) } } } func printServices(p endpoints.Partition, endpointID string) { ss := p.Services() if len(endpointID) > 0 { fmt.Printf("Services with endpoint %s in %s:\n", endpointID, p.ID()) } else { fmt.Printf("Services in %s:\n", p.ID()) } for id, s := range ss { if _, ok := s.Endpoints()[endpointID]; !ok && len(endpointID) > 0 { continue } fmt.Println(id) } } func findPartition(ps []endpoints.Partition, partitionID string) (endpoints.Partition, bool) { for _, p := range ps { if p.ID() == partitionID { return p, true } } return endpoints.Partition{}, false }
127
session-manager-plugin
aws
Go
// +build example,go1.15 package main import ( "crypto/tls" "crypto/x509" "flag" "fmt" "io/ioutil" "log" "net" "net/http" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "golang.org/x/net/http2" ) // Example of creating an HTTP Client configured with a client TLS // certificates. Can be used with endpoints such as HTTPS_PROXY that require // client certificates. // // Requires a cert and key flags, and optionally takes a CA file. // // To run: // go run -cert <certfile> -key <keyfile> [-ca <cafile>] // // You can generate self signed cert and key pem files // go run $(go env GOROOT)/src/crypto/tls/generate_cert.go -host <hostname> func main() { var clientCertFile, clientKeyFile, caFile string flag.StringVar(&clientCertFile, "cert", "cert.pem", "The `certificate file` to load.") flag.StringVar(&clientKeyFile, "key", "key.pem", "The `key file` to load.") flag.StringVar(&caFile, "ca", "ca.pem", "The `root CA` to load.") flag.Parse() if len(clientCertFile) == 0 || len(clientKeyFile) == 0 { flag.PrintDefaults() log.Fatalf("client certificate and key required") } tlsCfg, err := tlsConfigWithClientCert(clientCertFile, clientKeyFile, caFile) if err != nil { log.Fatalf("failed to load client cert, %v", err) } // Copy of net/http.DefaultTransport with TLS config loaded tr := defaultHTTPTransport() tr.TLSClientConfig = tlsCfg // re-enable HTTP/2 because modifing TLS config will prevent auto support // for HTTP/2. http2.ConfigureTransport(tr) // Configure the SDK's session with the HTTP client with TLS client // certificate support enabled. This session will be used to create all // SDK's API clients. sess, err := session.NewSession(&aws.Config{ HTTPClient: &http.Client{ Transport: tr, }, }) // Create each API client will the session configured with the client TLS // certificate. svc := s3.New(sess) resp, err := svc.ListBuckets(&s3.ListBucketsInput{}) if err != nil { log.Fatalf("failed to list buckets, %v", err) } fmt.Println("Buckets") fmt.Println(resp) } func tlsConfigWithClientCert(clientCertFile, clientKeyFile, caFile string) (*tls.Config, error) { clientCert, err := tls.LoadX509KeyPair(clientCertFile, clientKeyFile) if err != nil { return nil, fmt.Errorf("unable to load certificat files, %s, %s, %v", clientCertFile, clientKeyFile, err) } tlsCfg := &tls.Config{ Certificates: []tls.Certificate{ clientCert, }, } if len(caFile) != 0 { cert, err := ioutil.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("unable to load root CA file, %s, %v", caFile, err) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(cert) tlsCfg.RootCAs = caCertPool } tlsCfg.BuildNameToCertificate() return tlsCfg, nil } func defaultHTTPTransport() *http.Transport { return &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, MaxIdleConnsPerHost: 10, // Increased idle connections per host IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } }
124
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudwatchlogs" ) func main() { sess := session.Must( session.NewSession(&aws.Config{ // Use a custom retryer to provide custom retry rules. Retryer: CustomRetryer{ DefaultRetryer: client.DefaultRetryer{ NumMaxRetries: client.DefaultRetryerMaxNumRetries, }}, // Use the SDK's SharedCredentialsProvider directly instead of the // SDK's default credential chain. This ensures that the // application can call Config.Credentials.Expire. This is counter // to the SDK's default credentials chain, which will never reread // the shared credentials file. Credentials: credentials.NewCredentials(&credentials.SharedCredentialsProvider{ Filename: defaults.SharedCredentialsFilename(), Profile: "default", }), Region: aws.String(endpoints.UsWest2RegionID), }), ) // Add a request handler to the AfterRetry handler stack that is used by the // SDK to be executed after the SDK has determined if it will retry. // This handler forces the SDK's Credentials to be expired, and next call to // Credentials.Get will attempt to refresh the credentials. sess.Handlers.AfterRetry.PushBack(func(req *request.Request) { if aerr, ok := req.Error.(awserr.RequestFailure); ok && aerr != nil { if aerr.Code() == "InvalidClaimException" { // Force the credentials to expire based on error code. Next // call to Credentials.Get will attempt to refresh credentials. req.Config.Credentials.Expire() } } }) svc := cloudwatchlogs.New(sess) resp, err := svc.DescribeLogGroups(&cloudwatchlogs.DescribeLogGroupsInput{}) fmt.Println(resp, err) } // CustomRetryer wraps the SDK's built in DefaultRetryer adding additional // custom features. Such as, no retry for 5xx status codes, and refresh // credentials. type CustomRetryer struct { client.DefaultRetryer } // ShouldRetry overrides the SDK's built in DefaultRetryer adding customization // to not retry 5xx status codes. func (r CustomRetryer) ShouldRetry(req *request.Request) bool { if req.HTTPResponse.StatusCode >= 500 { // Don't retry any 5xx status codes. return false } // Fallback to SDK's built in retry rules return r.DefaultRetryer.ShouldRetry(req) }
79
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "os" "path/filepath" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) func exitErrorf(msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) } // Will make a request to S3 for the contents of an object. If the request // was successful, and the object was found the object's path and size will be // printed to stdout. // // If the object's bucket or key does not exist a specific error message will // be printed to stderr for the error. // // Any other error will be printed as an unknown error. // // Usage: handleServiceErrorCodes <bucket> <key> func main() { if len(os.Args) < 3 { exitErrorf("Usage: %s <bucket> <key>", filepath.Base(os.Args[0])) } sess := session.Must(session.NewSession()) svc := s3.New(sess) resp, err := svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String(os.Args[1]), Key: aws.String(os.Args[2]), }) if err != nil { // Casting to the awserr.Error type will allow you to inspect the error // code returned by the service in code. The error code can be used // to switch on context specific functionality. In this case a context // specific error message is printed to the user based on the bucket // and key existing. // // For information on other S3 API error codes see: // http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchBucket: exitErrorf("bucket %s does not exist", os.Args[1]) case s3.ErrCodeNoSuchKey: exitErrorf("object with key %s does not exist in bucket %s", os.Args[2], os.Args[1]) } } exitErrorf("unknown error occurred, %v", err) } defer resp.Body.Close() fmt.Printf("s3://%s/%s exists. size: %d\n", os.Args[1], os.Args[2], aws.Int64Value(resp.ContentLength)) }
67
session-manager-plugin
aws
Go
package main import ( "net" "net/http" "time" ) // NewClient creates a new HTTP Client using the ClientConfig values. func NewClient(cfg ClientConfig) *http.Client { tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: cfg.Timeouts.Connect, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: cfg.Timeouts.IdleConnection, DisableKeepAlives: !cfg.KeepAlive, TLSHandshakeTimeout: cfg.Timeouts.TLSHandshake, ExpectContinueTimeout: cfg.Timeouts.ExpectContinue, ResponseHeaderTimeout: cfg.Timeouts.ResponseHeader, } return &http.Client{ Transport: tr, } }
31
session-manager-plugin
aws
Go
package main import ( "flag" "net/http" "time" ) // ClientConfig provides the timeouts from CLI flags and default values for the // example apps's configuration. type ClientConfig struct { KeepAlive bool Timeouts Timeouts } // SetupFlags initializes the CLI flags. func (c *ClientConfig) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "client." flagset.BoolVar(&c.KeepAlive, prefix+"http-keep-alive", true, "Specifies if HTTP keep alive is enabled.") c.Timeouts.SetupFlags(prefix, flagset) } // Timeouts collection of HTTP client timeout values. type Timeouts struct { IdleConnection time.Duration Connect time.Duration TLSHandshake time.Duration ExpectContinue time.Duration ResponseHeader time.Duration } // SetupFlags initializes the CLI flags. func (c *Timeouts) SetupFlags(prefix string, flagset *flag.FlagSet) { prefix += "timeout." flagset.DurationVar(&c.IdleConnection, prefix+"idle-conn", 90*time.Second, "The `timeout` of idle connects to the remote host.") flagset.DurationVar(&c.Connect, prefix+"connect", 30*time.Second, "The `timeout` connecting to the remote host.") defTR := http.DefaultTransport.(*http.Transport) flagset.DurationVar(&c.TLSHandshake, prefix+"tls", defTR.TLSHandshakeTimeout, "The `timeout` waiting for the TLS handshake to complete.") c.ExpectContinue = defTR.ExpectContinueTimeout flagset.DurationVar(&c.ResponseHeader, prefix+"response-header", defTR.ResponseHeaderTimeout, "The `timeout` waiting for the TLS handshake to complete.") }
55
session-manager-plugin
aws
Go
// build example package main import ( "fmt" "io" "os" "time" ) // RecordTrace outputs the request trace as text. func RecordTrace(w io.Writer, trace *RequestTrace) { attempt := AttemptReport{ Reused: trace.Reused, Latency: trace.Finish.Sub(trace.Start), ReqWritten: trace.RequestWritten.Sub(trace.Start), } if !trace.FirstResponseByte.IsZero() { attempt.RespFirstByte = trace.FirstResponseByte.Sub(trace.Start) attempt.WaitRespFirstByte = trace.FirstResponseByte.Sub(trace.RequestWritten) } if !trace.Reused { attempt.DNSStart = trace.DNSStart.Sub(trace.Start) attempt.DNSDone = trace.DNSDone.Sub(trace.Start) attempt.DNS = trace.DNSDone.Sub(trace.DNSStart) attempt.ConnectStart = trace.ConnectStart.Sub(trace.Start) attempt.ConnectDone = trace.ConnectDone.Sub(trace.Start) attempt.Connect = trace.ConnectDone.Sub(trace.ConnectStart) attempt.TLSHandshakeStart = trace.TLSHandshakeStart.Sub(trace.Start) attempt.TLSHandshakeDone = trace.TLSHandshakeDone.Sub(trace.Start) attempt.TLSHandshake = trace.TLSHandshakeDone.Sub(trace.TLSHandshakeStart) } _, err := fmt.Fprintln(w, "Latency:", attempt.Latency, "ConnectionReused:", fmt.Sprintf("%t", attempt.Reused), "DNSStartAt:", fmt.Sprintf("%s", attempt.DNSStart), "DNSDoneAt:", fmt.Sprintf("%s", attempt.DNSDone), "DNSDur:", fmt.Sprintf("%s", attempt.DNS), "ConnectStartAt:", fmt.Sprintf("%s", attempt.ConnectStart), "ConnectDoneAt:", fmt.Sprintf("%s", attempt.ConnectDone), "ConnectDur:", fmt.Sprintf("%s", attempt.Connect), "TLSStatAt:", fmt.Sprintf("%s", attempt.TLSHandshakeStart), "TLSDoneAt:", fmt.Sprintf("%s", attempt.TLSHandshakeDone), "TLSDur:", fmt.Sprintf("%s", attempt.TLSHandshake), "RequestWritten", fmt.Sprintf("%s", attempt.ReqWritten), "RespFirstByte:", fmt.Sprintf("%s", attempt.RespFirstByte), "WaitRespFirstByte:", fmt.Sprintf("%s", attempt.WaitRespFirstByte), ) if err != nil { fmt.Fprintf(os.Stderr, "failed to write request trace, %v\n", err) } } // AttemptReport proviedes the structured timing information. type AttemptReport struct { Latency time.Duration Reused bool Err error DNSStart time.Duration DNSDone time.Duration DNS time.Duration ConnectStart time.Duration ConnectDone time.Duration Connect time.Duration TLSHandshakeStart time.Duration TLSHandshakeDone time.Duration TLSHandshake time.Duration ReqWritten time.Duration RespFirstByte time.Duration WaitRespFirstByte time.Duration }
101
session-manager-plugin
aws
Go
// build example package main import ( "bufio" "context" "errors" "flag" "fmt" "log" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sns" ) var clientCfg ClientConfig var topicARN string func init() { clientCfg.SetupFlags("", flag.CommandLine) flag.CommandLine.StringVar(&topicARN, "topic", "", "The topic `ARN` to send messages to") } func main() { if err := flag.CommandLine.Parse(os.Args[1:]); err != nil { flag.CommandLine.PrintDefaults() exitErrorf(err, "failed to parse CLI commands") } if len(topicARN) == 0 { flag.CommandLine.PrintDefaults() exitErrorf(errors.New("topic ARN required"), "") } httpClient := NewClient(clientCfg) sess, err := session.NewSession(&aws.Config{ HTTPClient: httpClient, }) if err != nil { exitErrorf(err, "failed to load config") } // Start making the requests. svc := sns.New(sess) ctx := context.Background() fmt.Printf("Message: ") // Scan messages from the input with newline separators. scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { trace, err := publishMessage(ctx, svc, topicARN, scanner.Text()) if err != nil { fmt.Fprintf(os.Stderr, "failed to publish message, %v\n", err) } log.Println(trace) fmt.Println() fmt.Printf("Message: ") } if err := scanner.Err(); err != nil { fmt.Fprintf(os.Stderr, "failed to read input, %v", err) } } // publishMessage will send the message to the SNS topic returning an request // trace for metrics. func publishMessage(ctx context.Context, svc *sns.SNS, topic, msg string) (*RequestTrace, error) { trace := &RequestTrace{} _, err := svc.PublishWithContext(ctx, &sns.PublishInput{ TopicArn: &topic, Message: &msg, }, trace.TraceRequest) if err != nil { return trace, err } return trace, nil } func exitErrorf(err error, msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, "FAILED: %v\n"+msg+"\n", append([]interface{}{err}, args...)...) os.Exit(1) }
90
session-manager-plugin
aws
Go
package main import ( "bytes" "context" "crypto/tls" "fmt" "io" "io/ioutil" "net/http/httptrace" "strings" "time" "github.com/aws/aws-sdk-go/aws/request" ) // RequestLatency provides latencies for the SDK API request and its attempts. type RequestLatency struct { Latency time.Duration Validate time.Duration Build time.Duration Attempts []RequestAttemptLatency } // RequestAttemptLatency provides latencies for an individual request attempt. type RequestAttemptLatency struct { Latency time.Duration Err error Sign time.Duration Send time.Duration HTTP HTTPLatency Unmarshal time.Duration UnmarshalError time.Duration WillRetry bool Retry time.Duration } // HTTPLatency provides latencies for an HTTP request. type HTTPLatency struct { Latency time.Duration ConnReused bool GetConn time.Duration DNS time.Duration Connect time.Duration TLS time.Duration WriteHeader time.Duration WriteRequest time.Duration WaitResponseFirstByte time.Duration ReadHeader time.Duration ReadBody time.Duration } // RequestTrace provides the structure to store SDK request attempt latencies. // Use TraceRequest as a API operation request option to capture trace metrics // for the individual request. type RequestTrace struct { Start, Finish time.Time ValidateStart, ValidateDone time.Time BuildStart, BuildDone time.Time ReadResponseBody bool Attempts []*RequestAttemptTrace } // Latency returns the latencies of the request trace components. func (t RequestTrace) Latency() RequestLatency { var attempts []RequestAttemptLatency for _, a := range t.Attempts { attempts = append(attempts, a.Latency()) } latency := RequestLatency{ Latency: safeTimeDelta(t.Start, t.Finish), Validate: safeTimeDelta(t.ValidateStart, t.ValidateDone), Build: safeTimeDelta(t.BuildStart, t.BuildDone), Attempts: attempts, } return latency } // TraceRequest is a SDK request Option that will add request handlers to an // individual request to track request latencies per attempt. Must be used only // for a single request call per RequestTrace value. func (t *RequestTrace) TraceRequest(r *request.Request) { t.Start = time.Now() r.Handlers.Complete.PushBack(t.onComplete) r.Handlers.Validate.PushFront(t.onValidateStart) r.Handlers.Validate.PushBack(t.onValidateDone) r.Handlers.Build.PushFront(t.onBuildStart) r.Handlers.Build.PushBack(t.onBuildDone) var attempt *RequestAttemptTrace // Signing and Start attempt r.Handlers.Sign.PushFront(func(rr *request.Request) { attempt = &RequestAttemptTrace{Start: time.Now()} attempt.SignStart = attempt.Start }) r.Handlers.Sign.PushBack(func(rr *request.Request) { attempt.SignDone = time.Now() }) // Ensure that the http trace added to the request always uses the original // context instead of each following attempt's context to prevent conflict // with previous http traces used. origContext := r.Context() // Send r.Handlers.Send.PushFront(func(rr *request.Request) { attempt.SendStart = time.Now() attempt.HTTPTrace = NewHTTPTrace(origContext) rr.SetContext(attempt.HTTPTrace) }) r.Handlers.Send.PushBack(func(rr *request.Request) { attempt.SendDone = time.Now() defer func() { attempt.HTTPTrace.Finish = time.Now() }() if rr.Error != nil { return } attempt.HTTPTrace.ReadHeaderDone = time.Now() if t.ReadResponseBody { attempt.HTTPTrace.ReadBodyStart = time.Now() var w bytes.Buffer if _, err := io.Copy(&w, rr.HTTPResponse.Body); err != nil { rr.Error = err return } rr.HTTPResponse.Body.Close() rr.HTTPResponse.Body = ioutil.NopCloser(&w) attempt.HTTPTrace.ReadBodyDone = time.Now() } }) // Unmarshal r.Handlers.Unmarshal.PushFront(func(rr *request.Request) { attempt.UnmarshalStart = time.Now() }) r.Handlers.Unmarshal.PushBack(func(rr *request.Request) { attempt.UnmarshalDone = time.Now() }) // Unmarshal Error r.Handlers.UnmarshalError.PushFront(func(rr *request.Request) { attempt.UnmarshalErrorStart = time.Now() }) r.Handlers.UnmarshalError.PushBack(func(rr *request.Request) { attempt.UnmarshalErrorDone = time.Now() }) // Retry handling and delay r.Handlers.Retry.PushFront(func(rr *request.Request) { attempt.RetryStart = time.Now() attempt.Err = rr.Error }) r.Handlers.AfterRetry.PushBack(func(rr *request.Request) { attempt.RetryDone = time.Now() attempt.WillRetry = rr.WillRetry() }) // Complete Attempt r.Handlers.CompleteAttempt.PushBack(func(rr *request.Request) { attempt.Finish = time.Now() t.Attempts = append(t.Attempts, attempt) }) } func (t *RequestTrace) String() string { var w strings.Builder l := t.Latency() writeDurField(&w, "Latency", l.Latency) writeDurField(&w, "Validate", l.Validate) writeDurField(&w, "Build", l.Build) writeField(&w, "Attempts", "%d", len(t.Attempts)) for i, a := range t.Attempts { fmt.Fprintf(&w, "\n\tAttempt: %d, %s", i, a) } return w.String() } func (t *RequestTrace) onComplete(*request.Request) { t.Finish = time.Now() } func (t *RequestTrace) onValidateStart(*request.Request) { t.ValidateStart = time.Now() } func (t *RequestTrace) onValidateDone(*request.Request) { t.ValidateDone = time.Now() } func (t *RequestTrace) onBuildStart(*request.Request) { t.BuildStart = time.Now() } func (t *RequestTrace) onBuildDone(*request.Request) { t.BuildDone = time.Now() } // RequestAttemptTrace provides a structure for storing trace information on // the SDK's request attempt. type RequestAttemptTrace struct { Start, Finish time.Time Err error SignStart, SignDone time.Time SendStart, SendDone time.Time HTTPTrace *HTTPTrace UnmarshalStart, UnmarshalDone time.Time UnmarshalErrorStart, UnmarshalErrorDone time.Time WillRetry bool RetryStart, RetryDone time.Time } // Latency returns the latencies of the request attempt trace components. func (t *RequestAttemptTrace) Latency() RequestAttemptLatency { return RequestAttemptLatency{ Latency: safeTimeDelta(t.Start, t.Finish), Err: t.Err, Sign: safeTimeDelta(t.SignStart, t.SignDone), Send: safeTimeDelta(t.SendStart, t.SendDone), HTTP: t.HTTPTrace.Latency(), Unmarshal: safeTimeDelta(t.UnmarshalStart, t.UnmarshalDone), UnmarshalError: safeTimeDelta(t.UnmarshalErrorStart, t.UnmarshalErrorDone), WillRetry: t.WillRetry, Retry: safeTimeDelta(t.RetryStart, t.RetryDone), } } func (t *RequestAttemptTrace) String() string { var w strings.Builder l := t.Latency() writeDurField(&w, "Latency", l.Latency) writeDurField(&w, "Sign", l.Sign) writeDurField(&w, "Send", l.Send) writeDurField(&w, "Unmarshal", l.Unmarshal) writeDurField(&w, "UnmarshalError", l.UnmarshalError) writeField(&w, "WillRetry", "%t", l.WillRetry) writeDurField(&w, "Retry", l.Retry) fmt.Fprintf(&w, "\n\t\tHTTP: %s", t.HTTPTrace) if t.Err != nil { fmt.Fprintf(&w, "\n\t\tError: %v", t.Err) } return w.String() } // HTTPTrace provides the trace time stamps of the HTTP request's segments. type HTTPTrace struct { context.Context Start, Finish time.Time GetConnStart, GetConnDone time.Time Reused bool DNSStart, DNSDone time.Time ConnectStart, ConnectDone time.Time TLSHandshakeStart, TLSHandshakeDone time.Time WriteHeaderDone time.Time WriteRequestDone time.Time FirstResponseByte time.Time ReadHeaderStart, ReadHeaderDone time.Time ReadBodyStart, ReadBodyDone time.Time } // NewHTTPTrace returns a initialized HTTPTrace for an // httptrace.ClientTrace, based on the context passed. func NewHTTPTrace(ctx context.Context) *HTTPTrace { t := &HTTPTrace{ Start: time.Now(), } trace := &httptrace.ClientTrace{ GetConn: t.getConn, GotConn: t.gotConn, PutIdleConn: t.putIdleConn, GotFirstResponseByte: t.gotFirstResponseByte, Got100Continue: t.got100Continue, DNSStart: t.dnsStart, DNSDone: t.dnsDone, ConnectStart: t.connectStart, ConnectDone: t.connectDone, TLSHandshakeStart: t.tlsHandshakeStart, TLSHandshakeDone: t.tlsHandshakeDone, WroteHeaders: t.wroteHeaders, Wait100Continue: t.wait100Continue, WroteRequest: t.wroteRequest, } t.Context = httptrace.WithClientTrace(ctx, trace) return t } // Latency returns the latencies for an HTTP request. func (t *HTTPTrace) Latency() HTTPLatency { latency := HTTPLatency{ Latency: safeTimeDelta(t.Start, t.Finish), ConnReused: t.Reused, WriteHeader: safeTimeDelta(t.GetConnDone, t.WriteHeaderDone), WriteRequest: safeTimeDelta(t.GetConnDone, t.WriteRequestDone), WaitResponseFirstByte: safeTimeDelta(t.WriteRequestDone, t.FirstResponseByte), ReadHeader: safeTimeDelta(t.ReadHeaderStart, t.ReadHeaderDone), ReadBody: safeTimeDelta(t.ReadBodyStart, t.ReadBodyDone), } if !t.Reused { latency.GetConn = safeTimeDelta(t.GetConnStart, t.GetConnDone) latency.DNS = safeTimeDelta(t.DNSStart, t.DNSDone) latency.Connect = safeTimeDelta(t.ConnectStart, t.ConnectDone) latency.TLS = safeTimeDelta(t.TLSHandshakeStart, t.TLSHandshakeDone) } else { latency.GetConn = safeTimeDelta(t.Start, t.GetConnDone) } return latency } func (t *HTTPTrace) String() string { var w strings.Builder l := t.Latency() writeDurField(&w, "Latency", l.Latency) writeField(&w, "ConnReused", "%t", l.ConnReused) writeDurField(&w, "GetConn", l.GetConn) writeDurField(&w, "WriteHeader", l.WriteHeader) writeDurField(&w, "WriteRequest", l.WriteRequest) writeDurField(&w, "WaitResponseFirstByte", l.WaitResponseFirstByte) writeDurField(&w, "ReadHeader", l.ReadHeader) writeDurField(&w, "ReadBody", l.ReadBody) if !t.Reused { fmt.Fprintf(&w, "\n\t\t\tConn: ") writeDurField(&w, "DNS", l.DNS) writeDurField(&w, "Connect", l.Connect) writeDurField(&w, "TLS", l.TLS) } return w.String() } func (t *HTTPTrace) getConn(hostPort string) { t.GetConnStart = time.Now() } func (t *HTTPTrace) gotConn(info httptrace.GotConnInfo) { t.GetConnDone = time.Now() t.Reused = info.Reused } func (t *HTTPTrace) putIdleConn(err error) {} func (t *HTTPTrace) gotFirstResponseByte() { t.FirstResponseByte = time.Now() t.ReadHeaderStart = t.FirstResponseByte } func (t *HTTPTrace) got100Continue() {} func (t *HTTPTrace) dnsStart(info httptrace.DNSStartInfo) { t.DNSStart = time.Now() } func (t *HTTPTrace) dnsDone(info httptrace.DNSDoneInfo) { t.DNSDone = time.Now() } func (t *HTTPTrace) connectStart(network, addr string) { t.ConnectStart = time.Now() } func (t *HTTPTrace) connectDone(network, addr string, err error) { t.ConnectDone = time.Now() } func (t *HTTPTrace) tlsHandshakeStart() { t.TLSHandshakeStart = time.Now() } func (t *HTTPTrace) tlsHandshakeDone(state tls.ConnectionState, err error) { t.TLSHandshakeDone = time.Now() } func (t *HTTPTrace) wroteHeaders() { t.WriteHeaderDone = time.Now() } func (t *HTTPTrace) wait100Continue() {} func (t *HTTPTrace) wroteRequest(info httptrace.WroteRequestInfo) { t.WriteRequestDone = time.Now() } func safeTimeDelta(start, end time.Time) time.Duration { if start.IsZero() || end.IsZero() || start.After(end) { return 0 } return end.Sub(start) } func writeField(w io.Writer, field string, format string, args ...interface{}) error { _, err := fmt.Fprintf(w, "%s: "+format+", ", append([]interface{}{field}, args...)...) return err } func writeDurField(w io.Writer, field string, dur time.Duration) error { if dur == 0 { return nil } _, err := fmt.Fprintf(w, "%s: %s, ", field, dur) return err }
426
session-manager-plugin
aws
Go
// +build example,go1.7 package main import ( "context" "flag" "fmt" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) // Uploads a file to S3 given a bucket and object key. Also takes a duration // value to terminate the update if it doesn't complete within that time. // // The AWS Region needs to be provided in the AWS shared config or on the // environment variable as `AWS_REGION`. Credentials also must be provided // Will default to shared config file, but can load from environment if provided. // // Usage: // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt func main() { var bucket, key string var timeout time.Duration flag.StringVar(&bucket, "b", "", "Bucket name.") flag.StringVar(&key, "k", "", "Object key name.") flag.DurationVar(&timeout, "d", 0, "Upload timeout.") flag.Parse() sess := session.Must(session.NewSession()) svc := s3.New(sess) // Create a context with a timeout that will abort the upload if it takes // more than the passed in timeout. ctx := context.Background() var cancelFn func() if timeout > 0 { ctx, cancelFn = context.WithTimeout(ctx, timeout) } // Ensure the context is canceled to prevent leaking. // See context package for more information, https://golang.org/pkg/context/ defer cancelFn() // Uploads the object to S3. The Context will interrupt the request if the // timeout expires. _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), Body: os.Stdin, }) if err != nil { if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { // If the SDK can determine the request or retry delay was canceled // by a context the CanceledErrorCode error code will be returned. fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) } else { fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) } os.Exit(1) } fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) }
72
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "io/ioutil" "net/http" "time" "github.com/aws/aws-sdk-go/service/cloudfront/sign" ) // Makes a request for object using CloudFront cookie signing, and outputs // the contents of the object to stdout. // // Usage example: // signCookies -file <privkey file> -id <keyId> -r <resource pattern> -g <object to get> func main() { var keyFile string // Private key PEM file var keyID string // Key pair ID of CloudFront key pair var resource string // CloudFront resource pattern var object string // S3 object frontented by CloudFront flag.StringVar(&keyFile, "file", "", "private key file") flag.StringVar(&keyID, "id", "", "key pair id") flag.StringVar(&resource, "r", "", "resource to request") flag.StringVar(&object, "g", "", "object to get") flag.Parse() // Load the PEM file into memory so it can be used by the signer privKey, err := sign.LoadPEMPrivKeyFile(keyFile) if err != nil { fmt.Println("failed to load key,", err) return } // Create the new CookieSigner to get signed cookies for CloudFront // resource requests signer := sign.NewCookieSigner(keyID, privKey) // Get the cookies for the resource. These will be used // to make the requests with cookies, err := signer.Sign(resource, time.Now().Add(1*time.Hour)) if err != nil { fmt.Println("failed to sign cookies", err) return } // Use the cookies in a http.Client to show how they allow the client // to request resources from CloudFront. req, err := http.NewRequest("GET", object, nil) fmt.Println("Cookies:") for _, c := range cookies { fmt.Printf("%s=%s;\n", c.Name, c.Value) req.AddCookie(c) } // Send and handle the response. For a successful response the object's // content will be written to stdout. The same process could be applied // to a http service written cookies to the response but using // http.SetCookie(w, c,) on the ResponseWriter. resp, err := http.DefaultClient.Do(req) if err != nil { fmt.Println("failed to send request", err) return } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("failed to read requested body", err) return } fmt.Println("Response:", resp.Status) fmt.Println(string(b)) }
80
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/expression" ) func exitWithError(err error) { fmt.Fprintln(os.Stderr, err) os.Exit(1) } func main() { cfg := Config{} if err := cfg.Load(); err != nil { exitWithError(fmt.Errorf("failed to load config, %v", err)) } // Create the config specifying the Region for the DynamoDB table. // If Config.Region is not set the region must come from the shared // config or AWS_REGION environment variable. awscfg := &aws.Config{} if len(cfg.Region) > 0 { awscfg.WithRegion(cfg.Region) } // Create the session that the DynamoDB service will use. sess := session.Must(session.NewSession(awscfg)) // Create the DynamoDB service client to make the query request with. svc := dynamodb.New(sess) // Create the Expression to fill the input struct with. filt := expression.Name("Artist").Equal(expression.Value("No One You Know")) proj := expression.NamesList(expression.Name("SongTitle"), expression.Name("AlbumTitle")) expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() if err != nil { exitWithError(fmt.Errorf("failed to create the Expression, %v", err)) } // Build the query input parameters params := &dynamodb.ScanInput{ ExpressionAttributeNames: expr.Names(), ExpressionAttributeValues: expr.Values(), FilterExpression: expr.Filter(), ProjectionExpression: expr.Projection(), TableName: aws.String(cfg.Table), } if cfg.Limit > 0 { params.Limit = aws.Int64(cfg.Limit) } // Make the DynamoDB Query API call result, err := svc.Scan(params) if err != nil { exitWithError(fmt.Errorf("failed to make Query API call, %v", err)) } fmt.Println(result) } type Config struct { Table string // required Region string // optional Limit int64 // optional } func (c *Config) Load() error { flag.Int64Var(&c.Limit, "limit", 0, "Limit is the max items to be returned, 0 is no limit") flag.StringVar(&c.Table, "table", "", "Table to Query on") flag.StringVar(&c.Region, "region", "", "AWS Region the table is in") flag.Parse() if len(c.Table) == 0 { flag.PrintDefaults() return fmt.Errorf("table name is required.") } return nil }
89
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) func exitWithError(err error) { fmt.Fprintln(os.Stderr, err) os.Exit(1) } func main() { cfg := Config{} if err := cfg.Load(); err != nil { exitWithError(fmt.Errorf("failed to load config, %v", err)) } // Create the config specifying the Region for the DynamoDB table. // If Config.Region is not set the region must come from the shared // config or AWS_REGION environment variable. awscfg := &aws.Config{} if len(cfg.Region) > 0 { awscfg.WithRegion(cfg.Region) } // Create the session that the DynamoDB service will use. sess := session.Must(session.NewSession(awscfg)) // Create the DynamoDB service client to make the query request with. svc := dynamodb.New(sess) // Build the query input parameters params := &dynamodb.ScanInput{ TableName: aws.String(cfg.Table), } if cfg.Limit > 0 { params.Limit = aws.Int64(cfg.Limit) } // Make the DynamoDB Query API call result, err := svc.Scan(params) if err != nil { exitWithError(fmt.Errorf("failed to make Query API call, %v", err)) } items := []Item{} // Unmarshal the Items field in the result value to the Item Go type. err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &items) if err != nil { exitWithError(fmt.Errorf("failed to unmarshal Query result items, %v", err)) } // Print out the items returned for i, item := range items { fmt.Printf("%d: Key: %d, Desc: %s\n", i, item.Key, item.Desc) fmt.Printf("\tNum Data Values: %d\n", len(item.Data)) for k, v := range item.Data { fmt.Printf("\t- %q: %v\n", k, v) } } } type Item struct { Key int Desc string Data map[string]interface{} } type Config struct { Table string // required Region string // optional Limit int64 // optional } func (c *Config) Load() error { flag.Int64Var(&c.Limit, "limit", 0, "Limit is the max items to be returned, 0 is no limit") flag.StringVar(&c.Table, "table", "", "Table to Query on") flag.StringVar(&c.Region, "region", "", "AWS Region the table is in") flag.Parse() if len(c.Table) == 0 { flag.PrintDefaults() return fmt.Errorf("table name is required.") } return nil }
99
session-manager-plugin
aws
Go
// +build example // Package unitTest demonstrates how to unit test, without needing to pass a // connector to every function, code that uses DynamoDB. package unitTest import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) // ItemGetter can be assigned a DynamoDB connector like: // svc := dynamodb.DynamoDB(sess) // getter.DynamoDB = dynamodbiface.DynamoDBAPI(svc) type ItemGetter struct { DynamoDB dynamodbiface.DynamoDBAPI } // Get a value from a DynamoDB table containing entries like: // {"id": "my primary key", "value": "valuable value"} func (ig *ItemGetter) Get(id string) (value string) { var input = &dynamodb.GetItemInput{ Key: map[string]*dynamodb.AttributeValue{ "id": { S: aws.String(id), }, }, TableName: aws.String("my_table"), AttributesToGet: []*string{ aws.String("value"), }, } if output, err := ig.DynamoDB.GetItem(input); err == nil { if _, ok := output.Item["value"]; ok { dynamodbattribute.Unmarshal(output.Item["value"], &value) } } return }
42
session-manager-plugin
aws
Go
// +build example // Unit tests for package unitTest. package unitTest import ( "errors" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) // A fakeDynamoDB instance. During testing, instatiate ItemGetter, then simply // assign an instance of fakeDynamoDB to it. type fakeDynamoDB struct { dynamodbiface.DynamoDBAPI payload map[string]string // Store expected return values err error } // Mock GetItem such that the output returned carries values identical to input. func (fd *fakeDynamoDB) GetItem(input *dynamodb.GetItemInput) (*dynamodb.GetItemOutput, error) { output := new(dynamodb.GetItemOutput) output.Item = make(map[string]*dynamodb.AttributeValue) for key, value := range fd.payload { output.Item[key] = &dynamodb.AttributeValue{ S: aws.String(value), } } return output, fd.err } func TestItemGetterGet(t *testing.T) { expectedKey := "expected key" expectedValue := "expected value" getter := new(ItemGetter) getter.DynamoDB = &fakeDynamoDB{ payload: map[string]string{"id": expectedKey, "value": expectedValue}, } if actualValue := getter.Get(expectedKey); actualValue != expectedValue { t.Errorf("Expected %q but got %q", expectedValue, actualValue) } } // When DynamoDB.GetItem returns a non-nil error, expect an empty string. func TestItemGetterGetFail(t *testing.T) { expectedKey := "expected key" expectedValue := "expected value" getter := new(ItemGetter) getter.DynamoDB = &fakeDynamoDB{ payload: map[string]string{"id": expectedKey, "value": expectedValue}, err: errors.New("any error"), } if actualValue := getter.Get(expectedKey); len(actualValue) > 0 { t.Errorf("Expected %q but got %q", expectedValue, actualValue) } }
60
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "log" "os" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" ) // This example will list instances with a filter // // Usage: // filter_ec2_by_tag <name_filter> func main() { sess := session.Must(session.NewSession()) nameFilter := os.Args[1] awsRegion := "us-east-1" svc := ec2.New(sess, &aws.Config{Region: aws.String(awsRegion)}) fmt.Printf("listing instances with tag %v in: %v\n", nameFilter, awsRegion) params := &ec2.DescribeInstancesInput{ Filters: []*ec2.Filter{ { Name: aws.String("tag:Name"), Values: []*string{ aws.String(strings.Join([]string{"*", nameFilter, "*"}, "")), }, }, }, } resp, err := svc.DescribeInstances(params) if err != nil { fmt.Println("there was an error listing instances in", awsRegion, err.Error()) log.Fatal(err.Error()) } fmt.Printf("%+v\n", *resp) }
44
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "os" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" ) // Prints a list of instances for each region. If no regions are provided // all regions will be searched. The state is required. // // Will use the AWS SDK for Go's default credential chain and region. You can // specify the region with the AWS_REGION environment variable. // // Usage: instancesByRegion -state <value> [-state val...] [-region region...] func main() { states, regions := parseArguments() if len(states) == 0 { fmt.Fprintf(os.Stderr, "error: %v\n", usage()) os.Exit(1) } instanceCriteria := " " for _, state := range states { instanceCriteria += "[" + state + "]" } if len(regions) == 0 { var err error regions, err = fetchRegion() if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } } for _, region := range regions { sess := session.Must(session.NewSession(&aws.Config{ Region: aws.String(region), })) ec2Svc := ec2.New(sess) params := &ec2.DescribeInstancesInput{ Filters: []*ec2.Filter{ { Name: aws.String("instance-state-name"), Values: aws.StringSlice(states), }, }, } result, err := ec2Svc.DescribeInstances(params) if err != nil { fmt.Println("Error", err) } else { fmt.Printf("\n\n\nFetching instance details for region: %s with criteria: %s**\n ", region, instanceCriteria) if len(result.Reservations) == 0 { fmt.Printf("There is no instance for the region: %s with the matching criteria:%s \n", region, instanceCriteria) } for _, reservation := range result.Reservations { fmt.Println("printing instance details.....") for _, instance := range reservation.Instances { fmt.Println("instance id " + *instance.InstanceId) fmt.Println("current State " + *instance.State.Name) } } fmt.Printf("done for region %s **** \n", region) } } } func fetchRegion() ([]string, error) { awsSession := session.Must(session.NewSession(&aws.Config{})) svc := ec2.New(awsSession) awsRegions, err := svc.DescribeRegions(&ec2.DescribeRegionsInput{}) if err != nil { return nil, err } regions := make([]string, 0, len(awsRegions.Regions)) for _, region := range awsRegions.Regions { regions = append(regions, *region.RegionName) } return regions, nil } type flagArgs []string func (a flagArgs) String() string { return strings.Join(a.Args(), ",") } func (a *flagArgs) Set(value string) error { *a = append(*a, value) return nil } func (a flagArgs) Args() []string { return []string(a) } func parseArguments() (states []string, regions []string) { var stateArgs, regionArgs flagArgs flag.Var(&stateArgs, "state", "state list") flag.Var(&regionArgs, "region", "region list") flag.Parse() if flag.NFlag() != 0 { states = append([]string{}, stateArgs.Args()...) regions = append([]string{}, regionArgs.Args()...) } return states, regions } func usage() string { return ` Missing mandatory flag 'state'. Please use like below Example: To fetch the stopped instance of all region use below: ./filter_ec2_by_region -state running -state stopped To fetch the stopped and running instance for region us-west-1 and eu-west-1 use below: ./filter_ec2_by_region -state running -state stopped -region us-west-1 -region=eu-west-1 ` }
138
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ecr" ) const DEFAULT_AWS_REGION = "us-east-1" // This example creates a new ECR Repository // // Usage: // AWS_REGION=us-east-1 go run -tags example createECRRepository.go <repo_name> func main() { config := &aws.Config{Region: aws.String(getAwsRegion())} svc := ecr.New(session.New(), config) repoName := getRepoNameArg() if repoName == "" { printUsageAndExit1() } input := &ecr.CreateRepositoryInput{ RepositoryName: aws.String(repoName), } output, err := svc.CreateRepository(input) if err != nil { fmt.Printf("\nError creating the repo %v in region %v\n%v\n", repoName, aws.StringValue(config.Region), err.Error()) os.Exit(1) } fmt.Printf("\nECR Repository \"%v\" created successfully!\n\nAWS Output:\n%v", repoName, output) } // Print correct usage and exit the program with code 1 func printUsageAndExit1() { fmt.Println("\nUsage: AWS_REGION=us-east-1 go run -tags example createECRRepository.go <repo_name>") os.Exit(1) } // Try get the repo name from the first argument func getRepoNameArg() string { if len(os.Args) < 2 { return "" } firstArg := os.Args[1] return firstArg } // Returns the aws region from env var or default region defined in DEFAULT_AWS_REGION constant func getAwsRegion() string { awsRegion := os.Getenv("AWS_REGION") if awsRegion != "" { return awsRegion } return DEFAULT_AWS_REGION }
65
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ecr" ) const DEFAULT_AWS_REGION = "us-east-1" // This example deletes an ECR Repository // // Usage: // AWS_REGION=us-east-1 go run -tags example deleteECRRepository.go <repo_name> func main() { config := &aws.Config{Region: aws.String(getAwsRegion())} svc := ecr.New(session.New(), config) repoName := getRepoNameArg() if repoName == "" { printUsageAndExit1() } input := &ecr.DeleteRepositoryInput{ Force: aws.Bool(false), RepositoryName: aws.String(repoName), } output, err := svc.DeleteRepository(input) if err != nil { fmt.Printf("\nError deleting the repo %v in region %v\n%v\n", repoName, aws.StringValue(config.Region), err.Error()) os.Exit(1) } fmt.Printf("\nECR Repository \"%v\" deleted successfully!\n\nAWS Output:\n%v", repoName, output) } // Print correct usage and exit the program with code 1 func printUsageAndExit1() { fmt.Println("\nUsage: AWS_REGION=us-east-1 go run -tags example deleteECRRepository.go <repo_name>") os.Exit(1) } // Try get the repo name from the first argument func getRepoNameArg() string { if len(os.Args) < 2 { return "" } firstArg := os.Args[1] return firstArg } // Returns the aws region from env var or default region defined in DEFAULT_AWS_REGION constant func getAwsRegion() string { awsRegion := os.Getenv("AWS_REGION") if awsRegion != "" { return awsRegion } return DEFAULT_AWS_REGION }
66
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "io" "log" "math/rand" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/mediastore" "github.com/aws/aws-sdk-go/service/mediastoredata" ) func main() { containerName := os.Args[1] objectPath := os.Args[2] // Create the SDK's session, and a AWS Elemental MediaStore Data client. sess := session.Must(session.NewSession()) dataSvc, err := getMediaStoreDataClient(containerName, sess) if err != nil { log.Fatalf("failed to create client, %v", err) } // Create a random reader to simulate a unseekable reader, wrap the reader // in an io.LimitReader to prevent uploading forever. randReader := rand.New(rand.NewSource(0)) reader := io.LimitReader(randReader, 1024*1024 /* 1MB */) // Wrap the unseekable reader with the SDK's RandSeekCloser. This type will // allow the SDK's to use the nonseekable reader. body := aws.ReadSeekCloser(reader) // make the PutObject API call with the nonseekable reader, causing the SDK // to send the request body payload as chunked transfer encoding. _, err = dataSvc.PutObject(&mediastoredata.PutObjectInput{ Path: &objectPath, Body: body, }) if err != nil { log.Fatalf("failed to upload object, %v", err) } fmt.Println("object uploaded") } // getMediaStoreDataClient uses the AWS Elemental MediaStore API to get the // endpoint for a container. If the container endpoint can be retrieved a AWS // Elemental MediaStore Data client will be created and returned. Otherwise // error is returned. func getMediaStoreDataClient(containerName string, sess *session.Session) (*mediastoredata.MediaStoreData, error) { endpoint, err := containerEndpoint(containerName, sess) if err != nil { return nil, err } dataSvc := mediastoredata.New(sess, &aws.Config{ Endpoint: endpoint, }) return dataSvc, nil } // ContainerEndpoint will attempt to get the endpoint for a container, // returning error if the container doesn't exist, or is not active within a // timeout. func containerEndpoint(name string, sess *session.Session) (*string, error) { for i := 0; i < 3; i++ { ctrlSvc := mediastore.New(sess) descResp, err := ctrlSvc.DescribeContainer(&mediastore.DescribeContainerInput{ ContainerName: &name, }) if err != nil { return nil, err } if status := aws.StringValue(descResp.Container.Status); status != "ACTIVE" { log.Println("waiting for container to be active, ", status) time.Sleep(10 * time.Second) continue } return descResp.Container.Endpoint, nil } return nil, fmt.Errorf("container is not active") }
93
session-manager-plugin
aws
Go
// +build example,skip package main import ( "database/sql" "database/sql/driver" "fmt" "log" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/rds/rdsutils" ) type stubDriver struct{} func (sd stubDriver) Open(name string) (driver.Conn, error) { return nil, nil } // Usage ./iam_authentication <region> <db user> <db name> <endpoint to database> <iam arn> func main() { if len(os.Args) < 5 { log.Println("USAGE ERROR: go run concatenateObjects.go <region> <endpoint to database> <iam arn>") os.Exit(1) } awsRegion := os.Args[1] dbUser := os.Args[2] dbName := os.Args[3] dbEndpoint := os.Args[4] awsCreds := stscreds.NewCredentials(session.New(&aws.Config{Region: &awsRegion}), os.Args[5]) authToken, err := rdsutils.BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds) // Create the MySQL DNS string for the DB connection // user:password@protocol(endpoint)/dbname?<params> dnsStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true", dbUser, authToken, dbEndpoint, dbName, ) const driverName = "stubSql" sql.Register(driverName, &stubDriver{}) // Use db to perform SQL operations on database if _, err = sql.Open(driverName, dnsStr); err != nil { panic(err) } fmt.Println("Successfully opened connection to database") }
53
session-manager-plugin
aws
Go
// +build example package main import ( "log" "net/url" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) type client struct { s3Client *s3.S3 bucket *string } // concatenate will contenate key1's object to key2's object under the key testKey func (c *client) concatenate(key1, key2, key3 string, uploadID *string) (*string, *string, error) { // The first part to be uploaded which is represented as part number 1 foo, err := c.s3Client.UploadPartCopy(&s3.UploadPartCopyInput{ Bucket: c.bucket, CopySource: aws.String(url.QueryEscape(*c.bucket + "/" + key1)), PartNumber: aws.Int64(1), Key: &key3, UploadId: uploadID, }) if err != nil { return nil, nil, err } // The second part that is going to be appended to the newly created testKey // object. bar, err := c.s3Client.UploadPartCopy(&s3.UploadPartCopyInput{ Bucket: c.bucket, CopySource: aws.String(url.QueryEscape(*c.bucket + "/" + key2)), PartNumber: aws.Int64(2), Key: &key3, UploadId: uploadID, }) if err != nil { return nil, nil, err } // The ETags are needed to complete the process return foo.CopyPartResult.ETag, bar.CopyPartResult.ETag, nil } func main() { if len(os.Args) < 4 { log.Println("USAGE ERROR: AWS_REGION=us-east-1 go run concatenateObjects.go <bucket> <key for object 1> <key for object 2> <key for output>") return } bucket := os.Args[1] key1 := os.Args[2] key2 := os.Args[3] key3 := os.Args[4] sess := session.New(&aws.Config{}) svc := s3.New(sess) c := client{svc, &bucket} // We let the service know that we want to do a multipart upload output, err := c.s3Client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{ Bucket: &bucket, Key: &key3, }) if err != nil { log.Println("ERROR:", err) return } foo, bar, err := c.concatenate(key1, key2, key3, output.UploadId) if err != nil { log.Println("ERROR:", err) return } // We finally complete the multipart upload. _, err = c.s3Client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{ Bucket: &bucket, Key: &key3, UploadId: output.UploadId, MultipartUpload: &s3.CompletedMultipartUpload{ Parts: []*s3.CompletedPart{ { ETag: foo, PartNumber: aws.Int64(1), }, { ETag: bar, PartNumber: aws.Int64(2), }, }, }, }) if err != nil { log.Println("ERROR:", err) return } }
105
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "io" "io/ioutil" "log" "os" "strings" "sync/atomic" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // progressWriter tracks the download progress of a file from S3 to a file // as the writeAt method is called, the byte size is added to the written total, // and then a log is printed of the written percentage from the total size // it looks like this on the command line: // 2019/02/22 12:59:15 File size:35943530 downloaded:16360 percentage:0% // 2019/02/22 12:59:15 File size:35943530 downloaded:16988 percentage:0% // 2019/02/22 12:59:15 File size:35943530 downloaded:33348 percentage:0% type progressWriter struct { written int64 writer io.WriterAt size int64 } func (pw *progressWriter) WriteAt(p []byte, off int64) (int, error) { atomic.AddInt64(&pw.written, int64(len(p))) percentageDownloaded := float32(pw.written*100) / float32(pw.size) fmt.Printf("File size:%d downloaded:%d percentage:%.2f%%\r", pw.size, pw.written, percentageDownloaded) return pw.writer.WriteAt(p, off) } func byteCountDecimal(b int64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) } func getFileSize(svc *s3.S3, bucket string, prefix string) (filesize int64, error error) { params := &s3.HeadObjectInput{ Bucket: aws.String(bucket), Key: aws.String(prefix), } resp, err := svc.HeadObject(params) if err != nil { return 0, err } return *resp.ContentLength, nil } func parseFilename(keyString string) (filename string) { ss := strings.Split(keyString, "/") s := ss[len(ss)-1] return s } func main() { if len(os.Args) < 2 { log.Println("USAGE ERROR: AWS_REGION=us-east-1 go run getObjWithProgress.go bucket-name object-key") return } bucket := os.Args[1] key := os.Args[2] filename := parseFilename(key) sess, err := session.NewSession() if err != nil { panic(err) } s3Client := s3.New(sess) downloader := s3manager.NewDownloader(sess) size, err := getFileSize(s3Client, bucket, key) if err != nil { panic(err) } log.Println("Starting download, size:", byteCountDecimal(size)) cwd, err := os.Getwd() if err != nil { panic(err) } temp, err := ioutil.TempFile(cwd, "getObjWithProgress-tmp-") if err != nil { panic(err) } tempfileName := temp.Name() writer := &progressWriter{writer: temp, size: size, written: 0} params := &s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), } if _, err := downloader.Download(writer, params); err != nil { log.Printf("Download failed! Deleting tempfile: %s", tempfileName) os.Remove(tempfileName) panic(err) } if err := temp.Close(); err != nil { panic(err) } if err := os.Rename(temp.Name(), filename); err != nil { panic(err) } fmt.Println() log.Println("File downloaded! Available at:", filename) }
134
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) // Lists all objects in a bucket using pagination // // Usage: // listObjects <bucket> func main() { if len(os.Args) < 2 { fmt.Println("you must specify a bucket") return } sess := session.Must(session.NewSession()) svc := s3.New(sess) i := 0 err := svc.ListObjectsPages(&s3.ListObjectsInput{ Bucket: &os.Args[1], }, func(p *s3.ListObjectsOutput, last bool) (shouldContinue bool) { fmt.Println("Page,", i) i++ for _, obj := range p.Contents { fmt.Println("Object:", *obj.Key) } return true }) if err != nil { fmt.Println("failed to list objects", err) return } }
44
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "os" "sort" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) func exit(msg ...interface{}) { fmt.Fprintln(os.Stderr, msg...) os.Exit(1) } // Lists all encrypted objects owned by an account. The `accounts` string // contains a list of profiles to use. // // Usage: // listObjectsConcurrentlv func main() { accounts := []string{"default", "default2", "otherprofile"} // Spin off a worker for each account to retrieve that account's bucketCh := make(chan *Bucket, 5) var wg sync.WaitGroup for _, acc := range accounts { wg.Add(1) go func(acc string) { defer wg.Done() sess, err := session.NewSessionWithOptions(session.Options{ Profile: acc, }) if err != nil { fmt.Fprintf(os.Stderr, "failed to create session for account, %s, %v\n", acc, err) return } if err = getAccountBuckets(sess, bucketCh, acc); err != nil { fmt.Fprintf(os.Stderr, "failed to get account %s's bucket info, %v\n", acc, err) } }(acc) } // Spin off a goroutine which will wait until all account buckets have been collected and // added to the bucketCh. Close the bucketCh so the for range below will exit once all // bucket info is printed. go func() { wg.Wait() close(bucketCh) }() // Receive from the bucket channel printing the information for each bucket to the console // when the bucketCh channel is drained. buckets := []*Bucket{} for b := range bucketCh { buckets = append(buckets, b) } sortBuckets(buckets) for _, b := range buckets { if b.Error != nil { fmt.Printf("Bucket %s, owned by: %s, failed: %v\n", b.Name, b.Owner, b.Error) continue } encObjs := b.encryptedObjects() fmt.Printf("Bucket: %s, owned by: %s, total objects: %d, failed objects: %d, encrypted objects: %d\n", b.Name, b.Owner, len(b.Objects), len(b.ErrObjects), len(encObjs)) if len(encObjs) > 0 { for _, encObj := range encObjs { fmt.Printf("\t%s %s:%s/%s\n", encObj.EncryptionType, b.Region, b.Name, encObj.Key) } } } } func sortBuckets(buckets []*Bucket) { s := sortalbeBuckets(buckets) sort.Sort(s) } type sortalbeBuckets []*Bucket func (s sortalbeBuckets) Len() int { return len(s) } func (s sortalbeBuckets) Swap(a, b int) { s[a], s[b] = s[b], s[a] } func (s sortalbeBuckets) Less(a, b int) bool { if s[a].Owner == s[b].Owner && s[a].Name < s[b].Name { return true } if s[a].Owner < s[b].Owner { return true } return false } func getAccountBuckets(sess *session.Session, bucketCh chan<- *Bucket, owner string) error { svc := s3.New(sess) buckets, err := listBuckets(svc) if err != nil { return fmt.Errorf("failed to list buckets, %v", err) } for _, bucket := range buckets { bucket.Owner = owner if bucket.Error != nil { continue } bckSvc := s3.New(sess, &aws.Config{ Region: aws.String(bucket.Region), Credentials: svc.Config.Credentials, }) bucketDetails(bckSvc, bucket) bucketCh <- bucket } return nil } func bucketDetails(svc *s3.S3, bucket *Bucket) { objs, errObjs, err := listBucketObjects(svc, bucket.Name) if err != nil { bucket.Error = err } else { bucket.Objects = objs bucket.ErrObjects = errObjs } } // A Object provides details of an S3 object type Object struct { Bucket string Key string Encrypted bool EncryptionType string } // An ErrObject provides details of the error occurred retrieving // an object's status. type ErrObject struct { Bucket string Key string Error error } // A Bucket provides details about a bucket and its objects type Bucket struct { Owner string Name string CreationDate time.Time Region string Objects []Object Error error ErrObjects []ErrObject } func (b *Bucket) encryptedObjects() []Object { encObjs := []Object{} for _, obj := range b.Objects { if obj.Encrypted { encObjs = append(encObjs, obj) } } return encObjs } func listBuckets(svc *s3.S3) ([]*Bucket, error) { res, err := svc.ListBuckets(&s3.ListBucketsInput{}) if err != nil { return nil, err } buckets := make([]*Bucket, len(res.Buckets)) for i, b := range res.Buckets { buckets[i] = &Bucket{ Name: *b.Name, CreationDate: *b.CreationDate, } locRes, err := svc.GetBucketLocation(&s3.GetBucketLocationInput{ Bucket: b.Name, }) if err != nil { buckets[i].Error = err continue } if locRes.LocationConstraint == nil { buckets[i].Region = "us-east-1" } else { buckets[i].Region = *locRes.LocationConstraint } } return buckets, nil } func listBucketObjects(svc *s3.S3, bucket string) ([]Object, []ErrObject, error) { listRes, err := svc.ListObjects(&s3.ListObjectsInput{ Bucket: &bucket, }) if err != nil { return nil, nil, err } objs := make([]Object, 0, len(listRes.Contents)) errObjs := []ErrObject{} for _, listObj := range listRes.Contents { objData, err := svc.HeadObject(&s3.HeadObjectInput{ Bucket: &bucket, Key: listObj.Key, }) if err != nil { errObjs = append(errObjs, ErrObject{Bucket: bucket, Key: *listObj.Key, Error: err}) continue } obj := Object{Bucket: bucket, Key: *listObj.Key} if objData.ServerSideEncryption != nil { obj.Encrypted = true obj.EncryptionType = *objData.ServerSideEncryption } objs = append(objs, obj) } return objs, errObjs, nil }
237
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "io" "log" "os" "runtime/debug" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // Usage: // go run -tags example <bucket> <key> <file to upload> // // Example: // AWS_REGION=us-west-2 AWS_PROFILE=default go run . "mybucket" "10MB.file" ./10MB.file func main() { sess, err := session.NewSession() if err != nil { log.Fatalf("failed to load session, %v", err) } uploader := s3manager.NewUploader(sess) file, err := os.Open(os.Args[3]) if err != nil { log.Fatalf("failed to open file, %v", err) } defer file.Close() // Wrap the readSeeker with a logger that will log usage, and stack traces // on errors. readLogger := NewReadLogger(file, sess.Config.Logger) // Upload with read logger resp, err := uploader.Upload(&s3manager.UploadInput{ Bucket: &os.Args[1], Key: &os.Args[2], Body: readLogger, }, func(u *s3manager.Uploader) { u.Concurrency = 1 u.RequestOptions = append(u.RequestOptions, func(r *request.Request) { }) }) fmt.Println(resp, err) } // Logger is a logger use for logging the readers usage. type Logger interface { Log(args ...interface{}) } // ReadSeeker interface provides the interface for a Reader, Seeker, and ReadAt. type ReadSeeker interface { io.ReadSeeker io.ReaderAt } // ReadLogger wraps an reader with logging for access. type ReadLogger struct { reader ReadSeeker logger Logger } // NewReadLogger a ReadLogger that wraps the passed in ReadSeeker (Reader, // Seeker, ReadAt) with a logger. func NewReadLogger(r ReadSeeker, logger Logger) *ReadLogger { return &ReadLogger{ reader: r, logger: logger, } } // Seek offsets the reader's current position for the next read. func (s *ReadLogger) Seek(offset int64, mode int) (int64, error) { newOffset, err := s.reader.Seek(offset, mode) msg := fmt.Sprintf( "ReadLogger.Seek(offset:%d, mode:%d) (newOffset:%d, err:%v)", offset, mode, newOffset, err) if err != nil { msg += fmt.Sprintf("\n\tStack:\n%s", string(debug.Stack())) } s.logger.Log(msg) return newOffset, err } // Read attempts to read from the reader, returning the bytes read, or error. func (s *ReadLogger) Read(b []byte) (int, error) { n, err := s.reader.Read(b) msg := fmt.Sprintf( "ReadLogger.Read(len(bytes):%d) (read:%d, err:%v)", len(b), n, err) if err != nil { msg += fmt.Sprintf("\n\tStack:\n%s", string(debug.Stack())) } s.logger.Log(msg) return n, err } // ReadAt will read the underlying reader starting at the offset. func (s *ReadLogger) ReadAt(b []byte, offset int64) (int, error) { n, err := s.reader.ReadAt(b, offset) msg := fmt.Sprintf( "ReadLogger.ReadAt(len(bytes):%d, offset:%d) (read:%d, err:%v)", len(b), offset, n, err) if err != nil { msg += fmt.Sprintf("\n\tStack:\n%s", string(debug.Stack())) } s.logger.Log(msg) return n, err }
121
session-manager-plugin
aws
Go
// +build example package main import ( "bytes" "encoding/json" "flag" "fmt" "io" "io/ioutil" "net/http" "os" "strconv" "strings" ) // client.go is an example of a client that will request URLs from a service that // the client will use to upload and download content with. // // The server must be started before the client is run. // // Use "--help" command line argument flag to see all options and defaults. If // filename is not provided the client will read from stdin for uploads and // write to stdout for downloads. // // Usage: // go run -tags example client.go -get myObjectKey -f filename func main() { method, filename, key, serverURL := loadConfig() var err error switch method { case GetMethod: // Requests the URL from the server that the client will use to download // the content from. The content will be written to the file pointed to // by filename. Creating it if the file does not exist. If filename is // not set the contents will be written to stdout. err = downloadFile(serverURL, key, filename) case PutMethod: // Requests the URL from the service that the client will use to upload // content to. The content will be read from the file pointed to by the // filename. If the filename is not set, content will be read from stdin. err = uploadFile(serverURL, key, filename) } if err != nil { exitError(err) } } // loadConfig configures the client based on the command line arguments used. func loadConfig() (method Method, serverURL, key, filename string) { var getKey, putKey string flag.StringVar(&getKey, "get", "", "Downloads the object from S3 by the `key`. Writes the object to a file the filename is provided, otherwise writes to stdout.") flag.StringVar(&putKey, "put", "", "Uploads data to S3 at the `key` provided. Uploads the file if filename is provided, otherwise reads from stdin.") flag.StringVar(&serverURL, "s", "http://127.0.0.1:8080", "Required `URL` the client will request presigned S3 operation from.") flag.StringVar(&filename, "f", "", "The `filename` of the file to upload and get from S3.") flag.Parse() var errs Errors if len(serverURL) == 0 { errs = append(errs, fmt.Errorf("server URL required")) } if !((len(getKey) != 0) != (len(putKey) != 0)) { errs = append(errs, fmt.Errorf("either `get` or `put` can be provided, and one of the two is required.")) } if len(getKey) > 0 { method = GetMethod key = getKey } else { method = PutMethod key = putKey } if len(errs) > 0 { fmt.Fprintf(os.Stderr, "Failed to load configuration:%v\n", errs) flag.PrintDefaults() os.Exit(1) } return method, filename, key, serverURL } // downloadFile will request a URL from the server that the client can download // the content pointed to by "key". The content will be written to the file // pointed to by filename, creating the file if it doesn't exist. If filename // is not set the content will be written to stdout. func downloadFile(serverURL, key, filename string) error { var w *os.File if len(filename) > 0 { f, err := os.Create(filename) if err != nil { return fmt.Errorf("failed to create download file %s, %v", filename, err) } w = f } else { w = os.Stdout } defer w.Close() // Get the presigned URL from the remote service. req, err := getPresignedRequest(serverURL, "GET", key, 0) if err != nil { return fmt.Errorf("failed to get get presigned request, %v", err) } // Gets the file contents with the URL provided by the service. resp, err := http.DefaultClient.Do(req) if err != nil { return fmt.Errorf("failed to do GET request, %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("failed to get S3 object, %d:%s", resp.StatusCode, resp.Status) } if _, err = io.Copy(w, resp.Body); err != nil { return fmt.Errorf("failed to write S3 object, %v", err) } return nil } // uploadFile will request a URL from the service that the client can use to // upload content to. The content will be read from the file pointed to by filename. // If filename is not set the content will be read from stdin. func uploadFile(serverURL, key, filename string) error { var r io.ReadCloser var size int64 if len(filename) > 0 { f, err := os.Open(filename) if err != nil { return fmt.Errorf("failed to open upload file %s, %v", filename, err) } // Get the size of the file so that the constraint of Content-Length // can be included with the presigned URL. This can be used by the // server or client to ensure the content uploaded is of a certain size. // // These constraints can further be expanded to include things like // Content-Type. Additionally constraints such as X-Amz-Content-Sha256 // header set restricting the content of the file to only the content // the client initially made the request with. This prevents the object // from being overwritten or used to upload other unintended content. stat, err := f.Stat() if err != nil { return fmt.Errorf("failed to stat file, %s, %v", filename, err) } size = stat.Size() r = f } else { buf := &bytes.Buffer{} io.Copy(buf, os.Stdin) size = int64(buf.Len()) r = ioutil.NopCloser(buf) } defer r.Close() // Get the Presigned URL from the remote service. Pass in the file's // size if it is known so that the presigned URL returned will be required // to be used with the size of content requested. req, err := getPresignedRequest(serverURL, "PUT", key, size) if err != nil { return fmt.Errorf("failed to get put presigned request, %v", err) } req.Body = r // Upload the file contents to S3. resp, err := http.DefaultClient.Do(req) if err != nil { return fmt.Errorf("failed to do PUT request, %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("failed to put S3 object, %d:%s", resp.StatusCode, resp.Status) } return nil } // getPresignRequest will request a URL from the service for the content specified // by the key and method. Returns a constructed Request that can be used to // upload or download content with based on the method used. // // If the PUT method is used the request's Body will need to be set on the returned // request value. func getPresignedRequest(serverURL, method, key string, contentLen int64) (*http.Request, error) { u := fmt.Sprintf("%s/presign/%s?method=%s&contentLength=%d", serverURL, key, method, contentLen, ) resp, err := http.Get(u) if err != nil { return nil, fmt.Errorf("failed to make request for presigned URL, %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("failed to get valid presign response, %s", resp.Status) } p := PresignResp{} if err := json.NewDecoder(resp.Body).Decode(&p); err != nil { return nil, fmt.Errorf("failed to decode response body, %v", err) } req, err := http.NewRequest(p.Method, p.URL, nil) if err != nil { return nil, fmt.Errorf("failed to build presigned request, %v", err) } for k, vs := range p.Header { for _, v := range vs { req.Header.Add(k, v) } } // Need to ensure that the content length member is set of the HTTP Request // or the request will not be transmitted correctly with a content length // value across the wire. if contLen := req.Header.Get("Content-Length"); len(contLen) > 0 { req.ContentLength, _ = strconv.ParseInt(contLen, 10, 64) } return req, nil } type Method int const ( PutMethod Method = iota GetMethod ) type Errors []error func (es Errors) Error() string { out := make([]string, len(es)) for _, e := range es { out = append(out, e.Error()) } return strings.Join(out, "\n") } type PresignResp struct { Method, URL string Header http.Header } func exitError(err error) { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) }
267
session-manager-plugin
aws
Go
// +build example package main import ( "encoding/json" "flag" "fmt" "net" "net/http" "os" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3iface" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // server.go is an example of a service that vends lists for requests for presigned // URLs for S3 objects. The service supports two S3 operations, "GetObject" and // "PutObject". // // Example GetObject request to the service for the object with the key "MyObjectKey": // // curl -v "http://127.0.0.1:8080/presign/my-object/key?method=GET" // // Example PutObject request to the service for the object with the key "MyObjectKey": // // curl -v "http://127.0.0.1:8080/presign/my-object/key?method=PUT&contentLength=1024" // // Use "--help" command line argument flag to see all options and defaults. // // Usage: // go run -tags example service.go -b myBucket func main() { addr, bucket, region := loadConfig() // Create a AWS SDK for Go Session that will load credentials using the SDK's // default credential change. sess := session.Must(session.NewSession()) // Use the GetBucketRegion utility to lookup the bucket's region automatically. // The service.go will only do this correctly for AWS regions. For AWS China // and AWS Gov Cloud the region needs to be specified to let the service know // to look in those partitions instead of AWS. if len(region) == 0 { var err error region, err = s3manager.GetBucketRegion(aws.BackgroundContext(), sess, bucket, endpoints.UsWest2RegionID) if err != nil { exitError(fmt.Errorf("failed to get bucket region, %v", err)) } } // Create a new S3 service client that will be use by the service to generate // presigned URLs with. Not actual API requests will be made with this client. // The credentials loaded when the Session was created above will be used // to sign the requests with. s3Svc := s3.New(sess, &aws.Config{ Region: aws.String(region), }) // Start the server listening and serve presigned URLs for GetObject and // PutObject requests. if err := listenAndServe(addr, bucket, s3Svc); err != nil { exitError(err) } } func loadConfig() (addr, bucket, region string) { flag.StringVar(&bucket, "b", "", "S3 `bucket` object should be uploaded to.") flag.StringVar(&region, "r", "", "AWS `region` the bucket exists in, If not set region will be looked up, only valid for AWS Regions, not AWS China or Gov Cloud.") flag.StringVar(&addr, "a", "127.0.0.1:8080", "The TCP `address` the server will be started on.") flag.Parse() if len(bucket) == 0 { fmt.Fprintln(os.Stderr, "bucket is required") flag.PrintDefaults() os.Exit(1) } return addr, bucket, region } func listenAndServe(addr, bucket string, svc s3iface.S3API) error { l, err := net.Listen("tcp", addr) if err != nil { return fmt.Errorf("failed to start service listener, %v", err) } const presignPath = "/presign/" // Create the HTTP handler for the "/presign/" path prefix. This will handle // all requests on this path, extracting the object's key from the path. http.HandleFunc(presignPath, func(w http.ResponseWriter, r *http.Request) { var u string var err error var signedHeaders http.Header query := r.URL.Query() var contentLen int64 // Optionally the Content-Length header can be included with the signature // of the request. This is helpful to ensure the content uploaded is the // size that is expected. Constraints like these can be further expanded // with headers such as `Content-Type`. These can be enforced by the service // requiring the client to satisfying those constraints when uploading // // In addition the client could provide the service with a SHA256 of the // content to be uploaded. This prevents any other third party from uploading // anything else with the presigned URL if contLenStr := query.Get("contentLength"); len(contLenStr) > 0 { contentLen, err = strconv.ParseInt(contLenStr, 10, 64) if err != nil { fmt.Fprintf(os.Stderr, "unable to parse request content length, %v", err) http.Error(w, err.Error(), http.StatusBadRequest) return } } // Extract the object key from the path key := strings.Replace(r.URL.Path, presignPath, "", 1) method := query.Get("method") switch method { case "PUT": // For creating PutObject presigned URLs fmt.Println("Received request to presign PutObject for,", key) sdkReq, _ := svc.PutObjectRequest(&s3.PutObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), // If ContentLength is 0 the header will not be included in the signature. ContentLength: aws.Int64(contentLen), }) u, signedHeaders, err = sdkReq.PresignRequest(15 * time.Minute) case "GET": // For creating GetObject presigned URLs fmt.Println("Received request to presign GetObject for,", key) sdkReq, _ := svc.GetObjectRequest(&s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), }) u, signedHeaders, err = sdkReq.PresignRequest(15 * time.Minute) default: fmt.Fprintf(os.Stderr, "invalid method provided, %s, %v\n", method, err) err = fmt.Errorf("invalid request") } if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Create the response back to the client with the information on the // presigned request and additional headers to include. if err := json.NewEncoder(w).Encode(PresignResp{ Method: method, URL: u, Header: signedHeaders, }); err != nil { fmt.Fprintf(os.Stderr, "failed to encode presign response, %v", err) } }) fmt.Println("Starting Server On:", "http://"+l.Addr().String()) s := &http.Server{} return s.Serve(l) } // PresignResp provides the Go representation of the JSON value that will be // sent to the client. type PresignResp struct { Method, URL string Header http.Header } func exitError(err error) { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) }
187
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) // Put an ACL on an S3 object // // Usage: // putBucketAcl <params> // -region <region> // required // -bucket <bucket> // required // -key <key> // required // -owner-name <owner-name> // -owner-id <owner-id> // -grantee-type <some type> // required // -uri <uri to group> // -email <email address> // -user-id <user-id> func main() { regionPtr := flag.String("region", "", "region of your request") bucketPtr := flag.String("bucket", "", "name of your bucket") keyPtr := flag.String("key", "", "of your object") ownerNamePtr := flag.String("owner-name", "", "of your request") ownerIDPtr := flag.String("owner-id", "", "of your request") granteeTypePtr := flag.String("grantee-type", "", "of your request") uriPtr := flag.String("uri", "", "of your grantee type") emailPtr := flag.String("email", "", "of your grantee type") userPtr := flag.String("user-id", "", "of your grantee type") displayNamePtr := flag.String("display-name", "", "of your grantee type") flag.Parse() // Based off the type, fields must be excluded. switch *granteeTypePtr { case s3.TypeCanonicalUser: emailPtr, uriPtr = nil, nil if *displayNamePtr == "" { displayNamePtr = nil } if *userPtr == "" { userPtr = nil } case s3.TypeAmazonCustomerByEmail: uriPtr, userPtr = nil, nil case s3.TypeGroup: emailPtr, userPtr = nil, nil } sess := session.Must(session.NewSession(&aws.Config{ Region: regionPtr, })) svc := s3.New(sess) resp, err := svc.PutObjectAcl(&s3.PutObjectAclInput{ Bucket: bucketPtr, Key: keyPtr, AccessControlPolicy: &s3.AccessControlPolicy{ Owner: &s3.Owner{ DisplayName: ownerNamePtr, ID: ownerIDPtr, }, Grants: []*s3.Grant{ { Grantee: &s3.Grantee{ Type: granteeTypePtr, DisplayName: displayNamePtr, URI: uriPtr, EmailAddress: emailPtr, ID: userPtr, }, Permission: aws.String(s3.BucketLogsPermissionFullControl), }, }, }, }) if err != nil { fmt.Println("failed", err) } else { fmt.Println("success", resp) } }
92
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "log" "os" "sync" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) type CustomReader struct { fp *os.File size int64 read int64 signMap map[int64]struct{} mux sync.Mutex } func (r *CustomReader) Read(p []byte) (int, error) { return r.fp.Read(p) } func (r *CustomReader) ReadAt(p []byte, off int64) (int, error) { n, err := r.fp.ReadAt(p, off) if err != nil { return n, err } r.mux.Lock() // Ignore the first signature call if _, ok := r.signMap[off]; ok { // Got the length have read( or means has uploaded), and you can construct your message r.read += int64(n) fmt.Printf("\rtotal read:%d progress:%d%%", r.read, int(float32(r.read*100)/float32(r.size))) } else { r.signMap[off] = struct{}{} } r.mux.Unlock() return n, err } func (r *CustomReader) Seek(offset int64, whence int) (int64, error) { return r.fp.Seek(offset, whence) } func main() { if len(os.Args) < 4 { log.Println("USAGE ERROR: AWS_REGION=us-west-2 go run -tags example putObjWithProcess.go <bucket> <key for object> <local file name>") return } bucket := os.Args[1] key := os.Args[2] filename := os.Args[3] sess, err := session.NewSession() if err != nil { log.Fatalf("failed to load session, %v", err) } file, err := os.Open(filename) if err != nil { log.Fatalf("failed to open file %v, %v", filename, err) } fileInfo, err := file.Stat() if err != nil { log.Fatalf("failed to stat file %v, %v", filename, err) return } reader := &CustomReader{ fp: file, size: fileInfo.Size(), signMap: map[int64]struct{}{}, } uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = 5 * 1024 * 1024 u.LeavePartsOnError = true }) output, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String(bucket), Key: aws.String(key), Body: reader, }) if err != nil { log.Fatalf("failed to put file %v, %v", filename, err) return } fmt.Println() log.Println(output.Location) }
101
session-manager-plugin
aws
Go
// +build example package main import ( "flag" "fmt" "mime" "os" "path/filepath" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // SyncFolderIterator is used to upload a given folder // to Amazon S3. type SyncFolderIterator struct { bucket string fileInfos []fileInfo err error } type fileInfo struct { key string fullpath string } // NewSyncFolderIterator will walk the path, and store the key and full path // of the object to be uploaded. This will return a new SyncFolderIterator // with the data provided from walking the path. func NewSyncFolderIterator(path, bucket string) *SyncFolderIterator { metadata := []fileInfo{} filepath.Walk(path, func(p string, info os.FileInfo, err error) error { if !info.IsDir() { key := strings.TrimPrefix(p, path) metadata = append(metadata, fileInfo{key, p}) } return nil }) return &SyncFolderIterator{ bucket, metadata, nil, } } // Next will determine whether or not there is any remaining files to // be uploaded. func (iter *SyncFolderIterator) Next() bool { return len(iter.fileInfos) > 0 } // Err returns any error when os.Open is called. func (iter *SyncFolderIterator) Err() error { return iter.err } // UploadObject will prep the new upload object by open that file and constructing a new // s3manager.UploadInput. func (iter *SyncFolderIterator) UploadObject() s3manager.BatchUploadObject { fi := iter.fileInfos[0] iter.fileInfos = iter.fileInfos[1:] body, err := os.Open(fi.fullpath) if err != nil { iter.err = err } extension := filepath.Ext(fi.key) mimeType := mime.TypeByExtension(extension) if mimeType == "" { mimeType = "binary/octet-stream" } input := s3manager.UploadInput{ Bucket: &iter.bucket, Key: &fi.key, Body: body, ContentType: &mimeType, } return s3manager.BatchUploadObject{ Object: &input, } } // Upload a directory to a given bucket // // Usage: // sync <params> // -region <region> // required // -bucket <bucket> // required // -path <path> // required func main() { bucketPtr := flag.String("bucket", "", "bucket to upload to") regionPtr := flag.String("region", "", "region to be used when making requests") pathPtr := flag.String("path", "", "path of directory to be synced") flag.Parse() sess := session.New(&aws.Config{ Region: regionPtr, }) uploader := s3manager.NewUploader(sess) iter := NewSyncFolderIterator(*pathPtr, *bucketPtr) if err := uploader.UploadWithIterator(aws.BackgroundContext(), iter); err != nil { fmt.Fprintf(os.Stderr, "unexpected error has occurred: %v", err) } if err := iter.Err(); err != nil { fmt.Fprintf(os.Stderr, "unexpected error occurred during file walking: %v", err) } fmt.Println("Success") }
121
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "io/ioutil" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3control" ) const ( bucketName = "myBucketName" keyName = "myKeyName" accountID = "123456789012" accessPoint = "accesspointname" ) func main() { sess := session.Must(session.NewSession()) s3Svc := s3.New(sess) s3ControlSvc := s3control.New(sess) // Create an S3 Bucket fmt.Println("create s3 bucket") _, err := s3Svc.CreateBucket(&s3.CreateBucketInput{ Bucket: aws.String(bucketName), }) if err != nil { panic(fmt.Errorf("failed to create bucket: %v", err)) } // Wait for S3 Bucket to Exist fmt.Println("wait for s3 bucket to exist") err = s3Svc.WaitUntilBucketExists(&s3.HeadBucketInput{ Bucket: aws.String(bucketName), }) if err != nil { panic(fmt.Sprintf("bucket failed to materialize: %v", err)) } // Create an Access Point referring to the bucket fmt.Println("create an access point") _, err = s3ControlSvc.CreateAccessPoint(&s3control.CreateAccessPointInput{ AccountId: aws.String(accountID), Bucket: aws.String(bucketName), Name: aws.String(accessPoint), }) if err != nil { panic(fmt.Sprintf("failed to create access point: %v", err)) } // Use the SDK's ARN builder to create an ARN for the Access Point. apARN := arn.ARN{ Partition: "aws", Service: "s3", Region: aws.StringValue(sess.Config.Region), AccountID: accountID, Resource: "accesspoint/" + accessPoint, } // And Use Access Point ARN where bucket parameters are accepted fmt.Println("get object using access point") getObjectOutput, err := s3Svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String(apARN.String()), Key: aws.String("somekey"), }) if err != nil { panic(fmt.Sprintf("failed get object request: %v", err)) } _, err = ioutil.ReadAll(getObjectOutput.Body) if err != nil { panic(fmt.Sprintf("failed to read object body: %v", err)) } }
82
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "io/ioutil" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3control" ) const ( bucketName = "myBucketName" keyName = "myKeyName" accountID = "123456789012" accessPoint = "accesspointname" // vpcBucketEndpoint will be used by the SDK to resolve an endpoint, when making a call to // access `bucket` data using s3 interface endpoint. This endpoint may be mutated by the SDK, // as per the input provided to work with ARNs. vpcBucketEndpoint = "https://bucket.vpce-0xxxxxxx-xxx8xxg.s3.us-west-2.vpce.amazonaws.com" // vpcAccesspointEndpoint will be used by the SDK to resolve an endpoint, when making a call to // access `access-point` data using s3 interface endpoint. This endpoint may be mutated by the SDK, // as per the input provided to work with ARNs. vpcAccesspointEndpoint = "https://accesspoint.vpce-0xxxxxxx-xxx8xxg.s3.us-west-2.vpce.amazonaws.com" // vpcControlEndpoint will be used by the SDK to resolve an endpoint, when making a call to // access `control` data using s3 interface endpoint. This endpoint may be mutated by the SDK, // as per the input provided to work with ARNs. vpcControlEndpoint = "https://control.vpce-0xxxxxxx-xxx8xxg.s3.us-west-2.vpce.amazonaws.com" ) func main() { sess := session.Must(session.NewSession()) s3BucketSvc := s3.New(sess, &aws.Config{ Endpoint: aws.String(vpcBucketEndpoint), }) s3AccesspointSvc := s3.New(sess, &aws.Config{ Endpoint: aws.String(vpcAccesspointEndpoint), }) s3ControlSvc := s3control.New(sess, &aws.Config{ Endpoint: aws.String(vpcControlEndpoint), }) // Create an S3 Bucket fmt.Println("create s3 bucket") _, err := s3BucketSvc.CreateBucket(&s3.CreateBucketInput{ Bucket: aws.String(bucketName), }) if err != nil { panic(fmt.Errorf("failed to create bucket: %v", err)) } // Wait for S3 Bucket to Exist fmt.Println("wait for s3 bucket to exist") err = s3BucketSvc.WaitUntilBucketExists(&s3.HeadBucketInput{ Bucket: aws.String(bucketName), }) if err != nil { panic(fmt.Sprintf("bucket failed to materialize: %v", err)) } // Create an Access Point referring to the bucket fmt.Println("create an access point") _, err = s3ControlSvc.CreateAccessPoint(&s3control.CreateAccessPointInput{ AccountId: aws.String(accountID), Bucket: aws.String(bucketName), Name: aws.String(accessPoint), }) if err != nil { panic(fmt.Sprintf("failed to create access point: %v", err)) } // Use the SDK's ARN builder to create an ARN for the Access Point. apARN := arn.ARN{ Partition: "aws", Service: "s3", Region: aws.StringValue(sess.Config.Region), AccountID: accountID, Resource: "accesspoint/" + accessPoint, } // And Use Access Point ARN where bucket parameters are accepted fmt.Println("get object using access point") getObjectOutput, err := s3AccesspointSvc.GetObject(&s3.GetObjectInput{ Bucket: aws.String(apARN.String()), Key: aws.String("somekey"), }) if err != nil { panic(fmt.Sprintf("failed get object request: %v", err)) } _, err = ioutil.ReadAll(getObjectOutput.Body) if err != nil { panic(fmt.Sprintf("failed to read object body: %v", err)) } }
106
session-manager-plugin
aws
Go
// +build example package main import ( "encoding/json" "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/sqs/sqsiface" ) func main() { if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "Queue URL required.") os.Exit(1) } sess := session.Must(session.NewSession()) q := Queue{ Client: sqs.New(sess), URL: os.Args[1], } msgs, err := q.GetMessages(20) if err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } fmt.Println("Messages:") for _, msg := range msgs { fmt.Printf("%s>%s: %s\n", msg.From, msg.To, msg.Msg) } } // Queue provides the ability to handle SQS messages. type Queue struct { Client sqsiface.SQSAPI URL string } // Message is a concrete representation of the SQS message type Message struct { From string `json:"from"` To string `json:"to"` Msg string `json:"msg"` } // GetMessages returns the parsed messages from SQS if any. If an error // occurs that error will be returned. func (q *Queue) GetMessages(waitTimeout int64) ([]Message, error) { params := sqs.ReceiveMessageInput{ QueueUrl: aws.String(q.URL), } if waitTimeout > 0 { params.WaitTimeSeconds = aws.Int64(waitTimeout) } resp, err := q.Client.ReceiveMessage(&params) if err != nil { return nil, fmt.Errorf("failed to get messages, %v", err) } msgs := make([]Message, len(resp.Messages)) for i, msg := range resp.Messages { parsedMsg := Message{} if err := json.Unmarshal([]byte(aws.StringValue(msg.Body)), &parsedMsg); err != nil { return nil, fmt.Errorf("failed to unmarshal message, %v", err) } msgs[i] = parsedMsg } return msgs, nil }
80
session-manager-plugin
aws
Go
// +build example package main import ( "fmt" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/sqs/sqsiface" ) type mockedReceiveMsgs struct { sqsiface.SQSAPI Resp sqs.ReceiveMessageOutput } func (m mockedReceiveMsgs) ReceiveMessage(in *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error) { // Only need to return mocked response output return &m.Resp, nil } func TestQueueGetMessage(t *testing.T) { cases := []struct { Resp sqs.ReceiveMessageOutput Expected []Message }{ { // Case 1, expect parsed responses Resp: sqs.ReceiveMessageOutput{ Messages: []*sqs.Message{ {Body: aws.String(`{"from":"user_1","to":"room_1","msg":"Hello!"}`)}, {Body: aws.String(`{"from":"user_2","to":"room_1","msg":"Hi user_1 :)"}`)}, }, }, Expected: []Message{ {From: "user_1", To: "room_1", Msg: "Hello!"}, {From: "user_2", To: "room_1", Msg: "Hi user_1 :)"}, }, }, { // Case 2, not messages returned Resp: sqs.ReceiveMessageOutput{}, Expected: []Message{}, }, } for i, c := range cases { q := Queue{ Client: mockedReceiveMsgs{Resp: c.Resp}, URL: fmt.Sprintf("mockURL_%d", i), } msgs, err := q.GetMessages(20) if err != nil { t.Fatalf("%d, unexpected error, %v", i, err) } if a, e := len(msgs), len(c.Expected); a != e { t.Fatalf("%d, expected %d messages, got %d", i, e, a) } for j, msg := range msgs { if a, e := msg, c.Expected[j]; a != e { t.Errorf("%d, expected %v message, got %v", i, e, a) } } } }
66
session-manager-plugin
aws
Go
// +build !go1.7 package context import "time" // An emptyCtx is a copy of the Go 1.7 context.emptyCtx type. This is copied to // provide a 1.6 and 1.5 safe version of context that is compatible with Go // 1.7's Context. // // An emptyCtx is never canceled, has no values, and has no deadline. It is not // struct{}, since vars of this type must have distinct addresses. type emptyCtx int func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { return } func (*emptyCtx) Done() <-chan struct{} { return nil } func (*emptyCtx) Err() error { return nil } func (*emptyCtx) Value(key interface{}) interface{} { return nil } func (e *emptyCtx) String() string { switch e { case BackgroundCtx: return "aws.BackgroundContext" } return "unknown empty Context" } // BackgroundCtx is the common base context. var BackgroundCtx = new(emptyCtx)
41
session-manager-plugin
aws
Go
package ini // ASTKind represents different states in the parse table // and the type of AST that is being constructed type ASTKind int // ASTKind* is used in the parse table to transition between // the different states const ( ASTKindNone = ASTKind(iota) ASTKindStart ASTKindExpr ASTKindEqualExpr ASTKindStatement ASTKindSkipStatement ASTKindExprStatement ASTKindSectionStatement ASTKindNestedSectionStatement ASTKindCompletedNestedSectionStatement ASTKindCommentStatement ASTKindCompletedSectionStatement ) func (k ASTKind) String() string { switch k { case ASTKindNone: return "none" case ASTKindStart: return "start" case ASTKindExpr: return "expr" case ASTKindStatement: return "stmt" case ASTKindSectionStatement: return "section_stmt" case ASTKindExprStatement: return "expr_stmt" case ASTKindCommentStatement: return "comment" case ASTKindNestedSectionStatement: return "nested_section_stmt" case ASTKindCompletedSectionStatement: return "completed_stmt" case ASTKindSkipStatement: return "skip" default: return "" } } // AST interface allows us to determine what kind of node we // are on and casting may not need to be necessary. // // The root is always the first node in Children type AST struct { Kind ASTKind Root Token RootToken bool Children []AST } func newAST(kind ASTKind, root AST, children ...AST) AST { return AST{ Kind: kind, Children: append([]AST{root}, children...), } } func newASTWithRootToken(kind ASTKind, root Token, children ...AST) AST { return AST{ Kind: kind, Root: root, RootToken: true, Children: children, } } // AppendChild will append to the list of children an AST has. func (a *AST) AppendChild(child AST) { a.Children = append(a.Children, child) } // GetRoot will return the root AST which can be the first entry // in the children list or a token. func (a *AST) GetRoot() AST { if a.RootToken { return *a } if len(a.Children) == 0 { return AST{} } return a.Children[0] } // GetChildren will return the current AST's list of children func (a *AST) GetChildren() []AST { if len(a.Children) == 0 { return []AST{} } if a.RootToken { return a.Children } return a.Children[1:] } // SetChildren will set and override all children of the AST. func (a *AST) SetChildren(children []AST) { if a.RootToken { a.Children = children } else { a.Children = append(a.Children[:1], children...) } } // Start is used to indicate the starting state of the parse table. var Start = newAST(ASTKindStart, AST{})
121
session-manager-plugin
aws
Go
package ini import ( "testing" ) const ( section = `[default] region = us-west-2 credential_source = Ec2InstanceMetadata s3 = foo=bar bar=baz output = json [assumerole] output = json region = us-west-2 ` ) func BenchmarkINIParser(b *testing.B) { for i := 0; i < b.N; i++ { ParseBytes([]byte(section)) } } func BenchmarkTokenize(b *testing.B) { lexer := iniLexer{} for i := 0; i < b.N; i++ { lexer.tokenize([]byte(section)) } }
34
session-manager-plugin
aws
Go
package ini var commaRunes = []rune(",") func isComma(b rune) bool { return b == ',' } func newCommaToken() Token { return newToken(TokenComma, commaRunes, NoneType) }
12
session-manager-plugin
aws
Go
package ini // isComment will return whether or not the next byte(s) is a // comment. func isComment(b []rune) bool { if len(b) == 0 { return false } switch b[0] { case ';': return true case '#': return true } return false } // newCommentToken will create a comment token and // return how many bytes were read. func newCommentToken(b []rune) (Token, int, error) { i := 0 for ; i < len(b); i++ { if b[i] == '\n' { break } if len(b)-i > 2 && b[i] == '\r' && b[i+1] == '\n' { break } } return newToken(TokenComment, b[:i], NoneType), i, nil }
36