(security:healthcare-rbac)=
# Healthcare RBAC Guide

This guide explains the role-based access control (RBAC) system for SeqsLab's Healthcare module, which manages genetic test samples through their complete lifecycle—from patient registration to final clinical report sign-off.

```{contents}
:local:
:depth: 3
```

## Overview

### What is Healthcare RBAC?

Healthcare RBAC in SeqsLab implements a **state-based permission model** specifically designed for clinical genetic testing workflows. Unlike general RBAC where permissions are static, healthcare permissions change dynamically based on where a sample is in its lifecycle.

This ensures:
- **Regulatory Compliance**: Meets CLIA/CAP requirements for clinical laboratory workflows
- **Quality Control**: Enforces proper review and approval gates
- **Separation of Duties**: Different roles handle different workflow stages
- **Audit Trail**: Complete tracking of who did what at each stage

### The Sample Lifecycle

Every genetic test sample moves through a defined lifecycle with four main stages:

```
┌─────────┐    ┌──────────┐    ┌────────┐    ┌────────┐
│ PENDING │───►│ ANALYSIS │───►│ REVIEW │───►│ REPORT │───►✅ CLOSED
└─────────┘    └──────────┘    └────────┘    └────────┘
     │              │              │              │
     └──────────────┴──────────────┴──────────────┘
  Data Entry    Wet/Dry Lab    QC Review    Sign-off
```

**Additional States:**
- **CLOSED**: Report signed out (final state)
- **REJECTED**: Sample stopped due to quality issues (can be rolled back)

```{important}
Permissions are **state-dependent**: what you can do with a sample depends on its current lifecycle stage.
```

## Healthcare Roles

SeqsLab Healthcare defines five specialized roles, each responsible for specific stages of the sample lifecycle.

### Role Summary Table

| Role | Primary Stage | Key Responsibility | Can Create Reports? |
|------|--------------|-------------------|-------------------|
| **ReporterDataEntryOperator** | PENDING | Enter patient and sample data | ❌ No |
| **MedicalTechnologist** | PENDING → ANALYSIS → REVIEW | Manage wet-lab operations and data uploads | ❌ No |
| **BioinformaticsScientist** | ANALYSIS → REVIEW | Run analysis pipelines and create interpretations | ❌ No |
| **LaboratorySupervisor** | REVIEW → REPORT | Approve reviews and create reports | ✅ **Yes** |
| **MedicalDirector** | REPORT → CLOSED | Sign out or reject final reports | ❌ No (only edits) |

---

## Role Details

### 1. ReporterDataEntryOperator

**Who**: Clinical data entry staff, receptionists, intake coordinators

**Primary Function**: Create patient records and register incoming samples

#### What You Can Do

**✅ Always Allowed:**
- Create new patient records (`Individual`)
- Create new genetic test orders (`Phenopacket`)
- Create new sample records (`Biosample`)
- Enter patient measurements and phenotypic features
- View all samples and patient data

**🔶 Conditionally Allowed:**
- **Update samples**: Only when sample is in `PENDING` state
- **Update patient records**: Only when all linked samples are in `PENDING` state
- **Delete samples**: Only when sample is in `PENDING` state

**❌ Not Allowed:**
- Upload dataset files
- Run analysis pipelines
- Create or view clinical reports
- Modify samples in ANALYSIS, REVIEW, or REPORT stages

#### Typical Workflow

1. Patient arrives for genetic testing
2. You create an `Individual` record with patient demographics
3. You create a `Phenopacket` (test order) linking to the patient
4. You create a `Biosample` record for the physical sample
5. Sample starts in `PENDING` state awaiting data upload
6. **Your work is complete** — sample moves to MedicalTechnologist

```{tip}
If you need to correct patient information after data upload has started, contact your LaboratorySupervisor or MedicalTechnologist.
```

---

### 2. MedicalTechnologist

**Who**: Lab technicians, medical technologists, wet-lab operators

**Primary Function**: Manage wet-lab operations, upload sequencing data, curate variant selections during review

**Inherits From**: `DataAdministrator` (includes full data hub and dataset management)

#### What You Can Do

**✅ Always Allowed:**
- Create, update, and delete samples (`Biosample`)
- Create, update, and delete patient records (`Phenopacket`)
- Upload and manage dataset files (FASTQ, BAM, VCF)
- Manage all data hub objects (DRS)
- Create and edit measurements and phenotypic features
- View all samples and interpretations
- **Curate review data**: Select reportable variants, choose gene panels, add clinical comments

