Nodejs Secure Config 配置加密方案
Node.js 启动后台服务,通常都要连接数据库,或者连接第三方接口等,这里就会有一些账号密码之类的需要提供,我们当然不能把这些私密的内容保存在代码库中,这样是非常不安全的。
比较简单的方式是保存在 .env.production
这样的文件中,而这文件不会提交到代码库,而是在部署时再放到相应的运行环境中。
即使是这样,也比较麻烦,而且部署的人员会接触到明文的 .env.production
配置信息,依然是有一些安全风险。
那么有什么好的解决方案吗? 下面列两个供大家参考:
Strong Config
Simple & Secure Config Management for Node.js
使用 sops 实现云加密,支持 PGP, AWS KMS, Google Cloud KMS, 和 Azure Key Valut 等云端 key 提供方案。
同时支持 schema.json
来进行格式校验等。
加密后的配置文件 production.yml
如下:
logger:
# This value remains as is because it doesn't have a 'Secret' suffix
level: DEBUG
auth:
apiClientId: non-secret-client-id
# This is now encrypted and safe to commit into version control :)
apiSecret: ENC[AES256_GCM,data:aeQ+hlVIah7WyJoVR/Jbkb6GLH7ihsV0D81+U++pkiWD0zeoRL/Oe9Q3Tz6j/TNvKKVDnohIMyw3UVjELOuSY+A==,iv:nVRZWogV4B7o=,tag:KrE2jssfP4uCvqq+pc/JyQ==,type:str]
# Also still the same value which will be substituted only at runtime
shell: ${SHELL}
# The below section is auto-generated by sops and contains important metadata to
# decrypt the config at runtime. Do not manually edit or delete this section.
sops:
gcp_kms:
- resource_id: projects/my-project/locations/europe-west1/keyRings/my-project-key-ring/cryptoKeys/my-strong-config-key
created_at: '2020-01-07T10:11:12Z'
enc: AiAAmdAgj1dw1XdD2MsVpvmA4Deo867hmcX2B3NDhe9BCF2axuZ18hJJFK9oBlE1BrD70djwqi+L8T+NRNVnGUP+1//w8cJATAfJ8W/cQZFcdFTqjezC+VYv9xYI8i1bRna4xfFo/INIJtFDR38ZH1nrQg==
lastmodified: '2020-01-07T10:11:12Z'
mac: ENC[AES256_GCM,data:ABcd1EF2gh3IJKl4MNOpQr5stuvWXYz6sBCDEfGhIjK=,iv:A1AaAAAaa111a1Aa111AA/aaaAaaAAaa+aAaAaAAAaA=,tag:AAaaA1a1aaaAa/aa11AaaA==,type:str]
encrypted_suffix: Secret
version: 3.5.0
secure-config
Easy and secure NodeJS configuration management
此方案相对简单,不用云端支持也可以实现加密,使用环境变量来保存 key 值,也支持 config.json
签名检验等功能。
加密后的配置文件 config.json
如下:
{
"database": {
"host": "127.0.0.1",
"user": "ENCRYPTED|50ceed2f97223100fbdf842ecbd4541f|df9ed9002bfc956eb14b1d2f8d960a11",
"pass": "ENCRYPTED|8fbf6ded36bcb15bd4734b3dc78f2890|7463b2ea8ed2c8d71272ac2e41761a35"
},
"__hmac": "3023eb8cf76894c0d5c7f893819916d876f98f781f8944b77e87257ef77c1adf"
}