如何使用Firebase模拟器、Python和安全规则



我正在用一些安全规则设置一个Firebase项目,例如从我的firestore.rules:

match /user_private/{uid} {
allow read: if request.auth != null && request.auth.uid == uid;
...

我有一个使用admin SDK的Python脚本,据我所知,它应该绕过这些规则。我已经在prod上同步了我的安全规则,Python可以用这个脚本很好地阅读它:

cred = credentials.ApplicationDefault()
firebase_app = firebase_admin.initialize_app(cred, {
'projectId': PROJECT_ID,
})
db = firestore.client(firebase_app)
print(
db.collection('user_private')
.document('abc123')
.get()
.to_dict())

这将正确打印匹配的文档。

不过,我希望能够使用Firebase模拟器进行测试。我更改了代码,以连接Python的模拟器,如下所述:

# ...same as above
db = firestore.client(firebase_app)
channel = grpc.insecure_channel('localhost:8080')
transport = firestore_grpc_transport.FirestoreGrpcTransport(channel=channel)
db._firestore_api_internal = firestore_client.FirestoreClient(
transport=transport)
print(...)

现在,当我运行脚本时,它试图查询模拟器,我得到:

Traceback (most recent call last):
File "/.venv/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 140, in error_remapped_callable
return _StreamingResponseIterator(
File "/.venv/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 66, in __init__
self._stored_first_result = next(self._wrapped)
File "/.venv/lib/python3.9/site-packages/grpc/_channel.py", line 426, in __next__
return self._next()
File "/.venv/lib/python3.9/site-packages/grpc/_channel.py", line 826, in _next
raise self
grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with:
status = StatusCode.PERMISSION_DENIED
details = "
false for 'get' @ L55"
debug_error_string = "{"created":"@1661203811.607181000","description":"Error received from peer ipv4:127.0.0.1:8080","file":"src/core/lib/surface/call.cc","file_line":967,"grpc_message":"nfalse for 'get' @ L55","grpc_status":7}"

(我认为权限被拒绝是因为服务帐户没有按照规则要求进行"身份验证"?(

有没有一种方法可以让Python SDK很好地使用模拟器+安全规则?还是我只需要关闭本地开发的安全性?

我觉得自己很笨。我尝试设置FIRESTORE_EMULATOR_HOSTGCLOUD_PROJECT环境标志变量,如链接问题中所述,效果很好。

最新更新