**❌ Not Allowed:**
- Run bioinformatics pipelines (requires BioinformaticsScientist)
- Create or update clinical reports
- Approve samples for reporting (requires LaboratorySupervisor)
- Sign out final reports (requires MedicalDirector)

#### Typical Workflow

**Stage 1: PENDING → ANALYSIS**
1. Receive sample in `PENDING` state
2. Upload sequencing data files (FASTQ)
3. Link files to the biosample
4. Transition sample to `ANALYSIS` state

**Stage 2: ANALYSIS** (Wet-lab operations)
1. Monitor sample processing
2. Upload additional QC data as needed
3. Wait for BioinformaticsScientist to run pipelines

**Stage 3: REVIEW** (Variant curation)
1. Review pipeline results
2. Select reportable variants
3. Choose appropriate gene panels
4. Add clinical comments and annotations
5. Prepare sample for LaboratorySupervisor approval

**Rollback Authority:**
- Can roll back samples from `REVIEW` → `ANALYSIS` or `ANALYSIS` → `PENDING` if reprocessing is needed

```{note}
MedicalTechnologist is the primary editor during the REVIEW stage, preparing the test review for supervisor approval.
```

---

### 3. BioinformaticsScientist

**Who**: Bioinformatics engineers, computational scientists, pipeline developers

**Primary Function**: Execute dry-lab analysis pipelines that generate variant interpretations

**Inherits From**: `DataHubWriter`, `DatasetViewer`, `DatasetWriter`, `JobExecutor`, `ToolUser`

#### What You Can Do

**✅ Always Allowed:**
- Submit and monitor workflow runs (WES)
- Create and manage analysis tools (TRS)
- Upload and manage datasets
- View all samples and patient data
- Create `Interpretation`, `Diagnosis`, `GenomicInterpretation`, and `PolygenicInterpretation` records
- Manage Reporter settings

**🔶 Conditionally Allowed:**
- **Update interpretations**: Only when linked sample is in `PENDING` or `ANALYSIS` state
- **Update samples**: Only when sample is in `PENDING` or `ANALYSIS` state

**❌ Not Allowed:**
- Create or update clinical reports
- Approve samples for reporting
- Sign out final reports
- Modify data once sample reaches `REVIEW` stage (requires MedicalTechnologist or LaboratorySupervisor)

#### Typical Workflow

1. Receive sample in `ANALYSIS` state (data uploaded by MedicalTechnologist)
2. Create bioinformatics workflow (e.g., variant calling pipeline)
3. Submit workflow run via WES
4. Monitor pipeline execution
5. Pipeline automatically creates:
   - `Interpretation` records (overall assessment)
   - `Diagnosis` records (disease context)
   - `GenomicInterpretation` records (variant-level findings with ACMG classifications)
   - `PolygenicInterpretation` records (polygenic risk scores)
6. Transition sample to `REVIEW` state upon completion
7. **Your work is complete** — sample moves to MedicalTechnologist for curation

```{important}
Once a sample reaches REVIEW stage, you can no longer modify interpretations. This ensures data integrity during the review process.
```

---

### 4. LaboratorySupervisor

**Who**: Lab supervisors, senior scientists, quality control managers

**Primary Function**: Review curated test data and approve samples for reporting by creating the official `PhenopacketReport`

**Inherits From**: `DatasetViewer`, `DataHubViewer`

#### What You Can Do

**✅ Always Allowed:**
- View all samples, patient data, and interpretations
- View all dataset files
- **Create `PhenopacketReport` records** (⭐ **Only role with this permission**)

**🔶 Conditionally Allowed:**
- **Update samples**: Only when sample is in `REVIEW` state
- **Delete samples/patient records**: Only when sample is in `CLOSED` state (for archival cleanup)

**❌ Not Allowed:**
- Upload dataset files
- Run analysis pipelines
- Modify interpretations
- Sign out final reports (requires MedicalDirector)

#### Typical Workflow

1. Receive sample in `REVIEW` state (curated by MedicalTechnologist)
2. Review the test review:
   - Verify selected variants are appropriate
   - Check gene panel selections
   - Review clinical comments
   - Ensure data quality meets standards
3. If approved:
   - Create a `PhenopacketReport` (snapshot of current data)
   - Transition sample to `REPORT` state
4. If not approved:
   - Roll back to `ANALYSIS` or `PENDING` for reprocessing
   - Communicate issues to MedicalTechnologist

