# Feature Specification: Multi-User Authentication and Authorization

**Feature Branch**: `016-multi-user-auth`
**Created**: 2026-01-26
**Status**: Draft
**Input**: User description: "Нужна поддержка многопользовательского логина. Нужно, чтобы пользователи могли логинится по связке логин/пароль, поддержка adfs, разделение прав доступа по плагинам"

## Clarifications

### Session 2026-01-26
- Q: Permission Model Structure? → A: RBAC (Role-Based Access Control) - Permissions assigned to Roles, Users assigned to Roles.
- Q: Initial Admin Provisioning? → A: CLI Command/Script - Explicit script to create the first admin user.
- Q: ADFS User Role Assignment? → A: AD Group Mapping - Login requires valid AD group membership; AD groups map to local Roles (e.g., 'superset_admin' -> 'Admin').
- Q: Token Management? → A: JWT (JSON Web Tokens) - Stateless, scalable, standard for SPAs.
- Q: Persistence Layer? → A: Dedicated SQLite DB (`auth.db`) - Relational storage for Users, Roles, Permissions.
- Q: Switching Auth Providers? → A: Dual Support - Both Local and ADFS login options are available simultaneously on the login page.

## User Scenarios & Testing *(mandatory)*

### User Story 1 - Local User Authentication (Priority: P1)

As a user, I want to log in using a username and password so that I can securely access the application.

**Why this priority**: Basic authentication is the foundation for multi-user support and is required before implementing more complex auth methods or permissions.

**Independent Test**: Can be fully tested by creating a local user account and successfully logging in/out without any external dependencies.

**Acceptance Scenarios**:

1. **Given** a registered user, **When** they enter valid credentials on the login page, **Then** they are redirected to the dashboard and receive a session token.
2. **Given** a registered user, **When** they enter invalid credentials, **Then** they see an error message "Invalid username or password".
3. **Given** an authenticated user, **When** they click logout, **Then** their session is terminated and they are redirected to the login page.

---

### User Story 2 - Plugin-Based Access Control (Priority: P1)

As an administrator, I want to assign specific plugin access rights to users so that I can control who can use sensitive tools (e.g., Backup, Migration).

**Why this priority**: Security is a core requirement. Without granular permissions, all authenticated users would have full administrative access, which defeats the purpose of multi-user support.

**Independent Test**: Create two users with different permissions (e.g., User A has access to "Backup", User B does not). Verify User A can access the Backup tool while User B receives a 403 Forbidden error.

**Acceptance Scenarios**:

1. **Given** a user with "Backup" plugin permission, **When** they navigate to the Backup tool, **Then** the page loads successfully.
2. **Given** a user WITHOUT "Backup" plugin permission, **When** they navigate to the Backup tool, **Then** they are denied access (UI hides the link, API returns 403).
3. **Given** an administrator, **When** they edit a user's permissions, **Then** the changes take effect immediately or upon next login.

---

### User Story 4 - Role Management (Priority: P1)

As an administrator, I want to create and manage roles with specific permissions so that I can easily assign standard access sets to users.

**Why this priority**: Essential for scalable user management. Assigning individual permissions to every user is tedious and error-prone.

**Acceptance Scenarios**:

1. **Given** an administrator, **When** they navigate to the Role Management page, **Then** they see a list of all system roles.
2. **Given** an administrator, **When** they create a new role "Auditor" with "READ" permission on "Logs", **Then** the role is saved and available for assignment.
3. **Given** an administrator, **When** they update a role's permissions, **Then** all users with that role effectively gain/lose those permissions.

**Why this priority**: Security is a core requirement. Without granular permissions, all authenticated users would have full administrative access, which defeats the purpose of multi-user support.

**Independent Test**: Create two users with different permissions (e.g., User A has access to "Backup", User B does not). Verify User A can access the Backup tool while User B receives a 403 Forbidden error.

**Acceptance Scenarios**:

1. **Given** a user with "Backup" plugin permission, **When** they navigate to the Backup tool, **Then** the page loads successfully.
2. **Given** a user WITHOUT "Backup" plugin permission, **When** they navigate to the Backup tool, **Then** they are denied access (UI hides the link, API returns 403).
3. **Given** an administrator, **When** they edit a user's permissions, **Then** the changes take effect immediately or upon next login.

