Загрузка данных


You are performing a deep security and business-logic audit of this financial service.

Your primary goal is NOT to look only for traditional OWASP vulnerabilities. The highest priority is to identify bugs that can cause incorrect movement of money, inconsistent financial state, duplicated operations, lost operations, incorrect balances, or divergence between internal and external payment state.

Use the installed skills and plugins where relevant, including:

- audit-context-building
- appsec / business-logic
- appsec / race-conditions
- claude-security
- fp-check
- variant-analysis
- property-based-testing

Do not jump directly into reporting vulnerabilities.

## Phase 1 — Build the financial system model

First, deeply analyze the repository and reconstruct the architecture and money flows.

Identify:

- payment flows
- payout flows
- withdrawals
- deposits
- transfers
- refunds
- chargebacks
- commissions
- fees
- cashback
- bonuses
- settlements
- merchant balances
- user balances
- ledger/accounting logic
- provider integrations
- reconciliation jobs
- asynchronous workers
- queues/topics
- schedulers/cron jobs
- webhook handlers
- retry mechanisms
- outbox/inbox patterns
- state machines
- transaction boundaries
- external side effects

Use `audit-context-building` before hunting for vulnerabilities.

For every important money-moving flow, reconstruct:

1. entry point
2. authentication/authorization
3. validation
4. business-state checks
5. balance/ledger checks
6. DB reads
7. DB writes
8. transaction boundaries
9. event publishing
10. worker processing
11. external provider calls
12. webhook processing
13. retries
14. reconciliation
15. final state

Produce a concise map of the most important financial flows before continuing.

---

## Phase 2 — Identify financial invariants

Infer the financial invariants the system is expected to preserve.

At minimum evaluate invariants such as:

### Exactly-once / duplicate prevention

For a single logical financial operation:

- it must not result in multiple external payouts
- it must not result in multiple withdrawals
- it must not result in multiple credits
- it must not create duplicate ledger entries
- retries must not create additional monetary side effects
- duplicate queue delivery must be safe
- duplicate webhook delivery must be safe

Check whether "exactly once" is truly guaranteed or only assumed.

### Idempotency

Check:

- idempotency keys
- uniqueness constraints
- idempotency key scope
- idempotency key generation
- reuse of keys
- payload binding
- storage lifetime
- race behavior for simultaneous identical requests
- behavior after timeout
- behavior after partial failure
- idempotency across service boundaries

Look for situations where application-level idempotency exists but database-level enforcement does not.

### Balance consistency

Check invariants like:

available_balance >= 0

unless the domain explicitly allows overdrafts.

Determine whether two concurrent operations can both validate the same balance and subsequently spend it.

Search for:

- check-then-act
- read-modify-write races
- lost updates
- write skew
- stale reads
- insufficient locking
- incorrect isolation levels
- missing optimistic locking
- missing version checks
- non-atomic balance updates

### Ledger consistency

If the system contains a ledger, verify whether:

sum(debits) == sum(credits)

for every balanced transaction or equivalent accounting invariant.

Check:

- duplicate postings
- missing postings
- partial postings
- mutation/deletion of historical ledger entries
- incorrect account direction
- cross-currency inconsistencies
- rounding errors
- inconsistent fees
- ledger state diverging from business entity state

### State-machine correctness

Reconstruct all important state machines.

Examples:

PENDING -> PROCESSING -> COMPLETED

or domain-specific equivalents.

Search for:

- invalid state transitions
- skipped states
- duplicate transitions
- transition reversal
- updates without checking previous state
- concurrent transitions from the same state
- stale-state updates
- terminal states being processed again
- multiple workers processing the same entity

Pay particular attention to transitions that trigger monetary side effects.

---

## Phase 3 — Analyze race conditions

Use the `race-conditions` skill aggressively.

For every money-moving operation, ask:

"What happens if this code runs twice at exactly the same time?"

Analyze concurrent execution of:

- HTTP requests
- gRPC requests
- workers
- queue consumers
- cron jobs
- webhook handlers
- retry jobs
- reconciliation jobs

Look specifically for patterns such as:

READ state
IF allowed
    execute monetary action
UPDATE state

instead of an atomic transition.

Look for:

- SELECT followed by UPDATE without locking
- missing `SELECT ... FOR UPDATE`
- incorrectly scoped transactions
- transaction started too late
- transaction committed too early
- external API call outside/inside transaction causing ambiguity
- conditional update without checking rows affected
- compare-and-swap failures ignored
- non-atomic Redis locks
- locks without fencing tokens
- locks expiring during processing
- distributed lock assumptions
- multiple queue consumers processing the same entity

