Skip to content

Harden Nexus Bitcoin services for sandbox production-readiness#15

Draft
support371 wants to merge 21 commits into
mainfrom
feat/nexus-production-hardening-20260621
Draft

Harden Nexus Bitcoin services for sandbox production-readiness#15
support371 wants to merge 21 commits into
mainfrom
feat/nexus-production-hardening-20260621

Conversation

@support371

@support371 support371 commented Jun 21, 2026

Copy link
Copy Markdown
Owner

Summary

This branch turns the existing fintech/Nexus prototype into a safer, testable backend baseline without enabling live money movement.

Included

  • repairs the invalid root vercel.json
  • adds HMAC-SHA256 authentication and timestamp replay protection for internal service calls
  • enforces KYC Tier 3+ for card issuance and fund loading
  • makes card issuance and fiat-to-BTC conversion sandbox-first and fail-closed
  • blocks live payments and live card issuance until a verified adapter and explicit approval exist
  • adds PostgreSQL-backed production idempotency with a development/test fallback
  • adds the core users, idempotency, ledger, conversion, and card database migration
  • adds an append-only audit writer foundation
  • adds .env.example, unit tests, and a GitHub CI workflow
  • updates the README with deployment and production gates

Validation performed

  • Python source compilation: passed for the new core modules
  • internal HMAC tests: passed
  • sandbox conversion and live-mode blocking tests: passed
  • Vercel configuration test added to CI

Safety state

  • PAYMENTS_MODE=sandbox
  • CARD_ISSUANCE_MODE=sandbox
  • ALLOW_LIVE_PAYMENTS=false
  • ALLOW_LIVE_CARD_ISSUANCE=false
  • no production credentials or secrets are included

Remaining external gates

  • GitHub CI must pass
  • PostgreSQL migration must be applied in the target environment
  • provider webhook behavior must be verified against official provider documentation
  • live provider adapters require separate security/compliance review and explicit owner approval

Summary by Sourcery

Harden Nexus card and conversion services for sandbox-only operation with authenticated internal traffic, database-backed idempotency, and production-ready configuration and CI.

New Features:

  • Introduce HMAC-authenticated internal request signing and verification for service-to-service calls.
  • Add sandbox-only fiat-to-BTC conversion and card issuance flows gated by configurable KYC tier thresholds.
  • Provide persistent idempotency storage backed by PostgreSQL with a safe in-memory fallback for non-production environments.
  • Add an append-only audit logger and core database schema for users, conversions, cards, idempotency keys, and ledger events.

Enhancements:

  • Tighten converter and card platform readiness and health endpoints to validate secrets, database connectivity, and operating modes before serving traffic.
  • Refine conversion logic to enforce AML limits, supported currency lists, and deterministic sandbox BTC rates while failing closed for live payments.
  • Restructure card platform client logic to enforce sandbox-first issuance, explicit live-mode approvals, and stricter error handling for downstream service failures.
  • Update service metadata, logging, and README documentation to reflect Nexus branding, sandbox-only operation, and production gating requirements.

Build:

  • Validate the root Vercel configuration and ensure routes are correctly wired to the FastAPI services.

CI:

  • Introduce a GitHub Actions CI workflow to install dependencies, validate Vercel configuration, compile Python modules, and run tests.

Documentation:

  • Add an example environment file and expand README documentation with service endpoints, local setup instructions, deployment routing, and production readiness gates.

Tests:

  • Add unit tests for conversion logic sandbox behavior, AML limits, and fail-closed live mode handling.
  • Add unit tests for internal HMAC request signing and verification and for idempotency behavior in different environments.
  • Add a test to validate the Vercel routing configuration for card and converter services.

@bolt-new-by-stackblitz

Copy link
Copy Markdown

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@vercel

vercel Bot commented Jun 21, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
fintech-microservices-core Ready Ready Preview, Comment Jun 21, 2026 12:35pm
fintech-microservices-core-64vb Ready Ready Preview, Comment Jun 21, 2026 12:35pm
fintech-microservices-core-73p3 Ready Ready Preview, Comment Jun 21, 2026 12:35pm
fintech-microservices-core-a1p8 Ready Ready Preview, Comment Jun 21, 2026 12:35pm
support371-fintech-microservices-core Ready Ready Preview, Comment Jun 21, 2026 12:35pm

@sourcery-ai

sourcery-ai Bot commented Jun 21, 2026