---

### User Story 3 - ADFS Integration (Priority: P2)

As a corporate user, I want to log in using my organization's ADFS credentials so that I don't have to manage a separate password.

**Why this priority**: Essential for enterprise environments but dependent on the core authentication infrastructure being in place (Story 1).

**Independent Test**: Configure the application with a test ADFS provider (or mock). Verify a user can initiate the SSO flow and be logged in automatically.

**Acceptance Scenarios**:

1. **Given** a configured ADFS provider, **When** a user clicks "Login with ADFS", **Then** they are redirected to the identity provider.
2. **Given** a successful ADFS authentication, **When** the user returns to the app, **Then** a local user session is created/matched and they are logged in.
3. **Given** a new ADFS user, **When** they log in for the first time, **Then** a local user record is automatically created (JIT provisioning) with default permissions.

---

### Edge Cases

- What happens when an ADFS user's account is disabled in the local system? (Should block login even if ADFS succeeds)
- How does the system handle concurrent sessions? (Allow or restrict?)
- What happens if a plugin is removed but users still have permission for it? (Graceful handling/cleanup)
- What happens if the ADFS server is unreachable? (Fallback to local login if applicable, or clear error message)

## Requirements *(mandatory)*

### Functional Requirements

- **FR-001**: System MUST support local user authentication via username and password.
- **FR-002**: System MUST support authentication via ADFS (Active Directory Federation Services) using standard federation protocols.
- **FR-003**: System MUST provide a web-based interface to manage users (Create, Read, Update, Delete) - restricted to administrators.
- **FR-004**: System MUST implement Role-Based Access Control (RBAC) where permissions are assigned to Roles, and Roles are assigned to Users.
- **FR-005**: System MUST enforce permissions at the server level for all plugin execution requests.
- **FR-006**: System MUST enforce permissions at the user interface level (hide navigation items/buttons for unauthorized plugins).
- **FR-007**: System MUST securely store local user credentials.
- **FR-008**: System MUST support Just-In-Time (JIT) provisioning for ADFS users ONLY if they belong to a mapped AD group.
- **FR-009**: System MUST provide a CLI utility to create an initial administrator account to prevent lockout during first deployment.
- **FR-010**: System MUST provide a web-based interface for configuring mappings between Active Directory Groups and local System Roles.
- **FR-011**: System MUST use JWT (JSON Web Tokens) for API session management.
- **FR-012**: System MUST persist authentication and authorization data in a dedicated SQLite database (`auth.db`).
- **FR-013**: System MUST provide a unified login interface supporting both Local (Username/Password) and ADFS (SSO Button) authentication methods simultaneously.
- **FR-014**: System MUST provide a web-based interface to manage Roles (Create, Update, Delete) and assign permissions to them.

### Key Entities

- **User**: Represents a system user. Attributes: ID, Username, Email, PasswordHash, AuthSource (Local/ADFS), IsActive, Roles (List[RoleID]).
- **Role**: Named collection of permissions. Attributes: ID, Name, Description, Permissions (List[Permission]).
- **Permission**: Represents access capability. Attributes: ResourceID (e.g., Plugin ID), Action (Execute, Read).
- **ADGroupMapping**: Configuration mapping AD Group names to Role IDs.

## Success Criteria *(mandatory)*

### Measurable Outcomes

- **SC-001**: Administrators can successfully create a new local user and assign specific plugin permissions in under 2 minutes.
- **SC-002**: Users without permission for a specific plugin are denied access 100% of the time when attempting to use its functions.
- **SC-003**: ADFS login flow completes successfully for valid credentials and maps to the correct local user identity.
- **SC-004**: User interface dynamically updates to show only permitted tools for the logged-in user.

## Assumptions

- The application currently has a simple or placeholder authentication mechanism.
- "Plugin access" refers to the ability to use the plugin's functionality and view its interface.
- A default administrator account will be available upon initial system setup to prevent lockout.