For every race condition, construct an explicit concurrent timeline:

T1 | T2

showing exactly how the invariant can break.

---

## Phase 4 — Partial failure analysis

This is one of the highest-priority parts of the audit.

For every external monetary side effect, enumerate crash/failure windows.

Example:

1. application decides payout is valid
2. application sends payout to provider
3. provider processes payout
4. network response is lost
5. application assumes failure
6. operation is retried
7. second payout occurs

Analyze failures between every pair of important steps.

Explicitly analyze:

- crash before DB commit
- crash after DB commit
- timeout before provider response
- timeout after provider completed operation
- network partition
- worker restart
- process SIGKILL
- DB commit succeeds but event publish fails
- event publish succeeds but DB commit fails
- external API succeeds but DB write fails
- DB state says success but provider failed
- webhook arrives before local state update
- webhook arrives multiple times
- webhook arrives out of order
- reconciliation executes concurrently with normal processing

Do not assume timeout means failure.

Distinguish:

- confirmed failure
- confirmed success
- unknown/ambiguous result

Check whether the system models ambiguous financial outcomes correctly.

---

## Phase 5 — Messaging / asynchronous processing

If Kafka, RabbitMQ, SQS, Redis queues, NATS, or similar systems exist, analyze delivery semantics.

Assume messages can be delivered:

- more than once
- late
- out of order
- after consumer restart

Check whether consumers are idempotent.

Search for:

- acknowledge-before-commit
- commit-before-ack
- missing inbox/deduplication
- duplicate event processing
- retries creating side effects
- dead-letter replay creating monetary duplication
- multiple topics representing the same operation
- event ordering assumptions

Determine whether "exactly once" is incorrectly assumed from queue infrastructure.

---

## Phase 6 — Database consistency

Inspect transaction usage and database constraints.

Check whether correctness relies only on application code where the database should enforce the invariant.

Look for missing:

- UNIQUE constraints
- foreign keys
- CHECK constraints
- conditional updates
- version columns
- row-level locks
- transaction boundaries

Pay special attention to uniqueness around:

- payment_id
- payout_id
- transaction_id
- provider_transaction_id
- idempotency_key
- webhook_event_id
- external_reference
- ledger operation IDs

Consider whether two concurrent transactions could bypass application checks.

---

## Phase 7 — External provider integration

For every payment/banking/crypto/external financial provider integration, determine:

- whether provider APIs are idempotent
- whether provider idempotency keys are used
- key lifetime
- key uniqueness
- whether internal operation IDs are reused
- how unknown results are reconciled
- how callbacks/webhooks are authenticated
- whether webhook events are deduplicated
- whether webhook order matters
- whether provider state is considered authoritative
- how reconciliation works

Look for internal/provider state divergence such as:

internal = FAILED
provider = SUCCESS

or

internal = COMPLETED
provider = FAILED

Identify whether such states can persist indefinitely.

---

## Phase 8 — Amount and currency integrity

Trace amounts end-to-end.

Verify that a user or attacker cannot alter:

- amount
- currency
- destination
- recipient
- account
- fee
- exchange rate
- commission

between authorization and execution.

Check for:

- trusting client-supplied calculated amounts
- recalculation inconsistencies
- decimal precision issues
- floating-point money calculations
- rounding errors
- integer overflow
- underflow
- currency decimal mismatches
- negative amount bugs
- fee calculation bugs
- inconsistent exchange-rate snapshots

---

## Phase 9 — Authorization and ownership

For every monetary operation verify:

- the authenticated actor owns or is authorized for the source account
- object IDs cannot be substituted
- destination modification is prevented
- administrative functionality is correctly protected
- tenant boundaries cannot be crossed
- authorization is checked at execution time, not only creation time

Look for IDOR/BOLA that can cause unauthorized money movement.

---

## Phase 10 — Business-logic abuse

Use the `business-logic` skill.

Think like an attacker or a malicious client.

Try to construct sequences such as:

create -> cancel -> retry -> approve

approve -> change amount -> execute

withdraw -> timeout -> retry

refund -> refund again

refund concurrently

cancel while processing

webhook before processing

replay webhook

reuse idempotency key with modified parameters

reuse external transaction identifiers

trigger reconciliation manually

submit two identical requests concurrently

submit many requests concurrently

change entity state through another endpoint

Search for cross-endpoint attacks where every endpoint is individually correct but their composition breaks a financial invariant.

---

## Phase 11 — Independent security audit

Run the `claude-security` approach independently after the focused financial analysis.

Use it to identify anything the business-logic audit missed.

