Search code examples
node.jsauthenticationpuppeteergoogle-cloud-run

How to manage changing secrets in GCP Cloud Run


I have a function I want to run in GCP Cloud Run that has multiple secrets and files for authentication that have very short expiration times. What is the best way to handle this, I can't find any password solutions that allow you to programmatically update the secrets and the only other option seems to be to redeploy the whole function every time a secret changes which I want to avoid. Are there any alternative solutions? Here is an example of a function in the code that logs in to a site and stores the cookies for persistent authentication, but the token is invalidated fairly frequently:

const sprLogin = async (page) => {
    await page.type('#username', process.env.USERNAME_SUNPOWER)
    await page.type('#password', process.env.PASSWORD_SUNPOWER)
    await page.click('[title="Sign In"]')
    await page.waitForSelector('[placeholder="Search Sites"]')
    const cookies = await page.cookies()

    const currentDir = path.dirname(__filename);
    const dataDir = path.join(currentDir, 'data')

    if(!fs.existsSync(dataDir)) {
        fs.mkdirSync(dataDir)
    }

    const filePath = path.join(dataDir, 'cookies.json');
    
    fs.writeFileSync(filePath, JSON.stringify(cookies))
}

Solution

  • In addition to @John Hanley's comment:

    I use a global scoped variable to keep track of the last read of secrets. Once a request handler detects the time has expired, it re-reads the secrets. Note: do not use terms like very short expiration times. Use actual numbers


    This approach offers automatic secret updates without full redeployments. It's suitable for moderately frequent changes (hourly or more). For very frequent updates, consider a sidecar container solution. Redeploying your entire Cloud Run service for every secret change is inefficient.


    Reference: