1
0
しくじりエンジニア!私みたいになるな!
Qiita Engineer Festa20242024年7月17日まで開催中!

Lambda に登録したKMSで暗号化した環境変数をLambdaで扱う方法

Last updated at Posted at 2024-07-13

Lambda では API トークンなどを環境変数として登録できます。
さらに、KMSを使用して暗号化することで、よりセキュアにAPIトークンなどを保存することができます。

しかし、KMSを使用して暗号化した環境変数を扱う際に沼にハマったので記録を残しておきます。
(意外とこれに該当する記事がぱっと見つかりませんでした。。。)

結論: 暗号化するコード(Python)

def decode_variables(encrypted_token_name: str) -> Optional[str]:
    """
    Decrypts the encrypted value of an environment variable.

    Args:
        encrypted_token_name (str): The name of the environment variable containing the encrypted value.

    Returns:
        Optional[str]: The decrypted value. Returns None if decryption fails.
    """
    encrypted_token = os.environ.get(encrypted_token_name)
    if not encrypted_token:
        raise ValueError(f"{encrypted_token_name} environment variable is required.")

    kms_client = boto3.client('kms')
    try:
        decoded_token = base64.b64decode(encrypted_token)
        decrypted_token = kms_client.decrypt(
            CiphertextBlob=decoded_token,
            EncryptionContext={'LambdaFunctionName': os.environ['AWS_LAMBDA_FUNCTION_NAME']}
        )['Plaintext'].decode('utf-8')
        return decrypted_token
    except Exception as e:
        print(f"Error decrypting token: {e}")
        return None

ハマったポイント

下記 kms クライアントで decrypt する際に、EncryptionContextを登録する必要があることがわからず沼にハマっていました。。。

kms_client.decrypt(
            CiphertextBlob=decord_token,
            EncryptionContext={'LambdaFunctionName': os.environ['AWS_LAMBDA_FUNCTION_NAME']}
)['Plaintext'].decode('utf-8')

特に下記のドキュメントを見ても、特に必須との記載はなく、必要のないものだと思っていましたが、これがないとエラーになっていました。。。
(強く推奨するとの記載があったので、必須と認識して良さそうです)

EncryptionContext (dict) –

Specifies the encryption context to use when decrypting the data. An encryption context is valid only for cryptographic operations with a symmetric encryption KMS key. The standard asymmetric encryption algorithms and HMAC algorithms that KMS uses do not support an encryption context.

An encryption context is a collection of non-secret key-value pairs that represent additional authenticated data. When you use an encryption context to encrypt data, you must specify the same (an exact case-sensitive match) encryption context to decrypt the data. An encryption context is supported only on operations with symmetric encryption KMS keys. On operations with symmetric encryption KMS keys, an encryption context is optional, but it is strongly recommended.

For more information, see Encryption context in the Key Management Service Developer Guide.

(string) –

(string) –
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0