securing-serverless-functions
This skill covers security hardening for serverless compute platforms including AWS Lambda, Azure Functions, and Google Cloud Functions. It addresses least privilege IAM roles, dependency vulnerability scanning, secrets management integration, input validation, function URL authentication, and runtime monitoring to protect against injection attacks, credential theft, and supply chain compromises.
What this skill does
# Securing Serverless Functions
## When to Use
- When deploying Lambda functions or Azure Functions with access to sensitive data or cloud APIs
- When auditing existing serverless workloads for overly permissive IAM roles
- When integrating serverless functions into a DevSecOps pipeline with automated security scanning
- When hardcoded secrets or vulnerable dependencies are discovered in function code
- When establishing runtime monitoring for serverless workloads to detect injection or credential theft
**Do not use** for container-based compute security (see securing-kubernetes-on-cloud), for API Gateway configuration (see implementing-cloud-waf-rules), or for serverless architecture design decisions.
## Prerequisites
- AWS Lambda, Azure Functions, or GCP Cloud Functions with deployment access
- CI/CD pipeline with dependency scanning tools (npm audit, Snyk, Dependabot)
- AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for secrets management
- CloudWatch, Application Insights, or Cloud Logging for function monitoring
## Workflow
### Step 1: Enforce Least Privilege IAM Roles
Assign each Lambda function a dedicated IAM role with permissions scoped to only the specific resources it accesses. Never share IAM roles across functions.
```bash
# Create a least-privilege role for a specific Lambda function
aws iam create-role \
--role-name order-processor-lambda-role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
# Attach a scoped policy (not AmazonDynamoDBFullAccess)
aws iam put-role-policy \
--role-name order-processor-lambda-role \
--policy-name order-processor-policy \
--policy-document '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["dynamodb:PutItem", "dynamodb:GetItem"],
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Orders"
},
{
"Effect": "Allow",
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/order-processor:*"
},
{
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:order-api-key-*"
}
]
}'
```
### Step 2: Eliminate Hardcoded Secrets
Replace plaintext credentials in environment variables with references to secrets management services. Use Lambda extensions or SDK calls to retrieve secrets at runtime.
```python
# INSECURE: Hardcoded credentials in environment variable
# DB_PASSWORD = os.environ['DB_PASSWORD'] # Stored as plaintext in Lambda config
# SECURE: Retrieve from AWS Secrets Manager with caching
import boto3
from botocore.exceptions import ClientError
import json
_secret_cache = {}
def get_secret(secret_name):
if secret_name in _secret_cache:
return _secret_cache[secret_name]
client = boto3.client('secretsmanager')
response = client.get_secret_value(SecretId=secret_name)
secret = json.loads(response['SecretString'])
_secret_cache[secret_name] = secret
return secret
def lambda_handler(event, context):
db_creds = get_secret('production/database/credentials')
db_host = db_creds['host']
db_password = db_creds['password']
# Use credentials securely
```
```bash
# Enable encryption at rest for Lambda environment variables
aws lambda update-function-configuration \
--function-name order-processor \
--kms-key-arn arn:aws:kms:us-east-1:123456789012:key/key-id
```
### Step 3: Scan Dependencies for Vulnerabilities
Integrate automated dependency scanning into the CI/CD pipeline to catch vulnerable packages before deployment.
```bash
# npm audit for Node.js Lambda functions
cd lambda-function/
npm audit --audit-level=high
npm audit fix
# Snyk scanning in CI/CD pipeline
snyk test --severity-threshold=high
snyk monitor --project-name=order-processor-lambda
# pip-audit for Python Lambda functions
pip-audit -r requirements.txt --desc on --fix
# Scan Lambda deployment package with Trivy
trivy fs --severity HIGH,CRITICAL ./lambda-package/
```
```yaml
# GitHub Actions CI/CD security scanning
name: Lambda Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install dependencies
run: npm ci
- name: Run npm audit
run: npm audit --audit-level=high
- name: Snyk vulnerability scan
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
- name: Scan with Semgrep for code vulnerabilities
uses: returntocorp/semgrep-action@v1
with:
config: p/owasp-top-ten
```
### Step 4: Implement Input Validation
Validate and sanitize all event input data to prevent injection attacks including SQL injection, command injection, and NoSQL injection through Lambda event sources.
```python
import re
import json
from jsonschema import validate, ValidationError
# Define expected input schema
ORDER_SCHEMA = {
"type": "object",
"properties": {
"orderId": {"type": "string", "pattern": "^[a-zA-Z0-9-]{1,36}$"},
"customerId": {"type": "string", "pattern": "^[a-zA-Z0-9]{1,20}$"},
"amount": {"type": "number", "minimum": 0.01, "maximum": 999999.99},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]}
},
"required": ["orderId", "customerId", "amount", "currency"],
"additionalProperties": False
}
def lambda_handler(event, context):
# Validate API Gateway event body
try:
body = json.loads(event.get('body', '{}'))
validate(instance=body, schema=ORDER_SCHEMA)
except (json.JSONDecodeError, ValidationError) as e:
return {
'statusCode': 400,
'body': json.dumps({'error': 'Invalid input', 'details': str(e)})
}
# Safe to proceed with validated input
order_id = body['orderId']
# Use parameterized queries for database operations
```
### Step 5: Configure Function URL and API Gateway Authentication
Secure function invocation endpoints with proper authentication. Never expose Lambda function URLs without IAM or Cognito authentication.
```bash
# Secure Lambda function URL with IAM auth (not NONE)
aws lambda create-function-url-config \
--function-name order-processor \
--auth-type AWS_IAM \
--cors '{
"AllowOrigins": ["https://app.company.com"],
"AllowMethods": ["POST"],
"AllowHeaders": ["Content-Type", "Authorization"],
"MaxAge": 3600
}'
# API Gateway with Cognito authorizer
aws apigateway create-authorizer \
--rest-api-id abc123 \
--name CognitoAuth \
--type COGNITO_USER_POOLS \
--provider-arns "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_EXAMPLE"
```
### Step 6: Enable Runtime Monitoring and Logging
Configure GuardDuty Lambda Network Activity Monitoring and CloudWatch structured logging to detect anomalous function behavior.
```bash
# Enable GuardDuty Lambda protection
aws guardduty update-detector \
--detector-id <detector-id> \
--features '[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}]'
# Configure Lambda to use structured logging
aws lambda update-function-configuration \
--function-name order-processor \
--logging-config '{"LogFormat": "JSON", "ApplicationLogLevel": "INFO", "SystemLogLevel": "WARN"}'
```
## Key Concepts
| Term | Definition |
|------|------------|
| Cold Start | Initial function invocation that includes container provisioning, increasing latency and creating a window where cached secrets may not be available |
| Event Injection | Attack where malicious input is embedded in Lambda event data from API Gateway, S3, SQS, or other event sources to exploit the function |
| Execution Role |Related in Cloud & DevOps
appbuilder-action-scaffolder
IncludedCreate, implement, deploy, and debug Adobe Runtime actions with consistent layout, validation, and error handling. Use this skill whenever the user needs to add actions to an App Builder project, understand action structure (params, response format, web/raw actions), configure actions in the manifest, use App Builder SDKs (State, Files, Events, database), deploy and invoke actions via CLI, debug action issues, or implement patterns such as webhook receivers, custom event providers, journaling consumers, large payload redirects, action sequence pipelines, and Asset Compute workers. Also trigger when users mention serverless functions in Adobe context, action logging, IMS authentication for actions, or cron-style scheduled actions.
orchestrating-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. Use this skill when the user needs a multi-step Data Cloud pipeline, cross-phase troubleshooting, or data space and data kit management. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase sf data360 workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching phase-specific skill), the task is STDM/session tracing/parquet telemetry (use observing-agentforce), standard CRM SOQL (use querying-soql), or Apex implementation (use generating-apex).
github-project-automation
IncludedAutomate GitHub repository setup with CI/CD workflows, issue templates, Dependabot, and CodeQL security scanning. Includes 12 production-tested workflows and prevents 18 errors: YAML syntax, action pinning, and configuration. Use when: setting up GitHub Actions CI/CD, creating issue/PR templates, enabling Dependabot or CodeQL scanning, deploying to Cloudflare Workers, implementing matrix testing, or troubleshooting YAML indentation, action version pinning, secrets syntax, runner versions, or CodeQL configuration. Keywords: github actions, github workflow, ci/cd, issue templates, pull request templates, dependabot, codeql, security scanning, yaml syntax, github automation, repository setup, workflow templates, github actions matrix, secrets management, branch protection, codeowners, github projects, continuous integration, continuous deployment, workflow syntax error, action version pinning, runner version, github context, yaml indentation error
sf-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase `sf data360` workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching sf-datacloud-* skill), the task is STDM/session tracing/parquet telemetry (use sf-ai-agentforce-observability), standard CRM SOQL (use sf-soql), or Apex implementation (use sf-apex).
fabric-cli
IncludedUse this skill for Fabric.so CLI workflows with the `fabric` terminal command: diagnose/install/login, search or browse a Fabric library, save notes/links/files, create folders, ask the Fabric AI assistant, manage tasks/workspaces, generate shell completion, check subscription usage, produce JSON output, and use Fabric as persistent agent memory. Do not use for Microsoft Fabric/Azure/Power BI `fab`, Daniel Miessler's Fabric framework, Python Fabric SSH, Fabric.js, or textile/fashion fabric.
lark
IncludedLark/Feishu CLI skills: lark-cli operations for docs, markdown, sheets, base, calendar, im, mail, task, okr, drive, wiki, slides, whiteboard, apps, approval, attendance, contact, vc, minutes, event. Use when the user needs to operate Lark/Feishu resources via lark-cli, send messages, manage documents, spreadsheets, calendars, tasks, OKRs, deploy web pages, or any Feishu/Lark workspace operations.