Keep it cool and secure: do's and don'ts for managing Web App secrets
Tags: cybersecurity, webdev, security, devops
Published: 2024-01-06 17:54:38

The security of your web application abides by the strength of your secrets. 

Severe data breaches and systems that got totally hijacked for cryptocurrency mining aren't just tales from the tech-crypt, they're real, heavy, and far too prevalent. 

Every other day we're hearing about some massive data breach or a bunch of servers turned into crypto-mining zombies. These aren't just wake-up calls; they're blaring alarms telling us to keep our digital house locked down tight. 

Forget about the headache of cleaning up after an attack; it's the trust you lose, the customers that give you the side-eye, and the reputation you've built up taking a major hit. So yeah, staying on top of our security game is more than a good idea; it's essential to keeping everything we've worked for safe and sound.

Keeping your API keys, passwords, and other sensitive intel secure isn't just about playing defense, it's about preserving your cool reputation, your customers' privacy, and the trust of your team.

As we roll into the do's and don'ts of managing these crucial secrets, let's stay open-minded and remember that:

1. Adopting the right practices isn't just a laid-back suggestion; it's the key to maintaining a robust and trustworthy application.
2. There are likely more insights and strategies beyond what I've shared. So, I warmly invite you to contribute your thoughts and additional do's and don'ts in the comments.

## Do's
Store your secrets like you’d keep your most precious item - in a cool, safe place, away from prying eyes.

![Gollum my precious](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xfisgjmndpo36og2f9c.jpg)

### Use Environment Variables

Environment are a way of keeping your info out of the codebase and reducing the risk of a bummer exposure. 

