Skip to main content

AWS Lambda static analysis tool for resource dependency detection and IAM policy generation

Project description

Lambda Analyzer

Python License: MIT Code style: black

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


Made with โค๏ธ for the serverless community

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lambda_analyzer-1.0.1.tar.gz (54.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lambda_analyzer-1.0.1-py3-none-any.whl (66.3 kB view details)

Uploaded Python 3

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

Hashes for lambda_analyzer-1.0.1.tar.gz
Algorithm Hash digest
SHA256 20bdf5082afdbb83378be94381535f6f511cb468680e7b6b652cd45b8606148b
MD5 fa0764c3658652899eec9c15e4315c7e
BLAKE2b-256 8b17b060fbb13d0daa6880c2bda01fd33ecd79f4ce89b748a88e3d453ba76703

See more details on using hashes here.

File details

Details for the file lambda_analyzer-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for lambda_analyzer-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 26d31757e962eb8948d5b4d5e8e4d6026f3e48e04b82f93700af872c606e83d1
MD5 088b6c4e68f6f1926495f1fd43226375
BLAKE2b-256 204335f48818bb3545843601599336e5541d60b4bc87c23005240703aca2aab2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page