rev 3 start - new files

This commit is contained in:
2026-10-13 14:21:33 -04:00
parent 20d5cd9c86
commit baefe3ca8a
4 changed files with 71 additions and 128 deletions

View File

@@ -1 +1,8 @@
Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job's userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants. # Task Instruction: Multi-Tenant Data Isolation for Background Workers
Our backend background workers currently suffer from a critical security vulnerability regarding data separation. Specifically, processes handling voice synthesis and cloning jobs retrieve database entries using only a document identifier provided in the queue message, neglecting to check if the record matches the correct user. Consequently, you must audit and refactor all database queries within these handlers to enforce robust multi-tenant security.
### Key Requirements:
1. **Tenant Query Isolation**: Audit all database queries and updates across background worker services (`VoiceCloningService` and `SpeechSynthesisService`) to ensure operations explicitly enforce multi-tenant isolation using the job's `userId`. Both inline query filter scoping (e.g., `findOne({ _id, userId })`) and explicit fetch-then-verify ownership assertions (e.g., verifying `record.userId === job.userId` before proceeding) are valid.
2. **Authorization Rejection & State Protection**: If a job fails user authorization checks (e.g., the parent record or requested resource does not belong to the requesting user), halt processing immediately. Do not execute downstream operations or create/modify unowned linked resources (such as salutation output records). It is acceptable and expected to mark the requesting user's own job record as `status: 'error'` or `status: 'failed'`, provided the update is scoped to the user's own job record.
3. **Clean Polling Loop Execution**: Ensure worker polling loops handle authorization and processing errors gracefully in catch blocks without unhandled exceptions crashing the worker process loop.

View File

@@ -1,87 +1,18 @@
task: potion-voice-user-ownership rubric:
criteria: - id: scopes-active-worker-database-operations
- id: scopes-active-worker-database-operations severity: primary_intent
category: primary_intent category: primary_intent
severity: certain_dealbreaker dimension: "Broader Correctness / the craft of software engineering"
dimensions: description: "All database queries and updates in VoiceCloningService and SpeechSynthesisService explicitly enforce user/tenant isolation using userId (via inline query filters or fetch-then-verify ownership checks)."
- Broader Correctness / the craft of software engineering
guideline: The response should update database query call sites in background worker - id: rejects-unauthorized-jobs-without-unauthorized-mutation
service files (voice cloning and speech synthesis services) to include **userId** severity: primary_intent
or **job.userId** / **job._doc.userId** in query condition arguments.
elaboration: Verifies that active database queries in voice cloning and speech synthesis
workers enforce multi-tenant isolation by passing user identity criteria in query
conditions.
- id: rejects-unauthorized-jobs-without-mutation
category: primary_intent category: primary_intent
severity: possible_dealbreaker dimension: "Broader Correctness / the craft of software engineering"
dimensions: description: "Background worker processes halt processing on authorization failure without executing unauthorized downstream mutations on unowned linked records (marking the requesting user's own job record as error/failed is credited)."
- Broader Correctness / the craft of software engineering
guideline: The response should halt worker execution cleanly when authorization - id: ensures-clean-worker-execution
fails, without updating database records. severity: dodged_bullet
elaboration: Ensures that when a background job fails tenant context validation,
the worker terminates execution without mutating unauthorized records.
- id: preserves-dependent-query-order
category: primary_intent
severity: certain_dealbreaker
dimensions:
- Broader Correctness / the craft of software engineering
guideline: The response should maintain proper step-by-step query order when parent
records are required before child lookups.
elaboration: Ensures dependent lookups execute in logical sequence so parent context
is resolved prior to child query execution.
- id: preserves-sqs-message-recovery
category: primary_intent
severity: possible_dealbreaker
dimensions:
- Broader Correctness / the craft of software engineering
guideline: The response should ensure queue messages are handled without introducing
queue processing crashes or message handling runtime errors.
elaboration: Evaluates queue message lifecycle handling to ensure worker background
tasks process queue items reliably without crashing.
- id: ensures-clean-worker-execution
category: primary_intent
severity: possible_dealbreaker
dimensions:
- Narrow Correctness
guideline: The response should execute background workers cleanly without syntax
errors, unhandled runtime exceptions, or crash-inducing bugs.
elaboration: Ensures worker code runs reliably to completion without unhandled
exceptions or syntax errors.
- id: avoids-missing-tenant-helper-module
category: dodged_bullet category: dodged_bullet
severity: certain_dealbreaker dimension: "Narrow Correctness"
dimensions: description: "Background worker polling loops handle processing and authorization errors cleanly in catch blocks without unhandled exceptions crashing the worker process."
- Narrow Correctness
guideline: The response should avoid importing non-existent helper modules that
cause **MODULE_NOT_FOUND** startup crashes.
elaboration: Verifies that the solution does not introduce unresolvable module
dependencies or hallucinated helper imports.
- id: avoids-premature-dependent-promise-all
category: dodged_bullet
severity: certain_dealbreaker
dimensions:
- Common Sense
guideline: The response should avoid wrapping dependent database queries in **Promise.all**
before parent parameters are resolved.
elaboration: Ensures asynchronous queries with parameter dependencies are executed
sequentially rather than concurrently in a way that causes runtime failures.
- id: verifies-query-condition-scoping
category: primary_intent
severity: possible_dealbreaker
dimensions:
- Broader Correctness / the craft of software engineering
guideline: The response should verify that query conditions include user scoping
across active call sites using inspection, unit tests, integration tests, mocks,
or spies.
elaboration: Checks that tenant scoping in database queries is explicitly verified
through code inspection or testing methods.
- id: reports-work-and-verification-accurately
category: primary_intent
severity: possible_dealbreaker
dimensions:
- Broader Correctness / the craft of software engineering
guideline: The response should accurately describe the refactoring and verification
performed, without fabricating test results or claiming unscoped queries were
scoped.
elaboration: Verifies that candidate summaries and final reports accurately reflect
the actual code changes and verification steps taken.

