Home > Mobile >  How to use Google Cloud Secrets in Cloud Run using react?
How to use Google Cloud Secrets in Cloud Run using react?

Time:10-02

I'm developing a react website that uses some sensitive API keys.

I'm hosting the application on Google Cloud Run, via a container.

I would like to access API keys through Google Cloud Secret Manager, but I am not able to. When I try to access them, the return is "undefined".

Here is my code snippet:

console.log(process.env.REACT_APP_API_KEY)

And the Dockerfile:

FROM node:14-alpine AS builder
WORKDIR /app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build

FROM nginx:1.19-alpine AS server
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder ./app/build /usr/share/nginx/html

I'm deploying the application using the gcloud command:

gcloud run deploy test-gcr-react \
--image gcr.io/test-gcr-react-app/test-gcr-react \
--region=southamerica-east1 \
--set-secrets=REACT_APP_API_KEY=REACT_APP_API_KEY:latest \
--allow-unauthenticated

PS: I have already given the proper access permissions to the service account "Default compute service account" to be a "Secret Manager Secret Advisor" of the secret REACT_APP_API_KEY.

CodePudding user response:

I guess you mean Secret Manager Secret Accessor role.

In order to do so you can do this:

gcloud secrets add-iam-policy-binding secret-id \
--member="serviceAccount:<project-number>[email protected]" \
--role="roles/secretmanager.secretAccessor"

But, make sure your cloud run is really using that service account, if not change the member field in the command up above to correct it to the appropriate service account instead.

CodePudding user response:

It's a common issue. Think about the role and the behavior of each layer:

  • NGINX serve directly the react JS
  • The react JS is ran directly on the user browser.

therefore, NEVER, the env var (your secret) is read. NGINX doesn't care of it, the user browser can't access Cloud Run env var.


The trick here is to set the API KEY in a conf file of your react APP at build time (in your dockerfile). The secret must be in the JS before the runtime. NGINX only serve JS, not update/change it

  • Related