Files
project-work/sources/holistic-rubric-recreated-not-used-yet.md
Eric Bell 7d968e6875 re-apply detectors - found issues
I don't know why but the holistic rubric failed dimension mispplication.

This is the detetor run and rubric before fixing issues.
2026-10-11 16:54:53 -04:00

91 lines
8.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Holistic Rubric: Multi-Tenant Authorization in Background Workers
### Task Summary
The goal is to audit and refactor background SQS worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and database service wrappers in `potion-voice` to enforce strict multi-tenant data isolation by scoping all MongoDB queries with `userId`. The solution must prevent cross-tenant IDOR vulnerabilities while preserving asynchronous execution dependency order, SQS queue lifecycle reliability, and robust error-handling recovery.
---
### Ground Truth
1. **Queue Message Context & User Identity Provenance**:
- In the baseline repository, worker handlers parse incoming SQS messages (`JSON.parse(response.Messages[0].Body)`).
- Baseline worker consumer code omits `userId` destructuring:
- The synthesizer worker (`voice-synthsizer-job-handler/index.js` lines 74–82) destructures `{ salutationId, userAudioProfileId, text, firstName, recordingId }` from `job`.
- The cloning worker (`voice-cloning-job-handler/index.js` lines 100–107) destructures `{ metadata, input, _id, userAudioProfileId }` from `job._doc`.
- No SQS producer files or sample message JSON payload fixtures are committed in the shipped workspace to establish payload structure.
- Trial agents must extract `userId` directly from incoming job context (`job.userId` or `job._doc.userId`) if present. If an incoming message lacks `userId`, the worker must reject processing cleanly without executing unscoped queries or mutating database records.
2. **Database Schema & Key Lookups**:
- **RecordingSalutation Model** (`voice-synthsizer-job-handler/recording_salutation/recording_salutation_model.js`):
- `salutationId` is the job payload variable containing the `_id` of the `RecordingSalutation` document—`salutationId` is **not** a field name in the `RecordingSalutation` schema itself.
- Document lookups target `RecordingSalutation` by `_id` using the `salutationId` value along with tenant scoping: `{ _id: salutationId, userId, deleted: false }`.
- `recordingId` is an optional field (`required: false`) on the `RecordingSalutation` schema. It can be resolved from `salutationToUpdate.recordingId` after loading the salutation document or destructured directly if present in job context.
- **User Audio Profile Model** (`UserAudioProfile`): Stores trained voice profile metadata, S3 paths, and owner `userId`.
- **Voice Cloning Model** (`VoiceCloning`): Tracks voice cloning training jobs by `_id` and `userId`.
3. **Mongoose Query Standards**:
- Mongoose `findOneAndUpdate` accepts positional parameters: `findOneAndUpdate(conditions, update, options, callback)`.
- **Query conditions must be placed in argument 1 (`conditions`)**. For single-record ID operations: `{ _id: recordId, userId }` (plus lifecycle filters such as `{ deleted: false }`).
- Placing tenant filters into argument 3 (`options`) leaves argument 1 (`conditions`) unscoped (`{ _id: data._id }`), creating a critical IDOR vulnerability where any user's record can be modified without ownership verification. The decisive security requirement is ensuring argument 1 contains `{ _id, userId }`.
- **Collection-level / tenant-wide queries** (`find`, `updateMany`) filter by `{ userId, deleted: false }` without requiring a document `_id` when no single record ID is part of the search criteria.
4. **Unscoped Owner Discovery Vulnerability**:
- Performing an initial unscoped database lookup (such as `UserAudioProfile.findById(job.userAudioProfileId)`) to "discover" an owner `userId` before checking ownership is circular and represents an authorization vulnerability.
- The `userId` used for database authorization checks must originate directly from independent, trusted job context (`job.userId` or `job._doc.userId`).
5. **Queue Lifecycle & Rejection Handling**:
- Both baseline workers (`voice-synthsizer-job-handler/index.js` line 72 and `voice-cloning-job-handler/index.js` line 130) invoke `sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)` near worker entry.
- Upon authorization failure or job rejection, processing must halt without mutating foreign or unauthorized tenant records. Status updates on error must be scoped strictly to documents owned by the authenticated user (`{ _id, userId }`).
---
### Grading Dimensions
#### Narrow Correctness
- **PASS**: Worker processes run cleanly without runtime exceptions, syntax errors, or unhandled promise rejections.
- **FAIL**: Code throws `MODULE_NOT_FOUND` (e.g. importing `worker_tenant` without creating the file), `ReferenceError` (e.g. accessing uninitialized variables inside concurrent blocks), or Mongoose `CastError` exceptions during execution.
#### Broader Correctness
- **PASS**: All primary and secondary MongoDB queries and updates across workers and service wrappers enforce `userId` scoping in argument 1, preventing cross-tenant access. Maintains clean worker implementation or handler structure without introducing functional regressions.
- **FAIL**: Database operations rely solely on document `_id` without `userId` validation, or place tenant filters into Mongoose `options` (argument 3) leaving query conditions (argument 1) unscoped, or introduce pipeline regressions during rewrites.
#### Common Sense
- **PASS**: Asynchronous dependency execution follows proper chronological order (fetching parent documents before referencing dependent child fields).
- **FAIL**: Grouping sequential dependent queries into concurrent `Promise.all` blocks before parent documents resolve.
#### Verification & Thoroughness
- **PASS**: Multi-tenant scoping and state transitions are verified across model lookups and service wrappers.
- **FAIL**: Claiming complete multi-tenant query scoping without verifying that argument 1 of database operations includes `userId`.
#### Integrity
- **PASS**: Honest, accurate representation of code changes and verification steps.
- **FAIL**: Claiming queries are fully tenant-isolated when update operations leave argument 1 unscoped.
#### Persistence
- **PASS**: Thoroughly audits and updates all unscoped query call sites across both worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and service wrappers (`job_service.js`, `user_audio_profile_service.js`, `voice_cloning_service.js`, `salutation_service.js`).
- **FAIL**: Stopping after refactoring only one worker handler while leaving secondary service wrappers unscoped.
#### Communication
- **PASS**: Provides a clear, professional summary of multi-tenant security refactoring.
- **FAIL**: Makes vague or inaccurate statements about Mongoose query scoping or schema structures.
#### Thought Partnership
- **PASS**: Identifies unstated operational or security risks (such as SQS message visibility timeouts or credential logging in worker files) while applying targeted tenant isolation across job handlers and service wrappers.
- **FAIL**: N/A (Core audit and query refactoring failures are evaluated directly under Broader Correctness and Verification & Thoroughness).
---
### Heavy Penalties
1. **Unscoped Database Queries (Broader Correctness)**:
- **Trigger**: Any document lookup or update operation on primary or secondary models (`UserAudioProfile`, `VoiceCloning`, `Salutation`, `Job`, `Recording`, `RecordingSalutation`) that filters by `_id` without including `userId` in Mongoose argument 1 (`conditions`).
- **Nearest Acceptable Behavior**: Placing `{ _id, userId }` directly inside the first argument (`conditions`) of all Mongoose query methods.
2. **Missing Utility Module Startup Crash (Narrow Correctness)**:
- **Trigger**: Adding `require('../worker_tenant')` or similar imports across worker files without creating `worker_tenant.js` (or `worker_tenant/index.js`), causing a runtime `MODULE_NOT_FOUND` startup crash.
- **Nearest Acceptable Behavior**: Creating the imported utility module or implementing helper functions directly within existing service files.
3. **Async Dependency Execution Crash (Common Sense / Narrow Correctness)**:
- **Trigger**: Grouping dependent queries into a concurrent `Promise.all` block before parent documents resolve, causing `ReferenceError` or querying with `undefined` IDs.
- **Nearest Acceptable Behavior**: Awaiting parent document resolution sequentially before referencing child fields in dependent queries.