```{tip}
You act as the quality gatekeeper between REVIEW and REPORT stages. Only create a report when you're confident the data meets clinical standards.
```

---

### 5. MedicalDirector

**Who**: Clinical medical directors, pathologists, attending physicians

**Primary Function**: Final review and sign-off of clinical reports

**Inherits From**: `DatasetViewer`, `DataHubViewer`

#### What You Can Do

**✅ Always Allowed:**
- View all clinical reports (`PhenopacketReport`)
- Update clinical reports (edit before sign-off)
- Delete clinical reports (reject back to REVIEW)
- List all samples and reports

**🔶 Conditionally Allowed:**
- **Update samples**: Only when sample is in `REPORT` state (to perform sign-out or rejection)
- **Delete interpretations**: Only when linked sample is in `REPORT` state

**❌ Not Allowed:**
- Create new reports (requires LaboratorySupervisor)
- View or modify samples in PENDING, ANALYSIS, or REVIEW stages
- Upload data or run pipelines

#### Typical Workflow

1. Receive sample in `REPORT` state (report created by LaboratorySupervisor)
2. Review the `PhenopacketReport`:
   - Verify clinical interpretation accuracy
   - Check variant pathogenicity classifications
   - Review clinical recommendations
   - Ensure report meets diagnostic standards
3. **Decision point:**
   - **Sign out**: Update report status to `FINAL`, transition sample to `CLOSED` ✅
   - **Reject**: Delete report, transition sample back to `REVIEW` for corrections ❌

**Post-Sign-Out:**
- If corrections needed after sign-out, LaboratorySupervisor can reissue (`CLOSED` → `REPORT`)
- You can then create an amended report

```{important}
You are the final authority on clinical report accuracy. Only sign out reports that meet diagnostic quality standards.
```

---

## Permission Tables by Data Model

### Biosample (Sample Records)

The central entity tracking sample lifecycle state.

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ✅ | ✅ | ❌ | ❌ | ❌ |
| **View** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **List** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Update** | 🔶 PENDING only | ✅ | 🔶 PENDING/ANALYSIS | 🔶 REVIEW only | 🔶 REPORT only |
| **Delete** | 🔶 PENDING only | ❌ | ❌ | 🔶 CLOSED only | ❌ |

### Phenopacket (Patient Test Orders)

Links patient to samples and clinical context.

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ✅ | ✅ | ❌ | ❌ | ❌ |
| **View** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **List** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **Update** | 🔶 All samples PENDING | ✅ | 🔶 PENDING/ANALYSIS | ❌ | ❌ |
| **Delete** | 🔶 All samples PENDING | ❌ | ❌ | 🔶 Any sample CLOSED | ❌ |

### PhenopacketReport (Clinical Reports)

Official diagnostic report snapshot.

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ❌ | ❌ | ❌ | ✅ **Only role** | ❌ |
| **View** | ❌ | ✅ | ✅ | ✅ | ✅ |
| **List** | ❌ | ✅ | ✅ | ✅ | ✅ |
| **Update** | ❌ | ❌ | ❌ | ❌ | ✅ **Only role** |
| **Delete** | ❌ | ❌ | ❌ | ❌ | ✅ **Only role** |

### Interpretation Models

Includes `Interpretation`, `Diagnosis`, `GenomicInterpretation`, `PolygenicInterpretation`.

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ❌ | ✅ | ✅ | ✅ | ❌ |
| **View** | ❌ | ✅ | ✅ | ✅ | ❌ |
| **List** | ❌ | ✅ | ✅ | ✅ | ❌ |
| **Update** | ❌ | ✅ | 🔶 PENDING/ANALYSIS | ✅ | ❌ |
| **Delete** | ❌ | ✅ | ❌ | ✅ | 🔶 REPORT only |

### Individual (Patient Demographics)

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ✅ | ❌ | ✅ | ❌ | ❌ |
| **View** | ✅ | ❌ | ✅ | ❌ | ❌ |
| **Update** | ✅ | ✅ | ✅ | ❌ | ❌ |
| **Delete** | ❌ | ❌ | ❌ | ❌ | ❌ |

### Measurement & PhenotypicFeature

Clinical measurements and observed phenotypes.

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ✅ | ✅ | ✅ | ❌ | ❌ |
| **View** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **Update** | ✅ | ✅ | ✅ | ❌ | ❌ |
| **Delete** | ❌ | ✅ | ✅ | ❌ | ❌ |

