github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/x/mongo/driver/auth/mongodbaws.go (about) 1 // Copyright (C) MongoDB, Inc. 2017-present. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 7 package auth 8 9 import ( 10 "context" 11 "errors" 12 13 "go.mongodb.org/mongo-driver/internal/aws/credentials" 14 "go.mongodb.org/mongo-driver/internal/credproviders" 15 "go.mongodb.org/mongo-driver/x/mongo/driver/auth/creds" 16 ) 17 18 // MongoDBAWS is the mechanism name for MongoDBAWS. 19 const MongoDBAWS = "MONGODB-AWS" 20 21 func newMongoDBAWSAuthenticator(cred *Cred) (Authenticator, error) { 22 if cred.Source != "" && cred.Source != "$external" { 23 return nil, newAuthError("MONGODB-AWS source must be empty or $external", nil) 24 } 25 return &MongoDBAWSAuthenticator{ 26 source: cred.Source, 27 credentials: &credproviders.StaticProvider{ 28 Value: credentials.Value{ 29 ProviderName: cred.Source, 30 AccessKeyID: cred.Username, 31 SecretAccessKey: cred.Password, 32 SessionToken: cred.Props["AWS_SESSION_TOKEN"], 33 }, 34 }, 35 }, nil 36 } 37 38 // MongoDBAWSAuthenticator uses AWS-IAM credentials over SASL to authenticate a connection. 39 type MongoDBAWSAuthenticator struct { 40 source string 41 credentials *credproviders.StaticProvider 42 } 43 44 // Auth authenticates the connection. 45 func (a *MongoDBAWSAuthenticator) Auth(ctx context.Context, cfg *Config) error { 46 httpClient := cfg.HTTPClient 47 if httpClient == nil { 48 return errors.New("cfg.HTTPClient must not be nil") 49 } 50 providers := creds.NewAWSCredentialProvider(httpClient, a.credentials) 51 adapter := &awsSaslAdapter{ 52 conversation: &awsConversation{ 53 credentials: providers.Cred, 54 }, 55 } 56 err := ConductSaslConversation(ctx, cfg, a.source, adapter) 57 if err != nil { 58 return newAuthError("sasl conversation error", err) 59 } 60 return nil 61 } 62 63 type awsSaslAdapter struct { 64 conversation *awsConversation 65 } 66 67 var _ SaslClient = (*awsSaslAdapter)(nil) 68 69 func (a *awsSaslAdapter) Start() (string, []byte, error) { 70 step, err := a.conversation.Step(nil) 71 if err != nil { 72 return MongoDBAWS, nil, err 73 } 74 return MongoDBAWS, step, nil 75 } 76 77 func (a *awsSaslAdapter) Next(challenge []byte) ([]byte, error) { 78 step, err := a.conversation.Step(challenge) 79 if err != nil { 80 return nil, err 81 } 82 return step, nil 83 } 84 85 func (a *awsSaslAdapter) Completed() bool { 86 return a.conversation.Done() 87 }