> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions

> Monitor and analyze user connections, queries, and activities in real-time

> [!TIP]
>
> Sessions are logical groupings of logs sent during a user session - they're primarily a UI convenience to make your life easier. All the underlying data is still available in the Logs page, but sessions provide a more intuitive way to view and analyze user activities.

## What are Sessions?

Sessions represent active or completed connections between users and protected resources through Formal Connectors or the Formal Endpoint. Every database query, SSH command, API call, or Kubernetes exec is captured as part of a session, providing complete visibility into data access.

All non-HTTP traffic through a connector is associated with a **session.** Each TCP connection is an individual session. Sessions may be long-lived and have many **events** occur during the duration of the session.

Sessions are the foundation of Formal's audit trail and real-time monitoring capabilities.

## Session Events

Each session contains multiple event types that track the connection lifecycle:

* **`session-start`**: Emitted when a TCP connection is opened
* **`session-login`**: Occurs when a user successfully authenticates to a resource
* **`session-login-failed`**: Occurs when authentication fails
* **`session-end`**: Occurs when the TCP connection is closed
* **`session-analysis`**: For SSH and Kubernetes, analyzes the session to compute a risk score

Many more event types (such as `request`, `admin-policy-action`, and `stream-event`) can also occur within a session. These events are visible in [the Logs page](https://app.formal.ai/logs) for a session. Filter by `session.id` in [the Logs page](https://app.formal.ai/logs?q=session.id%3A*) to view all events that occur during a session.

## Session States

> [tab] Active Sessions
>
> **Currently in progress** connections that you can monitor and terminate in
> real-time. Active sessions show:
>
> * **User identity and authentication method**
> * **Connected resource and protocol**
> * **Duration and start time**
> * **Real-time query/command stream**
> * **Evaluated policies and enforcement actions**
>
> Active sessions have not had their `session-end` event occur yet.

> [tab] Completed Sessions
>
> **Finished connections** with full audit records for review and compliance.
> Completed sessions provide:
>
> * **Complete query/command history**
> * **Session recordings (SSH, Kubernetes)**
> * **Policy evaluation results**
> * **Performance metrics**
> * **Risk analysis and anomaly detection**
>
> Completed sessions have a `session-end` event.

## Session Details by Protocol

### Database Sessions (PostgreSQL, MySQL, MongoDB, etc.)

View all queries executed during a session:

* **Query text**: Full SQL/NoSQL command
* **Execution time**: Query duration
* **Rows affected**: Number of records touched
* **Policy actions**: Masking, denials, warnings
* **Parameters**: Bind variables and arguments

![PostgreSQL session details](https://mintcdn.com/formal/z9GNtynV1YHUDYCN/assets/images/completed_session_postgres.png?fit=max\&auto=format\&n=z9GNtynV1YHUDYCN\&q=85\&s=52cba11093b936c2b421b15c455a41c3)

### SSH Sessions

Complete recordings of command-line interactions with pause, rewind, and fast-forward controls:

* **Full terminal recording**: Replay exactly what the user saw
* **Command extraction**: List of all executed commands
* **Risk scoring**: AI-powered analysis (1-5 risk level)
* **Session summary**: Natural language description of activities

![SSH session recording](https://mintcdn.com/formal/z9GNtynV1YHUDYCN/assets/images/recordings.png?fit=max\&auto=format\&n=z9GNtynV1YHUDYCN\&q=85\&s=b5a87028dc6579312f04f1cd2a517fd6)

> [!TIP]
>
> Risk level is determined by analyzing commands, file access patterns,
> privilege escalation, and destructive actions. Level 5 indicates highest risk.

### Kubernetes Sessions (kubectl exec)

Records all `kubectl exec` interactions:

* **Pod and container**: Which pod was accessed
* **Commands executed**: Full command history
* **User identity**: Who initiated the exec session
* **Risk analysis**: Automated threat detection

### HTTP/API Sessions

Captures REST API calls and responses:

* **Request path and method**: GET /users, POST /api/data
* **Headers**: Authorization, content-type, custom headers
* **Request/response body**: Full payloads
* **Status codes**: 200, 401, 403, etc.
* **Policy enforcement**: Rate limiting, authentication, filtering

## Session Analysis

Formal can automatically analyze session recordings to provide insights:

![Session analysis](https://mintcdn.com/formal/z9GNtynV1YHUDYCN/assets/images/analyze_session.png?fit=max\&auto=format\&n=z9GNtynV1YHUDYCN\&q=85\&s=48b9f26572c0a0c8567b5e2e0b15c8bc)

### AI-Powered Analysis

For SSH and Kubernetes sessions, Formal provides:

1. **Session Summary**: Natural language description of what happened
2. **Command List**: Extracted and categorized commands
3. **Risk Level**: Scored 1 (lowest) to 5 (highest) based on:
   * Privilege escalation attempts
   * File modifications or deletions
   * Network reconnaissance
   * Credential access
   * Known attack patterns

### Risk Score Framework

Session analysis includes a Risk Score in real time. The score is based on the commands executed and the actions performed during the session:

**1 – Low Risk**
Basic informational commands (e.g., `ls`, `pwd`), viewing non-sensitive files with `cat`, standard navigation and user-space operations

**2 – Mild Risk**
File modifications in user space, basic software installations from trusted sources, non-sensitive configuration changes

**3 – Moderate Risk**
System configuration modifications, database operations, user management activities, service restarts or modifications

**4 – High Risk**
Privilege escalation attempts, access or modification of sensitive files, suspicious downloads or external connections, unusual system probing or reconnaissance

**5 – Critical Risk**
Execution of malicious payloads, data exfiltration attempts, backdoor creation or modification, credential theft attempts, suspicious encryption or decryption activities

> [!NOTE]
>
> Risk scoring helps prioritize which sessions to review during security audits
> or incident response.

## Monitoring Sessions

### View Sessions

Navigate to [Sessions](https://app.formal.ai/sessions) in the Control Plane to see:

* **All sessions**: Active and completed across all users and resources
* **Real-time updates**: Active sessions refresh automatically
* **Session details**: Click any session to view full details

### Filtering

Filter sessions by:

* **User** and **End User**: Specific user or machine identity
* **Resource**: Which database, API, or server, by name, type, or hostname
* **Technology**: PostgreSQL, SSH, HTTP, etc.
* **Connector** and **Space**: Where the session ran
* **Session**: Client or server IP address
* **Time range**: Last hour, day, week, or custom

Use the left sidebar for quick filters or craft advanced queries for complex searches. Status appears in the session table and risk level in session details, but you can't filter by either.

### Advanced Search

Sessions can be filtered by various parameters using the menu on the left side of the page or by crafting a more sophisticated Quickwit query. This flexibility allows for targeted monitoring and analysis of user sessions based on specific criteria.

Session queries use the same fields as [Logs](https://docs.formal.ai/docs/guides/observability/logs.md#log-schema-reference). They only match each session's `session-login` event. Fields from other events, such as query text or risk scores, return no sessions.

Example queries:

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
# Find all sessions by user "alice"
user.formal.user.email:"alice@example.com"

# SSH sessions
resource.technology:ssh

# Sessions on a specific resource
resource.name:"production-postgres"
```

Search other session events from [Logs](https://docs.formal.ai/docs/guides/observability/logs.md#advanced-search):

```text theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
# High-risk SSH sessions (risk score 4 or 5)
resource.technology:ssh AND event_type:session-analysis AND session.analysis.data.riskscore:>=4

# Failed authentication attempts
event_type:session-login-failed

# Queries accessing specific table
event_type:request AND (request.query.received:"FROM users" OR request.query.received:"JOIN users")
```

## Terminating Active Sessions

If a session is identified as active and there's a need to immediately halt the user's access or activities, Formal allows administrators to terminate the session directly from the UI. This immediate action can be crucial in preventing unauthorized data access or mitigating potential security breaches in real-time.

**1. View active sessions**

Navigate to the Sessions page and find a session with the **Active** status

**2. Identify session**

Click on the suspicious session to view details

**3. Terminate**

Click **Terminate** in the session details, then confirm **Terminate Session**

**4. Verify**

Confirm the session status changes to Completed

> [!WARNING]
>
> Terminating a session immediately disconnects the user. Any in-flight queries
> or commands will be aborted.

## Session Metadata

Every session captures rich metadata:

| Field | Description |
| - | - |
| **Session ID** | Unique identifier |
| **User** | Formal user identity |
| **Resource** | Connected database, API, or server |
| **Protocol** | PostgreSQL, SSH, HTTP, etc. |
| **Start Time** | When connection began |
| **End Time** | When connection closed (completed only) |
| **Duration** | Total session length |
| **Queries/Commands** | Number of actions performed |
| **Policies Applied** | Which policies evaluated |
| **Actions Taken** | Denials, masking, rate limits |
| **Client IP** | Source IP address |
| **Client Application** | psql, Looker, ssh client, etc. |

## Use Cases

> [accordion] Security Audits
>
> Review completed sessions to ensure no unauthorized access or suspicious
> queries. Export session logs for compliance reporting.

> [accordion] Incident Response
>
> When a security incident is detected, search sessions to find:
>
> * What data was accessed
> * Which users were involved
> * Timeline of activities
> * Attack patterns

> [accordion] Compliance Reporting
>
> Demonstrate to auditors:
>
> * Who accessed what data and when
> * That policies were enforced
> * Complete audit trails for sensitive data

> [accordion] User Behavior Analytics
>
> Understand access patterns:
>
> * Which teams access which resources
> * Query complexity and frequency
> * Off-hours access patterns
> * Anomalous behavior detection

> [accordion] Real-Time Threat Detection
>
> Monitor active sessions for:
>
> * Privilege escalation attempts
> * Mass data exfiltration
> * Unusual query patterns
> * Unauthorized access attempts

## Best Practices

> [accordion] Set Up Alerting
>
> Configure alerts for high-risk sessions, failed authentications, or policy
> violations. Integrate with Slack, PagerDuty, or your SIEM.

> [accordion] Regular Security Reviews
>
> Schedule weekly or monthly reviews of high-risk sessions and policy denials to
> identify potential threats early.

> [accordion] Analyze Session Recordings
>
> For SSH and Kubernetes sessions, review AI-generated summaries and risk scores
> to prioritize investigations.

> [accordion] Export Session Data
>
> Regularly export session logs to your data warehouse or SIEM for long-term
> retention and advanced analytics.

> [accordion] Monitor Active Sessions
>
> Keep an eye on active sessions during critical maintenance windows or
> security incidents to catch issues in real-time.

## Next Steps

> [card] [View Logs](https://docs.formal.ai/docs/guides/observability/logs.md)
>
> See all queries and API calls across sessions

> [card] [Write Policies](https://docs.formal.ai/docs/guides/policies/introduction.md)
>
> Enforce rules based on session context


## Related topics

- [Get a session](https://docs.formal.ai/api-reference/corev1sessionsservice/get-a-session.md)
- [Create session termination](https://docs.formal.ai/api-reference/corev1sessionsservice/create-session-termination.md)
- [List session aggregations](https://docs.formal.ai/api-reference/corev1sessionsservice/list-session-aggregations.md)
- [List sessions V2](https://docs.formal.ai/api-reference/corev1sessionsservice/list-sessions-v2.md)
- [Delete human user sessions](https://docs.formal.ai/api-reference/corev1userservice/delete-human-user-sessions.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.