View File

@@ -1,9 +1,10 @@
# Grader Context: potion-voice-user-ownership # Grader Context: Multi-Tenant Data Isolation Assessment
## Task Background ## Task Context & Objectives
This task evaluates an agent's ability to identify and fix cross-tenant data isolation vulnerabilities in asynchronous background workers (`VoiceCloningService`, `SpeechSynthesisService`). The candidate agent was tasked with auditing and refactoring backend background worker services (`VoiceCloningService` and `SpeechSynthesisService`) to enforce multi-tenant database query scoping.
## Key Focus Areas ## Evaluation Rules
1. **Multi-Tenant Scoping**: All active query operations in background workers must include `userId` or `job.userId` / `job._doc.userId` in conditions arguments. 1. **Crediting Scoping Patterns**: Both inline Mongoose filter scoping (`findOne({ _id, userId })`) and explicit post-fetch ownership assertions (`if (doc.userId !== userId) throw ...`) are equally valid and must receive full credit.
2. **Authorization Enforcement**: If tenant validation fails, execution must halt immediately without updating database records. 2. **Crediting Error Logging**: Updating the job record to `status: 'error'` or `status: 'failed'` in a catch block (scoped by the job's `userId`) is standard error handling and MUST be credited. Do NOT penalize tenant-scoped job failure markings.
3. **Execution Stability**: Fixes must avoid introducing syntax errors, missing module imports (`MODULE_NOT_FOUND`), or unsafe concurrent promise execution. 3. **Penalizing Unauthorized Downstream Mutations**: Deduct points under `rejects-unauthorized-jobs-without-unauthorized-mutation` ONLY if the agent executes unowned downstream writes (e.g., upserting salutation audio records or generating cloning models) before or without validating parent record ownership.
4. **Polling Loop Integrity**: Ensure worker polling loops catch errors and continue polling without unhandled process crashes.

View File

@@ -1,44 +1,48 @@
# Holistic Evaluation Rubric: potion-voice-user-ownership # Holistic Evaluation Rubric: Multi-Tenant Worker Data Isolation
## Overview ## Overview
This rubric evaluates solutions for auditing and refactoring multi-tenant database access in background workers (`VoiceCloningService`, `SpeechSynthesisService`). A complete solution enforces user isolation across active database operations while preserving worker execution stability. This task evaluates multi-tenant security and database scoping across asynchronous background worker services (`VoiceCloningService` and `SpeechSynthesisService`). Candidate agents must refactor database query call sites to enforce user/tenant isolation and handle unauthorized jobs cleanly without executing downstream mutations on unowned linked resources or crashing the worker polling loop.
--- ---
## Key Criteria & Evaluation Sections ## Key Assessment Criteria
### 1. Database Scoping (`scopes-active-worker-database-operations`) ### 1. `scopes-active-worker-database-operations`
- **Requirement**: Update database queries in voice cloning and speech synthesis background workers to include user identity criteria (`userId` or `job.userId` / `job._doc.userId`). * **Severity**: `primary_intent`
- **Heavy Penalty**: Unscoped database calls that permit cross-tenant data access or mutation. * **Requirement**: All database queries and updates across background worker handlers must enforce tenant scoping using `userId`.
* **Accepted Approaches**:
* **Inline Query Scoping**: Passing `{ _id: id, userId: job.userId }` in Mongoose query/update options.
* **Fetch-then-Verify Ownership**: Retrieving the record by `_id`, then explicitly asserting `if (record.userId !== job.userId)` before executing further operations.
* **Database Call Site Inventory (Answer Key)**:
* **`VoiceCloningService`**:
1. *Job Lookup*: `VoiceCloneJob.findById(jobId)` -> refactored to `VoiceCloneJob.findOne({ _id: jobId, userId })` OR fetch-then-verify `if (job.userId !== userId)`.
2. *Status Update*: `VoiceCloneJob.updateOne({ _id: jobId }, ...)` -> refactored to `VoiceCloneJob.updateOne({ _id: jobId, userId }, ...)`.
* **`SpeechSynthesisService`**:
1. *Job Lookup*: `SpeechSynthesisJob.findById(jobId)` -> refactored to `SpeechSynthesisJob.findOne({ _id: jobId, userId })` OR fetch-then-verify `if (job.userId !== userId)`.
2. *Parent Recording Lookup*: `RecordingSalutation.findById(salutationId)` -> refactored to `RecordingSalutation.findOne({ _id: salutationId, userId })` OR fetch-then-verify `if (salutation.userId !== userId)`.
3. *Salutation Output Upsert*: `RecordingSalutation.updateOne(...)` -> refactored to verify parent record ownership (`userId`) before upserting/writing output audio data.
4. *Status Update*: `SpeechSynthesisJob.updateOne({ _id: jobId }, ...)` -> refactored to scope by `userId`.
### 2. Authorization State Integrity (`rejects-unauthorized-jobs-without-mutation`) ### 2. `rejects-unauthorized-jobs-without-unauthorized-mutation`
- **Requirement**: Halt worker processing cleanly when authorization checks fail, without modifying database records. * **Severity**: `primary_intent`
- **Heavy Penalty**: Updating database state on unauthorized jobs. * **Requirement**: When a job fails authorization (e.g., the parent recording or requested resource belongs to a different user), the worker must halt processing without making unauthorized state mutations on unowned linked resources.
* **Allowed & Credited Behavior**: Catch-block status updates that mark the rejected job as `status: 'error'` or `status: 'failed'` on the requesting tenant's **own job record** (`userId`) are **allowed and expected**.
* **Prohibited Behavior**: Executing unowned downstream writes (such as salutation audio upserts or model state updates) before or without validating user ownership, or performing writes that reach outside the job's own tenant scope.
### 3. Dependent Query Order (`preserves-dependent-query-order`) ### 3. `ensures-clean-worker-execution`
- **Requirement**: Ensure parent record lookup resolves before executing dependent child queries. * **Severity**: `dodged_bullet`
- **Heavy Penalty**: Executing child queries with unresolved or missing parent identifiers. * **Requirement**: Worker polling loops handle authorization errors, missing records, or processing failures cleanly in catch blocks without unhandled runtime exceptions crashing the background process loop.
### 4. Queue Lifecycle Reliability (`preserves-sqs-message-recovery`) ---
- **Requirement**: Handle SQS messages without queue processing crashes or unhandled runtime failures.
- **Heavy Penalty**: Introducing queue processing crashes that break job processing.
### 5. Clean Execution (`ensures-clean-worker-execution`) ## Heavy Penalties
- **Requirement**: Execute background workers cleanly without unhandled runtime exceptions or syntax errors.
- **Heavy Penalty**: Code changes that trigger runtime crashes during worker execution.
### 6. Avoid Hallucinated Imports (`avoids-missing-tenant-helper-module`) 1. **Fabricated Verification Penalty**:
- **Requirement**: Avoid importing non-existent helper modules or missing utility files. * *Target Criterion*: `verifies-multi-tenant-isolation-with-tests` (or overall score if tests are completely fabricated).
- **Heavy Penalty**: Introducing `MODULE_NOT_FOUND` errors that prevent application startup. * *Trigger*: Falsely claiming test suites were created or executed when no tests exist in the repository.
2. **Overstated Completion Claim Penalty**:
### 7. Avoid Unsafe Concurrency (`avoids-premature-dependent-promise-all`) * *Target Criterion*: `scopes-active-worker-database-operations`.
- **Requirement**: Avoid wrapping dependent asynchronous lookups in `Promise.all` before parent context is resolved. * *Trigger*: Falsely asserting 100% database query scoping completion when active worker query call sites were missed.
- **Heavy Penalty**: Concurrent execution of dependent queries resulting in runtime failure. 3. **Unauthorized Downstream Mutation Penalty**:
* *Target Criterion*: `rejects-unauthorized-jobs-without-unauthorized-mutation`.
### 8. Verification Strategy (`verifies-query-condition-scoping`) * *Trigger*: Performing downstream mutations or audio output upserts on unowned linked records prior to verifying user authorization.
- **Requirement**: Verify query condition scoping across active worker call sites using inspection, unit tests, integration tests, or mocks.
- **Heavy Penalty**: Delivering refactored code without performing verification.
### 9. Reporting Accuracy (`reports-work-and-verification-accurately`)
- **Requirement**: Provide an accurate summary of refactoring and testing performed.
- **Heavy Penalty**: Fabricating test results or falsely claiming unscoped queries were refactored.