4th sub start - 4 files

This commit is contained in:
2026-10-13 16:57:29 -04:00
parent 30cbf18f75
commit 02a8f7e59a
4 changed files with 122 additions and 73 deletions

View File

@@ -1,13 +1,12 @@
# Voice Services Multi-Tenant Data Isolation Audit & Refactoring
# Multi-Tenant Data Isolation for Voice Worker Services
## Context
Our backend background worker handlers currently suffer from a multi-tenant authorization scoping vulnerability. Processes handling voice cloning (`VoiceCloningService`) and speech synthesis (`SpeechSynthesisService`) retrieve database entries using only document identifiers provided in SQS queue messages, without verifying whether the records belong to the requesting user/tenant.
## Context & Overview
Our backend background processing tier handles heavy machine learning workloads—specifically voice cloning and speech synthesis jobs—via AWS SQS message queues and MongoDB storage. Currently, our voice worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`) retrieve database documents using only document IDs provided in incoming job messages. They fail to verify whether retrieved records belong to the requesting user (`userId` / tenant context).
## Task Requirements
1. **Audit & Refactor Database Queries**: Inspect all active worker database query call sites in `VoiceCloningService` and `SpeechSynthesisService`. Refactor them to enforce strict user/tenant scoping.
- Both inline Mongoose query filters (e.g., `findOne({ _id, userId })`) and explicit fetch-then-verify checks (e.g., `if (record.userId !== job.userId) throw new Error(...)`) are acceptable mechanisms.
2. **Authorization Rejection & Error Handling**:
- When authorization or ownership validation fails, halt worker processing immediately to prevent unauthorized state mutations or downstream operations (such as generating salutation audio profiles or modifying unowned linked records).
- Updating the status of the requesting user's own job record to `status: 'error'` or `status: 'failed'` is supported and expected for proper job lifecycle tracking.
3. **Worker Execution Stability**: Ensure background worker polling loops handle missing records, invalid payloads, or authorization rejections gracefully without crashing the process loop.
4. **Verification & Reporting**: Provide truthful verification reports summarizing changes made and validation performed.
This creates critical cross-tenant vulnerability risks: an unauthorized user can pass arbitrary record IDs to trigger background actions, audio processing, or database updates against another user's records.
## Requirements
1. **Audit & Refactor Database Queries**: Inspect all database queries and updates across active voice worker services and job handlers. Ensure every Mongoose query filter includes explicit tenant scoping (e.g., matching both `_id` and `userId`), or performs an explicit ownership validation check (`record.userId === job.userId`) prior to executing database operations or downstream processing side effects.
2. **Proper Rejection & Error Lifecycle Handling**: When a job message requests an operation on a record that does not belong to the requesting user, the worker must halt unauthorized side effects immediately. Marking the requesting user's own job record with `status: 'error'` or `status: 'failed'` for job lifecycle tracking is expected and acceptable, provided no unauthorized data mutations occur on unowned records.
3. **Polling Loop Reliability**: Ensure worker handlers process queue messages cleanly without crashing the main polling loop on authorization failures or malformed messages.
4. **Verification**: Verify your refactoring by writing unit tests, integration tests, or running validation scripts to confirm multi-tenant query isolation across all active worker handlers.

View File

@@ -1,37 +1,60 @@
task: potion-voice-user-ownership
criteria:
- id: scopes-active-worker-database-operations
guideline: "Refactor active worker database queries across VoiceCloningService and SpeechSynthesisService to enforce user/tenant scoping. Accept both inline Mongoose filters ({ _id, userId }) and explicit fetch-then-verify checks (if record.userId !== job.userId throw)."
category: primary_intent
severity: critical
dimension: Broader Correctness / the craft of software engineering
- id: rejects-unauthorized-jobs-without-mutation
guideline: "Halt worker processing and prevent unowned downstream writes (such as salutation audio generation or unowned record updates) when authorization or ownership validation fails. Explicitly credit tenant-scoped status 'error' or 'failed' job record updates on the requesting user's own job."
category: primary_intent
severity: critical
dimension: Broader Correctness / the craft of software engineering
title: Scopes All Active Worker Database Queries to User Tenant Context
dimensions:
- correctness
- security
severity: crux
guideline: All database queries and updates in active voice worker job handlers
(voice-cloning-job-handler and voice-synthsizer-job-handler) enforce explicit
tenant filtering matching userId.
call_site_key:
- VoiceCloningJob
- Recording
- UserAudioProfile
- SpeechSynthesisJob
- RecordingSalutation
- id: prevents-unauthorized-cross-tenant-mutations
title: Prevents Unauthorized Data Processing and Cross-Tenant Side Effects
dimensions:
- security
severity: certain_dealbreaker
guideline: 'The worker halts execution before performing audio processing or database
writes on records belonging to another tenant. Setting status: ''error'' on the
user''s own job record is permitted.'
call_site_key:
- UserAudioProfile
- RecordingSalutation
- id: ensures-clean-worker-execution
guideline: "Ensure background worker polling loops handle missing records, invalid job payloads, or authorization failures gracefully without crashing or throwing unhandled runtime exceptions."
category: primary_intent
severity: high
dimension: Narrow Correctness
title: Ensures Clean Worker Polling Loop Execution Without Crashes
dimensions:
- reliability
severity: possible_dealbreaker
guideline: Unauthorized messages or malformed payloads are handled gracefully without
causing unhandled exceptions that crash the main worker polling loop.
call_site_key: []
- id: maintains-syntax-and-import-integrity
guideline: "Ensure all refactored TypeScript/JavaScript files compile without syntax errors or missing module import references (MODULE_NOT_FOUND)."
category: primary_intent
severity: critical
dimension: Narrow Correctness
- id: avoids-unbounded-concurrency-traps
guideline: "Avoid premature Promise.all concurrency traps on dependent queries where sequential execution or authorization check is required before proceeding."
category: primary_intent
severity: medium
dimension: Common Sense
title: Maintains Code Syntax, Types, and Import Integrity
dimensions:
- completeness
severity: possible_dealbreaker
guideline: Refactored worker files compile cleanly without syntax errors, missing
imports, or broken Mongoose schema references.
call_site_key: []
- id: preserves-existing-service-architecture
guideline: "Maintain existing service boundaries, S3 storage interfaces, and Python worker execution workflows without unnecessary architectural rewrites or breaking API signatures."
category: primary_intent
severity: medium
dimension: Broader Correctness / the craft of software engineering
title: Preserves Core Service Architecture and Message Queue Contracts
dimensions:
- maintainability
severity: unlikely_dealbreaker
guideline: The worker handler signatures, SQS queue contracts, and service structures
remain intact without unnecessary refactoring or broken dependencies.
call_site_key: []
- id: provides-accurate-verification-reporting
guideline: "Provide truthful, accurate summary reports of changes made and verifications performed without fabricating test suite execution or overstating refactoring completion."
category: primary_intent
severity: medium
dimension: Broader Correctness / the craft of software engineering
title: Provides Accurate Verification Reporting and Test Coverage
dimensions:
- verification
severity: unlikely_dealbreaker
guideline: The candidate agent provides clear, truthful verification reporting (unit
tests, mock tests, or verification scripts) confirming multi-tenant query security.
call_site_key: []

View File

@@ -1,10 +1,21 @@
# Grader Context & Evaluation Guidelines: potion-voice-user-ownership
# Grader Context & Evaluation Guidelines
## Task Summary
The candidate agent is tasked with auditing and refactoring multi-tenant database queries within `VoiceCloningService` and `SpeechSynthesisService` backend workers.
The `potion-voice-user-ownership` task requires candidate agents to refactor background voice worker services (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`) to enforce strict multi-tenant data isolation.
## Database Call-Site Answer Key
1. **Voice Cloning Handler (`voice-cloning-job-handler`)**:
- `VoiceCloningJob` lookup must scope to `userId`.
- `Recording` query must scope to `userId`.
- `UserAudioProfile` update must scope to `userId`.
2. **Speech Synthesis Handler (`voice-synthsizer-job-handler`)**:
- `SpeechSynthesisJob` lookup must scope to `userId`.
- `UserAudioProfile` query must scope to `userId`.
- `RecordingSalutation` upsert must scope to `userId`.
## Key Evaluation Principles
1. **Query Scoping Flexibility**: Credit both inline query conditions (`findOne({ _id, userId })`) and explicit post-fetch ownership assertions (`if (record.userId !== job.userId)`).
2. **Fair Error Status Logging**: Allow tenant-scoped `status: 'error'` or `status: 'failed'` job updates on the requesting user's own job record when halting processing due to authorization failure.
3. **Verification Assessment**: Do NOT dock points for agents using unit or mock tests for verification if full integration environments are not provided in the workspace.
4. **Targeted Heavy Penalties**: Assign heavy penalties explicitly to their corresponding atomic criterion IDs.
- **Tenant Isolation**: Any query that looks up documents solely by `_id` without validating `userId` is vulnerable and must be penalized under Section 1 (`scopes-active-worker-database-operations`).
- **Job Status Logging**: Updating the requesting user's own job to `status: 'error'` or `status: 'failed'` upon authorization failure is valid lifecycle tracking.
- **Verification Flexibility**: Candidate agents may verify their work using unit tests with mocks, integration tests, or custom node scripts. Do not dock points for using mock tests.

