StackPractices
advanced By Mathias Paulenko

Serverless Security Checklist

Security hardening checklist for serverless functions on AWS Lambda, Azure Functions and GCP Cloud Functions: IAM, secrets, input validation, dependencies, network and logging.

Topics: serverless

Overview

Every serious serverless security review I’ve seen ends with the same handful of findings: a wildcard IAM statement nobody scoped down, a secret sitting in a plaintext environment variable visible in the console, an endpoint without auth that “was only for testing”, and a dependency tree nobody has audited since the project started. This checklist exists so you find those before the reviewer — or the attacker — does.

It covers application-level hardening for functions on AWS Lambda, Azure Functions and Google Cloud Functions. The cloud providers secure the platform (hypervisor, runtime patching, physical isolation); everything you deploy on top — IAM scope, secrets handling, input validation, dependencies, network configuration, logging — is your job. Shared responsibility stops at the runtime boundary.

This isn’t the same document as the neighboring checklists. For a general audit of controls and evidence see the security audit checklist; for reviewing security in pull requests use the PR security review checklist; for fixing specific web vulnerabilities work through the OWASP top 10 remediation checklist. This one is specifically about hardening FaaS functions — event-driven code with managed identity, ephemeral environments and per-invocation permissions.

How to Use This Checklist

Run it before a function’s first production deploy, then again after any security review, major dependency upgrade or architecture change. Order matters — fix findings in this sequence because the earlier items make the later ones meaningful:

  1. IAM first. An over-privileged role turns every other bug into a potential compromise. Scope it down before touching anything else.
  2. Secrets second. Pull anything hardcoded or plaintext out of env vars and into a managed secrets store. This takes minutes and removes the most common leak.
  3. Input validation and dependencies. These are your two external attack surfaces — what callers send you and what you import.
  4. Network and data. Only then tune VPC placement, TLS and encryption; the defaults are usually right until compliance says otherwise.
  5. Logging last. Without detection you won’t know when the first four fail.

Each section has a checklist, a working config or code example, and the reasoning that isn’t obvious from the config alone. Don’t treat it as a pass/fail audit — mark items as verified, deliberately skipped (with a note why), or broken. A skipped item you documented beats an item you never looked at.

Provider Differences: What Changes Where

The checklist items are the same across providers; the implementations aren’t. This is where multi-cloud write-ups usually get vague, so here’s the mapping:

LayerAWS LambdaAzure FunctionsGCP Cloud Functions
IdentityIAM execution roleManaged identityService account
Secrets storeSecrets Manager / SSMKey VaultSecret Manager
Private networkingVPC + security groupsVNet integrationVPC connector
Event validationAPI Gateway request schemasAPIM policiesAPI Gateway / ESPv2
Audit logCloudTrailAzure Activity LogCloud Audit Logs
Threat detectionGuardDutyDefender for CloudSecurity Command Center

Two provider-specific traps worth knowing: on AWS, attaching a function to a VPC adds cold-start latency and forces a NAT Gateway bill for internet access — only do it for private resources. On GCP, allUsers as an invoker makes the function public with no additional auth layer; it’s a one-line misconfiguration that shows up constantly in audits.

1. IAM and Access Control

1.1 Least Privilege

The execution role is the blast radius of the function. Everything the code can reach, it reaches through this role — so every wildcard here is a wildcard for the attacker who finds an injection.

  • Execution role has only the minimum required permissions
  • No wildcard (*) actions in IAM policies
  • Resource ARNs are scoped to specific resources (not *)
  • Separate roles per function (no shared roles)
  • No inline policies (use managed policies)
  • Role trust policy restricts which services can assume the role
# GOOD: Scoped IAM role
iam:
  role:
    statements:
      - Effect: Allow
        Action:
          - s3:GetObject
        Resource:
          - !Sub "arn:aws:s3:::orders-bucket/prod/*"
      - Effect: Allow
        Action:
          - dynamodb:PutItem
        Resource:
          - !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/orders-prod"

# BAD: Wildcard permissions
iam:
  role:
    statements:
      - Effect: Allow
        Action:
          - s3:*           # too broad
          - dynamodb:*     # too broad
        Resource:
          - "*"            # never use wildcard resources

Two practical notes. First, s3:* on a bucket is sometimes acceptable (the bucket itself is the boundary); Resource: "*" never is. Second, the serverless-iam-roles-per-function plugin generates one role per function automatically — without it, Serverless Framework shares a single role across the service, which is the quiet reason most deployments end up over-privileged.

