如何为不同租户设置不同加密密钥?
解读
在国内 SaaS 或金融级多租户系统中,**“不同租户不同密钥”**是合规刚需(等保 2.0、个人信息保护法、PCI-DSS)。面试官想确认三件事:
- 你是否理解“密钥与租户生命周期绑定”——密钥不能硬编码,必须可轮换、可吊销;
- 你是否能把密钥管理无缝嵌入 SQLAlchemy 的列级加密/解密流程,而不破坏 ORM 的声明式体验;
- 你是否能在连接池、异步会话、分片等高级场景下保证密钥线程安全且零泄漏。
一句话:不是“怎么存密钥”,而是“怎么让 SQLAlchemy 在正确时机拿到正确密钥,并保证性能与合规”。
知识点
- SQLAlchemy 类型装饰器(TypeDecorator):把 Python 明文 ↔ 数据库密文的转换封装成自定义列类型,业务代码无感知。
- SQLAlchemy 事件钩子:在
before_cursor_execute、refresh_flush、do_orm_execute等时机注入租户上下文,避免“明文穿越”。 - KMS 集成模式:
- 国内云:阿里云 KMS、腾讯云 KMS、华为云 KMS 均支持信封加密(DEK+KEK),满足等保三级。
- 自建:HashiCorp Vault + Transit Engine,通过 AppRole + K8s SA 做身份校验。
- 密钥缓存策略:使用
lru_cache或cachetools.TTLCache缓存 DEK,减少 KMS 调用延迟;缓存键用tenant_id + key_version,版本变更时自动失效。 - 线程/协程安全:
- 同步引擎:用
contextvars.ContextVar保存当前租户,防止 gevent 协程串号。 - 异步引擎:在
AsyncSession的bind_arguments里传递tenant_id,确保连接池复用不串密钥。
- 同步引擎:用
- Alembic 迁移:加密列类型变更需使用
alter_column并指定postgresql_using或mysql_using,避免全表锁。 - 合规审计:开启 SQLAlchemy 事件监听,记录
cipher_text_length、key_version、kms_request_id,对接国内 ELK/日志审计系统。
答案
步骤一:定义租户感知的加密列类型
from sqlalchemy import TypeDecorator, String, event
from cryptography.fernet import Fernet
import contextvars, cachetools, os, json
tenant_ctx: contextvars.ContextVar[str] = contextvars.ContextVar("tenant")
class TenantFernet(TypeDecorator):
impl = String(2048)
cache = cachetools.TTLCache(maxsize=256, ttl=300)
def _get_dek(self, tenant_id: str) -> bytes:
# 优先读缓存
if tenant_id in self.cache:
return self.cache[tenant_id]
# 调用阿里云 KMS Decrypt,拿到明文 DEK
import aliyunsdkcore.client as acs
client = acs.AcsClient(os.getenv("AK"), os.getenv("SK"), "cn-shanghai")
req = kms_models.GetDataKeyRequest()
req.KeyId = f"alias/tenant-{tenant_id}"
resp = client.do_action_with_exception(req)
dek = json.loads(resp)["Plaintext"]
self.cache[tenant_id] = dek
return dek
def process_bind_param(self, value, dialect):
if value is None:
return None
tenant_id = tenant_ctx.get()
f = Fernet(self._get_dek(tenant_id))
return f.encrypt(value.encode()).decode()
def process_result_value(self, value, dialect):
if value is None:
return None
tenant_id = tenant_ctx.get()
f = Fernet(self._get_dek(tenant_id))
return f.decrypt(value.encode()).decode()
步骤二:在会话级注入租户上下文
from sqlalchemy.orm import sessionmaker, scoped_session
Session = scoped_session(sessionmaker(bind=engine))
@event.listens_for(Session, "before_flush")
def receive_before_flush(session, flush_context, instances):
tenant = session.info.get("tenant")
if tenant:
tenant_ctx.set(tenant)
步骤三:使用方式(FastAPI 场景)
@app.post("/user")
async def create_user(item: UserIn, tenant: str = Header(...)):
async with AsyncSession(engine) as sess:
sess.info["tenant"] = tenant
sess.add(User(name=item.name, id_card=TenantFernet()))
await sess.commit()
步骤四:密钥轮换
- 在 KMS 创建新版本密钥,更新
alias/tenant-{id}指向新版本; - 清掉
TenantFernet.cache; - 老数据仍用旧版本解密,新数据自动用新版本加密,实现零停机轮换。
拓展思考
- 分片场景:若按租户分库分表,可在
ShardSession的id_chooser里把tenant_id映射到密钥,避免跨库密钥泄露。 - 性能调优:对高并发读场景,可预加载热点租户 DEK 到 Redis,设置
volatile-lru淘汰,减少 30% 以上 KMS 费用。 - 国密合规:把
Fernet换成国密SM4-GCM,通过pycryptodome实现,KMS 侧启用硬件密码机(HSM)保护 KEK,满足密评要求。 - 审计闭环:在
after_cursor_execute事件里把tenant_id、key_version、cipher_len、kms_request_id写入 Kafka,再同步到国家网安日志留存系统,实现 6 个月可追溯。