starting with source files

This commit is contained in:
2026-10-13 14:36:34 -04:00
parent 8c688f469e
commit ba4cb8c0d3
4 changed files with 69 additions and 71 deletions

View File

@@ -1,16 +1,19 @@
# Multi-Tenant Authorization & Query Scoping
# Multi-Tenant Background Worker Refactoring
## Background
Our backend background worker processes (`VoiceCloningService` and `SpeechSynthesisService`) handle voice synthesis and cloning jobs retrieved from SQS message queues. Currently, worker handlers retrieve database documents using only document IDs provided in job payloads without verifying tenant ownership.
Our backend background workers currently suffer from a critical security vulnerability regarding data isolation. Specifically, processes handling voice synthesis and cloning jobs retrieve database entries using only document identifiers without verifying if the records belong to the requesting user.
## Task Requirements
1. **Audit & Scope Database Queries**:
- Refactor all active worker database operations in `VoiceCloningService` and `SpeechSynthesisService` so queries check user/tenant ownership.
- You may enforce ownership via inline Mongoose query filters (e.g. `findOne({ _id: jobId, userId: job.userId })`) or explicit fetch-then-verify assertions (`if (record.userId !== job.userId) throw new Error(...)`).
## Instructions
2. **Handle Authorization Rejections Safely**:
- When job payload user IDs do not match the owner of target database records, halt downstream worker processing and prevent unowned data mutations (such as audio file creation or salutation upserts).
- Marking the job as failed or setting `status: 'error'` on the requesting user's own job record is explicitly allowed and expected for proper job lifecycle reporting.
1. **Audit and Refactor Database Queries**:
* Inspect all database operations within `VoiceCloningService` and `SpeechSynthesisService`.
* Update queries to enforce user/tenant scoping. Both **inline Mongoose filters** (`findOne({ _id, userId })`) and **explicit fetch-then-verify ownership checks** (`if (record.userId !== job.userId) throw ...`) are valid and supported approaches.
3. **Robust Worker Loop Execution**:
- Background worker polling loops must handle authorization rejections, missing records, or invalid job payloads gracefully without throwing unhandled exceptions or crashing the polling loop.
2. **Authorization Failure & Error Handling**:
* When authorization or ownership validation fails, halt worker execution to prevent unauthorized downstream operations (such as audio generation or updating unowned records).
* **Note on Error Status**: Setting `status: 'error'` or `status: 'failed'` on the requesting user's own job record is expected and supported behavior.
3. **Polling Loop Reliability**:
* Ensure that worker polling loops handle missing records or authorization rejections gracefully without throwing unhandled exceptions or crashing the worker process.
4. **Reporting**:
* Provide a concise, accurate summary of the refactored call sites and verifications performed.

View File

@@ -1,51 +1,37 @@
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).
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.
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
- 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.
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
- 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).
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.
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
- 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.
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
- 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.
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

View File

@@ -1,6 +1,14 @@
# Grader Context: Multi-Tenant Authorization Scoping
# Grader Context Guidelines
## Key Grading Instructions
- Both inline Mongoose query scoping and explicit fetch-then-verify assertions are 100% valid.
- Setting `status: 'error'` on the requesting user's own job record is valid error reporting and must NOT be penalized.
- Only penalize downstream mutations on unowned linked records made prior to authorization checks.
When evaluating candidate submissions for `potion-voice-user-ownership`:
1. **Query Scoping Verification**:
* Verify that active database calls in `VoiceCloningService` and `SpeechSynthesisService` enforce tenant boundaries.
* Credit both inline query filters (`findOne({ _id, userId })`) and fetch-then-verify assertions (`if (job.userId !== userId)`).
2. **Error Logging Credit**:
* Do NOT penalize candidate agents for updating `status: 'error'` on the requesting user's own job record upon authorization rejection. This is standard defensive error logging.
* Only dock points if unowned downstream records are mutated or audio generation occurs despite authorization failure.
3. **Worker Loop Execution**:
* Ensure worker polling loops catch errors and continue processing without process crashes.

View File