1.2 Cross-Service Access

  • No hardcoded AWS credentials in code
  • No access keys in environment variables
  • Secrets loaded from Secrets Manager / Key Vault / Secret Manager
  • STS assumed roles for cross-account access
  • Temporary credentials with short TTL (1 hour max)
import boto3
import json

def get_secret(secret_name: str, region: str = "us-east-1") -> dict:
    client = boto3.client("secretsmanager", region_name=region)
    response = client.get_secret_value(SecretId=secret_name)
    return json.loads(response["SecretString"])

# Usage — no hardcoded credentials
db_password = get_secret("prod/db-password")["password"]
api_key = get_secret("prod/api-key")["key"]

Call get_secret at module level, outside the handler, so the value is fetched once per execution environment and reused across warm invocations. Calling it inside the handler adds a Secrets Manager API call to every invocation — which is both a latency cost and a real bill at high concurrency. For the full lifecycle — naming, rotation schedules, caching — the secrets management guide goes deeper than this checklist can.

2. Input Validation

2.1 Request Validation

Event-driven functions get input from everywhere: HTTP bodies, queue messages, stream records, event bus payloads, other functions. It’s all untrusted — including events from your own services, because you can’t guarantee the producer wasn’t compromised or buggy.

  • All inputs are validated (body, query params, path params, headers)
  • Schema validation using JSON Schema or equivalent
  • Maximum payload size enforced (e.g., 1MB for APIs)
  • Content-Type header is validated
  • SQL injection prevention (parameterized queries)
  • XSS prevention (output encoding)
import json
from jsonschema import validate, ValidationError

ORDER_SCHEMA = {
    "type": "object",
    "properties": {
        "customerId": {"type": "string", "minLength": 1, "maxLength": 100},
        "items": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100,
            "items": {
                "type": "object",
                "properties": {
                    "productId": {"type": "string", "pattern": "^[a-zA-Z0-9-]+$"},
                    "quantity": {"type": "integer", "minimum": 1, "maximum": 999},
                },
                "required": ["productId", "quantity"],
            },
        },
    },
    "required": ["customerId", "items"],
    "additionalProperties": False,
}

def handler(event, context):
    try:
        body = json.loads(event.get("body", "{}"))
        validate(instance=body, schema=ORDER_SCHEMA)
    except ValidationError as e:
        return {"statusCode": 400, "body": json.dumps({"error": str(e)})}
    except json.JSONDecodeError:
        return {"statusCode": 400, "body": json.dumps({"error": "Invalid JSON"})}

    return process_order(body)

additionalProperties: False is doing more work than it looks: it silently drops fields you didn’t declare, which kills a whole class of mass-assignment bugs where extra JSON properties end up in your database writes. On AWS you can also push schema validation to API Gateway and reject malformed requests before they ever invoke the function — cheaper and faster than validating in code, though you lose the detailed error messages.

2.2 SQL Injection Prevention

# BAD: String concatenation
def get_user(user_id):
    query = f"SELECT * FROM users WHERE id = '{user_id}'"
    return db.execute(query)  # SQL injection!

# GOOD: Parameterized queries
def get_user(user_id):
    query = "SELECT * FROM users WHERE id = %s"
    return db.execute(query, (user_id,))

# GOOD: ORM with built-in parameterization
def get_user(user_id):
    return User.query.filter(User.id == user_id).first()

The f-string version still ships in production codebases every day, usually pasted from a tutorial. If you take one rule from this section: user input never enters a query string, a shell command, an eval/exec/Function() call, or an HTML template without a parameterized path in between. The OWASP remediation checklist covers injection and the rest of the web top 10 with per-item fixes if you need to remediate a finding rather than prevent one.

3. Dependency Security

3.1 Dependency Management

Your function’s dependencies ship inside your deployment package and run with your execution role’s permissions. A compromised transitive dependency isn’t a library bug — it’s code running inside your trust boundary with your credentials.

  • All dependencies are pinned to specific versions
  • npm audit or pip audit passes with no high/critical vulnerabilities
  • Dependencies are scanned in CI/CD pipeline
  • No dependencies from untrusted registries
  • Lockfile is committed and verified
  • SBOM (Software Bill of Materials) is generated
# npm — audit and fix
npm audit --audit-level=high
npm audit fix

# pip — safety check
pip install safety
safety check --full-report

# Snyk scan
npx snyk test --severity-threshold=high

# GitHub Dependabot — .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 10

