Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 232 additions & 0 deletions PULL_REQUEST.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
# Pull Request: Add Comprehensive E2E Test Suite for Cross-Border Payments

## Overview

This PR adds a comprehensive end-to-end test suite that simulates the complete cross-border payment flow, including KYC submission, quote generation, and final settlement. The test suite validates the full implementation of SEP-31 cross-border payments alongside existing SEP-10, SEP-12, SEP-24, and SEP-38 functionality.

## Motivation

The AnchorPoint dashboard needed comprehensive testing to ensure reliable operation of complex financial flows. Cross-border payments involve multiple SEPs (SEP-10, SEP-12, SEP-31) and require careful validation of the entire user journey from authentication through settlement. This E2E test suite provides confidence in the system's ability to handle real-world payment scenarios.

## What Changed

### 1. E2E Test Infrastructure
**Files:**
- `backend/src/test/e2e.test.ts` (extended)
- `backend/src/test/sep31-e2e.test.ts` (new)

- Added comprehensive test coverage for SEP-31 cross-border payments
- Extended existing E2E tests to include SEP-12 KYC flows
- Created focused test suite for SEP-31 payment lifecycle
- Added mocking for external services (KYC providers, price feeds, callbacks)

### 2. API Route Configuration
**File:** `backend/src/index.ts`

- Added SEP-31 route mounting (`/sep31`)
- Added SEP-12 route mounting (`/sep12`)
- Ensured proper middleware application for public endpoints

### 3. Admin API for Transaction Management
**File:** `backend/src/api/routes/admin.route.ts`

- Added `PATCH /api/admin/transactions/:id` endpoint for updating transaction status
- Implemented status validation and callback notifications
- Added support for settlement data (Stellar TX ID, external TX ID, amounts)

### 4. Test Dependencies
**File:** `backend/package.json`

- Added `nock` for HTTP request mocking
- Added test scripts: `test:e2e` and `test:sep31`

### 5. Documentation Updates
**File:** `README.md`

- Added comprehensive testing section
- Documented E2E test coverage and execution
- Included example test flows and API interactions

## Technical Details

### Test Coverage

The E2E test suite validates:

1. **SEP-1 Info**: Asset configuration and endpoint discovery
2. **SEP-10 Authentication**: Challenge generation and JWT token flow
3. **SEP-12 KYC**: Customer information submission and status tracking
4. **SEP-31 Payments**: Complete cross-border payment lifecycle
5. **SEP-38 Quotes**: Price discovery with external API integration
6. **SEP-24 Interactive**: Deposit/withdrawal flow initiation

### SEP-31 Payment Flow Testing

The test suite simulates the complete payment journey:

```
KYC Submission → Transaction Creation → Status Updates → Settlement
```

**Key Test Scenarios:**
- Multi-party KYC validation (sender and receiver)
- Transaction status progression through all SEP-31 states
- Callback notification handling
- Final settlement with transaction ID recording
- Error handling and validation

### Mocking Strategy

- **KYC Provider**: Simulates third-party KYC service responses
- **Price Feeds**: Mocks CoinGecko API for quote generation
- **Callbacks**: Validates merchant notification endpoints
- **Authentication**: Bypasses SEP-10 for focused testing

## API Changes

### New Admin Endpoint

```http
PATCH /api/admin/transactions/:id
```

**Request Body:**
```json
{
"status": "completed",
"stellar_transaction_id": "stellar_tx_123",
"external_transaction_id": "bank_transfer_456",
"amount_out": "99.50",
"amount_fee": "0.50"
}
```

**Response:**
```json
{
"message": "Transaction status updated successfully",
"transaction": { /* updated transaction object */ }
}
```

## Testing

### Prerequisites

```bash
# Start Docker services
docker-compose up -d

# Generate Prisma client
cd backend && npx prisma generate
```

### Running Tests

```bash
# Full E2E test suite
cd backend && npm run test:e2e

# SEP-31 specific tests
cd backend && npm run test:sep31

# With coverage
npm run test:coverage
```

### Test Structure

```
backend/src/test/
├── e2e.test.ts # Comprehensive multi-SEP test suite
└── sep31-e2e.test.ts # Focused cross-border payment tests
```

### Mock Data

The tests use realistic mock data:
- Stellar public keys for test accounts
- Complete KYC information sets
- Valid transaction amounts and fees
- Proper callback URLs and signatures

## Database Considerations

- Tests use SQLite database (configured via `DATABASE_URL`)
- Automatic cleanup between test runs
- No persistent data modifications
- Isolated test environment

## Security Validation

The test suite validates:
- **Input sanitization** for all API endpoints
- **Authentication bypass** prevention (mocked appropriately)
- **Data encryption** for PII in SEP-12 flows
- **Rate limiting** effectiveness
- **Error handling** for invalid requests

## Performance Impact

- Tests run efficiently with mocked external services
- No real network calls to Stellar Horizon or external APIs
- Database operations are optimized for test scenarios
- Parallel test execution support

## Future Enhancements

The test foundation enables:
- **Frontend E2E tests** with Playwright/Cypress
- **Load testing** for high-volume scenarios
- **Integration tests** with real Stellar network
- **Multi-currency support** validation
- **Regulatory compliance** verification

## Breaking Changes

None. This PR adds new test infrastructure without modifying existing functionality.

## Checklist

