> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Arvo-AI/aurora/llms.txt
> Use this file to discover all available pages before exploring further.

# Token Management

> Manage user credentials and cloud provider tokens

## Overview

Aurora provides token management capabilities for both user authentication and cloud provider credentials. This includes password management and secure token storage using HashiCorp Vault.

## Change Password

### Endpoint

```
POST /api/auth/change-password
```

Allows authenticated users to change their password.

### Headers

<ParamField header="X-User-ID" type="string" required>
  User ID from Auth.js session
</ParamField>

### Request Body

<ParamField body="currentPassword" type="string" required>
  User's current password
</ParamField>

<ParamField body="newPassword" type="string" required>
  New password (minimum 8 characters)
</ParamField>

### Response

<ResponseField name="message" type="string">
  Success message confirming password change
</ResponseField>

### Example Request

```bash cURL theme={null}
curl -X POST http://localhost:5080/api/auth/change-password \
  -H "Content-Type: application/json" \
  -H "X-User-ID: user-123" \
  -d '{
    "currentPassword": "oldPassword123",
    "newPassword": "newSecurePassword456"
  }'
```

```javascript JavaScript theme={null}
const response = await fetch('http://localhost:5080/api/auth/change-password', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-User-ID': 'user-123',
  },
  body: JSON.stringify({
    currentPassword: 'oldPassword123',
    newPassword: 'newSecurePassword456',
  }),
});

const data = await response.json();
```

```python Python theme={null}
import requests

response = requests.post(
    'http://localhost:5080/api/auth/change-password',
    headers={
        'Content-Type': 'application/json',
        'X-User-ID': 'user-123'
    },
    json={
        'currentPassword': 'oldPassword123',
        'newPassword': 'newSecurePassword456'
    }
)

data = response.json()
```

### Example Response

<CodeGroup>
  ```json Success (200) theme={null}
  {
    "message": "Password changed successfully"
  }
  ```

  ```json Invalid Current Password (401) theme={null}
  {
    "error": "Current password is incorrect"
  }
  ```

  ```json Missing Authentication (401) theme={null}
  {
    "error": "Authentication required"
  }
  ```

  ```json Password Too Short (400) theme={null}
  {
    "error": "New password must be at least 8 characters"
  }
  ```

  ```json User Not Found (404) theme={null}
  {
    "error": "User not found"
  }
  ```
</CodeGroup>

## Cloud Provider Token Management

Aurora securely manages cloud provider credentials using HashiCorp Vault.

### Token Storage Architecture

1. **Vault Storage**: Credentials stored in Vault's KV v2 engine
2. **Database References**: Only secret references stored in PostgreSQL
3. **Token Refresh**: Automatic refresh for OAuth2 tokens (GCP, Azure)
4. **Encryption**: All credentials encrypted at rest in Vault

### Supported Providers

* **GCP**: OAuth2 tokens with automatic refresh
* **AWS**: IAM role assumption with STS credentials
* **Azure**: Service principal credentials
* **Other Providers**: Grafana, Datadog, Netdata, Scaleway, Tailscale, Splunk, Slack, Coroot, Bitbucket, ThousandEyes

### Token Storage

Tokens are stored using the `store_tokens_in_db` function:

```python theme={null}
from utils.auth.token_management import store_tokens_in_db

# Store GCP OAuth2 tokens
store_tokens_in_db(
    user_id="user-123",
    token_data={
        "access_token": "ya29.a0...",
        "refresh_token": "1//0g...",
        "expires_at": 1234567890,
        "email": "user@example.com"
    },
    provider="gcp"
)

# Store AWS credentials
store_tokens_in_db(
    user_id="user-123",
    token_data={
        "role_arn": "arn:aws:iam::123456789012:role/AuroraAccess",
        "external_id": "unique-external-id"
    },
    provider="aws"
)

# Store Azure credentials
store_tokens_in_db(
    user_id="user-123",
    token_data={
        "tenant_id": "tenant-uuid",
        "client_id": "client-uuid",
        "client_secret": "secret-value"
    },
    provider="azure",
    subscription_name="Production Subscription",
    subscription_id="sub-uuid"
)
```

### Token Retrieval

Retrieve tokens using the `get_token_data` function:

```python theme={null}
from utils.auth.token_management import get_token_data

# Get tokens for a specific provider
token_data = get_token_data(
    user_id="user-123",
    provider="gcp"
)

# Get tokens from multiple providers (first match)
token_data = get_token_data(
    user_id="user-123",
    provider=["gcp", "aws", "azure"]
)
```

### Token Refresh

OAuth2 tokens are automatically refreshed:

```python theme={null}
from utils.auth.token_refresh import refresh_token_if_needed

# Automatically refresh if expiring within 5 minutes
token_data = refresh_token_if_needed(
    user_id="user-123",
    provider="gcp"
)
```

### Vault Configuration

Configure Vault using environment variables:

```bash theme={null}
# Vault server address
VAULT_ADDR=http://vault:8200

# Vault access token
VAULT_TOKEN=hvs.your-vault-token

# KV mount path (default: aurora)
VAULT_KV_MOUNT=aurora

# KV base path (default: users)
VAULT_KV_BASE_PATH=users
```

### Secret References

Vault secrets are referenced in the database:

```
vault:kv/data/aurora/users/aurora-dev-user123-gcp-token
```

The secret reference format:

* `vault:` prefix indicates Vault storage
* `kv/data/` is the KV v2 API path
* `aurora/users/` is the base path
* `aurora-dev-user123-gcp-token` is the secret name

## Security Best Practices

### Password Security

1. **Strong Passwords**: Enforce minimum 8-character passwords
2. **Bcrypt Hashing**: Use bcrypt with automatic salt generation
3. **No Plaintext**: Never store or log passwords in plaintext
4. **Rate Limiting**: Implement rate limiting on password change endpoint

### Token Security

1. **Vault Storage**: Store all credentials in Vault, not database
2. **Encryption**: Enable encryption at rest in Vault
3. **Access Control**: Use Vault policies to restrict access
4. **Secret Rotation**: Regularly rotate credentials
5. **Audit Logging**: Enable Vault audit logs

## Error Handling

| Status Code | Description                        |
| ----------- | ---------------------------------- |
| 200         | Operation successful               |
| 400         | Invalid request (validation error) |
| 401         | Authentication required or invalid |
| 404         | User or resource not found         |
| 500         | Internal server error              |

## Related Documentation

<CardGroup cols={2}>
  <Card title="Authentication Overview" icon="shield" href="/api/auth/overview">
    Learn about authentication
  </Card>

  <Card title="Login" icon="right-to-bracket" href="/api/auth/login">
    Authenticate users
  </Card>

  <Card title="Vault Integration" icon="vault" href="/security/vault">
    HashiCorp Vault setup
  </Card>
</CardGroup>