### File (Dataset Files)

Sequencing data files (FASTQ, BAM, VCF).

| Operation | Data Entry | Med Tech | Bioinfo | Lab Supervisor | Med Director |
|-----------|-----------|----------|---------|----------------|--------------|
| **Create** | ❌ | ❌ | ✅ | ❌ | ❌ |
| **View** | ❌ | ✅ | ✅ | ✅ | ❌ |
| **List** | ✅ | ✅ | ✅ | ✅ | ✅ |
| **Delete** | ❌ | ✅ | ✅ | ❌ | ❌ |

---

## Common Workflows

### Complete Sample Lifecycle

Here's how all five roles work together to process a genetic test sample:

**1. Sample Registration** (ReporterDataEntryOperator)
```
Patient arrives → Create Individual → Create Phenopacket → Create Biosample
State: PENDING
```

**2. Data Upload** (MedicalTechnologist)
```
Upload FASTQ files → Link to Biosample → Transition to ANALYSIS
State: PENDING → ANALYSIS
```

**3. Pipeline Execution** (BioinformaticsScientist)
```
Submit WES workflow → Pipeline runs → Creates Interpretations → Transition to REVIEW
State: ANALYSIS → REVIEW
```

**4. Variant Curation** (MedicalTechnologist)
```
Review variants → Select reportable variants → Choose panels → Add comments
State: REVIEW (editing)
```

**5. Quality Control** (LaboratorySupervisor)
```
Review curated data → Approve → Create PhenopacketReport → Transition to REPORT
State: REVIEW → REPORT
```

**6. Clinical Sign-Off** (MedicalDirector)
```
Review report → Sign out → Transition to CLOSED
State: REPORT → CLOSED ✅
```

### Rollback Scenarios

Sometimes samples need to go backward in the workflow:

**Scenario 1: Poor Data Quality**
- **Who**: MedicalTechnologist
- **Action**: Roll back from `REVIEW` → `ANALYSIS` or `ANALYSIS` → `PENDING`
- **Reason**: Need to reprocess sample or upload new data

**Scenario 2: Report Corrections Needed**
- **Who**: MedicalDirector
- **Action**: Delete report, sample returns to `REVIEW`
- **Reason**: Clinical interpretation needs revision

**Scenario 3: Post-Sign-Out Amendment**
- **Who**: LaboratorySupervisor
- **Action**: Reissue from `CLOSED` → `REPORT`
- **Reason**: Need to issue amended report with corrections

---

## Troubleshooting

### "Permission Denied" on Sample Update

**Error**: `403 Forbidden` when trying to update a biosample

**Check:**
1. **What is the sample's current state?**
   - ReporterDataEntryOperator: Only `PENDING`
   - BioinformaticsScientist: Only `PENDING` or `ANALYSIS`
   - LaboratorySupervisor: Only `REVIEW`
   - MedicalDirector: Only `REPORT`

2. **Are you trying to change the state?**
   - If updating `state` field, ensure you have authority for that transition
   - ReporterDataEntryOperator cannot change state from `PENDING`

**Solution**: Contact the role responsible for the current stage, or wait for sample to reach your stage.

### Cannot Create Report

**Error**: `403 Forbidden` when creating `PhenopacketReport`

**Reason**: Only `LaboratorySupervisor` can create reports.

**Solution**: If you need a report created, contact your LaboratorySupervisor.

### Cannot View Sample

**Error**: `403 Forbidden` or `404 Not Found` when viewing biosample

**Possible Causes:**
1. **MedicalDirector**: You can only view samples in `REPORT` or `CLOSED` state
2. **ReporterDataEntryOperator**: Cannot view reports (use Biosample view instead)
3. **Organization mismatch**: Sample belongs to different organization

**Solution**: Verify sample state and your role permissions. Contact administrator if you need broader access.

### Cannot Delete Interpretation

**Error**: `403 Forbidden` when deleting genomic interpretation

**Check:**
1. **BioinformaticsScientist**: Cannot delete interpretations (only create/update)
2. **MedicalDirector**: Can only delete when sample is in `REPORT` state
3. **MedicalTechnologist/LaboratorySupervisor**: Can delete at any time

**Solution**: Verify sample state or contact appropriate role.

---

## Best Practices

### For All Healthcare Users