Auditing on deploy day isn’t enough — new CVEs land against versions that were clean last month. Dependabot (or Renovate) keeps a standing pull request queue so upgrades are small and continuous instead of a panicked mass-bump after an incident. Pin everything, commit the lockfile, and let the bot do the churn.

3.2 Supply Chain Hardening

# .npmrc — restrict registry
registry=https://registry.npmjs.org/
strict-ssl=true

# package.json — lock dependencies
"scripts": {
  "preinstall": "npx lockfile-lint --path package-lock.json --allowed-hosts npm --validate-https"
}

The preinstall hook catches dependency-confusion and typosquat attempts: it verifies the lockfile only resolves packages from the official registry over HTTPS. It’s a cheap gate that fails the install before anything malicious runs. Worth adding if your CI installs dependencies on shared runners, where the install context is the least trusted part of the pipeline.

4. Network Security

4.1 VPC Configuration (AWS Lambda)

Only attach a function to a VPC when it actually touches private resources — RDS, ElastiCache, internal services behind a private load balancer. A VPC-attached function pays for the placement in cold start time and pays literally for NAT Gateway if it needs internet access.

  • Functions that access private resources are in a VPC
  • Security groups restrict inbound/outbound traffic
  • NAT Gateway is used for outbound internet access
  • VPC endpoints for AWS services (S3, DynamoDB, SQS)
  • No public subnets for Lambda functions
# serverless.yml — VPC configuration
functions:
  internalAPI:
    handler: src/handlers/internal.handler
    vpc:
      securityGroupIds:
        - !Ref LambdaSecurityGroup
      subnetIds:
        - !Ref PrivateSubnet1
        - !Ref PrivateSubnet2

resources:
  Resources:
    LambdaSecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
        GroupDescription: "Lambda security group"
        SecurityGroupEgress:
          - IpProtocol: tcp
            FromPort: 443
            ToPort: 443
            CidrIp: 0.0.0.0/0  # HTTPS only

VPC endpoints are the part people miss: without them, a function in a VPC calling S3 or DynamoDB routes through NAT Gateway and you pay NAT pricing for AWS-internal traffic. Gateway endpoints for S3 and DynamoDB are free — there’s no reason not to attach them.

4.2 API Gateway Security

  • API authentication enabled (JWT, API key, IAM)
  • Rate limiting configured
  • CORS restricted to known origins (not *)
  • Request validation enabled
  • WAF rules attached for web-facing APIs
  • TLS 1.2+ enforced
# API Gateway with JWT auth
events:
  - http:
      path: /orders
      method: post
      authorizer:
        type: jwt
        identitySource: $request.header.Authorization
        jwtConfiguration:
          issuer: "https://auth.example.com/"
          audience:
            - "order-service-api"
      cors:
        origin: "https://app.example.com"  # not "*"
        headers:
          - Content-Type
          - Authorization

The function URL feature on Lambda (lambda:InvokeFunctionUrl) is the easiest public exposure to create accidentally — it bypasses API Gateway entirely, so no gateway auth, no WAF, no throttling applies. If you use function URLs, auth type must be AWS_IAM unless the endpoint is genuinely public. Equivalent trap on GCP: allUsers invoker on Cloud Functions.

5. Data Protection

5.1 Encryption

  • Data at rest is encrypted (KMS, AES-256)
  • Data in transit uses TLS 1.2+
  • Environment variables with sensitive data use KMS encryption
  • Database connections use SSL/TLS
  • Secrets are encrypted in Secrets Manager / Key Vault
# Enable SSL for database connections
import psycopg2

conn = psycopg2.connect(
    host=db_host,
    dbname=db_name,
    user=db_user,
    password=db_password,
    sslmode="require",  # enforce TLS
    sslrootcert="/opt/certs/rds-ca.pem",
)

sslmode="require" matters more than people assume: managed databases accept non-TLS connections by default for compatibility, and a function-to-database hop inside a VPC still crosses infrastructure you don’t own. Same story for caches — ElastiCache and MemoryDB both support in-transit encryption and it’s off by default on some configurations.

5.2 PII Handling

  • PII isn’t logged in plain text
  • PII is masked or hashed in logs
  • Data retention policies are defined and enforced
  • GDPR / CCPA compliance verified
  • Data classification labels applied
import hashlib
import re

def mask_pii(data: dict) -> dict:
    """Mask sensitive fields for logging."""
    sensitive_fields = ["email", "phone", "ssn", "creditCard"]
    masked = {}
    for key, value in data.items():
        if key in sensitive_fields:
            masked[key] = hash_value(str(value))
        else:
            masked[key] = value
    return masked

