# License Server

A comprehensive microservices-based license management system for software licensing, validation, and analytics.

## Features

- **License Management**: Create, update, and manage software licenses
- **Hardware-based Validation**: Bind licenses to specific devices
- **Offline Support**: Generate offline validation tokens
- **Analytics**: Track usage patterns and detect anomalies
- **Rate Limiting**: Protect APIs with configurable rate limits
- **Event-driven Architecture**: Real-time event processing with RabbitMQ
- **Caching**: Redis-based caching for improved performance
- **Security**: JWT authentication, API key management, and audit logging

## Architecture

The system consists of four microservices:

1. **Auth Service** (Port 5001): JWT token management and API authentication
2. **License API** (Port 5002): License validation and activation
3. **Analytics Service** (Port 5003): Usage analytics and anomaly detection
4. **Admin API** (Port 5004): License administration and management

## Quick Start

### Prerequisites

- Docker and Docker Compose
- Make (optional, for using Makefile commands)
- Python 3.11+ (for local development)

### Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd lizenzserver
```

2. Copy environment variables:
```bash
cp .env.example .env
# Edit .env with your configuration
```

3. Build and start services:
```bash
make build
make up
```

Or without Make:
```bash
docker-compose build
docker-compose up -d
```

4. Initialize the database:
```bash
make init-db
```

### Verify Installation

Check service health:
```bash
curl http://localhost:5001/health
curl http://localhost:5002/health
curl http://localhost:5003/health
curl http://localhost:5004/health
```

## Usage

### Creating a License

```bash
curl -X POST http://localhost:5004/api/v1/admin/licenses \
  -H "X-Admin-API-Key: your-admin-key" \
  -H "Content-Type: application/json" \
  -d '{
    "customer_id": "cust-123",
    "max_devices": 5,
    "expires_in_days": 365,
    "features": ["premium", "support"]
  }'
```

### Validating a License

```bash
curl -X POST http://localhost:5002/api/v1/license/validate \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "license_key": "LIC-XXXXXXXXXXXX",
    "hardware_id": "device-123"
  }'
```

## API Documentation

Detailed API documentation is available in [API_DOCUMENTATION.md](API_DOCUMENTATION.md).

## Configuration

### Environment Variables

Key configuration options in `.env`:

- `DB_PASSWORD`: PostgreSQL password
- `REDIS_PASSWORD`: Redis password
- `JWT_SECRET`: Secret key for JWT tokens
- `ADMIN_API_KEY`: Admin API authentication key
- `FLASK_ENV`: Flask environment (development/production)

### Rate Limiting

Default rate limits:
- 60 requests per minute
- 1000 requests per hour
- 10000 requests per day

Configure per API key in the database.

## Development

### Running Locally

1. Install dependencies:
```bash
pip install -r requirements.txt
```

2. Set environment variables:
```bash
export DATABASE_URL=postgresql://user:pass@localhost:5432/licenses
export REDIS_URL=redis://localhost:6379
export RABBITMQ_URL=amqp://guest:guest@localhost:5672
```

3. Run a service:
```bash
python services/license_api/app.py
```

### Testing

Run tests:
```bash
make test
```

### Database Migrations

The database schema is in `init.sql`. Apply migrations:
```bash
docker-compose exec postgres psql -U license_admin -d licenses -f /path/to/migration.sql
```

## Monitoring

### Logs

View logs for all services:
```bash
make logs
```

View logs for specific service:
```bash
make logs-auth
make logs-license
make logs-analytics
make logs-admin
```

### Metrics

Services expose Prometheus metrics at `/metrics` endpoint.

### RabbitMQ Management

Access RabbitMQ management UI at http://localhost:15672
- Username: admin (or configured value)
- Password: admin_password (or configured value)

## Security

### Best Practices

1. **Change default passwords** in production
2. **Use HTTPS** in production (configure in nginx.conf)
3. **Rotate API keys** regularly
4. **Monitor anomalies** through the analytics service
5. **Set up IP whitelisting** for admin endpoints
6. **Enable audit logging** for compliance

### API Key Management

Create API keys through the Auth Service:
```bash
curl -X POST http://localhost:5001/api/v1/auth/api-key \
  -H "X-Admin-Secret: your-admin-secret" \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "My Application",
    "allowed_endpoints": ["license.validate", "license.activate"]
  }'
```

## Troubleshooting

### Common Issues

1. **Services not starting**: Check logs with `docker-compose logs <service-name>`
2. **Database connection errors**: Ensure PostgreSQL is healthy and credentials are correct
3. **Rate limit errors**: Check rate limit configuration and API key limits
4. **Cache misses**: Verify Redis connection and TTL settings

### Health Checks

All services provide health endpoints:
- Auth: http://localhost:5001/health
- License: http://localhost:5002/health
- Analytics: http://localhost:5003/health
- Admin: http://localhost:5004/health

## Contributing

1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to the branch
5. Create a Pull Request

## License

[Your License Here]

## Support

For support, please contact [support@example.com] or create an issue in the repository.