# Tara Secrets Management

Terraform module for managing Tara meditation platform secrets in AWS Secrets
Manager.

## Overview

This module creates and manages all secrets required for the Tara meditation
platform:

- **Database credentials** - PostgreSQL connection with auto-generated passwords
- **Redis credentials** - Cache authentication
- **JWT secrets** - Access and refresh token signing
- **Encryption keys** - Data and content encryption
- **OAuth credentials** - Apple Sign In, Google Sign In
- **Push notifications** - APNs (iOS), FCM (Android)
- **Analytics** - Mixpanel, Amplitude
- **Crash reporting** - Sentry
- **In-App Purchases** - Apple App Store, Google Play, Stripe
- **Storage** - S3/MinIO, CDN signing
- **AI services** - OpenAI, Anthropic
- **External services** - Email (SendGrid), SMS (Twilio)
- **App signing** - iOS certificates, Android keystore

## Features

- **KMS encryption** - All secrets encrypted with a dedicated KMS key
- **Auto-generation** - Secure random passwords/keys generated automatically
- **Multi-region replication** - Secrets can be replicated for DR
- **IAM policies** - Ready-to-use policy documents for ECS tasks
- **ECS integration** - Pre-formatted secret references for task definitions

## Usage

### Basic Usage

```hcl
module "tara_secrets" {
  source = "../../infra/terraform/secrets/tara"

  environment = "production"
  region      = "us-east-1"

  # Database
  database_config = {
    host     = "tara-db.xxxx.us-east-1.rds.amazonaws.com"
    database = "tara"
    username = "tara"
  }

  # Enable services
  apple_signin_config = {
    enabled     = true
    client_id   = "app.tara"
    team_id     = "XXXXXXXXXX"
    key_id      = "XXXXXXXXXX"
    private_key = file("path/to/key.p8")
  }

  mixpanel_config = {
    enabled = true
    token   = "xxxx"
  }
}
```

### Using Outputs in ECS

```hcl
# Get secrets for ECS task definition
module "tara_secrets" {
  source = "../../infra/terraform/secrets/tara"
  # ...
}

resource "aws_ecs_task_definition" "tara_api" {
  # ...

  container_definitions = jsonencode([{
    name  = "tara-api"
    image = "tara-api:latest"

    secrets = [
      module.tara_secrets.ecs_secrets.database_url,
      module.tara_secrets.ecs_secrets.jwt_access_secret,
      module.tara_secrets.ecs_secrets.jwt_refresh_secret,
      module.tara_secrets.ecs_secrets.redis_password,
    ]
  }])
}

# Attach IAM policy for secret access
resource "aws_iam_role_policy" "tara_secrets_access" {
  name   = "tara-secrets-access"
  role   = aws_iam_role.tara_task_role.id
  policy = module.tara_secrets.secrets_read_policy_json
}
```

## Directory Structure

```
infra/terraform/secrets/tara/
├── versions.tf           # Terraform and provider versions
├── variables.tf          # Input variables
├── main.tf               # Secret resources
├── outputs.tf            # Output values
├── README.md             # This file
└── examples/
    ├── development.tfvars.example
    ├── staging.tfvars.example
    └── production.tfvars.example
```

## Deployment

### Prerequisites

1. AWS credentials configured
2. Terraform >= 1.6.0
3. S3 backend bucket (for remote state)

### Initialize

```bash
cd infra/terraform/secrets/tara

# Initialize with local state (development)
terraform init

# Initialize with remote state (staging/production)
terraform init \
  -backend-config="bucket=oshun-terraform-state" \
  -backend-config="key=tara/secrets/production/terraform.tfstate" \
  -backend-config="region=us-east-1" \
  -backend-config="dynamodb_table=oshun-terraform-locks" \
  -backend-config="encrypt=true"
```

### Plan and Apply

```bash
# Development
cp examples/development.tfvars.example development.tfvars
# Edit development.tfvars with your values
terraform plan -var-file=development.tfvars
terraform apply -var-file=development.tfvars

# Production (use CI/CD or secure workstation)
terraform plan -var-file=production.tfvars
terraform apply -var-file=production.tfvars
```