- [x] Tests pass in isolated environment
- [x] No breaking changes to existing APIs
- [x] Comprehensive documentation added
- [x] Mock services properly configured
- [x] Database cleanup implemented
- [x] Error scenarios covered
- [x] Performance considerations addressed
- malformed or invalid transaction XDR
- expired or missing challenge data
- invalid operation type
- wrong challenge payload
- signature verification failure

## Notes for Reviewers

- This change is scoped to SEP-10 authentication only and does not alter SEP-24 or SEP-12 flows.
- The backend retains the existing JWT issuance strategy, using the challenge transaction only for authentication.
- Hardware wallets now receive a proper transaction envelope they can sign, improving compatibility with Trezor and Ledger.

## Files Changed

- `backend/src/utils/sep10-stellar.ts`
- `backend/src/services/auth.service.ts`
- `backend/src/api/controllers/auth.controller.ts`
- `backend/src/config/env.ts`
- `backend/src/services/webhook.service.ts` (merge conflict cleanup)
- `README.md`

## Future Improvements

- Add explicit support for custom derivation paths in wallet integrations
- Add multi-signature SEP-10 support for hardware-backed multisig accounts
- Integrate with wallet connection libraries for better UX

## Checklist

- [x] Generate SEP-10 challenge transaction XDR
- [x] Store challenge metadata and XDR for verification
- [x] Verify signatures from hardware wallets
- [x] Support both `testnet` and `public` networks
- [x] Document hardware wallet support

91 changes: 90 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ The entry point for any anchor. It defines the supported assets and the URLs for
### 2. SEP-10: Stellar Web Authentication
Before initiating transactions, the dashboard must authenticate the user's wallet.
- The dashboard requests a challenge transaction from the anchor.
- The user signs it with their wallet (e.g., Freight, Albedo, or Rabe).
- The user signs it with their wallet (e.g., Freight, Albedo, Rabe, **Trezor, or Ledger**).
- The dashboard submits the signed transaction to get a JWT.

**Hardware Wallet Support**: AnchorPoint now supports hardware wallets (Trezor, Ledger) for SEP-10 authentication. The backend generates proper Stellar transactions with manage_data operations containing the challenge, which hardware wallets can sign using their secure elements. This ensures compatibility with hardware wallets that require specific transaction structures and signature algorithms.

### 3. SEP-24: Interactive Flows
The core of AnchorPoint.
- **Deposit**: Request `/transactions/deposit/interactive`. The anchor returns a URL to a webview.
Expand Down Expand Up @@ -117,3 +119,90 @@ docker-compose down -v
### Development

For local development without Docker, see the [Backend README](./backend/README.md).

## Testing

### End-to-End Test Suite

The project includes a comprehensive end-to-end test suite that simulates a complete cross-border payment flow, including:

- **SEP-10 Authentication**: Challenge generation and signature verification (mocked for testing)
- **SEP-12 KYC Submission**: Customer information upload and status tracking
- **SEP-31 Cross-Border Payments**: Transaction creation, status updates, and settlement
- **SEP-38 Quotes**: Price discovery and quote generation
- **SEP-24 Deposits/Withdrawals**: Interactive deposit and withdrawal flows

#### Running E2E Tests

```bash
# Ensure Docker services are running
docker-compose up -d

# Run the full E2E test suite
cd backend
npm run test:e2e

# Run SEP-31 specific cross-border payment tests
npm run test:sep31
```

#### Test Coverage

The E2E test suite covers:

1. **SEP-1 Info**: Stellar.toml configuration and asset discovery
2. **SEP-10 Auth**: Challenge-response authentication flow (mocked)
3. **SEP-12 KYC**: Customer information submission and webhook updates
4. **SEP-31 Payments**: Full cross-border payment lifecycle from creation to settlement
5. **SEP-38 Quotes**: Firm quote generation with external price feeds
6. **SEP-24 Interactive**: Deposit/withdrawal flow initiation
7. **Complete Flow Integration**: End-to-end flow from KYC submission through final settlement

#### Test Flow Example

```typescript
// 1. SEP-10 Authentication (Mocked for testing)
const authToken = 'mock-jwt-token-for-e2e-testing';

// 2. SEP-12 KYC Submission
const kycRes = await request(app)
.put('/sep12/customer')
.set('Authorization', `Bearer ${authToken}`)
.field('account', clientPublicKey)
.field('first_name', 'John')
.field('last_name', 'Doe');

// 3. SEP-38 Quote Generation
const quoteRes = await request(app)
.post('/sep38/quote')
.set('Authorization', `Bearer ${authToken}`)
.send({
source_asset: 'USDC',
source_amount: '100',
destination_asset: 'XLM'
});

// 4. SEP-31 Transaction Creation
const transaction = await request(app)
.post('/sep31/transactions')
.set('Authorization', `Bearer ${authToken}`)
.send({
asset_code: 'USDC',
amount: '100.00',
sender_info: { /* KYC data */ },
receiver_info: { /* KYC data */ }
});

// 5. Status Updates and Settlement
await request(app)
.patch(`/api/admin/transactions/${transaction.id}`)
.send({
status: 'completed',
stellar_transaction_id: 'tx_123',
external_transaction_id: 'bank_tx_456',
amount_out: '99.50',
amount_fee: '0.50'
});
```

The test suite ensures compliance with Stellar Ecosystem Proposals and validates the complete user journey from authentication to final settlement, including proper callback handling and status transitions.
Loading