def hash_value(value: str) -> str:
    return hashlib.sha256(value.encode()).hexdigest()[:16]

Logs are where PII goes to leak: CloudWatch retention is long, access is broad, and nobody scrubs them. Hashing the value (rather than dropping the field) keeps logs useful — you can still correlate events for the same user without storing the email itself. If your data classification says a field can’t appear in logs at all, don’t log it, don’t debug-print it “temporarily”, and grep your log groups for it once a quarter.

6. Logging and Monitoring

6.1 Security Logging

  • Authentication events are logged
  • Authorization failures are logged
  • Input validation failures are logged
  • Rate limit violations are logged
  • Security logs are sent to a separate, tamper-proof log group
import json
import logging
from datetime import datetime

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def log_security_event(event_type: str, user_id: str, detail: str):
    logger.info(json.dumps({
        "security_event": True,
        "event_type": event_type,
        "user_id": user_id,
        "detail": detail,
        "timestamp": datetime.utcnow().isoformat(),
    }))

def handler(event, context):
    user = authenticate(event)
    if not user:
        log_security_event("auth_failure", "unknown", "Invalid token")
        return {"statusCode": 401, "body": json.dumps({"error": "Unauthorized"})}

    if not authorize(user, "read:orders"):
        log_security_event("authz_failure", user["id"], "Insufficient permissions")
        return {"statusCode": 403, "body": json.dumps({"error": "Forbidden"})}

    return process_order(event, user)

The security_event: true marker is what makes this grep-able: route those events to a dedicated log group or SIEM stream with tighter access than application logs. If application logs leak — and they leak more often than databases — the security trail shouldn’t leak with them. Note the example above needed datetime imported; the kind of detail that only shows up when you actually run the code.

6.2 Security Alarms

  • Alarm on high error rate (possible attack)
  • Alarm on high 4xx rate (possible scanning)
  • Alarm on unusual invocation patterns
  • Alarm on IAM policy changes
  • Alarm on function code changes outside CI/CD
# CloudWatch alarm for high 4xx rate (potential scanning)
SecurityScanAlarm:
  Type: AWS::CloudWatch::Alarm
  Properties:
    MetricName: 4XXError
    Namespace: AWS/ApiGateway
    Statistic: Sum
    Period: 300
    EvaluationPeriods: 1
    Threshold: 100
    ComparisonOperator: GreaterThanThreshold
    AlarmActions:
      - !Ref SecurityAlertTopic

The last two items are the ones teams forget: code and IAM changes that bypass your pipeline are the highest-signal security events you can detect. On AWS that’s CloudTrail events (UpdateFunctionCode, PutRolePolicy) forwarded to an alarm; anyone deploying outside CI is either a break-glass event or an intruder, and both deserve a page.

7. Compliance Checklist

7.1 General Compliance

  • Data classification: identify what data the function processes
  • Data residency: verify data stays in compliant regions
  • Audit trail: all security-relevant actions are logged
  • Access reviews: IAM roles reviewed quarterly
  • Penetration testing: functions included in scope
  • Incident response: runbook covers serverless-specific scenarios

Compliance items feel like paperwork until the audit lands — then they’re the difference between a conversation and a finding. The quarterly IAM review in particular pays for itself: roles accrete permissions as new functionality ships, and a role that was least-privilege at launch rarely still is a year later.

7.2 Compliance Frameworks

Framework  | Key requirements for serverless
───────────┼──────────────────────────────────────────────────
SOC 2      | Access controls, encryption, audit logging, monitoring
GDPR       | Data minimization, right to erasure, data residency
HIPAA      | PHI encryption, audit trails, BAA with cloud provider
PCI DSS    | No card data in functions, tokenization, network isolation
ISO 27001  | Risk assessment, access control, incident management

PCI DSS deserves a special note: the cheapest way to stay in scope is to keep card data out of functions entirely — send it to a tokenization service (Stripe, Adyen, your payment gateway) and only ever handle the token. The moment a card number crosses a function boundary, the function, its logs, its error traces and its DLQ all come into PCI scope.

Defense in Depth

Layered serverless security model: perimeter auth at the gateway, identity via IAM, input validation, dependency scanning, network isolation, encryption, and detection through logging and alarms

Every layer assumes the one before it eventually fails: auth stops casual traffic, validation stops malformed input, IAM contains the blast radius of code that gets exploited anyway, and logging tells you when all three were bypassed.

When a Security Alarm Fires