1. **Respect the Workflow**: Don't try to skip stages or bypass approvals
2. **Document Changes**: Add clear comments when modifying clinical data
3. **Communicate**: Coordinate with other roles when rolling back samples
4. **Verify State**: Always check sample state before attempting operations
5. **Report Issues**: Contact your supervisor if you encounter permission errors

### For Data Entry Staff

- ✅ Double-check patient demographics before moving to next stage
- ✅ Verify sample IDs match physical labels
- ✅ Complete all required fields before submission
- ❌ Don't create duplicate patient records

### For Lab Technicians

- ✅ Upload complete dataset files before transitioning to ANALYSIS
- ✅ Document QC metrics and processing notes
- ✅ Coordinate with BioinformaticsScientist on pipeline requirements
- ❌ Don't transition to REVIEW until pipeline completes

### For Bioinformatics Scientists

- ✅ Validate pipeline outputs before creating interpretations
- ✅ Use standardized ACMG classifications
- ✅ Document pipeline versions and parameters
- ❌ Don't modify interpretations after REVIEW stage

### For Lab Supervisors

- ✅ Thoroughly review all curated data before creating reports
- ✅ Verify variant selections match clinical indications
- ✅ Ensure gene panels are appropriate
- ❌ Don't create reports for incomplete reviews

### For Medical Directors

- ✅ Review reports against clinical guidelines
- ✅ Verify pathogenicity classifications
- ✅ Ensure recommendations are evidence-based
- ❌ Don't sign out reports with unresolved questions

---

## Compliance & Security

### Regulatory Compliance

Healthcare RBAC is designed to meet:

- **CLIA/CAP**: Clinical laboratory workflow requirements
  - Enforced review and approval gates
  - Separation of duties between roles
  - Complete audit trail

- **HIPAA**: Protected health information access controls
  - Organization isolation
  - Role-based access restrictions
  - Comprehensive logging

- **GDPR**: Patient data privacy
  - Controlled access to patient records
  - Data deletion capabilities (via LaboratorySupervisor)

### Audit Trail

Every action is logged with:
- User ID and role
- Timestamp
- Action performed (create/update/delete)
- Resource affected (biosample ID, phenopacket ID)
- Sample state at time of action

### Data Protection

- ✅ All patient data encrypted at rest and in transit
- ✅ Organization isolation strictly enforced
- ✅ Session timeout after inactivity
- ✅ Multi-factor authentication available
- ✅ Complete audit logging for compliance

---

## Getting Help

### Step 1: Check Your Role

Verify your assigned healthcare roles:
1. Log in to SeqsLab
2. Navigate to **User Profile**
3. View **Assigned Roles** section
4. Confirm you have the appropriate healthcare role

### Step 2: Verify Sample State

Check the sample's current lifecycle state:
1. Navigate to **Reporter → Sample List**
2. Find the sample
3. Check the **State** column
4. Verify your role has permissions for that state

### Step 3: Contact Your Administrator

If you need different permissions:
- **UserAdministrator**: Can assign healthcare roles
- **OrganizationAdministrator**: Can resolve organization-level issues
- **LaboratorySupervisor**: Can help with workflow questions

### Step 4: Submit Support Ticket

For technical issues:
- Email: support@seqslab.net
- Include: username, organization, sample ID, action attempted, error message

---

## Summary

Healthcare RBAC provides a **state-based permission model** that enforces proper clinical laboratory workflows:

✅ **Five Specialized Roles**: Each role handles specific lifecycle stages  
✅ **State-Based Permissions**: What you can do depends on sample state  
✅ **Quality Gates**: Enforced review and approval checkpoints  
✅ **Separation of Duties**: Different roles for different responsibilities  
✅ **Compliance Ready**: Meets CLIA/CAP, HIPAA, GDPR requirements  
✅ **Complete Audit Trail**: Every action logged for regulatory compliance  

### Quick Reference

| If you need to... | You need this role |
|-------------------|-------------------|
| Enter patient data | ReporterDataEntryOperator |
| Upload sequencing files | MedicalTechnologist |
| Run analysis pipelines | BioinformaticsScientist |
| Approve samples for reporting | LaboratorySupervisor |
| Sign out clinical reports | MedicalDirector |

### Related Documentation

- [General RBAC Overview](rbac.md) - Platform-wide RBAC concepts
- [Data Repository Service](../services/drs.md) - Dataset management
- [Workflow Execution Service](../services/wes.md) - Pipeline execution
- [GA4GH Phenopackets](https://phenopacket-schema.readthedocs.io/) - Data model specification
