I setup a test database with the following configuration rules for development:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
I tested it with curl:
url -X GET "https://firestore.googleapis.com/v1beta1/projects/<my-project-id>/databases/(default)/documents/configurations/test"
{
"name": "projects/<my-project-id>/databases/(default)/documents/configurations/test",
"fields": {
"hello": {
"stringValue": "world"
}
},
"createTime": "2023-10-04T17:23:41.476045Z",
"updateTime": "2023-10-04T17:23:41.476045Z"
}
Then I tried running the equivalent code with a go script:
// Firestore test
func readFromFirestore(){
ctx := context.Background()
client, err := firestore.NewClient(ctx, os.Getenv("PROJECT_ID"))
if err != nil {
log.Fatal("Error creating firestore client: ", err)
}
log.Println("Firestore client: ", client)
// Creating the documentref
docref := client.Doc("configurations/test")
fmt.Println("Document ref: ", docref)
docsnap, err := docref.Get(ctx)
if err != nil {
log.Fatal("Error reading document: ", err)
}
dataMap := docsnap.Data()
fmt.Println(dataMap)
}
And I get the following output
go run .
2023/10/04 14:33:15 Firestore client: &{0xc00011d590 <my-projectid> (default) 0xc00011d5a8}
Document ref: &{0xc0002c8160 projects/<my-project-id>/databases/(default)/documents/configurations/test configurations/test test 0xc00011d5f0}
2023/10/04 14:33:16 Error reading document: rpc error: code = PermissionDenied desc = Missing or insufficient permissions.
exit status 1
All the answers I find online for this error directs me towards configuring firestore security rules. But since I can retrieve the document with an unauthenticated HTTP request, I think this is not the issue. I think I probably made a mistake on my Go implementation.
I've tried searching for the error code, and followed the instructions of the main search results, without success. ChatGPT is also not helpful.
I found a solution.
I managed to make it work by setting the
GOOGLE_APPLICATON_CREDENTIALS="KEY PATH"environment variable, where theKEY_PATHis the path, relative or absolute, to a JSON credentials file.This is described in the firestore quickstart for server side libraries. https://cloud.google.com/firestore/docs/create-database-server-client-library
Not sure yet if there is a way to make this work only by authenticating with the CLI.
EDIT: Found a way to do it with the CLI
gcloud auth application-default loginI like this one even better because I don't need to have credential files in my system.