Detection without a response plan just produces anxiety at 3 AM. When a security alarm fires, work through it in this order:

  1. Confirm it’s real. Pull the triggering events from CloudTrail (AWS), Activity Log (Azure) or Cloud Audit Logs (GCP). A 4xx spike that’s all OPTIONS preflight is a CORS bug, not a scan. Look at the source IPs, user agents and the specific actions logged.
  2. Check what changed. Diff the last deploy against the previous version and check for IAM or config changes outside CI. Most “attacks” turn out to be a teammate’s deploy, a new integration misbehaving, or a scheduled job that started retrying.
  3. Contain if it’s an incident. Attach a deny policy or set reserved concurrency to 0 to freeze the function, revoke the execution role if credentials may be compromised, and block the source at the WAF. Speed beats elegance here — you can unfreeze once you understand what happened. Take the same approach for event sources: pause the event source mapping rather than deleting it, so you don’t lose the poisoned messages you may need as evidence.
  4. Preserve evidence before fixing. Export the log groups, snapshot the function config, and note the versions involved. Rolling forward destroys the data you need for the post-mortem.
  5. Close the loop in the checklist. Whatever failed has a checkbox somewhere above — mark it broken and add the fix to the next deployment, not just the incident ticket.

Common Security Mistakes

  • Wildcard ARNs “temporarily”. Resource: "*" ships to production for a demo and survives three years. Scope it or it becomes the finding in the next audit.
  • Secrets in plaintext env vars. Visible in the console, in CloudFormation, in serverless.yml in git history, and in every describe-function API response. Secrets Manager or nothing.
  • VPC “for security” on a function that only calls S3. You added cold start latency and a NAT bill while changing nothing about security — S3 traffic works fine over the public endpoint with TLS.
  • Function URL with no auth. One FunctionUrlAuthType: NONE and the endpoint is public on the internet with no gateway in front.
  • Logging the request body for debugging. Congratulations, you built a PII store in CloudWatch with looser access controls than your database.
  • npm audit fix --force before deploy. Blind upgrades break the function an hour before release. Pin, review the diff, upgrade deliberately.
  • A shared execution role for the whole service. One function’s vulnerability becomes every function’s permission set. Per-function roles or accept the coupling consciously.

Companion files: the serverless-security-checklist companion repo has the PII masking helper, the structured security-event logger, the Dependabot config and a security-audit.sh that runs the whole dependency gate in one pass.

See Also

References

Frequently Asked Questions

How do I prevent serverless function code injection?

Validate every input against a strict schema before it touches business logic — including events from queues and streams, not just HTTP. User input never enters a query string, shell command, eval()/exec()/Function() call or HTML template; use parameterized queries and output encoding everywhere. Dependency scanning catches the library-level variants (deserialization gadgets, template injection) that your own validation can't see.

Should serverless functions use a VPC?

Only when they need private resources — RDS, ElastiCache, internal APIs. VPC attachment costs cold start latency and forces a NAT Gateway for internet access, which is real money at volume. A function that only calls S3, DynamoDB or SQS doesn't need a VPC at all: use VPC endpoints if it's already in one, otherwise keep it out. I've seen more latency and billing damage from defensive VPC placement than from any actual network attack it prevented.

How do I rotate secrets for serverless functions?

AWS Secrets Manager does automatic rotation natively for RDS, DocumentDB and Redshift. For everything else, attach a rotation Lambda on a 30-90 day schedule — it updates the secret and lets dependent functions pick up the new value naturally. Two details that bite: functions cache secrets at cold start, so rotation creates a staleness window until environments recycle (re-resolve per invocation for critical keys, or accept ~minutes of lag); and never put secrets in plaintext env vars, where rotation doesn't reach them anyway.

What security tools should I use for serverless functions?

Snyk or Dependabot for dependencies; AWS Config rules for IAM and resource compliance; GuardDuty for anomalous API activity; CloudTrail for the audit trail. serverless-iam-roles-per-function fixes the shared-role problem at the framework level. AWS Access Analyzer catches unintended public access on functions and buckets — run it before go-live and leave it on. For endpoint testing, OWASP ZAP against the API Gateway stage covers what the checklist can't.

How do I secure environment variables in serverless functions?

Non-secret config goes in SSM Parameter Store (free, KMS-encrypted) or plain env vars — that's fine. Actual secrets go in Secrets Manager and get fetched at runtime via the SDK, cached at module level for a few minutes. Plaintext env vars leak through the console, CloudFormation templates, Terraform state and describe-function responses — everyone assumes they're hidden because they're not printed in the code, and they're wrong.