# Authentication & Authorization

Comprehensive security model for user authentication and resource authorization in Twig AI.

## Authentication

Verify user identity through multiple methods.

### Supported Methods

**1. Email/Password**

* Standard username/password
* Secure password hashing (bcrypt)
* Password requirements: 8+ characters, special chars
* Account lockout after failed attempts

**2. Single Sign-On (SSO)**

* SAML 2.0
* OAuth 2.0 / OpenID Connect
* Azure AD / Microsoft Entra
* Google Workspace
* Okta, OneLogin, custom IdPs

**3. Multi-Factor Authentication (MFA)**

* Time-based OTP (TOTP)
* SMS codes
* Authenticator apps
* Required for admin roles (recommended)

**4. API Keys**

* Programmatic access
* Bearer token authentication
* Scoped permissions
* Rotatable

## Authorization

Control what authenticated users can do.

### Role-Based Access Control (RBAC)

Four primary roles:

* **Super Admin**: Complete control
* **Admin**: Day-to-day management
* **Manager**: Team-level control
* **User**: Standard access

See [User Permissions & Roles](/product/administration/user-permissions.md) for complete matrix.

### Resource-Level Permissions

Control access to specific resources:

**Agents:**

* View: Can see agent exists
* Use: Can query agent
* Edit: Can modify configuration
* Manage: Full control

**Data Sources:**

* View: Can see source
* Connect: Can add to agents
* Edit: Can modify settings
* Process: Can trigger sync

**Groups:**

* Member: Part of group
* Manager: Can add/remove members
* Admin: Full group control

### Attribute-Based Access Control (ABAC)

Enterprise feature for fine-grained control:

```typescript
{
  "policy": {
    "resource": "agent:agent-123",
    "action": "use",
    "conditions": [
      {"user.role": "manager"},
      {"user.department": "support"},
      {"time.hour": {">=": 9, "<=": 17}}
    ]
  }
}
```

## Security Features

### Session Management

**Settings:**

```typescript
{
  "session": {
    "timeout": 28800,        // 8 hours
    "renewOnActivity": true,
    "maxConcurrent": 3,      // Max 3 sessions per user
    "enforceIPBinding": false
  }
}
```

**Security Controls:**

* Secure session cookies (httpOnly, secure, sameSite)
* Session invalidation on logout
* Automatic timeout after inactivity
* Concurrent session limits

### Token Security

**Access Tokens:**

* Short-lived (1 hour default)
* JWT format with signature
* Includes user ID, org ID, roles
* Cannot be modified

**Refresh Tokens:**

* Long-lived (30 days)
* Securely stored
* Can be revoked
* Used to obtain new access tokens

### Password Security

**Requirements:**

* Minimum 8 characters
* At least one uppercase letter
* At least one lowercase letter
* At least one number
* At least one special character

**Storage:**

* Bcrypt hashing (cost factor: 12)
* Salted per user
* Never stored in plain text
* Never logged

### API Key Security

**Generation:**

* Cryptographically random
* Minimum 32 characters
* Prefix indicates type (sk\_live\_, sk\_test\_)

**Storage:**

* Hashed in database
* Only shown once at creation
* Cannot be retrieved later

**Permissions:**

* Scoped to specific operations
* Can be revoked instantly
* Audit log of all usage

## Access Control Patterns

### Least Privilege

**Example:**

```
Support Agent User:
✅ Can use support agents
✅ Can view their interactions
❌ Cannot create agents
❌ Cannot view all users
❌ Cannot access billing

Reasoning: Only what's needed for their job
```

### Separation of Duties

**Example:**

```
Agent Creator:
✅ Can create and configure agents
❌ Cannot deploy to production

Production Approver:
❌ Cannot create agents
✅ Can deploy to production

Reasoning: Prevents unilateral changes
```

### Time-Based Access

```typescript
{
  "accessControl": {
    "allowedHours": {
      "start": 9,
      "end": 17,
      "timezone": "America/New_York"
    },
    "allowedDays": [1, 2, 3, 4, 5] // Mon-Fri
  }
}
```

## Audit Logging

All authentication and authorization events are logged:

**Logged Events:**

* Login attempts (success/failure)
* Logout events
* Role changes
* Permission grants/revokes
* API key creation/deletion
* Resource access attempts
* Failed authorization attempts

**Log Format:**

```json
{
  "timestamp": "2024-01-15T10:30:00Z",
  "event": "LOGIN_SUCCESS",
  "userId": "user-123",
  "email": "user@example.com",
  "ipAddress": "192.168.1.1",
  "userAgent": "Mozilla/5.0...",
  "mfaUsed": true,
  "sessionId": "session-456"
}
```

**Retention:** 90 days (configurable for Enterprise)

## Security Best Practices

### 1. Enable MFA

✅ Require for admins ✅ Encourage for all users ✅ Use authenticator apps (more secure than SMS) ❌ Don't rely solely on passwords

### 2. Regular Access Reviews

✅ Quarterly user access reviews ✅ Remove inactive accounts ✅ Verify role assignments ✅ Audit API key usage ❌ Don't grant permanent access without review

### 3. Principle of Least Privilege

✅ Grant minimum necessary permissions ✅ Use groups for management ✅ Time-limit contractor access ❌ Don't make everyone admin

### 4. Monitor Failed Attempts

✅ Alert on repeated failures ✅ Automatic account lockout ✅ Investigate suspicious patterns ❌ Don't ignore security logs

## Troubleshooting

### Cannot Login

**Check:**

1. Correct email/password
2. Account is active
3. MFA code is correct
4. Not locked out
5. SSO is configured properly

### Unauthorized API Requests

**Check:**

1. API key format correct
2. Key hasn't been revoked
3. Key has required scopes
4. Request to correct endpoint
5. Organization ID matches

### Permission Denied

**Check:**

1. User has required role
2. Resource exists and user has access
3. Group memberships are correct
4. No time-based restrictions apply

## Next Steps

* [SSO Integration](/product/security/sso-integration.md) - Enterprise authentication
* [Data Privacy](/product/security/data-privacy.md) - Data protection
* [Security Best Practices](/product/security/best-practices.md) - Harden security
* [User Permissions](/product/administration/user-permissions.md) - Manage roles


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.twig.so/product/security/authentication-authorization.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