## Inputs

| Name                 | Description              | Type        | Default          | Required |
| -------------------- | ------------------------ | ----------- | ---------------- | -------- |
| environment          | Deployment environment   | string      | -                | yes      |
| region               | AWS region               | string      | "us-east-1"      | no       |
| name_prefix          | Secret name prefix       | string      | "tara"           | no       |
| create_kms_key       | Create dedicated KMS key | bool        | true             | no       |
| database_config      | Database credentials     | object      | See variables.tf | no       |
| redis_config         | Redis credentials        | object      | See variables.tf | no       |
| jwt_config           | JWT secrets              | object      | See variables.tf | no       |
| apple_signin_config  | Apple Sign In            | object      | disabled         | no       |
| google_signin_config | Google Sign In           | object      | disabled         | no       |
| apns_config          | Apple Push Notifications | object      | disabled         | no       |
| fcm_config           | Firebase Cloud Messaging | object      | disabled         | no       |
| mixpanel_config      | Mixpanel analytics       | object      | disabled         | no       |
| sentry_config        | Sentry crash reporting   | object      | disabled         | no       |
| apple_iap_config     | Apple In-App Purchase    | object      | disabled         | no       |
| google_play_config   | Google Play IAP          | object      | disabled         | no       |
| stripe_config        | Stripe payments          | object      | disabled         | no       |
| s3_config            | S3 storage               | object      | enabled          | no       |
| openai_config        | OpenAI API               | object      | disabled         | no       |
| anthropic_config     | Anthropic API            | object      | disabled         | no       |
| custom_secrets       | Custom secrets           | map(object) | {}               | no       |

## Outputs

| Name                     | Description                               |
| ------------------------ | ----------------------------------------- |
| kms_key_arn              | KMS key ARN for secrets encryption        |
| database_secret_arn      | Database credentials secret ARN           |
| redis_secret_arn         | Redis credentials secret ARN              |
| jwt_access_secret_arn    | JWT access token secret ARN               |
| jwt_refresh_secret_arn   | JWT refresh token secret ARN              |
| all_secret_arns          | Map of all secret ARNs                    |
| secrets_read_policy_json | IAM policy for secret access              |
| ecs_secrets              | Pre-formatted ECS task definition secrets |
| secrets_summary          | Summary of created secrets                |

## Security Best Practices

1. **Never commit secrets** - Use `.gitignore` to exclude `*.tfvars` files
2. **Use remote state** - Store Terraform state in encrypted S3 with DynamoDB
   locking
3. **Rotate secrets** - Enable rotation for database credentials
4. **Least privilege** - Use the generated IAM policy to grant minimal access
5. **Audit access** - Enable CloudTrail logging for Secrets Manager
6. **Encrypt at rest** - Use dedicated KMS key (enabled by default)
7. **Replicate for DR** - Set `replica_regions` for production

## Environment-Specific Configuration

### Development

- Disable most external services
- Use local MinIO instead of S3
- Skip KMS key creation to reduce costs
- Use short recovery window (7 days)

### Staging

- Enable all services in sandbox/test mode
- Use test API keys
- Mirror production architecture
- Use staging bucket names

### Production

- Enable all services in production mode
- Use dedicated KMS key
- Enable multi-region replication
- Use maximum recovery window (30 days)
- Enable secret rotation

## Troubleshooting

### Secret not found

```bash
# List secrets matching prefix
aws secretsmanager list-secrets --filter Key=name,Values=/tara/production
```

### KMS decrypt error

```bash
# Check KMS key permissions
aws kms describe-key --key-id alias/tara-secrets-production
```

### Rotation failed

```bash
# Check rotation Lambda logs
aws logs tail /aws/lambda/tara-secrets-rotation
```

## Related Documentation

- [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/)
- [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
- [Tara Environment Configuration](../../../../tara/config/environments/)
