github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/internal/credproviders/env_provider.go (about)

     1  // Copyright (C) MongoDB, Inc. 2023-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 credproviders
     8  
     9  import (
    10  	"os"
    11  
    12  	"go.mongodb.org/mongo-driver/internal/aws/credentials"
    13  )
    14  
    15  // envProviderName provides a name of Env provider
    16  const envProviderName = "EnvProvider"
    17  
    18  // EnvVar is an environment variable
    19  type EnvVar string
    20  
    21  // Get retrieves the environment variable
    22  func (ev EnvVar) Get() string {
    23  	return os.Getenv(string(ev))
    24  }
    25  
    26  // A EnvProvider retrieves credentials from the environment variables of the
    27  // running process. Environment credentials never expire.
    28  type EnvProvider struct {
    29  	AwsAccessKeyIDEnv     EnvVar
    30  	AwsSecretAccessKeyEnv EnvVar
    31  	AwsSessionTokenEnv    EnvVar
    32  
    33  	retrieved bool
    34  }
    35  
    36  // NewEnvProvider returns a pointer to an ECS credential provider.
    37  func NewEnvProvider() *EnvProvider {
    38  	return &EnvProvider{
    39  		// AwsAccessKeyIDEnv is the environment variable for AWS_ACCESS_KEY_ID
    40  		AwsAccessKeyIDEnv: EnvVar("AWS_ACCESS_KEY_ID"),
    41  		// AwsSecretAccessKeyEnv is the environment variable for AWS_SECRET_ACCESS_KEY
    42  		AwsSecretAccessKeyEnv: EnvVar("AWS_SECRET_ACCESS_KEY"),
    43  		// AwsSessionTokenEnv is the environment variable for AWS_SESSION_TOKEN
    44  		AwsSessionTokenEnv: EnvVar("AWS_SESSION_TOKEN"),
    45  	}
    46  }
    47  
    48  // Retrieve retrieves the keys from the environment.
    49  func (e *EnvProvider) Retrieve() (credentials.Value, error) {
    50  	e.retrieved = false
    51  
    52  	v := credentials.Value{
    53  		AccessKeyID:     e.AwsAccessKeyIDEnv.Get(),
    54  		SecretAccessKey: e.AwsSecretAccessKeyEnv.Get(),
    55  		SessionToken:    e.AwsSessionTokenEnv.Get(),
    56  		ProviderName:    envProviderName,
    57  	}
    58  	err := verify(v)
    59  	if err == nil {
    60  		e.retrieved = true
    61  	}
    62  
    63  	return v, err
    64  }
    65  
    66  // IsExpired returns true if the credentials have not been retrieved.
    67  func (e *EnvProvider) IsExpired() bool {
    68  	return !e.retrieved
    69  }