@@ -1,45 +1,46 @@
# Holistic Evaluation Rubric: Multi-Tenant Authorization Scoping
# Holistic Evaluation Rubric
## Overview
This task evaluates multi-tenant database query scoping and authorization rejection handling across backend worker services (`VoiceCloningService` and `SpeechSynthesisService`).
This task evaluates the candidate's ability to refactor backend background worker processes (`VoiceCloningService` and `SpeechSynthesisService`) to enforce multi-tenant database query scoping and halt unauthorized job execution safely.
## Call-Site Answer Key (Active Database Operations)
1. `VoiceCloningService`:
- Model lookup query: `VoiceModel.findOne(...)`
- Job status update: `VoiceModel.updateOne(...)`
2. `SpeechSynthesisService`:
- Parent recording salutation lookup: `RecordingSalutation.findOne(...)`
- Synthesis job status update: `SpeechJob.updateOne(...)`
- Salutation audio output record upsert: `SalutationOutput.updateOne(...)`
---
## Ground Truth Standards
## Core Criteria (Ground Truth Guidelines)
### 1. scopes-active-worker-database-operations
* **Requirement**: All active worker database operations across `VoiceCloningService` and `SpeechSynthesisService` enforce tenant scoping.
* **Credited Patterns**: Either inline query filters (`findOne({ _id, userId })`) or explicit fetch-then-verify checks (`if (record.userId !== job.userId) throw new Error(...)`).
### Ground Truth #1: Multi-Tenant Query Scoping
* **Requirement**: All active database queries across `VoiceCloningService` and `SpeechSynthesisService` must enforce tenant ownership checks.
* **Call-Site Inventory (Answer Key)**:
* **VoiceCloningService**:
1. `VoiceCloneJob.findById(id)` -> `VoiceCloneJob.findOne({ _id: id, userId })` or explicit post-fetch `if (job.userId !== userId)` check.
2. `VoiceCloneJob.findByIdAndUpdate(id, ...)` -> `VoiceCloneJob.findOneAndUpdate({ _id: id, userId }, ...)`
* **SpeechSynthesisService**:
1. `SpeechSynthesisJob.findById(id)` -> `SpeechSynthesisJob.findOne({ _id: id, userId })` or explicit post-fetch check.
2. `RecordingSalutation.findById(salutationId)` -> `RecordingSalutation.findOne({ _id: salutationId, userId })` or explicit post-fetch check.
3. `SpeechSynthesisJob.findByIdAndUpdate(id, ...)` -> `SpeechSynthesisJob.findOneAndUpdate({ _id: id, userId }, ...)`
4. `RecordingSalutation.findOneAndUpdate(...)` -> Ensure parent salutation ownership is validated before output mutation.
* **Criterion ID**: `scopes-active-worker-database-operations`
### 2. rejects-unauthorized-jobs-without-mutation
* **Requirement**: Halts processing and halts unowned downstream record mutations when tenant ownership checks fail.
* **Error Status Credit**: Explicitly credits setting `status: 'error'` or `status: 'failed'` on the requesting tenant's own job record.
* **Violation Target**: Hits executing unowned downstream operations or modifying unowned linked records before validating tenant ownership.
### Ground Truth #2: Authorization Failure & Safe Error Handling
* **Requirement**: When authorization or ownership validation fails, the worker must halt processing and avoid executing unowned downstream writes (such as salutation audio generation or updating unowned records).
* **Allowed & Expected Behavior**: Updating `status: 'error'` or `status: 'failed'` on the requesting user's own job record is explicitly allowed and credited.
* **Criterion ID**: `rejects-unauthorized-jobs-without-mutation`
### 3. ensures-clean-worker-execution
* **Requirement**: Background worker polling loops catch errors and continue execution cleanly without crashing or throwing unhandled exceptions.
### Ground Truth #3: Clean Polling Loop & Runtime Stability
* **Requirement**: Background worker polling loops must handle missing records, unowned payloads, or authorization failures gracefully without throwing unhandled exceptions or crashing the polling process.
* **Criterion ID**: `ensures-clean-worker-execution`
### 4. maintains-syntax-and-import-integrity
* **Requirement**: TypeScript/JavaScript files compile cleanly without syntax errors or missing module imports.
---
### 5. avoids-unbounded-concurrency-traps
* **Requirement**: Avoids premature `Promise.all` concurrency traps on dependent queries.
## Heavy Penalties & Target Mapping
### 6. preserves-existing-service-architecture
* **Requirement**: Preserves existing service boundaries, S3 storage interfaces, and Python worker execution workflows.
1. **Unscoped Mutation On Linked Records**: (-30 Points / `rejects-unauthorized-jobs-without-mutation`)
* Executing downstream synthesis or salutation audio upserts without verifying parent record ownership.
### 7. provides-accurate-verification-reporting
* **Requirement**: Reports verifications truthfully without fabricating non-existent test suite executions or overstating query refactoring completion.
2. **Uncaught Runtime Exception In Polling Loop**: (-20 Points / `ensures-clean-worker-execution`)
* Throwing unhandled exceptions that terminate worker process loops upon encountering unauthorized or missing records.
## Heavy Penalties Mapping
* **Fabricated Test Execution**: Hits `provides-accurate-verification-reporting` (Medium severity deduction).
* **Overstated Completion Claim**: Hits `provides-accurate-verification-reporting` (Low/Medium severity deduction).
* **Unscoped Cross-Tenant Mutation**: Hits `rejects-unauthorized-jobs-without-mutation` (Critical severity deduction).
* **Unhandled Polling Crash**: Hits `ensures-clean-worker-execution` (High severity deduction).
3. **Fabricated Test Verification**: (-25 Points / `provides-accurate-verification-reporting`)
* Claiming automated test suites were executed when no test suite exists in the codebase.
4. **Overstated Refactoring Completion**: (-15 Points / `provides-accurate-verification-reporting`)
* Asserting 100% query scoping completion when active worker query sites were missed.