Consider using tools like [Gitlab CI/CD](https://docs.gitlab.com/ee/ci/variables/) variables or [Github secrets](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions) to fortify their security and seamlessly integrate them during the build process, tailored to your specific environment.

While environment variables are a common method for storing secrets, it's important to be aware of their potential risks, as highlighted in [this Trend Micro article](https://www.trendmicro.com/en_se/research/22/h/analyzing-hidden-danger-of-environment-variables-for-keeping-secrets.html). 

Environment variables are not inherently secure, as they are not encrypted and can be exposed to unauthorized access. Before using them, ensure that your deployment environment is secure and consider additional protective measures like access controls. Regularly review and audit your use of environment variables to prevent unintended exposure of sensitive information.

### Employ a Secret Management Tool
For a more comprehensive and robust secret management solution, get your hands on tools like [GCP Secret Manager](https://cloud.google.com/security/products/secret-manager), or [HashiCorp Vault](https://www.vaultproject.io/). They're like the security guards of your secrets, providing a safe house, access control, and keeping logs of who’s been snooping around.

I think this is a better alternative to using plain environment variables for storing API keys or secrets since they will be treated as encrypted secrets in a vault.

#### Environment Variables vs Secret Management Tool example

With Firebase Functions you can use Google Secret Manager and have a Parameterized configuration for both secrets and environment variables.

##### Environment Variables

You can create an env variable via an .env file or via deployment runtime or emulators. The following is a basic example, please see the [Firebase Docs](https://firebase.google.com/docs/functions/config-env?gen=2nd) for a full example.

```typescript

import { defineString } from 'firebase-functions/params';


export const baseStripeAPIURL: ConfigParameter = defineString('BASE_STRIPE_API_URL');

```
##### Secrets

You can create a secret using the firebase SDK:

```shell

firebase functions:secrets:set STRIPE_KEY

```

And then access the secret like so:

```typescript

import { defineSecret } from 'firebase-functions/params';

export const stripeKey: ConfigParameter = defineSecret('STRIPE_KEY');

```

### Encrypt secrets
Make sure your secrets are as unreadable as ancient hieroglyphs to those not in the know. Encryption is the magic spell here, with [AES-256](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) being the incantation of choice.

### Rotate secrets regularly
Rotate secrets at industry-recommended intervals, such as every 3-6 months, based on your application's threat model. 

Regularly switching things up minimizes the fallout from any leaks. You can create a calendar and notifications to remind you when to change your secrets, this can be simplified with a Secret Management Tool as well.

### Implement Least Privilege Access
Granting access to your system is like handing out backstage passes to a concert; you should only give them to those who absolutely need to be there. This approach minimizes the potential chaos if things go south. 

Begin by assigning the bare minimum level of privilege necessary, then cautiously elevate permissions if additional access is required for specific tasks. 

Consider also the temporal aspect of access—some may only need certain privileges for a limited period. Once their task is complete, or the time expires, revoke those privileges promptly. This way, you maintain a tight, secure environment, just as you would ensure only the essential crew is backstage during the show

### Audit and monitor access to your secrets
Regularly check who's got the backstage pass to your secrets and keep a watchful eye on access logs. Stay alert for any oddball activity that could spell trouble, like an uninvited guest at your chill gathering. You can use tools like [Cloud Audit Logs](https://cloud.google.com/logging/docs/audit) or [Cloud Armor](https://cloud.google.com/security/products/armor?hl=en)

### Secure your deployment pipeline
Ensure the path to rolling out your application is as secure as a locked diary. Use CI/CD tools that vibe with secret management and put up a "No Trespassing" sign to restrict access to the deployment process. You can use a tool like [Gitlab CI/CD](https://docs.gitlab.com/ee/ci/variables/)

### Use environment-specific secrets
Divide your secrets: one for development, testing, and production. This way, you prevent an accidental leak during a soundcheck from ruining the main show.

### Ensure backup security
Ensuring the security of your backups is as important as securing your primary data. Encrypting backup data protects it even if accessed by unauthorized parties. 

Regularly test and update your backup security measures to ensure they provide strong protection, making them an integral part of your data security strategy.

### Educate your team
Gather your band members and make sure they're in tune with the importance of secret management. It's like teaching them the chords to a complex song – they need to understand and follow the best practices to hit the right notes.

> Informed employees are a company's first and most effective line of defense.

It's important that they don't perceive this as a burdensome task. Providing informative and engaging learning content can help motivate your team about cybersecurity.

### Implement MFA
Implement Multi Factor Authentication as an essential layer of security for accessing secrets, significantly reducing the risk of unauthorized access.

## Don'ts

![Surprised Pikachu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdog2xs848efvsb2b1wn.png)

### Don't hardcode secrets
Never embed your secrets directly into your source code or configuration files. 

This practice, while convenient, is similar to leaving personal notes open in public spaces — it can inadvertently expose sensitive information. Instead, securely manage your secrets using environment variables or secret management tools to keep them protected.

### Don't share secrets unnecessarily
Avoid passing around your secrets like a hot potato unless it's absolutely necessary. Each service should have its own private stash to minimize the drama if something goes sideways.

### Don't use predictable secrets
Steer clear of secrets that are as predictable as a broken record. Always opt for strong, randomly generated passwords and keys that no one can guess.

### Don't ignore alerts
Heed the call when your security system sounds the alarm. Swiftly investigate any unusual activity or unauthorized alterations to your secrets – they might be signaling a problem you can't afford to ignore.

These alerts act as an early warning system, helping to prevent potential breaches and maintain the integrity of your security measures.

### Don't neglect regular audits
Regularly reviewing your secret management practices ensures they remain effective and up-to-date. Stay hip to the latest security trends and tweak your strategies to stay ahead of the curve.

### Don't overlook API limits
Be mindful of the rate limits of any APIs you're using. Exceeding these limits can disrupt service and potentially lead to security vulnerabilities, so it's important to stay within the prescribed boundaries.

### Don't store secrets in client-side code
Storing secrets in the client-side of your application can make them easily accessible to others. Instead, keep secrets server-side where they can be more securely managed and controlled, reducing the risk of exposure.

### Don't rely on obscurity
Relying solely on hiding information is not a secure strategy. Adopt a comprehensive approach that includes encrypting data, enforcing strict access controls, and regularly monitoring for suspicious activities. A proactive and layered security strategy offers far more protection than simply hoping secrets remain undiscovered.

### Don't neglect code reviews
Ensure code containing secret access or usage undergoes thorough code reviews to identify and mitigate potential vulnerabilities.

## Conclusion
By abiding by these do's and don'ts, you're not just throwing a security blanket over your application; you're actively engaging in a righteous quest to protect your digital realm. 

Security isn't a one-and-done deal. It's a continuous journey, a vibe you maintain. So, stay informed, stay cool, and most importantly, keep those secrets safe. Your application, your team, and your customers will thank you. 

There are likely more insights and strategies beyond what I've shared. So, I warmly invite you to contribute your thoughts and additional do's and don'ts in the comments. 

Let's learn and grow together in our quest for better security.

Thank you for reading ✌️😬