Copy link
Copy Markdown

Reviewer's Guide

Hardens the Nexus card and converter microservices for sandbox-only, production-ready operation by adding HMAC-authenticated internal traffic, deterministic sandbox conversion, PostgreSQL-backed idempotency and audit logging, stricter KYC enforcement, and CI/tests to validate configuration and security behavior.

Sequence diagram for sandbox fund loading with HMAC and idempotency

sequenceDiagram
    actor Client
    participant CardAPI as card_platform_main
    participant CardLogic as CardPlatformLogic
    participant ConverterAPI as converter_main
    participant Idempotency as IdempotencyStore
    participant Conversion as ConversionLogic

    Client->>CardAPI: load_card_funds
    CardAPI->>CardLogic: transfer_fiat_to_crypto(user_id, fiat_amount, fiat_currency)
    CardLogic->>CardLogic: sign_internal_request
    CardLogic->>ConverterAPI: POST /internal/transfer_funds
    Note right of CardLogic: headers INTERNAL_TIMESTAMP_HEADER, INTERNAL_SIGNATURE_HEADER

    ConverterAPI->>ConverterAPI: verify_internal_request
    ConverterAPI->>Idempotency: begin(transaction_key)
    alt [key already completed]
        ConverterAPI->>Idempotency: get_completed_response
        Idempotency-->>ConverterAPI: response
        ConverterAPI-->>CardLogic: idempotent_replay response
    else [new processing]
        ConverterAPI->>Conversion: execute_conversion_and_payout
        Conversion-->>ConverterAPI: conversion_result
        ConverterAPI->>Idempotency: complete(transaction_key, conversion_result)
        ConverterAPI-->>CardLogic: success response
    end

    CardLogic-->>CardAPI: response
    CardAPI-->>Client: conversion_initiated
Loading

Entity relationship diagram for Nexus core fintech schema