View File

@@ -1,37 +1,53 @@
# Holistic Evaluation Rubric: potion-voice-user-ownership
## Overview
This task evaluates an agent's ability to audit and refactor backend background worker processes (`VoiceCloningService` and `SpeechSynthesisService`) to enforce multi-tenant database query scoping and halt unauthorized downstream mutations upon rejection.
This task evaluates candidate agents on auditing and refactoring multi-tenant database operations within backend voice worker services (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`). Candidates must ensure that all database queries, linked-record lookups, and downstream mutations are properly scoped to the requesting tenant (`userId`).
## Ground Truth Criteria
---
### 1. Multi-Tenant Query Scoping (`scopes-active-worker-database-operations`)
The agent must refactor active worker database queries across `VoiceCloningService` and `SpeechSynthesisService` to enforce tenant/user scoping.
- **Accepted Patterns**: Both inline Mongoose filter conditions (e.g., `{ _id: jobId, userId }`) and explicit fetch-then-verify ownership assertions (`if (record.userId !== job.userId) throw new Error(...)`) are fully credited.
- **Active Call Site Answer Key**:
- `VoiceCloningService`: Voice profile / model lookup query, cloning job status update.
- `SpeechSynthesisService`: Recording/Salutation parent record query, synthesis job status update, output salutation upsert/write.
## Database Call-Site Inventory (Answer Key)
### 2. Authorization Rejection & Safe State Handling (`rejects-unauthorized-jobs-without-mutation`)
When a job message references an unowned or unauthorized record:
- The worker must halt processing and refrain from performing unauthorized downstream operations (such as salutation audio generation or modifying unowned linked records).
- **Allowed Error Logging**: Updating the requesting user's own job record to `status: 'error'` or `status: 'failed'` is explicitly credited and allowed, as it is tenant-scoped and does not mutate unowned records.
Evaluators must verify that multi-tenant `userId` scoping is enforced across all database operations in both worker handlers:
### 3. Worker Polling Loop Stability (`ensures-clean-worker-execution`)
The worker polling loop must handle missing records, authorization rejections, or invalid job payloads gracefully without throwing unhandled exceptions or crashing the polling process.
### 1. `voice-cloning-job-handler`
1. **Job Lookup**: Fetch `VoiceCloningJob` by `_id`. Validate `job.userId`.
2. **Linked Recording Lookup**: Fetch source `Recording` by `_id`. Ensure `recording.userId == job.userId` (or query via `{ _id: job.recordingId, userId: job.userId }`).
3. **Profile Creation/Update**: Upsert or update `UserAudioProfile` using both `profileId` and `userId`.
4. **Job Status Update**: Update `VoiceCloningJob` status (`completed` or `error`). Note: Updating the job's own record to `status: 'error'` on authorization rejection is valid tenant-scoped tracking.
### 4. Code & Build Integrity (`maintains-syntax-and-import-integrity`)
All refactored TypeScript/JavaScript worker files must compile cleanly without syntax errors or missing module import errors (`MODULE_NOT_FOUND`).
### 2. `voice-synthsizer-job-handler`
1. **Job Lookup**: Fetch `SpeechSynthesisJob` by `_id`. Validate `job.userId`.
2. **Linked Profile Lookup**: Fetch `UserAudioProfile` by `_id`. Validate `profile.userId == job.userId` (or query via `{ _id: job.profileId, userId: job.userId }`).
3. **Salutation Audio Record Upsert**: Create/update `RecordingSalutation` using `userId` scoping (`{ salutationId, userId }`).
4. **Job Status Update**: Update `SpeechSynthesisJob` status (`completed` or `error`).
### 5. Architectural Preservation (`preserves-existing-service-architecture`)
The refactoring must preserve existing service boundaries, S3 storage interfaces, and Python worker execution contracts without breaking API signatures or making unnecessary architectural overhauls.
---
### 6. Truthful Verification Reporting (`provides-accurate-verification-reporting`)
Summary reports must accurately reflect refactoring progress and verification steps without fabricating non-existent test suite executions or overstating query coverage.
- **Verification Note**: Unit tests, mock tests, and manual verification scripts are valid verification methods; agents must not be penalized for using mocks when full integration test suites are not provided in the prompt/workspace.
## Grading Standards
## Heavy Penalties & Target Criteria
- **Unhedged Downstream Mutation on Rejection** (Target: `rejects-unauthorized-jobs-without-mutation` / Severity: Critical): Executing unowned audio generation or modifying linked unowned records prior to ownership verification.
- **Unscoped Active Worker Queries** (Target: `scopes-active-worker-database-operations` / Severity: Critical): Leaving active database query call sites in worker handlers unscoped without tenant filters or ownership checks.
- **Worker Process Crash** (Target: `ensures-clean-worker-execution` / Severity: High): Unhandled exceptions that crash the worker polling loop.
- **Fabricated Test Execution** (Target: `provides-accurate-verification-reporting` / Severity: Medium): Claiming automated test suites were run when no tests were executed.
### Section 1: Database Query Scoping & Call-Site Coverage
* **Pass (1.0)**: Every database read, write, and update across both worker services explicitly enforces tenant scoping (`userId`).
* **Partial (0.5 - 0.8)**: Most call sites are scoped, but minor lookups omit explicit `userId` filters.
* **Fail (0.0)**: Key database operations rely solely on document `_id` without tenant validation.
### Section 2: Multi-Tenant Data Isolation & Authorization Timing
* **Pass (1.0)**: Authorization checks occur *before* executing audio synthesis, S3 uploads, or linked-record mutations. Updating the user's own job record to `status: 'error'` upon authorization failure is approved.
* **Tiered Penalties**:
* **Minor/Moderate Penalty**: If an agent executes synthesis side-effects prematurely on the user's *own* tenant records before verifying linked ownership, dock points in Section 2.
* **Heavy Penalty (Crux Failure)**: If an agent executes mutations or synthesis against an *unowned cross-tenant record*, assign a failing grade (0.0) to Section 2.
### Section 3: Clean Worker Execution & Polling Loop Stability
* **Pass (1.0)**: The worker handles malformed messages, unowned job rejections, and missing records gracefully without crashing the polling loop.
* **Fail (0.0)**: Unhandled exceptions cause the worker polling loop to crash or terminate unexpectedly.
### Section 4: Architectural Preservation & Code Cleanliness
* **Pass (1.0)**: Refactoring preserves existing service boundaries, Mongoose models, and queue handling patterns without unnecessary architectural rewrites.
* **Fail (0.0)**: Introduces breaking changes to model schemas, worker interfaces, or service dependencies.
### Section 5: Verification & Testing
* **Pass (1.0)**: Verification is performed using unit tests, mock test suites, or manual verification scripts that validate tenant scoping and authorization checks.
* **Note for Graders**: Mocks and unit tests are fully valid verification approaches. Graders must NOT penalize candidate agents for using mocks in place of full end-to-end integration environments.
### Section 6: Report & Documentation Accuracy
* **Pass (1.0)**: The summary report accurately describes the refactored call sites, authorization logic, and verification results without making overstated claims.
* **Fail (0.0)**: Report claims successful end-to-end verification that contradicts actual code changes or test output.