# AWS Account Billing Architecture via Stripe EventBridge

## Overview

This document describes the billing system for passing through AWS account costs to customers using Stripe's EventBridge integration. The system is designed to be simple, event-driven, and require minimal maintenance.

## Architecture Components

### 1. Infrastructure (CloudFormation)

The billing infrastructure is deployed as a CloudFormation stack in the management account:

- **Secrets Manager**: Stores Stripe API key securely
- **DynamoDB Table**: Maps Stripe customers to AWS accounts
- **Lambda Function**: Handles Stripe events and calculates AWS costs
- **EventBridge Rule**: Listens for Stripe events (invoice.created)
- **IAM Role**: Provides Lambda with necessary permissions

### 2. Event Flow

```
Stripe → EventBridge → Lambda → Cost Explorer API → Stripe Invoice
```

1. **Monthly Trigger**: Stripe automatically creates invoices for subscriptions
2. **Event Reception**: EventBridge receives `invoice.created` event
3. **Cost Calculation**: Lambda queries AWS Cost Explorer for account costs
4. **Invoice Update**: Lambda adds AWS costs (with markup) to Stripe invoice
5. **Payment Collection**: Stripe handles payment, retries, and receipts

### 3. CLI Commands

The `ai-org` CLI provides two simple commands for billing management:

```bash
# One-time Stripe product setup
ai-org billing setup

# Link AWS account to Stripe customer
ai-org billing link <account-id> <stripe-customer-id>
```

## Implementation Details

### Lambda Function Logic

The Lambda function performs the following steps when `invoice.created` event is received:

1. **Fetch Stripe API Key**: Retrieves key from AWS Secrets Manager
2. **Get Customer Mapping**: Looks up AWS accounts in DynamoDB
3. **Calculate Costs**: Queries Cost Explorer API for the billing period
4. **Apply Markup**: Adds 20% markup to AWS costs
5. **Update Invoice**: Creates line item in Stripe invoice

### Security

- **Secrets Management**: Stripe API key stored in AWS Secrets Manager, never in environment variables
- **Runtime Retrieval**: Lambda fetches secret at runtime, not at deployment
- **Least Privilege**: Lambda has minimal IAM permissions (read secret, DynamoDB, Cost Explorer)
- **No Hardcoding**: No sensitive data in CloudFormation templates or code

### Cost Calculation

- **Source**: AWS Cost Explorer API
- **Metrics**: UnblendedCost (actual AWS charges)
- **Period**: Previous 30 days from invoice date
- **Aggregation**: Sum all linked accounts for a customer
- **Markup**: 20% added to cover operational costs

## Setup Instructions

### Prerequisites

1. AWS Management account access
2. Stripe account with API keys
3. EventBridge partner event source enabled

### Initial Setup

1. **Set Stripe API Keys in `.env`**:
   ```bash
   # For testing (recommended to start)
   TEST_STRIPE_SECRET_KEY=sk_test_xxx

   # For production (when ready)
   STRIPE_SECRET_KEY=sk_live_xxx
   ```

2. **Deploy Infrastructure**:
   ```bash
   make deploy  # Includes billing stack deployment
   ```

3. **Configure Stripe Products**:
   ```bash
   ai-org billing setup
   ```

4. **Enable EventBridge in Stripe (Manual - Required)**:

   **In Stripe Dashboard:**
   - Navigate to **Developers** → **Events**
   - Click **Add endpoint** → Select **AWS EventBridge**
   - Enter your AWS Account ID (shown by `ai-org billing setup`)
   - Select region: `us-east-1`
   - Select events to send:
     - `invoice.created` (required)
     - `invoice.finalized`
     - `invoice.payment_succeeded`
     - `invoice.payment_failed`
     - `customer.subscription.created`
     - `customer.subscription.deleted`
   - Click **Add destination**
   - Copy the **Partner event source name** (e.g., `aws.partner/stripe.com/acct_xxx/evt-src-xxx`)

   **In AWS Console:**
   - Go to **Amazon EventBridge** → **Partner event sources**
   - Find your Stripe source (it should appear within a few minutes)
   - Click on it and select **Associate with event bus**
   - Choose **Associate with default event bus**
   - Click **Associate**

   The EventBridge Rule in your CloudFormation stack will automatically start receiving events.

### Customer Onboarding

1. **Create Stripe Customer**:
   - Use Stripe Dashboard or API to create customer
   - Set up subscription with monthly billing

2. **Link AWS Accounts**:
   ```bash
   ai-org billing link 558232169845 cus_xxx  # Staging account
   ai-org billing link 458894893282 cus_xxx  # Production account
   ```

## Testing

### Local Development

1. Use test Stripe API key in `.env`:
   ```
   STRIPE_SECRET_KEY=sk_test_xxx
   ```

2. Test with Stripe CLI:
   ```bash
   stripe trigger invoice.created
   ```

### Production Verification

1. Check Lambda logs in CloudWatch
2. Verify DynamoDB entries
3. Monitor Stripe Dashboard for invoice updates

## Maintenance

### Regular Tasks

- **Monitor**: Check CloudWatch logs for Lambda errors
- **Update Mappings**: Use `ai-org billing link` for new accounts
- **Rotate Keys**: Update secret in Secrets Manager as needed

### Troubleshooting

**Invoice not updated with AWS costs:**
- Check Lambda CloudWatch logs
- Verify customer mapping in DynamoDB
- Ensure Cost Explorer has data for the period

**Lambda permission errors:**
- Verify IAM role has required permissions
- Check Secrets Manager access
- Ensure EventBridge can invoke Lambda

## Cost Estimates

- **AWS Infrastructure**: ~$5/month
  - Lambda: <$1 (runs monthly per customer)
  - DynamoDB: <$1 (minimal storage)
  - Secrets Manager: $0.40/month
  - Cost Explorer API: $0.01 per request

- **Stripe Fees**: Standard payment processing
  - 2.9% + $0.30 per successful charge

## Future Enhancements

Potential improvements (not currently implemented):

- Cost breakdown by AWS service
- Custom markup percentages per customer
- Usage alerts and notifications
- Self-service customer portal
- Detailed cost reports in S3
