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
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package session starts the session. package session import ( "encoding/json" "errors" "fmt" "io" "os" "time" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/session-manager-plugin/src/datachannel" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/retry" "github.com/aws/session-manager-plugin/src/sdkutil" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/sessionutil" "github.com/aws/session-manager-plugin/src/version" "github.com/twinj/uuid" ) const ( LegacyArgumentLength = 4 ArgumentLength = 7 StartSessionOperation = "StartSession" VersionFile = "VERSION" ) var SessionRegistry = map[string]ISessionPlugin{} type ISessionPlugin interface { SetSessionHandlers(log.T) error ProcessStreamMessagePayload(log log.T, streamDataMessage message.ClientMessage) (isHandlerReady bool, err error) Initialize(log log.T, sessionVar *Session) Stop() Name() string } type ISession interface { Execute(log.T) error OpenDataChannel(log.T) error ProcessFirstMessage(log log.T, outputMessage message.ClientMessage) (isHandlerReady bool, err error) Stop() GetResumeSessionParams(log.T) (string, error) ResumeSessionHandler(log.T) error TerminateSession(log.T) error } func init() { SessionRegistry = make(map[string]ISessionPlugin) } func Register(session ISessionPlugin) { SessionRegistry[session.Name()] = session } type Session struct { DataChannel datachannel.IDataChannel SessionId string StreamUrl string TokenValue string IsAwsCliUpgradeNeeded bool Endpoint string ClientId string TargetId string sdk *ssm.SSM retryParams retry.RepeatableExponentialRetryer SessionType string SessionProperties interface{} DisplayMode sessionutil.DisplayMode } //startSession create the datachannel for session var startSession = func(session *Session, log log.T) error { return session.Execute(log) } //setSessionHandlersWithSessionType set session handlers based on session subtype var setSessionHandlersWithSessionType = func(session *Session, log log.T) error { // SessionType is set inside DataChannel sessionSubType := SessionRegistry[session.SessionType] sessionSubType.Initialize(log, session) return sessionSubType.SetSessionHandlers(log) } // Set up a scheduler to listen on stream data resend timeout event var handleStreamMessageResendTimeout = func(session *Session, log log.T) { log.Tracef("Setting up scheduler to listen on IsStreamMessageResendTimeout event.") go func() { for { // Repeat this loop for every 200ms time.Sleep(config.ResendSleepInterval) if <-session.DataChannel.IsStreamMessageResendTimeout() { log.Errorf("Terminating session %s as the stream data was not processed before timeout.", session.SessionId) if err := session.TerminateSession(log); err != nil { log.Errorf("Unable to terminate session upon stream data timeout. %v", err) } return } } }() } // ValidateInputAndStartSession validates input sent from AWS CLI and starts a session if validation is successful. // AWS CLI sends input in the order of // args[0] will be path of executable (ignored) // args[1] is session response // args[2] is client region // args[3] is operation name // args[4] is profile name from aws credentials/config files // args[5] is parameters input to aws cli for StartSession api // args[6] is endpoint for ssm service func ValidateInputAndStartSession(args []string, out io.Writer) { var ( err error session Session startSessionOutput ssm.StartSessionOutput response []byte region string operationName string profile string ssmEndpoint string target string ) log := log.Logger(true, "session-manager-plugin") uuid.SwitchFormat(uuid.CleanHyphen) if len(args) == 1 { fmt.Fprint(out, "\nThe Session Manager plugin was installed successfully. "+ "Use the AWS CLI to start a session.\n\n") return } else if len(args) == 2 && args[1] == "--version" { fmt.Fprintf(out, "%s\n", string(version.Version)) return } else if len(args) >= 2 && len(args) < LegacyArgumentLength { fmt.Fprintf(out, "\nUnknown operation %s. \nUse "+ "session-manager-plugin --version to check the version.\n\n", string(args[1])) return } else if len(args) == LegacyArgumentLength { // If arguments do not have Profile passed from AWS CLI to Session-Manager-Plugin then // should be upgraded to use Session Manager encryption feature session.IsAwsCliUpgradeNeeded = true } for argsIndex := 1; argsIndex < len(args); argsIndex++ { switch argsIndex { case 1: response = []byte(args[1]) case 2: region = args[2] case 3: operationName = args[3] case 4: profile = args[4] case 5: // args[5] is parameters input to aws cli for StartSession api call startSessionRequest := make(map[string]interface{}) json.Unmarshal([]byte(args[5]), &startSessionRequest) target = startSessionRequest["Target"].(string) case 6: ssmEndpoint = args[6] } } sdkutil.SetRegionAndProfile(region, profile) clientId := uuid.NewV4().String() switch operationName { case StartSessionOperation: if err = json.Unmarshal(response, &startSessionOutput); err != nil { log.Errorf("Cannot perform start session: %v", err) fmt.Fprintf(out, "Cannot perform start session: %v\n", err) return } session.SessionId = *startSessionOutput.SessionId session.StreamUrl = *startSessionOutput.StreamUrl session.TokenValue = *startSessionOutput.TokenValue session.Endpoint = ssmEndpoint session.ClientId = clientId session.TargetId = target session.DataChannel = &datachannel.DataChannel{} default: fmt.Fprint(out, "Invalid Operation") return } if err = startSession(&session, log); err != nil { log.Errorf("Cannot perform start session: %v", err) fmt.Fprintf(out, "Cannot perform start session: %v\n", err) return } } //Execute create data channel and start the session func (s *Session) Execute(log log.T) (err error) { fmt.Fprintf(os.Stdout, "\nStarting session with SessionId: %s\n", s.SessionId) // sets the display mode s.DisplayMode = sessionutil.NewDisplayMode(log) if err = s.OpenDataChannel(log); err != nil { log.Errorf("Error in Opening data channel: %v", err) return } handleStreamMessageResendTimeout(s, log) // The session type is set either by handshake or the first packet received. if !<-s.DataChannel.IsSessionTypeSet() { log.Errorf("unable to set SessionType for session %s", s.SessionId) return errors.New("unable to determine SessionType") } else { s.SessionType = s.DataChannel.GetSessionType() s.SessionProperties = s.DataChannel.GetSessionProperties() if err = setSessionHandlersWithSessionType(s, log); err != nil { log.Errorf("Session ending with error: %v", err) return } } return }
241
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package session starts the session. package session import ( "fmt" "math/rand" "os" sdkSession "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/retry" "github.com/aws/session-manager-plugin/src/sdkutil" ) // OpenDataChannel initializes datachannel func (s *Session) OpenDataChannel(log log.T) (err error) { s.retryParams = retry.RepeatableExponentialRetryer{ GeometricRatio: config.RetryBase, InitialDelayInMilli: rand.Intn(config.DataChannelRetryInitialDelayMillis) + config.DataChannelRetryInitialDelayMillis, MaxDelayInMilli: config.DataChannelRetryMaxIntervalMillis, MaxAttempts: config.DataChannelNumMaxRetries, } s.DataChannel.Initialize(log, s.ClientId, s.SessionId, s.TargetId, s.IsAwsCliUpgradeNeeded) s.DataChannel.SetWebsocket(log, s.StreamUrl, s.TokenValue) s.DataChannel.GetWsChannel().SetOnMessage( func(input []byte) { s.DataChannel.OutputMessageHandler(log, s.Stop, s.SessionId, input) }) s.DataChannel.RegisterOutputStreamHandler(s.ProcessFirstMessage, false) if err = s.DataChannel.Open(log); err != nil { log.Errorf("Retrying connection for data channel id: %s failed with error: %s", s.SessionId, err) s.retryParams.CallableFunc = func() (err error) { return s.DataChannel.Reconnect(log) } if err = s.retryParams.Call(); err != nil { log.Error(err) } } s.DataChannel.GetWsChannel().SetOnError( func(err error) { log.Errorf("Trying to reconnect the session: %v with seq num: %d", s.StreamUrl, s.DataChannel.GetStreamDataSequenceNumber()) s.retryParams.CallableFunc = func() (err error) { return s.ResumeSessionHandler(log) } if err = s.retryParams.Call(); err != nil { log.Error(err) } }) // Scheduler for resending of data s.DataChannel.ResendStreamDataMessageScheduler(log) return nil } // ProcessFirstMessage only processes messages with PayloadType Output to determine the // sessionType of the session to be launched. This is a fallback for agent versions that do not support handshake, they // immediately start sending shell output. func (s *Session) ProcessFirstMessage(log log.T, outputMessage message.ClientMessage) (isHandlerReady bool, err error) { // Immediately deregister self so that this handler is only called once, for the first message s.DataChannel.DeregisterOutputStreamHandler(s.ProcessFirstMessage) // Only set session type if the session type has not already been set. Usually session type will be set // by handshake protocol which would be the first message but older agents may not perform handshake if s.SessionType == "" { if outputMessage.PayloadType == uint32(message.Output) { log.Warn("Setting session type to shell based on PayloadType!") s.DataChannel.SetSessionType(config.ShellPluginName) s.DisplayMode.DisplayMessage(log, outputMessage) } } return true, nil } // Stop will end the session func (s *Session) Stop() { os.Exit(0) } // GetResumeSessionParams calls ResumeSession API and gets tokenvalue for reconnecting func (s *Session) GetResumeSessionParams(log log.T) (string, error) { var ( resumeSessionOutput *ssm.ResumeSessionOutput err error sdkSession *sdkSession.Session ) if sdkSession, err = sdkutil.GetNewSessionWithEndpoint(s.Endpoint); err != nil { return "", err } s.sdk = ssm.New(sdkSession) resumeSessionInput := ssm.ResumeSessionInput{ SessionId: &s.SessionId, } log.Debugf("Resume Session input parameters: %v", resumeSessionInput) if resumeSessionOutput, err = s.sdk.ResumeSession(&resumeSessionInput); err != nil { log.Errorf("Resume Session failed: %v", err) return "", err } if resumeSessionOutput.TokenValue == nil { return "", nil } return *resumeSessionOutput.TokenValue, nil } // ResumeSessionHandler gets token value and tries to Reconnect to datachannel func (s *Session) ResumeSessionHandler(log log.T) (err error) { s.TokenValue, err = s.GetResumeSessionParams(log) if err != nil { log.Errorf("Failed to get token: %v", err) return } else if s.TokenValue == "" { log.Debugf("Session: %s timed out", s.SessionId) fmt.Fprintf(os.Stdout, "Session: %s timed out.\n", s.SessionId) os.Exit(0) } s.DataChannel.GetWsChannel().SetChannelToken(s.TokenValue) err = s.DataChannel.Reconnect(log) return } // TerminateSession calls TerminateSession API func (s *Session) TerminateSession(log log.T) error { var ( err error newSession *sdkSession.Session ) if newSession, err = sdkutil.GetNewSessionWithEndpoint(s.Endpoint); err != nil { log.Errorf("Terminate Session failed: %v", err) return err } s.sdk = ssm.New(newSession) terminateSessionInput := ssm.TerminateSessionInput{ SessionId: &s.SessionId, } log.Debugf("Terminate Session input parameters: %v", terminateSessionInput) if _, err = s.sdk.TerminateSession(&terminateSessionInput); err != nil { log.Errorf("Terminate Session failed: %v", err) return err } return nil }
164
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package session starts the session. package session import ( "fmt" "testing" wsChannelMock "github.com/aws/session-manager-plugin/src/communicator/mocks" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/datachannel" dataChannelMock "github.com/aws/session-manager-plugin/src/datachannel/mocks" "github.com/aws/session-manager-plugin/src/message" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/assert" ) var ( clientId = "clientId_abc" sessionId = "sessionId_abc" instanceId = "i-123456" ) func TestOpenDataChannel(t *testing.T) { mockDataChannel = &dataChannelMock.IDataChannel{} mockWsChannel = &wsChannelMock.IWebSocketChannel{} sessionMock := &Session{} sessionMock.DataChannel = mockDataChannel SetupMockActions() mockDataChannel.On("Open", mock.Anything).Return(nil) err := sessionMock.OpenDataChannel(logger) assert.Nil(t, err) } func TestOpenDataChannelWithError(t *testing.T) { mockDataChannel = &dataChannelMock.IDataChannel{} mockWsChannel = &wsChannelMock.IWebSocketChannel{} sessionMock := &Session{} sessionMock.DataChannel = mockDataChannel SetupMockActions() //First reconnection failed when open datachannel, success after retry mockDataChannel.On("Open", mock.Anything).Return(fmt.Errorf("error")) mockDataChannel.On("Reconnect", mock.Anything).Return(fmt.Errorf("error")).Once() mockDataChannel.On("Reconnect", mock.Anything).Return(nil).Once() err := sessionMock.OpenDataChannel(logger) assert.Nil(t, err) } func TestProcessFirstMessageOutputMessageFirst(t *testing.T) { outputMessage := message.ClientMessage{ PayloadType: uint32(message.Output), Payload: []byte("testing"), } dataChannel := &datachannel.DataChannel{} dataChannel.Initialize(logger, clientId, sessionId, instanceId, false) session := Session{ DataChannel: dataChannel, } session.ProcessFirstMessage(logger, outputMessage) assert.Equal(t, config.ShellPluginName, session.DataChannel.GetSessionType()) assert.True(t, <-session.DataChannel.IsSessionTypeSet()) }
82
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package session starts the session. package session import ( "bytes" "fmt" "sync" "testing" "time" wsChannelMock "github.com/aws/session-manager-plugin/src/communicator/mocks" dataChannelMock "github.com/aws/session-manager-plugin/src/datachannel/mocks" "github.com/aws/session-manager-plugin/src/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) var ( logger = log.NewMockLog() mockDataChannel = &dataChannelMock.IDataChannel{} mockWsChannel = &wsChannelMock.IWebSocketChannel{} ) func TestValidateInputAndStartSessionWithNoInputArgument(t *testing.T) { var buffer bytes.Buffer args := []string{""} ValidateInputAndStartSession(args, &buffer) assert.Contains(t, buffer.String(), "The Session Manager plugin was installed successfully") } func TestValidateInputAndStartSessionWithWrongInputArgument(t *testing.T) { var buffer bytes.Buffer args := []string{1: "version"} ValidateInputAndStartSession(args, &buffer) assert.Contains(t, buffer.String(), "Use session-manager-plugin --version to check the version") } func TestValidateInputAndStartSession(t *testing.T) { var buffer bytes.Buffer sessionResponse := "{\"SessionId\": \"user-012345\", \"TokenValue\": \"ABCD\", \"StreamUrl\": \"wss://ssmmessages.us-east-1.amazonaws.com/v1/data-channel/user-012345?role=publish_subscribe\"}" args := []string{"session-manager-plugin", sessionResponse, "us-east-1", "StartSession", "", "{\"Target\": \"i-0123abc\"}", "https://ssm.us-east-1.amazonaws.com"} startSession = func(session *Session, log log.T) error { return fmt.Errorf("Some error") } ValidateInputAndStartSession(args, &buffer) assert.Contains(t, buffer.String(), "Cannot perform start session: Some error") } func TestExecute(t *testing.T) { sessionMock := &Session{} sessionMock.DataChannel = mockDataChannel SetupMockActions() mockDataChannel.On("Open", mock.Anything).Return(nil) isSessionTypeSetMock := make(chan bool, 1) isSessionTypeSetMock <- true mockDataChannel.On("IsSessionTypeSet").Return(isSessionTypeSetMock) mockDataChannel.On("GetSessionType").Return("Standard_Stream") mockDataChannel.On("GetSessionProperties").Return("SessionProperties") isStreamMessageResendTimeout := make(chan bool, 1) mockDataChannel.On("IsStreamMessageResendTimeout").Return(isStreamMessageResendTimeout) setSessionHandlersWithSessionType = func(session *Session, log log.T) error { return fmt.Errorf("start session error for %s", session.SessionType) } err := sessionMock.Execute(logger) assert.NotNil(t, err) assert.Contains(t, err.Error(), "start session error for Standard_Stream") } func TestExecuteAndStreamMessageResendTimesOut(t *testing.T) { sessionMock := &Session{} sessionMock.DataChannel = mockDataChannel SetupMockActions() mockDataChannel.On("Open", mock.Anything).Return(nil) isStreamMessageResendTimeout := make(chan bool, 1) mockDataChannel.On("IsStreamMessageResendTimeout").Return(isStreamMessageResendTimeout) var wg sync.WaitGroup wg.Add(1) handleStreamMessageResendTimeout = func(session *Session, log log.T) { time.Sleep(10 * time.Millisecond) isStreamMessageResendTimeout <- true wg.Done() return } isSessionTypeSetMock := make(chan bool, 1) isSessionTypeSetMock <- true mockDataChannel.On("IsSessionTypeSet").Return(isSessionTypeSetMock) mockDataChannel.On("GetSessionType").Return("Standard_Stream") mockDataChannel.On("GetSessionProperties").Return("SessionProperties") setSessionHandlersWithSessionType = func(session *Session, log log.T) error { return nil } var err error go func() { err = sessionMock.Execute(logger) time.Sleep(200 * time.Millisecond) }() wg.Wait() assert.Nil(t, err) } func SetupMockActions() { mockDataChannel.On("Initialize", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return() mockDataChannel.On("SetWebsocket", mock.Anything, mock.Anything, mock.Anything).Return() mockDataChannel.On("GetWsChannel").Return(mockWsChannel) mockDataChannel.On("RegisterOutputStreamHandler", mock.Anything, mock.Anything) mockDataChannel.On("ResendStreamDataMessageScheduler", mock.Anything).Return(nil) mockWsChannel.On("SetOnMessage", mock.Anything) mockWsChannel.On("SetOnError", mock.Anything) }
135
session-manager-plugin
aws
Go
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "fmt" "net" "os" "os/signal" "strconv" "time" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/sessionutil" "github.com/aws/session-manager-plugin/src/version" ) // BasicPortForwarding is type of port session // accepts one client connection at a time type BasicPortForwarding struct { port IPortSession stream *net.Conn listener *net.Listener sessionId string portParameters PortParameters session session.Session } // getNewListener returns a new listener to given address and type like tcp, unix etc. var getNewListener = func(listenerType string, listenerAddress string) (listener net.Listener, err error) { return net.Listen(listenerType, listenerAddress) } // acceptConnection returns connection to the listener var acceptConnection = func(log log.T, listener net.Listener) (tcpConn net.Conn, err error) { return listener.Accept() } // IsStreamNotSet checks if stream is not set func (p *BasicPortForwarding) IsStreamNotSet() (status bool) { return p.stream == nil } // Stop closes the stream func (p *BasicPortForwarding) Stop() { if p.stream != nil { (*p.stream).Close() } os.Exit(0) } // InitializeStreams establishes connection and initializes the stream func (p *BasicPortForwarding) InitializeStreams(log log.T, agentVersion string) (err error) { p.handleControlSignals(log) if err = p.startLocalConn(log); err != nil { return } return } // ReadStream reads data from the stream func (p *BasicPortForwarding) ReadStream(log log.T) (err error) { msg := make([]byte, config.StreamDataPayloadSize) for { numBytes, err := (*p.stream).Read(msg) if err != nil { log.Debugf("Reading from port %s failed with error: %v. Close this connection, listen and accept new one.", p.portParameters.PortNumber, err) // Send DisconnectToPort flag to agent when client tcp connection drops to ensure agent closes tcp connection too with server port if err = p.session.DataChannel.SendFlag(log, message.DisconnectToPort); err != nil { log.Errorf("Failed to send packet: %v", err) return err } if err = p.reconnect(log); err != nil { return err } // continue to read from connection as it has been re-established continue } log.Tracef("Received message of size %d from stdin.", numBytes) if err = p.session.DataChannel.SendInputDataMessage(log, message.Output, msg[:numBytes]); err != nil { log.Errorf("Failed to send packet: %v", err) return err } // Sleep to process more data time.Sleep(time.Millisecond) } } // WriteStream writes data to stream func (p *BasicPortForwarding) WriteStream(outputMessage message.ClientMessage) error { _, err := (*p.stream).Write(outputMessage.Payload) return err } // startLocalConn establishes a new local connection to forward remote server packets to func (p *BasicPortForwarding) startLocalConn(log log.T) (err error) { // When localPortNumber is not specified, set port number to 0 to let net.conn choose an open port at random localPortNumber := p.portParameters.LocalPortNumber if p.portParameters.LocalPortNumber == "" { localPortNumber = "0" } var listener net.Listener if listener, err = p.startLocalListener(log, localPortNumber); err != nil { log.Errorf("Unable to open tcp connection to port. %v", err) return err } var tcpConn net.Conn if tcpConn, err = acceptConnection(log, listener); err != nil { log.Errorf("Failed to accept connection with error. %v", err) return err } log.Infof("Connection accepted for session %s.", p.sessionId) fmt.Printf("Connection accepted for session %s.\n", p.sessionId) p.listener = &listener p.stream = &tcpConn return } // startLocalListener starts a local listener to given address func (p *BasicPortForwarding) startLocalListener(log log.T, portNumber string) (listener net.Listener, err error) { var displayMessage string switch p.portParameters.LocalConnectionType { case "unix": if listener, err = getNewListener(p.portParameters.LocalConnectionType, p.portParameters.LocalUnixSocket); err != nil { return } displayMessage = fmt.Sprintf("Unix socket %s opened for sessionId %s.", p.portParameters.LocalUnixSocket, p.sessionId) default: if listener, err = getNewListener("tcp", "localhost:"+portNumber); err != nil { return } // get port number the TCP listener opened p.portParameters.LocalPortNumber = strconv.Itoa(listener.Addr().(*net.TCPAddr).Port) displayMessage = fmt.Sprintf("Port %s opened for sessionId %s.", p.portParameters.LocalPortNumber, p.sessionId) } log.Info(displayMessage) fmt.Println(displayMessage) return } // handleControlSignals handles terminate signals func (p *BasicPortForwarding) handleControlSignals(log log.T) { c := make(chan os.Signal, 1) signal.Notify(c, sessionutil.ControlSignals...) go func() { <-c fmt.Println("Terminate signal received, exiting.") if version.DoesAgentSupportTerminateSessionFlag(log, p.session.DataChannel.GetAgentVersion()) { if err := p.session.DataChannel.SendFlag(log, message.TerminateSession); err != nil { log.Errorf("Failed to send TerminateSession flag: %v", err) } fmt.Fprintf(os.Stdout, "\n\nExiting session with sessionId: %s.\n\n", p.sessionId) p.Stop() } else { p.session.TerminateSession(log) } }() } // reconnect closes existing connection, listens to new connection and accept it func (p *BasicPortForwarding) reconnect(log log.T) (err error) { // close existing connection as it is in a state from which data cannot be read (*p.stream).Close() // wait for new connection on listener and accept it var conn net.Conn if conn, err = acceptConnection(log, *p.listener); err != nil { return log.Errorf("Failed to accept connection with error. %v", err) } p.stream = &conn return }
200
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "errors" "net" "os" "os/signal" "syscall" "testing" "time" "github.com/aws/session-manager-plugin/src/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) // This test passes ctrl+c signal which blocks running of all other tests. func TestSetSessionHandlers(t *testing.T) { mockLog.Infof("TestStartSession!!!!!") out, in := net.Pipe() defer out.Close() defer in.Close() counter := 0 countTimes := func() error { counter++ return nil } mockWebSocketChannel.On("SendMessage", mockLog, mock.Anything, mock.Anything). Return(countTimes()) mockSession := getSessionMock() portSession := PortSession{ Session: mockSession, portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, portSessionType: &BasicPortForwarding{ session: mockSession, portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, }, } signalCh := make(chan os.Signal, 1) go func() { time.Sleep(100 * time.Millisecond) if _, err := out.Write([]byte("testing123")); err != nil { mockLog.Infof("error: ", err) } }() go func() { acceptConnection = func(log log.T, listener net.Listener) (tcpConn net.Conn, err error) { return in, nil } signal.Notify(signalCh, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTSTP) process, _ := os.FindProcess(os.Getpid()) process.Signal(syscall.SIGINT) portSession.SetSessionHandlers(mockLog) }() time.Sleep(time.Second) assert.Equal(t, <-signalCh, syscall.SIGINT) assert.Equal(t, counter, 1) mockWebSocketChannel.AssertExpectations(t) } func TestStartSessionTCPLocalPortFromDocument(t *testing.T) { acceptConnection = func(log log.T, listener net.Listener) (tcpConn net.Conn, err error) { return nil, errors.New("accept failed") } portSession := PortSession{ Session: getSessionMock(), portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding", LocalPortNumber: "54321"}, portSessionType: &BasicPortForwarding{ session: getSessionMock(), portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, }, } portSession.SetSessionHandlers(mockLog) assert.Equal(t, "54321", portSession.portParameters.LocalPortNumber) } func TestStartSessionTCPAcceptFailed(t *testing.T) { connErr := errors.New("accept failed") acceptConnection = func(log log.T, listener net.Listener) (tcpConn net.Conn, err error) { return nil, connErr } portSession := PortSession{ Session: getSessionMock(), portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, portSessionType: &BasicPortForwarding{ session: getSessionMock(), portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, }, } assert.Equal(t, portSession.SetSessionHandlers(mockLog), connErr) } func TestStartSessionTCPConnectFailed(t *testing.T) { listenerError := errors.New("TCP connection failed") getNewListener = func(listenerType string, listenerAddress string) (listener net.Listener, err error) { return nil, listenerError } portSession := PortSession{ Session: getSessionMock(), portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, portSessionType: &BasicPortForwarding{ session: getSessionMock(), portParameters: PortParameters{PortNumber: "22", Type: "LocalPortForwarding"}, }, } assert.Equal(t, portSession.SetSessionHandlers(mockLog), listenerError) }
126
session-manager-plugin
aws
Go
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "bytes" "context" "encoding/binary" "fmt" "hash/fnv" "io" "net" "os" "os/signal" "path/filepath" "strconv" "sync" "time" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/sessionutil" "github.com/aws/session-manager-plugin/src/version" "github.com/xtaci/smux" "golang.org/x/sync/errgroup" ) // MuxClient contains smux client session and corresponding network connection type MuxClient struct { conn net.Conn session *smux.Session } // MgsConn contains local server and corresponding connection to smux client type MgsConn struct { listener net.Listener conn net.Conn } // MuxPortForwarding is type of port session // accepts multiple client connections through multiplexing type MuxPortForwarding struct { port IPortSession sessionId string socketFile string portParameters PortParameters session session.Session muxClient *MuxClient mgsConn *MgsConn } func (c *MgsConn) close() { c.listener.Close() c.conn.Close() } func (c *MuxClient) close() { c.session.Close() c.conn.Close() } // IsStreamNotSet checks if stream is not set func (p *MuxPortForwarding) IsStreamNotSet() (status bool) { return p.muxClient.conn == nil } // Stop closes all open stream func (p *MuxPortForwarding) Stop() { if p.mgsConn != nil { p.mgsConn.close() } if p.muxClient != nil { p.muxClient.close() } p.cleanUp() os.Exit(0) } // InitializeStreams initializes i/o streams func (p *MuxPortForwarding) InitializeStreams(log log.T, agentVersion string) (err error) { p.handleControlSignals(log) p.socketFile = getUnixSocketPath(p.sessionId, os.TempDir(), "session_manager_plugin_mux.sock") if err = p.initialize(log, agentVersion); err != nil { p.cleanUp() } return } // ReadStream reads data from different connections func (p *MuxPortForwarding) ReadStream(log log.T) (err error) { g, ctx := errgroup.WithContext(context.Background()) // reads data from smux client and transfers to server over datachannel g.Go(func() error { return p.transferDataToServer(log, ctx) }) // set up network listener on SSM port and handle client connections g.Go(func() error { return p.handleClientConnections(log, ctx) }) return g.Wait() } // WriteStream writes data to stream func (p *MuxPortForwarding) WriteStream(outputMessage message.ClientMessage) error { switch message.PayloadType(outputMessage.PayloadType) { case message.Output: _, err := p.mgsConn.conn.Write(outputMessage.Payload) return err case message.Flag: var flag message.PayloadTypeFlag buf := bytes.NewBuffer(outputMessage.Payload) binary.Read(buf, binary.BigEndian, &flag) if message.ConnectToPortError == flag { fmt.Printf("\nConnection to destination port failed, check SSM Agent logs.\n") } } return nil } // cleanUp deletes unix socket file func (p *MuxPortForwarding) cleanUp() { os.Remove(p.socketFile) } // initialize opens a network connection that acts as smux client func (p *MuxPortForwarding) initialize(log log.T, agentVersion string) (err error) { // open a network listener var listener net.Listener if listener, err = sessionutil.NewListener(log, p.socketFile); err != nil { return } var g errgroup.Group // start a go routine to accept connections on the network listener g.Go(func() error { if conn, err := listener.Accept(); err != nil { return err } else { p.mgsConn = &MgsConn{listener, conn} } return nil }) // start a connection to the local network listener and set up client side of mux g.Go(func() error { if muxConn, err := net.Dial(listener.Addr().Network(), listener.Addr().String()); err != nil { return err } else { smuxConfig := smux.DefaultConfig() if version.DoesAgentSupportDisableSmuxKeepAlive(log, agentVersion) { // Disable smux KeepAlive or else it breaks Session Manager idle timeout. smuxConfig.KeepAliveDisabled = true } if muxSession, err := smux.Client(muxConn, smuxConfig); err != nil { return err } else { p.muxClient = &MuxClient{muxConn, muxSession} } } return nil }) return g.Wait() } // handleControlSignals handles terminate signals func (p *MuxPortForwarding) handleControlSignals(log log.T) { c := make(chan os.Signal, 1) signal.Notify(c, sessionutil.ControlSignals...) go func() { <-c fmt.Println("Terminate signal received, exiting.") if err := p.session.DataChannel.SendFlag(log, message.TerminateSession); err != nil { log.Errorf("Failed to send TerminateSession flag: %v", err) } fmt.Fprintf(os.Stdout, "\n\nExiting session with sessionId: %s.\n\n", p.sessionId) p.Stop() }() } // transferDataToServer reads from smux client connection and sends on data channel func (p *MuxPortForwarding) transferDataToServer(log log.T, ctx context.Context) (err error) { msg := make([]byte, config.StreamDataPayloadSize) for { select { case <-ctx.Done(): return ctx.Err() default: var numBytes int if numBytes, err = p.mgsConn.conn.Read(msg); err != nil { log.Debugf("Reading from port failed with error: %v.", err) return } log.Tracef("Received message of size %d from mux client.", numBytes) if err = p.session.DataChannel.SendInputDataMessage(log, message.Output, msg[:numBytes]); err != nil { log.Errorf("Failed to send packet on data channel: %v", err) return } // sleep to process more data time.Sleep(time.Millisecond) } } } // handleClientConnections sets up network server on local ssm port to accept connections from clients (browser/terminal) func (p *MuxPortForwarding) handleClientConnections(log log.T, ctx context.Context) (err error) { var ( listener net.Listener displayMsg string ) if p.portParameters.LocalConnectionType == "unix" { if listener, err = net.Listen(p.portParameters.LocalConnectionType, p.portParameters.LocalUnixSocket); err != nil { return err } displayMsg = fmt.Sprintf("Unix socket %s opened for sessionId %s.", p.portParameters.LocalUnixSocket, p.sessionId) } else { localPortNumber := p.portParameters.LocalPortNumber if p.portParameters.LocalPortNumber == "" { localPortNumber = "0" } if listener, err = net.Listen("tcp", "localhost:"+localPortNumber); err != nil { return err } p.portParameters.LocalPortNumber = strconv.Itoa(listener.Addr().(*net.TCPAddr).Port) displayMsg = fmt.Sprintf("Port %s opened for sessionId %s.", p.portParameters.LocalPortNumber, p.sessionId) } defer listener.Close() log.Infof(displayMsg) fmt.Printf(displayMsg) log.Infof("Waiting for connections...\n") fmt.Printf("\nWaiting for connections...\n") var once sync.Once for { select { case <-ctx.Done(): return ctx.Err() default: if conn, err := listener.Accept(); err != nil { log.Errorf("Error while accepting connection: %v", err) } else { log.Infof("Connection accepted from %s\n for session [%s]", conn.RemoteAddr(), p.sessionId) once.Do(func() { fmt.Printf("\nConnection accepted for session [%s]\n", p.sessionId) }) stream, err := p.muxClient.session.OpenStream() if err != nil { continue } log.Debugf("Client stream opened %d\n", stream.ID()) go handleDataTransfer(stream, conn) } } } } // handleDataTransfer launches routines to transfer data between source and destination func handleDataTransfer(dst io.ReadWriteCloser, src io.ReadWriteCloser) { var wait sync.WaitGroup wait.Add(2) go func() { io.Copy(dst, src) dst.Close() wait.Done() }() go func() { io.Copy(src, dst) src.Close() wait.Done() }() wait.Wait() } // getUnixSocketPath generates the unix socket file name based on sessionId and returns the path. func getUnixSocketPath(sessionId string, dir string, suffix string) string { hash := fnv.New32a() hash.Write([]byte(sessionId)) return filepath.Join(dir, fmt.Sprintf("%d_%s", hash.Sum32(), suffix)) }
312
session-manager-plugin
aws
Go
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "net" "testing" "time" "github.com/aws/session-manager-plugin/src/datachannel" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/stretchr/testify/assert" ) // test readStream func TestReadStream(t *testing.T) { out, in := net.Pipe() defer out.Close() session := getSessionMock() portSession := PortSession{ Session: session, portSessionType: &MuxPortForwarding{ session: session, muxClient: &MuxClient{in, nil}, mgsConn: &MgsConn{nil, out}, }, } go func() { in.Write(outputMessage.Payload) in.Close() }() var actualPayload []byte datachannel.SendMessageCall = func(log log.T, dataChannel *datachannel.DataChannel, input []byte, inputType int) error { actualPayload = input return nil } go func() { portSession.portSessionType.ReadStream(mockLog) }() select { case <-time.After(time.Second): } deserializedMsg := &message.ClientMessage{} err := deserializedMsg.DeserializeClientMessage(mockLog, actualPayload) assert.Nil(t, err) assert.Equal(t, outputMessage.Payload, deserializedMsg.Payload) } // test writeStream func TestWriteStream(t *testing.T) { out, in := net.Pipe() defer in.Close() defer out.Close() portSession := PortSession{ portSessionType: &MuxPortForwarding{ session: getSessionMock(), mgsConn: &MgsConn{nil, in}, }, } go func() { portSession.portSessionType.WriteStream(outputMessage) }() msg := make([]byte, 20) n, _ := out.Read(msg) msg = msg[:n] assert.Equal(t, outputMessage.Payload, msg) } // Test handleDataTransfer func TestHandleDataTransferSrcToDst(t *testing.T) { msg := make([]byte, 20) out, in := net.Pipe() out1, in1 := net.Pipe() defer out1.Close() go func() { in.Write(outputMessage.Payload) in.Close() }() go func() { n, _ := out1.Read(msg) msg = msg[:n] }() handleDataTransfer(in1, out) assert.EqualValues(t, outputMessage.Payload, msg) } func TestHandleDataTransferDstToSrc(t *testing.T) { msg := make([]byte, 20) out, in := net.Pipe() out1, in1 := net.Pipe() defer out.Close() go func() { in1.Write(outputMessage.Payload) in1.Close() }() go func() { n, _ := out.Read(msg) msg = msg[:n] }() handleDataTransfer(in, out1) assert.EqualValues(t, outputMessage.Payload, msg) }
130
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/jsonutil" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" "github.com/aws/session-manager-plugin/src/version" ) const ( LocalPortForwardingType = "LocalPortForwarding" ) type PortSession struct { session.Session portParameters PortParameters portSessionType IPortSession } type IPortSession interface { IsStreamNotSet() (status bool) InitializeStreams(log log.T, agentVersion string) (err error) ReadStream(log log.T) (err error) WriteStream(outputMessage message.ClientMessage) (err error) Stop() } type PortParameters struct { PortNumber string `json:"portNumber"` LocalPortNumber string `json:"localPortNumber"` LocalUnixSocket string `json:"localUnixSocket"` LocalConnectionType string `json:"localConnectionType"` Type string `json:"type"` } func init() { session.Register(&PortSession{}) } // Name is the session name used inputStream the plugin func (PortSession) Name() string { return config.PortPluginName } func (s *PortSession) Initialize(log log.T, sessionVar *session.Session) { s.Session = *sessionVar if err := jsonutil.Remarshal(s.SessionProperties, &s.portParameters); err != nil { log.Errorf("Invalid format: %v", err) } if s.portParameters.Type == LocalPortForwardingType { if version.DoesAgentSupportTCPMultiplexing(log, s.DataChannel.GetAgentVersion()) { s.portSessionType = &MuxPortForwarding{ sessionId: s.SessionId, portParameters: s.portParameters, session: s.Session, } } else { s.portSessionType = &BasicPortForwarding{ sessionId: s.SessionId, portParameters: s.portParameters, session: s.Session, } } } else { s.portSessionType = &StandardStreamForwarding{ portParameters: s.portParameters, session: s.Session, } } s.DataChannel.RegisterOutputStreamHandler(s.ProcessStreamMessagePayload, true) s.DataChannel.GetWsChannel().SetOnMessage(func(input []byte) { if s.portSessionType.IsStreamNotSet() { outputMessage := &message.ClientMessage{} if err := outputMessage.DeserializeClientMessage(log, input); err != nil { log.Debugf("Ignore message deserialize error while stream connection had not set.") return } if outputMessage.MessageType == message.OutputStreamMessage { log.Debugf("Waiting for user to establish connection before processing incoming messages.") return } else { log.Infof("Received %s message while establishing connection", outputMessage.MessageType) } } s.DataChannel.OutputMessageHandler(log, s.Stop, s.SessionId, input) }) log.Infof("Connected to instance[%s] on port: %s", sessionVar.TargetId, s.portParameters.PortNumber) } func (s *PortSession) Stop() { s.portSessionType.Stop() } // StartSession redirects inputStream/outputStream data to datachannel. func (s *PortSession) SetSessionHandlers(log log.T) (err error) { if err = s.portSessionType.InitializeStreams(log, s.DataChannel.GetAgentVersion()); err != nil { return err } if err = s.portSessionType.ReadStream(log); err != nil { return err } return } // ProcessStreamMessagePayload writes messages received on datachannel to stdout func (s *PortSession) ProcessStreamMessagePayload(log log.T, outputMessage message.ClientMessage) (isHandlerReady bool, err error) { if s.portSessionType.IsStreamNotSet() { log.Debugf("Waiting for streams to be established before processing incoming messages.") return false, nil } log.Tracef("Received payload of size %d from datachannel.", outputMessage.PayloadLength) err = s.portSessionType.WriteStream(outputMessage) return true, err }
134
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "io/ioutil" "os" "testing" "time" "github.com/aws/session-manager-plugin/src/datachannel" "github.com/aws/session-manager-plugin/src/jsonutil" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) // Test Initialize func TestInitializePortSession(t *testing.T) { var portParameters PortParameters jsonutil.Remarshal(properties, &portParameters) mockWebSocketChannel.On("SetOnMessage", mock.Anything) portSession := PortSession{ Session: getSessionMock(), } portSession.Initialize(mockLog, &portSession.Session) mockWebSocketChannel.AssertExpectations(t) assert.Equal(t, portParameters, portSession.portParameters, "Initialize port parameters") assert.IsType(t, &StandardStreamForwarding{}, portSession.portSessionType) } func TestInitializePortSessionForPortForwardingWithOldAgent(t *testing.T) { var portParameters PortParameters jsonutil.Remarshal(map[string]interface{}{"portNumber": "8080", "type": "LocalPortForwarding"}, &portParameters) mockWebSocketChannel.On("SetOnMessage", mock.Anything) portSession := PortSession{ Session: getSessionMockWithParams(portParameters, "2.2.0.0"), } portSession.Initialize(mockLog, &portSession.Session) mockWebSocketChannel.AssertExpectations(t) assert.Equal(t, portParameters, portSession.portParameters, "Initialize port parameters") assert.IsType(t, &BasicPortForwarding{}, portSession.portSessionType) } func TestInitializePortSessionForPortForwarding(t *testing.T) { var portParameters PortParameters jsonutil.Remarshal(map[string]interface{}{"portNumber": "8080", "type": "LocalPortForwarding"}, &portParameters) mockWebSocketChannel.On("SetOnMessage", mock.Anything) portSession := PortSession{ Session: getSessionMockWithParams(portParameters, "3.1.0.0"), } portSession.Initialize(mockLog, &portSession.Session) mockWebSocketChannel.AssertExpectations(t) assert.Equal(t, portParameters, portSession.portParameters, "Initialize port parameters") assert.IsType(t, &MuxPortForwarding{}, portSession.portSessionType) } func TestStartSessionWithClosedWsConn(t *testing.T) { in, out, _ := os.Pipe() out.Write(outputMessage.Payload) oldStdin := os.Stdin os.Stdin = in var actualPayload []byte datachannel.SendMessageCall = func(log log.T, dataChannel *datachannel.DataChannel, input []byte, inputType int) error { actualPayload = input return nil } // Spawning a separate go routine to close files after a few seconds. // This is required as startSession has a for loop which will continuously reads data. go func() { time.Sleep(time.Second) os.Stdin = oldStdin in.Close() out.Close() }() portSession := PortSession{ Session: getSessionMock(), portParameters: PortParameters{PortNumber: "22"}, portSessionType: &StandardStreamForwarding{ inputStream: in, outputStream: out, session: getSessionMock(), }, } portSession.SetSessionHandlers(mockLog) deserializedMsg := &message.ClientMessage{} err := deserializedMsg.DeserializeClientMessage(mockLog, actualPayload) assert.Nil(t, err) assert.Equal(t, outputMessage.Payload, deserializedMsg.Payload) } // Test ProcessStreamMessagePayload func TestProcessStreamMessagePayload(t *testing.T) { in, out, _ := os.Pipe() defer func() { in.Close() out.Close() }() go func() { portSession := PortSession{ Session: getSessionMock(), portParameters: PortParameters{PortNumber: "22"}, portSessionType: &StandardStreamForwarding{ inputStream: in, outputStream: out, }, } portSession.ProcessStreamMessagePayload(mockLog, outputMessage) out.Close() }() payload, _ := ioutil.ReadAll(in) assert.Equal(t, outputMessage.Payload, payload) }
141
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "io" "os" "time" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" ) type StandardStreamForwarding struct { port IPortSession inputStream *os.File outputStream *os.File portParameters PortParameters session session.Session } // IsStreamNotSet checks if streams are not set func (p *StandardStreamForwarding) IsStreamNotSet() (status bool) { return p.inputStream == nil || p.outputStream == nil } // Stop closes the streams func (p *StandardStreamForwarding) Stop() { p.inputStream.Close() p.outputStream.Close() os.Exit(0) } // InitializeStreams initializes the streams with its file descriptors func (p *StandardStreamForwarding) InitializeStreams(log log.T, agentVersion string) (err error) { p.inputStream = os.Stdin p.outputStream = os.Stdout return } // ReadStream reads data from the input stream func (p *StandardStreamForwarding) ReadStream(log log.T) (err error) { msg := make([]byte, config.StreamDataPayloadSize) for { numBytes, err := p.inputStream.Read(msg) if err != nil { return p.handleReadError(log, err) } log.Tracef("Received message of size %d from stdin.", numBytes) if err = p.session.DataChannel.SendInputDataMessage(log, message.Output, msg[:numBytes]); err != nil { log.Errorf("Failed to send packet: %v", err) return err } // Sleep to process more data time.Sleep(time.Millisecond) } } // WriteStream writes data to output stream func (p *StandardStreamForwarding) WriteStream(outputMessage message.ClientMessage) error { _, err := p.outputStream.Write(outputMessage.Payload) return err } // handleReadError handles read error func (p *StandardStreamForwarding) handleReadError(log log.T, err error) error { if err == io.EOF { log.Infof("Session to instance[%s] on port[%s] was closed.", p.session.TargetId, p.portParameters.PortNumber) return nil } else { log.Errorf("Reading input failed with error: %v", err) return err } }
90
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "os" "testing" "time" "github.com/aws/session-manager-plugin/src/datachannel" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/stretchr/testify/assert" ) // Test StartSession func TestStartSessionForStandardStreamForwarding(t *testing.T) { in, out, _ := os.Pipe() out.Write(outputMessage.Payload) oldStdin := os.Stdin os.Stdin = in var actualPayload []byte datachannel.SendMessageCall = func(log log.T, dataChannel *datachannel.DataChannel, input []byte, inputType int) error { actualPayload = input return nil } // Spawning a separate go routine to close files after a few seconds. // This is required as startSession has a for loop which will continuously reads data. go func() { time.Sleep(time.Second) os.Stdin = oldStdin in.Close() out.Close() }() portSession := PortSession{ Session: getSessionMock(), portParameters: PortParameters{PortNumber: "22"}, portSessionType: &StandardStreamForwarding{ session: getSessionMock(), portParameters: PortParameters{PortNumber: "22"}, }, } portSession.SetSessionHandlers(mockLog) deserializedMsg := &message.ClientMessage{} err := deserializedMsg.DeserializeClientMessage(mockLog, actualPayload) assert.Nil(t, err) assert.Equal(t, outputMessage.Payload, deserializedMsg.Payload) }
64
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package portsession starts port session. package portsession import ( "github.com/aws/session-manager-plugin/src/communicator/mocks" "github.com/aws/session-manager-plugin/src/datachannel" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" ) var ( agentVersion = "2.3.750.0" mockLog = log.NewMockLog() mockWebSocketChannel = mocks.IWebSocketChannel{} outputMessage = message.ClientMessage{ PayloadType: uint32(message.Output), Payload: []byte("testing123"), PayloadLength: 10, } properties = map[string]interface{}{ "PortNumber": "22", } ) func getSessionMock() session.Session { return getSessionMockWithParams(properties, agentVersion) } func getSessionMockWithParams(properties interface{}, agentVersion string) session.Session { datachannel := &datachannel.DataChannel{} datachannel.SetAgentVersion(agentVersion) var mockSession = session.Session{ DataChannel: datachannel, } mockSession.DataChannel.Initialize(mockLog, "clientId", "sessionId", "targetId", false) mockSession.DataChannel.SetWsChannel(&mockWebSocketChannel) mockSession.SessionProperties = properties return mockSession }
56
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. //go:build darwin || freebsd || linux || netbsd || openbsd // +build darwin freebsd linux netbsd openbsd // Package sessionutil contains utility methods required to start session. package sessionutil import ( "os" "syscall" ) // All the signals to handles interrupt // SIGINT captures Ctrl+C // SIGQUIT captures Ctrl+\ // SIGTSTP captures Ctrl+Z var SignalsByteMap = map[os.Signal]byte{ syscall.SIGINT: '\003', syscall.SIGQUIT: '\x1c', syscall.SIGTSTP: '\032', } var ControlSignals = []os.Signal{syscall.SIGINT, syscall.SIGTSTP, syscall.SIGQUIT}
36
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. //go:build windows // +build windows // Package sessionutil contains utility methods required to start session. package sessionutil import ( "os" "syscall" ) // All the signals to handles interrupt // SIGINT captures Ctrl+C // SIGQUIT captures Ctrl+Z var SignalsByteMap = map[os.Signal]byte{ syscall.SIGINT: '\003', syscall.SIGQUIT: '\x1c', } var ControlSignals = []os.Signal{syscall.SIGINT, syscall.SIGQUIT}
34
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package sessionutil provides utility for sessions. package sessionutil import "github.com/aws/session-manager-plugin/src/log" func NewDisplayMode(log log.T) DisplayMode { displayMode := DisplayMode{} displayMode.InitDisplayMode(log) return displayMode }
24
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. //go:build darwin || freebsd || linux || netbsd || openbsd // +build darwin freebsd linux netbsd openbsd // Package sessionutil provides utility for sessions. package sessionutil import ( "fmt" "io" "net" "os" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" ) type DisplayMode struct { } func (d *DisplayMode) InitDisplayMode(log log.T) { } // DisplayMessage function displays the output on the screen func (d *DisplayMode) DisplayMessage(log log.T, message message.ClientMessage) { var out io.Writer = os.Stdout fmt.Fprint(out, string(message.Payload)) } // NewListener starts a new socket listener on the address. func NewListener(log log.T, address string) (net.Listener, error) { return net.Listen("unix", address) }
46
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. //go:build windows // +build windows // Package sessionutil provides utility for sessions. package sessionutil import ( "fmt" "net" "os" "syscall" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "golang.org/x/sys/windows" ) var EnvProgramFiles = os.Getenv("ProgramFiles") type DisplayMode struct { handle windows.Handle } func (d *DisplayMode) InitDisplayMode(log log.T) { var ( state uint32 fileDescriptor int err error ) // gets handler for Stdout fileDescriptor = int(syscall.Stdout) d.handle = windows.Handle(fileDescriptor) // gets current console mode i.e. current console settings if err = windows.GetConsoleMode(d.handle, &state); err != nil { log.Errorf("error getting console mode: %v", err) } // this flag is set in order to support control character sequences // that control cursor movement, color/font mode // refer - https://docs.microsoft.com/en-us/windows/console/setconsolemode state |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING // sets the console with new flag if err = windows.SetConsoleMode(d.handle, state); err != nil { log.Errorf("error setting console mode: %v", err) } } // DisplayMessage function displays the output on the screen func (d *DisplayMode) DisplayMessage(log log.T, message message.ClientMessage) { var ( done *uint32 err error ) // writes data to the specified file or input/output (I/O) device // refer - https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-writefile if err = windows.WriteFile(d.handle, message.Payload, done, nil); err != nil { log.Errorf("error occurred while writing to file: %v", err) fmt.Fprintf(os.Stdout, "\nError getting the output. %s\n", err.Error()) os.Exit(0) } } // NewListener starts a new socket listener on the address. // unix sockets are not supported in older windows versions, start tcp loopback server in such cases func NewListener(log log.T, address string) (net.Listener, error) { if listener, err := net.Listen("unix", address); err != nil { log.Infof("Failed to open unix socket listener, %v. Starting TCP listener.", err) return net.Listen("tcp", "localhost:0") } else { return listener, err } }
89
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package shellsession starts shell session. package shellsession import ( "bytes" "encoding/json" "os" "os/signal" "time" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/sessionutil" "golang.org/x/crypto/ssh/terminal" ) const ( ResizeSleepInterval = time.Millisecond * 500 StdinBufferLimit = 1024 ) type ShellSession struct { session.Session // SizeData is used to store size data at session level to compare with new size. SizeData message.SizeData originalSttyState bytes.Buffer } var GetTerminalSizeCall = func(fd int) (width int, height int, err error) { return terminal.GetSize(fd) } func init() { session.Register(&ShellSession{}) } // Name is the session name used in the plugin func (ShellSession) Name() string { return config.ShellPluginName } func (s *ShellSession) Initialize(log log.T, sessionVar *session.Session) { s.Session = *sessionVar s.DataChannel.RegisterOutputStreamHandler(s.ProcessStreamMessagePayload, true) s.DataChannel.GetWsChannel().SetOnMessage( func(input []byte) { s.DataChannel.OutputMessageHandler(log, s.Stop, s.SessionId, input) }) } // StartSession takes input and write it to data channel func (s *ShellSession) SetSessionHandlers(log log.T) (err error) { // handle re-size s.handleTerminalResize(log) // handle control signals s.handleControlSignals(log) //handles keyboard input err = s.handleKeyboardInput(log) return } // handleControlSignals handles control signals when given by user func (s *ShellSession) handleControlSignals(log log.T) { go func() { signals := make(chan os.Signal, 1) signal.Notify(signals, sessionutil.ControlSignals...) for { sig := <-signals if b, ok := sessionutil.SignalsByteMap[sig]; ok { if err := s.DataChannel.SendInputDataMessage(log, message.Output, []byte{b}); err != nil { log.Errorf("Failed to send control signals: %v", err) } } } }() } // handleTerminalResize checks size of terminal every 500ms and sends size data. func (s *ShellSession) handleTerminalResize(log log.T) { var ( width int height int inputSizeData []byte err error ) go func() { for { // If running from IDE GetTerminalSizeCall will not work. Supply a fixed width and height value. if width, height, err = GetTerminalSizeCall(int(os.Stdout.Fd())); err != nil { width = 300 height = 100 log.Errorf("Could not get size of the terminal: %s, using width %d height %d", err, width, height) } if s.SizeData.Rows != uint32(height) || s.SizeData.Cols != uint32(width) { sizeData := message.SizeData{ Cols: uint32(width), Rows: uint32(height), } s.SizeData = sizeData if inputSizeData, err = json.Marshal(sizeData); err != nil { log.Errorf("Cannot marshall size data: %v", err) } log.Debugf("Sending input size data: %s", inputSizeData) if err = s.DataChannel.SendInputDataMessage(log, message.Size, inputSizeData); err != nil { log.Errorf("Failed to Send size data: %v", err) } } // repeating this loop for every 500ms time.Sleep(ResizeSleepInterval) } }() } // ProcessStreamMessagePayload prints payload received on datachannel to console func (s ShellSession) ProcessStreamMessagePayload(log log.T, outputMessage message.ClientMessage) (isHandlerReady bool, err error) { s.DisplayMode.DisplayMessage(log, outputMessage) return true, nil }
141
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package shellsession starts shell session. package shellsession import ( "encoding/json" "fmt" "os" "os/signal" "sync" "syscall" "testing" "time" "github.com/aws/session-manager-plugin/src/communicator/mocks" "github.com/aws/session-manager-plugin/src/datachannel" dataChannelMock "github.com/aws/session-manager-plugin/src/datachannel/mocks" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/sessionutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) var ( expectedSequenceNumber = int64(0) logger = log.NewMockLog() clientId = "clientId" sessionId = "sessionId" instanceId = "instanceId" mockDataChannel = &dataChannelMock.IDataChannel{} mockWsChannel = &mocks.IWebSocketChannel{} ) func TestName(t *testing.T) { shellSession := ShellSession{} name := shellSession.Name() assert.Equal(t, name, "Standard_Stream") } func TestInitialize(t *testing.T) { session := &session.Session{} shellSession := ShellSession{} session.DataChannel = mockDataChannel mockDataChannel.On("RegisterOutputStreamHandler", mock.Anything, true).Times(1) mockDataChannel.On("GetWsChannel").Return(mockWsChannel) mockWsChannel.On("SetOnMessage", mock.Anything) shellSession.Initialize(logger, session) assert.Equal(t, shellSession.Session, *session) } func TestHandleControlSignals(t *testing.T) { session := session.Session{} session.DataChannel = mockDataChannel shellSession := ShellSession{} shellSession.Session = session waitCh := make(chan int, 1) counter := 0 sendDataMessage := func() error { counter++ return fmt.Errorf("SendInputDataMessage error") } mockDataChannel.On("SendInputDataMessage", mock.Anything, mock.Anything, mock.Anything).Return(sendDataMessage()) signalCh := make(chan os.Signal, 1) go func() { p, _ := os.FindProcess(os.Getpid()) signal.Notify(signalCh, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTSTP) shellSession.handleControlSignals(logger) p.Signal(syscall.SIGINT) time.Sleep(200 * time.Millisecond) close(waitCh) }() <-waitCh assert.Equal(t, <-signalCh, syscall.SIGINT) assert.Equal(t, counter, 1) } func TestSendInputDataMessageWithPayloadTypeSize(t *testing.T) { sizeData := message.SizeData{ Cols: 100, Rows: 100, } sizeDataBytes, _ := json.Marshal(sizeData) dataChannel := getDataChannel() mockChannel := &mocks.IWebSocketChannel{} dataChannel.SetWsChannel(mockChannel) SendMessageCallCount := 0 datachannel.SendMessageCall = func(log log.T, dataChannel *datachannel.DataChannel, input []byte, inputType int) error { SendMessageCallCount++ return nil } err := dataChannel.SendInputDataMessage(logger, message.Size, sizeDataBytes) assert.Nil(t, err) assert.Equal(t, expectedSequenceNumber, dataChannel.ExpectedSequenceNumber) assert.Equal(t, 1, SendMessageCallCount) } func TestTerminalResizeWhenSessionSizeDataIsNotEqualToActualSize(t *testing.T) { dataChannel := getDataChannel() session := session.Session{ DataChannel: dataChannel, } sizeData := message.SizeData{ Cols: 100, Rows: 100, } shellSession := ShellSession{ Session: session, SizeData: sizeData, } GetTerminalSizeCall = func(fd int) (width int, height int, err error) { return 123, 123, nil } var wg sync.WaitGroup wg.Add(1) // Spawning a separate go routine to close websocket connection. // This is required as handleTerminalResize has a for loop which will continuously check for // size data every 500ms. go func() { time.Sleep(1 * time.Second) wg.Done() }() SendMessageCallCount := 0 datachannel.SendMessageCall = func(log log.T, dataChannel *datachannel.DataChannel, input []byte, inputType int) error { SendMessageCallCount++ return nil } go shellSession.handleTerminalResize(logger) wg.Wait() assert.Equal(t, 1, SendMessageCallCount) } func TestProcessStreamMessagePayload(t *testing.T) { shellSession := ShellSession{} shellSession.DisplayMode = sessionutil.NewDisplayMode(logger) msg := message.ClientMessage{ Payload: []byte("Hello Agent\n"), } isReady, err := shellSession.ProcessStreamMessagePayload(logger, msg) assert.True(t, isReady) assert.Nil(t, err) } func getDataChannel() *datachannel.DataChannel { dataChannel := &datachannel.DataChannel{} dataChannel.Initialize(logger, clientId, sessionId, instanceId, false) dataChannel.SetWsChannel(mockWsChannel) return dataChannel }
173
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. //go:build darwin || freebsd || linux || netbsd || openbsd // +build darwin freebsd linux netbsd openbsd // Package shellsession starts shell session. package shellsession import ( "bufio" "bytes" "os" "os/exec" "time" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" ) //disableEchoAndInputBuffering disables echo to avoid double echo and disable input buffering func (s *ShellSession) disableEchoAndInputBuffering() { getState(&s.originalSttyState) setState(bytes.NewBufferString("cbreak")) setState(bytes.NewBufferString("-echo")) } // getState gets current state of terminal func getState(state *bytes.Buffer) error { cmd := exec.Command("stty", "-g") cmd.Stdin = os.Stdin cmd.Stdout = state return cmd.Run() } // setState sets the new settings to terminal func setState(state *bytes.Buffer) error { cmd := exec.Command("stty", state.String()) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout return cmd.Run() } // stop restores the terminal settings and exits func (s *ShellSession) Stop() { setState(&s.originalSttyState) setState(bytes.NewBufferString("echo")) // for linux and ubuntu os.Exit(0) } //handleKeyboardInput handles input entered by customer on terminal func (s *ShellSession) handleKeyboardInput(log log.T) (err error) { var ( stdinBytesLen int ) //handle double echo and disable input buffering s.disableEchoAndInputBuffering() stdinBytes := make([]byte, StdinBufferLimit) reader := bufio.NewReader(os.Stdin) for { if stdinBytesLen, err = reader.Read(stdinBytes); err != nil { log.Errorf("Unable read from Stdin: %v", err) break } if err = s.Session.DataChannel.SendInputDataMessage(log, message.Output, stdinBytes[:stdinBytesLen]); err != nil { log.Errorf("Failed to send UTF8 char: %v", err) break } // sleep to limit the rate of data transfer time.Sleep(time.Millisecond) } return }
87
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. //go:build windows // +build windows // Package shellsession starts shell session. package shellsession import ( "os" "time" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/message" "github.com/eiannone/keyboard" ) // Byte array for key inputs // Note: F11 cannot be converted to byte array var specialKeysInputMap = map[keyboard.Key][]byte{ keyboard.KeyEsc: {27}, keyboard.KeyArrowUp: {27, 79, 65}, keyboard.KeyArrowDown: {27, 79, 66}, keyboard.KeyArrowRight: {27, 79, 67}, keyboard.KeyArrowLeft: {27, 79, 68}, keyboard.KeyF1: {27, 79, 80}, keyboard.KeyF2: {27, 79, 81}, keyboard.KeyF3: {27, 79, 82}, keyboard.KeyF4: {27, 79, 83}, keyboard.KeyF5: {27, 91, 49, 53, 126}, keyboard.KeyF6: {27, 91, 49, 55, 126}, keyboard.KeyF7: {27, 91, 49, 56, 126}, keyboard.KeyF8: {27, 91, 49, 57, 126}, keyboard.KeyF9: {27, 91, 50, 48, 126}, keyboard.KeyF10: {27, 91, 50, 49, 126}, keyboard.KeyF12: {27, 91, 50, 52, 126}, keyboard.KeyHome: {27, 91, 72}, keyboard.KeyEnd: {27, 91, 70}, keyboard.KeyInsert: {27, 91, 50, 126}, keyboard.KeyDelete: {27, 91, 51, 126}, keyboard.KeyPgup: {27, 91, 53, 126}, keyboard.KeyPgdn: {27, 91, 54, 126}, } // stop restores the terminal settings and exits func (s *ShellSession) Stop() { os.Exit(0) } //handleKeyboardInput handles input entered by customer on terminal func (s *ShellSession) handleKeyboardInput(log log.T) (err error) { var ( character rune //character input from keyboard key keyboard.Key //special keys like arrows and function keys ) if err = keyboard.Open(); err != nil { log.Errorf("Failed to load Keyboard: %v", err) return } defer keyboard.Close() for { if character, key, err = keyboard.GetKey(); err != nil { log.Errorf("Failed to get the key stroke: %v", err) return } if character != 0 { charBytes := []byte(string(character)) if err = s.Session.DataChannel.SendInputDataMessage(log, message.Output, charBytes); err != nil { log.Errorf("Failed to send UTF8 char: %v", err) break } } else if key != 0 { keyBytes := []byte(string(key)) if byteValue, ok := specialKeysInputMap[key]; ok { keyBytes = byteValue } if err = s.Session.DataChannel.SendInputDataMessage(log, message.Output, keyBytes); err != nil { log.Errorf("Failed to send UTF8 char: %v", err) break } } // sleep to limit the rate of transfer time.Sleep(time.Millisecond) } return }
99
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package main represents the entry point to session manager plugin. package main import ( "os" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" _ "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/portsession" _ "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/shellsession" ) func main() { session.ValidateInputAndStartSession(os.Args, os.Stdout) }
28
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package main represents the entry point of the ssm cli. package main import ( "os" "github.com/aws/session-manager-plugin/src/ssmclicommands" ) //Created a ssmcli binary, used for testing purpose only. func main() { ssmclicommands.ValidateInput(os.Args, os.Stdout) }
27
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package ssmclicommands contains all the commands with its implementation. package ssmclicommands import ( "errors" "fmt" "io" "strings" "github.com/aws/session-manager-plugin/src/ssmclicommands/utils" "github.com/twinj/uuid" ) const ( ArgumentLength = 2 ) // ParseCliCommand function parses command and returns options to validate. func ParseCliCommand(args []string) (err error, options []string, command string, subcommand string, parameters map[string][]string) { argCount := len(args) pos := 1 // Options options = make([]string, 0) for _, val := range args[pos:] { if !utils.IsFlag(val) { break } options = append(options, utils.GetFlag(val)) pos++ } // Command if pos >= argCount { err = errors.New("command is required") return } command = strings.ToLower(args[pos]) pos++ //subcommand if pos >= argCount { return } subcommand = strings.ToLower(args[pos]) pos++ // Parameters if pos >= argCount { return } parameters = make(map[string][]string) var parameterName string for _, val := range args[2:] { if utils.IsFlag(val) { parameterName = utils.GetFlag(val) if parameterName == "" { // aws cli doesn't valid this err = fmt.Errorf("input contains parameter with no name") return } if _, exists := parameters[parameterName]; exists { // aws cli doesn't valid this err = fmt.Errorf("duplicate parameter %v", parameterName) return } parameters[parameterName] = make([]string, 0) } else { parameters[parameterName] = append(parameters[parameterName], val) } } return } // ValidateInput function validates the input and displays response accordingly. func ValidateInput(args []string, out io.Writer) { uuid.SwitchFormat(uuid.CleanHyphen) if len(args) < ArgumentLength { utils.DisplayCommandUsage(out) return } err, _, command, subcommand, parameters := ParseCliCommand(args) if err != nil { utils.DisplayCommandUsage(out) fmt.Fprint(out, err.Error()) return } if cmd, exists := utils.SsmCliCommands[command]; exists { if utils.IsHelp(subcommand, parameters) { fmt.Fprintln(out, cmd.Help()) } else { cmdErr, result := cmd.Execute(parameters) if cmdErr != nil { utils.DisplayCommandUsage(out) fmt.Fprint(out, cmdErr.Error()) return } else { fmt.Fprint(out, result) } } } else if command == utils.HelpFlag { utils.DisplayHelp(out) } else { utils.DisplayCommandUsage(out) fmt.Fprintf(out, "\nInvalid command %v. The following commands are supported:\n\n", command) utils.DisplaySupportedCommands(out) } }
126
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package ssmclicommands contains all the commands with its implementation. package ssmclicommands import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestParseCliCommand(t *testing.T) { args := []string{1: "--instance-id"} err, _, _, _, _ := ParseCliCommand(args) assert.NotNil(t, err) assert.Contains(t, err.Error(), "command is required") args = []string{1: "start-session", 2: "--instance-id", 3: "i-123456", 4: "--"} err, _, _, _, _ = ParseCliCommand(args) assert.NotNil(t, err) assert.Contains(t, err.Error(), "input contains parameter with no name") args = []string{1: "start-session", 2: "--instance-id", 3: "--instance-id"} err, _, _, _, _ = ParseCliCommand(args) assert.NotNil(t, err) assert.Contains(t, err.Error(), "duplicate parameter instance-id") args = []string{1: "start-session", 2: "--instance-id", 3: "i-123456", 4: "--region", 5: "us-east-1"} err, _, command, _, parameters := ParseCliCommand(args) assert.Nil(t, err) assert.Equal(t, command, "start-session") assert.Equal(t, parameters["instance-id"][0], "i-123456") assert.Equal(t, parameters["region"][0], "us-east-1") } func TestValidateInputUsage(t *testing.T) { var buffer bytes.Buffer var args []string ValidateInput(args, &buffer) assert.Contains(t, buffer.String(), "To see help text") args = []string{1: "ssmcli"} buffer.Reset() ValidateInput(args, &buffer) assert.Contains(t, buffer.String(), "Invalid command ssmcli") args = []string{1: "help"} buffer.Reset() ValidateInput(args, &buffer) assert.Contains(t, buffer.String(), "Available commands are") args = []string{1: "start-session", 2: "help"} buffer.Reset() ValidateInput(args, &buffer) assert.Contains(t, buffer.String(), "SYNOPSIS:") args = []string{1: "start-session", 2: "--instance-id", 3: "--instance-id"} buffer.Reset() ValidateInput(args, &buffer) assert.Contains(t, buffer.String(), "duplicate parameter instance-id") args = []string{1: "start-session", 2: "--region", 3: "us-east-1"} buffer.Reset() ValidateInput(args, &buffer) assert.Contains(t, buffer.String(), "instance-id is required") }
79
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package ssmclicommands contains all the commands with its implementation. package ssmclicommands import ( "bytes" "errors" "fmt" "html/template" "strings" sdkSession "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/session-manager-plugin/src/datachannel" "github.com/aws/session-manager-plugin/src/jsonutil" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/sdkutil" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" _ "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/portsession" _ "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session/shellsession" "github.com/aws/session-manager-plugin/src/ssmclicommands/utils" "github.com/twinj/uuid" ) const ( START_SESSION = "start-session" INSTANCE_ID = "instance-id" REGION = "region" PROFILE = "profile" ENDPOINT = "endpoint" DOCUMENT_NAME = "document-name" PARAMETERS = "parameters" ) var ParameterKeys = []string{INSTANCE_ID, REGION, PROFILE, ENDPOINT, DOCUMENT_NAME, PARAMETERS} const START_SESSION_HELP = `NAME : {{.StartSessionName}} SYNOPSIS: {{.SsmCliName}} {{.StartSessionName}} {{.InstanceId}} {{.Region}} PARAMETERS: {{.InstanceId}} (string) InstanceId InstanceId is required to start a session {{.Region}} (string) Region Region is required if not configured in aws config file (https://docs.aws.amazon.com/credref/latest/refdocs/creds-config-files.html) Command: For any region, {{.SsmCliName}} {{.StartSessionName}} --{{.InstanceId}} i-123456 --{{.Region}} us-east-1 For any aws credentials profile, {{.SsmCliName}} {{.StartSessionName}} --{{.InstanceId}} i-123456 --{{.Profile}} profile-name For any document with parameters, {{.SsmCliName}} {{.StartSessionName}} --{{.InstanceId}} i-123456 --{{.DocumentName}} AWS-StartPortForwardingSession --{{.Parameters}} '{"localPortNumber":["6789"]}' ` type StartSessionHelpParams struct { SsmCliName string StartSessionName string InstanceId string Region string Profile string Endpoint string DocumentName string Parameters string } type StartSessionCommand struct { helpText string sdk *ssm.SSM } //getSSMClient generate ssm client by configuration var getSSMClient = func(log log.T, region string, profile string, endpoint string) (*ssm.SSM, error) { sdkutil.SetRegionAndProfile(region, profile) var sdkSession *sdkSession.Session sdkSession, err := sdkutil.GetNewSessionWithEndpoint(endpoint) if err != nil { log.Errorf("Get session with endpoint Failed: %v", err) return nil, err } return ssm.New(sdkSession), nil } //executeSession to open datachannel var executeSession = func(log log.T, session *session.Session) (err error) { return session.Execute(log) } // startSession trigger a sdk start session call. var startSession = func(s *StartSessionCommand, input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { return s.sdk.StartSession(input) } func init() { utils.Register(&StartSessionCommand{}) } // Name is the command name used in the cli func (StartSessionCommand) Name() string { return START_SESSION } // Help prints help for the start-session cli command func (c *StartSessionCommand) Help() string { if len(c.helpText) == 0 { t, _ := template.New("StartSessionHelp").Parse(START_SESSION_HELP) params := StartSessionHelpParams{ utils.SsmCliName, START_SESSION, INSTANCE_ID, REGION, PROFILE, ENDPOINT, DOCUMENT_NAME, PARAMETERS, } buf := new(bytes.Buffer) t.Execute(buf, params) c.helpText = buf.String() } return c.helpText } //validates and execute start-session command func (s *StartSessionCommand) Execute(parameters map[string][]string) (error, string) { var ( err error region string profile string endpoint string instanceId string ) validation := s.validateStartSessionInput(parameters) if len(validation) > 0 { return errors.New(strings.Join(validation, "\n")), "" } log := log.Logger(true, "ssmcli") if parameters[REGION] != nil { region = parameters[REGION][0] } if parameters[PROFILE] != nil { profile = parameters[PROFILE][0] } if parameters[ENDPOINT] != nil { endpoint = parameters[ENDPOINT][0] } if parameters[INSTANCE_ID] != nil { instanceId = parameters[INSTANCE_ID][0] } if s.sdk, err = getSSMClient(log, region, profile, endpoint); err != nil { return err, "StartSession failed" } log.Infof("Calling StartSession API with parameters: %v", parameters) sessionId, tokenValue, streamUrl, err := s.getStartSessionParams(log, parameters) if err != nil { log.Errorf("Error in getting start awsSession params: %v", err) return err, "StartSession failed" } log.Infof("For SessionId: %s, StartSession returned streamUrl: %s", sessionId, streamUrl) clientId := uuid.NewV4().String() session := session.Session{ SessionId: sessionId, StreamUrl: streamUrl, TokenValue: tokenValue, Endpoint: endpoint, ClientId: clientId, TargetId: instanceId, DataChannel: &datachannel.DataChannel{}, } if err = executeSession(log, &session); err != nil { log.Errorf("Cannot perform start session: %v", err) return err, "StartSession failed" } return err, "StartSession executed successfully" } //func to validate start-session input func (StartSessionCommand) validateStartSessionInput(parameters map[string][]string) []string { validation := make([]string, 0) instanceIdValue := parameters[INSTANCE_ID] //look for required parameters if instanceIdValue == nil { validation = append(validation, fmt.Sprintf("%v is required", utils.FormatFlag(INSTANCE_ID))) } for key := range parameters { if !contains(ParameterKeys, key) { validation = append(validation, fmt.Sprintf("%v not a valid command parameter flag", key)) } } return validation } func contains(arr []string, item string) bool { for _, v := range arr { if v == item { return true } } return false } // function to get start-session parameters func (s *StartSessionCommand) getStartSessionParams(log log.T, parameters map[string][]string) (string, string, string, error) { //Fetch command token uuid.SwitchFormat(uuid.CleanHyphen) startSessionInput := ssm.StartSessionInput{ Target: &parameters[INSTANCE_ID][0], } if parameters[DOCUMENT_NAME] != nil { startSessionInput.DocumentName = &parameters[DOCUMENT_NAME][0] } delete(parameters, INSTANCE_ID) delete(parameters, DOCUMENT_NAME) delete(parameters, REGION) if parameters["parameters"] != nil && len(parameters["parameters"]) == 1 { userParameters := make(map[string][]*string) params := make(map[string][]string) if err := jsonutil.Unmarshal(parameters[PARAMETERS][0], &params); err != nil { return "", "", "", fmt.Errorf("%v not valid input, get error: %v", PARAMETERS, err) } for k, v := range params { values := make([]*string, len(v)) for index, element := range v { value := element values[index] = &value } userParameters[k] = values } startSessionInput.Parameters = userParameters } log.Infof("StartSession input parameters: %v", startSessionInput) startSessionOutput, err := startSession(s, &startSessionInput) if err != nil { log.Errorf("StartSession Failed: %v", err) return "", "", "", fmt.Errorf("start session failed with error: %v", err) } sessionId := startSessionOutput.SessionId tokenValue := startSessionOutput.TokenValue streamUrl := startSessionOutput.StreamUrl if tokenValue == nil || sessionId == nil || streamUrl == nil { return "", "", "", fmt.Errorf("token value or sessionId or streamUrl should not be empty. \n") } return *sessionId, *tokenValue, *streamUrl, err }
290
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package ssmclicommands contains all the commands with its implementation. package ssmclicommands import ( "fmt" "testing" "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/session-manager-plugin/src/log" "github.com/aws/session-manager-plugin/src/sessionmanagerplugin/session" "github.com/stretchr/testify/assert" ) var ( sessionId = "session_id" streamUrl = "wss://stream_url" tokenValue = "Token_value_123456" startSessionOutput = &ssm.StartSessionOutput{ SessionId: &sessionId, StreamUrl: &streamUrl, TokenValue: &tokenValue, } ) func TestStartSessionCommand_Help(t *testing.T) { command := &StartSessionCommand{ helpText: "StartSessionCommand Help Context", } output := command.Help() assert.Equal(t, output, "StartSessionCommand Help Context") command.helpText = "" output = command.Help() assert.Contains(t, output, "SYNOPSIS:") } func TestStartSessionCommand_ExecuteSuccess(t *testing.T) { parameter, _ := getCommandParameter() parameter[DOCUMENT_NAME] = []string{"AWS-StartPortForwardingSession"} parameter[PARAMETERS] = []string{"{\"portNumber\":[\"80\"],\"localPortNumber\":[\"6789\"]}"} command := &StartSessionCommand{ helpText: "StartSessionCommand Help Context", } getSSMClient = func(log log.T, region string, profile string, endpoint string) (*ssm.SSM, error) { assert.Equal(t, region, "us-east-1") assert.Empty(t, profile) ssmClient := &ssm.SSM{} return ssmClient, nil } executeSession = func(log log.T, session *session.Session) (err error) { assert.NotNil(t, session.DataChannel) return nil } startSession = func(s *StartSessionCommand, input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { assert.Equal(t, *input.Target, "i-123456") assert.Equal(t, *input.Parameters["portNumber"][0], "80") assert.Equal(t, *input.Parameters["localPortNumber"][0], "6789") assert.Equal(t, *input.DocumentName, "AWS-StartPortForwardingSession") return startSessionOutput, nil } err, msg := command.Execute(parameter) assert.Nil(t, err) assert.Equal(t, msg, "StartSession executed successfully") } func TestStartSessionCommand_ExecuteGetSSMClientFailure(t *testing.T) { parameter, _ := getCommandParameter() parameter[PROFILE] = []string{"user1"} command := &StartSessionCommand{ helpText: "StartSessionCommand Help Context", } getSSMClient = func(log log.T, region string, profile string, endpoint string) (*ssm.SSM, error) { assert.Equal(t, profile, "user1") return nil, fmt.Errorf("Get SSMClient Failure") } err, msg := command.Execute(parameter) assert.NotNil(t, err) assert.Equal(t, err.Error(), "Get SSMClient Failure") assert.Equal(t, msg, "StartSession failed") } func TestStartSessionCommand_ExecuteSessionFailure(t *testing.T) { parameter, _ := getCommandParameter() command := &StartSessionCommand{ helpText: "StartSessionCommand Help Context", } getSSMClient = func(log log.T, region string, profile string, endpoint string) (*ssm.SSM, error) { ssmClient := &ssm.SSM{} return ssmClient, nil } executeSession = func(log log.T, session *session.Session) (err error) { return fmt.Errorf("Execute Session Failure") } startSession = func(s *StartSessionCommand, input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { return startSessionOutput, nil } err, msg := command.Execute(parameter) assert.NotNil(t, err) assert.Equal(t, err.Error(), "Execute Session Failure") assert.Equal(t, msg, "StartSession failed") } func TestStartSessionCommand_validateStartSessionInput(t *testing.T) { parameter, _ := getCommandParameter() command := &StartSessionCommand{} validation := command.validateStartSessionInput(parameter) assert.Equal(t, len(validation), 0) } func TestStartSessionCommand_validateStartSessionInputWithoutRequiredParameters(t *testing.T) { parameters := map[string][]string{INSTANCE_ID: nil} command := &StartSessionCommand{} validation := command.validateStartSessionInput(parameters) assert.Equal(t, len(validation), 1) assert.Equal(t, validation[0], "--instance-id is required") } func TestStartSessionCommand_validateStartSessionInputWithInvalidParameters(t *testing.T) { parameters := map[string][]string{INSTANCE_ID: nil, "random-params": nil} command := &StartSessionCommand{} validation := command.validateStartSessionInput(parameters) assert.Equal(t, len(validation), 2) assert.Equal(t, validation[0], "--instance-id is required") assert.Equal(t, validation[1], "random-params not a valid command parameter flag") } func TestStartSessionCommand_getStartSessionParams(t *testing.T) { parameters, _ := getCommandParameter() command := &StartSessionCommand{} log := log.NewMockLog() startSession = func(s *StartSessionCommand, input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { return startSessionOutput, nil } id, token, url, err := command.getStartSessionParams(log, parameters) assert.Nil(t, err) assert.Equal(t, id, sessionId) assert.Equal(t, token, tokenValue) assert.Equal(t, url, streamUrl) } func TestStartSessionCommand_getStartSessionParamsWithStartSessionFailure(t *testing.T) { parameters, _ := getCommandParameter() command := &StartSessionCommand{} log := log.NewMockLog() startSession = func(s *StartSessionCommand, input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { return nil, fmt.Errorf("SendStartSession Failure") } id, token, url, err := command.getStartSessionParams(log, parameters) assert.NotNil(t, err) assert.Equal(t, err.Error(), "start session failed with error: SendStartSession Failure") assert.Empty(t, id) assert.Empty(t, token) assert.Empty(t, url) } func TestStartSessionCommand_getStartSessionParamsWithNilOutput(t *testing.T) { parameters, _ := getCommandParameter() command := &StartSessionCommand{} log := log.NewMockLog() output := &ssm.StartSessionOutput{} startSession = func(s *StartSessionCommand, input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { return output, nil } id, token, url, err := command.getStartSessionParams(log, parameters) assert.NotNil(t, err) assert.Contains(t, err.Error(), "token value or sessionId or streamUrl should not be empty.") assert.Empty(t, id) assert.Empty(t, token) assert.Empty(t, url) } func getCommandParameter() (parameters map[string][]string, err error) { args := []string{1: "start-session", 2: "--instance-id", 3: "i-123456", 4: "--region", 5: "us-east-1"} err, _, _, _, parameter := ParseCliCommand(args) return parameter, err }
202
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package utils contains all the utility functions. package utils import ( "fmt" "io" "sort" ) // DisplayCommandUsage prints cli usage info to console func DisplayCommandUsage(out io.Writer) { fmt.Fprintf(out, "usage: %v [options] <command> [parameters]\n", SsmCliName) fmt.Fprintf(out, "To see help text, you can run:\n\n") fmt.Fprintf(out, " %v %v\n", SsmCliName, HelpFlag) fmt.Fprintf(out, " %v <command> %v\n", SsmCliName, HelpFlag) } // DisplayHelp shows help for the ssmcli func DisplayHelp(out io.Writer) { fmt.Fprintf(out, "%v\n", SsmCliName) fmt.Fprintf(out, "Available commands are:\n") DisplaySupportedCommands(out) } // DisplaySupportedCommands prints a list of supported cli commands to the console func DisplaySupportedCommands(out io.Writer) { commands := make([]string, 0, len(SsmCliCommands)) for command := range SsmCliCommands { commands = append(commands, command) } sort.Strings(commands) for _, command := range commands { fmt.Fprintf(out, "%v\n", command) } }
49
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package utils contains all the utility functions. package utils import ( "fmt" "strings" ) const ( HelpFlag = "help" SsmCliName = "ssmcli" FlagPrefix = "--" ) // CliCommands is the set of support commands var SsmCliCommands map[string]SsmCliCommand // CliCommand defines the interface for all commands the cli can execute type SsmCliCommand interface { Execute(parameters map[string][]string) (error, string) Help() string Name() string } // init creates the map of commands - all imported commands will add themselves to the map func init() { SsmCliCommands = make(map[string]SsmCliCommand) } // Register func Register(command SsmCliCommand) { SsmCliCommands[command.Name()] = command } // IsFlag returns true if val is a flag func IsFlag(val string) bool { return strings.HasPrefix(val, FlagPrefix) } // GetFlag returns the flag name if val is a flag, or empty if it is not func GetFlag(val string) string { if strings.HasPrefix(val, FlagPrefix) { return strings.ToLower(strings.TrimLeft(val, FlagPrefix)) } return "" } // IsHelp determines if a subcommand or flag is a request for help func IsHelp(subcommand string, parameters map[string][]string) bool { if subcommand == HelpFlag { return true } if _, exists := parameters[HelpFlag]; exists { return true } return false } // FormatFlag returns a parameter name formatted as a command line flag func FormatFlag(flagName string) string { return fmt.Sprintf("%v%v", FlagPrefix, flagName) }
78
session-manager-plugin
aws
Go
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is an autogenerated file. // Changes made to this file will be overwritten during the build process. // Package version contains CLI version constant and utilities. package version // Version is the version of the CLI const Version = "1.2.0.0"
13
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package version contains CLI version constant and utilities. package version import ( "fmt" "strconv" "strings" ) type version struct { version []string } // NewVersion initializes version struct by splitting given version string into string list using separator "." func NewVersion(versionString string) (version, error) { if versionString == "" { return version{}, fmt.Errorf("invalid version %s", versionString) } return version{ strings.Split(versionString, "."), }, nil } // compare returns 0 if thisVersion is equal to otherVersion, 1 if thisVersion is greater than otherVersion, -1 otherwise func (thisVersion version) compare(otherVersion version) (int, error) { if len(thisVersion.version) != len(otherVersion.version) { return -1, fmt.Errorf("length mismatch for versions %s and %s", thisVersion.version, otherVersion.version) } var ( thisVersionSlice int otherVersionSlice int err error ) for i := range thisVersion.version { if thisVersionSlice, err = strconv.Atoi(thisVersion.version[i]); err != nil { return -1, err } if otherVersionSlice, err = strconv.Atoi(otherVersion.version[i]); err != nil { return -1, err } if thisVersionSlice > otherVersionSlice { return 1, nil } else if thisVersionSlice < otherVersionSlice { return -1, nil } } return 0, nil }
65
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package version contains version constants and utilities. package version import ( "testing" "github.com/stretchr/testify/assert" ) func TestCompareWhenVersionsAreSame(t *testing.T) { thisVersion, err := NewVersion("2.3.617.9") assert.Nil(t, err) otherVersion, err := NewVersion("2.3.617.9") assert.Nil(t, err) actual, err := thisVersion.compare(otherVersion) assert.Nil(t, err) assert.Equal(t, 0, actual) } func TestCompareWhenThisVersionIsGreaterThanOtherVersion(t *testing.T) { thisVersion, err := NewVersion("2.3.617.9") assert.Nil(t, err) otherVersion, err := NewVersion("2.3.56.9") assert.Nil(t, err) actual, err := thisVersion.compare(otherVersion) assert.Nil(t, err) assert.Equal(t, 1, actual) } func TestCompareWhenThisVersionIsLesserThanOtherVersion(t *testing.T) { thisVersion, err := NewVersion("2.3.617.9") assert.Nil(t, err) otherVersion, err := NewVersion("2.10.763.9") assert.Nil(t, err) actual, err := thisVersion.compare(otherVersion) assert.Nil(t, err) assert.Equal(t, -1, actual) } func TestCompareWhenVersionsLengthMismatch(t *testing.T) { thisVersion, err := NewVersion("2.3.56.0") assert.Nil(t, err) otherVersion, err := NewVersion("2.5.45") assert.Nil(t, err) _, err = thisVersion.compare(otherVersion) assert.NotNil(t, err) } func TestNewVersion(t *testing.T) { version, err := NewVersion("2.3.525.0") assert.Nil(t, err) assert.Equal(t, []string{"2", "3", "525", "0"}, version.version) } func TestNewVersionWhenGivenVersionIsEmptyString(t *testing.T) { _, err := NewVersion("") assert.NotNil(t, err) }
80
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package version contains version constants and utilities. package version import ( "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" ) // DoesAgentSupportTCPMultiplexing returns true if given agentVersion supports TCP multiplexing in port plugin, false otherwise func DoesAgentSupportTCPMultiplexing(log log.T, agentVersion string) (supported bool) { return isAgentVersionGreaterThanSupportedVersion(log, agentVersion, config.TCPMultiplexingSupportedAfterThisAgentVersion) } // DoesAgentSupportDisableSmuxKeepAlive returns true if given agentVersion disables smux KeepAlive in TCP multiplexing in port plugin, false otherwise func DoesAgentSupportDisableSmuxKeepAlive(log log.T, agentVersion string) (supported bool) { return isAgentVersionGreaterThanSupportedVersion(log, agentVersion, config.TCPMultiplexingWithSmuxKeepAliveDisabledAfterThisAgentVersion) } // DoesAgentSupportTerminateSessionFlag returns true if given agentVersion supports TerminateSession flag, false otherwise func DoesAgentSupportTerminateSessionFlag(log log.T, agentVersion string) (supported bool) { return isAgentVersionGreaterThanSupportedVersion(log, agentVersion, config.TerminateSessionFlagSupportedAfterThisAgentVersion) } // isAgentVersionGreaterThanSupportedVersion returns true if agentVersion is greater than supportedVersion, // false in case of any error and agentVersion is equalTo or less than supportedVersion func isAgentVersionGreaterThanSupportedVersion(log log.T, agentVersionString string, supportedVersionString string) (supported bool) { var ( supportedVersion version agentVersion version compareResult int err error ) if supportedVersion, err = NewVersion(supportedVersionString); err != nil { log.Debugf("supportedVersion initialization failed, %v", err) return } if agentVersion, err = NewVersion(agentVersionString); err != nil { log.Debugf("agentVersion initialization failed, %v", err) return } if compareResult, err = agentVersion.compare(supportedVersion); err != nil { log.Debugf("version comparison failed, %v", err) return } if compareResult == 1 { supported = true } return }
66
session-manager-plugin
aws
Go
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package version contains version constants and utilities. package version import ( "testing" "github.com/aws/session-manager-plugin/src/config" "github.com/aws/session-manager-plugin/src/log" "github.com/stretchr/testify/assert" ) type Comparison struct { agentVersion string supportedVersion string } var mockLog = log.NewMockLog() func TestDoesAgentSupportTCPMultiplexing(t *testing.T) { // Test exact version of feature; TCPMultiplexingSupported after 3.0.196.0 assert.False(t, DoesAgentSupportTCPMultiplexing(mockLog, config.TCPMultiplexingSupportedAfterThisAgentVersion)) // Test versions prior to feature implementation oldVersions := []string{ "1.2.3.4", "2.3.4.5", "3.0.195.100", "2.99.1000.0", } for _, tc := range oldVersions { assert.False(t, DoesAgentSupportTCPMultiplexing(mockLog, tc)) } // Test versions after feature implementation newVersions := []string{ "3.1.0.0", "3.0.197.0", "3.0.196.1", "4.0.0.0", } for _, tc := range newVersions { assert.True(t, DoesAgentSupportTCPMultiplexing(mockLog, tc)) } } func TestDoesAgentSupportTerminateSessionFlag(t *testing.T) { // Test exact version of feature; TerminateSessionFlag supported after 2.3.722.0 assert.False(t, DoesAgentSupportTerminateSessionFlag(mockLog, config.TerminateSessionFlagSupportedAfterThisAgentVersion)) // Test versions prior to feature implementation oldVersions := []string{ "1.2.3.4", "2.3.4.5", "2.3.721.100", "0.3.1000.0", } for _, tc := range oldVersions { assert.False(t, DoesAgentSupportTerminateSessionFlag(mockLog, tc)) } // Test versions after feature implementation newVersions := []string{ "3.1.0.0", "3.0.197.0", "2.3.723.0", "4.0.0.0", } for _, tc := range newVersions { assert.True(t, DoesAgentSupportTerminateSessionFlag(mockLog, tc)) } } func TestIsAgentVersionGreaterThanSupportedVersionWithNormalInputs(t *testing.T) { const ( defaultSupportedVersion = "3.0.0.0" ) // Test normal inputs where agentVersion <= supportedVersion normalNegativeCases := []Comparison{ {"3.0.0.0", defaultSupportedVersion}, {"1.2.3.4", defaultSupportedVersion}, {"2.99.99.99", defaultSupportedVersion}, {"3.4.5.2", "3.4.5.2"}, } for _, tc := range normalNegativeCases { assert.False(t, isAgentVersionGreaterThanSupportedVersion(mockLog, tc.agentVersion, tc.supportedVersion)) } // Test normal inputs where agentVersion > supportedVersion normalPositiveCases := []Comparison{ {"3.0.0.1", defaultSupportedVersion}, {"4.0.0.0", defaultSupportedVersion}, {"3.1.0.0", defaultSupportedVersion}, {"3.0.100.0", defaultSupportedVersion}, {"5.0.0.2", "5.0.0.0"}, } for _, tc := range normalPositiveCases { assert.True(t, isAgentVersionGreaterThanSupportedVersion(mockLog, tc.agentVersion, tc.supportedVersion)) } } func TestIsAgentVersionGreaterThanSupportedVersionEdgeCases(t *testing.T) { // Test non-numeric strings t.Run("Non-numeric strings", func(t *testing.T) { errorLog := log.NewMockLog() notNumberCase := Comparison{"randomString", "randomString"} assert.False(t, isAgentVersionGreaterThanSupportedVersion(errorLog, notNumberCase.agentVersion, notNumberCase.supportedVersion)) }) t.Run("Uneven-length strings", func(t *testing.T) { errorLog := log.NewMockLog() unevenLengthCase := Comparison{"1.4.1.2.4.1", "3.0.0.0"} assert.False(t, isAgentVersionGreaterThanSupportedVersion(errorLog, unevenLengthCase.agentVersion, unevenLengthCase.supportedVersion)) }) t.Run("Invalid Version Numbers", func(t *testing.T) { errorLog := log.NewMockLog() invalidVersionNumberCases := []Comparison{ {"", "3.0.0.0"}, {"3.0.0.0", ""}, {"3,0.0.0", "3.0.2.0"}, } for _, tc := range invalidVersionNumberCases { assert.False(t, isAgentVersionGreaterThanSupportedVersion(errorLog, tc.agentVersion, tc.supportedVersion)) } }) } func TestDoesAgentSupportTerminateSessionFlagForSupportedScenario(t *testing.T) { assert.True(t, DoesAgentSupportTerminateSessionFlag(mockLog, "2.3.750.0")) } func TestDoesAgentSupportTerminateSessionFlagForNotSupportedScenario(t *testing.T) { assert.False(t, DoesAgentSupportTerminateSessionFlag(mockLog, "2.3.614.0")) } func TestDoesAgentSupportTerminateSessionFlagWhenAgentVersionIsEqualSupportedAfterVersion(t *testing.T) { assert.False(t, DoesAgentSupportTerminateSessionFlag(mockLog, "2.3.722.0")) } func TestDoesAgentSupportDisableSmuxKeepAliveForNotSupportedScenario(t *testing.T) { assert.False(t, DoesAgentSupportDisableSmuxKeepAlive(mockLog, "3.1.1476.0")) } func TestDoesAgentSupportDisableSmuxKeepAliveForSupportedScenario(t *testing.T) { assert.True(t, DoesAgentSupportDisableSmuxKeepAlive(mockLog, "3.1.1600.0")) }
159
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package main represents the entry point to generate version. package main import ( "fmt" "io/ioutil" "log" "os" "path/filepath" "text/template" ) const ( ReadWriteAccess = 0600 LicenseString = "// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\n" VersiongoTemplate = `// This is an autogenerated file. // Changes made to this file will be overwritten during the build process. // Package version contains CLI version constant and utilities. package version // Version is the version of the CLI const Version = "{{.Version}}" ` ) // version-gen is a simple program that generates the plugin's version file, // containing information about the plugin's version func main() { versionContent, err := ioutil.ReadFile(filepath.Join("VERSION")) if err != nil { log.Fatalf("Error reading VERSION file. %v", err) } versionStr := string(versionContent) fmt.Printf("Session Manager Plugin Version: %v\n", versionStr) if err := ioutil.WriteFile(filepath.Join("VERSION"), []byte(versionStr), ReadWriteAccess); err != nil { log.Fatalf("Error writing to VERSION file. %v", err) } versionFilePath := filepath.Join("src", "version", "version.go") // Generate version.go type versionInfo struct { Version string } info := versionInfo{ Version: versionStr, } t := template.Must(template.New("version").Parse(string(LicenseString) + VersiongoTemplate)) outFile, err := os.Create(versionFilePath) if err != nil { log.Fatalf("Unable to create output version file: %v", err) } defer outFile.Close() err = t.Execute(outFile, info) if err != nil { log.Fatalf("Error applying template: %v", err) } }
78
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package websocketutil contains methods for interacting with websocket connections. package websocketutil import ( "errors" "github.com/aws/session-manager-plugin/src/log" "github.com/gorilla/websocket" ) // IWebsocketUtil is the interface for the websocketutil. type IWebsocketUtil interface { OpenConnection(url string) (*websocket.Conn, error) CloseConnection(ws websocket.Conn) error } // WebsocketUtil struct provides functionality around creating and maintaining websockets. type WebsocketUtil struct { dialer *websocket.Dialer log log.T } // NewWebsocketUtil is the factory function for websocketutil. func NewWebsocketUtil(logger log.T, dialerInput *websocket.Dialer) *WebsocketUtil { var websocketUtil *WebsocketUtil if dialerInput == nil { websocketUtil = &WebsocketUtil{ dialer: websocket.DefaultDialer, log: logger, } } else { websocketUtil = &WebsocketUtil{ dialer: dialerInput, log: logger, } } return websocketUtil } // OpenConnection opens a websocket connection provided an input url. func (u *WebsocketUtil) OpenConnection(url string) (*websocket.Conn, error) { u.log.Infof("Opening websocket connection to: ", url) conn, _, err := u.dialer.Dial(url, nil) if err != nil { u.log.Errorf("Failed to dial websocket: %s", err.Error()) return nil, err } u.log.Infof("Successfully opened websocket connection to: ", url) return conn, err } // CloseConnection closes a websocket connection given the Conn object as input. func (u *WebsocketUtil) CloseConnection(ws *websocket.Conn) error { if ws == nil { return errors.New("websocket conn object is nil") } u.log.Debugf("Closing websocket connection to:", ws.RemoteAddr().String()) err := ws.Close() if err != nil { u.log.Errorf("Failed to close websocket: %s", err.Error()) return err } u.log.Debugf("Successfully closed websocket connection to:", ws.RemoteAddr().String()) return nil }
91
session-manager-plugin
aws
Go
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may not // use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package websocketutil contains methods for interacting with websocket connections. package websocketutil import ( "fmt" "net/http" "net/http/httptest" "net/url" "testing" "github.com/aws/session-manager-plugin/src/log" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func handlerToBeTested(w http.ResponseWriter, req *http.Request) { conn, err := upgrader.Upgrade(w, req, nil) if err != nil { http.Error(w, fmt.Sprintf("cannot upgrade: %v", err), http.StatusInternalServerError) } mt, p, err := conn.ReadMessage() if err != nil { return } conn.WriteMessage(mt, []byte("hello "+string(p))) } func TestWebsocketUtilOpenCloseConnection(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(handlerToBeTested)) u, _ := url.Parse(srv.URL) u.Scheme = "ws" var log = log.NewMockLog() var ws = NewWebsocketUtil(log, nil) conn, _ := ws.OpenConnection(u.String()) assert.NotNil(t, conn, "Open connection failed.") err := ws.CloseConnection(conn) assert.Nil(t, err, "Error closing the websocket connection.") } func TestWebsocketUtilOpenConnectionInvalidUrl(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(handlerToBeTested)) u, _ := url.Parse(srv.URL) u.Scheme = "ws" var log = log.NewMockLog() var ws = NewWebsocketUtil(log, nil) conn, _ := ws.OpenConnection("InvalidUrl") assert.Nil(t, conn, "Open connection failed.") err := ws.CloseConnection(conn) assert.NotNil(t, err, "Error closing the websocket connection.") } func TestSendMessage(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(handlerToBeTested)) u, _ := url.Parse(srv.URL) u.Scheme = "ws" var log = log.NewMockLog() var ws = NewWebsocketUtil(log, nil) conn, _ := ws.OpenConnection(u.String()) assert.NotNil(t, conn, "Open connection failed.") conn.WriteMessage(websocket.TextMessage, []byte("testing testing")) err := ws.CloseConnection(conn) assert.Nil(t, err, "Error closing the websocket connection.") }
86
session-manager-plugin
aws
Go
// Package sdk is the official AWS SDK for the Go programming language. // // The AWS SDK for Go provides APIs and utilities that developers can use to // build Go applications that use AWS services, such as Amazon Elastic Compute // Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). // // The SDK removes the complexity of coding directly against a web service // interface. It hides a lot of the lower-level plumbing, such as authentication, // request retries, and error handling. // // The SDK also includes helpful utilities on top of the AWS APIs that add additional // capabilities and functionality. For example, the Amazon S3 Download and Upload // Manager will automatically split up large objects into multiple parts and // transfer them concurrently. // // See the s3manager package documentation for more information. // https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/ // // Getting More Information // // Checkout the Getting Started Guide and API Reference Docs detailed the SDK's // components and details on each AWS client the SDK supports. // // The Getting Started Guide provides examples and detailed description of how // to get setup with the SDK. // https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html // // The API Reference Docs include a detailed breakdown of the SDK's components // such as utilities and AWS clients. Use this as a reference of the Go types // included with the SDK, such as AWS clients, API operations, and API parameters. // https://docs.aws.amazon.com/sdk-for-go/api/ // // Overview of SDK's Packages // // The SDK is composed of two main components, SDK core, and service clients. // The SDK core packages are all available under the aws package at the root of // the SDK. Each client for a supported AWS service is available within its own // package under the service folder at the root of the SDK. // // * aws - SDK core, provides common shared types such as Config, Logger, // and utilities to make working with API parameters easier. // // * awserr - Provides the error interface that the SDK will use for all // errors that occur in the SDK's processing. This includes service API // response errors as well. The Error type is made up of a code and message. // Cast the SDK's returned error type to awserr.Error and call the Code // method to compare returned error to specific error codes. See the package's // documentation for additional values that can be extracted such as RequestId. // // * credentials - Provides the types and built in credentials providers // the SDK will use to retrieve AWS credentials to make API requests with. // Nested under this folder are also additional credentials providers such as // stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. // // * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. // Use this to lookup AWS service endpoint information such as which services // are in a region, and what regions a service is in. Constants are also provided // for all region identifiers, e.g UsWest2RegionID for "us-west-2". // // * session - Provides initial default configuration, and load // configuration from external sources such as environment and shared // credentials file. // // * request - Provides the API request sending, and retry logic for the SDK. // This package also includes utilities for defining your own request // retryer, and configuring how the SDK processes the request. // // * service - Clients for AWS services. All services supported by the SDK are // available under this folder. // // How to Use the SDK's AWS Service Clients // // The SDK includes the Go types and utilities you can use to make requests to // AWS service APIs. Within the service folder at the root of the SDK you'll find // a package for each AWS service the SDK supports. All service clients follows // a common pattern of creation and usage. // // When creating a client for an AWS service you'll first need to have a Session // value constructed. The Session provides shared configuration that can be shared // between your service clients. When service clients are created you can pass // in additional configuration via the aws.Config type to override configuration // provided by in the Session to create service client instances with custom // configuration. // // Once the service's client is created you can use it to make API requests the // AWS service. These clients are safe to use concurrently. // // Configuring the SDK // // In the AWS SDK for Go, you can configure settings for service clients, such // as the log level and maximum number of retries. Most settings are optional; // however, for each service client, you must specify a region and your credentials. // The SDK uses these values to send requests to the correct AWS region and sign // requests with the correct credentials. You can specify these values as part // of a session or as environment variables. // // See the SDK's configuration guide for more information. // https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html // // See the session package documentation for more information on how to use Session // with the SDK. // https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ // // See the Config type in the aws package for more information on configuration // options. // https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config // // Configuring Credentials // // When using the SDK you'll generally need your AWS credentials to authenticate // with AWS services. The SDK supports multiple methods of supporting these // credentials. By default the SDK will source credentials automatically from // its default credential chain. See the session package for more information // on this chain, and how to configure it. The common items in the credential // chain are the following: // // * Environment Credentials - Set of environment variables that are useful // when sub processes are created for specific roles. // // * Shared Credentials file (~/.aws/credentials) - This file stores your // credentials based on a profile name and is useful for local development. // // * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials // to application running on an EC2 instance. This removes the need to manage // credential files in production. // // Credentials can be configured in code as well by setting the Config's Credentials // value to a custom provider or using one of the providers included with the // SDK to bypass the default credential chain and use a custom one. This is // helpful when you want to instruct the SDK to only use a specific set of // credentials or providers. // // This example creates a credential provider for assuming an IAM role, "myRoleARN" // and configures the S3 service client to use that role for API requests. // // // Initial credentials loaded from SDK's default credential chain. Such as // // the environment, shared credentials (~/.aws/credentials), or EC2 Instance // // Role. These credentials will be used to to make the STS Assume Role API. // sess := session.Must(session.NewSession()) // // // Create the credentials from AssumeRoleProvider to assume the role // // referenced by the "myRoleARN" ARN. // creds := stscreds.NewCredentials(sess, "myRoleArn") // // // Create service client value configured for credentials // // from assumed role. // svc := s3.New(sess, &aws.Config{Credentials: creds})/ // // See the credentials package documentation for more information on credential // providers included with the SDK, and how to customize the SDK's usage of // credentials. // https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials // // The SDK has support for the shared configuration file (~/.aws/config). This // support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", // or enabling the feature in code when creating a Session via the // Option's SharedConfigState parameter. // // sess := session.Must(session.NewSessionWithOptions(session.Options{ // SharedConfigState: session.SharedConfigEnable, // })) // // Configuring AWS Region // // In addition to the credentials you'll need to specify the region the SDK // will use to make AWS API requests to. In the SDK you can specify the region // either with an environment variable, or directly in code when a Session or // service client is created. The last value specified in code wins if the region // is specified multiple ways. // // To set the region via the environment variable set the "AWS_REGION" to the // region you want to the SDK to use. Using this method to set the region will // allow you to run your application in multiple regions without needing additional // code in the application to select the region. // // AWS_REGION=us-west-2 // // The endpoints package includes constants for all regions the SDK knows. The // values are all suffixed with RegionID. These values are helpful, because they // reduce the need to type the region string manually. // // To set the region on a Session use the aws package's Config struct parameter // Region to the AWS region you want the service clients created from the session to // use. This is helpful when you want to create multiple service clients, and // all of the clients make API requests to the same region. // // sess := session.Must(session.NewSession(&aws.Config{ // Region: aws.String(endpoints.UsWest2RegionID), // })) // // See the endpoints package for the AWS Regions and Endpoints metadata. // https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ // // In addition to setting the region when creating a Session you can also set // the region on a per service client bases. This overrides the region of a // Session. This is helpful when you want to create service clients in specific // regions different from the Session's region. // // svc := s3.New(sess, &aws.Config{ // Region: aws.String(endpoints.UsWest2RegionID), // }) // // See the Config type in the aws package for more information and additional // options such as setting the Endpoint, and other service client configuration options. // https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config // // Making API Requests // // Once the client is created you can make an API request to the service. // Each API method takes a input parameter, and returns the service response // and an error. The SDK provides methods for making the API call in multiple ways. // // In this list we'll use the S3 ListObjects API as an example for the different // ways of making API requests. // // * ListObjects - Base API operation that will make the API request to the service. // // * ListObjectsRequest - API methods suffixed with Request will construct the // API request, but not send it. This is also helpful when you want to get a // presigned URL for a request, and share the presigned URL instead of your // application making the request directly. // // * ListObjectsPages - Same as the base API operation, but uses a callback to // automatically handle pagination of the API's response. // // * ListObjectsWithContext - Same as base API operation, but adds support for // the Context pattern. This is helpful for controlling the canceling of in // flight requests. See the Go standard library context package for more // information. This method also takes request package's Option functional // options as the variadic argument for modifying how the request will be // made, or extracting information from the raw HTTP response. // // * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for // the Context pattern. Similar to ListObjectsWithContext this method also // takes the request package's Option function option types as the variadic // argument. // // In addition to the API operations the SDK also includes several higher level // methods that abstract checking for and waiting for an AWS resource to be in // a desired state. In this list we'll use WaitUntilBucketExists to demonstrate // the different forms of waiters. // // * WaitUntilBucketExists. - Method to make API request to query an AWS service for // a resource's state. Will return successfully when that state is accomplished. // // * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds // support for the Context pattern. In addition these methods take request // package's WaiterOptions to configure the waiter, and how underlying request // will be made by the SDK. // // The API method will document which error codes the service might return for // the operation. These errors will also be available as const strings prefixed // with "ErrCode" in the service client's package. If there are no errors listed // in the API's SDK documentation you'll need to consult the AWS service's API // documentation for the errors that could be returned. // // ctx := context.Background() // // result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ // Bucket: aws.String("my-bucket"), // Key: aws.String("my-key"), // }) // if err != nil { // // Cast err to awserr.Error to handle specific error codes. // aerr, ok := err.(awserr.Error) // if ok && aerr.Code() == s3.ErrCodeNoSuchKey { // // Specific error code handling // } // return err // } // // // Make sure to close the body when done with it for S3 GetObject APIs or // // will leak connections. // defer result.Body.Close() // // fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) // // API Request Pagination and Resource Waiters // // Pagination helper methods are suffixed with "Pages", and provide the // functionality needed to round trip API page requests. Pagination methods // take a callback function that will be called for each page of the API's response. // // objects := []string{} // err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ // Bucket: aws.String(myBucket), // }, func(p *s3.ListObjectsOutput, lastPage bool) bool { // for _, o := range p.Contents { // objects = append(objects, aws.StringValue(o.Key)) // } // return true // continue paging // }) // if err != nil { // panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) // } // // fmt.Println("Objects in bucket:", objects) // // Waiter helper methods provide the functionality to wait for an AWS resource // state. These methods abstract the logic needed to to check the state of an // AWS resource, and wait until that resource is in a desired state. The waiter // will block until the resource is in the state that is desired, an error occurs, // or the waiter times out. If a resource times out the error code returned will // be request.WaiterResourceNotReadyErrorCode. // // err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ // Bucket: aws.String(myBucket), // }) // if err != nil { // aerr, ok := err.(awserr.Error) // if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { // fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") // } // panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) // } // fmt.Println("Bucket", myBucket, "exists") // // Complete SDK Example // // This example shows a complete working Go file which will upload a file to S3 // and use the Context pattern to implement timeout logic that will cancel the // request if it takes too long. This example highlights how to use sessions, // create a service client, make a request, handle the error, and process the // response. // // 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() // // // All clients require a Session. The Session provides the client with // // shared configuration such as region, endpoint, and credentials. A // // Session should be shared where possible to take advantage of // // configuration and credential caching. See the session package for // // more information. // sess := session.Must(session.NewSession()) // // // Create a new instance of the service's client with a Session. // // Optional aws.Config values can also be provided as variadic arguments // // to the New function. This option allows you to provide service // // specific configuration. // 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) // } package sdk import ( "github.com/jmespath/go-jmespath" ) const _ = jmespath.ASTEmpty
412
session-manager-plugin
aws
Go
package aws import ( "net/http" "time" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" ) // UseServiceDefaultRetries instructs the config to use the service's own // default number of retries. This will be the default action if // Config.MaxRetries is nil also. const UseServiceDefaultRetries = -1 // RequestRetryer is an alias for a type that implements the request.Retryer // interface. type RequestRetryer interface{} // A Config provides service configuration for service clients. By default, // all clients will use the defaults.DefaultConfig structure. // // // Create Session with MaxRetries configuration to be shared by multiple // // service clients. // sess := session.Must(session.NewSession(&aws.Config{ // MaxRetries: aws.Int(3), // })) // // // Create S3 service client with a specific Region. // svc := s3.New(sess, &aws.Config{ // Region: aws.String("us-west-2"), // }) type Config struct { // Enables verbose error printing of all credential chain errors. // Should be used when wanting to see all errors while attempting to // retrieve credentials. CredentialsChainVerboseErrors *bool // The credentials object to use when signing requests. Defaults to a // chain of credential providers to search for credentials in environment // variables, shared credential file, and EC2 Instance Roles. Credentials *credentials.Credentials // An optional endpoint URL (hostname only or fully qualified URI) // that overrides the default generated endpoint for a client. Set this // to `nil` or the value to `""` to use the default generated endpoint. // // Note: You must still provide a `Region` value when specifying an // endpoint for a client. Endpoint *string // The resolver to use for looking up endpoints for AWS service clients // to use based on region. EndpointResolver endpoints.Resolver // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call // ShouldRetry regardless of whether or not if request.Retryable is set. // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck // is not set, then ShouldRetry will only be called if request.Retryable is nil. // Proper handling of the request.Retryable field is important when setting this field. EnforceShouldRetryCheck *bool // The region to send requests to. This parameter is required and must // be configured globally or on a per-client basis unless otherwise // noted. A full list of regions is found in the "Regions and Endpoints" // document. // // See http://docs.aws.amazon.com/general/latest/gr/rande.html for AWS // Regions and Endpoints. Region *string // Set this to `true` to disable SSL when sending requests. Defaults // to `false`. DisableSSL *bool // The HTTP client to use when sending requests. Defaults to // `http.DefaultClient`. HTTPClient *http.Client // An integer value representing the logging level. The default log level // is zero (LogOff), which represents no logging. To enable logging set // to a LogLevel Value. LogLevel *LogLevelType // The logger writer interface to write logging messages to. Defaults to // standard out. Logger Logger // The maximum number of times that a request will be retried for failures. // Defaults to -1, which defers the max retry setting to the service // specific configuration. MaxRetries *int // Retryer guides how HTTP requests should be retried in case of // recoverable failures. // // When nil or the value does not implement the request.Retryer interface, // the client.DefaultRetryer will be used. // // When both Retryer and MaxRetries are non-nil, the former is used and // the latter ignored. // // To set the Retryer field in a type-safe manner and with chaining, use // the request.WithRetryer helper function: // // cfg := request.WithRetryer(aws.NewConfig(), myRetryer) // Retryer RequestRetryer // Disables semantic parameter validation, which validates input for // missing required fields and/or other semantic request input errors. DisableParamValidation *bool // Disables the computation of request and response checksums, e.g., // CRC32 checksums in Amazon DynamoDB. DisableComputeChecksums *bool // Set this to `true` to force the request to use path-style addressing, // i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client // will use virtual hosted bucket addressing when possible // (`http://BUCKET.s3.amazonaws.com/KEY`). // // Note: This configuration option is specific to the Amazon S3 service. // // See http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html // for Amazon S3: Virtual Hosting of Buckets S3ForcePathStyle *bool // Set this to `true` to disable the SDK adding the `Expect: 100-Continue` // header to PUT requests over 2MB of content. 100-Continue instructs the // HTTP client not to send the body until the service responds with a // `continue` status. This is useful to prevent sending the request body // until after the request is authenticated, and validated. // // http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html // // 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s // `ExpectContinueTimeout` for information on adjusting the continue wait // timeout. https://golang.org/pkg/net/http/#Transport // // You should use this flag to disable 100-Continue if you experience issues // with proxies or third party S3 compatible services. S3Disable100Continue *bool // Set this to `true` to enable S3 Accelerate feature. For all operations // compatible with S3 Accelerate will use the accelerate endpoint for // requests. Requests not compatible will fall back to normal S3 requests. // // The bucket must be enable for accelerate to be used with S3 client with // accelerate enabled. If the bucket is not enabled for accelerate an error // will be returned. The bucket name must be DNS compatible to also work // with accelerate. S3UseAccelerate *bool // S3DisableContentMD5Validation config option is temporarily disabled, // For S3 GetObject API calls, #1837. // // Set this to `true` to disable the S3 service client from automatically // adding the ContentMD5 to S3 Object Put and Upload API calls. This option // will also disable the SDK from performing object ContentMD5 validation // on GetObject API calls. S3DisableContentMD5Validation *bool // Set this to `true` to have the S3 service client to use the region specified // in the ARN, when an ARN is provided as an argument to a bucket parameter. S3UseARNRegion *bool // Set this to `true` to enable the SDK to unmarshal API response header maps to // normalized lower case map keys. // // For example S3's X-Amz-Meta prefixed header will be unmarshaled to lower case // Metadata member's map keys. The value of the header in the map is unaffected. LowerCaseHeaderMaps *bool // Set this to `true` to disable the EC2Metadata client from overriding the // default http.Client's Timeout. This is helpful if you do not want the // EC2Metadata client to create a new http.Client. This options is only // meaningful if you're not already using a custom HTTP client with the // SDK. Enabled by default. // // Must be set and provided to the session.NewSession() in order to disable // the EC2Metadata overriding the timeout for default credentials chain. // // Example: // sess := session.Must(session.NewSession(aws.NewConfig() // .WithEC2MetadataDisableTimeoutOverride(true))) // // svc := s3.New(sess) // EC2MetadataDisableTimeoutOverride *bool // Instructs the endpoint to be generated for a service client to // be the dual stack endpoint. The dual stack endpoint will support // both IPv4 and IPv6 addressing. // // Setting this for a service which does not support dual stack will fail // to make requests. It is not recommended to set this value on the session // as it will apply to all service clients created with the session. Even // services which don't support dual stack endpoints. // // If the Endpoint config value is also provided the UseDualStack flag // will be ignored. // // Only supported with. // // sess := session.Must(session.NewSession()) // // svc := s3.New(sess, &aws.Config{ // UseDualStack: aws.Bool(true), // }) UseDualStack *bool // SleepDelay is an override for the func the SDK will call when sleeping // during the lifecycle of a request. Specifically this will be used for // request delays. This value should only be used for testing. To adjust // the delay of a request see the aws/client.DefaultRetryer and // aws/request.Retryer. // // SleepDelay will prevent any Context from being used for canceling retry // delay of an API operation. It is recommended to not use SleepDelay at all // and specify a Retryer instead. SleepDelay func(time.Duration) // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. // Will default to false. This would only be used for empty directory names in s3 requests. // // Example: // sess := session.Must(session.NewSession(&aws.Config{ // DisableRestProtocolURICleaning: aws.Bool(true), // })) // // svc := s3.New(sess) // out, err := svc.GetObject(&s3.GetObjectInput { // Bucket: aws.String("bucketname"), // Key: aws.String("//foo//bar//moo"), // }) DisableRestProtocolURICleaning *bool // EnableEndpointDiscovery will allow for endpoint discovery on operations that // have the definition in its model. By default, endpoint discovery is off. // To use EndpointDiscovery, Endpoint should be unset or set to an empty string. // // Example: // sess := session.Must(session.NewSession(&aws.Config{ // EnableEndpointDiscovery: aws.Bool(true), // })) // // svc := s3.New(sess) // out, err := svc.GetObject(&s3.GetObjectInput { // Bucket: aws.String("bucketname"), // Key: aws.String("/foo/bar/moo"), // }) EnableEndpointDiscovery *bool // DisableEndpointHostPrefix will disable the SDK's behavior of prefixing // request endpoint hosts with modeled information. // // Disabling this feature is useful when you want to use local endpoints // for testing that do not support the modeled host prefix pattern. DisableEndpointHostPrefix *bool // STSRegionalEndpoint will enable regional or legacy endpoint resolving STSRegionalEndpoint endpoints.STSRegionalEndpoint // S3UsEast1RegionalEndpoint will enable regional or legacy endpoint resolving S3UsEast1RegionalEndpoint endpoints.S3UsEast1RegionalEndpoint } // NewConfig returns a new Config pointer that can be chained with builder // methods to set multiple configuration values inline without using pointers. // // // Create Session with MaxRetries configuration to be shared by multiple // // service clients. // sess := session.Must(session.NewSession(aws.NewConfig(). // WithMaxRetries(3), // )) // // // Create S3 service client with a specific Region. // svc := s3.New(sess, aws.NewConfig(). // WithRegion("us-west-2"), // ) func NewConfig() *Config { return &Config{} } // WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning // a Config pointer. func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config { c.CredentialsChainVerboseErrors = &verboseErrs return c } // WithCredentials sets a config Credentials value returning a Config pointer // for chaining. func (c *Config) WithCredentials(creds *credentials.Credentials) *Config { c.Credentials = creds return c } // WithEndpoint sets a config Endpoint value returning a Config pointer for // chaining. func (c *Config) WithEndpoint(endpoint string) *Config { c.Endpoint = &endpoint return c } // WithEndpointResolver sets a config EndpointResolver value returning a // Config pointer for chaining. func (c *Config) WithEndpointResolver(resolver endpoints.Resolver) *Config { c.EndpointResolver = resolver return c } // WithRegion sets a config Region value returning a Config pointer for // chaining. func (c *Config) WithRegion(region string) *Config { c.Region = &region return c } // WithDisableSSL sets a config DisableSSL value returning a Config pointer // for chaining. func (c *Config) WithDisableSSL(disable bool) *Config { c.DisableSSL = &disable return c } // WithHTTPClient sets a config HTTPClient value returning a Config pointer // for chaining. func (c *Config) WithHTTPClient(client *http.Client) *Config { c.HTTPClient = client return c } // WithMaxRetries sets a config MaxRetries value returning a Config pointer // for chaining. func (c *Config) WithMaxRetries(max int) *Config { c.MaxRetries = &max return c } // WithDisableParamValidation sets a config DisableParamValidation value // returning a Config pointer for chaining. func (c *Config) WithDisableParamValidation(disable bool) *Config { c.DisableParamValidation = &disable return c } // WithDisableComputeChecksums sets a config DisableComputeChecksums value // returning a Config pointer for chaining. func (c *Config) WithDisableComputeChecksums(disable bool) *Config { c.DisableComputeChecksums = &disable return c } // WithLogLevel sets a config LogLevel value returning a Config pointer for // chaining. func (c *Config) WithLogLevel(level LogLevelType) *Config { c.LogLevel = &level return c } // WithLogger sets a config Logger value returning a Config pointer for // chaining. func (c *Config) WithLogger(logger Logger) *Config { c.Logger = logger return c } // WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config // pointer for chaining. func (c *Config) WithS3ForcePathStyle(force bool) *Config { c.S3ForcePathStyle = &force return c } // WithS3Disable100Continue sets a config S3Disable100Continue value returning // a Config pointer for chaining. func (c *Config) WithS3Disable100Continue(disable bool) *Config { c.S3Disable100Continue = &disable return c } // WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config // pointer for chaining. func (c *Config) WithS3UseAccelerate(enable bool) *Config { c.S3UseAccelerate = &enable return c } // WithS3DisableContentMD5Validation sets a config // S3DisableContentMD5Validation value returning a Config pointer for chaining. func (c *Config) WithS3DisableContentMD5Validation(enable bool) *Config { c.S3DisableContentMD5Validation = &enable return c } // WithS3UseARNRegion sets a config S3UseARNRegion value and // returning a Config pointer for chaining func (c *Config) WithS3UseARNRegion(enable bool) *Config { c.S3UseARNRegion = &enable return c } // WithUseDualStack sets a config UseDualStack value returning a Config // pointer for chaining. func (c *Config) WithUseDualStack(enable bool) *Config { c.UseDualStack = &enable return c } // WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value // returning a Config pointer for chaining. func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config { c.EC2MetadataDisableTimeoutOverride = &enable return c } // WithSleepDelay overrides the function used to sleep while waiting for the // next retry. Defaults to time.Sleep. func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { c.SleepDelay = fn return c } // WithEndpointDiscovery will set whether or not to use endpoint discovery. func (c *Config) WithEndpointDiscovery(t bool) *Config { c.EnableEndpointDiscovery = &t return c } // WithDisableEndpointHostPrefix will set whether or not to use modeled host prefix // when making requests. func (c *Config) WithDisableEndpointHostPrefix(t bool) *Config { c.DisableEndpointHostPrefix = &t return c } // WithSTSRegionalEndpoint will set whether or not to use regional endpoint flag // when resolving the endpoint for a service func (c *Config) WithSTSRegionalEndpoint(sre endpoints.STSRegionalEndpoint) *Config { c.STSRegionalEndpoint = sre return c } // WithS3UsEast1RegionalEndpoint will set whether or not to use regional endpoint flag // when resolving the endpoint for a service func (c *Config) WithS3UsEast1RegionalEndpoint(sre endpoints.S3UsEast1RegionalEndpoint) *Config { c.S3UsEast1RegionalEndpoint = sre return c } // WithLowerCaseHeaderMaps sets a config LowerCaseHeaderMaps value // returning a Config pointer for chaining. func (c *Config) WithLowerCaseHeaderMaps(t bool) *Config { c.LowerCaseHeaderMaps = &t return c } // WithDisableRestProtocolURICleaning sets a config DisableRestProtocolURICleaning value // returning a Config pointer for chaining. func (c *Config) WithDisableRestProtocolURICleaning(t bool) *Config { c.DisableRestProtocolURICleaning = &t return c } // MergeIn merges the passed in configs into the existing config object. func (c *Config) MergeIn(cfgs ...*Config) { for _, other := range cfgs { mergeInConfig(c, other) } } func mergeInConfig(dst *Config, other *Config) { if other == nil { return } if other.CredentialsChainVerboseErrors != nil { dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors } if other.Credentials != nil { dst.Credentials = other.Credentials } if other.Endpoint != nil { dst.Endpoint = other.Endpoint } if other.EndpointResolver != nil { dst.EndpointResolver = other.EndpointResolver } if other.Region != nil { dst.Region = other.Region } if other.DisableSSL != nil { dst.DisableSSL = other.DisableSSL } if other.HTTPClient != nil { dst.HTTPClient = other.HTTPClient } if other.LogLevel != nil { dst.LogLevel = other.LogLevel } if other.Logger != nil { dst.Logger = other.Logger } if other.MaxRetries != nil { dst.MaxRetries = other.MaxRetries } if other.Retryer != nil { dst.Retryer = other.Retryer } if other.DisableParamValidation != nil { dst.DisableParamValidation = other.DisableParamValidation } if other.DisableComputeChecksums != nil { dst.DisableComputeChecksums = other.DisableComputeChecksums } if other.S3ForcePathStyle != nil { dst.S3ForcePathStyle = other.S3ForcePathStyle } if other.S3Disable100Continue != nil { dst.S3Disable100Continue = other.S3Disable100Continue } if other.S3UseAccelerate != nil { dst.S3UseAccelerate = other.S3UseAccelerate } if other.S3DisableContentMD5Validation != nil { dst.S3DisableContentMD5Validation = other.S3DisableContentMD5Validation } if other.S3UseARNRegion != nil { dst.S3UseARNRegion = other.S3UseARNRegion } if other.UseDualStack != nil { dst.UseDualStack = other.UseDualStack } if other.EC2MetadataDisableTimeoutOverride != nil { dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride } if other.SleepDelay != nil { dst.SleepDelay = other.SleepDelay } if other.DisableRestProtocolURICleaning != nil { dst.DisableRestProtocolURICleaning = other.DisableRestProtocolURICleaning } if other.EnforceShouldRetryCheck != nil { dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck } if other.EnableEndpointDiscovery != nil { dst.EnableEndpointDiscovery = other.EnableEndpointDiscovery } if other.DisableEndpointHostPrefix != nil { dst.DisableEndpointHostPrefix = other.DisableEndpointHostPrefix } if other.STSRegionalEndpoint != endpoints.UnsetSTSEndpoint { dst.STSRegionalEndpoint = other.STSRegionalEndpoint } if other.S3UsEast1RegionalEndpoint != endpoints.UnsetS3UsEast1Endpoint { dst.S3UsEast1RegionalEndpoint = other.S3UsEast1RegionalEndpoint } if other.LowerCaseHeaderMaps != nil { dst.LowerCaseHeaderMaps = other.LowerCaseHeaderMaps } } // Copy will return a shallow copy of the Config object. If any additional // configurations are provided they will be merged into the new config returned. func (c *Config) Copy(cfgs ...*Config) *Config { dst := &Config{} dst.MergeIn(c) for _, cfg := range cfgs { dst.MergeIn(cfg) } return dst }
606
session-manager-plugin
aws
Go
package aws import ( "net/http" "reflect" "testing" "github.com/aws/aws-sdk-go/aws/credentials" ) var testCredentials = credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") var copyTestConfig = Config{ Credentials: testCredentials, Endpoint: String("CopyTestEndpoint"), Region: String("COPY_TEST_AWS_REGION"), DisableSSL: Bool(true), HTTPClient: http.DefaultClient, LogLevel: LogLevel(LogDebug), Logger: NewDefaultLogger(), MaxRetries: Int(3), DisableParamValidation: Bool(true), DisableComputeChecksums: Bool(true), S3ForcePathStyle: Bool(true), } func TestCopy(t *testing.T) { want := copyTestConfig got := copyTestConfig.Copy() if !reflect.DeepEqual(*got, want) { t.Errorf("Copy() = %+v", got) t.Errorf(" want %+v", want) } got.Region = String("other") if got.Region == want.Region { t.Errorf("Expect setting copy values not not reflect in source") } } func TestCopyReturnsNewInstance(t *testing.T) { want := copyTestConfig got := copyTestConfig.Copy() if got == &want { t.Errorf("Copy() = %p; want different instance as source %p", got, &want) } } var mergeTestZeroValueConfig = Config{} var mergeTestConfig = Config{ Credentials: testCredentials, Endpoint: String("MergeTestEndpoint"), Region: String("MERGE_TEST_AWS_REGION"), DisableSSL: Bool(true), HTTPClient: http.DefaultClient, LogLevel: LogLevel(LogDebug), Logger: NewDefaultLogger(), MaxRetries: Int(10), DisableParamValidation: Bool(true), DisableComputeChecksums: Bool(true), DisableEndpointHostPrefix: Bool(true), EnableEndpointDiscovery: Bool(true), EnforceShouldRetryCheck: Bool(true), DisableRestProtocolURICleaning: Bool(true), S3ForcePathStyle: Bool(true), LowerCaseHeaderMaps: Bool(true), } var mergeTests = []struct { cfg *Config in *Config want *Config }{ {&Config{}, nil, &Config{}}, {&Config{}, &mergeTestZeroValueConfig, &Config{}}, {&Config{}, &mergeTestConfig, &mergeTestConfig}, } func TestMerge(t *testing.T) { for i, tt := range mergeTests { got := tt.cfg.Copy() got.MergeIn(tt.in) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Config %d %+v", i, tt.cfg) t.Errorf(" Merge(%+v)", tt.in) t.Errorf(" got %+v", got) t.Errorf(" want %+v", tt.want) } } }
92
session-manager-plugin
aws
Go
// +build !go1.9 package aws import "time" // Context is an copy of the Go v1.7 stdlib's context.Context interface. // It is represented as a SDK interface to enable you to use the "WithContext" // API methods with Go v1.6 and a Context type such as golang.org/x/net/context. // // See https://golang.org/pkg/context on how to use contexts. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. Done() <-chan struct{} // Err returns a non-nil error value after Done is closed. Err returns // Canceled if the context was canceled or DeadlineExceeded if the // context's deadline passed. No other values for Err are defined. // After Done is closed, successive calls to Err return the same value. Err() error // Value returns the value associated with this context for key, or nil // if no value is associated with key. Successive calls to Value with // the same key returns the same result. // // Use context values only for request-scoped data that transits // processes and API boundaries, not for passing optional parameters to // functions. Value(key interface{}) interface{} }
38
session-manager-plugin
aws
Go
// +build go1.9 package aws import "context" // Context is an alias of the Go stdlib's context.Context interface. // It can be used within the SDK's API operation "WithContext" methods. // // See https://golang.org/pkg/context on how to use contexts. type Context = context.Context
12
session-manager-plugin
aws
Go
// +build !go1.7 package aws import ( "github.com/aws/aws-sdk-go/internal/context" ) // BackgroundContext returns a context that will never be canceled, has no // values, and no deadline. This context is used by the SDK to provide // backwards compatibility with non-context API operations and functionality. // // Go 1.6 and before: // This context function is equivalent to context.Background in the Go stdlib. // // Go 1.7 and later: // The context returned will be the value returned by context.Background() // // See https://golang.org/pkg/context for more information on Contexts. func BackgroundContext() Context { return context.BackgroundCtx }
23
session-manager-plugin
aws
Go
// +build go1.7 package aws import "context" // BackgroundContext returns a context that will never be canceled, has no // values, and no deadline. This context is used by the SDK to provide // backwards compatibility with non-context API operations and functionality. // // Go 1.6 and before: // This context function is equivalent to context.Background in the Go stdlib. // // Go 1.7 and later: // The context returned will be the value returned by context.Background() // // See https://golang.org/pkg/context for more information on Contexts. func BackgroundContext() Context { return context.Background() }
21
session-manager-plugin
aws
Go
package aws import ( "time" ) // SleepWithContext will wait for the timer duration to expire, or the context // is canceled. Which ever happens first. If the context is canceled the Context's // error will be returned. // // Expects Context to always return a non-nil error if the Done channel is closed. func SleepWithContext(ctx Context, dur time.Duration) error { t := time.NewTimer(dur) defer t.Stop() select { case <-t.C: break case <-ctx.Done(): return ctx.Err() } return nil }
25
session-manager-plugin
aws
Go
package aws_test import ( "fmt" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/awstesting" ) func TestSleepWithContext(t *testing.T) { ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} err := aws.SleepWithContext(ctx, 1*time.Millisecond) if err != nil { t.Errorf("expect context to not be canceled, got %v", err) } } func TestSleepWithContext_Canceled(t *testing.T) { ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} expectErr := fmt.Errorf("context canceled") ctx.Error = expectErr close(ctx.DoneCh) err := aws.SleepWithContext(ctx, 10*time.Second) if err == nil { t.Fatalf("expect error, did not get one") } if e, a := expectErr, err; e != a { t.Errorf("expect %v error, got %v", e, a) } }
38
session-manager-plugin
aws
Go
package aws import "time" // String returns a pointer to the string value passed in. func String(v string) *string { return &v } // StringValue returns the value of the string pointer passed in or // "" if the pointer is nil. func StringValue(v *string) string { if v != nil { return *v } return "" } // StringSlice converts a slice of string values into a slice of // string pointers func StringSlice(src []string) []*string { dst := make([]*string, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // StringValueSlice converts a slice of string pointers into a slice of // string values func StringValueSlice(src []*string) []string { dst := make([]string, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // StringMap converts a string map of string values into a string // map of string pointers func StringMap(src map[string]string) map[string]*string { dst := make(map[string]*string) for k, val := range src { v := val dst[k] = &v } return dst } // StringValueMap converts a string map of string pointers into a string // map of string values func StringValueMap(src map[string]*string) map[string]string { dst := make(map[string]string) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Bool returns a pointer to the bool value passed in. func Bool(v bool) *bool { return &v } // BoolValue returns the value of the bool pointer passed in or // false if the pointer is nil. func BoolValue(v *bool) bool { if v != nil { return *v } return false } // BoolSlice converts a slice of bool values into a slice of // bool pointers func BoolSlice(src []bool) []*bool { dst := make([]*bool, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // BoolValueSlice converts a slice of bool pointers into a slice of // bool values func BoolValueSlice(src []*bool) []bool { dst := make([]bool, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // BoolMap converts a string map of bool values into a string // map of bool pointers func BoolMap(src map[string]bool) map[string]*bool { dst := make(map[string]*bool) for k, val := range src { v := val dst[k] = &v } return dst } // BoolValueMap converts a string map of bool pointers into a string // map of bool values func BoolValueMap(src map[string]*bool) map[string]bool { dst := make(map[string]bool) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Int returns a pointer to the int value passed in. func Int(v int) *int { return &v } // IntValue returns the value of the int pointer passed in or // 0 if the pointer is nil. func IntValue(v *int) int { if v != nil { return *v } return 0 } // IntSlice converts a slice of int values into a slice of // int pointers func IntSlice(src []int) []*int { dst := make([]*int, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // IntValueSlice converts a slice of int pointers into a slice of // int values func IntValueSlice(src []*int) []int { dst := make([]int, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // IntMap converts a string map of int values into a string // map of int pointers func IntMap(src map[string]int) map[string]*int { dst := make(map[string]*int) for k, val := range src { v := val dst[k] = &v } return dst } // IntValueMap converts a string map of int pointers into a string // map of int values func IntValueMap(src map[string]*int) map[string]int { dst := make(map[string]int) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Uint returns a pointer to the uint value passed in. func Uint(v uint) *uint { return &v } // UintValue returns the value of the uint pointer passed in or // 0 if the pointer is nil. func UintValue(v *uint) uint { if v != nil { return *v } return 0 } // UintSlice converts a slice of uint values uinto a slice of // uint pointers func UintSlice(src []uint) []*uint { dst := make([]*uint, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // UintValueSlice converts a slice of uint pointers uinto a slice of // uint values func UintValueSlice(src []*uint) []uint { dst := make([]uint, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // UintMap converts a string map of uint values uinto a string // map of uint pointers func UintMap(src map[string]uint) map[string]*uint { dst := make(map[string]*uint) for k, val := range src { v := val dst[k] = &v } return dst } // UintValueMap converts a string map of uint pointers uinto a string // map of uint values func UintValueMap(src map[string]*uint) map[string]uint { dst := make(map[string]uint) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Int8 returns a pointer to the int8 value passed in. func Int8(v int8) *int8 { return &v } // Int8Value returns the value of the int8 pointer passed in or // 0 if the pointer is nil. func Int8Value(v *int8) int8 { if v != nil { return *v } return 0 } // Int8Slice converts a slice of int8 values into a slice of // int8 pointers func Int8Slice(src []int8) []*int8 { dst := make([]*int8, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Int8ValueSlice converts a slice of int8 pointers into a slice of // int8 values func Int8ValueSlice(src []*int8) []int8 { dst := make([]int8, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Int8Map converts a string map of int8 values into a string // map of int8 pointers func Int8Map(src map[string]int8) map[string]*int8 { dst := make(map[string]*int8) for k, val := range src { v := val dst[k] = &v } return dst } // Int8ValueMap converts a string map of int8 pointers into a string // map of int8 values func Int8ValueMap(src map[string]*int8) map[string]int8 { dst := make(map[string]int8) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Int16 returns a pointer to the int16 value passed in. func Int16(v int16) *int16 { return &v } // Int16Value returns the value of the int16 pointer passed in or // 0 if the pointer is nil. func Int16Value(v *int16) int16 { if v != nil { return *v } return 0 } // Int16Slice converts a slice of int16 values into a slice of // int16 pointers func Int16Slice(src []int16) []*int16 { dst := make([]*int16, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Int16ValueSlice converts a slice of int16 pointers into a slice of // int16 values func Int16ValueSlice(src []*int16) []int16 { dst := make([]int16, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Int16Map converts a string map of int16 values into a string // map of int16 pointers func Int16Map(src map[string]int16) map[string]*int16 { dst := make(map[string]*int16) for k, val := range src { v := val dst[k] = &v } return dst } // Int16ValueMap converts a string map of int16 pointers into a string // map of int16 values func Int16ValueMap(src map[string]*int16) map[string]int16 { dst := make(map[string]int16) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Int32 returns a pointer to the int32 value passed in. func Int32(v int32) *int32 { return &v } // Int32Value returns the value of the int32 pointer passed in or // 0 if the pointer is nil. func Int32Value(v *int32) int32 { if v != nil { return *v } return 0 } // Int32Slice converts a slice of int32 values into a slice of // int32 pointers func Int32Slice(src []int32) []*int32 { dst := make([]*int32, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Int32ValueSlice converts a slice of int32 pointers into a slice of // int32 values func Int32ValueSlice(src []*int32) []int32 { dst := make([]int32, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Int32Map converts a string map of int32 values into a string // map of int32 pointers func Int32Map(src map[string]int32) map[string]*int32 { dst := make(map[string]*int32) for k, val := range src { v := val dst[k] = &v } return dst } // Int32ValueMap converts a string map of int32 pointers into a string // map of int32 values func Int32ValueMap(src map[string]*int32) map[string]int32 { dst := make(map[string]int32) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Int64 returns a pointer to the int64 value passed in. func Int64(v int64) *int64 { return &v } // Int64Value returns the value of the int64 pointer passed in or // 0 if the pointer is nil. func Int64Value(v *int64) int64 { if v != nil { return *v } return 0 } // Int64Slice converts a slice of int64 values into a slice of // int64 pointers func Int64Slice(src []int64) []*int64 { dst := make([]*int64, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Int64ValueSlice converts a slice of int64 pointers into a slice of // int64 values func Int64ValueSlice(src []*int64) []int64 { dst := make([]int64, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Int64Map converts a string map of int64 values into a string // map of int64 pointers func Int64Map(src map[string]int64) map[string]*int64 { dst := make(map[string]*int64) for k, val := range src { v := val dst[k] = &v } return dst } // Int64ValueMap converts a string map of int64 pointers into a string // map of int64 values func Int64ValueMap(src map[string]*int64) map[string]int64 { dst := make(map[string]int64) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Uint8 returns a pointer to the uint8 value passed in. func Uint8(v uint8) *uint8 { return &v } // Uint8Value returns the value of the uint8 pointer passed in or // 0 if the pointer is nil. func Uint8Value(v *uint8) uint8 { if v != nil { return *v } return 0 } // Uint8Slice converts a slice of uint8 values into a slice of // uint8 pointers func Uint8Slice(src []uint8) []*uint8 { dst := make([]*uint8, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Uint8ValueSlice converts a slice of uint8 pointers into a slice of // uint8 values func Uint8ValueSlice(src []*uint8) []uint8 { dst := make([]uint8, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Uint8Map converts a string map of uint8 values into a string // map of uint8 pointers func Uint8Map(src map[string]uint8) map[string]*uint8 { dst := make(map[string]*uint8) for k, val := range src { v := val dst[k] = &v } return dst } // Uint8ValueMap converts a string map of uint8 pointers into a string // map of uint8 values func Uint8ValueMap(src map[string]*uint8) map[string]uint8 { dst := make(map[string]uint8) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Uint16 returns a pointer to the uint16 value passed in. func Uint16(v uint16) *uint16 { return &v } // Uint16Value returns the value of the uint16 pointer passed in or // 0 if the pointer is nil. func Uint16Value(v *uint16) uint16 { if v != nil { return *v } return 0 } // Uint16Slice converts a slice of uint16 values into a slice of // uint16 pointers func Uint16Slice(src []uint16) []*uint16 { dst := make([]*uint16, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Uint16ValueSlice converts a slice of uint16 pointers into a slice of // uint16 values func Uint16ValueSlice(src []*uint16) []uint16 { dst := make([]uint16, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Uint16Map converts a string map of uint16 values into a string // map of uint16 pointers func Uint16Map(src map[string]uint16) map[string]*uint16 { dst := make(map[string]*uint16) for k, val := range src { v := val dst[k] = &v } return dst } // Uint16ValueMap converts a string map of uint16 pointers into a string // map of uint16 values func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { dst := make(map[string]uint16) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Uint32 returns a pointer to the uint32 value passed in. func Uint32(v uint32) *uint32 { return &v } // Uint32Value returns the value of the uint32 pointer passed in or // 0 if the pointer is nil. func Uint32Value(v *uint32) uint32 { if v != nil { return *v } return 0 } // Uint32Slice converts a slice of uint32 values into a slice of // uint32 pointers func Uint32Slice(src []uint32) []*uint32 { dst := make([]*uint32, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Uint32ValueSlice converts a slice of uint32 pointers into a slice of // uint32 values func Uint32ValueSlice(src []*uint32) []uint32 { dst := make([]uint32, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Uint32Map converts a string map of uint32 values into a string // map of uint32 pointers func Uint32Map(src map[string]uint32) map[string]*uint32 { dst := make(map[string]*uint32) for k, val := range src { v := val dst[k] = &v } return dst } // Uint32ValueMap converts a string map of uint32 pointers into a string // map of uint32 values func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { dst := make(map[string]uint32) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Uint64 returns a pointer to the uint64 value passed in. func Uint64(v uint64) *uint64 { return &v } // Uint64Value returns the value of the uint64 pointer passed in or // 0 if the pointer is nil. func Uint64Value(v *uint64) uint64 { if v != nil { return *v } return 0 } // Uint64Slice converts a slice of uint64 values into a slice of // uint64 pointers func Uint64Slice(src []uint64) []*uint64 { dst := make([]*uint64, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Uint64ValueSlice converts a slice of uint64 pointers into a slice of // uint64 values func Uint64ValueSlice(src []*uint64) []uint64 { dst := make([]uint64, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Uint64Map converts a string map of uint64 values into a string // map of uint64 pointers func Uint64Map(src map[string]uint64) map[string]*uint64 { dst := make(map[string]*uint64) for k, val := range src { v := val dst[k] = &v } return dst } // Uint64ValueMap converts a string map of uint64 pointers into a string // map of uint64 values func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { dst := make(map[string]uint64) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Float32 returns a pointer to the float32 value passed in. func Float32(v float32) *float32 { return &v } // Float32Value returns the value of the float32 pointer passed in or // 0 if the pointer is nil. func Float32Value(v *float32) float32 { if v != nil { return *v } return 0 } // Float32Slice converts a slice of float32 values into a slice of // float32 pointers func Float32Slice(src []float32) []*float32 { dst := make([]*float32, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Float32ValueSlice converts a slice of float32 pointers into a slice of // float32 values func Float32ValueSlice(src []*float32) []float32 { dst := make([]float32, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Float32Map converts a string map of float32 values into a string // map of float32 pointers func Float32Map(src map[string]float32) map[string]*float32 { dst := make(map[string]*float32) for k, val := range src { v := val dst[k] = &v } return dst } // Float32ValueMap converts a string map of float32 pointers into a string // map of float32 values func Float32ValueMap(src map[string]*float32) map[string]float32 { dst := make(map[string]float32) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Float64 returns a pointer to the float64 value passed in. func Float64(v float64) *float64 { return &v } // Float64Value returns the value of the float64 pointer passed in or // 0 if the pointer is nil. func Float64Value(v *float64) float64 { if v != nil { return *v } return 0 } // Float64Slice converts a slice of float64 values into a slice of // float64 pointers func Float64Slice(src []float64) []*float64 { dst := make([]*float64, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Float64ValueSlice converts a slice of float64 pointers into a slice of // float64 values func Float64ValueSlice(src []*float64) []float64 { dst := make([]float64, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // Float64Map converts a string map of float64 values into a string // map of float64 pointers func Float64Map(src map[string]float64) map[string]*float64 { dst := make(map[string]*float64) for k, val := range src { v := val dst[k] = &v } return dst } // Float64ValueMap converts a string map of float64 pointers into a string // map of float64 values func Float64ValueMap(src map[string]*float64) map[string]float64 { dst := make(map[string]float64) for k, val := range src { if val != nil { dst[k] = *val } } return dst } // Time returns a pointer to the time.Time value passed in. func Time(v time.Time) *time.Time { return &v } // TimeValue returns the value of the time.Time pointer passed in or // time.Time{} if the pointer is nil. func TimeValue(v *time.Time) time.Time { if v != nil { return *v } return time.Time{} } // SecondsTimeValue converts an int64 pointer to a time.Time value // representing seconds since Epoch or time.Time{} if the pointer is nil. func SecondsTimeValue(v *int64) time.Time { if v != nil { return time.Unix((*v / 1000), 0) } return time.Time{} } // MillisecondsTimeValue converts an int64 pointer to a time.Time value // representing milliseconds sinch Epoch or time.Time{} if the pointer is nil. func MillisecondsTimeValue(v *int64) time.Time { if v != nil { return time.Unix(0, (*v * 1000000)) } return time.Time{} } // TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". // The result is undefined if the Unix time cannot be represented by an int64. // Which includes calling TimeUnixMilli on a zero Time is undefined. // // This utility is useful for service API's such as CloudWatch Logs which require // their unix time values to be in milliseconds. // // See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information. func TimeUnixMilli(t time.Time) int64 { return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) } // TimeSlice converts a slice of time.Time values into a slice of // time.Time pointers func TimeSlice(src []time.Time) []*time.Time { dst := make([]*time.Time, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // TimeValueSlice converts a slice of time.Time pointers into a slice of // time.Time values func TimeValueSlice(src []*time.Time) []time.Time { dst := make([]time.Time, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } // TimeMap converts a string map of time.Time values into a string // map of time.Time pointers func TimeMap(src map[string]time.Time) map[string]*time.Time { dst := make(map[string]*time.Time) for k, val := range src { v := val dst[k] = &v } return dst } // TimeValueMap converts a string map of time.Time pointers into a string // map of time.Time values func TimeValueMap(src map[string]*time.Time) map[string]time.Time { dst := make(map[string]time.Time) for k, val := range src { if val != nil { dst[k] = *val } } return dst }
919
session-manager-plugin
aws
Go
package aws import ( "reflect" "testing" "time" ) var testCasesStringSlice = [][]string{ {"a", "b", "c", "d", "e"}, {"a", "b", "", "", "e"}, } func TestStringSlice(t *testing.T) { for idx, in := range testCasesStringSlice { if in == nil { continue } out := StringSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := StringValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesStringValueSlice = [][]*string{ {String("a"), String("b"), nil, String("c")}, } func TestStringValueSlice(t *testing.T) { for idx, in := range testCasesStringValueSlice { if in == nil { continue } out := StringValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != "" { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := StringSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != "" { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *in[i], *out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesStringMap = []map[string]string{ {"a": "1", "b": "2", "c": "3"}, } func TestStringMap(t *testing.T) { for idx, in := range testCasesStringMap { if in == nil { continue } out := StringMap(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := StringValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesBoolSlice = [][]bool{ {true, true, false, false}, } func TestBoolSlice(t *testing.T) { for idx, in := range testCasesBoolSlice { if in == nil { continue } out := BoolSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := BoolValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesBoolValueSlice = [][]*bool{} func TestBoolValueSlice(t *testing.T) { for idx, in := range testCasesBoolValueSlice { if in == nil { continue } out := BoolValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := BoolSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesBoolMap = []map[string]bool{ {"a": true, "b": false, "c": true}, } func TestBoolMap(t *testing.T) { for idx, in := range testCasesBoolMap { if in == nil { continue } out := BoolMap(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := BoolValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUintSlice = [][]uint{ {1, 2, 3, 4}, } func TestUintSlice(t *testing.T) { for idx, in := range testCasesUintSlice { if in == nil { continue } out := UintSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := UintValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUintValueSlice = [][]*uint{} func TestUintValueSlice(t *testing.T) { for idx, in := range testCasesUintValueSlice { if in == nil { continue } out := UintValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := UintSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesUintMap = []map[string]uint{ {"a": 3, "b": 2, "c": 1}, } func TestUintMap(t *testing.T) { for idx, in := range testCasesUintMap { if in == nil { continue } out := UintMap(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := UintValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesIntSlice = [][]int{ {1, 2, 3, 4}, } func TestIntSlice(t *testing.T) { for idx, in := range testCasesIntSlice { if in == nil { continue } out := IntSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := IntValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesIntValueSlice = [][]*int{} func TestIntValueSlice(t *testing.T) { for idx, in := range testCasesIntValueSlice { if in == nil { continue } out := IntValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := IntSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesIntMap = []map[string]int{ {"a": 3, "b": 2, "c": 1}, } func TestIntMap(t *testing.T) { for idx, in := range testCasesIntMap { if in == nil { continue } out := IntMap(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := IntValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt8Slice = [][]int8{ {1, 2, 3, 4}, } func TestInt8Slice(t *testing.T) { for idx, in := range testCasesInt8Slice { if in == nil { continue } out := Int8Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int8ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt8ValueSlice = [][]*int8{} func TestInt8ValueSlice(t *testing.T) { for idx, in := range testCasesInt8ValueSlice { if in == nil { continue } out := Int8ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Int8Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesInt8Map = []map[string]int8{ {"a": 3, "b": 2, "c": 1}, } func TestInt8Map(t *testing.T) { for idx, in := range testCasesInt8Map { if in == nil { continue } out := Int8Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int8ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt16Slice = [][]int16{ {1, 2, 3, 4}, } func TestInt16Slice(t *testing.T) { for idx, in := range testCasesInt16Slice { if in == nil { continue } out := Int16Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int16ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt16ValueSlice = [][]*int16{} func TestInt16ValueSlice(t *testing.T) { for idx, in := range testCasesInt16ValueSlice { if in == nil { continue } out := Int16ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Int16Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesInt16Map = []map[string]int16{ {"a": 3, "b": 2, "c": 1}, } func TestInt16Map(t *testing.T) { for idx, in := range testCasesInt16Map { if in == nil { continue } out := Int16Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int16ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt32Slice = [][]int32{ {1, 2, 3, 4}, } func TestInt32Slice(t *testing.T) { for idx, in := range testCasesInt32Slice { if in == nil { continue } out := Int32Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int32ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt32ValueSlice = [][]*int32{} func TestInt32ValueSlice(t *testing.T) { for idx, in := range testCasesInt32ValueSlice { if in == nil { continue } out := Int32ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Int32Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesInt32Map = []map[string]int32{ {"a": 3, "b": 2, "c": 1}, } func TestInt32Map(t *testing.T) { for idx, in := range testCasesInt32Map { if in == nil { continue } out := Int32Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int32ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt64Slice = [][]int64{ {1, 2, 3, 4}, } func TestInt64Slice(t *testing.T) { for idx, in := range testCasesInt64Slice { if in == nil { continue } out := Int64Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int64ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesInt64ValueSlice = [][]*int64{} func TestInt64ValueSlice(t *testing.T) { for idx, in := range testCasesInt64ValueSlice { if in == nil { continue } out := Int64ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Int64Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesInt64Map = []map[string]int64{ {"a": 3, "b": 2, "c": 1}, } func TestInt64Map(t *testing.T) { for idx, in := range testCasesInt64Map { if in == nil { continue } out := Int64Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Int64ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint8Slice = [][]uint8{ {1, 2, 3, 4}, } func TestUint8Slice(t *testing.T) { for idx, in := range testCasesUint8Slice { if in == nil { continue } out := Uint8Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint8ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint8ValueSlice = [][]*uint8{} func TestUint8ValueSlice(t *testing.T) { for idx, in := range testCasesUint8ValueSlice { if in == nil { continue } out := Uint8ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Uint8Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesUint8Map = []map[string]uint8{ {"a": 3, "b": 2, "c": 1}, } func TestUint8Map(t *testing.T) { for idx, in := range testCasesUint8Map { if in == nil { continue } out := Uint8Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint8ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint16Slice = [][]uint16{ {1, 2, 3, 4}, } func TestUint16Slice(t *testing.T) { for idx, in := range testCasesUint16Slice { if in == nil { continue } out := Uint16Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint16ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint16ValueSlice = [][]*uint16{} func TestUint16ValueSlice(t *testing.T) { for idx, in := range testCasesUint16ValueSlice { if in == nil { continue } out := Uint16ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Uint16Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesUint16Map = []map[string]uint16{ {"a": 3, "b": 2, "c": 1}, } func TestUint16Map(t *testing.T) { for idx, in := range testCasesUint16Map { if in == nil { continue } out := Uint16Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint16ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint32Slice = [][]uint32{ {1, 2, 3, 4}, } func TestUint32Slice(t *testing.T) { for idx, in := range testCasesUint32Slice { if in == nil { continue } out := Uint32Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint32ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint32ValueSlice = [][]*uint32{} func TestUint32ValueSlice(t *testing.T) { for idx, in := range testCasesUint32ValueSlice { if in == nil { continue } out := Uint32ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Uint32Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesUint32Map = []map[string]uint32{ {"a": 3, "b": 2, "c": 1}, } func TestUint32Map(t *testing.T) { for idx, in := range testCasesUint32Map { if in == nil { continue } out := Uint32Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint32ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint64Slice = [][]uint64{ {1, 2, 3, 4}, } func TestUint64Slice(t *testing.T) { for idx, in := range testCasesUint64Slice { if in == nil { continue } out := Uint64Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint64ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesUint64ValueSlice = [][]*uint64{} func TestUint64ValueSlice(t *testing.T) { for idx, in := range testCasesUint64ValueSlice { if in == nil { continue } out := Uint64ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Uint64Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesUint64Map = []map[string]uint64{ {"a": 3, "b": 2, "c": 1}, } func TestUint64Map(t *testing.T) { for idx, in := range testCasesUint64Map { if in == nil { continue } out := Uint64Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Uint64ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesFloat32Slice = [][]float32{ {1, 2, 3, 4}, } func TestFloat32Slice(t *testing.T) { for idx, in := range testCasesFloat32Slice { if in == nil { continue } out := Float32Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Float32ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesFloat32ValueSlice = [][]*float32{} func TestFloat32ValueSlice(t *testing.T) { for idx, in := range testCasesFloat32ValueSlice { if in == nil { continue } out := Float32ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Float32Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesFloat32Map = []map[string]float32{ {"a": 3, "b": 2, "c": 1}, } func TestFloat32Map(t *testing.T) { for idx, in := range testCasesFloat32Map { if in == nil { continue } out := Float32Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Float32ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesFloat64Slice = [][]float64{ {1, 2, 3, 4}, } func TestFloat64Slice(t *testing.T) { for idx, in := range testCasesFloat64Slice { if in == nil { continue } out := Float64Slice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Float64ValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesFloat64ValueSlice = [][]*float64{} func TestFloat64ValueSlice(t *testing.T) { for idx, in := range testCasesFloat64ValueSlice { if in == nil { continue } out := Float64ValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if out[i] != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := Float64Slice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if *(out2[i]) != 0 { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesFloat64Map = []map[string]float64{ {"a": 3, "b": 2, "c": 1}, } func TestFloat64Map(t *testing.T) { for idx, in := range testCasesFloat64Map { if in == nil { continue } out := Float64Map(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := Float64ValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesTimeSlice = [][]time.Time{ {time.Now(), time.Now().AddDate(100, 0, 0)}, } func TestTimeSlice(t *testing.T) { for idx, in := range testCasesTimeSlice { if in == nil { continue } out := TimeSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := TimeValueSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } var testCasesTimeValueSlice = [][]*time.Time{} func TestTimeValueSlice(t *testing.T) { for idx, in := range testCasesTimeValueSlice { if in == nil { continue } out := TimeValueSlice(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if in[i] == nil { if !out[i].IsZero() { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := *(in[i]), out[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } out2 := TimeSlice(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out2 { if in[i] == nil { if !(out2[i]).IsZero() { t.Errorf("Unexpected value at idx %d", idx) } } else { if e, a := in[i], out2[i]; e != a { t.Errorf("Unexpected value at idx %d", idx) } } } } } var testCasesTimeMap = []map[string]time.Time{ {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, } func TestTimeMap(t *testing.T) { for idx, in := range testCasesTimeMap { if in == nil { continue } out := TimeMap(in) if e, a := len(out), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } for i := range out { if e, a := in[i], *(out[i]); e != a { t.Errorf("Unexpected value at idx %d", idx) } } out2 := TimeValueMap(out) if e, a := len(out2), len(in); e != a { t.Errorf("Unexpected len at idx %d", idx) } if e, a := in, out2; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected value at idx %d", idx) } } } type TimeValueTestCase struct { in int64 outSecs time.Time outMillis time.Time } var testCasesTimeValue = []TimeValueTestCase{ { in: int64(1501558289000), outSecs: time.Unix(1501558289, 0), outMillis: time.Unix(1501558289, 0), }, { in: int64(1501558289001), outSecs: time.Unix(1501558289, 0), outMillis: time.Unix(1501558289, 1*1000000), }, } func TestSecondsTimeValue(t *testing.T) { for idx, testCase := range testCasesTimeValue { out := SecondsTimeValue(&testCase.in) if e, a := testCase.outSecs, out; e != a { t.Errorf("Unexpected value for time value at %d", idx) } } } func TestMillisecondsTimeValue(t *testing.T) { for idx, testCase := range testCasesTimeValue { out := MillisecondsTimeValue(&testCase.in) if e, a := testCase.outMillis, out; e != a { t.Errorf("Unexpected value for time value at %d", idx) } } }
1,533
session-manager-plugin
aws
Go
// Package aws provides the core SDK's utilities and shared types. Use this package's // utilities to simplify setting and reading API operations parameters. // // Value and Pointer Conversion Utilities // // This package includes a helper conversion utility for each scalar type the SDK's // API use. These utilities make getting a pointer of the scalar, and dereferencing // a pointer easier. // // Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. // The Pointer to value will safely dereference the pointer and return its value. // If the pointer was nil, the scalar's zero value will be returned. // // The value to pointer functions will be named after the scalar type. So get a // *string from a string value use the "String" function. This makes it easy to // to get pointer of a literal string value, because getting the address of a // literal requires assigning the value to a variable first. // // var strPtr *string // // // Without the SDK's conversion functions // str := "my string" // strPtr = &str // // // With the SDK's conversion functions // strPtr = aws.String("my string") // // // Convert *string to string value // str = aws.StringValue(strPtr) // // In addition to scalars the aws package also includes conversion utilities for // map and slice for commonly types used in API parameters. The map and slice // conversion functions use similar naming pattern as the scalar conversion // functions. // // var strPtrs []*string // var strs []string = []string{"Go", "Gophers", "Go"} // // // Convert []string to []*string // strPtrs = aws.StringSlice(strs) // // // Convert []*string to []string // strs = aws.StringValueSlice(strPtrs) // // SDK Default HTTP Client // // The SDK will use the http.DefaultClient if a HTTP client is not provided to // the SDK's Session, or service client constructor. This means that if the // http.DefaultClient is modified by other components of your application the // modifications will be picked up by the SDK as well. // // In some cases this might be intended, but it is a better practice to create // a custom HTTP Client to share explicitly through your application. You can // configure the SDK to use the custom HTTP Client by setting the HTTPClient // value of the SDK's Config type when creating a Session or service client. package aws
57
session-manager-plugin
aws
Go
package aws import "github.com/aws/aws-sdk-go/aws/awserr" var ( // ErrMissingRegion is an error that is returned if region configuration is // not found. ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) // ErrMissingEndpoint is an error that is returned if an endpoint cannot be // resolved for a service. ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) )
14
session-manager-plugin
aws
Go
package aws // JSONValue is a representation of a grab bag type that will be marshaled // into a json string. This type can be used just like any other map. // // Example: // // values := aws.JSONValue{ // "Foo": "Bar", // } // values["Baz"] = "Qux" type JSONValue map[string]interface{}
13
session-manager-plugin
aws
Go
package aws import ( "log" "os" ) // A LogLevelType defines the level logging should be performed at. Used to instruct // the SDK which statements should be logged. type LogLevelType uint // LogLevel returns the pointer to a LogLevel. Should be used to workaround // not being able to take the address of a non-composite literal. func LogLevel(l LogLevelType) *LogLevelType { return &l } // Value returns the LogLevel value or the default value LogOff if the LogLevel // is nil. Safe to use on nil value LogLevelTypes. func (l *LogLevelType) Value() LogLevelType { if l != nil { return *l } return LogOff } // Matches returns true if the v LogLevel is enabled by this LogLevel. Should be // used with logging sub levels. Is safe to use on nil value LogLevelTypes. If // LogLevel is nil, will default to LogOff comparison. func (l *LogLevelType) Matches(v LogLevelType) bool { c := l.Value() return c&v == v } // AtLeast returns true if this LogLevel is at least high enough to satisfies v. // Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default // to LogOff comparison. func (l *LogLevelType) AtLeast(v LogLevelType) bool { c := l.Value() return c >= v } const ( // LogOff states that no logging should be performed by the SDK. This is the // default state of the SDK, and should be use to disable all logging. LogOff LogLevelType = iota * 0x1000 // LogDebug state that debug output should be logged by the SDK. This should // be used to inspect request made and responses received. LogDebug ) // Debug Logging Sub Levels const ( // LogDebugWithSigning states that the SDK should log request signing and // presigning events. This should be used to log the signing details of // requests for debugging. Will also enable LogDebug. LogDebugWithSigning LogLevelType = LogDebug | (1 << iota) // LogDebugWithHTTPBody states the SDK should log HTTP request and response // HTTP bodys in addition to the headers and path. This should be used to // see the body content of requests and responses made while using the SDK // Will also enable LogDebug. LogDebugWithHTTPBody // LogDebugWithRequestRetries states the SDK should log when service requests will // be retried. This should be used to log when you want to log when service // requests are being retried. Will also enable LogDebug. LogDebugWithRequestRetries // LogDebugWithRequestErrors states the SDK should log when service requests fail // to build, send, validate, or unmarshal. LogDebugWithRequestErrors // LogDebugWithEventStreamBody states the SDK should log EventStream // request and response bodys. This should be used to log the EventStream // wire unmarshaled message content of requests and responses made while // using the SDK Will also enable LogDebug. LogDebugWithEventStreamBody ) // A Logger is a minimalistic interface for the SDK to log messages to. Should // be used to provide custom logging writers for the SDK to use. type Logger interface { Log(...interface{}) } // A LoggerFunc is a convenience type to convert a function taking a variadic // list of arguments and wrap it so the Logger interface can be used. // // Example: // s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { // fmt.Fprintln(os.Stdout, args...) // })}) type LoggerFunc func(...interface{}) // Log calls the wrapped function with the arguments provided func (f LoggerFunc) Log(args ...interface{}) { f(args...) } // NewDefaultLogger returns a Logger which will write log messages to stdout, and // use same formatting runes as the stdlib log.Logger func NewDefaultLogger() Logger { return &defaultLogger{ logger: log.New(os.Stdout, "", log.LstdFlags), } } // A defaultLogger provides a minimalistic logger satisfying the Logger interface. type defaultLogger struct { logger *log.Logger } // Log logs the parameters to the stdlib logger. See log.Println. func (l defaultLogger) Log(args ...interface{}) { l.logger.Println(args...) }
119
session-manager-plugin
aws
Go
package aws import ( "io" "strings" "sync" "github.com/aws/aws-sdk-go/internal/sdkio" ) // ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Allows the // SDK to accept an io.Reader that is not also an io.Seeker for unsigned // streaming payload API operations. // // A ReadSeekCloser wrapping an nonseekable io.Reader used in an API // operation's input will prevent that operation being retried in the case of // network errors, and cause operation requests to fail if the operation // requires payload signing. // // Note: If using With S3 PutObject to stream an object upload The SDK's S3 // Upload manager (s3manager.Uploader) provides support for streaming with the // ability to retry network errors. func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { return ReaderSeekerCloser{r} } // ReaderSeekerCloser represents a reader that can also delegate io.Seeker and // io.Closer interfaces to the underlying object if they are available. type ReaderSeekerCloser struct { r io.Reader } // IsReaderSeekable returns if the underlying reader type can be seeked. A // io.Reader might not actually be seekable if it is the ReaderSeekerCloser // type. func IsReaderSeekable(r io.Reader) bool { switch v := r.(type) { case ReaderSeekerCloser: return v.IsSeeker() case *ReaderSeekerCloser: return v.IsSeeker() case io.ReadSeeker: return true default: return false } } // Read reads from the reader up to size of p. The number of bytes read, and // error if it occurred will be returned. // // If the reader is not an io.Reader zero bytes read, and nil error will be // returned. // // Performs the same functionality as io.Reader Read func (r ReaderSeekerCloser) Read(p []byte) (int, error) { switch t := r.r.(type) { case io.Reader: return t.Read(p) } return 0, nil } // Seek sets the offset for the next Read to offset, interpreted according to // whence: 0 means relative to the origin of the file, 1 means relative to the // current offset, and 2 means relative to the end. Seek returns the new offset // and an error, if any. // // If the ReaderSeekerCloser is not an io.Seeker nothing will be done. func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { switch t := r.r.(type) { case io.Seeker: return t.Seek(offset, whence) } return int64(0), nil } // IsSeeker returns if the underlying reader is also a seeker. func (r ReaderSeekerCloser) IsSeeker() bool { _, ok := r.r.(io.Seeker) return ok } // HasLen returns the length of the underlying reader if the value implements // the Len() int method. func (r ReaderSeekerCloser) HasLen() (int, bool) { type lenner interface { Len() int } if lr, ok := r.r.(lenner); ok { return lr.Len(), true } return 0, false } // GetLen returns the length of the bytes remaining in the underlying reader. // Checks first for Len(), then io.Seeker to determine the size of the // underlying reader. // // Will return -1 if the length cannot be determined. func (r ReaderSeekerCloser) GetLen() (int64, error) { if l, ok := r.HasLen(); ok { return int64(l), nil } if s, ok := r.r.(io.Seeker); ok { return seekerLen(s) } return -1, nil } // SeekerLen attempts to get the number of bytes remaining at the seeker's // current position. Returns the number of bytes remaining or error. func SeekerLen(s io.Seeker) (int64, error) { // Determine if the seeker is actually seekable. ReaderSeekerCloser // hides the fact that a io.Readers might not actually be seekable. switch v := s.(type) { case ReaderSeekerCloser: return v.GetLen() case *ReaderSeekerCloser: return v.GetLen() } return seekerLen(s) } func seekerLen(s io.Seeker) (int64, error) { curOffset, err := s.Seek(0, sdkio.SeekCurrent) if err != nil { return 0, err } endOffset, err := s.Seek(0, sdkio.SeekEnd) if err != nil { return 0, err } _, err = s.Seek(curOffset, sdkio.SeekStart) if err != nil { return 0, err } return endOffset - curOffset, nil } // Close closes the ReaderSeekerCloser. // // If the ReaderSeekerCloser is not an io.Closer nothing will be done. func (r ReaderSeekerCloser) Close() error { switch t := r.r.(type) { case io.Closer: return t.Close() } return nil } // A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface // Can be used with the s3manager.Downloader to download content to a buffer // in memory. Safe to use concurrently. type WriteAtBuffer struct { buf []byte m sync.Mutex // GrowthCoeff defines the growth rate of the internal buffer. By // default, the growth rate is 1, where expanding the internal // buffer will allocate only enough capacity to fit the new expected // length. GrowthCoeff float64 } // NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer // provided by buf. func NewWriteAtBuffer(buf []byte) *WriteAtBuffer { return &WriteAtBuffer{buf: buf} } // WriteAt writes a slice of bytes to a buffer starting at the position provided // The number of bytes written will be returned, or error. Can overwrite previous // written slices if the write ats overlap. func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { pLen := len(p) expLen := pos + int64(pLen) b.m.Lock() defer b.m.Unlock() if int64(len(b.buf)) < expLen { if int64(cap(b.buf)) < expLen { if b.GrowthCoeff < 1 { b.GrowthCoeff = 1 } newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen))) copy(newBuf, b.buf) b.buf = newBuf } b.buf = b.buf[:expLen] } copy(b.buf[pos:], p) return pLen, nil } // Bytes returns a slice of bytes written to the buffer. func (b *WriteAtBuffer) Bytes() []byte { b.m.Lock() defer b.m.Unlock() return b.buf } // MultiCloser is a utility to close multiple io.Closers within a single // statement. type MultiCloser []io.Closer // Close closes all of the io.Closers making up the MultiClosers. Any // errors that occur while closing will be returned in the order they // occur. func (m MultiCloser) Close() error { var errs errors for _, c := range m { err := c.Close() if err != nil { errs = append(errs, err) } } if len(errs) != 0 { return errs } return nil } type errors []error func (es errors) Error() string { var parts []string for _, e := range es { parts = append(parts, e.Error()) } return strings.Join(parts, "\n") } // CopySeekableBody copies the seekable body to an io.Writer func CopySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { curPos, err := src.Seek(0, sdkio.SeekCurrent) if err != nil { return 0, err } // copy errors may be assumed to be from the body. n, err := io.Copy(dst, src) if err != nil { return n, err } // seek back to the first position after reading to reset // the body for transmission. _, err = src.Seek(curPos, sdkio.SeekStart) if err != nil { return n, err } return n, nil }
265
session-manager-plugin
aws
Go
package aws import ( "bytes" "math/rand" "testing" ) func TestWriteAtBuffer(t *testing.T) { b := &WriteAtBuffer{} n, err := b.WriteAt([]byte{1}, 0) if err != nil { t.Errorf("expected no error, but received %v", err) } if e, a := 1, n; e != a { t.Errorf("expected %d, but received %d", e, a) } n, err = b.WriteAt([]byte{1, 1, 1}, 5) if err != nil { t.Errorf("expected no error, but received %v", err) } if e, a := 3, n; e != a { t.Errorf("expected %d, but received %d", e, a) } n, err = b.WriteAt([]byte{2}, 1) if err != nil { t.Errorf("expected no error, but received %v", err) } if e, a := 1, n; e != a { t.Errorf("expected %d, but received %d", e, a) } n, err = b.WriteAt([]byte{3}, 2) if err != nil { t.Errorf("expected no error, but received %v", err) } if e, a := 1, n; e != a { t.Errorf("expected %d, but received %d", e, a) } if !bytes.Equal([]byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes()) { t.Errorf("expected %v, but received %v", []byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes()) } } func BenchmarkWriteAtBuffer(b *testing.B) { buf := &WriteAtBuffer{} r := rand.New(rand.NewSource(1)) b.ResetTimer() for i := 0; i < b.N; i++ { to := r.Intn(10) * 4096 bs := make([]byte, to) buf.WriteAt(bs, r.Int63n(10)*4096) } } func BenchmarkWriteAtBufferOrderedWrites(b *testing.B) { // test the performance of a WriteAtBuffer when written in an // ordered fashion. This is similar to the behavior of the // s3.Downloader, since downloads the first chunk of the file, then // the second, and so on. // // This test simulates a 150MB file being written in 30 ordered 5MB chunks. chunk := int64(5e6) max := chunk * 30 // we'll write the same 5MB chunk every time tmp := make([]byte, chunk) for i := 0; i < b.N; i++ { buf := &WriteAtBuffer{} for i := int64(0); i < max; i += chunk { buf.WriteAt(tmp, i) } } } func BenchmarkWriteAtBufferParallel(b *testing.B) { buf := &WriteAtBuffer{} r := rand.New(rand.NewSource(1)) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { to := r.Intn(10) * 4096 bs := make([]byte, to) buf.WriteAt(bs, r.Int63n(10)*4096) } }) }
93
session-manager-plugin
aws
Go
// +build go1.8 package aws import "net/url" // URLHostname will extract the Hostname without port from the URL value. // // Wrapper of net/url#URL.Hostname for backwards Go version compatibility. func URLHostname(url *url.URL) string { return url.Hostname() }
13
session-manager-plugin
aws
Go
// +build !go1.8 package aws import ( "net/url" "strings" ) // URLHostname will extract the Hostname without port from the URL value. // // Copy of Go 1.8's net/url#URL.Hostname functionality. func URLHostname(url *url.URL) string { return stripPort(url.Host) } // stripPort is copy of Go 1.8 url#URL.Hostname functionality. // https://golang.org/src/net/url/url.go func stripPort(hostport string) string { colon := strings.IndexByte(hostport, ':') if colon == -1 { return hostport } if i := strings.IndexByte(hostport, ']'); i != -1 { return strings.TrimPrefix(hostport[:i], "[") } return hostport[:colon] }
30
session-manager-plugin
aws
Go
// Package aws provides core functionality for making requests to AWS services. package aws // SDKName is the name of this AWS SDK const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK const SDKVersion = "1.40.17"
9
session-manager-plugin
aws
Go
// Package arn provides a parser for interacting with Amazon Resource Names. package arn import ( "errors" "strings" ) const ( arnDelimiter = ":" arnSections = 6 arnPrefix = "arn:" // zero-indexed sectionPartition = 1 sectionService = 2 sectionRegion = 3 sectionAccountID = 4 sectionResource = 5 // errors invalidPrefix = "arn: invalid prefix" invalidSections = "arn: not enough sections" ) // ARN captures the individual fields of an Amazon Resource Name. // See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more information. type ARN struct { // The partition that the resource is in. For standard AWS regions, the partition is "aws". If you have resources in // other partitions, the partition is "aws-partitionname". For example, the partition for resources in the China // (Beijing) region is "aws-cn". Partition string // The service namespace that identifies the AWS product (for example, Amazon S3, IAM, or Amazon RDS). For a list of // namespaces, see // http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces. Service string // The region the resource resides in. Note that the ARNs for some resources do not require a region, so this // component might be omitted. Region string // The ID of the AWS account that owns the resource, without the hyphens. For example, 123456789012. Note that the // ARNs for some resources don't require an account number, so this component might be omitted. AccountID string // The content of this part of the ARN varies by service. It often includes an indicator of the type of resource — // for example, an IAM user or Amazon RDS database - followed by a slash (/) or a colon (:), followed by the // resource name itself. Some services allows paths for resource names, as described in // http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-paths. Resource string } // Parse parses an ARN into its constituent parts. // // Some example ARNs: // arn:aws:elasticbeanstalk:us-east-1:123456789012:environment/My App/MyEnvironment // arn:aws:iam::123456789012:user/David // arn:aws:rds:eu-west-1:123456789012:db:mysql-db // arn:aws:s3:::my_corporate_bucket/exampleobject.png func Parse(arn string) (ARN, error) { if !strings.HasPrefix(arn, arnPrefix) { return ARN{}, errors.New(invalidPrefix) } sections := strings.SplitN(arn, arnDelimiter, arnSections) if len(sections) != arnSections { return ARN{}, errors.New(invalidSections) } return ARN{ Partition: sections[sectionPartition], Service: sections[sectionService], Region: sections[sectionRegion], AccountID: sections[sectionAccountID], Resource: sections[sectionResource], }, nil } // IsARN returns whether the given string is an ARN by looking for // whether the string starts with "arn:" and contains the correct number // of sections delimited by colons(:). func IsARN(arn string) bool { return strings.HasPrefix(arn, arnPrefix) && strings.Count(arn, ":") >= arnSections-1 } // String returns the canonical representation of the ARN func (arn ARN) String() string { return arnPrefix + arn.Partition + arnDelimiter + arn.Service + arnDelimiter + arn.Region + arnDelimiter + arn.AccountID + arnDelimiter + arn.Resource }
94
session-manager-plugin
aws
Go
// +build go1.7 package arn import ( "errors" "testing" ) func TestParseARN(t *testing.T) { cases := []struct { input string arn ARN err error }{ { input: "invalid", err: errors.New(invalidPrefix), }, { input: "arn:nope", err: errors.New(invalidSections), }, { input: "arn:aws:ecr:us-west-2:123456789012:repository/foo/bar", arn: ARN{ Partition: "aws", Service: "ecr", Region: "us-west-2", AccountID: "123456789012", Resource: "repository/foo/bar", }, }, { input: "arn:aws:elasticbeanstalk:us-east-1:123456789012:environment/My App/MyEnvironment", arn: ARN{ Partition: "aws", Service: "elasticbeanstalk", Region: "us-east-1", AccountID: "123456789012", Resource: "environment/My App/MyEnvironment", }, }, { input: "arn:aws:iam::123456789012:user/David", arn: ARN{ Partition: "aws", Service: "iam", Region: "", AccountID: "123456789012", Resource: "user/David", }, }, { input: "arn:aws:rds:eu-west-1:123456789012:db:mysql-db", arn: ARN{ Partition: "aws", Service: "rds", Region: "eu-west-1", AccountID: "123456789012", Resource: "db:mysql-db", }, }, { input: "arn:aws:s3:::my_corporate_bucket/exampleobject.png", arn: ARN{ Partition: "aws", Service: "s3", Region: "", AccountID: "", Resource: "my_corporate_bucket/exampleobject.png", }, }, } for _, tc := range cases { t.Run(tc.input, func(t *testing.T) { spec, err := Parse(tc.input) if tc.arn != spec { t.Errorf("Expected %q to parse as %v, but got %v", tc.input, tc.arn, spec) } if err == nil && tc.err != nil { t.Errorf("Expected err to be %v, but got nil", tc.err) } else if err != nil && tc.err == nil { t.Errorf("Expected err to be nil, but got %v", err) } else if err != nil && tc.err != nil && err.Error() != tc.err.Error() { t.Errorf("Expected err to be %v, but got %v", tc.err, err) } }) } } func TestIsARN(t *testing.T) { cases := map[string]struct { In string Expect bool // Params }{ "valid ARN slash resource": { In: "arn:aws:service:us-west-2:123456789012:restype/resvalue", Expect: true, }, "valid ARN colon resource": { In: "arn:aws:service:us-west-2:123456789012:restype:resvalue", Expect: true, }, "valid ARN resource": { In: "arn:aws:service:us-west-2:123456789012:*", Expect: true, }, "empty sections": { In: "arn:::::", Expect: true, }, "invalid ARN": { In: "some random string", }, "invalid ARN missing resource": { In: "arn:aws:service:us-west-2:123456789012", }, } for name, c := range cases { t.Run(name, func(t *testing.T) { actual := IsARN(c.In) if e, a := c.Expect, actual; e != a { t.Errorf("expect %s valid %v, got %v", c.In, e, a) } }) } }
132
session-manager-plugin
aws
Go
// Package awserr represents API error interface accessors for the SDK. package awserr // An Error wraps lower level errors with code, message and an original error. // The underlying concrete error type may also satisfy other interfaces which // can be to used to obtain more specific information about the error. // // Calling Error() or String() will always include the full information about // an error based on its underlying type. // // Example: // // output, err := s3manage.Upload(svc, input, opts) // if err != nil { // if awsErr, ok := err.(awserr.Error); ok { // // Get error details // log.Println("Error:", awsErr.Code(), awsErr.Message()) // // // Prints out full error message, including original error if there was one. // log.Println("Error:", awsErr.Error()) // // // Get original error // if origErr := awsErr.OrigErr(); origErr != nil { // // operate on original error. // } // } else { // fmt.Println(err.Error()) // } // } // type Error interface { // Satisfy the generic error interface. error // Returns the short phrase depicting the classification of the error. Code() string // Returns the error details message. Message() string // Returns the original error if one was set. Nil is returned if not set. OrigErr() error } // BatchError is a batch of errors which also wraps lower level errors with // code, message, and original errors. Calling Error() will include all errors // that occurred in the batch. // // Deprecated: Replaced with BatchedErrors. Only defined for backwards // compatibility. type BatchError interface { // Satisfy the generic error interface. error // Returns the short phrase depicting the classification of the error. Code() string // Returns the error details message. Message() string // Returns the original error if one was set. Nil is returned if not set. OrigErrs() []error } // BatchedErrors is a batch of errors which also wraps lower level errors with // code, message, and original errors. Calling Error() will include all errors // that occurred in the batch. // // Replaces BatchError type BatchedErrors interface { // Satisfy the base Error interface. Error // Returns the original error if one was set. Nil is returned if not set. OrigErrs() []error } // New returns an Error object described by the code, message, and origErr. // // If origErr satisfies the Error interface it will not be wrapped within a new // Error object and will instead be returned. func New(code, message string, origErr error) Error { var errs []error if origErr != nil { errs = append(errs, origErr) } return newBaseError(code, message, errs) } // NewBatchError returns an BatchedErrors with a collection of errors as an // array of errors. func NewBatchError(code, message string, errs []error) BatchedErrors { return newBaseError(code, message, errs) } // A RequestFailure is an interface to extract request failure information from // an Error such as the request ID of the failed request returned by a service. // RequestFailures may not always have a requestID value if the request failed // prior to reaching the service such as a connection error. // // Example: // // output, err := s3manage.Upload(svc, input, opts) // if err != nil { // if reqerr, ok := err.(RequestFailure); ok { // log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID()) // } else { // log.Println("Error:", err.Error()) // } // } // // Combined with awserr.Error: // // output, err := s3manage.Upload(svc, input, opts) // if err != nil { // if awsErr, ok := err.(awserr.Error); ok { // // Generic AWS Error with Code, Message, and original error (if any) // fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) // // if reqErr, ok := err.(awserr.RequestFailure); ok { // // A service error occurred // fmt.Println(reqErr.StatusCode(), reqErr.RequestID()) // } // } else { // fmt.Println(err.Error()) // } // } // type RequestFailure interface { Error // The status code of the HTTP response. StatusCode() int // The request ID returned by the service for a request failure. This will // be empty if no request ID is available such as the request failed due // to a connection error. RequestID() string } // NewRequestFailure returns a wrapped error with additional information for // request status code, and service requestID. // // Should be used to wrap all request which involve service requests. Even if // the request failed without a service response, but had an HTTP status code // that may be meaningful. func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { return newRequestError(err, statusCode, reqID) } // UnmarshalError provides the interface for the SDK failing to unmarshal data. type UnmarshalError interface { awsError Bytes() []byte } // NewUnmarshalError returns an initialized UnmarshalError error wrapper adding // the bytes that fail to unmarshal to the error. func NewUnmarshalError(err error, msg string, bytes []byte) UnmarshalError { return &unmarshalError{ awsError: New("UnmarshalError", msg, err), bytes: bytes, } }
165
session-manager-plugin
aws
Go
package awserr import ( "encoding/hex" "fmt" ) // SprintError returns a string of the formatted error code. // // Both extra and origErr are optional. If they are included their lines // will be added, but if they are not included their lines will be ignored. func SprintError(code, message, extra string, origErr error) string { msg := fmt.Sprintf("%s: %s", code, message) if extra != "" { msg = fmt.Sprintf("%s\n\t%s", msg, extra) } if origErr != nil { msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) } return msg } // A baseError wraps the code and message which defines an error. It also // can be used to wrap an original error object. // // Should be used as the root for errors satisfying the awserr.Error. Also // for any error which does not fit into a specific error wrapper type. type baseError struct { // Classification of error code string // Detailed information about error message string // Optional original error this error is based off of. Allows building // chained errors. errs []error } // newBaseError returns an error object for the code, message, and errors. // // code is a short no whitespace phrase depicting the classification of // the error that is being created. // // message is the free flow string containing detailed information about the // error. // // origErrs is the error objects which will be nested under the new errors to // be returned. func newBaseError(code, message string, origErrs []error) *baseError { b := &baseError{ code: code, message: message, errs: origErrs, } return b } // Error returns the string representation of the error. // // See ErrorWithExtra for formatting. // // Satisfies the error interface. func (b baseError) Error() string { size := len(b.errs) if size > 0 { return SprintError(b.code, b.message, "", errorList(b.errs)) } return SprintError(b.code, b.message, "", nil) } // String returns the string representation of the error. // Alias for Error to satisfy the stringer interface. func (b baseError) String() string { return b.Error() } // Code returns the short phrase depicting the classification of the error. func (b baseError) Code() string { return b.code } // Message returns the error details message. func (b baseError) Message() string { return b.message } // OrigErr returns the original error if one was set. Nil is returned if no // error was set. This only returns the first element in the list. If the full // list is needed, use BatchedErrors. func (b baseError) OrigErr() error { switch len(b.errs) { case 0: return nil case 1: return b.errs[0] default: if err, ok := b.errs[0].(Error); ok { return NewBatchError(err.Code(), err.Message(), b.errs[1:]) } return NewBatchError("BatchedErrors", "multiple errors occurred", b.errs) } } // OrigErrs returns the original errors if one was set. An empty slice is // returned if no error was set. func (b baseError) OrigErrs() []error { return b.errs } // So that the Error interface type can be included as an anonymous field // in the requestError struct and not conflict with the error.Error() method. type awsError Error // A requestError wraps a request or service error. // // Composed of baseError for code, message, and original error. type requestError struct { awsError statusCode int requestID string bytes []byte } // newRequestError returns a wrapped error with additional information for // request status code, and service requestID. // // Should be used to wrap all request which involve service requests. Even if // the request failed without a service response, but had an HTTP status code // that may be meaningful. // // Also wraps original errors via the baseError. func newRequestError(err Error, statusCode int, requestID string) *requestError { return &requestError{ awsError: err, statusCode: statusCode, requestID: requestID, } } // Error returns the string representation of the error. // Satisfies the error interface. func (r requestError) Error() string { extra := fmt.Sprintf("status code: %d, request id: %s", r.statusCode, r.requestID) return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) } // String returns the string representation of the error. // Alias for Error to satisfy the stringer interface. func (r requestError) String() string { return r.Error() } // StatusCode returns the wrapped status code for the error func (r requestError) StatusCode() int { return r.statusCode } // RequestID returns the wrapped requestID func (r requestError) RequestID() string { return r.requestID } // OrigErrs returns the original errors if one was set. An empty slice is // returned if no error was set. func (r requestError) OrigErrs() []error { if b, ok := r.awsError.(BatchedErrors); ok { return b.OrigErrs() } return []error{r.OrigErr()} } type unmarshalError struct { awsError bytes []byte } // Error returns the string representation of the error. // Satisfies the error interface. func (e unmarshalError) Error() string { extra := hex.Dump(e.bytes) return SprintError(e.Code(), e.Message(), extra, e.OrigErr()) } // String returns the string representation of the error. // Alias for Error to satisfy the stringer interface. func (e unmarshalError) String() string { return e.Error() } // Bytes returns the bytes that failed to unmarshal. func (e unmarshalError) Bytes() []byte { return e.bytes } // An error list that satisfies the golang interface type errorList []error // Error returns the string representation of the error. // // Satisfies the error interface. func (e errorList) Error() string { msg := "" // How do we want to handle the array size being zero if size := len(e); size > 0 { for i := 0; i < size; i++ { msg += e[i].Error() // We check the next index to see if it is within the slice. // If it is, then we append a newline. We do this, because unit tests // could be broken with the additional '\n' if i+1 < size { msg += "\n" } } } return msg }
222
session-manager-plugin
aws
Go
package awsutil import ( "io" "reflect" "time" ) // Copy deeply copies a src structure to dst. Useful for copying request and // response structures. // // Can copy between structs of different type, but will only copy fields which // are assignable, and exist in both structs. Fields which are not assignable, // or do not exist in both structs are ignored. func Copy(dst, src interface{}) { dstval := reflect.ValueOf(dst) if !dstval.IsValid() { panic("Copy dst cannot be nil") } rcopy(dstval, reflect.ValueOf(src), true) } // CopyOf returns a copy of src while also allocating the memory for dst. // src must be a pointer type or this operation will fail. func CopyOf(src interface{}) (dst interface{}) { dsti := reflect.New(reflect.TypeOf(src).Elem()) dst = dsti.Interface() rcopy(dsti, reflect.ValueOf(src), true) return } // rcopy performs a recursive copy of values from the source to destination. // // root is used to skip certain aspects of the copy which are not valid // for the root node of a object. func rcopy(dst, src reflect.Value, root bool) { if !src.IsValid() { return } switch src.Kind() { case reflect.Ptr: if _, ok := src.Interface().(io.Reader); ok { if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { dst.Elem().Set(src) } else if dst.CanSet() { dst.Set(src) } } else { e := src.Type().Elem() if dst.CanSet() && !src.IsNil() { if _, ok := src.Interface().(*time.Time); !ok { dst.Set(reflect.New(e)) } else { tempValue := reflect.New(e) tempValue.Elem().Set(src.Elem()) // Sets time.Time's unexported values dst.Set(tempValue) } } if src.Elem().IsValid() { // Keep the current root state since the depth hasn't changed rcopy(dst.Elem(), src.Elem(), root) } } case reflect.Struct: t := dst.Type() for i := 0; i < t.NumField(); i++ { name := t.Field(i).Name srcVal := src.FieldByName(name) dstVal := dst.FieldByName(name) if srcVal.IsValid() && dstVal.CanSet() { rcopy(dstVal, srcVal, false) } } case reflect.Slice: if src.IsNil() { break } s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) dst.Set(s) for i := 0; i < src.Len(); i++ { rcopy(dst.Index(i), src.Index(i), false) } case reflect.Map: if src.IsNil() { break } s := reflect.MakeMap(src.Type()) dst.Set(s) for _, k := range src.MapKeys() { v := src.MapIndex(k) v2 := reflect.New(v.Type()).Elem() rcopy(v2, v, false) dst.SetMapIndex(k, v2) } default: // Assign the value if possible. If its not assignable, the value would // need to be converted and the impact of that may be unexpected, or is // not compatible with the dst type. if src.Type().AssignableTo(dst.Type()) { dst.Set(src) } } }
109
session-manager-plugin
aws
Go
package awsutil_test import ( "bytes" "fmt" "io" "io/ioutil" "reflect" "testing" "time" "github.com/aws/aws-sdk-go/aws/awsutil" ) func ExampleCopy() { type Foo struct { A int B []*string } // Create the initial value str1 := "hello" str2 := "bye bye" f1 := &Foo{A: 1, B: []*string{&str1, &str2}} // Do the copy var f2 Foo awsutil.Copy(&f2, f1) // Print the result fmt.Println(awsutil.Prettify(f2)) // Output: // { // A: 1, // B: ["hello","bye bye"] // } } func TestCopy1(t *testing.T) { type Bar struct { a *int B *int c int D int } type Foo struct { A int B []*string C map[string]*int D *time.Time E *Bar } // Create the initial value str1 := "hello" str2 := "bye bye" int1 := 1 int2 := 2 intPtr1 := 1 intPtr2 := 2 now := time.Now() f1 := &Foo{ A: 1, B: []*string{&str1, &str2}, C: map[string]*int{ "A": &int1, "B": &int2, }, D: &now, E: &Bar{ &intPtr1, &intPtr2, 2, 3, }, } // Do the copy var f2 Foo awsutil.Copy(&f2, f1) // Values are equal if v1, v2 := f2.A, f1.A; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.B, f1.B; !reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.C, f1.C; !reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.D, f1.D; !v1.Equal(*v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.E.B, f1.E.B; !reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.E.D, f1.E.D; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } // But pointers are not! str3 := "nothello" int3 := 57 f2.A = 100 *f2.B[0] = str3 *f2.C["B"] = int3 *f2.D = time.Now() f2.E.a = &int3 *f2.E.B = int3 f2.E.c = 5 f2.E.D = 5 if v1, v2 := f2.A, f1.A; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.B, f1.B; reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.C, f1.C; reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.D, f1.D; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.E.a, f1.E.a; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.E.B, f1.E.B; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.E.c, f1.E.c; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.E.D, f1.E.D; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } } func TestCopyNestedWithUnexported(t *testing.T) { type Bar struct { a int B int } type Foo struct { A string B Bar } f1 := &Foo{A: "string", B: Bar{a: 1, B: 2}} var f2 Foo awsutil.Copy(&f2, f1) // Values match if v1, v2 := f2.A, f1.A; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.B, f1.B; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.B.a, f1.B.a; v1 == v2 { t.Errorf("expected values to be not equivalent, but received %v", v1) } if v1, v2 := f2.B.B, f2.B.B; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } } func TestCopyIgnoreNilMembers(t *testing.T) { type Foo struct { A *string B []string C map[string]string } f := &Foo{} if v1 := f.A; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1 := f.B; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1 := f.C; v1 != nil { t.Errorf("expected nil, but received %v", v1) } var f2 Foo awsutil.Copy(&f2, f) if v1 := f2.A; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1 := f2.B; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1 := f2.C; v1 != nil { t.Errorf("expected nil, but received %v", v1) } fcopy := awsutil.CopyOf(f) f3 := fcopy.(*Foo) if v1 := f3.A; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1 := f3.B; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1 := f3.C; v1 != nil { t.Errorf("expected nil, but received %v", v1) } } func TestCopyPrimitive(t *testing.T) { str := "hello" var s string awsutil.Copy(&s, &str) if v1, v2 := "hello", s; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } } func TestCopyNil(t *testing.T) { var s string awsutil.Copy(&s, nil) if v1, v2 := "", s; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } } func TestCopyReader(t *testing.T) { var buf io.Reader = bytes.NewReader([]byte("hello world")) var r io.Reader awsutil.Copy(&r, buf) b, err := ioutil.ReadAll(r) if err != nil { t.Errorf("expected no error, but received %v", err) } if v1, v2 := []byte("hello world"), b; !bytes.Equal(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } // empty bytes because this is not a deep copy b, err = ioutil.ReadAll(buf) if err != nil { t.Errorf("expected no error, but received %v", err) } if v1, v2 := []byte(""), b; !bytes.Equal(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } } func TestCopyDifferentStructs(t *testing.T) { type SrcFoo struct { A int B []*string C map[string]*int SrcUnique string SameNameDiffType int unexportedPtr *int ExportedPtr *int } type DstFoo struct { A int B []*string C map[string]*int DstUnique int SameNameDiffType string unexportedPtr *int ExportedPtr *int } // Create the initial value str1 := "hello" str2 := "bye bye" int1 := 1 int2 := 2 f1 := &SrcFoo{ A: 1, B: []*string{&str1, &str2}, C: map[string]*int{ "A": &int1, "B": &int2, }, SrcUnique: "unique", SameNameDiffType: 1, unexportedPtr: &int1, ExportedPtr: &int2, } // Do the copy var f2 DstFoo awsutil.Copy(&f2, f1) // Values are equal if v1, v2 := f2.A, f1.A; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.B, f1.B; !reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := f2.C, f1.C; !reflect.DeepEqual(v1, v2) { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := "unique", f1.SrcUnique; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := 1, f1.SameNameDiffType; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := 0, f2.DstUnique; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := "", f2.SameNameDiffType; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := int1, *f1.unexportedPtr; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1 := f2.unexportedPtr; v1 != nil { t.Errorf("expected nil, but received %v", v1) } if v1, v2 := int2, *f1.ExportedPtr; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } if v1, v2 := int2, *f2.ExportedPtr; v1 != v2 { t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) } } func ExampleCopyOf() { type Foo struct { A int B []*string } // Create the initial value str1 := "hello" str2 := "bye bye" f1 := &Foo{A: 1, B: []*string{&str1, &str2}} // Do the copy v := awsutil.CopyOf(f1) var f2 *Foo = v.(*Foo) // Print the result fmt.Println(awsutil.Prettify(f2)) // Output: // { // A: 1, // B: ["hello","bye bye"] // } }
354
session-manager-plugin
aws
Go
package awsutil import ( "reflect" ) // DeepEqual returns if the two values are deeply equal like reflect.DeepEqual. // In addition to this, this method will also dereference the input values if // possible so the DeepEqual performed will not fail if one parameter is a // pointer and the other is not. // // DeepEqual will not perform indirection of nested values of the input parameters. func DeepEqual(a, b interface{}) bool { ra := reflect.Indirect(reflect.ValueOf(a)) rb := reflect.Indirect(reflect.ValueOf(b)) if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid { // If the elements are both nil, and of the same type they are equal // If they are of different types they are not equal return reflect.TypeOf(a) == reflect.TypeOf(b) } else if raValid != rbValid { // Both values must be valid to be equal return false } return reflect.DeepEqual(ra.Interface(), rb.Interface()) }
28
session-manager-plugin
aws
Go
package awsutil_test import ( "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" ) func TestDeepEqual(t *testing.T) { cases := []struct { a, b interface{} equal bool }{ {"a", "a", true}, {"a", "b", false}, {"a", aws.String(""), false}, {"a", nil, false}, {"a", aws.String("a"), true}, {(*bool)(nil), (*bool)(nil), true}, {(*bool)(nil), (*string)(nil), false}, {nil, nil, true}, } for i, c := range cases { if awsutil.DeepEqual(c.a, c.b) != c.equal { t.Errorf("%d, a:%v b:%v, %t", i, c.a, c.b, c.equal) } } }
31
session-manager-plugin
aws
Go
package awsutil import ( "reflect" "regexp" "strconv" "strings" "github.com/jmespath/go-jmespath" ) var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) // rValuesAtPath returns a slice of values found in value v. The values // in v are explored recursively so all nested values are collected. func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value { pathparts := strings.Split(path, "||") if len(pathparts) > 1 { for _, pathpart := range pathparts { vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm) if len(vals) > 0 { return vals } } return nil } values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} components := strings.Split(path, ".") for len(values) > 0 && len(components) > 0 { var index *int64 var indexStar bool c := strings.TrimSpace(components[0]) if c == "" { // no actual component, illegal syntax return nil } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] { // TODO normalize case for user return nil // don't support unexported fields } // parse this component if m := indexRe.FindStringSubmatch(c); m != nil { c = m[1] if m[2] == "" { index = nil indexStar = true } else { i, _ := strconv.ParseInt(m[2], 10, 32) index = &i indexStar = false } } nextvals := []reflect.Value{} for _, value := range values { // pull component name out of struct member if value.Kind() != reflect.Struct { continue } if c == "*" { // pull all members for i := 0; i < value.NumField(); i++ { if f := reflect.Indirect(value.Field(i)); f.IsValid() { nextvals = append(nextvals, f) } } continue } value = value.FieldByNameFunc(func(name string) bool { if c == name { return true } else if !caseSensitive && strings.EqualFold(name, c) { return true } return false }) if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 { if !value.IsNil() { value.Set(reflect.Zero(value.Type())) } return []reflect.Value{value} } if createPath && value.Kind() == reflect.Ptr && value.IsNil() { // TODO if the value is the terminus it should not be created // if the value to be set to its position is nil. value.Set(reflect.New(value.Type().Elem())) value = value.Elem() } else { value = reflect.Indirect(value) } if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { if !createPath && value.IsNil() { value = reflect.ValueOf(nil) } } if value.IsValid() { nextvals = append(nextvals, value) } } values = nextvals if indexStar || index != nil { nextvals = []reflect.Value{} for _, valItem := range values { value := reflect.Indirect(valItem) if value.Kind() != reflect.Slice { continue } if indexStar { // grab all indices for i := 0; i < value.Len(); i++ { idx := reflect.Indirect(value.Index(i)) if idx.IsValid() { nextvals = append(nextvals, idx) } } continue } // pull out index i := int(*index) if i >= value.Len() { // check out of bounds if createPath { // TODO resize slice } else { continue } } else if i < 0 { // support negative indexing i = value.Len() + i } value = reflect.Indirect(value.Index(i)) if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { if !createPath && value.IsNil() { value = reflect.ValueOf(nil) } } if value.IsValid() { nextvals = append(nextvals, value) } } values = nextvals } components = components[1:] } return values } // ValuesAtPath returns a list of values at the case insensitive lexical // path inside of a structure. func ValuesAtPath(i interface{}, path string) ([]interface{}, error) { result, err := jmespath.Search(path, i) if err != nil { return nil, err } v := reflect.ValueOf(result) if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) { return nil, nil } if s, ok := result.([]interface{}); ok { return s, err } if v.Kind() == reflect.Map && v.Len() == 0 { return nil, nil } if v.Kind() == reflect.Slice { out := make([]interface{}, v.Len()) for i := 0; i < v.Len(); i++ { out[i] = v.Index(i).Interface() } return out, nil } return []interface{}{result}, nil } // SetValueAtPath sets a value at the case insensitive lexical path inside // of a structure. func SetValueAtPath(i interface{}, path string, v interface{}) { rvals := rValuesAtPath(i, path, true, false, v == nil) for _, rval := range rvals { if rval.Kind() == reflect.Ptr && rval.IsNil() { continue } setValue(rval, v) } } func setValue(dstVal reflect.Value, src interface{}) { if dstVal.Kind() == reflect.Ptr { dstVal = reflect.Indirect(dstVal) } srcVal := reflect.ValueOf(src) if !srcVal.IsValid() { // src is literal nil if dstVal.CanAddr() { // Convert to pointer so that pointer's value can be nil'ed // dstVal = dstVal.Addr() } dstVal.Set(reflect.Zero(dstVal.Type())) } else if srcVal.Kind() == reflect.Ptr { if srcVal.IsNil() { srcVal = reflect.Zero(dstVal.Type()) } else { srcVal = reflect.ValueOf(src).Elem() } dstVal.Set(srcVal) } else { dstVal.Set(srcVal) } }
222
session-manager-plugin
aws
Go
package awsutil_test import ( "strings" "testing" "github.com/aws/aws-sdk-go/aws/awsutil" ) type Struct struct { A []Struct z []Struct B *Struct D *Struct C string E map[string]string } var data = Struct{ A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, z: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}}, C: "initial", } var data2 = Struct{A: []Struct{ {A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, {A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, }} func TestValueAtPathSuccess(t *testing.T) { var testCases = []struct { expect []interface{} data interface{} path string }{ {[]interface{}{"initial"}, data, "C"}, {[]interface{}{"value1"}, data, "A[0].C"}, {[]interface{}{"value2"}, data, "A[1].C"}, {[]interface{}{"value3"}, data, "A[2].C"}, {[]interface{}{"value3"}, data, "a[2].c"}, {[]interface{}{"value3"}, data, "A[-1].C"}, {[]interface{}{"value1", "value2", "value3"}, data, "A[].C"}, {[]interface{}{"terminal"}, data, "B . B . C"}, {[]interface{}{"initial"}, data, "A.D.X || C"}, {[]interface{}{"initial"}, data, "A[0].B || C"}, {[]interface{}{ Struct{A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, Struct{A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, }, data2, "A"}, } for i, c := range testCases { v, err := awsutil.ValuesAtPath(c.data, c.path) if err != nil { t.Errorf("case %v, expected no error, %v", i, c.path) } if e, a := c.expect, v; !awsutil.DeepEqual(e, a) { t.Errorf("case %v, %v", i, c.path) } } } func TestValueAtPathFailure(t *testing.T) { var testCases = []struct { expect []interface{} errContains string data interface{} path string }{ {nil, "", data, "C.x"}, {nil, "SyntaxError: Invalid token: tDot", data, ".x"}, {nil, "", data, "X.Y.Z"}, {nil, "", data, "A[100].C"}, {nil, "", data, "A[3].C"}, {nil, "", data, "B.B.C.Z"}, {nil, "", data, "z[-1].C"}, {nil, "", nil, "A.B.C"}, {[]interface{}{}, "", Struct{}, "A"}, {nil, "", data, "A[0].B.C"}, {nil, "", data, "D"}, } for i, c := range testCases { v, err := awsutil.ValuesAtPath(c.data, c.path) if c.errContains != "" { if !strings.Contains(err.Error(), c.errContains) { t.Errorf("case %v, expected error, %v", i, c.path) } continue } else { if err != nil { t.Errorf("case %v, expected no error, %v", i, c.path) } } if e, a := c.expect, v; !awsutil.DeepEqual(e, a) { t.Errorf("case %v, %v", i, c.path) } } } func TestSetValueAtPathSuccess(t *testing.T) { var s Struct awsutil.SetValueAtPath(&s, "C", "test1") awsutil.SetValueAtPath(&s, "B.B.C", "test2") awsutil.SetValueAtPath(&s, "B.D.C", "test3") if e, a := "test1", s.C; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := "test2", s.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := "test3", s.B.D.C; e != a { t.Errorf("expected %v, but received %v", e, a) } awsutil.SetValueAtPath(&s, "B.*.C", "test0") if e, a := "test0", s.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } if e, a := "test0", s.B.D.C; e != a { t.Errorf("expected %v, but received %v", e, a) } var s2 Struct awsutil.SetValueAtPath(&s2, "b.b.c", "test0") if e, a := "test0", s2.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } awsutil.SetValueAtPath(&s2, "A", []Struct{{}}) if e, a := []Struct{{}}, s2.A; !awsutil.DeepEqual(e, a) { t.Errorf("expected %v, but received %v", e, a) } str := "foo" s3 := Struct{} awsutil.SetValueAtPath(&s3, "b.b.c", str) if e, a := "foo", s3.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } s3 = Struct{B: &Struct{B: &Struct{C: str}}} awsutil.SetValueAtPath(&s3, "b.b.c", nil) if e, a := "", s3.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } s3 = Struct{} awsutil.SetValueAtPath(&s3, "b.b.c", nil) if e, a := "", s3.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } s3 = Struct{} awsutil.SetValueAtPath(&s3, "b.b.c", &str) if e, a := "foo", s3.B.B.C; e != a { t.Errorf("expected %v, but received %v", e, a) } var s4 struct{ Name *string } awsutil.SetValueAtPath(&s4, "Name", str) if e, a := str, *s4.Name; e != a { t.Errorf("expected %v, but received %v", e, a) } s4 = struct{ Name *string }{} awsutil.SetValueAtPath(&s4, "Name", nil) if e, a := (*string)(nil), s4.Name; e != a { t.Errorf("expected %v, but received %v", e, a) } s4 = struct{ Name *string }{Name: &str} awsutil.SetValueAtPath(&s4, "Name", nil) if e, a := (*string)(nil), s4.Name; e != a { t.Errorf("expected %v, but received %v", e, a) } s4 = struct{ Name *string }{} awsutil.SetValueAtPath(&s4, "Name", &str) if e, a := str, *s4.Name; e != a { t.Errorf("expected %v, but received %v", e, a) } }
183
session-manager-plugin
aws
Go
package awsutil import ( "bytes" "fmt" "io" "reflect" "strings" ) // Prettify returns the string representation of a value. func Prettify(i interface{}) string { var buf bytes.Buffer prettify(reflect.ValueOf(i), 0, &buf) return buf.String() } // prettify will recursively walk value v to build a textual // representation of the value. func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { for v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Struct: strtype := v.Type().String() if strtype == "time.Time" { fmt.Fprintf(buf, "%s", v.Interface()) break } else if strings.HasPrefix(strtype, "io.") { buf.WriteString("<buffer>") break } buf.WriteString("{\n") names := []string{} for i := 0; i < v.Type().NumField(); i++ { name := v.Type().Field(i).Name f := v.Field(i) if name[0:1] == strings.ToLower(name[0:1]) { continue // ignore unexported fields } if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { continue // ignore unset fields } names = append(names, name) } for i, n := range names { val := v.FieldByName(n) buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(n + ": ") prettify(val, indent+2, buf) if i < len(names)-1 { buf.WriteString(",\n") } } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") case reflect.Slice: strtype := v.Type().String() if strtype == "[]uint8" { fmt.Fprintf(buf, "<binary> len %d", v.Len()) break } nl, id, id2 := "", "", "" if v.Len() > 3 { nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) } buf.WriteString("[" + nl) for i := 0; i < v.Len(); i++ { buf.WriteString(id2) prettify(v.Index(i), indent+2, buf) if i < v.Len()-1 { buf.WriteString("," + nl) } } buf.WriteString(nl + id + "]") case reflect.Map: buf.WriteString("{\n") for i, k := range v.MapKeys() { buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(k.String() + ": ") prettify(v.MapIndex(k), indent+2, buf) if i < v.Len()-1 { buf.WriteString(",\n") } } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") default: if !v.IsValid() { fmt.Fprint(buf, "<invalid value>") return } format := "%v" switch v.Interface().(type) { case string: format = "%q" case io.ReadSeeker, io.Reader: format = "buffer(%p)" } fmt.Fprintf(buf, format, v.Interface()) } }
114
session-manager-plugin
aws
Go
package awsutil import ( "bytes" "fmt" "reflect" "strings" ) // StringValue returns the string representation of a value. func StringValue(i interface{}) string { var buf bytes.Buffer stringValue(reflect.ValueOf(i), 0, &buf) return buf.String() } func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { for v.Kind() == reflect.Ptr { v = v.Elem() } switch v.Kind() { case reflect.Struct: buf.WriteString("{\n") for i := 0; i < v.Type().NumField(); i++ { ft := v.Type().Field(i) fv := v.Field(i) if ft.Name[0:1] == strings.ToLower(ft.Name[0:1]) { continue // ignore unexported fields } if (fv.Kind() == reflect.Ptr || fv.Kind() == reflect.Slice) && fv.IsNil() { continue // ignore unset fields } buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(ft.Name + ": ") if tag := ft.Tag.Get("sensitive"); tag == "true" { buf.WriteString("<sensitive>") } else { stringValue(fv, indent+2, buf) } buf.WriteString(",\n") } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") case reflect.Slice: nl, id, id2 := "", "", "" if v.Len() > 3 { nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) } buf.WriteString("[" + nl) for i := 0; i < v.Len(); i++ { buf.WriteString(id2) stringValue(v.Index(i), indent+2, buf) if i < v.Len()-1 { buf.WriteString("," + nl) } } buf.WriteString(nl + id + "]") case reflect.Map: buf.WriteString("{\n") for i, k := range v.MapKeys() { buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(k.String() + ": ") stringValue(v.MapIndex(k), indent+2, buf) if i < v.Len()-1 { buf.WriteString(",\n") } } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") default: format := "%v" switch v.Interface().(type) { case string: format = "%q" } fmt.Fprintf(buf, format, v.Interface()) } }
89
session-manager-plugin
aws
Go
// +build go1.7 package awsutil import ( "testing" "github.com/aws/aws-sdk-go/aws" ) type testStruct struct { Field1 string Field2 *string Field3 []byte `sensitive:"true"` Value []*string } func TestStringValue(t *testing.T) { cases := map[string]struct { Value interface{} Expect string }{ "general": { Value: testStruct{ Field1: "abc123", Field2: aws.String("abc123"), Field3: []byte("don't show me"), Value: []*string{ aws.String("first"), aws.String("second"), }, }, Expect: `{ Field1: "abc123", Field2: "abc123", Field3: <sensitive>, Value: ["first","second"], }`, }, } for d, c := range cases { t.Run(d, func(t *testing.T) { actual := StringValue(c.Value) if e, a := c.Expect, actual; e != a { t.Errorf("expect:\n%v\nactual:\n%v\n", e, a) } }) } }
52
session-manager-plugin
aws
Go
package client import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" ) // A Config provides configuration to a service client instance. type Config struct { Config *aws.Config Handlers request.Handlers PartitionID string Endpoint string SigningRegion string SigningName string // States that the signing name did not come from a modeled source but // was derived based on other data. Used by service client constructors // to determine if the signin name can be overridden based on metadata the // service has. SigningNameDerived bool } // ConfigProvider provides a generic way for a service client to receive // the ClientConfig without circular dependencies. type ConfigProvider interface { ClientConfig(serviceName string, cfgs ...*aws.Config) Config } // ConfigNoResolveEndpointProvider same as ConfigProvider except it will not // resolve the endpoint automatically. The service client's endpoint must be // provided via the aws.Config.Endpoint field. type ConfigNoResolveEndpointProvider interface { ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) Config } // A Client implements the base client request and response handling // used by all service clients. type Client struct { request.Retryer metadata.ClientInfo Config aws.Config Handlers request.Handlers } // New will return a pointer to a new initialized service client. func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client { svc := &Client{ Config: cfg, ClientInfo: info, Handlers: handlers.Copy(), } switch retryer, ok := cfg.Retryer.(request.Retryer); { case ok: svc.Retryer = retryer case cfg.Retryer != nil && cfg.Logger != nil: s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer) cfg.Logger.Log(s) fallthrough default: maxRetries := aws.IntValue(cfg.MaxRetries) if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { maxRetries = DefaultRetryerMaxNumRetries } svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries} } svc.AddDebugHandlers() for _, option := range options { option(svc) } return svc } // NewRequest returns a new Request pointer for the service API // operation and parameters. func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request { return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data) } // AddDebugHandlers injects debug logging handlers into the service to log request // debug information. func (c *Client) AddDebugHandlers() { c.Handlers.Send.PushFrontNamed(LogHTTPRequestHandler) c.Handlers.Send.PushBackNamed(LogHTTPResponseHandler) }
94
session-manager-plugin
aws
Go
package client import ( "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" ) func pushBackTestHandler(name string, list *request.HandlerList) *bool { called := false (*list).PushBackNamed(request.NamedHandler{ Name: name, Fn: func(r *request.Request) { called = true }, }) return &called } func pushFrontTestHandler(name string, list *request.HandlerList) *bool { called := false (*list).PushFrontNamed(request.NamedHandler{ Name: name, Fn: func(r *request.Request) { called = true }, }) return &called } func TestNewClient_CopyHandlers(t *testing.T) { handlers := request.Handlers{} firstCalled := pushBackTestHandler("first", &handlers.Send) secondCalled := pushBackTestHandler("second", &handlers.Send) var clientHandlerCalled *bool c := New(aws.Config{}, metadata.ClientInfo{}, handlers, func(c *Client) { clientHandlerCalled = pushFrontTestHandler("client handler", &c.Handlers.Send) }, ) if e, a := 2, handlers.Send.Len(); e != a { t.Errorf("expect %d original handlers, got %d", e, a) } if e, a := 5, c.Handlers.Send.Len(); e != a { t.Errorf("expect %d client handlers, got %d", e, a) } req := c.NewRequest(&request.Operation{}, struct{}{}, struct{}{}) handlers.Send.Run(req) if !*firstCalled { t.Errorf("expect first handler to of been called") } *firstCalled = false if !*secondCalled { t.Errorf("expect second handler to of been called") } *secondCalled = false if *clientHandlerCalled { t.Errorf("expect client handler to not of been called, but was") } c.Handlers.Send.Run(req) if !*firstCalled { t.Errorf("expect client's first handler to of been called") } if !*secondCalled { t.Errorf("expect client's second handler to of been called") } if !*clientHandlerCalled { t.Errorf("expect client's client handler to of been called") } }
81
session-manager-plugin
aws
Go
package client import ( "math" "strconv" "time" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/sdkrand" ) // DefaultRetryer implements basic retry logic using exponential backoff for // most services. If you want to implement custom retry logic, you can implement the // request.Retryer interface. // type DefaultRetryer struct { // Num max Retries is the number of max retries that will be performed. // By default, this is zero. NumMaxRetries int // MinRetryDelay is the minimum retry delay after which retry will be performed. // If not set, the value is 0ns. MinRetryDelay time.Duration // MinThrottleRetryDelay is the minimum retry delay when throttled. // If not set, the value is 0ns. MinThrottleDelay time.Duration // MaxRetryDelay is the maximum retry delay before which retry must be performed. // If not set, the value is 0ns. MaxRetryDelay time.Duration // MaxThrottleDelay is the maximum retry delay when throttled. // If not set, the value is 0ns. MaxThrottleDelay time.Duration } const ( // DefaultRetryerMaxNumRetries sets maximum number of retries DefaultRetryerMaxNumRetries = 3 // DefaultRetryerMinRetryDelay sets minimum retry delay DefaultRetryerMinRetryDelay = 30 * time.Millisecond // DefaultRetryerMinThrottleDelay sets minimum delay when throttled DefaultRetryerMinThrottleDelay = 500 * time.Millisecond // DefaultRetryerMaxRetryDelay sets maximum retry delay DefaultRetryerMaxRetryDelay = 300 * time.Second // DefaultRetryerMaxThrottleDelay sets maximum delay when throttled DefaultRetryerMaxThrottleDelay = 300 * time.Second ) // MaxRetries returns the number of maximum returns the service will use to make // an individual API request. func (d DefaultRetryer) MaxRetries() int { return d.NumMaxRetries } // setRetryerDefaults sets the default values of the retryer if not set func (d *DefaultRetryer) setRetryerDefaults() { if d.MinRetryDelay == 0 { d.MinRetryDelay = DefaultRetryerMinRetryDelay } if d.MaxRetryDelay == 0 { d.MaxRetryDelay = DefaultRetryerMaxRetryDelay } if d.MinThrottleDelay == 0 { d.MinThrottleDelay = DefaultRetryerMinThrottleDelay } if d.MaxThrottleDelay == 0 { d.MaxThrottleDelay = DefaultRetryerMaxThrottleDelay } } // RetryRules returns the delay duration before retrying this request again func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { // if number of max retries is zero, no retries will be performed. if d.NumMaxRetries == 0 { return 0 } // Sets default value for retryer members d.setRetryerDefaults() // minDelay is the minimum retryer delay minDelay := d.MinRetryDelay var initialDelay time.Duration isThrottle := r.IsErrorThrottle() if isThrottle { if delay, ok := getRetryAfterDelay(r); ok { initialDelay = delay } minDelay = d.MinThrottleDelay } retryCount := r.RetryCount // maxDelay the maximum retryer delay maxDelay := d.MaxRetryDelay if isThrottle { maxDelay = d.MaxThrottleDelay } var delay time.Duration // Logic to cap the retry count based on the minDelay provided actualRetryCount := int(math.Log2(float64(minDelay))) + 1 if actualRetryCount < 63-retryCount { delay = time.Duration(1<<uint64(retryCount)) * getJitterDelay(minDelay) if delay > maxDelay { delay = getJitterDelay(maxDelay / 2) } } else { delay = getJitterDelay(maxDelay / 2) } return delay + initialDelay } // getJitterDelay returns a jittered delay for retry func getJitterDelay(duration time.Duration) time.Duration { return time.Duration(sdkrand.SeededRand.Int63n(int64(duration)) + int64(duration)) } // ShouldRetry returns true if the request should be retried. func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { // ShouldRetry returns false if number of max retries is 0. if d.NumMaxRetries == 0 { return false } // If one of the other handlers already set the retry state // we don't want to override it based on the service's state if r.Retryable != nil { return *r.Retryable } return r.IsErrorRetryable() || r.IsErrorThrottle() } // This will look in the Retry-After header, RFC 7231, for how long // it will wait before attempting another request func getRetryAfterDelay(r *request.Request) (time.Duration, bool) { if !canUseRetryAfterHeader(r) { return 0, false } delayStr := r.HTTPResponse.Header.Get("Retry-After") if len(delayStr) == 0 { return 0, false } delay, err := strconv.Atoi(delayStr) if err != nil { return 0, false } return time.Duration(delay) * time.Second, true } // Will look at the status code to see if the retry header pertains to // the status code. func canUseRetryAfterHeader(r *request.Request) bool { switch r.HTTPResponse.StatusCode { case 429: case 503: default: return false } return true }
178
session-manager-plugin
aws
Go
package client import ( "net/http" "testing" "time" "github.com/aws/aws-sdk-go/aws/request" ) func TestRetryThrottleStatusCodes(t *testing.T) { cases := []struct { expectThrottle bool expectRetry bool r request.Request }{ { false, false, request.Request{ HTTPResponse: &http.Response{StatusCode: 200}, }, }, { true, true, request.Request{ HTTPResponse: &http.Response{StatusCode: 429}, }, }, { true, true, request.Request{ HTTPResponse: &http.Response{StatusCode: 502}, }, }, { true, true, request.Request{ HTTPResponse: &http.Response{StatusCode: 503}, }, }, { true, true, request.Request{ HTTPResponse: &http.Response{StatusCode: 504}, }, }, { false, true, request.Request{ HTTPResponse: &http.Response{StatusCode: 500}, }, }, } d := DefaultRetryer{NumMaxRetries: 10} for i, c := range cases { throttle := c.r.IsErrorThrottle() retry := d.ShouldRetry(&c.r) if e, a := c.expectThrottle, throttle; e != a { t.Errorf("%d: expected %v, but received %v", i, e, a) } if e, a := c.expectRetry, retry; e != a { t.Errorf("%d: expected %v, but received %v", i, e, a) } } } func TestCanUseRetryAfter(t *testing.T) { cases := []struct { r request.Request e bool }{ { request.Request{ HTTPResponse: &http.Response{StatusCode: 200}, }, false, }, { request.Request{ HTTPResponse: &http.Response{StatusCode: 500}, }, false, }, { request.Request{ HTTPResponse: &http.Response{StatusCode: 429}, }, true, }, { request.Request{ HTTPResponse: &http.Response{StatusCode: 503}, }, true, }, } for i, c := range cases { a := canUseRetryAfterHeader(&c.r) if c.e != a { t.Errorf("%d: expected %v, but received %v", i, c.e, a) } } } func TestGetRetryDelay(t *testing.T) { cases := []struct { r request.Request e time.Duration equal bool ok bool }{ { request.Request{ HTTPResponse: &http.Response{StatusCode: 429, Header: http.Header{"Retry-After": []string{"3600"}}}, }, 3600 * time.Second, true, true, }, { request.Request{ HTTPResponse: &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{"120"}}}, }, 120 * time.Second, true, true, }, { request.Request{ HTTPResponse: &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{"120"}}}, }, 1 * time.Second, false, true, }, { request.Request{ HTTPResponse: &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{""}}}, }, 0 * time.Second, true, false, }, } for i, c := range cases { a, ok := getRetryAfterDelay(&c.r) if c.ok != ok { t.Errorf("%d: expected %v, but received %v", i, c.ok, ok) } if (c.e != a) == c.equal { t.Errorf("%d: expected %v, but received %v", i, c.e, a) } } } func TestRetryDelay(t *testing.T) { d := DefaultRetryer{NumMaxRetries: 100} r := request.Request{} for i := 0; i < 100; i++ { rTemp := r rTemp.HTTPResponse = &http.Response{StatusCode: 500, Header: http.Header{"Retry-After": []string{"299"}}} rTemp.RetryCount = i a := d.RetryRules(&rTemp) if a > 5*time.Minute { t.Errorf("retry delay should never be greater than five minutes, received %s for retrycount %d", a, i) } } for i := 0; i < 100; i++ { rTemp := r rTemp.RetryCount = i rTemp.HTTPResponse = &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{""}}} a := d.RetryRules(&rTemp) if a > 5*time.Minute { t.Errorf("retry delay should not be greater than five minutes, received %s for retrycount %d", a, i) } } rTemp := r rTemp.RetryCount = 1 rTemp.HTTPResponse = &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{"300"}}} a := d.RetryRules(&rTemp) if a < 5*time.Minute { t.Errorf("retry delay should not be less than retry-after duration, received %s for retrycount %d", a, 1) } }
200
session-manager-plugin
aws
Go
package client import ( "bytes" "fmt" "io" "io/ioutil" "net/http/httputil" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" ) const logReqMsg = `DEBUG: Request %s/%s Details: ---[ REQUEST POST-SIGN ]----------------------------- %s -----------------------------------------------------` const logReqErrMsg = `DEBUG ERROR: Request %s/%s: ---[ REQUEST DUMP ERROR ]----------------------------- %s ------------------------------------------------------` type logWriter struct { // Logger is what we will use to log the payload of a response. Logger aws.Logger // buf stores the contents of what has been read buf *bytes.Buffer } func (logger *logWriter) Write(b []byte) (int, error) { return logger.buf.Write(b) } type teeReaderCloser struct { // io.Reader will be a tee reader that is used during logging. // This structure will read from a body and write the contents to a logger. io.Reader // Source is used just to close when we are done reading. Source io.ReadCloser } func (reader *teeReaderCloser) Close() error { return reader.Source.Close() } // LogHTTPRequestHandler is a SDK request handler to log the HTTP request sent // to a service. Will include the HTTP request body if the LogLevel of the // request matches LogDebugWithHTTPBody. var LogHTTPRequestHandler = request.NamedHandler{ Name: "awssdk.client.LogRequest", Fn: logRequest, } func logRequest(r *request.Request) { if !r.Config.LogLevel.AtLeast(aws.LogDebug) { return } logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) bodySeekable := aws.IsReaderSeekable(r.Body) b, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) if err != nil { r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) return } if logBody { if !bodySeekable { r.SetReaderBody(aws.ReadSeekCloser(r.HTTPRequest.Body)) } // Reset the request body because dumpRequest will re-wrap the // r.HTTPRequest's Body as a NoOpCloser and will not be reset after // read by the HTTP client reader. if err := r.Error; err != nil { r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) return } } r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(b))) } // LogHTTPRequestHeaderHandler is a SDK request handler to log the HTTP request sent // to a service. Will only log the HTTP request's headers. The request payload // will not be read. var LogHTTPRequestHeaderHandler = request.NamedHandler{ Name: "awssdk.client.LogRequestHeader", Fn: logRequestHeader, } func logRequestHeader(r *request.Request) { b, err := httputil.DumpRequestOut(r.HTTPRequest, false) if err != nil { r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) return } r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(b))) } const logRespMsg = `DEBUG: Response %s/%s Details: ---[ RESPONSE ]-------------------------------------- %s -----------------------------------------------------` const logRespErrMsg = `DEBUG ERROR: Response %s/%s: ---[ RESPONSE DUMP ERROR ]----------------------------- %s -----------------------------------------------------` // LogHTTPResponseHandler is a SDK request handler to log the HTTP response // received from a service. Will include the HTTP response body if the LogLevel // of the request matches LogDebugWithHTTPBody. var LogHTTPResponseHandler = request.NamedHandler{ Name: "awssdk.client.LogResponse", Fn: logResponse, } func logResponse(r *request.Request) { if !r.Config.LogLevel.AtLeast(aws.LogDebug) { return } lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} if r.HTTPResponse == nil { lw.Logger.Log(fmt.Sprintf(logRespErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, "request's HTTPResponse is nil")) return } logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) if logBody { r.HTTPResponse.Body = &teeReaderCloser{ Reader: io.TeeReader(r.HTTPResponse.Body, lw), Source: r.HTTPResponse.Body, } } handlerFn := func(req *request.Request) { b, err := httputil.DumpResponse(req.HTTPResponse, false) if err != nil { lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) return } lw.Logger.Log(fmt.Sprintf(logRespMsg, req.ClientInfo.ServiceName, req.Operation.Name, string(b))) if logBody { b, err := ioutil.ReadAll(lw.buf) if err != nil { lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) return } lw.Logger.Log(string(b)) } } const handlerName = "awsdk.client.LogResponse.ResponseBody" r.Handlers.Unmarshal.SetBackNamed(request.NamedHandler{ Name: handlerName, Fn: handlerFn, }) r.Handlers.UnmarshalError.SetBackNamed(request.NamedHandler{ Name: handlerName, Fn: handlerFn, }) } // LogHTTPResponseHeaderHandler is a SDK request handler to log the HTTP // response received from a service. Will only log the HTTP response's headers. // The response payload will not be read. var LogHTTPResponseHeaderHandler = request.NamedHandler{ Name: "awssdk.client.LogResponseHeader", Fn: logResponseHeader, } func logResponseHeader(r *request.Request) { if r.Config.Logger == nil { return } b, err := httputil.DumpResponse(r.HTTPResponse, false) if err != nil { r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) return } r.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(b))) }
203
session-manager-plugin
aws
Go
package client import ( "bytes" "fmt" "io" "io/ioutil" "net/http" "reflect" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" ) type mockCloser struct { closed bool } func (closer *mockCloser) Read(b []byte) (int, error) { return 0, io.EOF } func (closer *mockCloser) Close() error { closer.closed = true return nil } func TestTeeReaderCloser(t *testing.T) { expected := "FOO" buf := bytes.NewBuffer([]byte(expected)) lw := bytes.NewBuffer(nil) c := &mockCloser{} closer := teeReaderCloser{ io.TeeReader(buf, lw), c, } b := make([]byte, len(expected)) _, err := closer.Read(b) closer.Close() if expected != lw.String() { t.Errorf("Expected %q, but received %q", expected, lw.String()) } if err != nil { t.Errorf("Expected 'nil', but received %v", err) } if !c.closed { t.Error("Expected 'true', but received 'false'") } } func TestLogWriter(t *testing.T) { expected := "FOO" lw := &logWriter{nil, bytes.NewBuffer(nil)} lw.Write([]byte(expected)) if expected != lw.buf.String() { t.Errorf("Expected %q, but received %q", expected, lw.buf.String()) } } func TestLogRequest(t *testing.T) { cases := []struct { Body io.ReadSeeker ExpectBody []byte LogLevel aws.LogLevelType }{ { Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("body content"))), ExpectBody: []byte("body content"), }, { Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("body content"))), LogLevel: aws.LogDebugWithHTTPBody, ExpectBody: []byte("body content"), }, { Body: bytes.NewReader([]byte("body content")), ExpectBody: []byte("body content"), }, { Body: bytes.NewReader([]byte("body content")), LogLevel: aws.LogDebugWithHTTPBody, ExpectBody: []byte("body content"), }, } for i, c := range cases { logW := bytes.NewBuffer(nil) req := request.New( aws.Config{ Credentials: credentials.AnonymousCredentials, Logger: &bufLogger{w: logW}, LogLevel: aws.LogLevel(c.LogLevel), }, metadata.ClientInfo{ Endpoint: "https://mock-service.mock-region.amazonaws.com", }, testHandlers(), nil, &request.Operation{ Name: "APIName", HTTPMethod: "POST", HTTPPath: "/", }, struct{}{}, nil, ) req.SetReaderBody(c.Body) req.Build() logRequest(req) b, err := ioutil.ReadAll(req.HTTPRequest.Body) if err != nil { t.Fatalf("%d, expect to read SDK request Body", i) } if e, a := c.ExpectBody, b; !reflect.DeepEqual(e, a) { t.Errorf("%d, expect %v body, got %v", i, e, a) } } } func TestLogResponse(t *testing.T) { cases := []struct { Body *bytes.Buffer ExpectBody []byte ReadBody bool LogLevel aws.LogLevelType ExpectLog bool }{ { Body: bytes.NewBuffer([]byte("body content")), ExpectBody: []byte("body content"), }, { Body: bytes.NewBuffer([]byte("body content")), LogLevel: aws.LogDebug, ExpectLog: true, ExpectBody: []byte("body content"), }, { Body: bytes.NewBuffer([]byte("body content")), LogLevel: aws.LogDebugWithHTTPBody, ExpectLog: true, ReadBody: true, ExpectBody: []byte("body content"), }, } for i, c := range cases { var logW bytes.Buffer req := request.New( aws.Config{ Credentials: credentials.AnonymousCredentials, Logger: &bufLogger{w: &logW}, LogLevel: aws.LogLevel(c.LogLevel), }, metadata.ClientInfo{ Endpoint: "https://mock-service.mock-region.amazonaws.com", }, testHandlers(), nil, &request.Operation{ Name: "APIName", HTTPMethod: "POST", HTTPPath: "/", }, struct{}{}, nil, ) req.HTTPResponse = &http.Response{ StatusCode: 200, Status: "OK", Header: http.Header{ "ABC": []string{"123"}, }, Body: ioutil.NopCloser(c.Body), } logResponse(req) req.Handlers.Unmarshal.Run(req) if c.ReadBody { if e, a := len(c.ExpectBody), c.Body.Len(); e != a { t.Errorf("%d, expect original body not to of been read", i) } } if c.ExpectLog && logW.Len() == 0 { t.Errorf("%d, expect HTTP Response headers to be logged", i) } else if !c.ExpectLog && logW.Len() != 0 { t.Errorf("%d, expect no log, got,\n%v", i, logW.String()) } b, err := ioutil.ReadAll(req.HTTPResponse.Body) if err != nil { t.Fatalf("%d, expect to read SDK request Body", i) } if e, a := c.ExpectBody, b; !bytes.Equal(e, a) { t.Errorf("%d, expect %v body, got %v", i, e, a) } } } type bufLogger struct { w *bytes.Buffer } func (l *bufLogger) Log(args ...interface{}) { fmt.Fprintln(l.w, args...) } func testHandlers() request.Handlers { var handlers request.Handlers handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) return handlers }
228
session-manager-plugin
aws
Go
package client import ( "time" "github.com/aws/aws-sdk-go/aws/request" ) // NoOpRetryer provides a retryer that performs no retries. // It should be used when we do not want retries to be performed. type NoOpRetryer struct{} // MaxRetries returns the number of maximum returns the service will use to make // an individual API; For NoOpRetryer the MaxRetries will always be zero. func (d NoOpRetryer) MaxRetries() int { return 0 } // ShouldRetry will always return false for NoOpRetryer, as it should never retry. func (d NoOpRetryer) ShouldRetry(_ *request.Request) bool { return false } // RetryRules returns the delay duration before retrying this request again; // since NoOpRetryer does not retry, RetryRules always returns 0. func (d NoOpRetryer) RetryRules(_ *request.Request) time.Duration { return 0 }
29
session-manager-plugin
aws
Go
package client import ( "net/http" "testing" "time" "github.com/aws/aws-sdk-go/aws/request" ) func TestNoOpRetryer(t *testing.T) { cases := []struct { r request.Request expectMaxRetries int expectRetryDelay time.Duration expectRetry bool }{ { r: request.Request{ HTTPResponse: &http.Response{StatusCode: 200}, }, expectMaxRetries: 0, expectRetryDelay: 0, expectRetry: false, }, } d := NoOpRetryer{} for i, c := range cases { maxRetries := d.MaxRetries() retry := d.ShouldRetry(&c.r) retryDelay := d.RetryRules(&c.r) if e, a := c.expectMaxRetries, maxRetries; e != a { t.Errorf("%d: expected %v, but received %v for number of max retries", i, e, a) } if e, a := c.expectRetry, retry; e != a { t.Errorf("%d: expected %v, but received %v for should retry", i, e, a) } if e, a := c.expectRetryDelay, retryDelay; e != a { t.Errorf("%d: expected %v, but received %v as retry delay", i, e, a) } } }
47
session-manager-plugin
aws
Go
package metadata // ClientInfo wraps immutable data from the client.Client structure. type ClientInfo struct { ServiceName string ServiceID string APIVersion string PartitionID string Endpoint string SigningName string SigningRegion string JSONVersion string TargetPrefix string }
15
session-manager-plugin
aws
Go
package corehandlers import ( "bytes" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strconv" "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/aws/request" ) // Interface for matching types which also have a Len method. type lener interface { Len() int } // BuildContentLengthHandler builds the content length of a request based on the body, // or will use the HTTPRequest.Header's "Content-Length" if defined. If unable // to determine request body length and no "Content-Length" was specified it will panic. // // The Content-Length will only be added to the request if the length of the body // is greater than 0. If the body is empty or the current `Content-Length` // header is <= 0, the header will also be stripped. var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) { var length int64 if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { length, _ = strconv.ParseInt(slength, 10, 64) } else { if r.Body != nil { var err error length, err = aws.SeekerLen(r.Body) if err != nil { r.Error = awserr.New(request.ErrCodeSerialization, "failed to get request body's length", err) return } } } if length > 0 { r.HTTPRequest.ContentLength = length r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) } else { r.HTTPRequest.ContentLength = 0 r.HTTPRequest.Header.Del("Content-Length") } }} var reStatusCode = regexp.MustCompile(`^(\d{3})`) // ValidateReqSigHandler is a request handler to ensure that the request's // signature doesn't expire before it is sent. This can happen when a request // is built and signed significantly before it is sent. Or significant delays // occur when retrying requests that would cause the signature to expire. var ValidateReqSigHandler = request.NamedHandler{ Name: "core.ValidateReqSigHandler", Fn: func(r *request.Request) { // Unsigned requests are not signed if r.Config.Credentials == credentials.AnonymousCredentials { return } signedTime := r.Time if !r.LastSignedAt.IsZero() { signedTime = r.LastSignedAt } // 5 minutes to allow for some clock skew/delays in transmission. // Would be improved with aws/aws-sdk-go#423 if signedTime.Add(5 * time.Minute).After(time.Now()) { return } fmt.Println("request expired, resigning") r.Sign() }, } // SendHandler is a request handler to send service request using HTTP client. var SendHandler = request.NamedHandler{ Name: "core.SendHandler", Fn: func(r *request.Request) { sender := sendFollowRedirects if r.DisableFollowRedirects { sender = sendWithoutFollowRedirects } if request.NoBody == r.HTTPRequest.Body { // Strip off the request body if the NoBody reader was used as a // place holder for a request body. This prevents the SDK from // making requests with a request body when it would be invalid // to do so. // // Use a shallow copy of the http.Request to ensure the race condition // of transport on Body will not trigger reqOrig, reqCopy := r.HTTPRequest, *r.HTTPRequest reqCopy.Body = nil r.HTTPRequest = &reqCopy defer func() { r.HTTPRequest = reqOrig }() } var err error r.HTTPResponse, err = sender(r) if err != nil { handleSendError(r, err) } }, } func sendFollowRedirects(r *request.Request) (*http.Response, error) { return r.Config.HTTPClient.Do(r.HTTPRequest) } func sendWithoutFollowRedirects(r *request.Request) (*http.Response, error) { transport := r.Config.HTTPClient.Transport if transport == nil { transport = http.DefaultTransport } return transport.RoundTrip(r.HTTPRequest) } func handleSendError(r *request.Request, err error) { // Prevent leaking if an HTTPResponse was returned. Clean up // the body. if r.HTTPResponse != nil { r.HTTPResponse.Body.Close() } // Capture the case where url.Error is returned for error processing // response. e.g. 301 without location header comes back as string // error and r.HTTPResponse is nil. Other URL redirect errors will // comeback in a similar method. if e, ok := err.(*url.Error); ok && e.Err != nil { if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { code, _ := strconv.ParseInt(s[1], 10, 64) r.HTTPResponse = &http.Response{ StatusCode: int(code), Status: http.StatusText(int(code)), Body: ioutil.NopCloser(bytes.NewReader([]byte{})), } return } } if r.HTTPResponse == nil { // Add a dummy request response object to ensure the HTTPResponse // value is consistent. r.HTTPResponse = &http.Response{ StatusCode: int(0), Status: http.StatusText(int(0)), Body: ioutil.NopCloser(bytes.NewReader([]byte{})), } } // Catch all request errors, and let the default retrier determine // if the error is retryable. r.Error = awserr.New(request.ErrCodeRequestError, "send request failed", err) // Override the error with a context canceled error, if that was canceled. ctx := r.Context() select { case <-ctx.Done(): r.Error = awserr.New(request.CanceledErrorCode, "request context canceled", ctx.Err()) r.Retryable = aws.Bool(false) default: } } // ValidateResponseHandler is a request handler to validate service response. var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) { if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { // this may be replaced by an UnmarshalError handler r.Error = awserr.New("UnknownError", "unknown error", r.Error) } }} // AfterRetryHandler performs final checks to determine if the request should // be retried and how long to delay. var AfterRetryHandler = request.NamedHandler{ Name: "core.AfterRetryHandler", Fn: func(r *request.Request) { // If one of the other handlers already set the retry state // we don't want to override it based on the service's state if r.Retryable == nil || aws.BoolValue(r.Config.EnforceShouldRetryCheck) { r.Retryable = aws.Bool(r.ShouldRetry(r)) } if r.WillRetry() { r.RetryDelay = r.RetryRules(r) if sleepFn := r.Config.SleepDelay; sleepFn != nil { // Support SleepDelay for backwards compatibility and testing sleepFn(r.RetryDelay) } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { r.Error = awserr.New(request.CanceledErrorCode, "request context canceled", err) r.Retryable = aws.Bool(false) return } // when the expired token exception occurs the credentials // need to be expired locally so that the next request to // get credentials will trigger a credentials refresh. if r.IsErrorExpired() { r.Config.Credentials.Expire() } r.RetryCount++ r.Error = nil } }} // ValidateEndpointHandler is a request handler to validate a request had the // appropriate Region and Endpoint set. Will set r.Error if the endpoint or // region is not valid. var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointHandler", Fn: func(r *request.Request) { if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { r.Error = aws.ErrMissingRegion } else if r.ClientInfo.Endpoint == "" { // Was any endpoint provided by the user, or one was derived by the // SDK's endpoint resolver? r.Error = aws.ErrMissingEndpoint } }}
233
session-manager-plugin
aws
Go
// +build go1.10 package corehandlers_test import ( "bytes" "io" "net/http" "net/http/httptest" "testing" "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/unit" "github.com/aws/aws-sdk-go/service/s3" ) func TestSendHandler_HEADNoBody(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() if e, a := "HEAD", r.Method; e != a { t.Errorf("expected %v method, got %v", e, a) } var buf bytes.Buffer io.Copy(&buf, r.Body) if n := buf.Len(); n != 0 { t.Errorf("expect empty body, got %d", n) } w.WriteHeader(http.StatusOK) })) defer server.Close() svc := s3.New(unit.Session, &aws.Config{ Endpoint: aws.String(server.URL), Credentials: credentials.AnonymousCredentials, S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true), }) req, _ := svc.HeadObjectRequest(&s3.HeadObjectInput{ Bucket: aws.String("bucketname"), Key: aws.String("keyname"), }) if e, a := request.NoBody, req.HTTPRequest.Body; e != a { t.Fatalf("expect %T request body, got %T", e, a) } if err := req.Send(); err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := http.StatusOK, req.HTTPResponse.StatusCode; e != a { t.Errorf("expect %d status code, got %d", e, a) } }
59
session-manager-plugin
aws
Go
package corehandlers_test import ( "bytes" "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "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/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/awstesting" "github.com/aws/aws-sdk-go/awstesting/unit" "github.com/aws/aws-sdk-go/internal/sdktesting" "github.com/aws/aws-sdk-go/service/s3" ) func TestValidateEndpointHandler(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() svc := awstesting.NewClient(aws.NewConfig().WithRegion("us-west-2")) svc.Handlers.Clear() svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) err := req.Build() if err != nil { t.Errorf("expect no error, got %v", err) } } func TestValidateEndpointHandlerErrorRegion(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() svc := awstesting.NewClient() svc.Handlers.Clear() svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) err := req.Build() if err == nil { t.Errorf("expect error, got none") } if e, a := aws.ErrMissingRegion, err; e != a { t.Errorf("expect %v to be %v", e, a) } } type mockCredsProvider struct { expired bool retrieveCalled bool } func (m *mockCredsProvider) Retrieve() (credentials.Value, error) { m.retrieveCalled = true return credentials.Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", ProviderName: "mockCredsProvider", }, nil } func (m *mockCredsProvider) IsExpired() bool { return m.expired } func TestAfterRetryRefreshCreds(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() credProvider := &mockCredsProvider{} sess := unit.Session.Copy(&aws.Config{ Credentials: credentials.NewCredentials(credProvider), MaxRetries: aws.Int(2), }) clientInfo := metadata.ClientInfo{ Endpoint: "http://endpoint", SigningName: "", } svc := client.New(*sess.Config, clientInfo, sess.Handlers) svc.Handlers.Sign.PushBack(func(r *request.Request) { if !svc.Config.Credentials.IsExpired() { t.Errorf("expect credentials of of been expired before request attempt") } _, err := svc.Config.Credentials.Get() r.Error = err }) var respID int resps := []struct { Resp *http.Response Err error }{ { Resp: &http.Response{ StatusCode: 403, Header: http.Header{}, Body: ioutil.NopCloser(bytes.NewBuffer([]byte{})), }, Err: awserr.New("ExpiredToken", "", nil), }, { Resp: &http.Response{ StatusCode: 403, Header: http.Header{}, Body: ioutil.NopCloser(bytes.NewBuffer([]byte{})), }, Err: awserr.New("ExpiredToken", "", nil), }, { Resp: &http.Response{ StatusCode: 200, Header: http.Header{}, Body: ioutil.NopCloser(bytes.NewBuffer([]byte{})), }, }, } svc.Handlers.Send.Clear() svc.Handlers.Send.PushBack(func(r *request.Request) { r.HTTPResponse = resps[respID].Resp }) svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) { r.Error = resps[respID].Err }) svc.Handlers.CompleteAttempt.PushBack(func(r *request.Request) { respID++ }) if !svc.Config.Credentials.IsExpired() { t.Fatalf("expect to start out expired") } if credProvider.retrieveCalled { t.Fatalf("expect retrieve not yet called") } req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) if err := req.Send(); err != nil { t.Fatalf("expect no error, got %v", err) } if e, a := len(resps)-1, req.RetryCount; e != a { t.Errorf("expect %v retries, got %v", e, a) } if svc.Config.Credentials.IsExpired() { t.Errorf("expect credentials not to be expired") } if !credProvider.retrieveCalled { t.Errorf("expect retrieve to be called") } } func TestAfterRetryWithContextCanceled(t *testing.T) { c := awstesting.NewClient() req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} req.SetContext(ctx) req.Error = fmt.Errorf("some error") req.Retryable = aws.Bool(true) req.HTTPResponse = &http.Response{ StatusCode: 500, } close(ctx.DoneCh) ctx.Error = fmt.Errorf("context canceled") corehandlers.AfterRetryHandler.Fn(req) if req.Error == nil { t.Fatalf("expect error but didn't receive one") } aerr := req.Error.(awserr.Error) if e, a := request.CanceledErrorCode, aerr.Code(); e != a { t.Errorf("expect %q, error code got %q", e, a) } } func TestAfterRetryWithContext(t *testing.T) { c := awstesting.NewClient() req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} req.SetContext(ctx) req.Error = fmt.Errorf("some error") req.Retryable = aws.Bool(true) req.HTTPResponse = &http.Response{ StatusCode: 500, } corehandlers.AfterRetryHandler.Fn(req) if req.Error != nil { t.Fatalf("expect no error, got %v", req.Error) } if e, a := 1, req.RetryCount; e != a { t.Errorf("expect retry count to be %d, got %d", e, a) } } func TestSendWithContextCanceled(t *testing.T) { c := awstesting.NewClient(&aws.Config{ SleepDelay: func(dur time.Duration) { t.Errorf("SleepDelay should not be called") }, }) req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} req.SetContext(ctx) req.Error = fmt.Errorf("some error") req.Retryable = aws.Bool(true) req.HTTPResponse = &http.Response{ StatusCode: 500, } close(ctx.DoneCh) ctx.Error = fmt.Errorf("context canceled") corehandlers.SendHandler.Fn(req) if req.Error == nil { t.Fatalf("expect error but didn't receive one") } aerr := req.Error.(awserr.Error) if e, a := request.CanceledErrorCode, aerr.Code(); e != a { t.Errorf("expect %q, error code got %q", e, a) } } type testSendHandlerTransport struct{} func (t *testSendHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) { return nil, fmt.Errorf("mock error") } func TestSendHandlerError(t *testing.T) { svc := awstesting.NewClient(&aws.Config{ HTTPClient: &http.Client{ Transport: &testSendHandlerTransport{}, }, }) svc.Handlers.Clear() svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) r.Send() if r.Error == nil { t.Errorf("expect error, got none") } if r.HTTPResponse == nil { t.Errorf("expect response, got none") } } func TestSendWithoutFollowRedirects(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/original": w.Header().Set("Location", "/redirected") w.WriteHeader(301) case "/redirected": t.Fatalf("expect not to redirect, but was") } })) defer server.Close() svc := awstesting.NewClient(&aws.Config{ DisableSSL: aws.Bool(true), Endpoint: aws.String(server.URL), }) svc.Handlers.Clear() svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) r := svc.NewRequest(&request.Operation{ Name: "Operation", HTTPPath: "/original", }, nil, nil) r.DisableFollowRedirects = true err := r.Send() if err != nil { t.Errorf("expect no error, got %v", err) } if e, a := 301, r.HTTPResponse.StatusCode; e != a { t.Errorf("expect %d status code, got %d", e, a) } } func TestValidateReqSigHandler(t *testing.T) { cases := []struct { Req *request.Request Resign bool }{ { Req: &request.Request{ Config: aws.Config{Credentials: credentials.AnonymousCredentials}, Time: time.Now().Add(-15 * time.Minute), }, Resign: false, }, { Req: &request.Request{ Time: time.Now().Add(-15 * time.Minute), }, Resign: true, }, { Req: &request.Request{ Time: time.Now().Add(-1 * time.Minute), }, Resign: false, }, } for i, c := range cases { c.Req.HTTPRequest = &http.Request{URL: &url.URL{}} resigned := false c.Req.Handlers.Sign.PushBack(func(r *request.Request) { resigned = true }) corehandlers.ValidateReqSigHandler.Fn(c.Req) if c.Req.Error != nil { t.Errorf("expect no error, got %v", c.Req.Error) } if e, a := c.Resign, resigned; e != a { t.Errorf("%d, expect %v to be %v", i, e, a) } } } func setupContentLengthTestServer(t *testing.T, hasContentLength bool, contentLength int64) *httptest.Server { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, ok := r.Header["Content-Length"] if e, a := hasContentLength, ok; e != a { t.Errorf("expect %v to be %v", e, a) } if hasContentLength { if e, a := contentLength, r.ContentLength; e != a { t.Errorf("expect %v to be %v", e, a) } } b, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("expect no error, got %v", err) } r.Body.Close() authHeader := r.Header.Get("Authorization") if hasContentLength { if e, a := "content-length", authHeader; !strings.Contains(a, e) { t.Errorf("expect %v to be in %v", e, a) } } else { if e, a := "content-length", authHeader; strings.Contains(a, e) { t.Errorf("expect %v to not be in %v", e, a) } } if e, a := contentLength, int64(len(b)); e != a { t.Errorf("expect %v to be %v", e, a) } })) return server } func TestBuildContentLength_ZeroBody(t *testing.T) { server := setupContentLengthTestServer(t, false, 0) defer server.Close() svc := s3.New(unit.Session, &aws.Config{ Endpoint: aws.String(server.URL), S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true), }) _, err := svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String("bucketname"), Key: aws.String("keyname"), }) if err != nil { t.Errorf("expect no error, got %v", err) } } func TestBuildContentLength_NegativeBody(t *testing.T) { server := setupContentLengthTestServer(t, false, 0) defer server.Close() svc := s3.New(unit.Session, &aws.Config{ Endpoint: aws.String(server.URL), S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true), }) req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ Bucket: aws.String("bucketname"), Key: aws.String("keyname"), }) req.HTTPRequest.Header.Set("Content-Length", "-1") if req.Error != nil { t.Errorf("expect no error, got %v", req.Error) } } func TestBuildContentLength_WithBody(t *testing.T) { server := setupContentLengthTestServer(t, true, 1024) defer server.Close() svc := s3.New(unit.Session, &aws.Config{ Endpoint: aws.String(server.URL), S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true), }) _, err := svc.PutObject(&s3.PutObjectInput{ Bucket: aws.String("bucketname"), Key: aws.String("keyname"), Body: bytes.NewReader(make([]byte, 1024)), }) if err != nil { t.Errorf("expect no error, got %v", err) } }
453
session-manager-plugin
aws
Go
package corehandlers import "github.com/aws/aws-sdk-go/aws/request" // ValidateParametersHandler is a request handler to validate the input parameters. // Validating parameters only has meaning if done prior to the request being sent. var ValidateParametersHandler = request.NamedHandler{Name: "core.ValidateParametersHandler", Fn: func(r *request.Request) { if !r.ParamsFilled() { return } if v, ok := r.Params.(request.Validator); ok { if err := v.Validate(); err != nil { r.Error = err } } }}
18
session-manager-plugin
aws
Go
package corehandlers_test import ( "fmt" "reflect" "testing" "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/client/metadata" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/awstesting/unit" "github.com/aws/aws-sdk-go/service/kinesis" ) var testSvc = func() *client.Client { s := &client.Client{ Config: aws.Config{}, ClientInfo: metadata.ClientInfo{ ServiceName: "mock-service", APIVersion: "2015-01-01", }, } return s }() type StructShape struct { _ struct{} `type:"structure"` RequiredList []*ConditionalStructShape `required:"true"` RequiredMap map[string]*ConditionalStructShape `required:"true"` RequiredBool *bool `required:"true"` OptionalStruct *ConditionalStructShape hiddenParameter *string } func (s *StructShape) Validate() error { invalidParams := request.ErrInvalidParams{Context: "StructShape"} if s.RequiredList == nil { invalidParams.Add(request.NewErrParamRequired("RequiredList")) } if s.RequiredMap == nil { invalidParams.Add(request.NewErrParamRequired("RequiredMap")) } if s.RequiredBool == nil { invalidParams.Add(request.NewErrParamRequired("RequiredBool")) } if s.RequiredList != nil { for i, v := range s.RequiredList { if v == nil { continue } if err := v.Validate(); err != nil { invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RequiredList", i), err.(request.ErrInvalidParams)) } } } if s.RequiredMap != nil { for i, v := range s.RequiredMap { if v == nil { continue } if err := v.Validate(); err != nil { invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RequiredMap", i), err.(request.ErrInvalidParams)) } } } if s.OptionalStruct != nil { if err := s.OptionalStruct.Validate(); err != nil { invalidParams.AddNested("OptionalStruct", err.(request.ErrInvalidParams)) } } if invalidParams.Len() > 0 { return invalidParams } return nil } type ConditionalStructShape struct { _ struct{} `type:"structure"` Name *string `required:"true"` } func (s *ConditionalStructShape) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ConditionalStructShape"} if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } if invalidParams.Len() > 0 { return invalidParams } return nil } func TestNoErrors(t *testing.T) { input := &StructShape{ RequiredList: []*ConditionalStructShape{}, RequiredMap: map[string]*ConditionalStructShape{ "key1": {Name: aws.String("Name")}, "key2": {Name: aws.String("Name")}, }, RequiredBool: aws.Bool(true), OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")}, } req := testSvc.NewRequest(&request.Operation{}, input, nil) corehandlers.ValidateParametersHandler.Fn(req) if req.Error != nil { t.Fatalf("expect no error, got %v", req.Error) } } func TestMissingRequiredParameters(t *testing.T) { input := &StructShape{} req := testSvc.NewRequest(&request.Operation{}, input, nil) corehandlers.ValidateParametersHandler.Fn(req) if req.Error == nil { t.Fatalf("expect error") } if e, a := "InvalidParameter", req.Error.(awserr.Error).Code(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "3 validation error(s) found.", req.Error.(awserr.Error).Message(); e != a { t.Errorf("expect %v, got %v", e, a) } errs := req.Error.(awserr.BatchedErrors).OrigErrs() if e, a := 3, len(errs); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "ParamRequiredError: missing required field, StructShape.RequiredList.", errs[0].Error(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "ParamRequiredError: missing required field, StructShape.RequiredMap.", errs[1].Error(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "ParamRequiredError: missing required field, StructShape.RequiredBool.", errs[2].Error(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "InvalidParameter: 3 validation error(s) found.\n- missing required field, StructShape.RequiredList.\n- missing required field, StructShape.RequiredMap.\n- missing required field, StructShape.RequiredBool.\n", req.Error.Error(); e != a { t.Errorf("expect %v, got %v", e, a) } } func TestNestedMissingRequiredParameters(t *testing.T) { input := &StructShape{ RequiredList: []*ConditionalStructShape{{}}, RequiredMap: map[string]*ConditionalStructShape{ "key1": {Name: aws.String("Name")}, "key2": {}, }, RequiredBool: aws.Bool(true), OptionalStruct: &ConditionalStructShape{}, } req := testSvc.NewRequest(&request.Operation{}, input, nil) corehandlers.ValidateParametersHandler.Fn(req) if req.Error == nil { t.Fatalf("expect error") } if e, a := "InvalidParameter", req.Error.(awserr.Error).Code(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "3 validation error(s) found.", req.Error.(awserr.Error).Message(); e != a { t.Errorf("expect %v, got %v", e, a) } errs := req.Error.(awserr.BatchedErrors).OrigErrs() if e, a := 3, len(errs); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "ParamRequiredError: missing required field, StructShape.RequiredList[0].Name.", errs[0].Error(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "ParamRequiredError: missing required field, StructShape.RequiredMap[key2].Name.", errs[1].Error(); e != a { t.Errorf("expect %v, got %v", e, a) } if e, a := "ParamRequiredError: missing required field, StructShape.OptionalStruct.Name.", errs[2].Error(); e != a { t.Errorf("expect %v, got %v", e, a) } } type testInput struct { StringField *string `min:"5"` ListField []string `min:"3"` MapField map[string]string `min:"4"` } func (s testInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "testInput"} if s.StringField != nil && len(*s.StringField) < 5 { invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) } if s.ListField != nil && len(s.ListField) < 3 { invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) } if s.MapField != nil && len(s.MapField) < 4 { invalidParams.Add(request.NewErrParamMinLen("MapField", 4)) } if invalidParams.Len() > 0 { return invalidParams } return nil } var testsFieldMin = []struct { err awserr.Error in testInput }{ { err: func() awserr.Error { invalidParams := request.ErrInvalidParams{Context: "testInput"} invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) return invalidParams }(), in: testInput{StringField: aws.String("abcd")}, }, { err: func() awserr.Error { invalidParams := request.ErrInvalidParams{Context: "testInput"} invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) return invalidParams }(), in: testInput{StringField: aws.String("abcd"), ListField: []string{"a", "b"}}, }, { err: func() awserr.Error { invalidParams := request.ErrInvalidParams{Context: "testInput"} invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) invalidParams.Add(request.NewErrParamMinLen("MapField", 4)) return invalidParams }(), in: testInput{StringField: aws.String("abcd"), ListField: []string{"a", "b"}, MapField: map[string]string{"a": "a", "b": "b"}}, }, { err: nil, in: testInput{StringField: aws.String("abcde"), ListField: []string{"a", "b", "c"}, MapField: map[string]string{"a": "a", "b": "b", "c": "c", "d": "d"}}, }, } func TestValidateFieldMinParameter(t *testing.T) { for i, c := range testsFieldMin { req := testSvc.NewRequest(&request.Operation{}, &c.in, nil) corehandlers.ValidateParametersHandler.Fn(req) if e, a := c.err, req.Error; !reflect.DeepEqual(e, a) { t.Errorf("%d, expect %v, got %v", i, e, a) } } } func BenchmarkValidateAny(b *testing.B) { input := &kinesis.PutRecordsInput{ StreamName: aws.String("stream"), } for i := 0; i < 100; i++ { record := &kinesis.PutRecordsRequestEntry{ Data: make([]byte, 10000), PartitionKey: aws.String("partition"), } input.Records = append(input.Records, record) } req, _ := kinesis.New(unit.Session).PutRecordsRequest(input) b.ResetTimer() for i := 0; i < b.N; i++ { corehandlers.ValidateParametersHandler.Fn(req) if err := req.Error; err != nil { b.Fatalf("validation failed: %v", err) } } }
287
session-manager-plugin
aws
Go
package corehandlers import ( "os" "runtime" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" ) // SDKVersionUserAgentHandler is a request handler for adding the SDK Version // to the user agent. var SDKVersionUserAgentHandler = request.NamedHandler{ Name: "core.SDKVersionUserAgentHandler", Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH), } const execEnvVar = `AWS_EXECUTION_ENV` const execEnvUAKey = `exec-env` // AddHostExecEnvUserAgentHander is a request handler appending the SDK's // execution environment to the user agent. // // If the environment variable AWS_EXECUTION_ENV is set, its value will be // appended to the user agent string. var AddHostExecEnvUserAgentHander = request.NamedHandler{ Name: "core.AddHostExecEnvUserAgentHander", Fn: func(r *request.Request) { v := os.Getenv(execEnvVar) if len(v) == 0 { return } request.AddToUserAgent(r, execEnvUAKey+"/"+v) }, }
38
session-manager-plugin
aws
Go
package corehandlers import ( "net/http" "os" "testing" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/sdktesting" ) func TestAddHostExecEnvUserAgentHander(t *testing.T) { cases := []struct { ExecEnv string Expect string }{ {ExecEnv: "Lambda", Expect: execEnvUAKey + "/Lambda"}, {ExecEnv: "", Expect: ""}, {ExecEnv: "someThingCool", Expect: execEnvUAKey + "/someThingCool"}, } for i, c := range cases { sdktesting.StashEnv() os.Setenv(execEnvVar, c.ExecEnv) req := &request.Request{ HTTPRequest: &http.Request{ Header: http.Header{}, }, } AddHostExecEnvUserAgentHander.Fn(req) if err := req.Error; err != nil { t.Fatalf("%d, expect no error, got %v", i, err) } if e, a := c.Expect, req.HTTPRequest.Header.Get("User-Agent"); e != a { t.Errorf("%d, expect %v user agent, got %v", i, e, a) } } }
42
session-manager-plugin
aws
Go
package credentials import ( "github.com/aws/aws-sdk-go/aws/awserr" ) var ( // ErrNoValidProvidersFoundInChain Is returned when there are no valid // providers in the ChainProvider. // // This has been deprecated. For verbose error messaging set // aws.Config.CredentialsChainVerboseErrors to true. ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", `no valid providers in chain. Deprecated. For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, nil) ) // A ChainProvider will search for a provider which returns credentials // and cache that provider until Retrieve is called again. // // The ChainProvider provides a way of chaining multiple providers together // which will pick the first available using priority order of the Providers // in the list. // // If none of the Providers retrieve valid credentials Value, ChainProvider's // Retrieve() will return the error ErrNoValidProvidersFoundInChain. // // If a Provider is found which returns valid credentials Value ChainProvider // will cache that Provider for all calls to IsExpired(), until Retrieve is // called again. // // Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider. // In this example EnvProvider will first check if any credentials are available // via the environment variables. If there are none ChainProvider will check // the next Provider in the list, EC2RoleProvider in this case. If EC2RoleProvider // does not return any credentials ChainProvider will return the error // ErrNoValidProvidersFoundInChain // // creds := credentials.NewChainCredentials( // []credentials.Provider{ // &credentials.EnvProvider{}, // &ec2rolecreds.EC2RoleProvider{ // Client: ec2metadata.New(sess), // }, // }) // // // Usage of ChainCredentials with aws.Config // svc := ec2.New(session.Must(session.NewSession(&aws.Config{ // Credentials: creds, // }))) // type ChainProvider struct { Providers []Provider curr Provider VerboseErrors bool } // NewChainCredentials returns a pointer to a new Credentials object // wrapping a chain of providers. func NewChainCredentials(providers []Provider) *Credentials { return NewCredentials(&ChainProvider{ Providers: append([]Provider{}, providers...), }) } // Retrieve returns the credentials value or error if no provider returned // without error. // // If a provider is found it will be cached and any calls to IsExpired() // will return the expired state of the cached provider. func (c *ChainProvider) Retrieve() (Value, error) { var errs []error for _, p := range c.Providers { creds, err := p.Retrieve() if err == nil { c.curr = p return creds, nil } errs = append(errs, err) } c.curr = nil var err error err = ErrNoValidProvidersFoundInChain if c.VerboseErrors { err = awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) } return Value{}, err } // IsExpired will returned the expired state of the currently cached provider // if there is one. If there is no current provider, true will be returned. func (c *ChainProvider) IsExpired() bool { if c.curr != nil { return c.curr.IsExpired() } return true }
101
session-manager-plugin
aws
Go
package credentials import ( "reflect" "testing" "github.com/aws/aws-sdk-go/aws/awserr" ) type secondStubProvider struct { creds Value expired bool err error } func (s *secondStubProvider) Retrieve() (Value, error) { s.expired = false s.creds.ProviderName = "secondStubProvider" return s.creds, s.err } func (s *secondStubProvider) IsExpired() bool { return s.expired } func TestChainProviderWithNames(t *testing.T) { p := &ChainProvider{ Providers: []Provider{ &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, &secondStubProvider{ creds: Value{ AccessKeyID: "AKIF", SecretAccessKey: "NOSECRET", SessionToken: "", }, }, &stubProvider{ creds: Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "", }, }, }, } creds, err := p.Retrieve() if err != nil { t.Errorf("Expect no error, got %v", err) } if e, a := "secondStubProvider", creds.ProviderName; e != a { t.Errorf("Expect provider name to match, %v got, %v", e, a) } // Also check credentials if e, a := "AKIF", creds.AccessKeyID; e != a { t.Errorf("Expect access key ID to match, %v got %v", e, a) } if e, a := "NOSECRET", creds.SecretAccessKey; e != a { t.Errorf("Expect secret access key to match, %v got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("Expect session token to be empty, %v", v) } } func TestChainProviderGet(t *testing.T) { p := &ChainProvider{ Providers: []Provider{ &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, &stubProvider{ creds: Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "", }, }, }, } creds, err := p.Retrieve() if err != nil { t.Errorf("Expect no error, got %v", err) } if e, a := "AKID", creds.AccessKeyID; e != a { t.Errorf("Expect access key ID to match, %v got %v", e, a) } if e, a := "SECRET", creds.SecretAccessKey; e != a { t.Errorf("Expect secret access key to match, %v got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("Expect session token to be empty, %v", v) } } func TestChainProviderIsExpired(t *testing.T) { stubProvider := &stubProvider{expired: true} p := &ChainProvider{ Providers: []Provider{ stubProvider, }, } if !p.IsExpired() { t.Errorf("Expect expired to be true before any Retrieve") } _, err := p.Retrieve() if err != nil { t.Errorf("Expect no error, got %v", err) } if p.IsExpired() { t.Errorf("Expect not expired after retrieve") } stubProvider.expired = true if !p.IsExpired() { t.Errorf("Expect return of expired provider") } _, err = p.Retrieve() if err != nil { t.Errorf("Expect no error, got %v", err) } if p.IsExpired() { t.Errorf("Expect not expired after retrieve") } } func TestChainProviderWithNoProvider(t *testing.T) { p := &ChainProvider{ Providers: []Provider{}, } if !p.IsExpired() { t.Errorf("Expect expired with no providers") } _, err := p.Retrieve() if e, a := ErrNoValidProvidersFoundInChain, err; e != a { t.Errorf("Expect no providers error returned, %v, got %v", e, a) } } func TestChainProviderWithNoValidProvider(t *testing.T) { errs := []error{ awserr.New("FirstError", "first provider error", nil), awserr.New("SecondError", "second provider error", nil), } p := &ChainProvider{ Providers: []Provider{ &stubProvider{err: errs[0]}, &stubProvider{err: errs[1]}, }, } if !p.IsExpired() { t.Errorf("Expect expired with no providers") } _, err := p.Retrieve() if e, a := ErrNoValidProvidersFoundInChain, err; e != a { t.Errorf("Expect no providers error returned, %v, got %v", e, a) } } func TestChainProviderWithNoValidProviderWithVerboseEnabled(t *testing.T) { errs := []error{ awserr.New("FirstError", "first provider error", nil), awserr.New("SecondError", "second provider error", nil), } p := &ChainProvider{ VerboseErrors: true, Providers: []Provider{ &stubProvider{err: errs[0]}, &stubProvider{err: errs[1]}, }, } if !p.IsExpired() { t.Errorf("Expect expired with no providers") } _, err := p.Retrieve() expectErr := awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) if e, a := expectErr, err; !reflect.DeepEqual(e, a) { t.Errorf("Expect no providers error returned, %v, got %v", e, a) } }
190
session-manager-plugin
aws
Go
// +build !go1.7 package credentials import ( "github.com/aws/aws-sdk-go/internal/context" ) // backgroundContext returns a context that will never be canceled, has no // values, and no deadline. This context is used by the SDK to provide // backwards compatibility with non-context API operations and functionality. // // Go 1.6 and before: // This context function is equivalent to context.Background in the Go stdlib. // // Go 1.7 and later: // The context returned will be the value returned by context.Background() // // See https://golang.org/pkg/context for more information on Contexts. func backgroundContext() Context { return context.BackgroundCtx }
23
session-manager-plugin
aws
Go
// +build go1.7 package credentials import "context" // backgroundContext returns a context that will never be canceled, has no // values, and no deadline. This context is used by the SDK to provide // backwards compatibility with non-context API operations and functionality. // // Go 1.6 and before: // This context function is equivalent to context.Background in the Go stdlib. // // Go 1.7 and later: // The context returned will be the value returned by context.Background() // // See https://golang.org/pkg/context for more information on Contexts. func backgroundContext() Context { return context.Background() }
21
session-manager-plugin
aws
Go
// +build !go1.9 package credentials import "time" // Context is an copy of the Go v1.7 stdlib's context.Context interface. // It is represented as a SDK interface to enable you to use the "WithContext" // API methods with Go v1.6 and a Context type such as golang.org/x/net/context. // // This type, aws.Context, and context.Context are equivalent. // // See https://golang.org/pkg/context on how to use contexts. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. Done() <-chan struct{} // Err returns a non-nil error value after Done is closed. Err returns // Canceled if the context was canceled or DeadlineExceeded if the // context's deadline passed. No other values for Err are defined. // After Done is closed, successive calls to Err return the same value. Err() error // Value returns the value associated with this context for key, or nil // if no value is associated with key. Successive calls to Value with // the same key returns the same result. // // Use context values only for request-scoped data that transits // processes and API boundaries, not for passing optional parameters to // functions. Value(key interface{}) interface{} }
40
session-manager-plugin
aws
Go
// +build go1.9 package credentials import "context" // Context is an alias of the Go stdlib's context.Context interface. // It can be used within the SDK's API operation "WithContext" methods. // // This type, aws.Context, and context.Context are equivalent. // // See https://golang.org/pkg/context on how to use contexts. type Context = context.Context
14
session-manager-plugin
aws
Go
// Package credentials provides credential retrieval and management // // The Credentials is the primary method of getting access to and managing // credentials Values. Using dependency injection retrieval of the credential // values is handled by a object which satisfies the Provider interface. // // By default the Credentials.Get() will cache the successful result of a // Provider's Retrieve() until Provider.IsExpired() returns true. At which // point Credentials will call Provider's Retrieve() to get new credential Value. // // The Provider is responsible for determining when credentials Value have expired. // It is also important to note that Credentials will always call Retrieve the // first time Credentials.Get() is called. // // Example of using the environment variable credentials. // // creds := credentials.NewEnvCredentials() // // // Retrieve the credentials value // credValue, err := creds.Get() // if err != nil { // // handle error // } // // Example of forcing credentials to expire and be refreshed on the next Get(). // This may be helpful to proactively expire credentials and refresh them sooner // than they would naturally expire on their own. // // creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{}) // creds.Expire() // credsValue, err := creds.Get() // // New credentials will be retrieved instead of from cache. // // // Custom Provider // // Each Provider built into this package also provides a helper method to generate // a Credentials pointer setup with the provider. To use a custom Provider just // create a type which satisfies the Provider interface and pass it to the // NewCredentials method. // // type MyProvider struct{} // func (m *MyProvider) Retrieve() (Value, error) {...} // func (m *MyProvider) IsExpired() bool {...} // // creds := credentials.NewCredentials(&MyProvider{}) // credValue, err := creds.Get() // package credentials import ( "fmt" "sync" "time" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/internal/sync/singleflight" ) // AnonymousCredentials is an empty Credential object that can be used as // dummy placeholder credentials for requests that do not need signed. // // This Credentials can be used to configure a service to not sign requests // when making service API calls. For example, when accessing public // s3 buckets. // // svc := s3.New(session.Must(session.NewSession(&aws.Config{ // Credentials: credentials.AnonymousCredentials, // }))) // // Access public S3 buckets. var AnonymousCredentials = NewStaticCredentials("", "", "") // A Value is the AWS credentials value for individual credential fields. type Value struct { // AWS Access key ID AccessKeyID string // AWS Secret Access Key SecretAccessKey string // AWS Session Token SessionToken string // Provider used to get credentials ProviderName string } // HasKeys returns if the credentials Value has both AccessKeyID and // SecretAccessKey value set. func (v Value) HasKeys() bool { return len(v.AccessKeyID) != 0 && len(v.SecretAccessKey) != 0 } // A Provider is the interface for any component which will provide credentials // Value. A provider is required to manage its own Expired state, and what to // be expired means. // // The Provider should not need to implement its own mutexes, because // that will be managed by Credentials. type Provider interface { // Retrieve returns nil if it successfully retrieved the value. // Error is returned if the value were not obtainable, or empty. Retrieve() (Value, error) // IsExpired returns if the credentials are no longer valid, and need // to be retrieved. IsExpired() bool } // ProviderWithContext is a Provider that can retrieve credentials with a Context type ProviderWithContext interface { Provider RetrieveWithContext(Context) (Value, error) } // An Expirer is an interface that Providers can implement to expose the expiration // time, if known. If the Provider cannot accurately provide this info, // it should not implement this interface. type Expirer interface { // The time at which the credentials are no longer valid ExpiresAt() time.Time } // An ErrorProvider is a stub credentials provider that always returns an error // this is used by the SDK when construction a known provider is not possible // due to an error. type ErrorProvider struct { // The error to be returned from Retrieve Err error // The provider name to set on the Retrieved returned Value ProviderName string } // Retrieve will always return the error that the ErrorProvider was created with. func (p ErrorProvider) Retrieve() (Value, error) { return Value{ProviderName: p.ProviderName}, p.Err } // IsExpired will always return not expired. func (p ErrorProvider) IsExpired() bool { return false } // A Expiry provides shared expiration logic to be used by credentials // providers to implement expiry functionality. // // The best method to use this struct is as an anonymous field within the // provider's struct. // // Example: // type EC2RoleProvider struct { // Expiry // ... // } type Expiry struct { // The date/time when to expire on expiration time.Time // If set will be used by IsExpired to determine the current time. // Defaults to time.Now if CurrentTime is not set. Available for testing // to be able to mock out the current time. CurrentTime func() time.Time } // SetExpiration sets the expiration IsExpired will check when called. // // If window is greater than 0 the expiration time will be reduced by the // window value. // // Using a window is helpful to trigger credentials to expire sooner than // the expiration time given to ensure no requests are made with expired // tokens. func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { // Passed in expirations should have the monotonic clock values stripped. // This ensures time comparisons will be based on wall-time. e.expiration = expiration.Round(0) if window > 0 { e.expiration = e.expiration.Add(-window) } } // IsExpired returns if the credentials are expired. func (e *Expiry) IsExpired() bool { curTime := e.CurrentTime if curTime == nil { curTime = time.Now } return e.expiration.Before(curTime()) } // ExpiresAt returns the expiration time of the credential func (e *Expiry) ExpiresAt() time.Time { return e.expiration } // A Credentials provides concurrency safe retrieval of AWS credentials Value. // Credentials will cache the credentials value until they expire. Once the value // expires the next Get will attempt to retrieve valid credentials. // // Credentials is safe to use across multiple goroutines and will manage the // synchronous state so the Providers do not need to implement their own // synchronization. // // The first Credentials.Get() will always call Provider.Retrieve() to get the // first instance of the credentials Value. All calls to Get() after that // will return the cached credentials Value until IsExpired() returns true. type Credentials struct { sf singleflight.Group m sync.RWMutex creds Value provider Provider } // NewCredentials returns a pointer to a new Credentials with the provider set. func NewCredentials(provider Provider) *Credentials { c := &Credentials{ provider: provider, } return c } // GetWithContext returns the credentials value, or error if the credentials // Value failed to be retrieved. Will return early if the passed in context is // canceled. // // Will return the cached credentials Value if it has not expired. If the // credentials Value has expired the Provider's Retrieve() will be called // to refresh the credentials. // // If Credentials.Expire() was called the credentials Value will be force // expired, and the next call to Get() will cause them to be refreshed. // // Passed in Context is equivalent to aws.Context, and context.Context. func (c *Credentials) GetWithContext(ctx Context) (Value, error) { // Check if credentials are cached, and not expired. select { case curCreds, ok := <-c.asyncIsExpired(): // ok will only be true, of the credentials were not expired. ok will // be false and have no value if the credentials are expired. if ok { return curCreds, nil } case <-ctx.Done(): return Value{}, awserr.New("RequestCanceled", "request context canceled", ctx.Err()) } // Cannot pass context down to the actual retrieve, because the first // context would cancel the whole group when there is not direct // association of items in the group. resCh := c.sf.DoChan("", func() (interface{}, error) { return c.singleRetrieve(&suppressedContext{ctx}) }) select { case res := <-resCh: return res.Val.(Value), res.Err case <-ctx.Done(): return Value{}, awserr.New("RequestCanceled", "request context canceled", ctx.Err()) } } func (c *Credentials) singleRetrieve(ctx Context) (interface{}, error) { c.m.Lock() defer c.m.Unlock() if curCreds := c.creds; !c.isExpiredLocked(curCreds) { return curCreds, nil } var creds Value var err error if p, ok := c.provider.(ProviderWithContext); ok { creds, err = p.RetrieveWithContext(ctx) } else { creds, err = c.provider.Retrieve() } if err == nil { c.creds = creds } return creds, err } // Get returns the credentials value, or error if the credentials Value failed // to be retrieved. // // Will return the cached credentials Value if it has not expired. If the // credentials Value has expired the Provider's Retrieve() will be called // to refresh the credentials. // // If Credentials.Expire() was called the credentials Value will be force // expired, and the next call to Get() will cause them to be refreshed. func (c *Credentials) Get() (Value, error) { return c.GetWithContext(backgroundContext()) } // Expire expires the credentials and forces them to be retrieved on the // next call to Get(). // // This will override the Provider's expired state, and force Credentials // to call the Provider's Retrieve(). func (c *Credentials) Expire() { c.m.Lock() defer c.m.Unlock() c.creds = Value{} } // IsExpired returns if the credentials are no longer valid, and need // to be retrieved. // // If the Credentials were forced to be expired with Expire() this will // reflect that override. func (c *Credentials) IsExpired() bool { c.m.RLock() defer c.m.RUnlock() return c.isExpiredLocked(c.creds) } // asyncIsExpired returns a channel of credentials Value. If the channel is // closed the credentials are expired and credentials value are not empty. func (c *Credentials) asyncIsExpired() <-chan Value { ch := make(chan Value, 1) go func() { c.m.RLock() defer c.m.RUnlock() if curCreds := c.creds; !c.isExpiredLocked(curCreds) { ch <- curCreds } close(ch) }() return ch } // isExpiredLocked helper method wrapping the definition of expired credentials. func (c *Credentials) isExpiredLocked(creds interface{}) bool { return creds == nil || creds.(Value) == Value{} || c.provider.IsExpired() } // ExpiresAt provides access to the functionality of the Expirer interface of // the underlying Provider, if it supports that interface. Otherwise, it returns // an error. func (c *Credentials) ExpiresAt() (time.Time, error) { c.m.RLock() defer c.m.RUnlock() expirer, ok := c.provider.(Expirer) if !ok { return time.Time{}, awserr.New("ProviderNotExpirer", fmt.Sprintf("provider %s does not support ExpiresAt()", c.creds.ProviderName), nil) } if c.creds == (Value{}) { // set expiration time to the distant past return time.Time{}, nil } return expirer.ExpiresAt(), nil } type suppressedContext struct { Context } func (s *suppressedContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, false } func (s *suppressedContext) Done() <-chan struct{} { return nil } func (s *suppressedContext) Err() error { return nil }
384
session-manager-plugin
aws
Go
// +build go1.9 package credentials import ( "fmt" "strconv" "sync" "testing" "time" ) func BenchmarkCredentials_Get(b *testing.B) { stub := &stubProvider{} cases := []int{1, 10, 100, 500, 1000, 10000} for _, c := range cases { b.Run(strconv.Itoa(c), func(b *testing.B) { creds := NewCredentials(stub) var wg sync.WaitGroup wg.Add(c) for i := 0; i < c; i++ { go func() { for j := 0; j < b.N; j++ { v, err := creds.Get() if err != nil { b.Errorf("expect no error %v, %v", v, err) } } wg.Done() }() } b.ResetTimer() wg.Wait() }) } } func BenchmarkCredentials_Get_Expire(b *testing.B) { p := &blockProvider{} expRates := []int{10000, 1000, 100} cases := []int{1, 10, 100, 500, 1000, 10000} for _, expRate := range expRates { for _, c := range cases { b.Run(fmt.Sprintf("%d-%d", expRate, c), func(b *testing.B) { creds := NewCredentials(p) var wg sync.WaitGroup wg.Add(c) for i := 0; i < c; i++ { go func(id int) { for j := 0; j < b.N; j++ { v, err := creds.Get() if err != nil { b.Errorf("expect no error %v, %v", v, err) } // periodically expire creds to cause rwlock if id == 0 && j%expRate == 0 { creds.Expire() } } wg.Done() }(i) } b.ResetTimer() wg.Wait() }) } } } type blockProvider struct { creds Value expired bool err error } func (s *blockProvider) Retrieve() (Value, error) { s.expired = false s.creds.ProviderName = "blockProvider" time.Sleep(time.Millisecond) return s.creds, s.err } func (s *blockProvider) IsExpired() bool { return s.expired }
91
session-manager-plugin
aws
Go
// +build go1.7 package credentials import ( "context" "testing" ) func TestCredentialsGetWithContext(t *testing.T) { stub := &stubProviderConcurrent{ stubProvider: stubProvider{ creds: Value{ AccessKeyID: "AKIDEXAMPLE", SecretAccessKey: "KEYEXAMPLE", }, }, done: make(chan struct{}), } c := NewCredentials(stub) ctx, cancel1 := context.WithCancel(context.Background()) ctx1 := &ContextWaiter{Context: ctx, waiting: make(chan struct{}, 1)} ctx2 := &ContextWaiter{Context: context.Background(), waiting: make(chan struct{}, 1)} var err1, err2 error var creds1, creds2 Value done1 := make(chan struct{}) go func() { creds1, err1 = c.GetWithContext(ctx1) close(done1) }() <-ctx1.waiting <-ctx1.waiting done2 := make(chan struct{}) go func() { creds2, err2 = c.GetWithContext(ctx2) close(done2) }() <-ctx2.waiting cancel1() <-done1 close(stub.done) <-done2 if err1 == nil { t.Errorf("expect first to have error") } if creds1.HasKeys() { t.Errorf("expect first not to have keys, %v", creds1) } if err2 != nil { t.Errorf("expect second not to have error, %v", err2) } if !creds2.HasKeys() { t.Errorf("expect second to have keys") } } type ContextWaiter struct { context.Context waiting chan struct{} } func (c *ContextWaiter) Done() <-chan struct{} { go func() { c.waiting <- struct{}{} }() return c.Context.Done() }
78
session-manager-plugin
aws
Go
package credentials import ( "math/rand" "sync" "testing" "time" "github.com/aws/aws-sdk-go/aws/awserr" ) type stubProvider struct { creds Value retrievedCount int expired bool err error } func (s *stubProvider) Retrieve() (Value, error) { s.retrievedCount++ s.expired = false s.creds.ProviderName = "stubProvider" return s.creds, s.err } func (s *stubProvider) IsExpired() bool { return s.expired } func TestCredentialsGet(t *testing.T) { c := NewCredentials(&stubProvider{ creds: Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "", }, expired: true, }) creds, err := c.Get() if err != nil { t.Errorf("Expected no error, got %v", err) } if e, a := "AKID", creds.AccessKeyID; e != a { t.Errorf("Expect access key ID to match, %v got %v", e, a) } if e, a := "SECRET", creds.SecretAccessKey; e != a { t.Errorf("Expect secret access key to match, %v got %v", e, a) } if v := creds.SessionToken; len(v) != 0 { t.Errorf("Expect session token to be empty, %v", v) } } func TestCredentialsGetWithError(t *testing.T) { c := NewCredentials(&stubProvider{err: awserr.New("provider error", "", nil), expired: true}) _, err := c.Get() if e, a := "provider error", err.(awserr.Error).Code(); e != a { t.Errorf("Expected provider error, %v got %v", e, a) } } func TestCredentialsExpire(t *testing.T) { stub := &stubProvider{} c := NewCredentials(stub) stub.expired = false if !c.IsExpired() { t.Errorf("Expected to start out expired") } c.Expire() if !c.IsExpired() { t.Errorf("Expected to be expired") } c.Get() if c.IsExpired() { t.Errorf("Expected not to be expired") } stub.expired = true if !c.IsExpired() { t.Errorf("Expected to be expired") } } type MockProvider struct { Expiry } func (*MockProvider) Retrieve() (Value, error) { return Value{}, nil } func TestCredentialsGetWithProviderName(t *testing.T) { stub := &stubProvider{} c := NewCredentials(stub) creds, err := c.Get() if err != nil { t.Errorf("Expected no error, got %v", err) } if e, a := creds.ProviderName, "stubProvider"; e != a { t.Errorf("Expected provider name to match, %v got %v", e, a) } } func TestCredentialsIsExpired_Race(t *testing.T) { creds := NewChainCredentials([]Provider{&MockProvider{}}) starter := make(chan struct{}) var wg sync.WaitGroup wg.Add(10) for i := 0; i < 10; i++ { go func() { defer wg.Done() <-starter for i := 0; i < 100; i++ { creds.IsExpired() } }() } close(starter) wg.Wait() } func TestCredentialsExpiresAt_NoExpirer(t *testing.T) { stub := &stubProvider{} c := NewCredentials(stub) _, err := c.ExpiresAt() if e, a := "ProviderNotExpirer", err.(awserr.Error).Code(); e != a { t.Errorf("Expected provider error, %v got %v", e, a) } } type stubProviderExpirer struct { stubProvider expiration time.Time } func (s *stubProviderExpirer) ExpiresAt() time.Time { return s.expiration } func TestCredentialsExpiresAt_HasExpirer(t *testing.T) { stub := &stubProviderExpirer{} c := NewCredentials(stub) // fetch initial credentials so that forceRefresh is set false _, err := c.Get() if err != nil { t.Errorf("Unexpecte error: %v", err) } stub.expiration = time.Unix(rand.Int63(), 0) expiration, err := c.ExpiresAt() if err != nil { t.Errorf("Expected no error, got %v", err) } if stub.expiration != expiration { t.Errorf("Expected matching expiration, %v got %v", stub.expiration, expiration) } c.Expire() expiration, err = c.ExpiresAt() if err != nil { t.Errorf("Expected no error, got %v", err) } if !expiration.IsZero() { t.Errorf("Expected distant past expiration, got %v", expiration) } } type stubProviderConcurrent struct { stubProvider done chan struct{} } func (s *stubProviderConcurrent) Retrieve() (Value, error) { <-s.done return s.stubProvider.Retrieve() } func TestCredentialsGetConcurrent(t *testing.T) { stub := &stubProviderConcurrent{ done: make(chan struct{}), } c := NewCredentials(stub) done := make(chan struct{}) for i := 0; i < 2; i++ { go func() { c.Get() done <- struct{}{} }() } // Validates that a single call to Retrieve is shared between two calls to Get stub.done <- struct{}{} <-done <-done } type stubProviderRefreshable struct { creds Value expired bool hasRetrieved bool } func (s *stubProviderRefreshable) Retrieve() (Value, error) { // On first retrieval, return the creds that this provider was created with. // On subsequent retrievals, return new refreshed credentials. if !s.hasRetrieved { s.expired = true s.hasRetrieved = true } else { s.creds = Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "NEW_SESSION", } s.expired = false time.Sleep(10 * time.Millisecond) } return s.creds, nil } func (s *stubProviderRefreshable) IsExpired() bool { return s.expired } func TestCredentialsGet_RefreshableProviderRace(t *testing.T) { stub := &stubProviderRefreshable{ creds: Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "OLD_SESSION", }, } c := NewCredentials(stub) // The first Get() causes stubProviderRefreshable to consider its // OLD_SESSION credentials expired on subsequent retrievals. creds, err := c.Get() if err != nil { t.Errorf("Expected no error, got %v", err) } if e, a := "OLD_SESSION", creds.SessionToken; e != a { t.Errorf("Expect session token to match, %v got %v", e, a) } // Since stubProviderRefreshable considers its OLD_SESSION credentials // expired, all subsequent calls to Get() should retrieve NEW_SESSION creds. var wg sync.WaitGroup wg.Add(100) for i := 0; i < 100; i++ { go func() { defer wg.Done() creds, err := c.Get() if err != nil { t.Errorf("Expected no error, got %v", err) } if c.IsExpired() { t.Errorf("not expect expired") } if e, a := "NEW_SESSION", creds.SessionToken; e != a { t.Errorf("Expect session token to match, %v got %v", e, a) } }() } wg.Wait() }
281
session-manager-plugin
aws
Go
package credentials import ( "os" "github.com/aws/aws-sdk-go/aws/awserr" ) // EnvProviderName provides a name of Env provider const EnvProviderName = "EnvProvider" var ( // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be // found in the process's environment. ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key // can't be found in the process's environment. ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) ) // A EnvProvider retrieves credentials from the environment variables of the // running process. Environment credentials never expire. // // Environment variables used: // // * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY // // * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY type EnvProvider struct { retrieved bool } // NewEnvCredentials returns a pointer to a new Credentials object // wrapping the environment variable provider. func NewEnvCredentials() *Credentials { return NewCredentials(&EnvProvider{}) } // Retrieve retrieves the keys from the environment. func (e *EnvProvider) Retrieve() (Value, error) { e.retrieved = false id := os.Getenv("AWS_ACCESS_KEY_ID") if id == "" { id = os.Getenv("AWS_ACCESS_KEY") } secret := os.Getenv("AWS_SECRET_ACCESS_KEY") if secret == "" { secret = os.Getenv("AWS_SECRET_KEY") } if id == "" { return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound } if secret == "" { return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound } e.retrieved = true return Value{ AccessKeyID: id, SecretAccessKey: secret, SessionToken: os.Getenv("AWS_SESSION_TOKEN"), ProviderName: EnvProviderName, }, nil } // IsExpired returns if the credentials have been retrieved. func (e *EnvProvider) IsExpired() bool { return !e.retrieved }
75
session-manager-plugin
aws
Go
package credentials import ( "os" "testing" "github.com/aws/aws-sdk-go/internal/sdktesting" ) func TestEnvProviderRetrieve(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() os.Setenv("AWS_ACCESS_KEY_ID", "access") os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") os.Setenv("AWS_SESSION_TOKEN", "token") e := EnvProvider{} creds, err := e.Retrieve() if err != nil { t.Errorf("expect nil, got %v", err) } if e, a := "access", 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 := "token", creds.SessionToken; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestEnvProviderIsExpired(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() os.Setenv("AWS_ACCESS_KEY_ID", "access") os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") os.Setenv("AWS_SESSION_TOKEN", "token") e := EnvProvider{} if !e.IsExpired() { t.Errorf("Expect creds to be expired before retrieve.") } _, err := e.Retrieve() if err != nil { t.Errorf("expect nil, got %v", err) } if e.IsExpired() { t.Errorf("Expect creds to not be expired after retrieve.") } } func TestEnvProviderNoAccessKeyID(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") e := EnvProvider{} _, err := e.Retrieve() if e, a := ErrAccessKeyIDNotFound, err; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestEnvProviderNoSecretAccessKey(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() os.Setenv("AWS_ACCESS_KEY_ID", "access") e := EnvProvider{} _, err := e.Retrieve() if e, a := ErrSecretAccessKeyNotFound, err; e != a { t.Errorf("expect %v, got %v", e, a) } } func TestEnvProviderAlternateNames(t *testing.T) { restoreEnvFn := sdktesting.StashEnv() defer restoreEnvFn() os.Setenv("AWS_ACCESS_KEY", "access") os.Setenv("AWS_SECRET_KEY", "secret") e := EnvProvider{} creds, err := e.Retrieve() if err != nil { t.Errorf("expect nil, got %v", err) } if e, a := "access", 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 v := creds.SessionToken; len(v) != 0 { t.Errorf("Expected no token, %v", v) } }
107
session-manager-plugin
aws
Go
package credentials import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/internal/ini" "github.com/aws/aws-sdk-go/internal/shareddefaults" ) // SharedCredsProviderName provides a name of SharedCreds provider const SharedCredsProviderName = "SharedCredentialsProvider" var ( // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) ) // A SharedCredentialsProvider retrieves access key pair (access key ID, // secret access key, and session token if present) credentials from the current // user's home directory, and keeps track if those credentials are expired. // // Profile ini file example: $HOME/.aws/credentials type SharedCredentialsProvider struct { // Path to the shared credentials file. // // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the // env value is empty will default to current user's home directory. // Linux/OSX: "$HOME/.aws/credentials" // Windows: "%USERPROFILE%\.aws\credentials" Filename string // AWS Profile to extract credentials from the shared credentials file. If empty // will default to environment variable "AWS_PROFILE" or "default" if // environment variable is also not set. Profile string // retrieved states if the credentials have been successfully retrieved. retrieved bool } // NewSharedCredentials returns a pointer to a new Credentials object // wrapping the Profile file provider. func NewSharedCredentials(filename, profile string) *Credentials { return NewCredentials(&SharedCredentialsProvider{ Filename: filename, Profile: profile, }) } // Retrieve reads and extracts the shared credentials from the current // users home directory. func (p *SharedCredentialsProvider) Retrieve() (Value, error) { p.retrieved = false filename, err := p.filename() if err != nil { return Value{ProviderName: SharedCredsProviderName}, err } creds, err := loadProfile(filename, p.profile()) if err != nil { return Value{ProviderName: SharedCredsProviderName}, err } p.retrieved = true return creds, nil } // IsExpired returns if the shared credentials have expired. func (p *SharedCredentialsProvider) IsExpired() bool { return !p.retrieved } // loadProfiles loads from the file pointed to by shared credentials filename for profile. // The credentials retrieved from the profile will be returned or error. Error will be // returned if it fails to read from the file, or the data is invalid. func loadProfile(filename, profile string) (Value, error) { config, err := ini.OpenFile(filename) if err != nil { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) } iniProfile, ok := config.GetSection(profile) if !ok { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", nil) } id := iniProfile.String("aws_access_key_id") if len(id) == 0 { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey", fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), nil) } secret := iniProfile.String("aws_secret_access_key") if len(secret) == 0 { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret", fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), nil) } // Default to empty string if not found token := iniProfile.String("aws_session_token") return Value{ AccessKeyID: id, SecretAccessKey: secret, SessionToken: token, ProviderName: SharedCredsProviderName, }, nil } // filename returns the filename to use to read AWS shared credentials. // // Will return an error if the user's home directory path cannot be found. func (p *SharedCredentialsProvider) filename() (string, error) { if len(p.Filename) != 0 { return p.Filename, nil } if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); len(p.Filename) != 0 { return p.Filename, nil } if home := shareddefaults.UserHomeDir(); len(home) == 0 { // Backwards compatibility of home directly not found error being returned. // This error is too verbose, failure when opening the file would of been // a better error to return. return "", ErrSharedCredentialsHomeNotFound } p.Filename = shareddefaults.SharedCredentialsFilename() return p.Filename, nil } // profile returns the AWS shared credentials profile. If empty will read // environment variable "AWS_PROFILE". If that is not set profile will // return "default". func (p *SharedCredentialsProvider) profile() string { if p.Profile == "" { p.Profile = os.Getenv("AWS_PROFILE") } if p.Profile == "" { p.Profile = "default" } return p.Profile }
152