Do not blindly duplicate findings.

Merge findings only when they share the same root cause.

---

## Phase 12 — False-positive verification

Before reporting any finding as a vulnerability, use `fp-check`.

For every candidate finding, prove:

1. reachable execution path
2. triggering conditions
3. actual state mutation
4. violated invariant
5. realistic concurrency/failure/attacker scenario
6. why existing protections do not prevent it

Do not report speculative vulnerabilities without evidence.

Explicitly downgrade findings when the necessary assumptions are not proven.

Classify each finding as:

- Confirmed
- Highly likely
- Needs runtime verification
- False positive

---

## Phase 13 — Variant analysis

For every confirmed or highly likely financial bug, run `variant-analysis`.

Search the entire repository for the same root cause.

Example:

if a duplicate payout bug exists in withdrawals, search for the same pattern in:

- refunds
- cashback
- merchant settlement
- affiliate payout
- bonus payout
- commissions
- transfers
- chargebacks
- reconciliation
- crypto withdrawals

Do not limit variant analysis to matching function names.

Search structurally for the underlying bug pattern.

---

## Phase 14 — Property-based tests

For important findings and critical flows, use `property-based-testing`.

Suggest concrete properties/invariants that should become automated tests.

Examples:

For every operation ID:

external_side_effect_count(operation_id) <= 1

For every completed payout:

exactly one provider transaction exists

For every provider transaction:

at most one internal successful payout references it

For every balanced ledger transaction:

sum(debits) == sum(credits)

For every duplicate event:

process(event)
process(event)

must produce the same financial result as:

process(event)

Test retry sequences such as:

PROCESS
TIMEOUT
RETRY
WEBHOOK
RETRY
RECONCILE

and arbitrary permutations.

Where appropriate propose state-machine/property-based tests.

---

# Severity model

Use severity based primarily on financial impact.

## Critical

Examples:

- arbitrary money creation
- arbitrary withdrawal
- double payout
- double spend
- authorization bypass causing money movement
- attacker-controlled balance manipulation
- systemic ledger corruption
- widespread duplicate settlement

## High

Examples:

- realistic duplicate payment under race condition
- reproducible inconsistent balance
- provider/internal state divergence causing financial loss
- replayable financial webhook
- refund amount exceeding original payment

## Medium

Examples:

- financial inconsistency requiring unusual timing
- recoverable ledger mismatch
- operational reconciliation issue

## Low

Do not inflate severity for theoretical issues without plausible financial consequences.

---

# Required final report

Return findings ordered by financial risk.

For each finding include:

### [Severity] Title

**Confidence:** Confirmed / Highly likely / Needs runtime verification

**Affected flow**

Describe the financial operation.

**Files and code locations**

Provide exact files/functions/lines where possible.

**Invariant violated**

State the financial invariant that is broken.

**Root cause**

Explain the underlying design/code problem.

**Execution scenario**

Give a concrete sequence.

For concurrency issues provide:

T1 | T2

timeline.

For partial failures provide the precise crash/timeout window.

**Financial impact**

Explain exactly how money/state can become incorrect.

Examples:

- two payouts instead of one
- balance credited twice
- balance debited zero times
- provider paid but internal DB reports failed
- duplicate ledger entries
- reconciliation permanently diverges

**Existing protections**

Describe protections already present and why they are insufficient.

**Proof / evidence**

Show the exact code path demonstrating the issue.

**Recommended fix**

Prefer systemic fixes over local `if` checks.

Examples:

- DB unique constraint
- atomic conditional update
- row-level locking
- serializable transaction
- transactional outbox
- durable idempotency record
- provider idempotency key
- inbox/deduplication table
- explicit UNKNOWN state
- reconciliation mechanism

**Regression/property test**

Describe the test that should permanently prevent recurrence.

**Variants**

List other flows containing the same underlying pattern.

---

# Important audit rules

Do not spend excessive time on low-value issues such as:

- generic code style
- minor linting
- naming
- obvious dependency warnings

unless they create a meaningful security or financial risk.

Prioritize monetary correctness above everything else.

Assume:

- requests can execute concurrently
- workers can execute concurrently
- messages can be duplicated
- messages can be reordered
- network requests can timeout after succeeding
- processes can crash at any instruction
- clients can intentionally replay requests
- external services can return ambiguous results

Never treat "this is unlikely" as sufficient protection for a financial invariant.

The core question throughout the audit is:

> Can any sequence of retries, concurrent requests, duplicated messages, reordered events, crashes, timeouts, or state transitions cause the system to move a different amount of money than intended?

Continue until all major money-moving flows have been analyzed.