erDiagram
    users {
        TEXT user_id PK
        SMALLINT kyc_tier
        TEXT kyc_status
    }

    nexus_idempotency_keys {
        TEXT idempotency_key PK
        TEXT status
        JSONB response_json
    }

    nexus_ledger_events {
        TEXT event_id PK
        TEXT event_type
        TEXT actor_type
        TEXT actor_id
        TEXT subject_id
        TEXT trace_id
        JSONB event_data
    }

    nexus_conversion_records {
        TEXT transaction_key PK
        TEXT user_id FK
        NUMERIC fiat_amount
        CHAR3 fiat_currency
        NUMERIC btc_amount
        BIGINT satoshis
        TEXT payment_mode
        TEXT status
    }

    nexus_card_records {
        TEXT card_id PK
        TEXT user_id FK
        TEXT card_mode
        TEXT status
    }

    users ||--o{ nexus_conversion_records : has_conversions
    users ||--o{ nexus_card_records : has_cards
    users ||--o{ nexus_ledger_events : has_events
    nexus_idempotency_keys ||--o{ nexus_conversion_records : correlates
    nexus_ledger_events ||--o{ nexus_conversion_records : logs
Loading

File-Level Changes

Change Details Files
Introduce PostgreSQL-backed idempotency for conversion and webhook processing with a safe in-memory fallback for non-production.
  • Add IdempotencyStore abstraction that uses a nexus_idempotency_keys table in PostgreSQL when DATABASE_URL is set and APP_ENV=production, otherwise a guarded in-memory map
  • Wire converter_service endpoints through a _process_transaction helper that claims idempotency keys, returns stored responses on replay, and releases keys on failure
  • Add tests to ensure in-memory behavior in non-production and fail-closed behavior in production without DATABASE_URL
converter_service/idempotency.py
converter_service/main.py
migrations/001_core_schema.sql
tests/test_idempotency.py
Strengthen service-to-service and webhook security using HMAC-SHA256 with timestamp-based replay protection and deterministic payload signing.
  • Add common.security helpers to sign and verify internal requests with timestamp-based HMAC, including configurable tolerance
  • Require INTERNAL_SERVICE_SECRET and signed body for internal /internal/transfer_funds calls, rejecting invalid or stale signatures
  • Normalize and validate webhook signatures using STRIGA_WEBHOOK_SECRET with constant-time comparison
  • Add unit tests covering internal signing/verification and Vercel routing
common/security.py
converter_service/main.py
converter_service/logic.py
card_platform_service/clients.py
tests/test_security.py
tests/test_vercel_config.py
Make conversion logic sandbox-first, deterministic, and fail-closed for live mode with configurable AML limits and fiat support.
  • Refactor ConversionLogic to accept Decimal inputs, enforce AML_SINGLE_TRANSACTION_LIMIT, and validate SUPPORTED_FIAT_CURRENCIES
  • Add sandbox BTC rate loading from SANDBOX_BTC_RATES_JSON and return deterministic simulated conversion results, including satoshis and rate metadata
  • Ensure PAYMENTS_MODE defaults to sandbox and raise clear RuntimeErrors if live mode is selected without explicit ALLOW_LIVE_PAYMENTS approval and a real adapter
  • Add unit tests validating sandbox determinism, AML rejection, and live-mode fail-closed behavior
converter_service/logic.py
tests/test_conversion_logic.py
Enforce KYC Tier 3+ for card issuance and fund loading, and keep card issuance sandbox-only with fail-closed live mode.
  • Replace persistent DB connection in CardPlatformLogic with on-demand connections via DATABASE_URL or legacy DB_* variables with SSL configuration
  • Add get_user_kyc_tier and is_kyc_tier_approved helpers with configurable minimum KYC tier, and require Tier>=3 in a shared _approved_kyc_tier function
  • Implement sandbox-only issue_new_card that simulates card issuance; reject live mode unless CARD_ISSUANCE_MODE=sandbox and ALLOW_LIVE_CARD_ISSUANCE is explicitly true and a real adapter exists
  • Update card issuance and funds load endpoints to use Decimal validation, structured error handling, and more descriptive status codes
card_platform_service/clients.py
card_platform_service/main.py
migrations/001_core_schema.sql
Add append-only audit logging and core database schema for users, ledger events, conversions, cards, and idempotency.
  • Introduce AuditLogger that writes structured events to nexus_ledger_events in PostgreSQL with a logging-only fallback for non-production
  • Define core tables for users, nexus_idempotency_keys, nexus_ledger_events, nexus_conversion_records, and nexus_card_records with integrity constraints and indexes
  • Guard production audit logging against missing DATABASE_URL to prevent silent loss of audit trails
common/audit.py
migrations/001_core_schema.sql
Harden FastAPI services with typed models, readiness checks, sandbox-only modes, and improved logging/health behavior.
  • Upgrade converter_service FastAPI app metadata, health/ready endpoints, and internal/webhook handlers to use Pydantic Field constraints, Decimal, UUID trace IDs, and richer health diagnostics including payment_mode and config checks
  • Add card_platform_service readiness check that validates CONVERTER_INTERNAL_URL, INTERNAL_SERVICE_SECRET, and database availability, and include card_mode in health output
  • Standardize JSON logging formats and improve error logging and HTTPException responses for clearer operational diagnostics
converter_service/main.py
card_platform_service/main.py
Add CI, environment examples, and README updates to document sandbox-only operation and deployment gates.
  • Introduce a GitHub Actions CI workflow that installs dev dependencies, validates vercel.json, compiles Python modules, and runs pytest
  • Add .env.example and requirements-dev.txt to standardize local setup and testing
  • Update README to describe current sandbox safety state, service endpoints, Vercel routing, prototype and Foundry locations, and explicit production approval gates
  • Ensure vercel.json routes /api/v1, /webhook, /internal, and /health to the appropriate FastAPI entrypoints and add tests to enforce this
.github/workflows/ci.yml
.env.example
requirements-dev.txt
README.md
vercel.json
tests/test_vercel_config.py
common/__init__.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@socket-security

socket-security Bot commented Jun 21, 2026

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedpypi/​pytest@​9.1.187100100100100
Addedpypi/​httpx@​0.28.1100100100100100

View full report

Copy link
Copy Markdown
Owner Author

Validation update (2026-06-21):

  • Python compilation passed for the new core modules.
  • Local security, sandbox conversion, live-mode blocking, and idempotency tests passed.
  • The latest GitHub Actions attempt failed before any workflow step started (steps: []), and the job log archive returned unavailable/BlobNotFound.
  • A gateway credential validator and tests were added, but card/funding routes are not yet exposed through the Nexus product API. The product integration remains read-only until route-level gateway enforcement is accepted and verified.

This PR remains draft, mergeable, sandbox-only, and unmerged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant