AWS Lambda static analysis tool for resource dependency detection and IAM policy generation
Project description
Lambda Analyzer
A powerful static analysis tool that automatically infers AWS Lambda resource dependencies and generates optimal IAM policies from your Python code. Say goodbye to manually crafting complex SAM templates and overly permissive IAM policies.
๐ Features
- ๐ Smart Code Analysis: Static analysis of Python Lambda functions to detect AWS service usage
- ๐ก๏ธ Least Privilege IAM: Automatically generates minimal IAM policies based on actual API calls
- ๐ Template Generation: Creates complete SAM/CloudFormation templates from code analysis
- ๐ฏ Resource Detection: Identifies required AWS services, triggers, and environment variables
- ๐ Visual Reports: Generates comprehensive analysis reports with recommendations
- ๐ง CLI & Python API: Use as a command-line tool or integrate into your workflow
๐ฆ Installation
pip install lambda-analyzer
Or install from source:
git clone https://github.com/DinoYu95/lambda-analyzer.git
cd lambda-analyzer
pip install -e .
๐ฏ Quick Start
Analyze a Lambda Function
# Analyze a single Lambda function
lambda-analyzer analyze my_lambda.py
# Analyze entire project
lambda-analyzer analyze ./src --recursive
# Generate SAM template
lambda-analyzer generate-template --input ./src --output template.yaml
Python API
from lambda_analyzer import LambdaAnalyzer
analyzer = LambdaAnalyzer()
result = analyzer.analyze_file('my_lambda.py')
print(f"AWS Services detected: {result.services}")
print(f"IAM Policy: {result.iam_policy}")
๐ Usage Examples
Example 1: Simple S3 Lambda
Input Code (s3_handler.py):
import boto3
import json
def lambda_handler(event, context):
s3_client = boto3.client('s3')
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
response = s3_client.get_object(Bucket=bucket, Key=key)
content = response['Body'].read()
return {
'statusCode': 200,
'body': json.dumps({'processed': True})
}
Generated Output:
$ lambda-analyzer analyze multi_service.py
๐ Analysis Results for multi_service.py
=====================================
๐ Detected AWS Services:
โข S3 (Simple Storage Service)
๐ก Inferred Triggers:
โข S3 Event Notification (from event['Records'][0]['s3'])
๐ก๏ธ Required IAM Permissions:
โข s3:GetObject
๐ Generated IAM Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "*"
}
]
}
๐ก Recommendations:
โข Consider restricting S3 resource to specific buckets
โข Add error handling for missing objects
Example 2: Multi-Service Lambda
Input Code (multi_service.py):
import boto3
import os
from datetime import datetime
def lambda_handler(event, context):
# DynamoDB operations
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
# S3 operations
s3_client = boto3.client('s3')
# SNS notifications
sns_client = boto3.client('sns')
# Process data
item = {
'id': event['user_id'],
'timestamp': datetime.now().isoformat(),
'data': event['data']
}
# DynamoDB write
table.put_item(Item=item)
# S3 backup
s3_client.put_object(
Bucket=os.environ['BACKUP_BUCKET'],
Key=f"backup/{item['id']}.json",
Body=str(item)
)
# Send notification
sns_client.publish(
TopicArn=os.environ['SNS_TOPIC'],
Message=f"Processed user {event['user_id']}"
)
return {'statusCode': 200}
Generated SAM Template:
$ lambda-analyzer generate-template multi_service.py --format sam
# Generated template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MultiServiceFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: multi_service.lambda_handler
Runtime: python3.9
Environment:
Variables:
TABLE_NAME: !Ref UserTable
BACKUP_BUCKET: !Ref BackupBucket
SNS_TOPIC: !Ref NotificationTopic
Policies:
- DynamoDBWritePolicy:
TableName: !Ref UserTable
- S3WritePolicy:
BucketName: !Ref BackupBucket
- SNSPublishMessagePolicy:
TopicName: !Ref NotificationTopic
UserTable:
Type: AWS::DynamoDB::Table
Properties:
# Table configuration will be prompted interactively
BackupBucket:
Type: AWS::S3::Bucket
NotificationTopic:
Type: AWS::SNS::Topic
๐ ๏ธ Configuration
Create a .lambda-analyzer.yaml configuration file in your project root:
# Analysis settings
analysis:
python_version: "3.9"
include_patterns: ["*.py"]
exclude_patterns: ["test_*.py", "tests/"]
# Template generation
template:
format: sam # sam, cloudformation, cdk
runtime: python3.9
timeout: 30
memory: 512
# Resource configuration
resources:
dynamodb:
tables:
- name: users-table
hash_key: user_id
hash_key_type: S
billing_mode: PAY_PER_REQUEST
s3:
buckets:
- name: backup-bucket
versioning: true
encryption: true
# IAM settings
iam:
least_privilege: true
resource_constraints: true
๐ง Advanced Features
Interactive Resource Configuration
# Launch interactive setup wizard
lambda-analyzer init
? What type of trigger does your Lambda use? S3 Event
? Which S3 bucket? my-source-bucket
? What DynamoDB tables are used? users-table, sessions-table
? Configure table schema for users-table? Yes
? Primary key: user_id (String)
? Sort key: None
? Global Secondary Indexes? email-index
Security Analysis
# Perform security analysis
lambda-analyzer security-check ./src
๐ Security Analysis Results
===========================
โ ๏ธ High Risk Issues:
โข Wildcard resource permissions detected in S3 policy
โข Missing encryption for DynamoDB table
โก Medium Risk Issues:
โข Lambda function has overly broad IAM permissions
โ
Recommendations:
โข Specify exact S3 bucket ARNs instead of wildcards
โข Enable encryption at rest for DynamoDB
โข Use resource-based policies where possible
Performance Insights
# Analyze performance implications
lambda-analyzer performance ./src
๐ Performance Analysis
======================
๐ Optimization Opportunities:
โข Cold start: ~2.1s (boto3 client initialization)
โข Memory usage: Estimated 128MB (current allocation: 512MB)
โข Dependencies: 15 imports, 3 heavy libraries
๐ก Recommendations:
โข Consider connection pooling for database clients
โข Use Lambda Layers for shared dependencies
โข Reduce memory allocation to 256MB
โข Initialize clients outside handler for reuse
๐ API Reference
LambdaAnalyzer Class
from lambda_analyzer import LambdaAnalyzer
analyzer = LambdaAnalyzer(config_path='.lambda-analyzer.yaml')
# Analyze single file
result = analyzer.analyze_file('handler.py')
# Analyze directory
results = analyzer.analyze_directory('./src', recursive=True)
# Generate templates
template = analyzer.generate_template(
results,
format='sam',
output_path='template.yaml'
)
AnalysisResult Object
class AnalysisResult:
file_path: str
services: List[str] # ['s3', 'dynamodb', 'sns']
api_calls: Dict[str, List[str]] # {'s3': ['get_object', 'put_object']}
iam_policy: Dict # Generated IAM policy JSON
environment_variables: List[str] # Required env vars
triggers: List[Dict] # Inferred event sources
security_issues: List[SecurityIssue] # Potential security problems
recommendations: List[str] # Optimization suggestions
๐งช Running Tests
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest tests/ -v
# Run with coverage
pytest tests/ --cov=lambda_analyzer --cov-report=html
# Type checking
mypy lambda_analyzer/
# Linting
black lambda_analyzer/ tests/
flake8 lambda_analyzer/ tests/
Development Setup
# Clone repository
git clone https://github.com/DinoYu95/lambda-analyzer.git
cd lambda-analyzer
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install in development mode
pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install
Architecture Overview
lambda_analyzer/
โโโ core/
โ โโโ analyzer.py # Main analysis engine
โ โโโ ast_parser.py # Python AST parsing
โ โโโ service_detector.py # AWS service detection
โ โโโ policy_generator.py # IAM policy generation
โโโ templates/
โ โโโ sam.py # SAM template generator
โ โโโ cloudformation.py # CloudFormation generator
โ โโโ cdk.py # CDK generator
โโโ cli/
โ โโโ main.py # CLI entry point
โ โโโ commands/ # CLI command implementations
โ โโโ interactive.py # Interactive wizards
โโโ utils/
โ โโโ aws_mappings.py # AWS API to IAM permission mappings
โ โโโ patterns.py # Common Lambda patterns
โ โโโ security.py # Security analysis
โโโ tests/
โโโ fixtures/ # Test Lambda functions
โโโ unit/ # Unit tests
โโโ integration/ # Integration tests
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- AWS SAM team for inspiration
- Chalice framework for IAM policy generation concepts
- The Python AST module for making static analysis possible
๐ Support
- ๐ง Email Support
Made with โค๏ธ for the serverless community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file lambda_analyzer-1.0.1.tar.gz.
File metadata
- Download URL: lambda_analyzer-1.0.1.tar.gz
- Upload date:
- Size: 54.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
20bdf5082afdbb83378be94381535f6f511cb468680e7b6b652cd45b8606148b
|
|
| MD5 |
fa0764c3658652899eec9c15e4315c7e
|
|
| BLAKE2b-256 |
8b17b060fbb13d0daa6880c2bda01fd33ecd79f4ce89b748a88e3d453ba76703
|
File details
Details for the file lambda_analyzer-1.0.1-py3-none-any.whl.
File metadata
- Download URL: lambda_analyzer-1.0.1-py3-none-any.whl
- Upload date:
- Size: 66.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
26d31757e962eb8948d5b4d5e8e4d6026f3e48e04b82f93700af872c606e83d1
|
|
| MD5 |
088b6c4e68f6f1926495f1fd43226375
|
|
| BLAKE2b-256 |
204335f48818bb3545843601599336e5541d60b4bc87c23005240703aca2aab2
|