调用Google KMS API时遭遇反常的INVALID_ARGUMENT错误
问题分析与解决
你的核心问题是请求对象的字段命名不符合Google Cloud KMS Node.js SDK的序列化要求:
Google Cloud的Node.js SDK采用驼峰命名来对应API的蛇形命名规则,但你代码里用了蛇形命名(比如version_template、protection_level、skip_initial_version_creation),这会导致SDK在将请求对象序列化为API要求的格式时,无法正确识别这些字段,最终实际发送给KMS API的请求里缺失了version_template.algorithm字段。
修正后的代码
export const createRSAKey = async (parentKeyRingName: string, cryptoKeyId: string) => { const kmsClient = new KeyManagementServiceClient(); const request = { parent: parentKeyRingName, cryptoKeyId, cryptoKey: { purpose: google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN, // 改用驼峰命名versionTemplate versionTemplate: { // 改用驼峰命名protectionLevel protectionLevel: google.cloud.kms.v1.ProtectionLevel.SOFTWARE, algorithm: google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_4096_SHA256, }, }, // 改用驼峰命名skipInitialVersionCreation skipInitialVersionCreation: false, }; console.log("Sending request", request); const response = await kmsClient.createCryptoKey(request); console.log(response); };
关键说明
- 字段命名匹配:SDK内部会自动将驼峰命名的字段转换为API要求的蛇形命名(比如
versionTemplate→version_template),但蛇形命名的字段不会被正确识别和转换,导致API接收不到对应参数。 - 枚举值有效性:你使用的枚举值(
5对应ASYMMETRIC_SIGN、7对应RSA_SIGN_PKCS1_4096_SHA256)是正确的,问题不在枚举值本身,而是字段结构的序列化失败。 - 验证方法:修正后可以开启SDK的调试日志,查看实际发送给API的请求内容,确认
version_template.algorithm字段已正确包含。
内容的提问来源于stack exchange,提问作者Michele Bolognini
相关产品推荐
相关产品推荐

