...

Source file src/go.mongodb.org/mongo-driver/x/mongo/driver/auth/creds/awscreds.go

Documentation: go.mongodb.org/mongo-driver/x/mongo/driver/auth/creds

     1  // Copyright (C) MongoDB, Inc. 2022-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 creds
     8  
     9  import (
    10  	"context"
    11  	"net/http"
    12  	"time"
    13  
    14  	"go.mongodb.org/mongo-driver/internal/aws/credentials"
    15  	"go.mongodb.org/mongo-driver/internal/credproviders"
    16  	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
    17  )
    18  
    19  const (
    20  	// expiryWindow will allow the credentials to trigger refreshing prior to the credentials actually expiring.
    21  	// This is beneficial so expiring credentials do not cause request to fail unexpectedly due to exceptions.
    22  	//
    23  	// Set an early expiration of 5 minutes before the credentials are actually expired.
    24  	expiryWindow = 5 * time.Minute
    25  )
    26  
    27  // AWSCredentialProvider wraps AWS credentials.
    28  type AWSCredentialProvider struct {
    29  	Cred *credentials.Credentials
    30  }
    31  
    32  // NewAWSCredentialProvider generates new AWSCredentialProvider
    33  func NewAWSCredentialProvider(httpClient *http.Client, providers ...credentials.Provider) AWSCredentialProvider {
    34  	providers = append(
    35  		providers,
    36  		credproviders.NewEnvProvider(),
    37  		credproviders.NewAssumeRoleProvider(httpClient, expiryWindow),
    38  		credproviders.NewECSProvider(httpClient, expiryWindow),
    39  		credproviders.NewEC2Provider(httpClient, expiryWindow),
    40  	)
    41  
    42  	return AWSCredentialProvider{credentials.NewChainCredentials(providers)}
    43  }
    44  
    45  // GetCredentialsDoc generates AWS credentials.
    46  func (p AWSCredentialProvider) GetCredentialsDoc(ctx context.Context) (bsoncore.Document, error) {
    47  	creds, err := p.Cred.GetWithContext(ctx)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	builder := bsoncore.NewDocumentBuilder().
    52  		AppendString("accessKeyId", creds.AccessKeyID).
    53  		AppendString("secretAccessKey", creds.SecretAccessKey)
    54  	if token := creds.SessionToken; len(token) > 0 {
    55  		builder.AppendString("sessionToken", token)
    56  	}
    57  	return builder.Build(), nil
    58  }
    59  

View as plain text