From e8e49ebbdc56b1b434ad7b30e8c9019cccde4ad2 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 20 Aug 2025 16:24:07 +0200 Subject: [PATCH 01/93] Criar test --- test | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 test diff --git a/test b/test new file mode 100644 index 0000000..c2b2428 --- /dev/null +++ b/test @@ -0,0 +1,14 @@ +Hi Ricardo, Florian, + +Just following up on this week’s discussions — we have identified some pending items that were not fully covered in the current design solution. Since the requirements and scope remain the same as previously shared, I’ll summarize the key points below: + +⸻ + +Privacy Layer – Design Solution L2 + • Swap Smart Contract with custom privacy: all requirement details were already shared via email (Privacy Solution Challenge, Solution & Next Steps). This involves Pente, where the privacy group provides a solid design solution with all components involved and an end-to-end flow. + • The Paladin SDK is not compatible with Java implementations. Our expectation is that you provide a solution for this gap. At the moment, this is blocking the development team, as it is still unclear which design solution to adopt. + +Enterprise Bridge Privacy Solution + • Provide all Smart Contract Bridges and off-chain components involved in this flow. + • Deliver a sequence diagram representing the two-way interaction between the Enterprise Network and the Paladin Node (Noto). + • Set up a Paladin node for the Bridge. From b5dcfb57f29ad9276ffb8eebed3fadfe42e43212 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 20 Aug 2025 16:28:46 +0200 Subject: [PATCH 02/93] Atualizar o test --- test | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/test b/test index c2b2428..e69de29 100644 --- a/test +++ b/test @@ -1,14 +0,0 @@ -Hi Ricardo, Florian, - -Just following up on this week’s discussions — we have identified some pending items that were not fully covered in the current design solution. Since the requirements and scope remain the same as previously shared, I’ll summarize the key points below: - -⸻ - -Privacy Layer – Design Solution L2 - • Swap Smart Contract with custom privacy: all requirement details were already shared via email (Privacy Solution Challenge, Solution & Next Steps). This involves Pente, where the privacy group provides a solid design solution with all components involved and an end-to-end flow. - • The Paladin SDK is not compatible with Java implementations. Our expectation is that you provide a solution for this gap. At the moment, this is blocking the development team, as it is still unclear which design solution to adopt. - -Enterprise Bridge Privacy Solution - • Provide all Smart Contract Bridges and off-chain components involved in this flow. - • Deliver a sequence diagram representing the two-way interaction between the Enterprise Network and the Paladin Node (Noto). - • Set up a Paladin node for the Bridge. From 41c3db6a001f03a5de2e90a366086c32535ff795 Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 21 Aug 2025 11:35:39 +0200 Subject: [PATCH 03/93] Atualizar o test --- test | 1 + 1 file changed, 1 insertion(+) diff --git a/test b/test index e69de29..4ced095 100644 --- a/test +++ b/test @@ -0,0 +1 @@ +The DevOps CI/CD pipeline integrates source code management, build automation, and deployment into a streamlined process that ensures rapid and reliable delivery of application updates. Source code is managed in public repositories (GitHub, Docker Hub), where commits trigger the AWS Code and AWS Pipeline services to orchestrate automated builds, tests, and deployments. Application artifacts and container images are stored securely in the AWS Container Registry and S3 Artifact Store, ensuring version control and traceability. Once validated, updated services are deployed into the Swift API Sandbox environment on Google Cloud Platform, where the Application API and OAuth Server are hosted. This setup enables a fully automated, secure, and auditable workflow from code commit to production deployment, supporting agility while maintaining compliance and reliability. \ No newline at end of file From 9675e9e269b7d2e1310de5e197a22450e3f7797b Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 21 Aug 2025 11:39:21 +0200 Subject: [PATCH 04/93] Atualizar o test --- test | 1 - 1 file changed, 1 deletion(-) diff --git a/test b/test index 4ced095..e69de29 100644 --- a/test +++ b/test @@ -1 +0,0 @@ -The DevOps CI/CD pipeline integrates source code management, build automation, and deployment into a streamlined process that ensures rapid and reliable delivery of application updates. Source code is managed in public repositories (GitHub, Docker Hub), where commits trigger the AWS Code and AWS Pipeline services to orchestrate automated builds, tests, and deployments. Application artifacts and container images are stored securely in the AWS Container Registry and S3 Artifact Store, ensuring version control and traceability. Once validated, updated services are deployed into the Swift API Sandbox environment on Google Cloud Platform, where the Application API and OAuth Server are hosted. This setup enables a fully automated, secure, and auditable workflow from code commit to production deployment, supporting agility while maintaining compliance and reliability. \ No newline at end of file From 830dc448435a1833f19124bff4889f698cf5ac8d Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 21 Aug 2025 14:20:51 +0200 Subject: [PATCH 05/93] Atualizar o test --- test | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/test b/test index e69de29..afc65dc 100644 --- a/test +++ b/test @@ -0,0 +1,82 @@ +4.2.2.2 Backend API + +The Backend API, built on Spring Boot, is the orchestration hub for all business processes. Beyond request validation and persistence, it is directly responsible for preparing and submitting blockchain transactions. To do so, the Backend API invokes the WalletConfigHelper to retrieve the appropriate signing key or account configuration. This ensures separation of concerns between transaction orchestration and key management. + +Once a transaction is prepared, the Backend API calls the RelayerHelper to handle signing and submission to the RPC node. Smart contract functions are invoked via ABI-encoded payloads generated by the Backend API, ensuring that business workflows are consistently enforced on-chain. In the prototype, these responsibilities remain centralized in the Backend API, with helpers annotated as @Component to allow seamless refactoring into standalone services in later phases. + +⸻ + +4.2.2.3 Relayer Service (Next Phase) + +The Relayer Service ensures reliable and nonce-safe submission of transactions to the blockchain network. It encapsulates low-level responsibilities such as transaction signing, nonce management, gas policy enforcement, and retry/backoff strategies. The Relayer relies on Web3J for encoding, signing, and broadcasting transactions over JSON-RPC. + +In the prototype, these capabilities are abstracted as a RelayerHelper. This helper receives unsigned payloads from the Backend API, obtains the signing key via WalletConfigHelper, signs them, and uses Web3J to submit them directly to the RPC node. In the next phase, the helper will evolve into a dedicated service, enabling horizontal scalability, centralized nonce queues, and clearer separation between orchestration (Backend API) and execution (Relayer). + + +4.2.2.9 Smart Contracts + +Smart contracts define the on-chain business logic that governs issuance, transfers, and settlements. They encapsulate the rules for token lifecycle management, validation of participants, and enforcement of workflows such as atomic swaps. The Backend API interacts with these contracts via ABI-encoded function calls submitted as signed transactions. + +In the prototype, contracts are deployed on the Linea L2 test environment, with interaction handled directly by the Backend API. In future phases, these contracts will integrate more tightly with Relayer Services and Event Listeners to enable richer orchestration and monitoring. + +⸻ + +4.2.2.10 Contract Bridges + +Bridges provide interoperability between the platform and external networks, such as SWIFT or other DLT ecosystems. They act as a trusted relay for data and asset transfers, ensuring that events in one domain are consistently reflected in another. The Bridge component validates external attestations, manages acknowledgements, and enforces regulatory compliance. + +In the prototype, bridging logic is abstracted using a BridgeHelper inside the Backend API, returning mock responses. The actual bridge implementation will be added in the next phase to support secure cross-network transaction settlement. + +⸻ + +4.2.2.11 Gas Fee Responsibility + +All on-chain operations require gas to be executed on the blockchain. Responsibility for gas payment depends on the architecture: in the prototype, the Backend API directly signs and submits transactions using a dedicated service account, which covers the gas cost. This ensures predictable testing without requiring participants to manage their own gas balances. + +In the next phase, the Relayer Service will manage gas sponsorship more explicitly. It may implement a sponsored transaction model, where the Relayer pays gas on behalf of users, or enforce a quota model, where participants deposit funds in advance. This abstraction ensures that business actors (Issuer, Buyer, Bank) are shielded from direct gas management, while still allowing governance rules to define cost allocation + +4.2.2.3 Relayer Service (Next Phase) + +The Relayer Service is responsible for nonce-safe submission of signed transactions to the blockchain, implementing retry strategies, gas sponsorship, and idempotency. It acts as a controlled gateway to the blockchain, decoupling transaction submission from backend logic. + +In the prototype, this functionality is represented by a RelayerHelper within the Backend API. This helper signs transactions via KMS and submits them directly to the node. In the next phase, the helper will be replaced by a standalone service to improve scalability and resilience. + +⸻ + +4.2.2.4 Event Listener / Indexer (Next Phase) + +The Event Listener subscribes to contract events and normalizes them into application-friendly formats. It updates the backend with confirmations, state changes, and derived business events. This allows the system to replace ad-hoc polling with structured event processing. + +For the prototype, event consumption is abstracted through an EventReaderHelper that queries receipts or logs directly from the blockchain. In the next phase, the Event Listener will be deployed as a dedicated service, ensuring real-time synchronization between on-chain state and backend persistence. + +⸻ + +4.2.2.5 Notification Service (Next Phase) + +The Notification Service delivers outbound alerts to stakeholders via email, SMS, or webhooks, triggered by specific business events such as transaction settlement or contract state changes. This improves transparency and user engagement across participants. + +In the prototype, notifications are mocked through a NotificationHelper inside the Backend API. This allows the system to demonstrate workflows without requiring external delivery channels, while still maintaining consistent interfaces for future integration. + +⸻ + +4.2.2.6 Bridge Connector (Next Phase) + +The Bridge Connector enables interoperability between the blockchain platform and external networks (e.g., SWIFT integration). It validates cross-domain operations, manages attestations, and ensures consistency of settlement information across systems. + +For the prototype, this component is abstracted using a BridgeHelper that returns deterministic mock responses. In future phases, the connector will be implemented as a secure microservice, handling real cross-network communication and regulatory compliance requirements. + +⸻ + +4.2.2.7 KMS Integration + +The Key Management Service (KMS) provides secure custody of cryptographic keys used for signing transactions. The Backend API interacts with KMS over HTTPS, ensuring private keys never leave the secure enclave. This enhances security and compliance for sensitive financial operations. + +KMS is fully integrated in the prototype, supporting signing requests initiated by the Backend API. This integration remains unchanged across phases, forming the foundation of secure transaction execution. + +⸻ + +4.2.2.8 Database + +A relational database (e.g., PostgreSQL) serves as the system of record for off-chain data, including user requests, transaction metadata, mappings, and audit logs. The Backend API ensures consistent writes and supports query interfaces for reporting and monitoring. + +The database is already part of the prototype and will remain central to subsequent phases. Future improvements may include event-sourced projections populated by the Event Listener, enriching the read model with real-time on-chain updates From 955684cd24a912f356431d3326f9162685ff70a7 Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 21 Aug 2025 14:28:32 +0200 Subject: [PATCH 06/93] Atualizar o test --- test | 82 ------------------------------------------------------------ 1 file changed, 82 deletions(-) diff --git a/test b/test index afc65dc..e69de29 100644 --- a/test +++ b/test @@ -1,82 +0,0 @@ -4.2.2.2 Backend API - -The Backend API, built on Spring Boot, is the orchestration hub for all business processes. Beyond request validation and persistence, it is directly responsible for preparing and submitting blockchain transactions. To do so, the Backend API invokes the WalletConfigHelper to retrieve the appropriate signing key or account configuration. This ensures separation of concerns between transaction orchestration and key management. - -Once a transaction is prepared, the Backend API calls the RelayerHelper to handle signing and submission to the RPC node. Smart contract functions are invoked via ABI-encoded payloads generated by the Backend API, ensuring that business workflows are consistently enforced on-chain. In the prototype, these responsibilities remain centralized in the Backend API, with helpers annotated as @Component to allow seamless refactoring into standalone services in later phases. - -⸻ - -4.2.2.3 Relayer Service (Next Phase) - -The Relayer Service ensures reliable and nonce-safe submission of transactions to the blockchain network. It encapsulates low-level responsibilities such as transaction signing, nonce management, gas policy enforcement, and retry/backoff strategies. The Relayer relies on Web3J for encoding, signing, and broadcasting transactions over JSON-RPC. - -In the prototype, these capabilities are abstracted as a RelayerHelper. This helper receives unsigned payloads from the Backend API, obtains the signing key via WalletConfigHelper, signs them, and uses Web3J to submit them directly to the RPC node. In the next phase, the helper will evolve into a dedicated service, enabling horizontal scalability, centralized nonce queues, and clearer separation between orchestration (Backend API) and execution (Relayer). - - -4.2.2.9 Smart Contracts - -Smart contracts define the on-chain business logic that governs issuance, transfers, and settlements. They encapsulate the rules for token lifecycle management, validation of participants, and enforcement of workflows such as atomic swaps. The Backend API interacts with these contracts via ABI-encoded function calls submitted as signed transactions. - -In the prototype, contracts are deployed on the Linea L2 test environment, with interaction handled directly by the Backend API. In future phases, these contracts will integrate more tightly with Relayer Services and Event Listeners to enable richer orchestration and monitoring. - -⸻ - -4.2.2.10 Contract Bridges - -Bridges provide interoperability between the platform and external networks, such as SWIFT or other DLT ecosystems. They act as a trusted relay for data and asset transfers, ensuring that events in one domain are consistently reflected in another. The Bridge component validates external attestations, manages acknowledgements, and enforces regulatory compliance. - -In the prototype, bridging logic is abstracted using a BridgeHelper inside the Backend API, returning mock responses. The actual bridge implementation will be added in the next phase to support secure cross-network transaction settlement. - -⸻ - -4.2.2.11 Gas Fee Responsibility - -All on-chain operations require gas to be executed on the blockchain. Responsibility for gas payment depends on the architecture: in the prototype, the Backend API directly signs and submits transactions using a dedicated service account, which covers the gas cost. This ensures predictable testing without requiring participants to manage their own gas balances. - -In the next phase, the Relayer Service will manage gas sponsorship more explicitly. It may implement a sponsored transaction model, where the Relayer pays gas on behalf of users, or enforce a quota model, where participants deposit funds in advance. This abstraction ensures that business actors (Issuer, Buyer, Bank) are shielded from direct gas management, while still allowing governance rules to define cost allocation - -4.2.2.3 Relayer Service (Next Phase) - -The Relayer Service is responsible for nonce-safe submission of signed transactions to the blockchain, implementing retry strategies, gas sponsorship, and idempotency. It acts as a controlled gateway to the blockchain, decoupling transaction submission from backend logic. - -In the prototype, this functionality is represented by a RelayerHelper within the Backend API. This helper signs transactions via KMS and submits them directly to the node. In the next phase, the helper will be replaced by a standalone service to improve scalability and resilience. - -⸻ - -4.2.2.4 Event Listener / Indexer (Next Phase) - -The Event Listener subscribes to contract events and normalizes them into application-friendly formats. It updates the backend with confirmations, state changes, and derived business events. This allows the system to replace ad-hoc polling with structured event processing. - -For the prototype, event consumption is abstracted through an EventReaderHelper that queries receipts or logs directly from the blockchain. In the next phase, the Event Listener will be deployed as a dedicated service, ensuring real-time synchronization between on-chain state and backend persistence. - -⸻ - -4.2.2.5 Notification Service (Next Phase) - -The Notification Service delivers outbound alerts to stakeholders via email, SMS, or webhooks, triggered by specific business events such as transaction settlement or contract state changes. This improves transparency and user engagement across participants. - -In the prototype, notifications are mocked through a NotificationHelper inside the Backend API. This allows the system to demonstrate workflows without requiring external delivery channels, while still maintaining consistent interfaces for future integration. - -⸻ - -4.2.2.6 Bridge Connector (Next Phase) - -The Bridge Connector enables interoperability between the blockchain platform and external networks (e.g., SWIFT integration). It validates cross-domain operations, manages attestations, and ensures consistency of settlement information across systems. - -For the prototype, this component is abstracted using a BridgeHelper that returns deterministic mock responses. In future phases, the connector will be implemented as a secure microservice, handling real cross-network communication and regulatory compliance requirements. - -⸻ - -4.2.2.7 KMS Integration - -The Key Management Service (KMS) provides secure custody of cryptographic keys used for signing transactions. The Backend API interacts with KMS over HTTPS, ensuring private keys never leave the secure enclave. This enhances security and compliance for sensitive financial operations. - -KMS is fully integrated in the prototype, supporting signing requests initiated by the Backend API. This integration remains unchanged across phases, forming the foundation of secure transaction execution. - -⸻ - -4.2.2.8 Database - -A relational database (e.g., PostgreSQL) serves as the system of record for off-chain data, including user requests, transaction metadata, mappings, and audit logs. The Backend API ensures consistent writes and supports query interfaces for reporting and monitoring. - -The database is already part of the prototype and will remain central to subsequent phases. Future improvements may include event-sourced projections populated by the Event Listener, enriching the read model with real-time on-chain updates From 27b111d6e78c8a3932c610242f0ba04cdc4fad1d Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Aug 2025 10:16:52 +0200 Subject: [PATCH 07/93] Atualizar o test --- test | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test b/test index e69de29..fed00ab 100644 --- a/test +++ b/test @@ -0,0 +1,17 @@ +Considering that this private network is EVM-compatible, the deployed smart contracts are designed with modularity and upgradability as core principles, ensuring that business logic can evolve without disrupting existing state or user balances. This is achieved through established patterns such as the Proxy (UUPS/Transparent Proxy) model or the Diamond Standard (EIP-2535), which separate storage from logic and allow new contract implementations to be plugged in seamlessly. By adopting these approaches, the platform supports safe upgrades, modular feature extensions, and long-term maintainability while preserving security and auditability of deployed assets. + + +In the future production environment, the implementation will evolve from prototype helpers to fully decoupled microservices integrated with AWS KMS for secure key custody and transaction signing. The Wallet Service will manage wallet creation and address queries, while the RelayerSigner service will ensure nonce-safe, policy-driven transaction submission. By centralizing cryptographic operations in KMS and separating responsibilities across dedicated services, the platform will achieve enterprise-grade security, scalability, and compliance, ensuring readiness for real-world financial operations. + +Transaction Signing Flow +2. Backend API Prepares Transaction +The Backend API validates the request, encodes the smart contract call (ABI), and builds a transaction intent (function + parameters + target contract). + 3. RelayerSigner Handles Transaction +The intent is passed to the RelayerSigner service. RelayerSigner is responsible for: + • Allocating a nonce (nonce-safe queue). + • Setting gas policies (gas limit, priority fee). + • Preparing the raw transaction object. + 4. Request Signature from AWS KMS +RelayerSigner calls AWS KMS (via HTTPS/KMS SDK) with the transaction hash/digest. + • KMS signs the payload internally using the private key stored in its HSM. + • Only the signature is returned; the private key never leaves AWS KMS. \ No newline at end of file From a839b91bf94a499bbc0a59eea4f40c06264cc56c Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Aug 2025 13:05:26 +0200 Subject: [PATCH 08/93] Atualizar o test --- test | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/test b/test index fed00ab..4abcbc1 100644 --- a/test +++ b/test @@ -1,17 +1,27 @@ -Considering that this private network is EVM-compatible, the deployed smart contracts are designed with modularity and upgradability as core principles, ensuring that business logic can evolve without disrupting existing state or user balances. This is achieved through established patterns such as the Proxy (UUPS/Transparent Proxy) model or the Diamond Standard (EIP-2535), which separate storage from logic and allow new contract implementations to be plugged in seamlessly. By adopting these approaches, the platform supports safe upgrades, modular feature extensions, and long-term maintainability while preserving security and auditability of deployed assets. +Wallet create flow +Step 1 – Backend API → Wallet Service +The Backend API calls POST /wallets with user context, target chainId, and an idempotency key. The Wallet Service validates the request for duplicates and authorization. -In the future production environment, the implementation will evolve from prototype helpers to fully decoupled microservices integrated with AWS KMS for secure key custody and transaction signing. The Wallet Service will manage wallet creation and address queries, while the RelayerSigner service will ensure nonce-safe, policy-driven transaction submission. By centralizing cryptographic operations in KMS and separating responsibilities across dedicated services, the platform will achieve enterprise-grade security, scalability, and compliance, ensuring readiness for real-world financial operations. +Step 2 – Wallet Service → AWS KMS +The Wallet Service uses the KMS SDK to generate a secp256k1 key pair. The private key stays in the HSM; only the public key and kms_key_id are returned.3 +Step 3 – Derive Address & Persist +The service derives the EVM address from the public key. It persists {userId, address, kms_key_id, chainId, createdAt} and writes an audit event. + +Step 4 – Backend Off-chain Registry Update +The Wallet Service returns {address, kms_key_id, chainId} to the Backend. Backend persists this mapping in its wallet registry to tie the user to the address and key. + +Trabsaction Flow +1. Prepares the raw transaction (to, value, data, gas, nonce, chainId). + 2. Calculates the transaction hash/digest (the message that needs to be signed, e.g., per EIP-155 for Ethereum). + 3. Sends only this digest to AWS KMS via the KMS SDK. + 4. KMS signs the digest internally using the private key in HSM and returns the signature. + 5. RelayerSigner attaches the signature to the raw transaction → serializes (RLP encoding) → broadcasts via JSON-RPC to the blockchain node. + +Wallet Creation Flow + 1. Backend API sends request to the Wallet Service with user context, chainId, and an idempotency key. + 2. Wallet Service calls AWS KMS to generate a new secp256k1 key pair inside the HSM. + 3. AWS KMS creates the key pair securely; the private key never leaves KMS, and the service retrieves the public key + kms_key_id. + 4. Wallet Service derives the EVM address from the public key and persists {userId, address, kms_key_id, chainId, createdAt} with audit logs. + 5. Backend API updates its wallet registry by tying the user to the new address and KMS key reference for future queries and signing operations. -Transaction Signing Flow -2. Backend API Prepares Transaction -The Backend API validates the request, encodes the smart contract call (ABI), and builds a transaction intent (function + parameters + target contract). - 3. RelayerSigner Handles Transaction -The intent is passed to the RelayerSigner service. RelayerSigner is responsible for: - • Allocating a nonce (nonce-safe queue). - • Setting gas policies (gas limit, priority fee). - • Preparing the raw transaction object. - 4. Request Signature from AWS KMS -RelayerSigner calls AWS KMS (via HTTPS/KMS SDK) with the transaction hash/digest. - • KMS signs the payload internally using the private key stored in its HSM. - • Only the signature is returned; the private key never leaves AWS KMS. \ No newline at end of file From 5efedbf852224ba7abac00f48c7c5bd874df0003 Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Aug 2025 13:27:04 +0200 Subject: [PATCH 09/93] Atualizar o test --- test | 33 ++++++--------------------------- 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/test b/test index 4abcbc1..fe05337 100644 --- a/test +++ b/test @@ -1,27 +1,6 @@ -Wallet create flow - -Step 1 – Backend API → Wallet Service -The Backend API calls POST /wallets with user context, target chainId, and an idempotency key. The Wallet Service validates the request for duplicates and authorization. - -Step 2 – Wallet Service → AWS KMS -The Wallet Service uses the KMS SDK to generate a secp256k1 key pair. The private key stays in the HSM; only the public key and kms_key_id are returned.3 -Step 3 – Derive Address & Persist -The service derives the EVM address from the public key. It persists {userId, address, kms_key_id, chainId, createdAt} and writes an audit event. - -Step 4 – Backend Off-chain Registry Update -The Wallet Service returns {address, kms_key_id, chainId} to the Backend. Backend persists this mapping in its wallet registry to tie the user to the address and key. - -Trabsaction Flow -1. Prepares the raw transaction (to, value, data, gas, nonce, chainId). - 2. Calculates the transaction hash/digest (the message that needs to be signed, e.g., per EIP-155 for Ethereum). - 3. Sends only this digest to AWS KMS via the KMS SDK. - 4. KMS signs the digest internally using the private key in HSM and returns the signature. - 5. RelayerSigner attaches the signature to the raw transaction → serializes (RLP encoding) → broadcasts via JSON-RPC to the blockchain node. - -Wallet Creation Flow - 1. Backend API sends request to the Wallet Service with user context, chainId, and an idempotency key. - 2. Wallet Service calls AWS KMS to generate a new secp256k1 key pair inside the HSM. - 3. AWS KMS creates the key pair securely; the private key never leaves KMS, and the service retrieves the public key + kms_key_id. - 4. Wallet Service derives the EVM address from the public key and persists {userId, address, kms_key_id, chainId, createdAt} with audit logs. - 5. Backend API updates its wallet registry by tying the user to the new address and KMS key reference for future queries and signing operations. - + 1. Backend API validates the request and builds the transaction intent, including function, parameters, and target contract. + 2. RelayerSigner prepares the raw transaction with values such as to, value, data, gas, nonce, and chainId. + 3. RelayerSigner calculates the transaction digest (hash to be signed, following EIP-155 for Ethereum). + 4. RelayerSigner sends the digest to AWS KMS using the KMS SDK. + 5. AWS KMS signs the digest internally with the private key in the HSM and returns the signature. + 6. RelayerSigner attaches the signature to the raw transaction, serializes it using RLP encoding, and broadcasts it to the blockchain node via JSON-RPC. From c301dd434e45be2270977cc225fe8efe2d62327c Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Aug 2025 23:22:58 +0200 Subject: [PATCH 10/93] Atualizar o test --- test | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 83 insertions(+), 6 deletions(-) diff --git a/test b/test index fe05337..28bf2bc 100644 --- a/test +++ b/test @@ -1,6 +1,83 @@ - 1. Backend API validates the request and builds the transaction intent, including function, parameters, and target contract. - 2. RelayerSigner prepares the raw transaction with values such as to, value, data, gas, nonce, and chainId. - 3. RelayerSigner calculates the transaction digest (hash to be signed, following EIP-155 for Ethereum). - 4. RelayerSigner sends the digest to AWS KMS using the KMS SDK. - 5. AWS KMS signs the digest internally with the private key in the HSM and returns the signature. - 6. RelayerSigner attaches the signature to the raw transaction, serializes it using RLP encoding, and broadcasts it to the blockchain node via JSON-RPC. + The Swift SLE Interoperability architecture establishes a secure and controlled communication channel between the enterprise DLT network and Swift’s Secure Ledger Environment (SLE). In this setup, the Bridge Operator is hosted inside the Swift SLE and acts as the relay component of the Arbitrary Message Bridge (AMB). The Bridge Operator monitors events from the enterprise blockchain, validates them, and forwards the corresponding payloads into the SLE for execution. + +All communication between the enterprise DLT and the Bridge Operator in SLE occurs over a trusted network channel enforced by: + • Certified IP whitelisting to restrict inbound and outbound traffic. + • Mutual TLS with X.509 certificates issued by an approved CA to authenticate endpoints. + • Firewalls and network segmentation to isolate the Bridge Operator from untrusted domains while ensuring secure routing of messages. + +This design ensures that only authorized blockchain nodes within the enterprise network can send messages to the Bridge Operator, while the operator in SLE securely forwards these messages for processing and integration with Swift’s messaging layer. By embedding the bridge inside SLE, trust boundaries are reinforced: the enterprise network controls the message origin, while Swift SLE governs the secure relay and final execution. + +Trusted Private Bridge – Alternative Solution + +This alternative design focuses on preserving user anonymity while bridging assets between an enterprise private chain and the Swift SLE privacy system. + +Forward Flow (Enterprise → Linea / Swift Privacy) + 1. A user on the private chain locks assets into an escrow contract with the destination defined on Linea. + 2. The Bridge Operator (running inside Swift SLE) monitors these escrow events. + 3. When an escrow event is detected, the Bridge Operator sends a bridge request (amount, token type, destination address). + 4. The Notary validates the request, checking sender trust and authorization. + 5. If valid, the Notary (or Noto) mints the equivalent token on Linea and transfers it to the destination address. + • If this is the first time bridging a new asset, a new Noto token may be deployed. + +Reverse Flow (Swift Privacy → Enterprise) + 1. A user on Swift SLE privacy system wants to move assets back to the enterprise ledger. + 2. The user submits a burn request to the Notary. + 3. The Notary burns the Noto token on Linea. + 4. The Notary provides proof of burn to the Bridge Operator in SLE. + 5. The Bridge Operator instructs the escrow contract on the enterprise chain to release the locked funds to the user’s destination address. + +Swift SLE Interoperability – Enterprise Network Perspective + +Core Points + • The Enterprise Network is the origin and destination for tokenized assets and financial transactions that require interoperability with Swift SLE. + • Interoperability is achieved via a Trusted Private Bridge pattern, where the Bridge Operator is hosted inside the Swift SLE. + • All communications between the Enterprise Network and SLE are secured using trusted IPs, mutual TLS certificates, and firewall-enforced network segmentation. + • The Enterprise Network interacts with escrow smart contracts and bridge contracts, while the actual message relay and validation are handled within SLE. + +⸻ + +Key Components in Enterprise Network + 1. Enterprise DLT Nodes (Bank A, Bank B, Bank C, etc.) + • Submit user transactions (e.g., token lock, transfer initiation). + • Expose events for escrow/bridge monitoring. + 2. Escrow / Token Bridge Contract + • Holds locked funds when bridging to SLE. + • Emits events monitored by the Bridge Operator in SLE. + • Releases funds when receiving proof of burn from SLE. + 3. ERC-3643 / Token Contracts + • Represent tokenized assets in the private chain. + • Integrated with compliance rules (KYC/AML) but isolated from cross-chain execution. + 4. Network Security Layer + • Firewall rules restrict communication only to the SLE Bridge Operator. + • Trusted IPs allow point-to-point connections. + • TLS Certificates authenticate enterprise nodes when sending requests to SLE. + +⸻ + +Interaction Flow (Enterprise → SLE → Enterprise) + +1. Enterprise → Swift SLE (Asset Export) + 1. User in the Enterprise Network initiates a transfer request by locking tokens in the Escrow Contract. + 2. The Escrow Contract emits an event with details: {amount, token, destinationAddress}. + 3. The Bridge Operator (inside SLE) monitors and captures this event via a secure, certificate-based channel. + 4. The Bridge Operator sends a bridge request to the Notary in SLE. + 5. The Notary validates and instructs Linea/Noto to mint the equivalent token on the destination side. + +2. Swift SLE → Enterprise (Asset Import / Return Flow) + 1. A user in Swift SLE burns a token on Linea via the Notary. + 2. The Notary generates proof of burn and forwards it to the Bridge Operator. + 3. The Bridge Operator sends the validated proof back to the Enterprise Escrow Contract. + 4. The Escrow Contract releases the locked tokens to the user’s specified address on the Enterprise chain. + +⸻ + +Enterprise Perspective Summary + +From the Enterprise Network’s point of view: + • Escrow Contracts are the main integration point for cross-chain bridging. + • No direct exposure to Linea or external networks — all cross-chain logic is encapsulated in SLE. + • Bridge Operator in SLE acts as the trusted relay, enforcing interoperability while preserving the Enterprise network’s compliance and security posture. + • Security and compliance are guaranteed by network isolation, certificate-based communication, and escrow-backed asset transfer logic. + + + From cfbb44fcdb40b470ec9e4e25b4be2cfc0949b1f9 Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Aug 2025 23:35:32 +0200 Subject: [PATCH 11/93] Atualizar o test --- test | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test b/test index 28bf2bc..42abbd1 100644 --- a/test +++ b/test @@ -80,4 +80,14 @@ From the Enterprise Network’s point of view: • Security and compliance are guaranteed by network isolation, certificate-based communication, and escrow-backed asset transfer logic. +The AMB is represented by the combination of: + • TokenBridge Contract (on Enterprise chain) + • Bridge Operator (off-chain relay) + • Notary Contract (on Linea) + +This trio forms the Arbitrary Message Bridge, because: + • Enterprise contract emits a message (any payload, not only token events). + • Bridge Operator relays it across. + • Notary + Noto on Linea verify/execute it. + From 3c883684e2131c525cd1e379e7a05cd66a0948fc Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Aug 2025 23:43:20 +0200 Subject: [PATCH 12/93] Atualizar o test --- test | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test b/test index 42abbd1..68571e5 100644 --- a/test +++ b/test @@ -90,4 +90,14 @@ This trio forms the Arbitrary Message Bridge, because: • Bridge Operator relays it across. • Notary + Noto on Linea verify/execute it. +Where the AMB fits + • The AMB is represented by the combination of: + • TokenBridge Contract (on Enterprise chain) + • Bridge Operator (off-chain relay) + • Notary Contract (on Linea) + +This trio forms the Arbitrary Message Bridge, because: + • Enterprise contract emits a message (any payload, not only token events). + • Bridge Operator relays it across. + • Notary + Noto on Linea verify/execute it. From a6cb643955efe4f250dcb6c8208420cac9a6db59 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sat, 23 Aug 2025 18:23:54 +0200 Subject: [PATCH 13/93] Atualizar o test --- test | 106 ++++------------------------------------------------------- 1 file changed, 7 insertions(+), 99 deletions(-) diff --git a/test b/test index 68571e5..786ac74 100644 --- a/test +++ b/test @@ -1,103 +1,11 @@ - The Swift SLE Interoperability architecture establishes a secure and controlled communication channel between the enterprise DLT network and Swift’s Secure Ledger Environment (SLE). In this setup, the Bridge Operator is hosted inside the Swift SLE and acts as the relay component of the Arbitrary Message Bridge (AMB). The Bridge Operator monitors events from the enterprise blockchain, validates them, and forwards the corresponding payloads into the SLE for execution. +Direct Relayer Integration) -All communication between the enterprise DLT and the Bridge Operator in SLE occurs over a trusted network channel enforced by: - • Certified IP whitelisting to restrict inbound and outbound traffic. - • Mutual TLS with X.509 certificates issued by an approved CA to authenticate endpoints. - • Firewalls and network segmentation to isolate the Bridge Operator from untrusted domains while ensuring secure routing of messages. +The Paladin Relayer is the privacy solution that enables secure interoperability between the Enterprise network and the Swift SLE ecosystem. Instead of relying on external bridge components, the Enterprise interacts directly with the Paladin Relayer API using the Paladin SDK over a secure, authenticated network channel. -This design ensures that only authorized blockchain nodes within the enterprise network can send messages to the Bridge Operator, while the operator in SLE securely forwards these messages for processing and integration with Swift’s messaging layer. By embedding the bridge inside SLE, trust boundaries are reinforced: the enterprise network controls the message origin, while Swift SLE governs the secure relay and final execution. +As the privacy layer, the Paladin Relayer enforces strict admission controls (mTLS, IP allow-listing, JWT/HMAC) and ensures that every request complies with enterprise and regulatory policies. Once validated, the Relayer delegates execution to the Paladin Notary and Privacy Group runtime, where Noto tokens and Hooks smart contracts enforce confidentiality, compliance, and business logic. -Trusted Private Bridge – Alternative Solution - -This alternative design focuses on preserving user anonymity while bridging assets between an enterprise private chain and the Swift SLE privacy system. - -Forward Flow (Enterprise → Linea / Swift Privacy) - 1. A user on the private chain locks assets into an escrow contract with the destination defined on Linea. - 2. The Bridge Operator (running inside Swift SLE) monitors these escrow events. - 3. When an escrow event is detected, the Bridge Operator sends a bridge request (amount, token type, destination address). - 4. The Notary validates the request, checking sender trust and authorization. - 5. If valid, the Notary (or Noto) mints the equivalent token on Linea and transfers it to the destination address. - • If this is the first time bridging a new asset, a new Noto token may be deployed. - -Reverse Flow (Swift Privacy → Enterprise) - 1. A user on Swift SLE privacy system wants to move assets back to the enterprise ledger. - 2. The user submits a burn request to the Notary. - 3. The Notary burns the Noto token on Linea. - 4. The Notary provides proof of burn to the Bridge Operator in SLE. - 5. The Bridge Operator instructs the escrow contract on the enterprise chain to release the locked funds to the user’s destination address. - -Swift SLE Interoperability – Enterprise Network Perspective - -Core Points - • The Enterprise Network is the origin and destination for tokenized assets and financial transactions that require interoperability with Swift SLE. - • Interoperability is achieved via a Trusted Private Bridge pattern, where the Bridge Operator is hosted inside the Swift SLE. - • All communications between the Enterprise Network and SLE are secured using trusted IPs, mutual TLS certificates, and firewall-enforced network segmentation. - • The Enterprise Network interacts with escrow smart contracts and bridge contracts, while the actual message relay and validation are handled within SLE. - -⸻ - -Key Components in Enterprise Network - 1. Enterprise DLT Nodes (Bank A, Bank B, Bank C, etc.) - • Submit user transactions (e.g., token lock, transfer initiation). - • Expose events for escrow/bridge monitoring. - 2. Escrow / Token Bridge Contract - • Holds locked funds when bridging to SLE. - • Emits events monitored by the Bridge Operator in SLE. - • Releases funds when receiving proof of burn from SLE. - 3. ERC-3643 / Token Contracts - • Represent tokenized assets in the private chain. - • Integrated with compliance rules (KYC/AML) but isolated from cross-chain execution. - 4. Network Security Layer - • Firewall rules restrict communication only to the SLE Bridge Operator. - • Trusted IPs allow point-to-point connections. - • TLS Certificates authenticate enterprise nodes when sending requests to SLE. - -⸻ - -Interaction Flow (Enterprise → SLE → Enterprise) - -1. Enterprise → Swift SLE (Asset Export) - 1. User in the Enterprise Network initiates a transfer request by locking tokens in the Escrow Contract. - 2. The Escrow Contract emits an event with details: {amount, token, destinationAddress}. - 3. The Bridge Operator (inside SLE) monitors and captures this event via a secure, certificate-based channel. - 4. The Bridge Operator sends a bridge request to the Notary in SLE. - 5. The Notary validates and instructs Linea/Noto to mint the equivalent token on the destination side. - -2. Swift SLE → Enterprise (Asset Import / Return Flow) - 1. A user in Swift SLE burns a token on Linea via the Notary. - 2. The Notary generates proof of burn and forwards it to the Bridge Operator. - 3. The Bridge Operator sends the validated proof back to the Enterprise Escrow Contract. - 4. The Escrow Contract releases the locked tokens to the user’s specified address on the Enterprise chain. - -⸻ - -Enterprise Perspective Summary - -From the Enterprise Network’s point of view: - • Escrow Contracts are the main integration point for cross-chain bridging. - • No direct exposure to Linea or external networks — all cross-chain logic is encapsulated in SLE. - • Bridge Operator in SLE acts as the trusted relay, enforcing interoperability while preserving the Enterprise network’s compliance and security posture. - • Security and compliance are guaranteed by network isolation, certificate-based communication, and escrow-backed asset transfer logic. - - -The AMB is represented by the combination of: - • TokenBridge Contract (on Enterprise chain) - • Bridge Operator (off-chain relay) - • Notary Contract (on Linea) - -This trio forms the Arbitrary Message Bridge, because: - • Enterprise contract emits a message (any payload, not only token events). - • Bridge Operator relays it across. - • Notary + Noto on Linea verify/execute it. - -Where the AMB fits - • The AMB is represented by the combination of: - • TokenBridge Contract (on Enterprise chain) - • Bridge Operator (off-chain relay) - • Notary Contract (on Linea) - -This trio forms the Arbitrary Message Bridge, because: - • Enterprise contract emits a message (any payload, not only token events). - • Bridge Operator relays it across. - • Notary + Noto on Linea verify/execute it. +This design provides enterprises with a direct, privacy-preserving integration path: + • Deposit flows allow enterprises to request minting of Noto tokens inside a private Paladin domain. + • Withdrawal flows enable enterprises to burn Noto tokens privately and reconcile settlement back into their enterprise ledgers. +By centralizing privacy and compliance functions in the Paladin Relayer, the solution ensures that sensitive operations remain protected, while interoperability with the Swift SLE environment is maintained through a controlled and secure channel. \ No newline at end of file From ce4435ab9493603d788ac5c509c8518e66596a7b Mon Sep 17 00:00:00 2001 From: Arthur Date: Sat, 23 Aug 2025 18:25:11 +0200 Subject: [PATCH 14/93] Atualizar o test --- test | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test b/test index 786ac74..c49fb84 100644 --- a/test +++ b/test @@ -8,4 +8,8 @@ This design provides enterprises with a direct, privacy-preserving integration p • Deposit flows allow enterprises to request minting of Noto tokens inside a private Paladin domain. • Withdrawal flows enable enterprises to burn Noto tokens privately and reconcile settlement back into their enterprise ledgers. -By centralizing privacy and compliance functions in the Paladin Relayer, the solution ensures that sensitive operations remain protected, while interoperability with the Swift SLE environment is maintained through a controlled and secure channel. \ No newline at end of file +By centralizing privacy and compliance functions in the Paladin Relayer, the solution ensures that sensitive operations remain protected, while interoperability with the Swift SLE environment is maintained through a controlled and secure channel. + +The interoperability between the Enterprise network and the Swift SLE ecosystem enables digital assets and tokenized instruments (ERC20/ERC3643) to be managed securely while preserving privacy and compliance. This model uses the Paladin Relayer as the privacy solution, providing a controlled interface for enterprises to interact with the SLE environment. Through the Paladin SDK, enterprise applications connect to the Relayer API over a trusted network channel, where all requests are authenticated and authorized using mechanisms such as IP allow-listing, mutual TLS with X.509 certificates, and application-level credentials (JWT/HMAC). + +Once admitted, the Paladin Relayer validates each operation, applies compliance policies through the Notary, and executes the corresponding actions inside the Privacy Group runtime, where Noto tokens and Hooks contracts enforce business logic and confidentiality. This design allows enterprises to mint or burn Noto tokens privately while ensuring interoperability with the Swift SLE ecosystem, enabling secure flows for issuance (deposit) and redemption (withdrawal) without exposing sensitive operations to untrusted domains. From 5d52ce8c40c735ed461c9872ffd3f87ff32a3167 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sat, 23 Aug 2025 20:07:35 +0200 Subject: [PATCH 15/93] Atualizar o test --- test | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/test b/test index c49fb84..40760bf 100644 --- a/test +++ b/test @@ -1,15 +1,12 @@ -Direct Relayer Integration) - -The Paladin Relayer is the privacy solution that enables secure interoperability between the Enterprise network and the Swift SLE ecosystem. Instead of relying on external bridge components, the Enterprise interacts directly with the Paladin Relayer API using the Paladin SDK over a secure, authenticated network channel. - -As the privacy layer, the Paladin Relayer enforces strict admission controls (mTLS, IP allow-listing, JWT/HMAC) and ensures that every request complies with enterprise and regulatory policies. Once validated, the Relayer delegates execution to the Paladin Notary and Privacy Group runtime, where Noto tokens and Hooks smart contracts enforce confidentiality, compliance, and business logic. - -This design provides enterprises with a direct, privacy-preserving integration path: - • Deposit flows allow enterprises to request minting of Noto tokens inside a private Paladin domain. - • Withdrawal flows enable enterprises to burn Noto tokens privately and reconcile settlement back into their enterprise ledgers. - -By centralizing privacy and compliance functions in the Paladin Relayer, the solution ensures that sensitive operations remain protected, while interoperability with the Swift SLE environment is maintained through a controlled and secure channel. - -The interoperability between the Enterprise network and the Swift SLE ecosystem enables digital assets and tokenized instruments (ERC20/ERC3643) to be managed securely while preserving privacy and compliance. This model uses the Paladin Relayer as the privacy solution, providing a controlled interface for enterprises to interact with the SLE environment. Through the Paladin SDK, enterprise applications connect to the Relayer API over a trusted network channel, where all requests are authenticated and authorized using mechanisms such as IP allow-listing, mutual TLS with X.509 certificates, and application-level credentials (JWT/HMAC). - -Once admitted, the Paladin Relayer validates each operation, applies compliance policies through the Notary, and executes the corresponding actions inside the Privacy Group runtime, where Noto tokens and Hooks contracts enforce business logic and confidentiality. This design allows enterprises to mint or burn Noto tokens privately while ensuring interoperability with the Swift SLE ecosystem, enabling secure flows for issuance (deposit) and redemption (withdrawal) without exposing sensitive operations to untrusted domains. +2) Enterprise Backend creates and signs a meta‑transaction, then submits to the Paladin Relayer API (safe channel) +The Backend builds the EIP‑712 payload (domain + message with nonce/deadline), signs it with the participant’s wallet (or KMS), and sends { payload, userSignature, nonce, deadline } to the Relayer. + +3. Relayer pre-check (off-chain ECDSA recover) +Before paying gas, the Paladin Relayer validates the signature off-chain: + • The recovered address equals the claimed user in the payload. + • The nonce has not been replayed. + • The deadline has not expired. +If any check fails, the Relayer rejects the request before broadcasting. + 4. Relayer broadcasts to Paladin RPC + • If the Paladin network is configured with gasPrice = 0 (default in privacy/enterprise deployments), no gas sponsor is required; the Relayer simply forwards the signed payload. + • If the Paladin network runs with gasPrice ≠ 0, the Relayer must use a gas sponsor wallet to cover the transaction fee when broadcasting. \ No newline at end of file From 1d62ddcce533b513f06661a1edfb3f4b20c09e7e Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 12:04:47 +0200 Subject: [PATCH 16/93] Atualizar o test --- test | 59 +++++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/test b/test index 40760bf..93efbcb 100644 --- a/test +++ b/test @@ -1,12 +1,47 @@ -2) Enterprise Backend creates and signs a meta‑transaction, then submits to the Paladin Relayer API (safe channel) -The Backend builds the EIP‑712 payload (domain + message with nonce/deadline), signs it with the participant’s wallet (or KMS), and sends { payload, userSignature, nonce, deadline } to the Relayer. - -3. Relayer pre-check (off-chain ECDSA recover) -Before paying gas, the Paladin Relayer validates the signature off-chain: - • The recovered address equals the claimed user in the payload. - • The nonce has not been replayed. - • The deadline has not expired. -If any check fails, the Relayer rejects the request before broadcasting. - 4. Relayer broadcasts to Paladin RPC - • If the Paladin network is configured with gasPrice = 0 (default in privacy/enterprise deployments), no gas sponsor is required; the Relayer simply forwards the signed payload. - • If the Paladin network runs with gasPrice ≠ 0, the Relayer must use a gas sponsor wallet to cover the transaction fee when broadcasting. \ No newline at end of file +2. Components (Responsibilities & Interfaces) + +2.1 Wallet Service (Enterprise) + • Purpose: Custody users’/participants’ keys (or fetch from KMS) and perform EIP‑712 signing for meta‑transactions. + • Interfaces: + • POST /wallets → create wallet (optional, if not using external custody). + • POST /sign/eip712 → body: {domain, types, message}; returns {signature}. + • Notes: Can proxy to KMS for signing; never exposes private keys. + +2.2 SLE Backend API (Enterprise) + • Purpose: Orchestrates business flows; builds meta‑tx payloads; calls Paladin Relayer API. + • Interfaces: Internal RPC/HTTP handlers; outbound to Paladin Relayer: + • POST /relayer/mint + • POST /relayer/burn + • Security: mTLS client cert + JWT/HMAC to Relayer. + +2.3 AWS KMS (Enterprise) + • Purpose: HSM‑backed key storage/signing for enterprise accounts and, optionally, gas‑sponsor keys. + • Interfaces: KMS Sign, GetPublicKey; algorithm ECDSA_secp256k1 (or via external plugin). + +2.4 RelayerSigner (Enterprise) + • Purpose: Utility service to assemble and serialize transactions; attaches sponsor signature only if gasPrice ≠ 0; RLP encodes and submits to JSON‑RPC. + • Interfaces: POST /tx/build, POST /tx/send. + • Notes: In gasPrice = 0 mode, it forwards the meta‑tx without sponsor signing. + +2.5 Paladin Relayer (SLE) + • Purpose: Single bridge‑facing component (edge). Admits requests, validates user EIP‑712 signatures off‑chain, applies quotas, and submits to Paladin RPC. + • Interfaces (external to Enterprise over mTLS): + • POST /v1/mint → {payload, userSignature, nonce, deadline, …} + • POST /v1/burn → {payload, userSignature, nonce, deadline, …} + • GET /v1/requests/{id} → status, paladinTxHash, receipts. + • Security: mTLS clientAuth, IP allow‑list, JWT/HMAC, replay window (nonce+timestamp), rate‑limit per client DN. + • Persistence: Writes audit records to Database. + +2.6 Issuer Bridge Operator (SLE) (only if using the “Trusted Bridge” variant) + • Purpose: Listens to Enterprise on‑chain events and calls Issuer Notary/Relayer. + • If your latest model is Relayer‑only, you can omit this component. + +2.7 Paladin RPC Node / Issuer Paladin RPC Node (SLE) + • Purpose: EVM execution for Privacy Groups (Noto + Hooks + Notary wiring). + • Interfaces: JSON‑RPC (eth_sendRawTransaction, eth_call, eth_getTransactionReceipt). + +2.8 Linea RPC Node (optional) + • Purpose: If the flow needs L2 interactions or anchoring. + +2.9 Database (SLE) + • Purpose: Durable, tamper‑evident audit: {requestId, clientDn, user, nonce, deadline, method, paramsHash, paladinTxHash, status, timestamps \ No newline at end of file From d1730ba209da3ba6e3acb6bd16086f38cc94b270 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 16:19:19 +0200 Subject: [PATCH 17/93] Update test --- test | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/test b/test index 93efbcb..5815d35 100644 --- a/test +++ b/test @@ -44,4 +44,84 @@ • Purpose: If the flow needs L2 interactions or anchoring. 2.9 Database (SLE) - • Purpose: Durable, tamper‑evident audit: {requestId, clientDn, user, nonce, deadline, method, paramsHash, paladinTxHash, status, timestamps \ No newline at end of file + • Purpose: Durable, tamper‑evident audit: {requestId, clientDn, user, nonce, deadline, method, paramsHash, paladinTxHash, status, timestamps + + + + + +##### +Low Level Design (LLD) – SLE Solution +1. Introduction + +This document describes the Low Level Design (LLD) of the SLE Solution. It details each component, their responsibilities, and the interactions between services, relayers, smart contracts, and external systems. The goal is to provide developers with a clear, technical implementation view. + +2. Diagram + +(Include the diagram you showed: SLE Design Solution – Component Implementation) + +3. Component Responsibilities +Component Name Description Interfaces / Dependencies +SLE Backend API Provides REST endpoints for enterprise apps to interact with blockchain components. Handles validation, orchestration, and persistence. REST APIs, Database, Paladin Relayer +SLE Controller Manages business logic for enterprise flows (transactions, balances). Invokes SLE Services +SLE Service Implements use cases (e.g., mint, transfer, query). SLE DAO/Repository, Paladin Relayer +SLE DAO/Repository Provides persistence layer and access to off-chain data. Database +Paladin Relayer Service Intermediary between backend and blockchain. Converts API calls into signed blockchain transactions. Web3 SDK, Besu RPC +Paladin Controller / Service Implements relayer operations such as signing, nonce handling, and submission. Paladin SDK +Issuer Bridge Operator Responsible for interoperability with external networks. Executes bridge transactions. BridgeOperator Service, Web3 +Bridge Contracts Smart contracts deployed on-chain for asset transfer and message passing. Besu RPC +Paladin Contracts Smart contracts for privacy groups, tokenization, and private balance queries. Besu RPC +ERC Tokens Standard ERC-20/721/1155 assets for fungible and non-fungible representation. Blockchain APIs +Database Stores off-chain data, metadata, and historical records. SQL/NoSQL interface +4. Component Implementation +4.1 SLE Backend Application + +Controllers: Handle API requests (e.g., TransactionController, BalanceController). + +Services: Implement business flows (e.g., TransferService, BalanceService). + +DAO/Repository: Interfaces with database for persistence. + +Interfaces: REST endpoints (/api/v1/...), DB queries, calls Paladin Relayer. + +4.2 Paladin Relayer Service + +Responsibilities: + +Accepts requests from SLE Backend. + +Prepares raw transactions and signs with private key (HSM/KMS). + +Submits to Besu RPC. + +Interfaces: REST API, Web3 SDK. + +4.3 Issuer Bridge Operator + +Responsibilities: + +Connects SLE network with external (SWIFT/Linea) networks. + +Executes mint/burn on both sides. + +Interfaces: BridgeOperator Service, Web3, Bridge Contracts. + +4.4 Smart Contracts + +ERC Tokens – implement standard token logic. + +Paladin Contracts – support private transactions, tokenization, and privacy groups. + +Bridge Contracts – implement message passing and asset transfer. + +5. Data Flow (Example: Get Private Balance) + +User calls SLE Backend API (/balance/private). + +SLE Controller → Service → Paladin Relayer. + +Paladin Relayer builds Web3 call to Paladin Contract. + +Smart contract returns balance, relayer sends result back to backend. + +Backend responds to client. From 1ca77651cc30aa9c9c192cc302e6747a38dfed1d Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 16:33:14 +0200 Subject: [PATCH 18/93] Update test --- test | 128 +---------------------------------------------------------- 1 file changed, 1 insertion(+), 127 deletions(-) diff --git a/test b/test index 5815d35..1374167 100644 --- a/test +++ b/test @@ -1,127 +1 @@ -2. Components (Responsibilities & Interfaces) - -2.1 Wallet Service (Enterprise) - • Purpose: Custody users’/participants’ keys (or fetch from KMS) and perform EIP‑712 signing for meta‑transactions. - • Interfaces: - • POST /wallets → create wallet (optional, if not using external custody). - • POST /sign/eip712 → body: {domain, types, message}; returns {signature}. - • Notes: Can proxy to KMS for signing; never exposes private keys. - -2.2 SLE Backend API (Enterprise) - • Purpose: Orchestrates business flows; builds meta‑tx payloads; calls Paladin Relayer API. - • Interfaces: Internal RPC/HTTP handlers; outbound to Paladin Relayer: - • POST /relayer/mint - • POST /relayer/burn - • Security: mTLS client cert + JWT/HMAC to Relayer. - -2.3 AWS KMS (Enterprise) - • Purpose: HSM‑backed key storage/signing for enterprise accounts and, optionally, gas‑sponsor keys. - • Interfaces: KMS Sign, GetPublicKey; algorithm ECDSA_secp256k1 (or via external plugin). - -2.4 RelayerSigner (Enterprise) - • Purpose: Utility service to assemble and serialize transactions; attaches sponsor signature only if gasPrice ≠ 0; RLP encodes and submits to JSON‑RPC. - • Interfaces: POST /tx/build, POST /tx/send. - • Notes: In gasPrice = 0 mode, it forwards the meta‑tx without sponsor signing. - -2.5 Paladin Relayer (SLE) - • Purpose: Single bridge‑facing component (edge). Admits requests, validates user EIP‑712 signatures off‑chain, applies quotas, and submits to Paladin RPC. - • Interfaces (external to Enterprise over mTLS): - • POST /v1/mint → {payload, userSignature, nonce, deadline, …} - • POST /v1/burn → {payload, userSignature, nonce, deadline, …} - • GET /v1/requests/{id} → status, paladinTxHash, receipts. - • Security: mTLS clientAuth, IP allow‑list, JWT/HMAC, replay window (nonce+timestamp), rate‑limit per client DN. - • Persistence: Writes audit records to Database. - -2.6 Issuer Bridge Operator (SLE) (only if using the “Trusted Bridge” variant) - • Purpose: Listens to Enterprise on‑chain events and calls Issuer Notary/Relayer. - • If your latest model is Relayer‑only, you can omit this component. - -2.7 Paladin RPC Node / Issuer Paladin RPC Node (SLE) - • Purpose: EVM execution for Privacy Groups (Noto + Hooks + Notary wiring). - • Interfaces: JSON‑RPC (eth_sendRawTransaction, eth_call, eth_getTransactionReceipt). - -2.8 Linea RPC Node (optional) - • Purpose: If the flow needs L2 interactions or anchoring. - -2.9 Database (SLE) - • Purpose: Durable, tamper‑evident audit: {requestId, clientDn, user, nonce, deadline, method, paramsHash, paladinTxHash, status, timestamps - - - - - -##### -Low Level Design (LLD) – SLE Solution -1. Introduction - -This document describes the Low Level Design (LLD) of the SLE Solution. It details each component, their responsibilities, and the interactions between services, relayers, smart contracts, and external systems. The goal is to provide developers with a clear, technical implementation view. - -2. Diagram - -(Include the diagram you showed: SLE Design Solution – Component Implementation) - -3. Component Responsibilities -Component Name Description Interfaces / Dependencies -SLE Backend API Provides REST endpoints for enterprise apps to interact with blockchain components. Handles validation, orchestration, and persistence. REST APIs, Database, Paladin Relayer -SLE Controller Manages business logic for enterprise flows (transactions, balances). Invokes SLE Services -SLE Service Implements use cases (e.g., mint, transfer, query). SLE DAO/Repository, Paladin Relayer -SLE DAO/Repository Provides persistence layer and access to off-chain data. Database -Paladin Relayer Service Intermediary between backend and blockchain. Converts API calls into signed blockchain transactions. Web3 SDK, Besu RPC -Paladin Controller / Service Implements relayer operations such as signing, nonce handling, and submission. Paladin SDK -Issuer Bridge Operator Responsible for interoperability with external networks. Executes bridge transactions. BridgeOperator Service, Web3 -Bridge Contracts Smart contracts deployed on-chain for asset transfer and message passing. Besu RPC -Paladin Contracts Smart contracts for privacy groups, tokenization, and private balance queries. Besu RPC -ERC Tokens Standard ERC-20/721/1155 assets for fungible and non-fungible representation. Blockchain APIs -Database Stores off-chain data, metadata, and historical records. SQL/NoSQL interface -4. Component Implementation -4.1 SLE Backend Application - -Controllers: Handle API requests (e.g., TransactionController, BalanceController). - -Services: Implement business flows (e.g., TransferService, BalanceService). - -DAO/Repository: Interfaces with database for persistence. - -Interfaces: REST endpoints (/api/v1/...), DB queries, calls Paladin Relayer. - -4.2 Paladin Relayer Service - -Responsibilities: - -Accepts requests from SLE Backend. - -Prepares raw transactions and signs with private key (HSM/KMS). - -Submits to Besu RPC. - -Interfaces: REST API, Web3 SDK. - -4.3 Issuer Bridge Operator - -Responsibilities: - -Connects SLE network with external (SWIFT/Linea) networks. - -Executes mint/burn on both sides. - -Interfaces: BridgeOperator Service, Web3, Bridge Contracts. - -4.4 Smart Contracts - -ERC Tokens – implement standard token logic. - -Paladin Contracts – support private transactions, tokenization, and privacy groups. - -Bridge Contracts – implement message passing and asset transfer. - -5. Data Flow (Example: Get Private Balance) - -User calls SLE Backend API (/balance/private). - -SLE Controller → Service → Paladin Relayer. - -Paladin Relayer builds Web3 call to Paladin Contract. - -Smart contract returns balance, relayer sends result back to backend. - -Backend responds to client. +The purpose of this section is to provide a technical implementation view of the SLE system. It details each component, the technologies used, their responsibilities, and the interactions between services, smart contracts, and external systems within the SLE context. From 5d6cd918364181435147ca5d08a61a7a628a9f38 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 17:51:03 +0200 Subject: [PATCH 19/93] Update test --- test | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test b/test index 1374167..1d81582 100644 --- a/test +++ b/test @@ -1 +1,7 @@ -The purpose of this section is to provide a technical implementation view of the SLE system. It details each component, the technologies used, their responsibilities, and the interactions between services, smart contracts, and external systems within the SLE context. +| **Component** | **Description** | **Interface** | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Linea Besu L2 Node** | Enterprise-grade Layer 2 node built on Hyperledger Besu, responsible for executing and validating smart contracts within the Linea L2 environment. It accommodates contracts such as **TokenBridge**, **ERC20/721/1155**, and **Message Contracts** to support token transfers, bridging, and interoperability. | Exposes JSON-RPC (HTTP/WebSocket) for transaction submission and contract queries; interacts with SLE Backend via Paladin Relayer; integrates with Issuer Bridge Operator for cross-network operations. | +| **Paladin Node** | Privacy-enabled node based on Besu with additional modules for confidential transactions and private state management. It accommodates contracts such as **Noto Contract**, **NotoHookTracker**, and **Notary**, enabling private balances, event tracking, and notarization within privacy groups. | Exposes JSON-RPC (HTTP/WebSocket) for contract calls and private transactions; provides Privacy Group APIs; accessed via Paladin SDK (used by Paladin Relayer and Issuer Bridge Operator). | +| **Component** | **Description** | **Interface** | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Database** | Centralized persistence layer that stores off-chain data required by the SLE system. It accommodates business records, metadata, transaction history, and any information not stored directly on the blockchain. | Exposes SQL/NoSQL queries depending on implementation (e.g., PostgreSQL, MongoDB). Interacts with the SLE DAO/Repository via JDBC/ORM. Provides read/write access to the SLE Backend API. | From 56093e8f1b1f3a9ba6dc3fece3345c57caca0ac7 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 18:39:28 +0200 Subject: [PATCH 20/93] Update test --- test | 151 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 144 insertions(+), 7 deletions(-) diff --git a/test b/test index 1d81582..8d53602 100644 --- a/test +++ b/test @@ -1,7 +1,144 @@ -| **Component** | **Description** | **Interface** | -| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Linea Besu L2 Node** | Enterprise-grade Layer 2 node built on Hyperledger Besu, responsible for executing and validating smart contracts within the Linea L2 environment. It accommodates contracts such as **TokenBridge**, **ERC20/721/1155**, and **Message Contracts** to support token transfers, bridging, and interoperability. | Exposes JSON-RPC (HTTP/WebSocket) for transaction submission and contract queries; interacts with SLE Backend via Paladin Relayer; integrates with Issuer Bridge Operator for cross-network operations. | -| **Paladin Node** | Privacy-enabled node based on Besu with additional modules for confidential transactions and private state management. It accommodates contracts such as **Noto Contract**, **NotoHookTracker**, and **Notary**, enabling private balances, event tracking, and notarization within privacy groups. | Exposes JSON-RPC (HTTP/WebSocket) for contract calls and private transactions; provides Privacy Group APIs; accessed via Paladin SDK (used by Paladin Relayer and Issuer Bridge Operator). | -| **Component** | **Description** | **Interface** | -| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Database** | Centralized persistence layer that stores off-chain data required by the SLE system. It accommodates business records, metadata, transaction history, and any information not stored directly on the blockchain. | Exposes SQL/NoSQL queries depending on implementation (e.g., PostgreSQL, MongoDB). Interacts with the SLE DAO/Repository via JDBC/ORM. Provides read/write access to the SLE Backend API. | +Helper Classes + +What/why: +Helper classes are cross-cutting utilities that encapsulate common technical logic, avoid duplication, and simplify usage of external libraries. They should be stateless and reusable across Services and Controllers. + +13.1 RelayerHelper + +Purpose: Encapsulates technical operations needed to prepare and submit transactions to the Paladin Relayer API. + +Responsibilities: + +Build and normalize request payloads for /mint and /burn. + +Attach required headers (Authorization, Idempotency-Key, X-Request-Id). + +Handle retries, exponential backoff, and error code mapping. + +Wrap responses into typed DTOs (RelayerResponseDto). + +Example (Domain = Relayer): + +RelayerHelper.buildMintPayload(participantId, method, params, nonce, deadline) → returns standardized JSON body. + +RelayerHelper.wrapResponse(httpResponse) → maps raw JSON to RelayerResponseDto. + +13.2 ConfigHelper (Web3 / Chain configuration) + +Purpose: Centralizes blockchain configuration and Web3 client setup. + +Responsibilities: + +Load Paladin/Enterprise RPC URLs, chainIds, gas settings from application.yml or environment. + +Provide factory methods to create Web3 clients (Web3j or similar). + +Normalize gas model (zero vs sponsor): + +If gasPrice = 0: build tx with gasPrice=0, require only gasLimit. + +If gasPrice ≠ 0: attach sponsor wallet credentials (via KMS or HSM). + +Expose domain constants (e.g., verifying contract address for meta-tx validation). + +Example (Domain = Config): + +ConfigHelper.getChainConfig("paladin") → { rpcUrl, chainId, gasPriceMode }. + +ConfigHelper.createWeb3Client("paladin") → returns a ready Web3j instance bound to the Paladin RPC node. + +Best Practices for Helpers + +Keep them stateless: no persistence, no session. + +Inject via Spring @Component / @Bean so they can be mocked in tests. + +Unit test separately (verify payload formatting, config loading). + +Never mix business rules (those live in Service) — helpers are purely technical. + + + + +################# +5.1.1.2 SLE Backend Application – Components Implementation + +The SLE Backend Application is a Java/Spring Boot service that exposes REST APIs to the frontend and external systems, providing orchestration for blockchain interactions through Paladin Relayer and persistence via the database. It is designed following Domain-Driven Design (DDD) and layered architecture principles. + +Subcomponents + +SLE Controller (Java/Spring Boot) + +Purpose: Entry point for REST API requests. Orchestrates the flow between frontend clients and backend services. + +Responsibilities: + +Map HTTP requests to application services. + +Perform request validation and error handling. + +Expose endpoints such as /api/v1/tokens, /api/v1/balances. + +Interface: REST (JSON/HTTPS). + +SLE Entity (Java/Spring Boot) + +Purpose: Represents domain objects aligned with business logic (e.g., Token, Account, Balance). + +Responsibilities: + +Encapsulate core attributes and behavior of business entities. + +Ensure consistency of domain rules within aggregates. + +Interface: Used internally by Services and Repositories. + +SLE Service (Java/Spring Boot) + +Purpose: Implements business use cases. + +Responsibilities: + +Execute domain logic (e.g., minting, burning, transferring tokens). + +Interact with Paladin Relayer for blockchain transactions. + +Interact with DAO for persistence. + +Interface: Invoked by Controllers. + +SLE Helpers (Java/Spring Boot) + +Purpose: Provide reusable utilities for Web3 integration, configuration, and common logic. + +Responsibilities: + +Wrap Web3J calls (transaction encoding/decoding). + +Centralize cryptographic or configuration helpers. + +Interface: Internal to backend. + +SLE DAO/Repository (Java/Spring Boot) + +Purpose: Data persistence abstraction. + +Responsibilities: + +Manage CRUD operations for entities. + +Implement repositories for aggregate roots (e.g., NotoAccountRepository). + +Interface: JDBC/ORM, interacts with Database. + +Web3J (Java Library) + +Purpose: Blockchain integration library. + +Responsibilities: + +Facilitate JSON-RPC calls to blockchain nodes. + +Encode/decode smart contract ABI calls. + +Interface: JSON-RPC over HTTP/WebSocket. From 1d40b6fd3dff5a0786d9366b49db94d1d2dd1533 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 18:46:44 +0200 Subject: [PATCH 21/93] Update test --- test | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test b/test index 8d53602..b55012a 100644 --- a/test +++ b/test @@ -142,3 +142,45 @@ Facilitate JSON-RPC calls to blockchain nodes. Encode/decode smart contract ABI calls. Interface: JSON-RPC over HTTP/WebSocket. + + +All controllers and endpoints are organized by macro domain (bounded context). Each domain has its own controller(s), request/response models, services, and routes. This enforces clear ownership, isolates business rules, and keeps APIs predictable. + +Package pattern: com.swift.sle..application +Examples: com.swift.sle.token.application, com.swift.sle.balance.application, com.swift.sle.bridge.application + +Controller naming: Controller +Examples: TokenTransferController, BalanceQueryController, BridgeOperationController + +Route base per domain (versioned): /api/v1//... +Examples: + +POST /api/v1/token/transfer + +POST /api/v1/token/mint + +GET /api/v1/balance/{wallet}?asset=NOTO + +POST /api/v1/bridge/lock / POST /api/v1/bridge/release + +DTOs scoped to the domain: com.swift.sle..application.dto +Examples: TransferRequest, TransferResponse, PrivateBalanceResponse + +Data Transfer Objects (DTOs) + +What & Why +DTOs are lightweight objects used to carry data across layers (API ↔ service ↔ client) without exposing internal domain/entities. They: + +decouple external API contracts from internal models; + +enforce validation at the boundary; + +stabilize APIs during internal refactors. + +Conventions + +Scope DTOs by domain: com.swift.sle..application.dto + +Suffix with Request / Response. + +Immutable where possible (records) and validated with jakarta.validation From f2c150859f430b32a857d2720a544ee3a7e56429 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 19:19:46 +0200 Subject: [PATCH 22/93] Update test --- test | 187 +++++------------------------------------------------------ 1 file changed, 16 insertions(+), 171 deletions(-) diff --git a/test b/test index b55012a..8cdc240 100644 --- a/test +++ b/test @@ -1,186 +1,31 @@ -Helper Classes +Service Layer -What/why: -Helper classes are cross-cutting utilities that encapsulate common technical logic, avoid duplication, and simplify usage of external libraries. They should be stateless and reusable across Services and Controllers. +Orchestrates business use cases. -13.1 RelayerHelper +Coordinates between domain entities, repositories, and external systems (e.g., Paladin Relayer). -Purpose: Encapsulates technical operations needed to prepare and submit transactions to the Paladin Relayer API. +DDD convention: these are Application Services (when they orchestrate) or Domain Services (when they encapsulate domain logic). -Responsibilities: +DTOs (Data Transfer Objects) -Build and normalize request payloads for /mint and /burn. +Represent request/response models for APIs. -Attach required headers (Authorization, Idempotency-Key, X-Request-Id). +Separate external API contract from domain entities. -Handle retries, exponential backoff, and error code mapping. +DDD convention: DTOs belong to the Application Layer. -Wrap responses into typed DTOs (RelayerResponseDto). +DAO/Repository Layer -Example (Domain = Relayer): +Encapsulates persistence logic. -RelayerHelper.buildMintPayload(participantId, method, params, nonce, deadline) → returns standardized JSON body. +Interfaces are in the Domain Layer, implementations in the Infrastructure Layer. -RelayerHelper.wrapResponse(httpResponse) → maps raw JSON to RelayerResponseDto. +DDD convention: Repository is a core building block. -13.2 ConfigHelper (Web3 / Chain configuration) +Entities -Purpose: Centralizes blockchain configuration and Web3 client setup. +Represent domain objects (e.g., Token, Account, Balance). -Responsibilities: +Contain attributes and business rules. -Load Paladin/Enterprise RPC URLs, chainIds, gas settings from application.yml or environment. - -Provide factory methods to create Web3 clients (Web3j or similar). - -Normalize gas model (zero vs sponsor): - -If gasPrice = 0: build tx with gasPrice=0, require only gasLimit. - -If gasPrice ≠ 0: attach sponsor wallet credentials (via KMS or HSM). - -Expose domain constants (e.g., verifying contract address for meta-tx validation). - -Example (Domain = Config): - -ConfigHelper.getChainConfig("paladin") → { rpcUrl, chainId, gasPriceMode }. - -ConfigHelper.createWeb3Client("paladin") → returns a ready Web3j instance bound to the Paladin RPC node. - -Best Practices for Helpers - -Keep them stateless: no persistence, no session. - -Inject via Spring @Component / @Bean so they can be mocked in tests. - -Unit test separately (verify payload formatting, config loading). - -Never mix business rules (those live in Service) — helpers are purely technical. - - - - -################# -5.1.1.2 SLE Backend Application – Components Implementation - -The SLE Backend Application is a Java/Spring Boot service that exposes REST APIs to the frontend and external systems, providing orchestration for blockchain interactions through Paladin Relayer and persistence via the database. It is designed following Domain-Driven Design (DDD) and layered architecture principles. - -Subcomponents - -SLE Controller (Java/Spring Boot) - -Purpose: Entry point for REST API requests. Orchestrates the flow between frontend clients and backend services. - -Responsibilities: - -Map HTTP requests to application services. - -Perform request validation and error handling. - -Expose endpoints such as /api/v1/tokens, /api/v1/balances. - -Interface: REST (JSON/HTTPS). - -SLE Entity (Java/Spring Boot) - -Purpose: Represents domain objects aligned with business logic (e.g., Token, Account, Balance). - -Responsibilities: - -Encapsulate core attributes and behavior of business entities. - -Ensure consistency of domain rules within aggregates. - -Interface: Used internally by Services and Repositories. - -SLE Service (Java/Spring Boot) - -Purpose: Implements business use cases. - -Responsibilities: - -Execute domain logic (e.g., minting, burning, transferring tokens). - -Interact with Paladin Relayer for blockchain transactions. - -Interact with DAO for persistence. - -Interface: Invoked by Controllers. - -SLE Helpers (Java/Spring Boot) - -Purpose: Provide reusable utilities for Web3 integration, configuration, and common logic. - -Responsibilities: - -Wrap Web3J calls (transaction encoding/decoding). - -Centralize cryptographic or configuration helpers. - -Interface: Internal to backend. - -SLE DAO/Repository (Java/Spring Boot) - -Purpose: Data persistence abstraction. - -Responsibilities: - -Manage CRUD operations for entities. - -Implement repositories for aggregate roots (e.g., NotoAccountRepository). - -Interface: JDBC/ORM, interacts with Database. - -Web3J (Java Library) - -Purpose: Blockchain integration library. - -Responsibilities: - -Facilitate JSON-RPC calls to blockchain nodes. - -Encode/decode smart contract ABI calls. - -Interface: JSON-RPC over HTTP/WebSocket. - - -All controllers and endpoints are organized by macro domain (bounded context). Each domain has its own controller(s), request/response models, services, and routes. This enforces clear ownership, isolates business rules, and keeps APIs predictable. - -Package pattern: com.swift.sle..application -Examples: com.swift.sle.token.application, com.swift.sle.balance.application, com.swift.sle.bridge.application - -Controller naming: Controller -Examples: TokenTransferController, BalanceQueryController, BridgeOperationController - -Route base per domain (versioned): /api/v1//... -Examples: - -POST /api/v1/token/transfer - -POST /api/v1/token/mint - -GET /api/v1/balance/{wallet}?asset=NOTO - -POST /api/v1/bridge/lock / POST /api/v1/bridge/release - -DTOs scoped to the domain: com.swift.sle..application.dto -Examples: TransferRequest, TransferResponse, PrivateBalanceResponse - -Data Transfer Objects (DTOs) - -What & Why -DTOs are lightweight objects used to carry data across layers (API ↔ service ↔ client) without exposing internal domain/entities. They: - -decouple external API contracts from internal models; - -enforce validation at the boundary; - -stabilize APIs during internal refactors. - -Conventions - -Scope DTOs by domain: com.swift.sle..application.dto - -Suffix with Request / Response. - -Immutable where possible (records) and validated with jakarta.validation +DDD convention: live in the Domain Layer. From 0f638bd509c7cb9000991f5b13f5fa470c12f99d Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 19:32:46 +0200 Subject: [PATCH 23/93] Atualizar o test --- test | 34 +++++----------------------------- 1 file changed, 5 insertions(+), 29 deletions(-) diff --git a/test b/test index 8cdc240..f67a49f 100644 --- a/test +++ b/test @@ -1,31 +1,7 @@ -Service Layer - -Orchestrates business use cases. - -Coordinates between domain entities, repositories, and external systems (e.g., Paladin Relayer). - -DDD convention: these are Application Services (when they orchestrate) or Domain Services (when they encapsulate domain logic). - -DTOs (Data Transfer Objects) - -Represent request/response models for APIs. - -Separate external API contract from domain entities. - -DDD convention: DTOs belong to the Application Layer. -DAO/Repository Layer - -Encapsulates persistence logic. - -Interfaces are in the Domain Layer, implementations in the Infrastructure Layer. - -DDD convention: Repository is a core building block. - -Entities - -Represent domain objects (e.g., Token, Account, Balance). - -Contain attributes and business rules. +Service Layer +Coordinates interactions between domain entities, repositories, and external systems. Invoked by controllers, it executes domain logic and communicates with DAOs for data persistence. -DDD convention: live in the Domain Layer. +A DTO (Data Transfer Object) is a simple data container used to transfer information between layers of the application or across system boundaries (e.g., between the Backend API and the frontend, or between Backend and Relayer). + • Purpose: + • Decouple external API contracts from internal domain models. \ No newline at end of file From d351f09ba8a31f83e418d59b7f09f5bd9bb748ee Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 24 Aug 2025 19:39:31 +0200 Subject: [PATCH 24/93] Atualizar o test --- test | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/test b/test index f67a49f..0187d09 100644 --- a/test +++ b/test @@ -1,7 +1 @@ - -Service Layer -Coordinates interactions between domain entities, repositories, and external systems. Invoked by controllers, it executes domain logic and communicates with DAOs for data persistence. - -A DTO (Data Transfer Object) is a simple data container used to transfer information between layers of the application or across system boundaries (e.g., between the Backend API and the frontend, or between Backend and Relayer). - • Purpose: - • Decouple external API contracts from internal domain models. \ No newline at end of file +is a simple data container used to transfer information between layers of the application or across system boundaries. It primarily represents request and response payloads for REST endpoints, ensuring a clear contract for external clients. By design, DTOs decouple external API specifications from internal domain models, allowing the system to evolve internally without breaking external integrations. \ No newline at end of file From daabcddb0a36bfea522163fce912c7a76d213bd8 Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 25 Aug 2025 09:09:28 +0200 Subject: [PATCH 25/93] Atualizar o test --- test | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/test b/test index 0187d09..5d33a9a 100644 --- a/test +++ b/test @@ -1 +1,72 @@ -is a simple data container used to transfer information between layers of the application or across system boundaries. It primarily represents request and response payloads for REST endpoints, ensuring a clear contract for external clients. By design, DTOs decouple external API specifications from internal domain models, allowing the system to evolve internally without breaking external integrations. \ No newline at end of file +5.1.3 Issuer Bridge Operator + +Introduction +The Issuer Bridge Operator is the trusted enterprise component responsible for monitoring bridge activity, validating proofs, and orchestrating mint/burn flows between external networks (Linea L2) and the Paladin privacy environment. It ensures regulatory compliance and guarantees that asset transfers are atomic and secure. + +Solution + • The Operator monitors Proof-of-Burn and Proof-of-Mint events. + • It coordinates with the Paladin Relayer Service to request minting of private tokens or to validate proofs when unlocking tokens on the public network. + • The Operator also provides APIs for issuer applications to initiate or audit bridge transactions. + +Layer & Implementation + • BridgeOperator Controller: Exposes APIs to issuer systems. + • BridgeOperator Service: Core logic for proof verification, orchestration of mint/burn, and integration with Paladin Relayer Service. + • Helpers: + • Web3J Helper → used to listen for events from external RPC nodes (Linea L2) and to submit transactions (e.g., unlock ERC20/3643 tokens). + +5.1.2 Paladin Relayer Service + +Introduction +The Paladin Relayer Service is implemented as a Node.js/TypeScript microservice. The rationale for this technology choice is twofold: + 1. The SLE Backend Application is built in Java, but Paladin does not currently provide a Java SDK. To overcome this limitation, the Paladin TypeScript SDK is encapsulated within a dedicated Node.js service that exposes REST APIs to external systems. + 2. The Relayer also facilitates bridging between public ERC20/3643 tokens (on Linea L2) and private Noto tokens (inside the Paladin environment). This requires tight integration with ethers.js and asynchronous event listeners, which are natively supported in the Node.js/TypeScript ecosystem. + +Solution +The Relayer has two main functions: + • Bridge Functionality: + • Listens to NotoBridgeContract (Escrow) events on Linea L2 using ethers.js (via query or WebSocket). + • When a public token is locked, the Relayer mints an equivalent Noto private token inside the privacy domain using the Paladin SDK. + • In the reverse direction, when a Noto private token is burned, the Relayer receives a Proof of Burn from the Notary. This proof is then submitted to the NotoBridgeContract on Linea L2, which validates the proof and unlocks the corresponding public tokens. + • Private Balance Indexing: + • The Relayer listens to NotoHooks events that signal changes in private state. + • These events are indexed off-chain to maintain a synchronized balance store per user address, which external applications can query without direct access to the Paladin privacy environment. + + + + + + +5.1.4 Smart Contracts + +Introduction +Smart Contracts form the backbone of the solution, ensuring automated and secure asset lifecycle management in both public (Linea L2) and private (Paladin) domains. All contracts are fully compatible with Solidity v0.8.x, enabling use of the latest compiler features and security improvements. These contracts support regulated ERC20/3643 tokens, private tokens (Noto), bridging logic, and auxiliary utilities for privacy-preserving interactions. + +Solution +The smart contract landscape can be divided into three groups: + +⸻ + +1. ERC Tokens (Public Side – Linea L2) + • ERC20/3643 Contracts → define regulated fungible assets, supporting compliance requirements such as whitelisting and transfer restrictions. + • These tokens can be escrowed into bridge contracts for transfer into the Paladin privacy domain. + • Implementation Modularity: + • Proxy Pattern (ERC-1967 / UUPS): Provides upgradeability while preserving the same contract address. + • Requirement: If Proxy is adopted, ERC contracts must be implemented as Upgradeable Contracts (using OpenZeppelin upgradeable libraries). + • Diamond Standard (EIP-2535): Provides fine-grained modularity for complex regulated token logic, allowing multiple facets (compliance, transfer rules, metadata, etc.) to be extended without redeployment. + • Both approaches are supported, and the chosen pattern depends on issuer requirements for governance, upgrade strategy, and extensibility. + +⸻ + +2. Paladin Contracts (Private Side – Paladin Domain) + • Noto Contract → represents private token balances within Paladin’s privacy environment. + • NotoHookTracker Contract → extends the base NotoHook contract to emit detailed state-change events, enabling off-chain balance indexing by the Paladin Relayer. + • Factory Contracts → provide deployment and instantiation utilities for creating new private token contracts or privacy group instances dynamically. + • PrivacyGroup Contract → manages membership, rules, and access controls for executing private transactions within Paladin domains. + • Auxiliary Contracts → support utility functions required for Paladin domain operations (e.g., metadata storage, lifecycle management). + +⸻ + +3. Bridge Contracts (Cross-Domain) + • NotoBridgeContract (Escrow) → deployed on Linea L2, used to lock ERC20/3643 tokens when bridging into Paladin. Upon receiving valid Proof of Burn confirmation from the Paladin Relayer, it unlocks the equivalent tokens back to the public domain. + • TokenBridge Contract / Message Contract → responsible for handling proof submission and synchronization of token states between Linea L2 and Paladin private domains. + • Implementation Note: The Bridge Contract implementation will be provided and maintained by ConsenSys, ensuring alignment with Linea infrastructure and interoperability standards. From 032cccf49266f63386f302fe8a2854b7fc55e8f1 Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 25 Aug 2025 09:28:03 +0200 Subject: [PATCH 26/93] Atualizar o test --- test | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test b/test index 5d33a9a..9ae76f6 100644 --- a/test +++ b/test @@ -23,13 +23,13 @@ The Paladin Relayer Service is implemented as a Node.js/TypeScript microservice. Solution The Relayer has two main functions: - • Bridge Functionality: + Bridge Functionality: • Listens to NotoBridgeContract (Escrow) events on Linea L2 using ethers.js (via query or WebSocket). • When a public token is locked, the Relayer mints an equivalent Noto private token inside the privacy domain using the Paladin SDK. • In the reverse direction, when a Noto private token is burned, the Relayer receives a Proof of Burn from the Notary. This proof is then submitted to the NotoBridgeContract on Linea L2, which validates the proof and unlocks the corresponding public tokens. - • Private Balance Indexing: - • The Relayer listens to NotoHooks events that signal changes in private state. - • These events are indexed off-chain to maintain a synchronized balance store per user address, which external applications can query without direct access to the Paladin privacy environment. + Private Balance Indexing: + PaladiSDK provide Noto balance function (https://github.com/LF-Decentralized-Trust-labs/paladin/commit/53da41b0f7f4349740a02004b5ee5f9f6be46c59) for check current state per address, but this function won't work if you end up with a very large number of UTXOs. For a production solution is recommend indexing events as they happen, and maintaining a live database or other off chain snapshot of balances. + The Relayer listens to NotoHooksTracker events that signal changes in private state, these events are indexed off-chain to maintain a synchronized balance store per user address. From acb0b317d453277f12a6e161a4b0696d9dfba676 Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 25 Aug 2025 11:42:50 +0200 Subject: [PATCH 27/93] Atualizar o test --- test | 73 ++---------------------------------------------------------- 1 file changed, 2 insertions(+), 71 deletions(-) diff --git a/test b/test index 9ae76f6..1fa61e2 100644 --- a/test +++ b/test @@ -1,72 +1,3 @@ -5.1.3 Issuer Bridge Operator +NotoBridgeContract (Escrow) is deployed on Linea L2 and is used to lock ERC20/3643 public tokens when bridging into Paladin. Upon receiving a valid Proof of Burn confirmation from the Paladin Relayer, it unlocks the equivalent tokens back into the public domain. -Introduction -The Issuer Bridge Operator is the trusted enterprise component responsible for monitoring bridge activity, validating proofs, and orchestrating mint/burn flows between external networks (Linea L2) and the Paladin privacy environment. It ensures regulatory compliance and guarantees that asset transfers are atomic and secure. - -Solution - • The Operator monitors Proof-of-Burn and Proof-of-Mint events. - • It coordinates with the Paladin Relayer Service to request minting of private tokens or to validate proofs when unlocking tokens on the public network. - • The Operator also provides APIs for issuer applications to initiate or audit bridge transactions. - -Layer & Implementation - • BridgeOperator Controller: Exposes APIs to issuer systems. - • BridgeOperator Service: Core logic for proof verification, orchestration of mint/burn, and integration with Paladin Relayer Service. - • Helpers: - • Web3J Helper → used to listen for events from external RPC nodes (Linea L2) and to submit transactions (e.g., unlock ERC20/3643 tokens). - -5.1.2 Paladin Relayer Service - -Introduction -The Paladin Relayer Service is implemented as a Node.js/TypeScript microservice. The rationale for this technology choice is twofold: - 1. The SLE Backend Application is built in Java, but Paladin does not currently provide a Java SDK. To overcome this limitation, the Paladin TypeScript SDK is encapsulated within a dedicated Node.js service that exposes REST APIs to external systems. - 2. The Relayer also facilitates bridging between public ERC20/3643 tokens (on Linea L2) and private Noto tokens (inside the Paladin environment). This requires tight integration with ethers.js and asynchronous event listeners, which are natively supported in the Node.js/TypeScript ecosystem. - -Solution -The Relayer has two main functions: - Bridge Functionality: - • Listens to NotoBridgeContract (Escrow) events on Linea L2 using ethers.js (via query or WebSocket). - • When a public token is locked, the Relayer mints an equivalent Noto private token inside the privacy domain using the Paladin SDK. - • In the reverse direction, when a Noto private token is burned, the Relayer receives a Proof of Burn from the Notary. This proof is then submitted to the NotoBridgeContract on Linea L2, which validates the proof and unlocks the corresponding public tokens. - Private Balance Indexing: - PaladiSDK provide Noto balance function (https://github.com/LF-Decentralized-Trust-labs/paladin/commit/53da41b0f7f4349740a02004b5ee5f9f6be46c59) for check current state per address, but this function won't work if you end up with a very large number of UTXOs. For a production solution is recommend indexing events as they happen, and maintaining a live database or other off chain snapshot of balances. - The Relayer listens to NotoHooksTracker events that signal changes in private state, these events are indexed off-chain to maintain a synchronized balance store per user address. - - - - - - -5.1.4 Smart Contracts - -Introduction -Smart Contracts form the backbone of the solution, ensuring automated and secure asset lifecycle management in both public (Linea L2) and private (Paladin) domains. All contracts are fully compatible with Solidity v0.8.x, enabling use of the latest compiler features and security improvements. These contracts support regulated ERC20/3643 tokens, private tokens (Noto), bridging logic, and auxiliary utilities for privacy-preserving interactions. - -Solution -The smart contract landscape can be divided into three groups: - -⸻ - -1. ERC Tokens (Public Side – Linea L2) - • ERC20/3643 Contracts → define regulated fungible assets, supporting compliance requirements such as whitelisting and transfer restrictions. - • These tokens can be escrowed into bridge contracts for transfer into the Paladin privacy domain. - • Implementation Modularity: - • Proxy Pattern (ERC-1967 / UUPS): Provides upgradeability while preserving the same contract address. - • Requirement: If Proxy is adopted, ERC contracts must be implemented as Upgradeable Contracts (using OpenZeppelin upgradeable libraries). - • Diamond Standard (EIP-2535): Provides fine-grained modularity for complex regulated token logic, allowing multiple facets (compliance, transfer rules, metadata, etc.) to be extended without redeployment. - • Both approaches are supported, and the chosen pattern depends on issuer requirements for governance, upgrade strategy, and extensibility. - -⸻ - -2. Paladin Contracts (Private Side – Paladin Domain) - • Noto Contract → represents private token balances within Paladin’s privacy environment. - • NotoHookTracker Contract → extends the base NotoHook contract to emit detailed state-change events, enabling off-chain balance indexing by the Paladin Relayer. - • Factory Contracts → provide deployment and instantiation utilities for creating new private token contracts or privacy group instances dynamically. - • PrivacyGroup Contract → manages membership, rules, and access controls for executing private transactions within Paladin domains. - • Auxiliary Contracts → support utility functions required for Paladin domain operations (e.g., metadata storage, lifecycle management). - -⸻ - -3. Bridge Contracts (Cross-Domain) - • NotoBridgeContract (Escrow) → deployed on Linea L2, used to lock ERC20/3643 tokens when bridging into Paladin. Upon receiving valid Proof of Burn confirmation from the Paladin Relayer, it unlocks the equivalent tokens back to the public domain. - • TokenBridge Contract / Message Contract → responsible for handling proof submission and synchronization of token states between Linea L2 and Paladin private domains. - • Implementation Note: The Bridge Contract implementation will be provided and maintained by ConsenSys, ensuring alignment with Linea infrastructure and interoperability standards. +TokenBridge Contract and Message Contract are responsible for handling proof submission and synchronizing token states between Ethereum L1 and Linea L2. These contracts are provided and maintained by ConsenSys. \ No newline at end of file From 04277d3199ecf9674d53d07535e6a232b7660951 Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 25 Aug 2025 11:53:54 +0200 Subject: [PATCH 28/93] Update test --- test | 2 -- 1 file changed, 2 deletions(-) diff --git a/test b/test index 1fa61e2..8b13789 100644 --- a/test +++ b/test @@ -1,3 +1 @@ -NotoBridgeContract (Escrow) is deployed on Linea L2 and is used to lock ERC20/3643 public tokens when bridging into Paladin. Upon receiving a valid Proof of Burn confirmation from the Paladin Relayer, it unlocks the equivalent tokens back into the public domain. -TokenBridge Contract and Message Contract are responsible for handling proof submission and synchronizing token states between Ethereum L1 and Linea L2. These contracts are provided and maintained by ConsenSys. \ No newline at end of file From 0c9a2d8a0ecfa02211ccbee7ff2285c9a8fd5127 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 27 Aug 2025 13:13:06 +0200 Subject: [PATCH 29/93] Atualizar o test --- test | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test b/test index 8b13789..6b2cd00 100644 --- a/test +++ b/test @@ -1 +1,16 @@ +Hi [Name/Team], +In addition, please clarify a few points regarding the Validium setup and ensure these are properly included in our documentation: + 1. RBAC + We need to specify at which layer the access control definition should occur. + At the application/API Gateway level? + At the smart contract level? + Or via an off-chain component that represents this functionality? + 2. Validium Operator + Please clarify which component should represent the Validium operator. + 3. Enterprise Trusted Bridge + How is privacy ensured when bridging to L2 with Validium? + Once transactions are bridged, how is privacy maintained? + Is it possible to enforce RBAC policies for the bridge node? + 4. Infrastructure + The cloud infrastructure documentation should be updated with the Validium perspective, including nodes and off-chain components. \ No newline at end of file From 826efa5d0bf008a8532443010e68e1fe3db6f37e Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 27 Aug 2025 15:06:04 +0200 Subject: [PATCH 30/93] Atualizar o test --- test | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/test b/test index 6b2cd00..e69de29 100644 --- a/test +++ b/test @@ -1,16 +0,0 @@ -Hi [Name/Team], - -In addition, please clarify a few points regarding the Validium setup and ensure these are properly included in our documentation: - 1. RBAC - We need to specify at which layer the access control definition should occur. - At the application/API Gateway level? - At the smart contract level? - Or via an off-chain component that represents this functionality? - 2. Validium Operator - Please clarify which component should represent the Validium operator. - 3. Enterprise Trusted Bridge - How is privacy ensured when bridging to L2 with Validium? - Once transactions are bridged, how is privacy maintained? - Is it possible to enforce RBAC policies for the bridge node? - 4. Infrastructure - The cloud infrastructure documentation should be updated with the Validium perspective, including nodes and off-chain components. \ No newline at end of file From 69781be5e706a87cb7c4de0c16e8c06cb866c650 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 16 Sep 2025 13:24:00 +0200 Subject: [PATCH 31/93] Atualizar o test --- test | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test b/test index e69de29..109bf05 100644 --- a/test +++ b/test @@ -0,0 +1,42 @@ +RBAC Middleware + +AS-IS + • Authentication (API Key): +Works as API Key Mocked (no API Key generation/verification). + • Authorization (JWT/JWKS): +No JWT token or session manager (no JWT issuer/JWKS verifier). +Access control is mocked with hard-coded roles (admin/operator) instead of being managed in a database schema. +No access control is implemented for ContractAddress or WalletAddress (no allowlist). + +⸻ + +TO-BE: Option 1 (Middleware) + • Authentication (API Key): +Implement an API Key generator and verifier to manage the full API Key lifecycle as part of the database schema. + • Authorization (JWT/JWKS): +Define a JWT token manager with a configurable TTL (time-to-live). +Database schema should define Users, Roles, Permissions, etc. +Consider operation-level access control for ContractAddress, WalletAddress, and other necessary attributes. +Use a cache manager to store JWTs, JWKS, and permissions. + +⸻ + +TO-BE: Option 2 (API Gateway + Middleware) + • Authentication (API Key): +API Gateway is responsible for full API Key lifecycle management (issuer/verifier). + • Authorization (JWT/JWKS): +Middleware defines a JWT token manager with configurable TTL. +Database schema defines Users, Roles, Permissions, etc. +Middleware enforces operation-level access control for ContractAddress, WalletAddress, and others. +Use a cache manager to store JWTs, JWKS, and permissions. + +⸻ + +TO-BE: Option 3 (API Gateway + IdP + Middleware) + • Authentication (API Key): +API Gateway is responsible for API Key lifecycle management (issuer/verifier). + • Authorization (JWT/JWKS): +Identity Provider (IdP) is responsible for authentication and authorization via JWT lifecycle automation (issuer + JWKS verifier). +Minimal custom schema can be supported in the IdP. +Middleware can enforce additional operation-level access control (ContractAddress, WalletAddress, etc., if necessary). +Use a cache manager to store JWTs, JWKS, and permissions. From 04b93c8900b617fa11ee9636ed5938a7520b0deb Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 16 Sep 2025 13:27:46 +0200 Subject: [PATCH 32/93] Atualizar o test --- test | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test b/test index 109bf05..63b8483 100644 --- a/test +++ b/test @@ -40,3 +40,7 @@ Identity Provider (IdP) is responsible for authentication and authorization via Minimal custom schema can be supported in the IdP. Middleware can enforce additional operation-level access control (ContractAddress, WalletAddress, etc., if necessary). Use a cache manager to store JWTs, JWKS, and permissions. + +Option 1: Middleware does everything (API Key + JWT + RBAC). + • Option 2: API Gateway manages API Key, Middleware handles JWT + RBAC. + • Option 3: API Gateway + IdP manage API Key + JWT, Middleware only enforces RBAC/allowlist. From a1921676167fe595da8d685618e32436bcdba0be Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 16 Sep 2025 13:43:40 +0200 Subject: [PATCH 33/93] Atualizar o test --- test | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/test b/test index 63b8483..acfa0a9 100644 --- a/test +++ b/test @@ -42,5 +42,66 @@ Middleware can enforce additional operation-level access control (ContractAddres Use a cache manager to store JWTs, JWKS, and permissions. Option 1: Middleware does everything (API Key + JWT + RBAC). - • Option 2: API Gateway manages API Key, Middleware handles JWT + RBAC. + sequenceDiagram + participant Client + participant Middleware + participant DB as Database + participant Cache + + Client->>Middleware: Send request with API Key + JWT + Middleware->>DB: Verify API Key (generator/verifier) + Middleware->>Cache: Check cached JWT/JWKS + alt JWT not cached or expired + Middleware->>DB: Validate JWT, roles, permissions + Middleware->>Cache: Store JWT/JWKS with TTL + end + Middleware->>DB: Enforce allowlist (ContractAddress, WalletAddress) + Middleware-->>Client: Return response (authorized or denied) + + +• Option 2: API Gateway manages API Key, Middleware handles JWT + RBAC. +sequenceDiagram + participant Client + participant APIGW as API Gateway + participant Middleware + participant DB as Database + participant Cache + + Client->>APIGW: Send request with API Key + APIGW->>APIGW: Verify API Key (issuer/verifier) + APIGW->>Middleware: Forward request with JWT + Middleware->>Cache: Check cached JWT/JWKS + alt JWT not cached or expired + Middleware->>DB: Validate JWT, roles, permissions + Middleware->>Cache: Store JWT/JWKS with TTL + end + Middleware->>DB: Enforce allowlist (ContractAddress, WalletAddress) + Middleware-->>APIGW: Response (authorized/denied) + APIGW-->>Client: Return response + • Option 3: API Gateway + IdP manage API Key + JWT, Middleware only enforces RBAC/allowlist. +sequenceDiagram + participant Client + participant APIGW as API Gateway + participant IdP + participant Middleware + participant DB as Database + participant Cache + + Client->>APIGW: Send request with API Key + APIGW->>APIGW: Verify API Key (issuer/verifier) + APIGW->>IdP: Request JWT (authentication/authorization) + IdP->>APIGW: Return JWT + APIGW->>Middleware: Forward request with JWT + Middleware->>Cache: Check cached JWT/JWKS + alt JWT not cached or expired + Middleware->>IdP: Retrieve JWKS + Middleware->>DB: Validate roles, permissions + Middleware->>Cache: Store JWT/JWKS with TTL + end + Middleware->>DB: Enforce allowlist (ContractAddress, WalletAddress) + Middleware-->>APIGW: Response (authorized/denied) + APIGW-->>Client: Return response + + + From 5a3e1c75cb20283dc72916e94bae637356a28ed6 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 23 Sep 2025 23:35:46 +0200 Subject: [PATCH 34/93] Atualizar o test --- test | 128 +++++++++++++++-------------------------------------------- 1 file changed, 32 insertions(+), 96 deletions(-) diff --git a/test b/test index acfa0a9..cf46a3a 100644 --- a/test +++ b/test @@ -1,107 +1,43 @@ -RBAC Middleware +“The Backend API delegates transaction submission to an RBAC Middleware that validates JWT/API-key, enforces role/permission and allowlists, performs policy checks, and only then signs/relays the transaction to the network.” +Minimal architecture & flow + 1. Client → Backend API: request to perform action on contract with params (+ Bearer JWT / API key). + 2. Backend API → RBAC Middleware (/authorize-and-send): + • Validate token (IdP/JWKS or API-key). + • Evaluate RBAC (role→permission) and allowlists (contract address, function selector, wallet address, chainId, limits). + • Apply policy (rate/nonce limits, quotas, velocity, compliance). + • If allowed, sign (HSM/KMS) or forward to Relayer; submit via RPC. + 3. Middleware → Backend API: returns tx hash / receipt (or deny with reason). + 4. Backend API → Client: responds with result. -AS-IS - • Authentication (API Key): -Works as API Key Mocked (no API Key generation/verification). - • Authorization (JWT/JWKS): -No JWT token or session manager (no JWT issuer/JWKS verifier). -Access control is mocked with hard-coded roles (admin/operator) instead of being managed in a database schema. -No access control is implemented for ContractAddress or WalletAddress (no allowlist). -⸻ +4.3.3 Privacy and RBAC Middleware -TO-BE: Option 1 (Middleware) - • Authentication (API Key): -Implement an API Key generator and verifier to manage the full API Key lifecycle as part of the database schema. - • Authorization (JWT/JWKS): -Define a JWT token manager with a configurable TTL (time-to-live). -Database schema should define Users, Roles, Permissions, etc. -Consider operation-level access control for ContractAddress, WalletAddress, and other necessary attributes. -Use a cache manager to store JWTs, JWKS, and permissions. +The Privacy and RBAC Middleware provides a secure enforcement layer that governs access to Validium-based off-chain state and orchestrates blockchain transaction execution under strict role-based policies. -⸻ +Off-chain Privacy and Validium Control -TO-BE: Option 2 (API Gateway + Middleware) - • Authentication (API Key): -API Gateway is responsible for full API Key lifecycle management (issuer/verifier). - • Authorization (JWT/JWKS): -Middleware defines a JWT token manager with configurable TTL. -Database schema defines Users, Roles, Permissions, etc. -Middleware enforces operation-level access control for ContractAddress, WalletAddress, and others. -Use a cache manager to store JWTs, JWKS, and permissions. +In this architecture, sensitive data and transaction states are stored off-chain within Validium private storage, ensuring that only zero-knowledge proofs are posted to Layer 1. This prevents exposure of confidential business information while guaranteeing verifiability through cryptographic proofs. + • On-chain: only validity proofs and hashes are committed. + • Off-chain: transaction intents, balances, and settlement details remain private, queryable only by authorized participants. + • Logs and calldata: enriched human-readable details are made available in event logs, minimizing on-chain storage costs and preserving confidentiality. -⸻ +RBAC Enforcement -TO-BE: Option 3 (API Gateway + IdP + Middleware) - • Authentication (API Key): -API Gateway is responsible for API Key lifecycle management (issuer/verifier). - • Authorization (JWT/JWKS): -Identity Provider (IdP) is responsible for authentication and authorization via JWT lifecycle automation (issuer + JWKS verifier). -Minimal custom schema can be supported in the IdP. -Middleware can enforce additional operation-level access control (ContractAddress, WalletAddress, etc., if necessary). -Use a cache manager to store JWTs, JWKS, and permissions. +Access to Validium RPC endpoints and private storage is gated by Role-Based Access Control (RBAC). Each request is validated against policies that define: + • Who (user identity, API key, JWT claims). + • What (contract, function selector, resource scope). + • How (permissions, quotas, transaction type, nonce safety). -Option 1: Middleware does everything (API Key + JWT + RBAC). - sequenceDiagram - participant Client - participant Middleware - participant DB as Database - participant Cache - - Client->>Middleware: Send request with API Key + JWT - Middleware->>DB: Verify API Key (generator/verifier) - Middleware->>Cache: Check cached JWT/JWKS - alt JWT not cached or expired - Middleware->>DB: Validate JWT, roles, permissions - Middleware->>Cache: Store JWT/JWKS with TTL - end - Middleware->>DB: Enforce allowlist (ContractAddress, WalletAddress) - Middleware-->>Client: Return response (authorized or denied) - - -• Option 2: API Gateway manages API Key, Middleware handles JWT + RBAC. -sequenceDiagram - participant Client - participant APIGW as API Gateway - participant Middleware - participant DB as Database - participant Cache - - Client->>APIGW: Send request with API Key - APIGW->>APIGW: Verify API Key (issuer/verifier) - APIGW->>Middleware: Forward request with JWT - Middleware->>Cache: Check cached JWT/JWKS - alt JWT not cached or expired - Middleware->>DB: Validate JWT, roles, permissions - Middleware->>Cache: Store JWT/JWKS with TTL - end - Middleware->>DB: Enforce allowlist (ContractAddress, WalletAddress) - Middleware-->>APIGW: Response (authorized/denied) - APIGW-->>Client: Return response - - • Option 3: API Gateway + IdP manage API Key + JWT, Middleware only enforces RBAC/allowlist. -sequenceDiagram - participant Client - participant APIGW as API Gateway - participant IdP - participant Middleware - participant DB as Database - participant Cache - - Client->>APIGW: Send request with API Key - APIGW->>APIGW: Verify API Key (issuer/verifier) - APIGW->>IdP: Request JWT (authentication/authorization) - IdP->>APIGW: Return JWT - APIGW->>Middleware: Forward request with JWT - Middleware->>Cache: Check cached JWT/JWKS - alt JWT not cached or expired - Middleware->>IdP: Retrieve JWKS - Middleware->>DB: Validate roles, permissions - Middleware->>Cache: Store JWT/JWKS with TTL - end - Middleware->>DB: Enforce allowlist (ContractAddress, WalletAddress) - Middleware-->>APIGW: Response (authorized/denied) - APIGW-->>Client: Return response +This ensures that only authorized entities can prepare and submit blockchain transactions or query confidential off-chain state. +Prototype vs Production + • Prototype Phase: RBAC policies are mocked within the middleware to validate functional flows without requiring full identity infrastructure. This enables rapid iteration and integration testing. + • Production Phase: RBAC is integrated with an Identity Provider (IdP) for fine-grained authorization and an API Gateway for authentication. External users authenticate via credentials; JWT tokens are issued and validated against RBAC policies before any transaction is processed. +Delegated Transaction Model +The Backend API does not broadcast blockchain transactions directly. Instead, it delegates transaction preparation and submission to the RBAC Middleware: + 1. Prepare: Business logic in the backoffice assembles the transaction intent (using EIP-712 typed structured data). + 2. Authorize: Middleware validates intent against RBAC rules, allowlists, and quotas. + 3. Sign/Relay: If authorized, the Middleware signs the transaction (via KMS/HSM) or relays it on behalf of the user. + 4. Execute: Settlement occurs on-chain, with confidentiality preserved off-chain. \ No newline at end of file From 82459c57033c6de3ddceba49034a4049e5d60154 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 23 Sep 2025 23:41:35 +0200 Subject: [PATCH 35/93] Atualizar o test --- test | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/test b/test index cf46a3a..c3546ec 100644 --- a/test +++ b/test @@ -40,4 +40,56 @@ The Backend API does not broadcast blockchain transactions directly. Instead, it 1. Prepare: Business logic in the backoffice assembles the transaction intent (using EIP-712 typed structured data). 2. Authorize: Middleware validates intent against RBAC rules, allowlists, and quotas. 3. Sign/Relay: If authorized, the Middleware signs the transaction (via KMS/HSM) or relays it on behalf of the user. - 4. Execute: Settlement occurs on-chain, with confidentiality preserved off-chain. \ No newline at end of file + 4. Execute: Settlement occurs on-chain, with confidentiality preserved off-chain. +EIP-1159 (Ethereum Improvement Proposal 1159) + +Also known as: London Hard Fork / Fee Market Change / “Base Fee” model + • Introduced in August 2021 with the London upgrade. + • Changed how transaction fees (gas fees) are calculated on Ethereum. + +Before (old model): + • Users set a gas price (bid). + • Miners picked transactions with the highest bids → fee auction. + • Problem: fees were volatile, spikes during congestion. + +After (EIP-1159): + • Transactions now include: + • Base Fee: algorithmically set by the protocol, changes block to block depending on network demand. + • Priority Fee (tip): optional extra you pay to incentivize miners/validators. + • Max Fee: maximum total you are willing to pay. + +Benefits: + • More predictable gas prices. + • Better UX for wallets/dapps (no guessing fees). + • Base fee is burned → reduces ETH supply (deflationary pressure). + +⸻ + +🔹 EIP-712 + +Typed Structured Data Hashing and Signing + • Standard for signing structured, human-readable messages off-chain. + • Instead of signing a raw transaction (binary blob), users sign typed data with clear fields. + +Example use cases: + • Permit approvals (EIP-2612): sign a message to allow spending tokens, without sending an on-chain approval tx. + • Meta-transactions: user signs an intent, a relayer submits it on-chain. + • Off-chain agreements: swaps, orders, settlements — validated on-chain later. + +Benefits: + • Prevents phishing & replay attacks (domain separator + nonce). + • Messages are human-readable (wallet shows “You allow 100 DAI to be spent by 0x…”). + • Decouples signing from execution → gasless UX, batch transactions, Validium off-chain intents (like in your setup). + +⸻ + +🔹 TL;DR + • EIP-1159 → gas fee market reform (base fee, tip, fee burning). + • EIP-712 → standard for signing structured, human-readable off-chain messages (intents, permits). + +⸻ + +⚡ Quick analogy: + • EIP-1159 = how you pay the highway toll (fairer and predictable). + • EIP-712 = how you sign a contract before driving (clear, structured, verifiable intent). + From d78a2ce113baa9870b9b0a3c32f599016561ed68 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 13:15:59 +0200 Subject: [PATCH 36/93] Update test --- test | 131 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) diff --git a/test b/test index c3546ec..34df118 100644 --- a/test +++ b/test @@ -93,3 +93,134 @@ Benefits: • EIP-1159 = how you pay the highway toll (fairer and predictable). • EIP-712 = how you sign a contract before driving (clear, structured, verifiable intent). + + +========== + +Settlement and EIP-712 Signatures +1. Overview + +The settlement process is designed to securely authorize and execute asset transfers or swaps using EIP-712 typed data signatures. Instead of requiring users to broadcast and pay for multiple on-chain transactions, the system allows them to sign structured off-chain messages (intents). These intents can later be executed on-chain by a settlement contract, ensuring atomicity, replay protection, and compliance with agreed conditions. + +This architecture decouples authorization (off-chain signature) from execution (on-chain settlement), enabling flexible models such as user-only execution, relayer-based execution, or allow-listed counterparties (e.g., Swift integration). + +2. Baseline vs. Intent-Based Flows +Traditional Transaction Flow + +Each action (approve, transfer, swap) is a separate on-chain transaction. + +The user must maintain ETH (or gas token) for fees. + +Transactions are executed sequentially by nonce order. + +Cancelling or modifying one step requires re-signing subsequent transactions. + +EIP-712 Intent Flow + +The user signs a typed message describing “what is authorized” (amount, asset, counterparty, conditions). + +The settlement contract verifies the signature, validates constraints (deadlines, balances, minimum received amounts), and executes the transfer. + +Multiple signed intents can be batched and settled atomically. + +Execution may be: + +Signer-only – only the original signer executes. + +Permissionless – any relayer can execute. + +Allowlisted – execution is restricted to specific third parties. + +3. Settlement Contract Design (EIP-215 Reference) + +The smart contract implements settlement logic as follows: + +Typed Data Verification + +Uses EIP-712 hashing (_hashTypedDataV4) to reconstruct the signed intent. + +Ensures replay protection by storing the message hash once executed. + +Execution + +On valid signature and constraints, tokens are transferred between parties (ERC-20/ERC-721/ERC-1155 support). + +Batch execution is supported to settle multiple intents in one transaction. + +Replay and Fraud Prevention + +Settlement contract persists only minimal state (message hash), reducing gas costs. + +Rich intent data is emitted as logs for auditability. + +4. Backend Settlement Service + +The backend complements the on-chain settlement contract by: + +Generating EIP-712 Payloads + +Constructs domain separators and typed data (chainId, verifying contract, action struct). + +Provides the signing payload to users via API/SDK. + +Signature Collection + +Users sign the typed data with their private keys (e.g., MetaMask, Ledger, Custody service). + +The backend stores signed intents off-chain until settlement is triggered. + +Settlement Trigger + +Backend (or relayer) submits signed intents to the settlement contract. + +Supports multi-party settlement by ensuring both counterparties’ signatures are present. + +Monitoring and Validation + +Tracks settlement status via events. + +Handles retries, nonce checks, and invalid signature rejection. + +5. Data, Cost, and Storage Considerations + +Minimal On-Chain Storage: Only message hashes are stored (~20k gas per new write). + +Event-Based Audit Trail: Detailed intent parameters are logged in transaction receipts. + +Batch Efficiency: Many EIP-712 messages can be executed in a single settlement transaction, optimizing gas usage. + +Execution Flexibility: Settlement can be initiated by signers, relayers, or trusted entities. + +6. Compliance and Extensibility + +Standards Alignment: Built on EIP-712 for typed data and EIP-2612 for token approvals. + +Extensible Structures: Supports swaps, transfers, and future settlement types (DvP, PvP). + +Integration with Custody/Swift: Allow-listed execution enables enterprise integrations. + +✅ Deliverables for this section: + +Diagram: Show the lifecycle (User signs intent → Backend stores signature → Relayer submits → Settlement contract verifies & executes). + +Appendix: Include typed data structure definitions from your backend PDF. + +References: + +EIP-712 + +EIP-2612 + +Internal Settlement Contract (EIP-215 reference) + +Would you like me to also create a clean PDF deliverable for this section (formatted like a proper architecture document, with headings, diagrams placeholders, and references), so you can attach it directly to your project? + +Sources +You said: +create one paragraph for Settlement Backend resposabilities and Settlement contract +ChatGPT said: + +Here’s a compact version you can use in your architecture documentation: + +Settlement Backend Responsibilities and Settlement Contract +The Settlement Backend is responsible for constructing EIP-712 typed data payloads, collecting and managing user signatures, validating settlement conditions off-chain, and triggering on-chain execution via relayers or allow-listed entities. It ensures multi-party agreements are gathered, monitors settlement status through emitted events, and provides auditability and retry mechanisms. The Settlement Contract, on the other hand, acts as the final execution layer: it verifies signatures using EIP-712 standards, enforces replay protection by storing message hashes, validates transfer conditions (balances, deadlines, allowances), and atomically executes swaps or transfers between parties, persisting only minimal state while emitting rich event logs for transparency and compliance. From 07d6b097c647a51aedd6196f1d2dd1512f6c37b7 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 13:25:55 +0000 Subject: [PATCH 37/93] Atualizar o test --- test | 233 ++++------------------------------------------------------- 1 file changed, 15 insertions(+), 218 deletions(-) diff --git a/test b/test index 34df118..c32fb07 100644 --- a/test +++ b/test @@ -1,226 +1,23 @@ -“The Backend API delegates transaction submission to an RBAC Middleware that validates JWT/API-key, enforces role/permission and allowlists, performs policy checks, and only then signs/relays the transaction to the network.” -Minimal architecture & flow - 1. Client → Backend API: request to perform action on contract with params (+ Bearer JWT / API key). - 2. Backend API → RBAC Middleware (/authorize-and-send): - • Validate token (IdP/JWKS or API-key). - • Evaluate RBAC (role→permission) and allowlists (contract address, function selector, wallet address, chainId, limits). - • Apply policy (rate/nonce limits, quotas, velocity, compliance). - • If allowed, sign (HSM/KMS) or forward to Relayer; submit via RPC. - 3. Middleware → Backend API: returns tx hash / receipt (or deny with reason). - 4. Backend API → Client: responds with result. +RBAC Middleware - -4.3.3 Privacy and RBAC Middleware - -The Privacy and RBAC Middleware provides a secure enforcement layer that governs access to Validium-based off-chain state and orchestrates blockchain transaction execution under strict role-based policies. - -Off-chain Privacy and Validium Control - -In this architecture, sensitive data and transaction states are stored off-chain within Validium private storage, ensuring that only zero-knowledge proofs are posted to Layer 1. This prevents exposure of confidential business information while guaranteeing verifiability through cryptographic proofs. - • On-chain: only validity proofs and hashes are committed. - • Off-chain: transaction intents, balances, and settlement details remain private, queryable only by authorized participants. - • Logs and calldata: enriched human-readable details are made available in event logs, minimizing on-chain storage costs and preserving confidentiality. - -RBAC Enforcement - -Access to Validium RPC endpoints and private storage is gated by Role-Based Access Control (RBAC). Each request is validated against policies that define: - • Who (user identity, API key, JWT claims). - • What (contract, function selector, resource scope). - • How (permissions, quotas, transaction type, nonce safety). - -This ensures that only authorized entities can prepare and submit blockchain transactions or query confidential off-chain state. - -Prototype vs Production - • Prototype Phase: RBAC policies are mocked within the middleware to validate functional flows without requiring full identity infrastructure. This enables rapid iteration and integration testing. - • Production Phase: RBAC is integrated with an Identity Provider (IdP) for fine-grained authorization and an API Gateway for authentication. External users authenticate via credentials; JWT tokens are issued and validated against RBAC policies before any transaction is processed. - -Delegated Transaction Model - -The Backend API does not broadcast blockchain transactions directly. Instead, it delegates transaction preparation and submission to the RBAC Middleware: - 1. Prepare: Business logic in the backoffice assembles the transaction intent (using EIP-712 typed structured data). - 2. Authorize: Middleware validates intent against RBAC rules, allowlists, and quotas. - 3. Sign/Relay: If authorized, the Middleware signs the transaction (via KMS/HSM) or relays it on behalf of the user. - 4. Execute: Settlement occurs on-chain, with confidentiality preserved off-chain. -EIP-1159 (Ethereum Improvement Proposal 1159) - -Also known as: London Hard Fork / Fee Market Change / “Base Fee” model - • Introduced in August 2021 with the London upgrade. - • Changed how transaction fees (gas fees) are calculated on Ethereum. - -Before (old model): - • Users set a gas price (bid). - • Miners picked transactions with the highest bids → fee auction. - • Problem: fees were volatile, spikes during congestion. - -After (EIP-1159): - • Transactions now include: - • Base Fee: algorithmically set by the protocol, changes block to block depending on network demand. - • Priority Fee (tip): optional extra you pay to incentivize miners/validators. - • Max Fee: maximum total you are willing to pay. - -Benefits: - • More predictable gas prices. - • Better UX for wallets/dapps (no guessing fees). - • Base fee is burned → reduces ETH supply (deflationary pressure). +The RBAC Middleware ensures privacy and enforces authorization rules across the bridge workflow. Each Issuer integrates with the RBAC Middleware to maintain an isolated privacy domain. The RBAC Middleware is responsible for authorizing mint and burn operations, ensuring only valid and approved transactions move across the networks. ⸻ -🔹 EIP-712 - -Typed Structured Data Hashing and Signing - • Standard for signing structured, human-readable messages off-chain. - • Instead of signing a raw transaction (binary blob), users sign typed data with clear fields. - -Example use cases: - • Permit approvals (EIP-2612): sign a message to allow spending tokens, without sending an on-chain approval tx. - • Meta-transactions: user signs an intent, a relayer submits it on-chain. - • Off-chain agreements: swaps, orders, settlements — validated on-chain later. +4.3.4.2 Bridge interaction flow -Benefits: - • Prevents phishing & replay attacks (domain separator + nonce). - • Messages are human-readable (wallet shows “You allow 100 DAI to be spent by 0x…”). - • Decouples signing from execution → gasless UX, batch transactions, Validium off-chain intents (like in your setup). +Bridge from Enterprise to Swift SLE + 5. A participant in the Enterprise Network initiates a deposit request via the Backend application by first approving the TokenBridge Contract to move funds from the ERC20/ERC3643 contract and locking tokens in the TokenBridge Contract. + 6. The TokenBridge Contract emits an event with details (amount, token, destinationAddress). + 7. The Issuer Bridge Operator monitors and captures this event via a secure message channel. + 8. The Issuer Bridge Operator, using a gas-sponsor wallet, pays the gas on behalf of the Enterprise participant and sends the transaction details to the RBAC Middleware. + 9. The RBAC Middleware validates the request and authorizes the mint of the private tokens inside the Swift SLE environment. ⸻ -🔹 TL;DR - • EIP-1159 → gas fee market reform (base fee, tip, fee burning). - • EIP-712 → standard for signing structured, human-readable off-chain messages (intents, permits). - -⸻ - -⚡ Quick analogy: - • EIP-1159 = how you pay the highway toll (fairer and predictable). - • EIP-712 = how you sign a contract before driving (clear, structured, verifiable intent). - - - -========== - -Settlement and EIP-712 Signatures -1. Overview - -The settlement process is designed to securely authorize and execute asset transfers or swaps using EIP-712 typed data signatures. Instead of requiring users to broadcast and pay for multiple on-chain transactions, the system allows them to sign structured off-chain messages (intents). These intents can later be executed on-chain by a settlement contract, ensuring atomicity, replay protection, and compliance with agreed conditions. - -This architecture decouples authorization (off-chain signature) from execution (on-chain settlement), enabling flexible models such as user-only execution, relayer-based execution, or allow-listed counterparties (e.g., Swift integration). - -2. Baseline vs. Intent-Based Flows -Traditional Transaction Flow - -Each action (approve, transfer, swap) is a separate on-chain transaction. - -The user must maintain ETH (or gas token) for fees. - -Transactions are executed sequentially by nonce order. - -Cancelling or modifying one step requires re-signing subsequent transactions. - -EIP-712 Intent Flow - -The user signs a typed message describing “what is authorized” (amount, asset, counterparty, conditions). - -The settlement contract verifies the signature, validates constraints (deadlines, balances, minimum received amounts), and executes the transfer. - -Multiple signed intents can be batched and settled atomically. - -Execution may be: - -Signer-only – only the original signer executes. - -Permissionless – any relayer can execute. - -Allowlisted – execution is restricted to specific third parties. - -3. Settlement Contract Design (EIP-215 Reference) - -The smart contract implements settlement logic as follows: - -Typed Data Verification - -Uses EIP-712 hashing (_hashTypedDataV4) to reconstruct the signed intent. - -Ensures replay protection by storing the message hash once executed. - -Execution - -On valid signature and constraints, tokens are transferred between parties (ERC-20/ERC-721/ERC-1155 support). - -Batch execution is supported to settle multiple intents in one transaction. - -Replay and Fraud Prevention - -Settlement contract persists only minimal state (message hash), reducing gas costs. - -Rich intent data is emitted as logs for auditability. - -4. Backend Settlement Service - -The backend complements the on-chain settlement contract by: - -Generating EIP-712 Payloads - -Constructs domain separators and typed data (chainId, verifying contract, action struct). - -Provides the signing payload to users via API/SDK. - -Signature Collection - -Users sign the typed data with their private keys (e.g., MetaMask, Ledger, Custody service). - -The backend stores signed intents off-chain until settlement is triggered. - -Settlement Trigger - -Backend (or relayer) submits signed intents to the settlement contract. - -Supports multi-party settlement by ensuring both counterparties’ signatures are present. - -Monitoring and Validation - -Tracks settlement status via events. - -Handles retries, nonce checks, and invalid signature rejection. - -5. Data, Cost, and Storage Considerations - -Minimal On-Chain Storage: Only message hashes are stored (~20k gas per new write). - -Event-Based Audit Trail: Detailed intent parameters are logged in transaction receipts. - -Batch Efficiency: Many EIP-712 messages can be executed in a single settlement transaction, optimizing gas usage. - -Execution Flexibility: Settlement can be initiated by signers, relayers, or trusted entities. - -6. Compliance and Extensibility - -Standards Alignment: Built on EIP-712 for typed data and EIP-2612 for token approvals. - -Extensible Structures: Supports swaps, transfers, and future settlement types (DvP, PvP). - -Integration with Custody/Swift: Allow-listed execution enables enterprise integrations. - -✅ Deliverables for this section: - -Diagram: Show the lifecycle (User signs intent → Backend stores signature → Relayer submits → Settlement contract verifies & executes). - -Appendix: Include typed data structure definitions from your backend PDF. - -References: - -EIP-712 - -EIP-2612 - -Internal Settlement Contract (EIP-215 reference) - -Would you like me to also create a clean PDF deliverable for this section (formatted like a proper architecture document, with headings, diagrams placeholders, and references), so you can attach it directly to your project? - -Sources -You said: -create one paragraph for Settlement Backend resposabilities and Settlement contract -ChatGPT said: - -Here’s a compact version you can use in your architecture documentation: - -Settlement Backend Responsibilities and Settlement Contract -The Settlement Backend is responsible for constructing EIP-712 typed data payloads, collecting and managing user signatures, validating settlement conditions off-chain, and triggering on-chain execution via relayers or allow-listed entities. It ensures multi-party agreements are gathered, monitors settlement status through emitted events, and provides auditability and retry mechanisms. The Settlement Contract, on the other hand, acts as the final execution layer: it verifies signatures using EIP-712 standards, enforces replay protection by storing message hashes, validates transfer conditions (balances, deadlines, allowances), and atomically executes swaps or transfers between parties, persisting only minimal state while emitting rich event logs for transparency and compliance. +Bridge from Swift SLE to Enterprise + 6. A participant in the Enterprise Network initiates a withdrawal request via the Backend application, which sends a request to the Issuer Bridge Operator. + 7. The Issuer Bridge Operator forwards the withdrawal request to the RBAC Middleware for authorization. + 8. The RBAC Middleware validates the burn, generates a proof of burn, and returns it to the Issuer Bridge Operator. + 9. The Issuer Bridge Operator sends the validated proof back to the Enterprise TokenBridge Contract. + 10. The TokenBridge Contract releases the locked tokens to the specified address on the Enterprise Network. \ No newline at end of file From e32b8c9c81bdf4b0d6595f8af24457cecbb8bd96 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 17:19:45 +0000 Subject: [PATCH 38/93] Atualizar o test --- test | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/test b/test index c32fb07..1c60268 100644 --- a/test +++ b/test @@ -20,4 +20,69 @@ Bridge from Swift SLE to Enterprise 7. The Issuer Bridge Operator forwards the withdrawal request to the RBAC Middleware for authorization. 8. The RBAC Middleware validates the burn, generates a proof of burn, and returns it to the Issuer Bridge Operator. 9. The Issuer Bridge Operator sends the validated proof back to the Enterprise TokenBridge Contract. - 10. The TokenBridge Contract releases the locked tokens to the specified address on the Enterprise Network. \ No newline at end of file + 10. The TokenBridge Contract releases the locked tokens to the specified address on the Enterprise Network. + +------ +Generate PKI client cert (bank → gets installed on their machine/app). + 2. Create API key in API Gateway (send to bank). + 3. Create Keycloak client_id/secret (send to bank). + 4. Bank calls OIDC → get JWT → call API with mTLS + API key + JWT. + + +Bank ↔ API Gateway: mTLS + API Key (+ JWT you issue via RBAC broker endpoint) + • API Gateway ↔ RBAC: private (VPC Link) + • RBAC ↔ Keycloak: internal only (HTTPS), RBAC holds the client secrets + +Onboarding steps (day-1 for a new bank) + +1) PKI + Gateway + 1. Issue client cert for the bank (or sign their CSR). + 2. Add your CA to API Gateway mTLS truststore (S3 PEM). + 3. Create API Key (bankX-prod) + Usage Plan; require on routes. + 4. Keep Gateway JWT Authorizer enabled (we’ll feed it a Keycloak token). + +2) Keycloak (internal only) + 1. Create client: bankX-api-client (OIDC, confidential; service accounts ON). + 2. Assign roles/scopes (bridge:deposit, etc.). + 3. Add mappers: + • aud = my-enterprise-api + • org_id = bankX + • include roles in token + 4. Copy client_secret. Do NOT share with bank. + +3) RBAC DB (tenant & allowlists) + • Map cert subject ⇄ org_id=bankX + • Map API key id ⇄ org_id=bankX + • Seed allowlists (wallets, contracts, function_sigs). + +4) RBAC exposes a /token endpoint (Token Broker) + • Bank does not talk to Keycloak. + • Bank calls RBAC /token over Gateway with mTLS + API key. + • RBAC authenticates bank (mTLS+API key), finds org_id, looks up bank’s Keycloak client creds, calls Keycloak token endpoint (client_credentials), returns the access_token (JWT) to the bank. +5) Bank calls your real APIs +Gateway validates: + • mTLS client cert ✅ + • x-api-key usage plan ✅ + • JWT (issuer/audience/signature) via JWKS ✅ + +RBAC Middleware (on the API path) then: + • Parses JWT → org_id, roles/scopes + • Enforces allowlists (wallet/contract/function) + • Proceeds with business flow + +Bank → Gateway (/token): mTLS + API key + 2. Gateway → RBAC (/token): pass through + 3. RBAC → Keycloak: client_credentials with bankX-api-client + 4. Keycloak → RBAC: returns JWT (aud=my-enterprise-api, org=bankX) + 5. RBAC → Bank: returns JWT + 6. Bank → Gateway (/bridge/deposit): mTLS + API key + Bearer JWT + 7. Gateway: validates JWT (JWKS) + API key; forwards + 8. RBAC: enforces RBAC/allowlists; executes + + +Pattern A (preferred — what you’re already designing) + • Partner → RBAC: mTLS + API key (no Keycloak secret). + • RBAC → Keycloak: uses stored client_id/secret per bank (in Secrets Manager/Vault). + • RBAC /token returns Keycloak access_token (JWT) to the bank. + • Bank uses that JWT + mTLS + API key for API calls. + From 542556a3f0195021989a04eb11267f2ed1fea688 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 20:53:52 +0000 Subject: [PATCH 39/93] Atualizar o test --- test | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/test b/test index 1c60268..430c4bb 100644 --- a/test +++ b/test @@ -86,3 +86,106 @@ Pattern A (preferred — what you’re already designing) • RBAC /token returns Keycloak access_token (JWT) to the bank. • Bank uses that JWT + mTLS + API key for API calls. + + +==== +Got it—here’s the exact flow you described, clean and precise. + +Flow A — RBAC issues JWT on behalf of the bank + +Preconditions / Mappings + • api_key_id ↔ tenant_id ↔ oidc_client_id ↔ secret_ref (in DB) + • secret_ref points to Secret Manager entry for the OIDC client secret + • Cert fingerprint for the bank is registered (for mTLS) + +Sequence (Mermaid) + +sequenceDiagram + participant Bank as Bank Backend + participant GW as API Gateway + participant RBAC as RBAC Middleware + participant SM as Secret Manager + participant IdP as IdP (OIDC) + + Note over Bank: 1) Get JWT via RBAC + Bank->>GW: POST /auth/jwt (mTLS)
Headers: x-api-key + GW->>GW: Verify mTLS client cert ✅
Verify API key ✅ (get api_key_id) + GW->>RBAC: Forward request
Headers: X-Api-Key-Id, X-Client-Cert-Fingerprint + + RBAC->>RBAC: Lookup api_key_id → (tenant, oidc_client_id, secret_ref) + RBAC->>SM: Get client_secret (secret_ref) + SM-->>RBAC: client_secret + RBAC->>IdP: POST /oauth2/token (client_credentials)
client_id=oidc_client_id&client_secret + IdP-->>RBAC: { access_token (JWT), expires_in } + RBAC-->>GW: { access_token (JWT) } + GW-->>Bank: { access_token (JWT) } + + Note over Bank: 2) Call protected API + Bank->>GW: POST /settlement/v1/... (mTLS)
Headers: x-api-key, Authorization: Bearer JWT + GW->>GW: Verify mTLS ✅, verify API key ✅, rate-limit/log + GW->>RBAC: Forward request + JWT
Headers: X-Api-Key-Id, X-Client-Cert-Fingerprint + RBAC->>RBAC: Verify JWT (JWKS cache), resolve tenant, enforce RBAC/allowlists + RBAC-->>GW: 200/401/403/429/5xx + GW-->>Bank: Response + +Endpoints & Headers + +1) Get JWT (Bank → RBAC via Gateway) + +POST /auth/jwt +x-api-key: +# mTLS client cert presented at TLS layer +Body: { "scope": "settlement.write" } # optional + +Gateway → RBAC (forwarded): + +X-Api-Key-Id: +X-Client-Cert-Fingerprint: sha256:<...> +X-Request-Id: + +RBAC → IdP (client credentials): + +POST /oauth2/token +Content-Type: application/x-www-form-urlencoded + +grant_type=client_credentials& +client_id=& +client_secret=& +scope=settlement.write + +RBAC → Bank (via Gateway): + +{ + "access_token": "", + "token_type": "Bearer", + "expires_in": 600 +} + +2) Protected API call + +POST /settlement/v1/submit +Authorization: Bearer +x-api-key: +# mTLS client cert at TLS + +What each component does + • API Gateway + • Verifies mTLS and API key; resolves/attaches X-Api-Key-Id + • Rate limits, quotas, logging; forwards fingerprint header + • RBAC Middleware + • For /auth/jwt: DB lookup → fetch client_secret from Secret Manager → OIDC token request → return JWT + • For protected APIs: verify JWT (JWKS cache), map tenant, enforce RBAC + allowlists (wallets/contracts/methods), audit + • Secret Manager + • Stores OIDC client_secret; returns on-demand (never logs it) + • IdP (OIDC) + • Issues short-lived access tokens for client_credentials + +Security & Ops tips (for this model) + • Do not expose or log client_secret; only RBAC reads from Secret Manager. + • Cache the JWT per tenant until expiry; proactively refresh on 80–90% TTL. + • Enable CRL/OCSP on Gateway for client-cert revocation. + • Use mTLS-bound tokens (RFC 8705) if your IdP supports it (extra strong binding). + • Rotate: API keys, client secrets; monitor token issuance rates (abuse detection). + • In RBAC, verify JWT claims: iss, aud, exp, nbf, scope/roles, sub. + +If you want, I can tailor the headers and config for your stack (e.g., Kong, AWS API Gateway, or NGINX + Keycloak/Okta), including example plugin settings and JWKS caching code. From bef48cc917a40cb84fc8aff9e8a4ba39010eced2 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 20:55:17 +0000 Subject: [PATCH 40/93] Atualizar o test --- test | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test b/test index 430c4bb..3a9e741 100644 --- a/test +++ b/test @@ -189,3 +189,24 @@ Security & Ops tips (for this model) • In RBAC, verify JWT claims: iss, aud, exp, nbf, scope/roles, sub. If you want, I can tailor the headers and config for your stack (e.g., Kong, AWS API Gateway, or NGINX + Keycloak/Okta), including example plugin settings and JWKS caching code. + +Onboarding (new bank) + 1. PKI / mTLS + + • Platform CA issues client certificate for the bank (or signs bank CSR). + • Distribute: bank-client.crt + bank-client.key (to bank) and Root/Intermediate CA (to both sides). + • Register the bank cert thumbprint (SHA-256) in your tenant table. + + 2. API Key (Gateway) + + • Create API key in the API Gateway; attach usage plan (rate/quotas) and tenant tag. + • Store mapping in DB: bank_id ↔ api_key_id ↔ cert_thumbprint. + + 3. OIDC Client (IdP) + + • Create OIDC client (grant: client_credentials for system-to-system). + • Get client_id/client_secret; assign scopes/roles. + • Store mapping in DB: bank_id ↔ oidc_client_id ↔ scopes/roles. + • (Optional, strong) Enable MTLS-bound tokens at IdP so the JWT is tied to the bank cert. + + From 80b65fac1be81c66c2a9d1e50ef0b4d7a753d8b0 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 21:03:32 +0000 Subject: [PATCH 41/93] Atualizar o test --- test | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test b/test index 3a9e741..9b6c6bf 100644 --- a/test +++ b/test @@ -209,4 +209,14 @@ Onboarding (new bank) • Store mapping in DB: bank_id ↔ oidc_client_id ↔ scopes/roles. • (Optional, strong) Enable MTLS-bound tokens at IdP so the JWT is tied to the bank cert. +API Gateway +The API Gateway acts as the secure entry point for all requests, enforcing mTLS for mutual authentication, validating API keys, and applying rate limiting to protect against abuse. It provides identification and traffic control for each tenant, while also enabling simple service integration by routing validated requests to the RBAC Middleware and downstream services. +Identity Provider (IdP) +The Identity Provider (IdP) implements OpenID Connect (OIDC) on top of the OAuth2 protocol, enabling strong authentication and standardized token issuance. It manages roles, claims, and allowlists, providing signed JWTs that the RBAC Middleware can verify to enforce fine-grained authorization across APIs and smart contract operations. + +Prototype Phase +In the prototype phase, RBAC policies are mocked within the middleware to validate functional flows without requiring a full identity infrastructure. The middleware is also responsible for sending blockchain transactions (received from the Mock Backoffice Application) to the Validium RPC Node and for covering the gas fees. This setup enables rapid iteration, testing, and integration of the solution. + +Production Phase +In the production phase, the RBAC middleware should be integrated with an Identity Provider (IdP) to enable fine-grained authorization. OpenConnect ID should be configured so that JWT tokens issued by the IdP are validated against RBAC policies before any transaction is processed. Responsibility for signing transactions and paying gas fees should be shifted to the RelayerSigner component, which will handle these functions. From fa6525ccecc21f73c1d07a6ce92a30e5b9002395 Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 24 Sep 2025 21:09:11 +0000 Subject: [PATCH 42/93] Atualizar o test --- test | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test b/test index 9b6c6bf..a240b19 100644 --- a/test +++ b/test @@ -220,3 +220,9 @@ In the prototype phase, RBAC policies are mocked within the middleware to valida Production Phase In the production phase, the RBAC middleware should be integrated with an Identity Provider (IdP) to enable fine-grained authorization. OpenConnect ID should be configured so that JWT tokens issued by the IdP are validated against RBAC policies before any transaction is processed. Responsibility for signing transactions and paying gas fees should be shifted to the RelayerSigner component, which will handle these functions. + +mTLS + PKI – The CA issues a client certificate and sends it to the bank. + 2. API Key – An API key is generated in the API Gateway and provided to the bank. + 3. OIDC Client – The IdP creates a client_id and client_secret, mapped in the DB with the api_key_id. + 4. JWT Retrieval – The bank calls RBAC Middleware with API key + client certificate → Gateway verifies them → RBAC fetches secret from Secret Manager and obtains a JWT from the IdP. + 5. Protected API Access – The bank calls APIs using API key + client certificate + JWT. From a470dbe20565f4085d6b49a582034ce05e0c1c1d Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 25 Sep 2025 07:27:52 +0000 Subject: [PATCH 43/93] Atualizar o test --- test | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/test b/test index a240b19..4447524 100644 --- a/test +++ b/test @@ -226,3 +226,30 @@ mTLS + PKI – The CA issues a client certificate and sends it to the bank. 3. OIDC Client – The IdP creates a client_id and client_secret, mapped in the DB with the api_key_id. 4. JWT Retrieval – The bank calls RBAC Middleware with API key + client certificate → Gateway verifies them → RBAC fetches secret from Secret Manager and obtains a JWT from the IdP. 5. Protected API Access – The bank calls APIs using API key + client certificate + JWT. + +RBAC ensures that the off-chain state is accessible only to authorized parties and should be enforced at the API layer, which sits between the application services and the Validium Swift node RPC. + +When external users connect via the API, they should be identified using the API key provided by the API Gateway. Communication is secured through mTLS/PKI, where the API Gateway verifies the client certificate. The Identity Provider (IdP), configured with OpenID Connect (OIDC), provides fine-grained identity and authorization by issuing JWT tokens that are validated against RBAC policies. + +sequenceDiagram + participant CA as Certificate Authority (CA) + participant GW as API Gateway + participant IdP as IdP / OIDC + participant DB as Database + participant RBAC as RBAC Middleware + participant Bank as Bank + + Note over Bank,CA: Step 1 - mTLS + PKI + CA->>Bank: Issue client certificate (X.509) + Bank-->>CA: Stores cert & private key + + Note over Bank,GW: Step 2 - API Key + GW->>Bank: Generate & provide API key + GW->>DB: Store api_key_id mapping + + Note over Bank,IdP: Step 3 - OIDC Client + IdP->>RBAC: Create client_id + secret + RBAC->>DB: Map (api_key_id, client_id, client_secret_ref) + IdP-->>Bank: Provide client_id + secret + + From c33edc83262bf4a0a0288a0d7da49e628e1515eb Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 10:00:44 +0200 Subject: [PATCH 44/93] Update test --- test | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 1 deletion(-) diff --git a/test b/test index 4447524..f1b4d90 100644 --- a/test +++ b/test @@ -1,4 +1,93 @@ -RBAC Middleware +RBAC Application + + +Authentication +sequenceDiagram + autonumber + participant U as User (Browser) + participant P as Portal (https://app.sua-app.com) + participant R as RBAC Middleware (https://api.sua-app.com) + participant K as Keycloak (https://login.sua-idp.com) + participant S as Session Store (e.g., Redis) + participant A as Downstream API / Microservice + + %% ---- LOGIN INIT ---- + U->>P: Open Portal (/) + P->>R: GET /auth/login?next=/dashboard (credentials: include) + note right of R: Generate state (+ optional nonce / PKCE code_challenge) + + R->>U: 302 Redirect → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE[&code_challenge=...] + U->>K: GET .../auth (Login Page) + + %% ---- USER AUTHENTICATES ---- + K->>U: Render Login Page (username/password, MFA, etc.) + U->>K: Submit credentials (and MFA if any) + + %% ---- CALLBACK TO RBAC ---- + K->>U: 302 Redirect → https://api.sua-app.com/auth/callback?code=CODE&state=STATE + U->>R: GET /auth/callback?code=CODE&state=STATE + + note right of R: Validate state (and nonce if using id_token)
Exchange code → tokens at /token + + R->>K: POST /realms//protocol/openid-connect/token
grant_type=authorization_code&client_id=rbac-middleware&client_secret=***&code=CODE&redirect_uri=https://api.sua-app.com/auth/callback[&code_verifier=...] + K-->>R: 200 { access_token, refresh_token, id_token, expires_in } + + R->>S: Save session {sub, roles, access_token, refresh_token, expires_at} + R->>U: Set-Cookie: sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard + + %% ---- PORTAL USES API WITH SESSION COOKIE ---- + U->>P: GET /dashboard + P->>R: XHR: GET /api/me (credentials: include; cookie: sid=SESSION_ID) + + note over R: Load session by sid
If access token near expiry → refresh + + alt Access token expiring (<60s) + R->>K: POST /token (grant_type=refresh_token&client_id=rbac-middleware&client_secret=***&refresh_token=RT) + K-->>R: 200 { new access_token, refresh_token, expires_in } + R->>S: Update session tokens and expiry + end + + R->>A: GET /me (Authorization: Bearer ) + A-->>R: 200 { user profile / claims } + R-->>P: 200 { user profile / claims } + + %% ---- AUTHZ / RBAC ENFORCEMENT ---- + P->>R: POST /api/tx (credentials: include) + note right of R: Enforce roles/allowlists (wallet/contract/etc.) before calling downstream + R->>A: POST /tx (Authorization: Bearer ) + A-->>R: 200 { result } + R-->>P: 200 { result } + + %% ---- LOGOUT ---- + U->>P: Click "Logout" + P->>R: POST /auth/logout (credentials: include) + R->>S: Destroy session (SESSION_ID) + R->>U: Clear-Cookie sid= (HttpOnly, expires past) + R->>K: (Optional) GET /protocol/openid-connect/logout?post_logout_redirect_uri=https://app.sua-app.com/ + K-->>U: 302 → https://app.sua-app.com/ + + %% ---- ERROR HANDLING (EXAMPLES) ---- + rect rgba(255, 230, 230, 0.5) + note over R,K: If /token refresh fails (invalid/expired RT):
→ redirect user to /auth/login preserving next=/current + end + + + + + + + + + + + + + + + + + +RBAC API The RBAC Middleware ensures privacy and enforces authorization rules across the bridge workflow. Each Issuer integrates with the RBAC Middleware to maintain an isolated privacy domain. The RBAC Middleware is responsible for authorizing mint and burn operations, ensuring only valid and approved transactions move across the networks. From d45c881d7fd225965d9d1960d25bb1879f0d3b21 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 10:03:31 +0200 Subject: [PATCH 45/93] Update test --- test | 103 ++++++++++++++++++++++++++++------------------------------- 1 file changed, 48 insertions(+), 55 deletions(-) diff --git a/test b/test index f1b4d90..1001181 100644 --- a/test +++ b/test @@ -1,75 +1,68 @@ RBAC Application -Authentication sequenceDiagram autonumber participant U as User (Browser) - participant P as Portal (https://app.sua-app.com) - participant R as RBAC Middleware (https://api.sua-app.com) - participant K as Keycloak (https://login.sua-idp.com) - participant S as Session Store (e.g., Redis) - participant A as Downstream API / Microservice + participant P as Portal (app.sua-app.com) + participant N as NGINX Edge (mTLS gateway) + participant R as RBAC Middleware (api.sua-app.com) + participant K as Keycloak (login.sua-idp.com) + participant CA as PKI (Root/Intermediate CA) + participant S as Session Store (Redis) + participant A as Downstream API + + %% ---- ONE-TIME PKI ENROLLMENT ---- + rect rgba(235, 245, 255, 0.7) + U->>CA: Request client certificate (CSR) + CA-->>U: Issue client cert (User.crt) signed by Intermediate CA + note over U,CA: Cert instalado no browser (ou no dispositivo) com a chave privada + end + + %% ---- FIRST CONTACT: mTLS @ NGINX ---- + U->>N: TLS handshake (Server presents N cert; Client presents User.crt) + N-->>U: TLS established if cert valid (verify chain, CRL/OCSP, expiry) + note over N: ssl_verify_client on;
verify against CA bundle %% ---- LOGIN INIT ---- U->>P: Open Portal (/) - P->>R: GET /auth/login?next=/dashboard (credentials: include) - note right of R: Generate state (+ optional nonce / PKCE code_challenge) + P->>N: GET /auth/login?next=/dashboard (cookie/samesite) + N->>R: Proxy /auth/login (mTLS upstream optional) + R->>R: Generate state (and optional nonce/PKCE) + R-->>U: 302 → K /auth (client_id, response_type=code,
redirect_uri=https://api.sua-app.com/auth/callback, scope, state[, code_challenge]) - R->>U: 302 Redirect → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE[&code_challenge=...] + %% ---- KEYCLOAK INTERACTIVE LOGIN ---- U->>K: GET .../auth (Login Page) + K->>U: Render login + MFA/WebAuthn + U->>K: Submit credentials/MFA - %% ---- USER AUTHENTICATES ---- - K->>U: Render Login Page (username/password, MFA, etc.) - U->>K: Submit credentials (and MFA if any) - - %% ---- CALLBACK TO RBAC ---- - K->>U: 302 Redirect → https://api.sua-app.com/auth/callback?code=CODE&state=STATE - U->>R: GET /auth/callback?code=CODE&state=STATE + %% ---- CALLBACK TO RBAC (CONFIDENTIAL CLIENT) ---- + K-->>U: 302 → https://api.sua-app.com/auth/callback?code&state + U->>N: GET /auth/callback?code&state (mTLS again) + N->>R: Proxy /auth/callback - note right of R: Validate state (and nonce if using id_token)
Exchange code → tokens at /token + R->>K: POST /token (authorization_code, client_id, client_secret[, code_verifier]) + K-->>R: {access_token, refresh_token, id_token, expires_in} + R->>S: Save session {sub, roles, AT, RT, exp} + R-->>U: Set-Cookie sid=... (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard - R->>K: POST /realms//protocol/openid-connect/token
grant_type=authorization_code&client_id=rbac-middleware&client_secret=***&code=CODE&redirect_uri=https://api.sua-app.com/auth/callback[&code_verifier=...] - K-->>R: 200 { access_token, refresh_token, id_token, expires_in } - - R->>S: Save session {sub, roles, access_token, refresh_token, expires_at} - R->>U: Set-Cookie: sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard - - %% ---- PORTAL USES API WITH SESSION COOKIE ---- + %% ---- API USE WITH SESSION COOKIE + mTLS EDGE ---- U->>P: GET /dashboard - P->>R: XHR: GET /api/me (credentials: include; cookie: sid=SESSION_ID) - - note over R: Load session by sid
If access token near expiry → refresh - - alt Access token expiring (<60s) - R->>K: POST /token (grant_type=refresh_token&client_id=rbac-middleware&client_secret=***&refresh_token=RT) - K-->>R: 200 { new access_token, refresh_token, expires_in } - R->>S: Update session tokens and expiry - end - - R->>A: GET /me (Authorization: Bearer ) - A-->>R: 200 { user profile / claims } - R-->>P: 200 { user profile / claims } - - %% ---- AUTHZ / RBAC ENFORCEMENT ---- - P->>R: POST /api/tx (credentials: include) - note right of R: Enforce roles/allowlists (wallet/contract/etc.) before calling downstream - R->>A: POST /tx (Authorization: Bearer ) - A-->>R: 200 { result } - R-->>P: 200 { result } + P->>N: XHR GET /api/me (credentials: include; mTLS) + N->>R: Proxy /api/me (optionally mTLS upstream) + R->>R: Load session; refresh AT if near expiry + R->>A: GET /me (Authorization: Bearer ) + A-->>R: 200 { profile/claims } + R-->>P: 200 { profile/claims } %% ---- LOGOUT ---- - U->>P: Click "Logout" - P->>R: POST /auth/logout (credentials: include) - R->>S: Destroy session (SESSION_ID) - R->>U: Clear-Cookie sid= (HttpOnly, expires past) - R->>K: (Optional) GET /protocol/openid-connect/logout?post_logout_redirect_uri=https://app.sua-app.com/ - K-->>U: 302 → https://app.sua-app.com/ - - %% ---- ERROR HANDLING (EXAMPLES) ---- - rect rgba(255, 230, 230, 0.5) - note over R,K: If /token refresh fails (invalid/expired RT):
→ redirect user to /auth/login preserving next=/current - end + U->>P: Click Logout + P->>N: POST /auth/logout (mTLS) + N->>R: Proxy /auth/logout + R->>S: Destroy session; clear cookie + R->>K: (optional) end_session → post_logout_redirect_uri=https://app.sua-app.com/ + K-->>U: 302 → Portal + From 99efbbe811baeb3f6b1ec1a5c36d926c458f642b Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 10:12:03 +0200 Subject: [PATCH 46/93] Update test --- test | 183 ++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 137 insertions(+), 46 deletions(-) diff --git a/test b/test index 1001181..d114370 100644 --- a/test +++ b/test @@ -1,67 +1,158 @@ -RBAC Application +RBAC Application sequenceDiagram autonumber participant U as User (Browser) - participant P as Portal (app.sua-app.com) + participant P as Portal (https://app.sua-app.com) participant N as NGINX Edge (mTLS gateway) - participant R as RBAC Middleware (api.sua-app.com) - participant K as Keycloak (login.sua-idp.com) - participant CA as PKI (Root/Intermediate CA) + participant R as RBAC Middleware (https://api.sua-app.com) + participant K as Keycloak (https://login.sua-idp.com) participant S as Session Store (Redis) participant A as Downstream API - %% ---- ONE-TIME PKI ENROLLMENT ---- - rect rgba(235, 245, 255, 0.7) - U->>CA: Request client certificate (CSR) - CA-->>U: Issue client cert (User.crt) signed by Intermediate CA - note over U,CA: Cert instalado no browser (ou no dispositivo) com a chave privada - end - - %% ---- FIRST CONTACT: mTLS @ NGINX ---- - U->>N: TLS handshake (Server presents N cert; Client presents User.crt) - N-->>U: TLS established if cert valid (verify chain, CRL/OCSP, expiry) - note over N: ssl_verify_client on;
verify against CA bundle - %% ---- LOGIN INIT ---- U->>P: Open Portal (/) - P->>N: GET /auth/login?next=/dashboard (cookie/samesite) - N->>R: Proxy /auth/login (mTLS upstream optional) - R->>R: Generate state (and optional nonce/PKCE) - R-->>U: 302 → K /auth (client_id, response_type=code,
redirect_uri=https://api.sua-app.com/auth/callback, scope, state[, code_challenge]) + P->>R: GET /auth/login?next=/dashboard + U->>N: TLS handshake with client cert + N-->>U: TLS established (cert validated by CA) - %% ---- KEYCLOAK INTERACTIVE LOGIN ---- + R->>U: 302 Redirect → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE U->>K: GET .../auth (Login Page) - K->>U: Render login + MFA/WebAuthn - U->>K: Submit credentials/MFA - - %% ---- CALLBACK TO RBAC (CONFIDENTIAL CLIENT) ---- - K-->>U: 302 → https://api.sua-app.com/auth/callback?code&state - U->>N: GET /auth/callback?code&state (mTLS again) - N->>R: Proxy /auth/callback - - R->>K: POST /token (authorization_code, client_id, client_secret[, code_verifier]) - K-->>R: {access_token, refresh_token, id_token, expires_in} - R->>S: Save session {sub, roles, AT, RT, exp} - R-->>U: Set-Cookie sid=... (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard - - %% ---- API USE WITH SESSION COOKIE + mTLS EDGE ---- - U->>P: GET /dashboard - P->>N: XHR GET /api/me (credentials: include; mTLS) - N->>R: Proxy /api/me (optionally mTLS upstream) - R->>R: Load session; refresh AT if near expiry - R->>A: GET /me (Authorization: Bearer ) - A-->>R: 200 { profile/claims } - R-->>P: 200 { profile/claims } + + %% ---- USER AUTHENTICATES ---- + K->>U: Render Login Page + U->>K: Submit credentials (username/password + MFA) + + %% ---- CALLBACK ---- + K->>U: 302 Redirect → https://api.sua-app.com/auth/callback?code=CODE&state=STATE + U->>N: GET /auth/callback?code=CODE&state=STATE (mTLS again) + N->>R: Proxy request + + R->>K: POST /token
grant_type=authorization_code&client_id=rbac-middleware&client_secret=***&code=CODE&redirect_uri=https://api.sua-app.com/auth/callback + K-->>R: {access_token, refresh_token, id_token} + + R->>S: Save session {sub, roles, tokens, expiry} + R->>U: Set-Cookie sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard + + %% ---- API USE ---- + U->>P: Open /dashboard + P->>N: XHR /api/me (cookie: sid=SESSION_ID, mTLS) + N->>R: Proxy /api/me + R->>A: GET /me (Authorization: Bearer ) + A-->>R: 200 {profile} + R-->>P: 200 {profile} + + %% ---- REFRESH ---- + R->>K: POST /token (grant_type=refresh_token&client_id=rbac-middleware&client_secret=***&refresh_token=RT) + K-->>R: {new access_token, refresh_token} + R->>S: Update session %% ---- LOGOUT ---- U->>P: Click Logout P->>N: POST /auth/logout (mTLS) N->>R: Proxy /auth/logout - R->>S: Destroy session; clear cookie - R->>K: (optional) end_session → post_logout_redirect_uri=https://app.sua-app.com/ - K-->>U: 302 → Portal + R->>S: Destroy session + R->>U: Clear sid cookie + R->>K: (optional) end_session_endpoint + K-->>U: Redirect → https://app.sua-app.com/ + + +Authentication + +Step-by-Step Description (without PKCE) +Prerequisites + +PKI setup: Root CA → Intermediate CA → issue client certificates. + +User installs client cert in browser/device. + +NGINX configured with mTLS (ssl_verify_client on;). + +Keycloak client rbac-middleware created as confidential: + +Authorization Code Flow enabled + +Redirect URI: https://api.sua-app.com/auth/callback + +Post Logout Redirect URI: https://app.sua-app.com/* + +Authentication Flow + +User opens https://app.sua-app.com. + +Portal requests login at https://api.sua-app.com/auth/login?next=/dashboard. + +mTLS check: browser presents client cert, NGINX validates with CA → request allowed. + +RBAC generates a state, then responds with 302 redirect to Keycloak /auth with params: + +client_id=rbac-middleware + +response_type=code + +redirect_uri=https://api.sua-app.com/auth/callback + +scope=openid profile email + +state= + +Keycloak shows Login Page. + +User authenticates (password, MFA, etc.). + +Callback + Token Exchange + +Keycloak redirects to RBAC: https://api.sua-app.com/auth/callback?code=...&state=.... + +mTLS again: NGINX validates client cert, forwards to RBAC. + +RBAC validates state, then calls Keycloak /token with: + +grant_type=authorization_code +client_id=rbac-middleware +client_secret=SECRET +code=XYZ +redirect_uri=https://api.sua-app.com/auth/callback + + +Keycloak responds with tokens. + +RBAC saves {access_token, refresh_token, expiry} in session store (Redis). + +RBAC sets sid cookie (HttpOnly, Secure, SameSite) and redirects user to portal /dashboard. + +Using the Application + +Portal uses the session cookie (sid) in requests to RBAC APIs. + +RBAC checks session, enforces RBAC rules (roles, allowlists), and forwards calls downstream with Authorization: Bearer . + +Microservice responds, RBAC passes result back to portal. + +Token Refresh + +If access_token near expiry, RBAC uses refresh_token with Keycloak /token to get a new pair. + +RBAC updates the session transparently. + +Logout + +Portal calls POST /auth/logout. + +RBAC clears session + cookie, optionally calls Keycloak end_session_endpoint. + +User is redirected back to https://app.sua-app.com/ logged out. + +✅ With this model: + +Tokens never touch the browser. + +Browser → NGINX requires a valid client certificate (mTLS). + +RBAC Middleware is the only Keycloak client (confidential, with client_secret). + + From d889186a2918e30719c72d408ca84494b9e53720 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 10:23:44 +0200 Subject: [PATCH 47/93] Update test --- test | 177 +++++++++++++---------------------------------------------- 1 file changed, 39 insertions(+), 138 deletions(-) diff --git a/test b/test index d114370..572f031 100644 --- a/test +++ b/test @@ -4,145 +4,46 @@ RBAC Application sequenceDiagram autonumber participant U as User (Browser) - participant P as Portal (https://app.sua-app.com) - participant N as NGINX Edge (mTLS gateway) - participant R as RBAC Middleware (https://api.sua-app.com) - participant K as Keycloak (https://login.sua-idp.com) - participant S as Session Store (Redis) - participant A as Downstream API + participant N as NGINX (Edge proxy) + participant P as Portal SDL Frontend (app.sua-app.com) + participant R as RBAC Middleware (api.sua-app.com) + participant K as Keycloak (login.sua-idp.com) + participant S as Session Store (e.g., Redis) + + %% ---- PORTAL LOAD VIA NGINX ---- + U->>N: GET https://app.sua-app.com/ + N->>P: Proxy / (serve SPA) + P-->>N: index.html, JS/CSS + N-->>U: Portal assets + + %% ---- LOGIN INITIATION (Portal calls RBAC via NGINX route) ---- + U->>N: GET /auth/login?next=/dashboard %% initiated by Portal (button/auto) + N->>R: Proxy /auth/login + note right of R: Generate state (and nonce) + + %% ---- REDIRECT TO KEYCLOAK ---- + R-->>U: 302 → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE + U->>K: GET .../auth (Keycloak Login Page) + K->>U: Render login (username/password, MFA) + U->>K: Submit credentials + + %% ---- CALLBACK TO RBAC (CONFIDENTIAL CLIENT) ---- + K-->>U: 302 → https://api.sua-app.com/auth/callback?code=CODE&state=STATE + U->>N: GET /auth/callback?code=CODE&state=STATE + N->>R: Proxy /auth/callback + + %% ---- CODE → TOKENS (SERVER-SIDE) ---- + R->>K: POST /token (grant_type=authorization_code,
client_id=rbac-middleware, client_secret=***, code, redirect_uri) + K-->>R: 200 { access_token, refresh_token, id_token, expires_in } + + %% ---- CREATE SESSION + REDIRECT TO PORTAL ---- + R->>S: Save session { sub, roles, tokens, expiry } + R-->>U: Set-Cookie: sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard + U->>N: GET /dashboard + N->>P: Proxy /dashboard (serve SPA route) + P-->>N: dashboard assets + N-->>U: Portal (authenticated session established) - %% ---- LOGIN INIT ---- - U->>P: Open Portal (/) - P->>R: GET /auth/login?next=/dashboard - U->>N: TLS handshake with client cert - N-->>U: TLS established (cert validated by CA) - - R->>U: 302 Redirect → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE - U->>K: GET .../auth (Login Page) - - %% ---- USER AUTHENTICATES ---- - K->>U: Render Login Page - U->>K: Submit credentials (username/password + MFA) - - %% ---- CALLBACK ---- - K->>U: 302 Redirect → https://api.sua-app.com/auth/callback?code=CODE&state=STATE - U->>N: GET /auth/callback?code=CODE&state=STATE (mTLS again) - N->>R: Proxy request - - R->>K: POST /token
grant_type=authorization_code&client_id=rbac-middleware&client_secret=***&code=CODE&redirect_uri=https://api.sua-app.com/auth/callback - K-->>R: {access_token, refresh_token, id_token} - - R->>S: Save session {sub, roles, tokens, expiry} - R->>U: Set-Cookie sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard - - %% ---- API USE ---- - U->>P: Open /dashboard - P->>N: XHR /api/me (cookie: sid=SESSION_ID, mTLS) - N->>R: Proxy /api/me - R->>A: GET /me (Authorization: Bearer ) - A-->>R: 200 {profile} - R-->>P: 200 {profile} - - %% ---- REFRESH ---- - R->>K: POST /token (grant_type=refresh_token&client_id=rbac-middleware&client_secret=***&refresh_token=RT) - K-->>R: {new access_token, refresh_token} - R->>S: Update session - - %% ---- LOGOUT ---- - U->>P: Click Logout - P->>N: POST /auth/logout (mTLS) - N->>R: Proxy /auth/logout - R->>S: Destroy session - R->>U: Clear sid cookie - R->>K: (optional) end_session_endpoint - K-->>U: Redirect → https://app.sua-app.com/ - - -Authentication - -Step-by-Step Description (without PKCE) -Prerequisites - -PKI setup: Root CA → Intermediate CA → issue client certificates. - -User installs client cert in browser/device. - -NGINX configured with mTLS (ssl_verify_client on;). - -Keycloak client rbac-middleware created as confidential: - -Authorization Code Flow enabled - -Redirect URI: https://api.sua-app.com/auth/callback - -Post Logout Redirect URI: https://app.sua-app.com/* - -Authentication Flow - -User opens https://app.sua-app.com. - -Portal requests login at https://api.sua-app.com/auth/login?next=/dashboard. - -mTLS check: browser presents client cert, NGINX validates with CA → request allowed. - -RBAC generates a state, then responds with 302 redirect to Keycloak /auth with params: - -client_id=rbac-middleware - -response_type=code - -redirect_uri=https://api.sua-app.com/auth/callback - -scope=openid profile email - -state= - -Keycloak shows Login Page. - -User authenticates (password, MFA, etc.). - -Callback + Token Exchange - -Keycloak redirects to RBAC: https://api.sua-app.com/auth/callback?code=...&state=.... - -mTLS again: NGINX validates client cert, forwards to RBAC. - -RBAC validates state, then calls Keycloak /token with: - -grant_type=authorization_code -client_id=rbac-middleware -client_secret=SECRET -code=XYZ -redirect_uri=https://api.sua-app.com/auth/callback - - -Keycloak responds with tokens. - -RBAC saves {access_token, refresh_token, expiry} in session store (Redis). - -RBAC sets sid cookie (HttpOnly, Secure, SameSite) and redirects user to portal /dashboard. - -Using the Application - -Portal uses the session cookie (sid) in requests to RBAC APIs. - -RBAC checks session, enforces RBAC rules (roles, allowlists), and forwards calls downstream with Authorization: Bearer . - -Microservice responds, RBAC passes result back to portal. - -Token Refresh - -If access_token near expiry, RBAC uses refresh_token with Keycloak /token to get a new pair. - -RBAC updates the session transparently. - -Logout - -Portal calls POST /auth/logout. - -RBAC clears session + cookie, optionally calls Keycloak end_session_endpoint. - -User is redirected back to https://app.sua-app.com/ logged out. ✅ With this model: From be338ea8f9d06dcd0d12909c0dd73fb40892628a Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 10:31:28 +0200 Subject: [PATCH 48/93] Update test --- test | 52 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/test b/test index 572f031..f706f53 100644 --- a/test +++ b/test @@ -3,46 +3,68 @@ RBAC Application sequenceDiagram autonumber - participant U as User (Browser) - participant N as NGINX (Edge proxy) + participant CA as Certificate Authority (Root/Intermediate) + participant U as User (Browser with Client Cert) + participant N as NGINX (Edge mTLS Proxy) participant P as Portal SDL Frontend (app.sua-app.com) participant R as RBAC Middleware (api.sua-app.com) participant K as Keycloak (login.sua-idp.com) - participant S as Session Store (e.g., Redis) + participant S as Session Store (Redis) - %% ---- PORTAL LOAD VIA NGINX ---- + %% ---- ONE-TIME ENROLLMENT (PKI) ---- + U->>CA: Submit CSR (request client certificate) + CA-->>U: Issue client certificate (User.crt / .p12) + note over U,CA: User installs client cert+key in the browser/device + + %% ---- PORTAL LOAD (mTLS @ NGINX) ---- + U->>N: TLS handshake (client presents User.crt) + N-->>U: Verify cert chain (Root/Intermediate CA), CRL/OCSP, expiry → TLS established U->>N: GET https://app.sua-app.com/ N->>P: Proxy / (serve SPA) P-->>N: index.html, JS/CSS N-->>U: Portal assets - %% ---- LOGIN INITIATION (Portal calls RBAC via NGINX route) ---- - U->>N: GET /auth/login?next=/dashboard %% initiated by Portal (button/auto) + %% ---- LOGIN INITIATION (via NGINX → RBAC) ---- + U->>N: GET /auth/login?next=/dashboard (same origin) + N-->>U: Enforce mTLS again (same TLS session or re-handshake per config) N->>R: Proxy /auth/login - note right of R: Generate state (and nonce) + note right of R: Generate state (and nonce if validating ID Token) - %% ---- REDIRECT TO KEYCLOAK ---- + %% ---- REDIRECT TO KEYCLOAK (INTERACTIVE LOGIN) ---- R-->>U: 302 → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE U->>K: GET .../auth (Keycloak Login Page) - K->>U: Render login (username/password, MFA) + K->>U: Render login (username/password, MFA/WebAuthn) U->>K: Submit credentials %% ---- CALLBACK TO RBAC (CONFIDENTIAL CLIENT) ---- K-->>U: 302 → https://api.sua-app.com/auth/callback?code=CODE&state=STATE U->>N: GET /auth/callback?code=CODE&state=STATE + N-->>U: Verify client cert (mTLS) → allow N->>R: Proxy /auth/callback - %% ---- CODE → TOKENS (SERVER-SIDE) ---- + %% ---- SERVER-SIDE CODE → TOKENS ---- R->>K: POST /token (grant_type=authorization_code,
client_id=rbac-middleware, client_secret=***, code, redirect_uri) K-->>R: 200 { access_token, refresh_token, id_token, expires_in } - - %% ---- CREATE SESSION + REDIRECT TO PORTAL ---- - R->>S: Save session { sub, roles, tokens, expiry } + R->>S: Save session { sub, tokens, expiry } R-->>U: Set-Cookie: sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard + + %% ---- FINAL REDIRECT TO PORTAL (AUTH ESTABLISHED) ---- U->>N: GET /dashboard - N->>P: Proxy /dashboard (serve SPA route) + N->>P: Proxy /dashboard (SPA route) P-->>N: dashboard assets - N-->>U: Portal (authenticated session established) + N-->>U: Portal (authenticated session via cookie) + + + +CA/PKI: issue user/browser client certs; publish CA chain (Root+Intermediate) to NGINX. + +NGINX: ssl_verify_client on; ssl_client_certificate ; (enable OCSP/CRL as needed). + +Keycloak: single confidential client rbac-middleware with redirect https://api.sua-app.com/auth/callback. + +RBAC: handles /auth/login → redirect to KC; /auth/callback → /token exchange; sets sid HttpOnly cookie; redirects to /dashboard. + +Portal: served behind NGINX; browser only ever sends the client cert (mTLS) and receives the session cookie (no JWT exposure). ✅ With this model: From 7a950bca201511ebc676e417795543767241bdda Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 10:55:20 +0200 Subject: [PATCH 49/93] Update test --- test | 90 +++++++++++++++++++++++++++++++++++------------------------- 1 file changed, 52 insertions(+), 38 deletions(-) diff --git a/test b/test index f706f53..49d66b5 100644 --- a/test +++ b/test @@ -1,70 +1,84 @@ RBAC Application - sequenceDiagram autonumber participant CA as Certificate Authority (Root/Intermediate) participant U as User (Browser with Client Cert) participant N as NGINX (Edge mTLS Proxy) + participant O as oauth2-proxy (OIDC Client) + participant K as Keycloak (login.sua-idp.com) participant P as Portal SDL Frontend (app.sua-app.com) participant R as RBAC Middleware (api.sua-app.com) - participant K as Keycloak (login.sua-idp.com) - participant S as Session Store (Redis) %% ---- ONE-TIME ENROLLMENT (PKI) ---- U->>CA: Submit CSR (request client certificate) - CA-->>U: Issue client certificate (User.crt / .p12) + CA-->>U: Issue client certificate (User.crt/.p12) note over U,CA: User installs client cert+key in the browser/device - %% ---- PORTAL LOAD (mTLS @ NGINX) ---- + %% ---- FIRST REQUEST (mTLS @ NGINX) ---- U->>N: TLS handshake (client presents User.crt) - N-->>U: Verify cert chain (Root/Intermediate CA), CRL/OCSP, expiry → TLS established + N-->>U: Verify chain (Root/Intermediate), CRL/OCSP, expiry → TLS established U->>N: GET https://app.sua-app.com/ - N->>P: Proxy / (serve SPA) + N->>O: subrequest: GET /oauth2/auth (auth_request) + O-->>N: 401 (no session cookie yet) + N-->>U: 302 → /oauth2/start (kick off OIDC) + + %% ---- REDIRECT TO KEYCLOAK ---- + U->>N: GET /oauth2/start + N->>O: Proxy /oauth2/start + O-->>U: 302 → K /realms//protocol/openid-connect/auth?client_id=...&response_type=code&redirect_uri=https://app.sua-app.com/oauth2/callback&scope=openid%20email%20profile&state=...&nonce=... + U->>K: GET .../auth (Keycloak Login Page) + K->>U: Render login (user/password, MFA/WebAuthn) + U->>K: Submit credentials + + %% ---- OIDC CALLBACK ---- + K-->>U: 302 → https://app.sua-app.com/oauth2/callback?code=CODE&state=STATE + U->>N: GET /oauth2/callback (still under mTLS) + N->>O: Proxy /oauth2/callback + + %% ---- TOKEN EXCHANGE (INSIDE OAUTH2-PROXY) ---- + O->>K: POST /token (authorization_code, client_id, client_secret, code, redirect_uri) + K-->>O: 200 {access_token, id_token, refresh_token, expires_in} + O-->>U: Set-Cookie: _oauth2_proxy=SESSION (HttpOnly, Secure, SameSite) + 302 → original URL + + %% ---- AUTHORIZED CONTENT ---- + U->>N: GET https://app.sua-app.com/ (with _oauth2_proxy cookie) + N->>O: subrequest /oauth2/auth (validate session) + O-->>N: 200 + headers (X-Auth-Request-User/Email/Groups) + N->>P: Proxy / (serve SPA) P-->>N: index.html, JS/CSS - N-->>U: Portal assets + N-->>U: Portal assets (authenticated) - %% ---- LOGIN INITIATION (via NGINX → RBAC) ---- - U->>N: GET /auth/login?next=/dashboard (same origin) - N-->>U: Enforce mTLS again (same TLS session or re-handshake per config) - N->>R: Proxy /auth/login - note right of R: Generate state (and nonce if validating ID Token) + %% ---- OPTIONAL BACKENDS ---- + U->>N: XHR /api/... (cookie present) + N->>O: /oauth2/auth (still OK) + O-->>N: 200 + identity headers + N->>R: Proxy /api/... (pass identity headers) + R-->>N: 200 + N-->>U: 200 - %% ---- REDIRECT TO KEYCLOAK (INTERACTIVE LOGIN) ---- - R-->>U: 302 → K /realms//protocol/openid-connect/auth
client_id=rbac-middleware&response_type=code&redirect_uri=https://api.sua-app.com/auth/callback&scope=openid profile email&state=STATE - U->>K: GET .../auth (Keycloak Login Page) - K->>U: Render login (username/password, MFA/WebAuthn) - U->>K: Submit credentials - %% ---- CALLBACK TO RBAC (CONFIDENTIAL CLIENT) ---- - K-->>U: 302 → https://api.sua-app.com/auth/callback?code=CODE&state=STATE - U->>N: GET /auth/callback?code=CODE&state=STATE - N-->>U: Verify client cert (mTLS) → allow - N->>R: Proxy /auth/callback +NGINX: + +Enforces mTLS (client certificate required). - %% ---- SERVER-SIDE CODE → TOKENS ---- - R->>K: POST /token (grant_type=authorization_code,
client_id=rbac-middleware, client_secret=***, code, redirect_uri) - K-->>R: 200 { access_token, refresh_token, id_token, expires_in } - R->>S: Save session { sub, tokens, expiry } - R-->>U: Set-Cookie: sid=SESSION_ID (HttpOnly, Secure, SameSite) + 302 → https://app.sua-app.com/dashboard +Uses auth_request to ask oauth2-proxy if the user is authenticated. - %% ---- FINAL REDIRECT TO PORTAL (AUTH ESTABLISHED) ---- - U->>N: GET /dashboard - N->>P: Proxy /dashboard (SPA route) - P-->>N: dashboard assets - N-->>U: Portal (authenticated session via cookie) +Serves Portal and proxies APIs only when oauth2-proxy says “OK”. +oauth2-proxy: +Acts as the OIDC client to Keycloak. -CA/PKI: issue user/browser client certs; publish CA chain (Root+Intermediate) to NGINX. +Builds the /authorize URL (with state/nonce), handles /callback, exchanges code→tokens. -NGINX: ssl_verify_client on; ssl_client_certificate ; (enable OCSP/CRL as needed). +Sets a secure session cookie (e.g. _oauth2_proxy) and injects identity headers on success. -Keycloak: single confidential client rbac-middleware with redirect https://api.sua-app.com/auth/callback. +Keeps tokens server-side (not exposed to the browser). -RBAC: handles /auth/login → redirect to KC; /auth/callback → /token exchange; sets sid HttpOnly cookie; redirects to /dashboard. +Keycloak: IdP (login page, MFA, token endpoint). -Portal: served behind NGINX; browser only ever sends the client cert (mTLS) and receives the session cookie (no JWT exposure). +Portal / RBAC: receive requests only after oauth2-proxy has authenticated the session; they can consume identity headers. ✅ With this model: From a34d3914c77658b4aaf372f77439f6ab90565cbd Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 09:18:42 +0000 Subject: [PATCH 50/93] Atualizar o test --- test | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test b/test index 49d66b5..a9e6d42 100644 --- a/test +++ b/test @@ -1,5 +1,14 @@ RBAC Application + + +- OAUTH2_PROXY_CLIENT_ID=your-client-id +- OAUTH2_PROXY_CLIENT_SECRET=your-client-secret +- OAUTH2_PROXY_PROVIDER=oidc +- OAUTH2_PROXY_OIDC_ISSUER_URL=https://login.your-keycloak.com/realms/your-realm + + + sequenceDiagram autonumber participant CA as Certificate Authority (Root/Intermediate) From 56faeebb525a8adea104a79de7f99c31c5cedbbd Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 11:23:10 +0200 Subject: [PATCH 51/93] Update test --- test | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/test b/test index a9e6d42..eaff358 100644 --- a/test +++ b/test @@ -1,6 +1,54 @@ RBAC Application +sequenceDiagram + autonumber + participant U as User (Browser) + participant N as NGINX (Edge mTLS Proxy) + participant O as oauth2-proxy (OIDC Client) + participant K as Keycloak (login.sua-idp.com) + participant P as Portal SDL Frontend (app.sua-app.com) + + %% ---- USER CLICKS LOGOUT IN THE PORTAL ---- + U->>N: POST /logout (or /oauth2/sign_out) + note over N: mTLS enforced: client cert is verified + alt App-driven logout route (/logout) + N->>O: Proxy /oauth2/sign_out + else Direct call to oauth2-proxy + N->>O: Proxy /oauth2/sign_out + end + + %% ---- CLEAR LOCAL SESSION (oauth2-proxy) ---- + O-->>U: Set-Cookie: _oauth2_proxy=; Expires=past; HttpOnly; Secure; SameSite + note right of O: Local session invalidated (no tokens exposed to browser) + + %% ---- OPTIONAL: SSO LOGOUT AT KEYCLOAK (RP-INITIATED) ---- + alt SSO logout enabled + O-->>U: 302 → K /protocol/openid-connect/logout
?post_logout_redirect_uri=https://app.sua-app.com/logged-out + U->>N: GET /protocol/openid-connect/logout?... (to Keycloak) + N->>K: Proxy logout to Keycloak + K-->>U: 302 → https://app.sua-app.com/logged-out + U->>N: GET /logged-out + N->>P: Proxy /logged-out (public page) + P-->>N: logged-out view + N-->>U: Render "logged out" + else Local logout only + O-->>U: 302 → https://app.sua-app.com/logged-out (or 204) + U->>N: GET /logged-out + N->>P: Proxy /logged-out + P-->>N: logged-out view + N-->>U: Render "logged out" + end + + %% ---- EDGE CASES ---- + rect rgba(255,240,220,0.5) + note over O: If session already missing/expired → still clear cookie and continue. + note over K: Without SSO logout, Keycloak session may remain active.
Next visit may auto-login unless the IdP session times out or is cleared. + end + + + + - OAUTH2_PROXY_CLIENT_ID=your-client-id - OAUTH2_PROXY_CLIENT_SECRET=your-client-secret From 328ebfa6ef91a311711e28ac637fa404c39c9711 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 11:47:03 +0200 Subject: [PATCH 52/93] Update test --- test | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/test b/test index eaff358..2adbd7c 100644 --- a/test +++ b/test @@ -1,6 +1,85 @@ RBAC Application + +#RBAC MIddleware Drive automatic page redirect without OAuth2_proxy client + +sequenceDiagram + autonumber + participant CA as Certificate Authority (Root/Intermediate) + participant U as User (Browser w/ Client Cert) + participant N as NGINX (Edge mTLS Proxy) + participant P as Portal SDL Frontend (app.sua-app.com) + participant R as RBAC Middleware (api.sua-app.com) + participant K as Keycloak (login.sua-idp.com) + participant S as Session Store (Redis) + + %% ---------------- ONE-TIME ENROLLMENT (PKI) ---------------- + U->>CA: Submit CSR (generate keypair locally, send CSR) + CA-->>U: Issue client certificate (User.crt / .p12) + note over U,CA: User installs cert+key in the browser/OS keychain + + %% ---------------- PORTAL ENTRY (mTLS @ EDGE) ---------------- + U->>N: TLS handshake + present client cert + N-->>U: TLS established if cert valid (verify chain+CRL/OCSP) + note over U,N: mTLS gate passed → request forwarded to Portal SDL + + U->>P: GET / (initial page load, static assets via NGINX) + P-->>U: 200 HTML/JS (Portal bootstraps & calls RBAC to check session) + + %% ---------------- AUTH GUARD (RBAC REDIRECT TO KEYCLOAK) ---------------- + U->>R: GET /session/check (no cookie or invalid) + R-->>U: 302 Redirect → K /realms/{realm}/protocol/openid-connect/auth
?client_id=portal-sdl&response_type=code&scope=openid%20profile%20email&redirect_uri=https%3A%2F%2Fapp.sua-app.com%2Foidc%2Fcallback&state=origURL&code_challenge=...&code_challenge_method=S256 + + %% ---------------- KEYCLOAK LOGIN ---------------- + U->>K: GET /auth (OIDC authorize) + K-->>U: Login page (username/password, MFA, etc.) + U->>K: Submit credentials (and MFA if any) + K-->>U: 302 → https://app.sua-app.com/oidc/callback?code=...&state=origURL + + %% ---------------- CALLBACK + TOKEN EXCHANGE ---------------- + U->>N: GET /oidc/callback?code=...&state=... + N->>R: Proxy /oidc/callback (preserve headers) + R->>K: POST /token (code → tokens, using client_secret if confidential) + K-->>R: 200 { access_token, refresh_token, id_token, expires_in } + + %% ---------------- SESSION CREATION ---------------- + R->>S: SET session:{sid} = { sub, roles, tokens, expiry } + S-->>R: OK + R-->>U: Set-Cookie: rbac_session=SID; HttpOnly; Secure; SameSite=Lax + R-->>U: 302 → state.origURL (return to originally requested page) + + %% ---------------- AUTHENTICATED USE (SUBSEQUENT CALLS) ---------------- + U->>P: GET / (now with rbac_session cookie) + P-->>U: 200 (app shell) + U->>R: GET /api/transfer (cookie: rbac_session=SID) + R->>S: GET session:{sid} + S-->>R: { sub, roles, tokens (or cached claims) } + R->>R: Validate session & RBAC (roles/claims/tenant) + R-->>U: 200 OK (or 403 if not authorized) + + %% ---------------- TOKEN REFRESH (WHEN NEEDED) ---------------- + R->>K: POST /token (grant_type=refresh_token) + K-->>R: 200 { new access_token, refresh_token } + R->>S: UPDATE session:{sid} tokens/expiry + S-->>R: OK + + +mTLS is enforced only at NGINX (edge). User auth still uses OIDC via Keycloak. + +The Portal never handles tokens directly; RBAC does the code exchange, stores tokens/claims in Redis, and sets a Secure+HttpOnly session cookie. + +Use PKCE if the RBAC callback ever runs in a public context; otherwise make the Keycloak client confidential with a client secret. + +Add allowlists to avoid loops: /oidc/callback, /health, static assets, etc. + + + + + + +#Logout + sequenceDiagram autonumber participant U as User (Browser) From 6c7fe7b32799d0e5d80c7e99743833cb144b8866 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 12:12:00 +0200 Subject: [PATCH 53/93] Update test --- test | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 2 deletions(-) diff --git a/test b/test index 2adbd7c..8015cee 100644 --- a/test +++ b/test @@ -127,6 +127,72 @@ sequenceDiagram +#RBAC with oatuh2_proxy_client authorization + +sequenceDiagram + autonumber + participant U as User (Browser) + participant N as NGINX (mTLS + auth_request) + participant O as oauth2-proxy (OIDC session) + participant R as RBAC Middleware (api.sua-app.com) + participant DB as RBAC Policy DB (roles/allowlists/limits) + participant S as Signer/Relayer (KMS) + participant CH as Chain RPC (node) + + %% ---- PRECONDITION: user is already logged in ---- + note over U,O: Browser holds _oauth2_proxy session cookie (HttpOnly, Secure) + + %% ---- TRANSFER REQUEST FROM THE PORTAL ---- + U->>N: POST /api/transfer (credentials: include; CSRF header) + note over N: mTLS: verify client cert (optional but recommended) + + %% ---- AUTHN CHECK AT THE EDGE ---- + N->>O: subrequest /oauth2/auth (validate session cookie) + O-->>N: 200 OK + X-Auth-Request-User/Email/Groups + note over N: If 401 → 302 to /oauth2/start (not shown) + + %% ---- FORWARD TO RBAC WITH IDENTITY CONTEXT ---- + N->>R: Proxy /api/transfer
X-Auth-Request-User, X-Auth-Request-Email, X-SSL-Client-Verify/CN, CSRF token + + %% ---- RBAC AUTHORIZATION ---- + R->>R: Validate CSRF, content-type, schema (amount, from, to, contract) + R->>DB: Fetch user→tenant mapping, roles, wallet/contract allowlists, tx limits + DB-->>R: {roles:["writer"], wallets:["0xFrom..."], contracts:["0xToken..."], limits:{daily:..., perTx:...}} + R->>R: Enforce policy: role=writer? fromWallet allowed? contract allowed? amounts/limits OK? + alt Authorized + %% ---- PREP + SUBMIT TRANSACTION ---- + R->>S: Build tx (e.g., ERC20 transfer), EIP-1559 params, optional EIP-712; request signature + S->>CH: Send signed tx to chain RPC + CH-->>S: txHash / receipt (pending or mined) + S-->>R: {txHash, status:pended} + R-->>N: 200 { txHash, status:"submitted" } + N-->>U: 200 { txHash, status:"submitted" } + else Denied + R-->>N: 403 { error:"not_authorized", reason:"wallet/contract/role/limit" } + N-->>U: 403 { error, reason } + end + +Browser → NGINX: POST /api/transfer with the session cookie (from oauth2-proxy) and a CSRF header from your SPA. + +NGINX → oauth2-proxy: auth_request validates the cookie. If valid, oauth2-proxy returns 200 and injects identity headers (e.g., X-Auth-Request-User, X-Auth-Request-Email, X-Auth-Request-Groups). + +NGINX → RBAC: forwards the call, passing the identity headers (and, if you enforce device binding, X-SSL-Client-Verify/X-SSL-Client-CN). + +RBAC: + +Validates CSRF and the payload (from, to, amount, contractAddress). + +Loads roles & allowlists from its Policy DB (e.g., writer role; fromWallet allowed; contract allowed; per-tx/daily limits). + +If authorized, RBAC prepares the transaction (ERC-20 transfer or equivalent), optionally as EIP-712 typed data, requests a signature from the Signer/Relayer (KMS), and submits to the Chain RPC. Returns { txHash, status:"submitted" }. + +If denied, returns 403 with the reason (role/wallet/contract/limit). + + + + + +#RBAC with oatuh2_proxy_client authentication - OAUTH2_PROXY_CLIENT_ID=your-client-id @@ -134,8 +200,6 @@ sequenceDiagram - OAUTH2_PROXY_PROVIDER=oidc - OAUTH2_PROXY_OIDC_ISSUER_URL=https://login.your-keycloak.com/realms/your-realm - - sequenceDiagram autonumber participant CA as Certificate Authority (Root/Intermediate) From eaa362899a5194c5bf660480e16d0298dd11c0c7 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 12:42:30 +0000 Subject: [PATCH 54/93] Atualizar o test --- test | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/test b/test index 8015cee..5a8450e 100644 --- a/test +++ b/test @@ -2,6 +2,86 @@ RBAC Application +sequenceDiagram + autonumber + participant U as User Browser + participant CA as Certificate Authority (Root/Intermediate) + participant I as NGINX/Ingress (mTLS Gate + auth_request) + participant R as RBAC Middleware (OIDC Client + Session + API) + participant K as Keycloak (IdP) + participant F as SDL Frontend (Dashboard) + participant B as SDL Backend + + %% 0) One-time PKI enrollment + U->>CA: CSR (generate keypair locally) + CA-->>U: Client cert (.crt/.p12) + note over U,CA: User installs cert+key in browser/OS + + %% 1) mTLS at edge + U->>I: TLS handshake (client cert) + I->>I: Verify against CA (CRL/OCSP) + alt mTLS OK + I-->>U: TLS established + else mTLS fail + I-->>U: 400/401 mTLS required + return + end + + %% 2) Guard dashboard with RBAC session + U->>I: GET /app + I->>R: auth_request /rbac/session/verify + alt No session + R-->>I: 401 + I-->>U: 302 → R:/login?rd=/app + else Session OK + R-->>I: 200 + optional identity headers + I->>F: GET /app + F-->>U: 200 Dashboard + end + + %% 3) RBAC performs OIDC (Auth Code) with Keycloak + U->>R: GET /login?rd=/app + R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback + U->>K: Keycloak login (creds/MFA) + K-->>U: 302 → R:/callback?code=AUTH_CODE + U->>R: GET /callback?code=AUTH_CODE + R->>K: POST /token (code → tokens) + K-->>R: {access_token, id_token, refresh_token} + R->>R: Create server-side session (store tokens/claims) + R-->>U: Set rbac_session cookie + 302 /app + + %% 4) Authenticated dashboard load (after login) + U->>I: GET /app (with rbac_session) + I->>R: auth_request /rbac/session/verify + R-->>I: 200 OK (may include X-Client-Cert-Subject) + I->>F: GET /app + F-->>U: 200 Dashboard + + %% 5) User triggers a business action via Backend + U->>I: POST /backend/transfer (XHR) + I->>R: auth_request /rbac/session/verify + R-->>I: 200 OK + I->>B: POST /transfer (forward) + + %% 6) SDL Backend calls RBAC API endpoint (same RBAC) + B->>R: POST /api/transfer (cookie: rbac_session) + R->>R: Resolve session → user/tenant/roles + R->>R: Authorize policy (claims, role, scope, mTLS subject if required) + alt Authorized + R->>R: Execute business logic (transfer) %% RBAC == API + R-->>B: 200 OK (result) + B-->>U: 200 OK (JSON) + else Forbidden + R-->>B: 403 Forbidden + B-->>U: 403 Forbidden + end + + %% 7) Silent refresh handled by RBAC + R->>K: POST /token (refresh_token when needed) + K-->>R: new access_token + R->>R: Update session store + + #RBAC MIddleware Drive automatic page redirect without OAuth2_proxy client sequenceDiagram From 5a79f15c82cc96e3f86718ae9ba987ea136011cb Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 12:51:24 +0000 Subject: [PATCH 55/93] Atualizar o test --- test | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/test b/test index 5a8450e..363d674 100644 --- a/test +++ b/test @@ -1,7 +1,87 @@ RBAC Application +sequenceDiagram + autonumber + participant U as User Browser + participant CA as Certificate Authority (Root/Intermediate) + participant I as NGINX/Ingress (mTLS Gate + auth_request) + participant R as RBAC Middleware (OIDC Client + Session + API) + participant K as Keycloak (IdP) + participant F as SDL Frontend (Dashboard) + participant B as SDL Backend + + %% 0) One-time PKI enrollment + U->>CA: CSR (generate keypair locally) + CA-->>U: Client cert (.crt/.p12) + note over U,CA: User installs cert+key in browser/OS + + %% 1) mTLS at edge + U->>I: TLS handshake (client cert) + I->>I: Verify against CA (CRL/OCSP) + alt mTLS OK + I-->>U: TLS established + else mTLS fail + I-->>U: 400/401 mTLS required + end + + %% 2) Guard dashboard with RBAC session + U->>I: GET /app + I->>R: auth_request /rbac/session/verify + alt No session + R-->>I: 401 + I-->>U: 302 → R:/login?rd=/app + else Session OK + R-->>I: 200 + optional identity headers + I->>F: GET /app + F-->>U: 200 Dashboard + end + + %% 3) RBAC performs OIDC (Auth Code) with Keycloak + U->>R: GET /login?rd=/app + R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback + U->>K: Keycloak login (creds/MFA) + K-->>U: 302 → R:/callback?code=AUTH_CODE + U->>R: GET /callback?code=AUTH_CODE + R->>K: POST /token (code → tokens) + K-->>R: {access_token, id_token, refresh_token} + R->>R: Create server-side session (store tokens/claims) + R-->>U: Set rbac_session cookie + 302 /app + + %% 4) Authenticated dashboard load (after login) + U->>I: GET /app (with rbac_session) + I->>R: auth_request /rbac/session/verify + R-->>I: 200 OK (may include X-Client-Cert-Subject) + I->>F: GET /app + F-->>U: 200 Dashboard + + %% 5) User triggers a business action via Backend + U->>I: POST /backend/transfer (XHR) + I->>R: auth_request /rbac/session/verify + R-->>I: 200 OK + I->>B: POST /transfer (forward) + + %% 6) SDL Backend calls RBAC API endpoint (same RBAC) + B->>R: POST /api/transfer (cookie: rbac_session) + R->>R: Resolve session → user/tenant/roles + R->>R: Authorize policy (claims, role, scope, mTLS subject if required) + alt Authorized + R->>R: Execute business logic (transfer) %% RBAC == API + R-->>B: 200 OK (result) + B-->>U: 200 OK (JSON) + else Forbidden + R-->>B: 403 Forbidden + B-->>U: 403 Forbidden + end + + %% 7) Silent refresh handled by RBAC + R->>K: POST /token (refresh_token when needed) + K-->>R: new access_token + R->>R: Update session store + + +#fail sequenceDiagram autonumber participant U as User Browser From 3a1698ac0f787ac24e36254ba340a1081f4b20ce Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 14:17:11 +0000 Subject: [PATCH 56/93] Atualizar o test --- test | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/test b/test index 363d674..5bf833b 100644 --- a/test +++ b/test @@ -1,6 +1,53 @@ RBAC Application +option JWT request + +sequenceDiagram + autonumber + participant U as Browser (SPA) + participant B as SDL Backend (BFF + Session Store) + participant R as RBAC Middleware (OIDC Client + API) + participant K as Keycloak (IdP) + + %% 1) Login pelo Backend (delegado ao RBAC) + U->>B: POST /login (usuário envia user/pass via HTTPS) + B->>R: POST /login (proxy para RBAC) + R->>K: /authorize + /token + K-->>R: {access_token, refresh_token} + R-->>B: {access_token, refresh_token} + B->>B: Armazena {tokens, claims} no Session Store + B-->>U: 200 { session_id: "abc123" } + note over U,B: Browser nunca recebe JWT, só session_id + + %% 2) Request normal + U->>B: POST /transfer (header: X-Session-Id: abc123) + B->>B: Resolve session_id → tokens + B->>R: POST /api/transfer + Authorization: Bearer + R->>R: Valida token, aplica RBAC + alt autorizado + R-->>B: 200 {result} + B-->>U: 200 {result} + else proibido + R-->>B: 403 Forbidden + B-->>U: 403 Forbidden + end + + %% 3) Refresh (invisível para Browser) + B->>R: usa refresh_token antes do expirar + R->>K: /token (refresh) + K-->>R: {new access_token} + R-->>B: {new access_token} + B->>B: Atualiza session store + + + + + + + +======== sequenceDiagram autonumber participant U as User Browser From 7845f6a23882b818fdf66d809461c2ed1a05339c Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 14:37:09 +0000 Subject: [PATCH 57/93] Atualizar o test --- test | 86 ++++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 64 insertions(+), 22 deletions(-) diff --git a/test b/test index 5bf833b..b2f2ad7 100644 --- a/test +++ b/test @@ -5,42 +5,84 @@ option JWT request sequenceDiagram autonumber - participant U as Browser (SPA) + participant CA as Certificate Authority + participant U as User Browser (Client Cert) + participant I as Ingress/NGINX (mTLS Gate + auth_request) + participant F as SDL Frontend (Dashboard) participant B as SDL Backend (BFF + Session Store) participant R as RBAC Middleware (OIDC Client + API) participant K as Keycloak (IdP) - %% 1) Login pelo Backend (delegado ao RBAC) - U->>B: POST /login (usuário envia user/pass via HTTPS) - B->>R: POST /login (proxy para RBAC) - R->>K: /authorize + /token - K-->>R: {access_token, refresh_token} - R-->>B: {access_token, refresh_token} - B->>B: Armazena {tokens, claims} no Session Store + %% 0) One-time PKI + U->>CA: CSR (generate keypair locally) + CA-->>U: client.crt / client.p12 + note over U,CA: Browser installs the client certificate for mTLS + + %% 1) mTLS Handshake + U->>I: TLS handshake (presents client cert) + I->>I: Verify certificate against CA (CRL/OCSP) + alt mTLS OK + I-->>U: TLS established + else Failed + I-->>U: 401 mTLS required + return + end + + %% 2) Initial access to Dashboard + U->>I: GET /app + I->>F: Proxy /app (but protected by backend auth) + F-->>U: HTML/JS (SPA loads but still needs authentication) + + %% 3) SPA calls Backend for login + U->>I: POST /backend/login + I->>B: Proxy /login + + %% 4) Backend delegates login to RBAC + B->>R: /login?rd=/app + R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback + + %% 5) Browser interacts with Keycloak + U->>K: Login (user enters credentials/MFA) + K-->>U: 302 → R:/callback?code=AUTH_CODE + U->>R: GET /callback?code=AUTH_CODE + + %% 6) RBAC exchanges AUTH_CODE for tokens with Keycloak + R->>K: POST /token (grant_type=authorization_code, code=AUTH_CODE) + K-->>R: {access_token (JWT), id_token, refresh_token} + R->>B: {access_token, refresh_token, claims} %% returns to Backend + + %% 7) SDL Backend creates internal session + B->>B: Create session_id=abc123 → {tokens, claims} in Redis B-->>U: 200 { session_id: "abc123" } - note over U,B: Browser nunca recebe JWT, só session_id + note over U,B: Browser never sees the JWT, only a session_id - %% 2) Request normal - U->>B: POST /transfer (header: X-Session-Id: abc123) - B->>B: Resolve session_id → tokens + %% 8) User accesses the Dashboard + U->>I: GET /app (SPA runs authenticated) + I->>F: GET /app + F-->>U: Dashboard (JS calls Backend APIs) + + %% 9) Business request (e.g. transfer) + U->>I: POST /backend/transfer + X-Session-Id: abc123 + I->>B: /transfer + B->>B: Resolve session_id=abc123 → {access_token} B->>R: POST /api/transfer Authorization: Bearer - R->>R: Valida token, aplica RBAC - alt autorizado + R->>R: Validate JWT (Keycloak JWKS), apply RBAC policies + alt Authorized R-->>B: 200 {result} B-->>U: 200 {result} - else proibido + else Denied R-->>B: 403 Forbidden B-->>U: 403 Forbidden end - %% 3) Refresh (invisível para Browser) - B->>R: usa refresh_token antes do expirar - R->>K: /token (refresh) - K-->>R: {new access_token} - R-->>B: {new access_token} - B->>B: Atualiza session store - + %% 10) Token refresh (invisible to Browser) + B->>R: POST /token (refresh_token) + R->>K: /token (grant_type=refresh_token) + K-->>R: {new_access_token} + R-->>B: {new_access_token} + B->>B: Update session abc123 From 0eb3018e0e681cb95e5bf2288f3e88fd57db7e48 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 14:42:29 +0000 Subject: [PATCH 58/93] Atualizar o test --- test | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/test b/test index b2f2ad7..80b6a68 100644 --- a/test +++ b/test @@ -25,13 +25,12 @@ sequenceDiagram I-->>U: TLS established else Failed I-->>U: 401 mTLS required - return end %% 2) Initial access to Dashboard U->>I: GET /app - I->>F: Proxy /app (but protected by backend auth) - F-->>U: HTML/JS (SPA loads but still needs authentication) + I->>F: Proxy /app (protected) + F-->>U: HTML/JS (SPA loads but needs auth) %% 3) SPA calls Backend for login U->>I: POST /backend/login @@ -42,33 +41,33 @@ sequenceDiagram R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback %% 5) Browser interacts with Keycloak - U->>K: Login (user enters credentials/MFA) + U->>K: Login (credentials/MFA) K-->>U: 302 → R:/callback?code=AUTH_CODE U->>R: GET /callback?code=AUTH_CODE %% 6) RBAC exchanges AUTH_CODE for tokens with Keycloak - R->>K: POST /token (grant_type=authorization_code, code=AUTH_CODE) + R->>K: POST /token (authorization_code) K-->>R: {access_token (JWT), id_token, refresh_token} - R->>B: {access_token, refresh_token, claims} %% returns to Backend + R->>B: {access_token, refresh_token, claims} %% 7) SDL Backend creates internal session - B->>B: Create session_id=abc123 → {tokens, claims} in Redis + B->>B: Create session_id=abc123 → {tokens, claims} (Redis) B-->>U: 200 { session_id: "abc123" } note over U,B: Browser never sees the JWT, only a session_id %% 8) User accesses the Dashboard - U->>I: GET /app (SPA runs authenticated) + U->>I: GET /app (now authenticated) I->>F: GET /app - F-->>U: Dashboard (JS calls Backend APIs) + F-->>U: Dashboard - %% 9) Business request (e.g. transfer) + %% 9) Business request (e.g., transfer) U->>I: POST /backend/transfer X-Session-Id: abc123 I->>B: /transfer - B->>B: Resolve session_id=abc123 → {access_token} + B->>B: Resolve session_id → {access_token} B->>R: POST /api/transfer Authorization: Bearer - R->>R: Validate JWT (Keycloak JWKS), apply RBAC policies + R->>R: Validate JWT (Keycloak JWKS) & apply RBAC alt Authorized R-->>B: 200 {result} B-->>U: 200 {result} @@ -77,15 +76,24 @@ sequenceDiagram B-->>U: 403 Forbidden end - %% 10) Token refresh (invisible to Browser) + %% 10) Token refresh (server-side) B->>R: POST /token (refresh_token) - R->>K: /token (grant_type=refresh_token) + R->>K: /token (refresh_token) K-->>R: {new_access_token} R-->>B: {new_access_token} B->>B: Update session abc123 +Highlights + • CA + mTLS → ensures device identity before login. + • RBAC Middleware is the only OIDC Client talking to Keycloak. + • SDL Backend never talks to Keycloak — it only delegates to RBAC. + • Browser never gets the JWT, it only receives a session_id. + • Backend injects the JWT when calling RBAC (Authorization: Bearer ). + • RBAC Middleware validates the JWT and applies RBAC policies. + + From 575ac9ea7f027965265d5c550884154d4e3e595c Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 14:47:13 +0000 Subject: [PATCH 59/93] Atualizar o test --- test | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/test b/test index 80b6a68..2a473e8 100644 --- a/test +++ b/test @@ -61,12 +61,10 @@ sequenceDiagram F-->>U: Dashboard %% 9) Business request (e.g., transfer) - U->>I: POST /backend/transfer - X-Session-Id: abc123 + U->>I: POST /backend/transfer\nX-Session-Id: abc123 I->>B: /transfer B->>B: Resolve session_id → {access_token} - B->>R: POST /api/transfer - Authorization: Bearer + B->>R: POST /api/transfer\nAuthorization: Bearer R->>R: Validate JWT (Keycloak JWKS) & apply RBAC alt Authorized R-->>B: 200 {result} @@ -84,7 +82,6 @@ sequenceDiagram B->>B: Update session abc123 - Highlights • CA + mTLS → ensures device identity before login. • RBAC Middleware is the only OIDC Client talking to Keycloak. From 401ea2bd1cae8d04f5cd2bb4825779b18f232ebf Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 15:49:38 +0000 Subject: [PATCH 60/93] Atualizar o test --- test | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/test b/test index 2a473e8..c469e41 100644 --- a/test +++ b/test @@ -1,4 +1,27 @@ +Database segregation by Role + Row-Level Security (RLS) + +Roles + • Admin — Read/write any data in SDL; can also register a new participant (organization). + • Operator (participants/banks) — Read/write data belonging to your own organization in SDL. + • Auditor — Read-only access to data belonging to your own organization in SDL. + +Onboarding (new organization) + • Organization name + • BIC (tenant_id) + • Email + • Temporary password + • Role (auditor/operator) + • Whitelist (wallet address / allow list) + +Database schema (top-level entities) + • Organization + • User + • Permission (Allowlist) + • Transaction + + + RBAC Application option JWT request From f478c30e1552a77cb42537bb0641cede927fd4b8 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 15:52:46 +0000 Subject: [PATCH 61/93] Atualizar o test --- test | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 1 deletion(-) diff --git a/test b/test index c469e41..7e8446c 100644 --- a/test +++ b/test @@ -1,4 +1,5 @@ + Database segregation by Role + Row-Level Security (RLS) Roles @@ -20,7 +21,95 @@ Database schema (top-level entities) • Permission (Allowlist) • Transaction - +How RBAC + RLS work together (short intro) + +The RBAC Middleware authenticates the caller (OIDC, mTLS, etc.), resolves the tenant (e.g., by BIC) and the user’s roles (admin/operator/auditor), and then opens a PostgreSQL connection scoped to that tenant. +At the start of each request, the middleware sets session variables, for example: + • SET LOCAL app.tenant_id = ''; + • SET LOCAL app.user_id = ''; + • SET LOCAL app.roles = 'admin,operator'; + +Each table has RLS enabled with policies that read these session values via current_setting('app.tenant_id', true) and allow or deny operations: + • Admin: full CRUD for the tenant (and, optionally, a special platform_admin can create organizations). + • Operator: CRUD only within the tenant; writes may be restricted (e.g., transactions must target a wallet on the tenant’s allowlist). + • Auditor: SELECT-only within the tenant. + +Because the database enforces RLS, even if an application bug appears, cross-tenant leakage is blocked at the data layer. + +Database schema + +erDiagram + ORGANIZATION ||--o{ USER : "has many" + ORGANIZATION ||--o{ PERMISSION_ALLOWLIST : "defines" + ORGANIZATION ||--o{ TRANSACTION : "owns" + + USER ||--o{ TRANSACTION : "created_by" + USER }o--o{ ROLE : "has (scoped to org)" + ROLE ||--o{ ROLE_PERMISSION : "grants" + + ORGANIZATION { + uuid id PK "tenant_id" + string name + string bic UNIQUE + timestamptz created_at + timestamptz updated_at + } + + USER { + uuid id PK + uuid org_id FK "-> ORGANIZATION.id" + string email UNIQUE + string password_hash + boolean is_active + timestamptz created_at + timestamptz updated_at + } + + ROLE { + uuid id PK + string name "admin | operator | auditor | platform_admin" + } + + USER_ROLE { + uuid user_id FK "-> USER.id" + uuid role_id FK "-> ROLE.id" + uuid org_id FK "-> ORGANIZATION.id" + PK "user_id, role_id, org_id" + } + + ROLE_PERMISSION { + uuid role_id FK "-> ROLE.id" + text permission "e.g., tx:create, tx:read, allowlist:write" + PK "role_id, permission" + } + + PERMISSION_ALLOWLIST { + uuid id PK + uuid org_id FK "-> ORGANIZATION.id" + text wallet_address + text label + boolean active + timestamptz created_at + UNIQUE "org_id, wallet_address" + } + + TRANSACTION { + uuid id PK + uuid org_id FK "-> ORGANIZATION.id" + uuid created_by FK "-> USER.id" + text to_wallet + numeric amount + jsonb payload + text status "draft|submitted|confirmed|failed" + timestamptz created_Flow summary + 1. Caller authenticates → RBAC Middleware resolves tenant & roles. + 2. RBAC Middleware sets app.tenant_id + app.roles on the DB session/transaction. + 3. RLS policies evaluate those values and enforce data access per tenant/role. + 4. Other microservices can delegate all authorization to RBAC by using its DB session/pool or by calling RBAC’s APIs. + + + +======= RBAC Application From 4b40e765fe63b11e407947a6eb35e2ad75db19a0 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 16:26:51 +0000 Subject: [PATCH 62/93] Atualizar o test --- test | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test b/test index 7e8446c..fe12b53 100644 --- a/test +++ b/test @@ -1,4 +1,25 @@ +Admin → app.roles='admin', app.tenant_id not required. + • Auditor → app.roles='auditor', app.tenant_id not required. + • Operator → app.roles='operator' and app.tenant_id=''. + +Admins bypass tenant_id restrictions (cross-tenant CRUD). + • Auditors bypass tenant_id restrictions but are limited to read-only. + • Operators are strictly tenant-bound, and Postgres RLS enforces that by checking current_setting('app.tenant_id'). + +Admin → cross-tenant read/write (can access data of any organization, including registering new orgs). + • Operator → tenant-scoped read/write (restricted to their own org; writes must respect allowlist). + • Auditor → cross-tenant read-only. + +user_id can be useful + 1. Auditing & traceability +Every row created/updated can be stamped with created_by = user_id. +→ You can later trace exactly which user (not just which organization) performed an action. + 2. Per-user restrictions inside a tenant +Suppose two Operators belong to the same tenant, but one should only access a subset of data (e.g., wallets assigned to them). +→ Then you need user_id in RLS to check created_by = current_setting('app.user_id')::uuid. + 3. Row-level ownership +For example, if you let Operators see only their own draft transactions (not those of colleagues in the same org), RLS can enforce Database segregation by Role + Row-Level Security (RLS) From 10158a50270211a7c641d1221833b3fb040a8d42 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 16:57:26 +0000 Subject: [PATCH 63/93] Atualizar o test --- test | 956 +++-------------------------------------------------------- 1 file changed, 35 insertions(+), 921 deletions(-) diff --git a/test b/test index fe12b53..f312ec5 100644 --- a/test +++ b/test @@ -1,952 +1,66 @@ - -Admin → app.roles='admin', app.tenant_id not required. - • Auditor → app.roles='auditor', app.tenant_id not required. - • Operator → app.roles='operator' and app.tenant_id=''. - -Admins bypass tenant_id restrictions (cross-tenant CRUD). - • Auditors bypass tenant_id restrictions but are limited to read-only. - • Operators are strictly tenant-bound, and Postgres RLS enforces that by checking current_setting('app.tenant_id'). - -Admin → cross-tenant read/write (can access data of any organization, including registering new orgs). - • Operator → tenant-scoped read/write (restricted to their own org; writes must respect allowlist). - • Auditor → cross-tenant read-only. - -user_id can be useful - 1. Auditing & traceability -Every row created/updated can be stamped with created_by = user_id. -→ You can later trace exactly which user (not just which organization) performed an action. - 2. Per-user restrictions inside a tenant -Suppose two Operators belong to the same tenant, but one should only access a subset of data (e.g., wallets assigned to them). -→ Then you need user_id in RLS to check created_by = current_setting('app.user_id')::uuid. - 3. Row-level ownership -For example, if you let Operators see only their own draft transactions (not those of colleagues in the same org), RLS can enforce - -Database segregation by Role + Row-Level Security (RLS) - -Roles - • Admin — Read/write any data in SDL; can also register a new participant (organization). - • Operator (participants/banks) — Read/write data belonging to your own organization in SDL. - • Auditor — Read-only access to data belonging to your own organization in SDL. - -Onboarding (new organization) - • Organization name - • BIC (tenant_id) - • Email - • Temporary password - • Role (auditor/operator) - • Whitelist (wallet address / allow list) - -Database schema (top-level entities) - • Organization - • User - • Permission (Allowlist) - • Transaction - -How RBAC + RLS work together (short intro) - -The RBAC Middleware authenticates the caller (OIDC, mTLS, etc.), resolves the tenant (e.g., by BIC) and the user’s roles (admin/operator/auditor), and then opens a PostgreSQL connection scoped to that tenant. -At the start of each request, the middleware sets session variables, for example: - • SET LOCAL app.tenant_id = ''; - • SET LOCAL app.user_id = ''; - • SET LOCAL app.roles = 'admin,operator'; - -Each table has RLS enabled with policies that read these session values via current_setting('app.tenant_id', true) and allow or deny operations: - • Admin: full CRUD for the tenant (and, optionally, a special platform_admin can create organizations). - • Operator: CRUD only within the tenant; writes may be restricted (e.g., transactions must target a wallet on the tenant’s allowlist). - • Auditor: SELECT-only within the tenant. - -Because the database enforces RLS, even if an application bug appears, cross-tenant leakage is blocked at the data layer. - -Database schema - erDiagram ORGANIZATION ||--o{ USER : "has many" ORGANIZATION ||--o{ PERMISSION_ALLOWLIST : "defines" ORGANIZATION ||--o{ TRANSACTION : "owns" + ORGANIZATION ||--o{ USER_ROLE : "scopes" USER ||--o{ TRANSACTION : "created_by" - USER }o--o{ ROLE : "has (scoped to org)" + USER }o--o{ ROLE : "has" + USER ||--o{ USER_ROLE : "assigned" + ROLE ||--o{ ROLE_PERMISSION : "grants" + ROLE ||--o{ USER_ROLE : "applies to" ORGANIZATION { - uuid id PK "tenant_id" + string id PK string name - string bic UNIQUE - timestamptz created_at - timestamptz updated_at + string bic + datetime created_at + datetime updated_at } USER { - uuid id PK - uuid org_id FK "-> ORGANIZATION.id" - string email UNIQUE + string id PK + string org_id + string email string password_hash boolean is_active - timestamptz created_at - timestamptz updated_at + datetime created_at + datetime updated_at } ROLE { - uuid id PK - string name "admin | operator | auditor | platform_admin" + string id PK + string name } USER_ROLE { - uuid user_id FK "-> USER.id" - uuid role_id FK "-> ROLE.id" - uuid org_id FK "-> ORGANIZATION.id" - PK "user_id, role_id, org_id" + string user_id PK + string role_id PK + string org_id PK } ROLE_PERMISSION { - uuid role_id FK "-> ROLE.id" - text permission "e.g., tx:create, tx:read, allowlist:write" - PK "role_id, permission" + string role_id PK + string permission PK } PERMISSION_ALLOWLIST { - uuid id PK - uuid org_id FK "-> ORGANIZATION.id" - text wallet_address - text label + string id PK + string org_id + string wallet_address + string label boolean active - timestamptz created_at - UNIQUE "org_id, wallet_address" + datetime created_at } TRANSACTION { - uuid id PK - uuid org_id FK "-> ORGANIZATION.id" - uuid created_by FK "-> USER.id" - text to_wallet - numeric amount - jsonb payload - text status "draft|submitted|confirmed|failed" - timestamptz created_Flow summary - 1. Caller authenticates → RBAC Middleware resolves tenant & roles. - 2. RBAC Middleware sets app.tenant_id + app.roles on the DB session/transaction. - 3. RLS policies evaluate those values and enforce data access per tenant/role. - 4. Other microservices can delegate all authorization to RBAC by using its DB session/pool or by calling RBAC’s APIs. - - - -======= - -RBAC Application - -option JWT request - -sequenceDiagram - autonumber - participant CA as Certificate Authority - participant U as User Browser (Client Cert) - participant I as Ingress/NGINX (mTLS Gate + auth_request) - participant F as SDL Frontend (Dashboard) - participant B as SDL Backend (BFF + Session Store) - participant R as RBAC Middleware (OIDC Client + API) - participant K as Keycloak (IdP) - - %% 0) One-time PKI - U->>CA: CSR (generate keypair locally) - CA-->>U: client.crt / client.p12 - note over U,CA: Browser installs the client certificate for mTLS - - %% 1) mTLS Handshake - U->>I: TLS handshake (presents client cert) - I->>I: Verify certificate against CA (CRL/OCSP) - alt mTLS OK - I-->>U: TLS established - else Failed - I-->>U: 401 mTLS required - end - - %% 2) Initial access to Dashboard - U->>I: GET /app - I->>F: Proxy /app (protected) - F-->>U: HTML/JS (SPA loads but needs auth) - - %% 3) SPA calls Backend for login - U->>I: POST /backend/login - I->>B: Proxy /login - - %% 4) Backend delegates login to RBAC - B->>R: /login?rd=/app - R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback - - %% 5) Browser interacts with Keycloak - U->>K: Login (credentials/MFA) - K-->>U: 302 → R:/callback?code=AUTH_CODE - U->>R: GET /callback?code=AUTH_CODE - - %% 6) RBAC exchanges AUTH_CODE for tokens with Keycloak - R->>K: POST /token (authorization_code) - K-->>R: {access_token (JWT), id_token, refresh_token} - R->>B: {access_token, refresh_token, claims} - - %% 7) SDL Backend creates internal session - B->>B: Create session_id=abc123 → {tokens, claims} (Redis) - B-->>U: 200 { session_id: "abc123" } - note over U,B: Browser never sees the JWT, only a session_id - - %% 8) User accesses the Dashboard - U->>I: GET /app (now authenticated) - I->>F: GET /app - F-->>U: Dashboard - - %% 9) Business request (e.g., transfer) - U->>I: POST /backend/transfer\nX-Session-Id: abc123 - I->>B: /transfer - B->>B: Resolve session_id → {access_token} - B->>R: POST /api/transfer\nAuthorization: Bearer - R->>R: Validate JWT (Keycloak JWKS) & apply RBAC - alt Authorized - R-->>B: 200 {result} - B-->>U: 200 {result} - else Denied - R-->>B: 403 Forbidden - B-->>U: 403 Forbidden - end - - %% 10) Token refresh (server-side) - B->>R: POST /token (refresh_token) - R->>K: /token (refresh_token) - K-->>R: {new_access_token} - R-->>B: {new_access_token} - B->>B: Update session abc123 - - -Highlights - • CA + mTLS → ensures device identity before login. - • RBAC Middleware is the only OIDC Client talking to Keycloak. - • SDL Backend never talks to Keycloak — it only delegates to RBAC. - • Browser never gets the JWT, it only receives a session_id. - • Backend injects the JWT when calling RBAC (Authorization: Bearer ). - • RBAC Middleware validates the JWT and applies RBAC policies. - - - - - -======== -sequenceDiagram - autonumber - participant U as User Browser - participant CA as Certificate Authority (Root/Intermediate) - participant I as NGINX/Ingress (mTLS Gate + auth_request) - participant R as RBAC Middleware (OIDC Client + Session + API) - participant K as Keycloak (IdP) - participant F as SDL Frontend (Dashboard) - participant B as SDL Backend - - %% 0) One-time PKI enrollment - U->>CA: CSR (generate keypair locally) - CA-->>U: Client cert (.crt/.p12) - note over U,CA: User installs cert+key in browser/OS - - %% 1) mTLS at edge - U->>I: TLS handshake (client cert) - I->>I: Verify against CA (CRL/OCSP) - alt mTLS OK - I-->>U: TLS established - else mTLS fail - I-->>U: 400/401 mTLS required - end - - %% 2) Guard dashboard with RBAC session - U->>I: GET /app - I->>R: auth_request /rbac/session/verify - alt No session - R-->>I: 401 - I-->>U: 302 → R:/login?rd=/app - else Session OK - R-->>I: 200 + optional identity headers - I->>F: GET /app - F-->>U: 200 Dashboard - end - - %% 3) RBAC performs OIDC (Auth Code) with Keycloak - U->>R: GET /login?rd=/app - R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback - U->>K: Keycloak login (creds/MFA) - K-->>U: 302 → R:/callback?code=AUTH_CODE - U->>R: GET /callback?code=AUTH_CODE - R->>K: POST /token (code → tokens) - K-->>R: {access_token, id_token, refresh_token} - R->>R: Create server-side session (store tokens/claims) - R-->>U: Set rbac_session cookie + 302 /app - - %% 4) Authenticated dashboard load (after login) - U->>I: GET /app (with rbac_session) - I->>R: auth_request /rbac/session/verify - R-->>I: 200 OK (may include X-Client-Cert-Subject) - I->>F: GET /app - F-->>U: 200 Dashboard - - %% 5) User triggers a business action via Backend - U->>I: POST /backend/transfer (XHR) - I->>R: auth_request /rbac/session/verify - R-->>I: 200 OK - I->>B: POST /transfer (forward) - - %% 6) SDL Backend calls RBAC API endpoint (same RBAC) - B->>R: POST /api/transfer (cookie: rbac_session) - R->>R: Resolve session → user/tenant/roles - R->>R: Authorize policy (claims, role, scope, mTLS subject if required) - alt Authorized - R->>R: Execute business logic (transfer) %% RBAC == API - R-->>B: 200 OK (result) - B-->>U: 200 OK (JSON) - else Forbidden - R-->>B: 403 Forbidden - B-->>U: 403 Forbidden - end - - %% 7) Silent refresh handled by RBAC - R->>K: POST /token (refresh_token when needed) - K-->>R: new access_token - R->>R: Update session store - - - -#fail -sequenceDiagram - autonumber - participant U as User Browser - participant CA as Certificate Authority (Root/Intermediate) - participant I as NGINX/Ingress (mTLS Gate + auth_request) - participant R as RBAC Middleware (OIDC Client + Session + API) - participant K as Keycloak (IdP) - participant F as SDL Frontend (Dashboard) - participant B as SDL Backend - - %% 0) One-time PKI enrollment - U->>CA: CSR (generate keypair locally) - CA-->>U: Client cert (.crt/.p12) - note over U,CA: User installs cert+key in browser/OS - - %% 1) mTLS at edge - U->>I: TLS handshake (client cert) - I->>I: Verify against CA (CRL/OCSP) - alt mTLS OK - I-->>U: TLS established - else mTLS fail - I-->>U: 400/401 mTLS required - return - end - - %% 2) Guard dashboard with RBAC session - U->>I: GET /app - I->>R: auth_request /rbac/session/verify - alt No session - R-->>I: 401 - I-->>U: 302 → R:/login?rd=/app - else Session OK - R-->>I: 200 + optional identity headers - I->>F: GET /app - F-->>U: 200 Dashboard - end - - %% 3) RBAC performs OIDC (Auth Code) with Keycloak - U->>R: GET /login?rd=/app - R-->>U: 302 → K:/authorize?client_id=rbac&redirect_uri=R:/callback - U->>K: Keycloak login (creds/MFA) - K-->>U: 302 → R:/callback?code=AUTH_CODE - U->>R: GET /callback?code=AUTH_CODE - R->>K: POST /token (code → tokens) - K-->>R: {access_token, id_token, refresh_token} - R->>R: Create server-side session (store tokens/claims) - R-->>U: Set rbac_session cookie + 302 /app - - %% 4) Authenticated dashboard load (after login) - U->>I: GET /app (with rbac_session) - I->>R: auth_request /rbac/session/verify - R-->>I: 200 OK (may include X-Client-Cert-Subject) - I->>F: GET /app - F-->>U: 200 Dashboard - - %% 5) User triggers a business action via Backend - U->>I: POST /backend/transfer (XHR) - I->>R: auth_request /rbac/session/verify - R-->>I: 200 OK - I->>B: POST /transfer (forward) - - %% 6) SDL Backend calls RBAC API endpoint (same RBAC) - B->>R: POST /api/transfer (cookie: rbac_session) - R->>R: Resolve session → user/tenant/roles - R->>R: Authorize policy (claims, role, scope, mTLS subject if required) - alt Authorized - R->>R: Execute business logic (transfer) %% RBAC == API - R-->>B: 200 OK (result) - B-->>U: 200 OK (JSON) - else Forbidden - R-->>B: 403 Forbidden - B-->>U: 403 Forbidden - end - - %% 7) Silent refresh handled by RBAC - R->>K: POST /token (refresh_token when needed) - K-->>R: new access_token - R->>R: Update session store - - -#RBAC MIddleware Drive automatic page redirect without OAuth2_proxy client - -sequenceDiagram - autonumber - participant CA as Certificate Authority (Root/Intermediate) - participant U as User (Browser w/ Client Cert) - participant N as NGINX (Edge mTLS Proxy) - participant P as Portal SDL Frontend (app.sua-app.com) - participant R as RBAC Middleware (api.sua-app.com) - participant K as Keycloak (login.sua-idp.com) - participant S as Session Store (Redis) - - %% ---------------- ONE-TIME ENROLLMENT (PKI) ---------------- - U->>CA: Submit CSR (generate keypair locally, send CSR) - CA-->>U: Issue client certificate (User.crt / .p12) - note over U,CA: User installs cert+key in the browser/OS keychain - - %% ---------------- PORTAL ENTRY (mTLS @ EDGE) ---------------- - U->>N: TLS handshake + present client cert - N-->>U: TLS established if cert valid (verify chain+CRL/OCSP) - note over U,N: mTLS gate passed → request forwarded to Portal SDL - - U->>P: GET / (initial page load, static assets via NGINX) - P-->>U: 200 HTML/JS (Portal bootstraps & calls RBAC to check session) - - %% ---------------- AUTH GUARD (RBAC REDIRECT TO KEYCLOAK) ---------------- - U->>R: GET /session/check (no cookie or invalid) - R-->>U: 302 Redirect → K /realms/{realm}/protocol/openid-connect/auth
?client_id=portal-sdl&response_type=code&scope=openid%20profile%20email&redirect_uri=https%3A%2F%2Fapp.sua-app.com%2Foidc%2Fcallback&state=origURL&code_challenge=...&code_challenge_method=S256 - - %% ---------------- KEYCLOAK LOGIN ---------------- - U->>K: GET /auth (OIDC authorize) - K-->>U: Login page (username/password, MFA, etc.) - U->>K: Submit credentials (and MFA if any) - K-->>U: 302 → https://app.sua-app.com/oidc/callback?code=...&state=origURL - - %% ---------------- CALLBACK + TOKEN EXCHANGE ---------------- - U->>N: GET /oidc/callback?code=...&state=... - N->>R: Proxy /oidc/callback (preserve headers) - R->>K: POST /token (code → tokens, using client_secret if confidential) - K-->>R: 200 { access_token, refresh_token, id_token, expires_in } - - %% ---------------- SESSION CREATION ---------------- - R->>S: SET session:{sid} = { sub, roles, tokens, expiry } - S-->>R: OK - R-->>U: Set-Cookie: rbac_session=SID; HttpOnly; Secure; SameSite=Lax - R-->>U: 302 → state.origURL (return to originally requested page) - - %% ---------------- AUTHENTICATED USE (SUBSEQUENT CALLS) ---------------- - U->>P: GET / (now with rbac_session cookie) - P-->>U: 200 (app shell) - U->>R: GET /api/transfer (cookie: rbac_session=SID) - R->>S: GET session:{sid} - S-->>R: { sub, roles, tokens (or cached claims) } - R->>R: Validate session & RBAC (roles/claims/tenant) - R-->>U: 200 OK (or 403 if not authorized) - - %% ---------------- TOKEN REFRESH (WHEN NEEDED) ---------------- - R->>K: POST /token (grant_type=refresh_token) - K-->>R: 200 { new access_token, refresh_token } - R->>S: UPDATE session:{sid} tokens/expiry - S-->>R: OK - - -mTLS is enforced only at NGINX (edge). User auth still uses OIDC via Keycloak. - -The Portal never handles tokens directly; RBAC does the code exchange, stores tokens/claims in Redis, and sets a Secure+HttpOnly session cookie. - -Use PKCE if the RBAC callback ever runs in a public context; otherwise make the Keycloak client confidential with a client secret. - -Add allowlists to avoid loops: /oidc/callback, /health, static assets, etc. - - - - - - -#Logout - -sequenceDiagram - autonumber - participant U as User (Browser) - participant N as NGINX (Edge mTLS Proxy) - participant O as oauth2-proxy (OIDC Client) - participant K as Keycloak (login.sua-idp.com) - participant P as Portal SDL Frontend (app.sua-app.com) - - %% ---- USER CLICKS LOGOUT IN THE PORTAL ---- - U->>N: POST /logout (or /oauth2/sign_out) - note over N: mTLS enforced: client cert is verified - alt App-driven logout route (/logout) - N->>O: Proxy /oauth2/sign_out - else Direct call to oauth2-proxy - N->>O: Proxy /oauth2/sign_out - end - - %% ---- CLEAR LOCAL SESSION (oauth2-proxy) ---- - O-->>U: Set-Cookie: _oauth2_proxy=; Expires=past; HttpOnly; Secure; SameSite - note right of O: Local session invalidated (no tokens exposed to browser) - - %% ---- OPTIONAL: SSO LOGOUT AT KEYCLOAK (RP-INITIATED) ---- - alt SSO logout enabled - O-->>U: 302 → K /protocol/openid-connect/logout
?post_logout_redirect_uri=https://app.sua-app.com/logged-out - U->>N: GET /protocol/openid-connect/logout?... (to Keycloak) - N->>K: Proxy logout to Keycloak - K-->>U: 302 → https://app.sua-app.com/logged-out - U->>N: GET /logged-out - N->>P: Proxy /logged-out (public page) - P-->>N: logged-out view - N-->>U: Render "logged out" - else Local logout only - O-->>U: 302 → https://app.sua-app.com/logged-out (or 204) - U->>N: GET /logged-out - N->>P: Proxy /logged-out - P-->>N: logged-out view - N-->>U: Render "logged out" - end - - %% ---- EDGE CASES ---- - rect rgba(255,240,220,0.5) - note over O: If session already missing/expired → still clear cookie and continue. - note over K: Without SSO logout, Keycloak session may remain active.
Next visit may auto-login unless the IdP session times out or is cleared. - end - - - -#RBAC with oatuh2_proxy_client authorization - -sequenceDiagram - autonumber - participant U as User (Browser) - participant N as NGINX (mTLS + auth_request) - participant O as oauth2-proxy (OIDC session) - participant R as RBAC Middleware (api.sua-app.com) - participant DB as RBAC Policy DB (roles/allowlists/limits) - participant S as Signer/Relayer (KMS) - participant CH as Chain RPC (node) - - %% ---- PRECONDITION: user is already logged in ---- - note over U,O: Browser holds _oauth2_proxy session cookie (HttpOnly, Secure) - - %% ---- TRANSFER REQUEST FROM THE PORTAL ---- - U->>N: POST /api/transfer (credentials: include; CSRF header) - note over N: mTLS: verify client cert (optional but recommended) - - %% ---- AUTHN CHECK AT THE EDGE ---- - N->>O: subrequest /oauth2/auth (validate session cookie) - O-->>N: 200 OK + X-Auth-Request-User/Email/Groups - note over N: If 401 → 302 to /oauth2/start (not shown) - - %% ---- FORWARD TO RBAC WITH IDENTITY CONTEXT ---- - N->>R: Proxy /api/transfer
X-Auth-Request-User, X-Auth-Request-Email, X-SSL-Client-Verify/CN, CSRF token - - %% ---- RBAC AUTHORIZATION ---- - R->>R: Validate CSRF, content-type, schema (amount, from, to, contract) - R->>DB: Fetch user→tenant mapping, roles, wallet/contract allowlists, tx limits - DB-->>R: {roles:["writer"], wallets:["0xFrom..."], contracts:["0xToken..."], limits:{daily:..., perTx:...}} - R->>R: Enforce policy: role=writer? fromWallet allowed? contract allowed? amounts/limits OK? - alt Authorized - %% ---- PREP + SUBMIT TRANSACTION ---- - R->>S: Build tx (e.g., ERC20 transfer), EIP-1559 params, optional EIP-712; request signature - S->>CH: Send signed tx to chain RPC - CH-->>S: txHash / receipt (pending or mined) - S-->>R: {txHash, status:pended} - R-->>N: 200 { txHash, status:"submitted" } - N-->>U: 200 { txHash, status:"submitted" } - else Denied - R-->>N: 403 { error:"not_authorized", reason:"wallet/contract/role/limit" } - N-->>U: 403 { error, reason } - end - -Browser → NGINX: POST /api/transfer with the session cookie (from oauth2-proxy) and a CSRF header from your SPA. - -NGINX → oauth2-proxy: auth_request validates the cookie. If valid, oauth2-proxy returns 200 and injects identity headers (e.g., X-Auth-Request-User, X-Auth-Request-Email, X-Auth-Request-Groups). - -NGINX → RBAC: forwards the call, passing the identity headers (and, if you enforce device binding, X-SSL-Client-Verify/X-SSL-Client-CN). - -RBAC: - -Validates CSRF and the payload (from, to, amount, contractAddress). - -Loads roles & allowlists from its Policy DB (e.g., writer role; fromWallet allowed; contract allowed; per-tx/daily limits). - -If authorized, RBAC prepares the transaction (ERC-20 transfer or equivalent), optionally as EIP-712 typed data, requests a signature from the Signer/Relayer (KMS), and submits to the Chain RPC. Returns { txHash, status:"submitted" }. - -If denied, returns 403 with the reason (role/wallet/contract/limit). - - - - - -#RBAC with oatuh2_proxy_client authentication - - -- OAUTH2_PROXY_CLIENT_ID=your-client-id -- OAUTH2_PROXY_CLIENT_SECRET=your-client-secret -- OAUTH2_PROXY_PROVIDER=oidc -- OAUTH2_PROXY_OIDC_ISSUER_URL=https://login.your-keycloak.com/realms/your-realm - -sequenceDiagram - autonumber - participant CA as Certificate Authority (Root/Intermediate) - participant U as User (Browser with Client Cert) - participant N as NGINX (Edge mTLS Proxy) - participant O as oauth2-proxy (OIDC Client) - participant K as Keycloak (login.sua-idp.com) - participant P as Portal SDL Frontend (app.sua-app.com) - participant R as RBAC Middleware (api.sua-app.com) - - %% ---- ONE-TIME ENROLLMENT (PKI) ---- - U->>CA: Submit CSR (request client certificate) - CA-->>U: Issue client certificate (User.crt/.p12) - note over U,CA: User installs client cert+key in the browser/device - - %% ---- FIRST REQUEST (mTLS @ NGINX) ---- - U->>N: TLS handshake (client presents User.crt) - N-->>U: Verify chain (Root/Intermediate), CRL/OCSP, expiry → TLS established - U->>N: GET https://app.sua-app.com/ - N->>O: subrequest: GET /oauth2/auth (auth_request) - O-->>N: 401 (no session cookie yet) - N-->>U: 302 → /oauth2/start (kick off OIDC) - - %% ---- REDIRECT TO KEYCLOAK ---- - U->>N: GET /oauth2/start - N->>O: Proxy /oauth2/start - O-->>U: 302 → K /realms//protocol/openid-connect/auth?client_id=...&response_type=code&redirect_uri=https://app.sua-app.com/oauth2/callback&scope=openid%20email%20profile&state=...&nonce=... - U->>K: GET .../auth (Keycloak Login Page) - K->>U: Render login (user/password, MFA/WebAuthn) - U->>K: Submit credentials - - %% ---- OIDC CALLBACK ---- - K-->>U: 302 → https://app.sua-app.com/oauth2/callback?code=CODE&state=STATE - U->>N: GET /oauth2/callback (still under mTLS) - N->>O: Proxy /oauth2/callback - - %% ---- TOKEN EXCHANGE (INSIDE OAUTH2-PROXY) ---- - O->>K: POST /token (authorization_code, client_id, client_secret, code, redirect_uri) - K-->>O: 200 {access_token, id_token, refresh_token, expires_in} - O-->>U: Set-Cookie: _oauth2_proxy=SESSION (HttpOnly, Secure, SameSite) + 302 → original URL - - %% ---- AUTHORIZED CONTENT ---- - U->>N: GET https://app.sua-app.com/ (with _oauth2_proxy cookie) - N->>O: subrequest /oauth2/auth (validate session) - O-->>N: 200 + headers (X-Auth-Request-User/Email/Groups) - N->>P: Proxy / (serve SPA) - P-->>N: index.html, JS/CSS - N-->>U: Portal assets (authenticated) - - %% ---- OPTIONAL BACKENDS ---- - U->>N: XHR /api/... (cookie present) - N->>O: /oauth2/auth (still OK) - O-->>N: 200 + identity headers - N->>R: Proxy /api/... (pass identity headers) - R-->>N: 200 - N-->>U: 200 - - -NGINX: - -Enforces mTLS (client certificate required). - -Uses auth_request to ask oauth2-proxy if the user is authenticated. - -Serves Portal and proxies APIs only when oauth2-proxy says “OK”. - -oauth2-proxy: - -Acts as the OIDC client to Keycloak. - -Builds the /authorize URL (with state/nonce), handles /callback, exchanges code→tokens. - -Sets a secure session cookie (e.g. _oauth2_proxy) and injects identity headers on success. - -Keeps tokens server-side (not exposed to the browser). - -Keycloak: IdP (login page, MFA, token endpoint). - -Portal / RBAC: receive requests only after oauth2-proxy has authenticated the session; they can consume identity headers. - - -✅ With this model: - -Tokens never touch the browser. - -Browser → NGINX requires a valid client certificate (mTLS). - -RBAC Middleware is the only Keycloak client (confidential, with client_secret). - - - - - - - - - - - - - - - - - - - - -RBAC API - -The RBAC Middleware ensures privacy and enforces authorization rules across the bridge workflow. Each Issuer integrates with the RBAC Middleware to maintain an isolated privacy domain. The RBAC Middleware is responsible for authorizing mint and burn operations, ensuring only valid and approved transactions move across the networks. - -⸻ - -4.3.4.2 Bridge interaction flow - -Bridge from Enterprise to Swift SLE - 5. A participant in the Enterprise Network initiates a deposit request via the Backend application by first approving the TokenBridge Contract to move funds from the ERC20/ERC3643 contract and locking tokens in the TokenBridge Contract. - 6. The TokenBridge Contract emits an event with details (amount, token, destinationAddress). - 7. The Issuer Bridge Operator monitors and captures this event via a secure message channel. - 8. The Issuer Bridge Operator, using a gas-sponsor wallet, pays the gas on behalf of the Enterprise participant and sends the transaction details to the RBAC Middleware. - 9. The RBAC Middleware validates the request and authorizes the mint of the private tokens inside the Swift SLE environment. - -⸻ - -Bridge from Swift SLE to Enterprise - 6. A participant in the Enterprise Network initiates a withdrawal request via the Backend application, which sends a request to the Issuer Bridge Operator. - 7. The Issuer Bridge Operator forwards the withdrawal request to the RBAC Middleware for authorization. - 8. The RBAC Middleware validates the burn, generates a proof of burn, and returns it to the Issuer Bridge Operator. - 9. The Issuer Bridge Operator sends the validated proof back to the Enterprise TokenBridge Contract. - 10. The TokenBridge Contract releases the locked tokens to the specified address on the Enterprise Network. - ------- -Generate PKI client cert (bank → gets installed on their machine/app). - 2. Create API key in API Gateway (send to bank). - 3. Create Keycloak client_id/secret (send to bank). - 4. Bank calls OIDC → get JWT → call API with mTLS + API key + JWT. - - -Bank ↔ API Gateway: mTLS + API Key (+ JWT you issue via RBAC broker endpoint) - • API Gateway ↔ RBAC: private (VPC Link) - • RBAC ↔ Keycloak: internal only (HTTPS), RBAC holds the client secrets - -Onboarding steps (day-1 for a new bank) - -1) PKI + Gateway - 1. Issue client cert for the bank (or sign their CSR). - 2. Add your CA to API Gateway mTLS truststore (S3 PEM). - 3. Create API Key (bankX-prod) + Usage Plan; require on routes. - 4. Keep Gateway JWT Authorizer enabled (we’ll feed it a Keycloak token). - -2) Keycloak (internal only) - 1. Create client: bankX-api-client (OIDC, confidential; service accounts ON). - 2. Assign roles/scopes (bridge:deposit, etc.). - 3. Add mappers: - • aud = my-enterprise-api - • org_id = bankX - • include roles in token - 4. Copy client_secret. Do NOT share with bank. - -3) RBAC DB (tenant & allowlists) - • Map cert subject ⇄ org_id=bankX - • Map API key id ⇄ org_id=bankX - • Seed allowlists (wallets, contracts, function_sigs). - -4) RBAC exposes a /token endpoint (Token Broker) - • Bank does not talk to Keycloak. - • Bank calls RBAC /token over Gateway with mTLS + API key. - • RBAC authenticates bank (mTLS+API key), finds org_id, looks up bank’s Keycloak client creds, calls Keycloak token endpoint (client_credentials), returns the access_token (JWT) to the bank. -5) Bank calls your real APIs -Gateway validates: - • mTLS client cert ✅ - • x-api-key usage plan ✅ - • JWT (issuer/audience/signature) via JWKS ✅ - -RBAC Middleware (on the API path) then: - • Parses JWT → org_id, roles/scopes - • Enforces allowlists (wallet/contract/function) - • Proceeds with business flow - -Bank → Gateway (/token): mTLS + API key - 2. Gateway → RBAC (/token): pass through - 3. RBAC → Keycloak: client_credentials with bankX-api-client - 4. Keycloak → RBAC: returns JWT (aud=my-enterprise-api, org=bankX) - 5. RBAC → Bank: returns JWT - 6. Bank → Gateway (/bridge/deposit): mTLS + API key + Bearer JWT - 7. Gateway: validates JWT (JWKS) + API key; forwards - 8. RBAC: enforces RBAC/allowlists; executes - - -Pattern A (preferred — what you’re already designing) - • Partner → RBAC: mTLS + API key (no Keycloak secret). - • RBAC → Keycloak: uses stored client_id/secret per bank (in Secrets Manager/Vault). - • RBAC /token returns Keycloak access_token (JWT) to the bank. - • Bank uses that JWT + mTLS + API key for API calls. - - - -==== -Got it—here’s the exact flow you described, clean and precise. - -Flow A — RBAC issues JWT on behalf of the bank - -Preconditions / Mappings - • api_key_id ↔ tenant_id ↔ oidc_client_id ↔ secret_ref (in DB) - • secret_ref points to Secret Manager entry for the OIDC client secret - • Cert fingerprint for the bank is registered (for mTLS) - -Sequence (Mermaid) - -sequenceDiagram - participant Bank as Bank Backend - participant GW as API Gateway - participant RBAC as RBAC Middleware - participant SM as Secret Manager - participant IdP as IdP (OIDC) - - Note over Bank: 1) Get JWT via RBAC - Bank->>GW: POST /auth/jwt (mTLS)
Headers: x-api-key - GW->>GW: Verify mTLS client cert ✅
Verify API key ✅ (get api_key_id) - GW->>RBAC: Forward request
Headers: X-Api-Key-Id, X-Client-Cert-Fingerprint - - RBAC->>RBAC: Lookup api_key_id → (tenant, oidc_client_id, secret_ref) - RBAC->>SM: Get client_secret (secret_ref) - SM-->>RBAC: client_secret - RBAC->>IdP: POST /oauth2/token (client_credentials)
client_id=oidc_client_id&client_secret - IdP-->>RBAC: { access_token (JWT), expires_in } - RBAC-->>GW: { access_token (JWT) } - GW-->>Bank: { access_token (JWT) } - - Note over Bank: 2) Call protected API - Bank->>GW: POST /settlement/v1/... (mTLS)
Headers: x-api-key, Authorization: Bearer JWT - GW->>GW: Verify mTLS ✅, verify API key ✅, rate-limit/log - GW->>RBAC: Forward request + JWT
Headers: X-Api-Key-Id, X-Client-Cert-Fingerprint - RBAC->>RBAC: Verify JWT (JWKS cache), resolve tenant, enforce RBAC/allowlists - RBAC-->>GW: 200/401/403/429/5xx - GW-->>Bank: Response - -Endpoints & Headers - -1) Get JWT (Bank → RBAC via Gateway) - -POST /auth/jwt -x-api-key: -# mTLS client cert presented at TLS layer -Body: { "scope": "settlement.write" } # optional - -Gateway → RBAC (forwarded): - -X-Api-Key-Id: -X-Client-Cert-Fingerprint: sha256:<...> -X-Request-Id: - -RBAC → IdP (client credentials): - -POST /oauth2/token -Content-Type: application/x-www-form-urlencoded - -grant_type=client_credentials& -client_id=& -client_secret=& -scope=settlement.write - -RBAC → Bank (via Gateway): - -{ - "access_token": "", - "token_type": "Bearer", - "expires_in": 600 -} - -2) Protected API call - -POST /settlement/v1/submit -Authorization: Bearer -x-api-key: -# mTLS client cert at TLS - -What each component does - • API Gateway - • Verifies mTLS and API key; resolves/attaches X-Api-Key-Id - • Rate limits, quotas, logging; forwards fingerprint header - • RBAC Middleware - • For /auth/jwt: DB lookup → fetch client_secret from Secret Manager → OIDC token request → return JWT - • For protected APIs: verify JWT (JWKS cache), map tenant, enforce RBAC + allowlists (wallets/contracts/methods), audit - • Secret Manager - • Stores OIDC client_secret; returns on-demand (never logs it) - • IdP (OIDC) - • Issues short-lived access tokens for client_credentials - -Security & Ops tips (for this model) - • Do not expose or log client_secret; only RBAC reads from Secret Manager. - • Cache the JWT per tenant until expiry; proactively refresh on 80–90% TTL. - • Enable CRL/OCSP on Gateway for client-cert revocation. - • Use mTLS-bound tokens (RFC 8705) if your IdP supports it (extra strong binding). - • Rotate: API keys, client secrets; monitor token issuance rates (abuse detection). - • In RBAC, verify JWT claims: iss, aud, exp, nbf, scope/roles, sub. - -If you want, I can tailor the headers and config for your stack (e.g., Kong, AWS API Gateway, or NGINX + Keycloak/Okta), including example plugin settings and JWKS caching code. - -Onboarding (new bank) - 1. PKI / mTLS - - • Platform CA issues client certificate for the bank (or signs bank CSR). - • Distribute: bank-client.crt + bank-client.key (to bank) and Root/Intermediate CA (to both sides). - • Register the bank cert thumbprint (SHA-256) in your tenant table. - - 2. API Key (Gateway) - - • Create API key in the API Gateway; attach usage plan (rate/quotas) and tenant tag. - • Store mapping in DB: bank_id ↔ api_key_id ↔ cert_thumbprint. - - 3. OIDC Client (IdP) - - • Create OIDC client (grant: client_credentials for system-to-system). - • Get client_id/client_secret; assign scopes/roles. - • Store mapping in DB: bank_id ↔ oidc_client_id ↔ scopes/roles. - • (Optional, strong) Enable MTLS-bound tokens at IdP so the JWT is tied to the bank cert. - -API Gateway -The API Gateway acts as the secure entry point for all requests, enforcing mTLS for mutual authentication, validating API keys, and applying rate limiting to protect against abuse. It provides identification and traffic control for each tenant, while also enabling simple service integration by routing validated requests to the RBAC Middleware and downstream services. - -Identity Provider (IdP) -The Identity Provider (IdP) implements OpenID Connect (OIDC) on top of the OAuth2 protocol, enabling strong authentication and standardized token issuance. It manages roles, claims, and allowlists, providing signed JWTs that the RBAC Middleware can verify to enforce fine-grained authorization across APIs and smart contract operations. - -Prototype Phase -In the prototype phase, RBAC policies are mocked within the middleware to validate functional flows without requiring a full identity infrastructure. The middleware is also responsible for sending blockchain transactions (received from the Mock Backoffice Application) to the Validium RPC Node and for covering the gas fees. This setup enables rapid iteration, testing, and integration of the solution. - -Production Phase -In the production phase, the RBAC middleware should be integrated with an Identity Provider (IdP) to enable fine-grained authorization. OpenConnect ID should be configured so that JWT tokens issued by the IdP are validated against RBAC policies before any transaction is processed. Responsibility for signing transactions and paying gas fees should be shifted to the RelayerSigner component, which will handle these functions. - -mTLS + PKI – The CA issues a client certificate and sends it to the bank. - 2. API Key – An API key is generated in the API Gateway and provided to the bank. - 3. OIDC Client – The IdP creates a client_id and client_secret, mapped in the DB with the api_key_id. - 4. JWT Retrieval – The bank calls RBAC Middleware with API key + client certificate → Gateway verifies them → RBAC fetches secret from Secret Manager and obtains a JWT from the IdP. - 5. Protected API Access – The bank calls APIs using API key + client certificate + JWT. - -RBAC ensures that the off-chain state is accessible only to authorized parties and should be enforced at the API layer, which sits between the application services and the Validium Swift node RPC. - -When external users connect via the API, they should be identified using the API key provided by the API Gateway. Communication is secured through mTLS/PKI, where the API Gateway verifies the client certificate. The Identity Provider (IdP), configured with OpenID Connect (OIDC), provides fine-grained identity and authorization by issuing JWT tokens that are validated against RBAC policies. - -sequenceDiagram - participant CA as Certificate Authority (CA) - participant GW as API Gateway - participant IdP as IdP / OIDC - participant DB as Database - participant RBAC as RBAC Middleware - participant Bank as Bank - - Note over Bank,CA: Step 1 - mTLS + PKI - CA->>Bank: Issue client certificate (X.509) - Bank-->>CA: Stores cert & private key - - Note over Bank,GW: Step 2 - API Key - GW->>Bank: Generate & provide API key - GW->>DB: Store api_key_id mapping - - Note over Bank,IdP: Step 3 - OIDC Client - IdP->>RBAC: Create client_id + secret - RBAC->>DB: Map (api_key_id, client_id, client_secret_ref) - IdP-->>Bank: Provide client_id + secret - - + string id PK + string org_id + string created_by + string to_wallet + decimal amount + string payload + string status + datetime created_at + } \ No newline at end of file From 7ac8e44e9e104e0d0bbb45827ab53239936ea74b Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 17:08:34 +0000 Subject: [PATCH 64/93] Atualizar o test --- test | 46 ++++++++++++---------------------------------- 1 file changed, 12 insertions(+), 34 deletions(-) diff --git a/test b/test index f312ec5..12de1e0 100644 --- a/test +++ b/test @@ -2,52 +2,30 @@ erDiagram ORGANIZATION ||--o{ USER : "has many" ORGANIZATION ||--o{ PERMISSION_ALLOWLIST : "defines" ORGANIZATION ||--o{ TRANSACTION : "owns" - ORGANIZATION ||--o{ USER_ROLE : "scopes" USER ||--o{ TRANSACTION : "created_by" - USER }o--o{ ROLE : "has" - USER ||--o{ USER_ROLE : "assigned" - - ROLE ||--o{ ROLE_PERMISSION : "grants" - ROLE ||--o{ USER_ROLE : "applies to" ORGANIZATION { - string id PK + uuid id PK "tenant_id" string name - string bic + string bic datetime created_at datetime updated_at } USER { - string id PK - string org_id + uuid id PK + uuid org_id "-> ORGANIZATION.id" string email - string password_hash + string role_id "Keycloak role id or name" boolean is_active datetime created_at datetime updated_at } - ROLE { - string id PK - string name - } - - USER_ROLE { - string user_id PK - string role_id PK - string org_id PK - } - - ROLE_PERMISSION { - string role_id PK - string permission PK - } - PERMISSION_ALLOWLIST { - string id PK - string org_id + uuid id PK + uuid org_id "-> ORGANIZATION.id" string wallet_address string label boolean active @@ -55,12 +33,12 @@ erDiagram } TRANSACTION { - string id PK - string org_id - string created_by + uuid id PK + uuid org_id "-> ORGANIZATION.id" + uuid created_by "-> USER.id" string to_wallet decimal amount - string payload - string status + string payload "JSON as text" + string status "draft|submitted|confirmed|failed" datetime created_at } \ No newline at end of file From c37477a185549a661f4a6bdb8563f0c909db6245 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 17:19:24 +0000 Subject: [PATCH 65/93] Atualizar o test --- test | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test b/test index 12de1e0..f2e56ee 100644 --- a/test +++ b/test @@ -4,11 +4,13 @@ erDiagram ORGANIZATION ||--o{ TRANSACTION : "owns" USER ||--o{ TRANSACTION : "created_by" + USER ||--o{ PERMISSION_ALLOWLIST : "created_by" ORGANIZATION { - uuid id PK "tenant_id" + uuid id PK string name - string bic + string bic "tenant_id" + uuid created_by "-> USER.id (admin)" datetime created_at datetime updated_at } @@ -19,6 +21,7 @@ erDiagram string email string role_id "Keycloak role id or name" boolean is_active + uuid created_by "-> USER.id (admin)" datetime created_at datetime updated_at } @@ -26,6 +29,7 @@ erDiagram PERMISSION_ALLOWLIST { uuid id PK uuid org_id "-> ORGANIZATION.id" + uuid created_by "-> USER.id" string wallet_address string label boolean active From 1a45756840d05759b32ecc7faf72019553420cf7 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 17:38:23 +0000 Subject: [PATCH 66/93] Atualizar o test --- test | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test b/test index f2e56ee..8227839 100644 --- a/test +++ b/test @@ -1,3 +1,8 @@ + +Row-Level Security (RLS) is a PostgreSQL feature that enables fine-grained access control at the row level, allowing organizations to enforce policies that restrict which records a user can query, insert, update, or delete. By applying conditions tied to attributes such as tenant IDs, user roles, or whitelists (e.g., wallet addresses), RLS ensures that each participant only interacts with data belonging to their organization, while maintaining strong isolation within a shared database. +In order to manage secure access and maintain clear separation of responsibilities within the SDL platform, specific roles are configured in Keycloak to govern permissions for different participants. These roles define the scope of actions that each user can perform—ranging from full administrative capabilities, such as registering new organizations, to read-only auditing or operational data management. Alongside this, the onboarding process ensures that every new organization is properly registered with essential information, including identification details, access credentials, assigned roles, and whitelists for allowed interactions. + + erDiagram ORGANIZATION ||--o{ USER : "has many" ORGANIZATION ||--o{ PERMISSION_ALLOWLIST : "defines" From 7148ea92f8068b67dac491f6ce05f12e2dd407b4 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 21:00:49 +0000 Subject: [PATCH 67/93] Atualizar o test --- test | 54 +----------------------------------------------------- 1 file changed, 1 insertion(+), 53 deletions(-) diff --git a/test b/test index 8227839..c8ea95a 100644 --- a/test +++ b/test @@ -1,53 +1 @@ - -Row-Level Security (RLS) is a PostgreSQL feature that enables fine-grained access control at the row level, allowing organizations to enforce policies that restrict which records a user can query, insert, update, or delete. By applying conditions tied to attributes such as tenant IDs, user roles, or whitelists (e.g., wallet addresses), RLS ensures that each participant only interacts with data belonging to their organization, while maintaining strong isolation within a shared database. -In order to manage secure access and maintain clear separation of responsibilities within the SDL platform, specific roles are configured in Keycloak to govern permissions for different participants. These roles define the scope of actions that each user can perform—ranging from full administrative capabilities, such as registering new organizations, to read-only auditing or operational data management. Alongside this, the onboarding process ensures that every new organization is properly registered with essential information, including identification details, access credentials, assigned roles, and whitelists for allowed interactions. - - -erDiagram - ORGANIZATION ||--o{ USER : "has many" - ORGANIZATION ||--o{ PERMISSION_ALLOWLIST : "defines" - ORGANIZATION ||--o{ TRANSACTION : "owns" - - USER ||--o{ TRANSACTION : "created_by" - USER ||--o{ PERMISSION_ALLOWLIST : "created_by" - - ORGANIZATION { - uuid id PK - string name - string bic "tenant_id" - uuid created_by "-> USER.id (admin)" - datetime created_at - datetime updated_at - } - - USER { - uuid id PK - uuid org_id "-> ORGANIZATION.id" - string email - string role_id "Keycloak role id or name" - boolean is_active - uuid created_by "-> USER.id (admin)" - datetime created_at - datetime updated_at - } - - PERMISSION_ALLOWLIST { - uuid id PK - uuid org_id "-> ORGANIZATION.id" - uuid created_by "-> USER.id" - string wallet_address - string label - boolean active - datetime created_at - } - - TRANSACTION { - uuid id PK - uuid org_id "-> ORGANIZATION.id" - uuid created_by "-> USER.id" - string to_wallet - decimal amount - string payload "JSON as text" - string status "draft|submitted|confirmed|failed" - datetime created_at - } \ No newline at end of file +The RBAC Middleware opens a PostgreSQL connection scoped with parameters derived from the JWT token—tenant ID (tenant_id), user ID (user_id), and user roles (admin/auditor/operator)—extracted through OIDC/IdP authentication. This ensures data segregation is enforced according to RLS policies. \ No newline at end of file From 3d344f1e548825d8573413740cf9c7e0b3c78a0b Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 21:07:56 +0000 Subject: [PATCH 68/93] Atualizar o test --- test | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test b/test index c8ea95a..cd0ac9e 100644 --- a/test +++ b/test @@ -1 +1,7 @@ -The RBAC Middleware opens a PostgreSQL connection scoped with parameters derived from the JWT token—tenant ID (tenant_id), user ID (user_id), and user roles (admin/auditor/operator)—extracted through OIDC/IdP authentication. This ensures data segregation is enforced according to RLS policies. \ No newline at end of file +When a new user is created, there are two attributes in Keycloak that should be set and exposed via a JWT token to enable data segregation per role: + +Organization ID: Also referred to as tenant_id. Keycloak does not provide this attribute out of the box. You need to add it as a custom attribute and configure a Protocol Mapper to inject it into the JWT as a claim. In this case, the RBAC middleware should generate the organization ID (UUID v4) and send it to Keycloak when creating the user. + +User ID: Keycloak automatically generates the user ID (sub) when creating the user. + +Keycloak provides an Admin API, which allows you to create new users, set temporary passwords, and assign roles. To use this API, you need a preconfigured service account with a client ID and secret in Keycloak. These credentials are required to invoke the Admin API endpoints. \ No newline at end of file From fd0a1ee7b41166f6e57d6311b4da5fbc96172f64 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Sep 2025 21:44:55 +0000 Subject: [PATCH 69/93] Atualizar o test --- test | 52 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/test b/test index cd0ac9e..f633226 100644 --- a/test +++ b/test @@ -1,7 +1,51 @@ -When a new user is created, there are two attributes in Keycloak that should be set and exposed via a JWT token to enable data segregation per role: +sequenceDiagram + autonumber + actor A as Admin (RBAC role: admin) + participant FE as SDL Frontend (Admin UI) + participant BE as SDL Backend Service + participant DB as Postgres (RLS) + participant KC as Keycloak (Admin API) -Organization ID: Also referred to as tenant_id. Keycloak does not provide this attribute out of the box. You need to add it as a custom attribute and configure a Protocol Mapper to inject it into the JWT as a claim. In this case, the RBAC middleware should generate the organization ID (UUID v4) and send it to Keycloak when creating the user. + %% --- Start --- + A->>FE: Submit Create Org + Initial User (name, bic, email, roles) + FE->>BE: POST /onboarding (payload + idempotency-key) -User ID: Keycloak automatically generates the user ID (sub) when creating the user. + BE->>BE: Validate input & uniqueness + BE->>DB: BEGIN TRANSACTION + BE->>DB: INSERT Organization (tenant_id=UUIDv4, created_by=A.user_id) + DB-->>BE: org_id, tenant_id + BE->>DB: INSERT User (pending, is_active=false, tenant_id) + DB-->>BE: user_id + BE->>DB: INSERT PermissionAllowlist (inactive, optional) + DB-->>BE: allowlist_ids -Keycloak provides an Admin API, which allows you to create new users, set temporary passwords, and assign roles. To use this API, you need a preconfigured service account with a client ID and secret in Keycloak. These credentials are required to invoke the Admin API endpoints. \ No newline at end of file + %% --- Keycloak provisioning --- + BE->>KC: POST /admin/realms//users {username,email, attributes:{tenant_id,bic}} + KC-->>BE: 201 Created (kc_user_id) + BE->>KC: PUT /users/{kc_user_id}/reset-password {value:, temporary:true|false} + KC-->>BE: 204 No Content + BE->>KC: POST /users/{kc_user_id}/role-mappings/... {roles[]} + KC-->>BE: 204 No Content + BE->>KC: GET /users/{kc_user_id} + KC-->>BE: 200 OK (verify attributes) + + %% --- Finalize DB --- + BE->>DB: UPDATE User SET is_active=true, role_id/roles=… + BE->>DB: UPDATE PermissionAllowlist SET active=true + BE->>DB: COMMIT + + BE-->>FE: 201 Created (org_id, tenant_id, user_id, kc_user_id) + FE-->>A: Success (organization + initial user onboarded) + + %% --- Error handling --- + rect rgb(255,245,245) + note over BE,KC: If Keycloak fails + BE->>DB: ROLLBACK + BE-->>FE: 409/422 Error + end + + rect rgb(255,245,245) + note over DB,BE: If DB commit fails after KC success + BE->>KC: DELETE /users/{kc_user_id} (best effort) + BE-->>FE: 500 Error + alert + end \ No newline at end of file From 8b6b8cea4c7293a5a72c1f2a5433b1f8b0c69b0d Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 7 Oct 2025 08:17:13 +0000 Subject: [PATCH 70/93] Atualizar o test --- test | 132 ++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 81 insertions(+), 51 deletions(-) diff --git a/test b/test index f633226..300c7bc 100644 --- a/test +++ b/test @@ -1,51 +1,81 @@ -sequenceDiagram - autonumber - actor A as Admin (RBAC role: admin) - participant FE as SDL Frontend (Admin UI) - participant BE as SDL Backend Service - participant DB as Postgres (RLS) - participant KC as Keycloak (Admin API) - - %% --- Start --- - A->>FE: Submit Create Org + Initial User (name, bic, email, roles) - FE->>BE: POST /onboarding (payload + idempotency-key) - - BE->>BE: Validate input & uniqueness - BE->>DB: BEGIN TRANSACTION - BE->>DB: INSERT Organization (tenant_id=UUIDv4, created_by=A.user_id) - DB-->>BE: org_id, tenant_id - BE->>DB: INSERT User (pending, is_active=false, tenant_id) - DB-->>BE: user_id - BE->>DB: INSERT PermissionAllowlist (inactive, optional) - DB-->>BE: allowlist_ids - - %% --- Keycloak provisioning --- - BE->>KC: POST /admin/realms//users {username,email, attributes:{tenant_id,bic}} - KC-->>BE: 201 Created (kc_user_id) - BE->>KC: PUT /users/{kc_user_id}/reset-password {value:, temporary:true|false} - KC-->>BE: 204 No Content - BE->>KC: POST /users/{kc_user_id}/role-mappings/... {roles[]} - KC-->>BE: 204 No Content - BE->>KC: GET /users/{kc_user_id} - KC-->>BE: 200 OK (verify attributes) - - %% --- Finalize DB --- - BE->>DB: UPDATE User SET is_active=true, role_id/roles=… - BE->>DB: UPDATE PermissionAllowlist SET active=true - BE->>DB: COMMIT - - BE-->>FE: 201 Created (org_id, tenant_id, user_id, kc_user_id) - FE-->>A: Success (organization + initial user onboarded) - - %% --- Error handling --- - rect rgb(255,245,245) - note over BE,KC: If Keycloak fails - BE->>DB: ROLLBACK - BE-->>FE: 409/422 Error - end - - rect rgb(255,245,245) - note over DB,BE: If DB commit fails after KC success - BE->>KC: DELETE /users/{kc_user_id} (best effort) - BE-->>FE: 500 Error + alert - end \ No newline at end of file +classDiagram + class ORGANIZATION { + +uuid id + +uuid tenant_id + +string name + +string bic + +uuid api_key_id + +uuid created_by + +datetime created_at + +datetime updated_at + } + + class USER { + +uuid id + +uuid tenant_id + +uuid org_id + +string email + +string username + +string role_id + +boolean is_active + +uuid created_by + +datetime created_at + +datetime updated_at + } + + class TRANSACTION { + +uuid id + +uuid tenant_id + +uuid org_id + +uuid created_by + +string payload + +string status + +datetime created_at + } + + class WALLET_LIST { + +uuid tenant_id <> + +uuid id <> + +uuid org_id + +string address + +string label + +string network + +boolean is_active + +datetime created_at + } + + class CONTRACT_LIST { + +uuid tenant_id <> + +uuid id <> + +uuid org_id + +string address + +string label + +string chain_id + +boolean is_active + +datetime created_at + } + + class PERMISSION { + +uuid tenant_id <> + +uuid id <> + +uuid org_id + +uuid created_by + +uuid wallet_id + +uuid contract_id + +int amount + +int type_tx + +string label + +boolean is_active + +datetime created_at + } + + ORGANIZATION "1" --> "many" USER : has + ORGANIZATION "1" --> "many" TRANSACTION : has + ORGANIZATION "1" --> "many" WALLET_LIST : has + ORGANIZATION "1" --> "many" CONTRACT_LIST : has + + USER "1" --> "many" TRANSACTION : created_by + USER "1" --> "many" PERMISSION : created_by + + WALLET_LIST "1" --> "many" PERMISSION : wallet_id + CONTRACT_LIST "1" --> "many" PERMISSION : contract_id \ No newline at end of file From 4e48c951922a45fccfeb596f12cd78a5be1427a8 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 7 Oct 2025 09:04:17 +0000 Subject: [PATCH 71/93] Atualizar o test --- test | 118 ++++++++++++++++++++++++----------------------------------- 1 file changed, 48 insertions(+), 70 deletions(-) diff --git a/test b/test index 300c7bc..229041f 100644 --- a/test +++ b/test @@ -1,81 +1,59 @@ -classDiagram - class ORGANIZATION { - +uuid id - +uuid tenant_id - +string name - +string bic - +uuid api_key_id - +uuid created_by - +datetime created_at - +datetime updated_at +erDiagram + ORGANIZATION { + uuid id PK + string name + string bic + uuid api_key_id + uuid created_by "user_id (optional)" + datetime created_at + datetime updated_at } - class USER { - +uuid id - +uuid tenant_id - +uuid org_id - +string email - +string username - +string role_id - +boolean is_active - +uuid created_by - +datetime created_at - +datetime updated_at + "USER" { + uuid id PK + uuid org_id FK "belongs to ORGANIZATION (tenant)" + string email + string username + string role_id "Keycloak role name" + boolean is_active + uuid created_by "user_id (optional)" + datetime created_at + datetime updated_at } - class TRANSACTION { - +uuid id - +uuid tenant_id - +uuid org_id - +uuid created_by - +string payload - +string status - +datetime created_at + WALLET_ALLOW_LIST { + uuid id PK + uuid user_id FK "owner (extends USER)" + string address + string label + string network + boolean is_active + datetime created_at } - class WALLET_LIST { - +uuid tenant_id <> - +uuid id <> - +uuid org_id - +string address - +string label - +string network - +boolean is_active - +datetime created_at + CONTRACT_ALLOW_LIST { + uuid id PK + uuid user_id FK "owner (extends USER)" + string address + string label + string chain_id + boolean is_active + datetime created_at } - class CONTRACT_LIST { - +uuid tenant_id <> - +uuid id <> - +uuid org_id - +string address - +string label - +string chain_id - +boolean is_active - +datetime created_at + TRANSACTION { + uuid id PK + uuid org_id FK "scoped to ORGANIZATION" + uuid created_by FK "user_id" + string payload "JSON as text" + string status "confirmed|failed" + datetime created_at } - class PERMISSION { - +uuid tenant_id <> - +uuid id <> - +uuid org_id - +uuid created_by - +uuid wallet_id - +uuid contract_id - +int amount - +int type_tx - +string label - +boolean is_active - +datetime created_at - } - - ORGANIZATION "1" --> "many" USER : has - ORGANIZATION "1" --> "many" TRANSACTION : has - ORGANIZATION "1" --> "many" WALLET_LIST : has - ORGANIZATION "1" --> "many" CONTRACT_LIST : has - - USER "1" --> "many" TRANSACTION : created_by - USER "1" --> "many" PERMISSION : created_by + %% --------- Relationships ---------- + ORGANIZATION ||--o{ "USER" : has + "USER" ||--o{ WALLET_ALLOW_LIST : owns_wallets + "USER" ||--o{ CONTRACT_ALLOW_LIST : owns_contracts - WALLET_LIST "1" --> "many" PERMISSION : wallet_id - CONTRACT_LIST "1" --> "many" PERMISSION : contract_id \ No newline at end of file + ORGANIZATION ||--o{ TRANSACTION : has_many + "USER" ||--o{ TRANSACTION : created_by \ No newline at end of file From 2abd2230eede04f7fcb5089427ffdf7da82d79c4 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 7 Oct 2025 09:12:31 +0000 Subject: [PATCH 72/93] Atualizar o test --- test | 58 +++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/test b/test index 229041f..dff3e94 100644 --- a/test +++ b/test @@ -4,56 +4,80 @@ erDiagram string name string bic uuid api_key_id - uuid created_by "user_id (optional)" datetime created_at datetime updated_at } "USER" { uuid id PK - uuid org_id FK "belongs to ORGANIZATION (tenant)" + uuid org_id FK "belongs to ORGANIZATION" string email string username - string role_id "Keycloak role name" + string role_id boolean is_active - uuid created_by "user_id (optional)" datetime created_at datetime updated_at } - WALLET_ALLOW_LIST { + CONTRACT_LIST { uuid id PK - uuid user_id FK "owner (extends USER)" + uuid org_id FK "eligible contracts for this org" string address string label - string network + string chain_id boolean is_active datetime created_at } - CONTRACT_ALLOW_LIST { + WALLET_LIST { uuid id PK - uuid user_id FK "owner (extends USER)" + uuid org_id FK "eligible wallets for this org" string address string label - string chain_id + string network + boolean is_active + datetime created_at + } + + USER_CONTRACT_ALLOW { + uuid id PK + uuid user_id FK + uuid contract_id FK + boolean is_active + datetime created_at + } + + USER_WALLET_ALLOW { + uuid id PK + uuid user_id FK + uuid wallet_id FK boolean is_active datetime created_at } TRANSACTION { uuid id PK - uuid org_id FK "scoped to ORGANIZATION" - uuid created_by FK "user_id" - string payload "JSON as text" - string status "confirmed|failed" + uuid org_id FK + uuid created_by FK "user_id" + string payload "JSON as text" + string status "confirmed|failed" datetime created_at } - %% --------- Relationships ---------- + %% ---- Catalog ownership by org + ORGANIZATION ||--o{ CONTRACT_LIST : catalogs + ORGANIZATION ||--o{ WALLET_LIST : catalogs + + %% ---- Users in org ORGANIZATION ||--o{ "USER" : has - "USER" ||--o{ WALLET_ALLOW_LIST : owns_wallets - "USER" ||--o{ CONTRACT_ALLOW_LIST : owns_contracts + %% ---- Per-user allow mappings + "USER" ||--o{ USER_CONTRACT_ALLOW : can_use_contract + CONTRACT_LIST ||--o{ USER_CONTRACT_ALLOW : contract + + "USER" ||--o{ USER_WALLET_ALLOW : can_use_wallet + WALLET_LIST ||--o{ USER_WALLET_ALLOW : wallet + + %% ---- Transactions ORGANIZATION ||--o{ TRANSACTION : has_many "USER" ||--o{ TRANSACTION : created_by \ No newline at end of file From fec6dd7e10205e9a8b840b0c27cc75f8c788aa8e Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 12 Oct 2025 15:43:16 +0200 Subject: [PATCH 73/93] Atualizar o test --- test | 113 ++++++++++++++++------------------------------------------- 1 file changed, 30 insertions(+), 83 deletions(-) diff --git a/test b/test index dff3e94..c78570b 100644 --- a/test +++ b/test @@ -1,83 +1,30 @@ -erDiagram - ORGANIZATION { - uuid id PK - string name - string bic - uuid api_key_id - datetime created_at - datetime updated_at - } - - "USER" { - uuid id PK - uuid org_id FK "belongs to ORGANIZATION" - string email - string username - string role_id - boolean is_active - datetime created_at - datetime updated_at - } - - CONTRACT_LIST { - uuid id PK - uuid org_id FK "eligible contracts for this org" - string address - string label - string chain_id - boolean is_active - datetime created_at - } - - WALLET_LIST { - uuid id PK - uuid org_id FK "eligible wallets for this org" - string address - string label - string network - boolean is_active - datetime created_at - } - - USER_CONTRACT_ALLOW { - uuid id PK - uuid user_id FK - uuid contract_id FK - boolean is_active - datetime created_at - } - - USER_WALLET_ALLOW { - uuid id PK - uuid user_id FK - uuid wallet_id FK - boolean is_active - datetime created_at - } - - TRANSACTION { - uuid id PK - uuid org_id FK - uuid created_by FK "user_id" - string payload "JSON as text" - string status "confirmed|failed" - datetime created_at - } - - %% ---- Catalog ownership by org - ORGANIZATION ||--o{ CONTRACT_LIST : catalogs - ORGANIZATION ||--o{ WALLET_LIST : catalogs - - %% ---- Users in org - ORGANIZATION ||--o{ "USER" : has - - %% ---- Per-user allow mappings - "USER" ||--o{ USER_CONTRACT_ALLOW : can_use_contract - CONTRACT_LIST ||--o{ USER_CONTRACT_ALLOW : contract - - "USER" ||--o{ USER_WALLET_ALLOW : can_use_wallet - WALLET_LIST ||--o{ USER_WALLET_ALLOW : wallet - - %% ---- Transactions - ORGANIZATION ||--o{ TRANSACTION : has_many - "USER" ||--o{ TRANSACTION : created_by \ No newline at end of file +Provide participating banks with secure access to the Paladin and Validium test environments through a centralized Identity and Access Management (IAM) layer. +This IAM layer ensures minimum viable security for authentication (AuthN) and authorization (AuthZ) by integrating an Identity Provider (IdP) service — Keycloak — and enabling Single Sign-On (SSO) across all services. + +The goal is to establish a standardized, test-ready access control framework that simulates production-grade security principles while maintaining operational simplicity during integration and evaluation phases. + +⸻ + +Scope + • Applies to all participants (banks) accessing Paladin and Validium environments. + • Covers user identity lifecycle, authentication, and authorization across all APIs, dashboards, and backend services. + • Ensures each participant has isolated identity domains (realms) with centralized policies. + +⸻ + +Architecture Overview + 1. Identity Provider (IdP) + • Keycloak acts as the central IdP, managing identities for all participant organizations. + • Each bank has a dedicated realm or organizational group for identity isolation. + • Supports federated login if the participant prefers to use its own corporate IdP (via SAML/OIDC). + 2. Authentication (AuthN) + • Users authenticate through Keycloak’s SSO portal. + • Supports password, MFA, and token-based authentication. + • Session tokens (JWT/OAuth2) are issued and validated by backend services. + 3. Authorization (AuthZ) + • Role-Based Access Control (RBAC) defines user privileges (e.g., Admin, Auditor, Operator). + • Access tokens include roles and organization claims for service-level enforcement. + • Backend microservices validate the JWT using the Keycloak JWKS endpoint. + 4. SSO Integration + • All web and API services (Paladin, Validium, and auxiliary dashboards) integrate with Keycloak for SSO. + • Once authenticated, the user can access all authorized systems without re-login. From f0745a1d5318109eba81d587736af398d73b9585 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 12 Oct 2025 16:17:45 +0200 Subject: [PATCH 74/93] Atualizar o test --- test | 31 +------------------------------ 1 file changed, 1 insertion(+), 30 deletions(-) diff --git a/test b/test index c78570b..1c52f91 100644 --- a/test +++ b/test @@ -1,30 +1 @@ -Provide participating banks with secure access to the Paladin and Validium test environments through a centralized Identity and Access Management (IAM) layer. -This IAM layer ensures minimum viable security for authentication (AuthN) and authorization (AuthZ) by integrating an Identity Provider (IdP) service — Keycloak — and enabling Single Sign-On (SSO) across all services. - -The goal is to establish a standardized, test-ready access control framework that simulates production-grade security principles while maintaining operational simplicity during integration and evaluation phases. - -⸻ - -Scope - • Applies to all participants (banks) accessing Paladin and Validium environments. - • Covers user identity lifecycle, authentication, and authorization across all APIs, dashboards, and backend services. - • Ensures each participant has isolated identity domains (realms) with centralized policies. - -⸻ - -Architecture Overview - 1. Identity Provider (IdP) - • Keycloak acts as the central IdP, managing identities for all participant organizations. - • Each bank has a dedicated realm or organizational group for identity isolation. - • Supports federated login if the participant prefers to use its own corporate IdP (via SAML/OIDC). - 2. Authentication (AuthN) - • Users authenticate through Keycloak’s SSO portal. - • Supports password, MFA, and token-based authentication. - • Session tokens (JWT/OAuth2) are issued and validated by backend services. - 3. Authorization (AuthZ) - • Role-Based Access Control (RBAC) defines user privileges (e.g., Admin, Auditor, Operator). - • Access tokens include roles and organization claims for service-level enforcement. - • Backend microservices validate the JWT using the Keycloak JWKS endpoint. - 4. SSO Integration - • All web and API services (Paladin, Validium, and auxiliary dashboards) integrate with Keycloak for SSO. - • Once authenticated, the user can access all authorized systems without re-login. +The authentication process is handled through Keycloak’s Single Sign-On (SSO) portal using the OpenID Connect (OIDC) protocol. When a user logs in, Keycloak validates the credentials and issues a set of session tokens based on OAuth 2.0 standards—an ID token for user identity and an access token for authorization. These tokens, encoded as JWTs, are included in subsequent API requests to the Validium and Paladin services. Each backend service validates the token’s signature and claims through Keycloak’s JWKS endpoint, ensuring secure, centralized authentication and authorization across all components in the shared environment. \ No newline at end of file From 35135e3e7cf841fd364272214c4c1831c8d81ce0 Mon Sep 17 00:00:00 2001 From: Arthur Date: Sun, 12 Oct 2025 16:33:12 +0200 Subject: [PATCH 75/93] Atualizar o test --- test | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/test b/test index 1c52f91..99fb47c 100644 --- a/test +++ b/test @@ -1 +1,9 @@ -The authentication process is handled through Keycloak’s Single Sign-On (SSO) portal using the OpenID Connect (OIDC) protocol. When a user logs in, Keycloak validates the credentials and issues a set of session tokens based on OAuth 2.0 standards—an ID token for user identity and an access token for authorization. These tokens, encoded as JWTs, are included in subsequent API requests to the Validium and Paladin services. Each backend service validates the token’s signature and claims through Keycloak’s JWKS endpoint, ensuring secure, centralized authentication and authorization across all components in the shared environment. \ No newline at end of file +Authentication Flow + +The authentication process is managed through Keycloak’s Single Sign-On (SSO) portal using the OpenID Connect (OIDC) protocol. When a user logs in, Keycloak validates the provided credentials and issues a set of session tokens based on OAuth 2.0 standards. These include an ID token that contains user identity claims and an access token used to request access to protected resources. Both tokens are encoded as JWTs and securely transmitted to the client application for use in subsequent API interactions. + +⸻ + +Authorization Flow + +Once authentication is complete, the issued access token is attached to each API request sent to the Validium and Paladin backend services. These services validate the token’s signature and claims through Keycloak’s JWKS endpoint to ensure its authenticity and integrity. Authorization decisions are then enforced based on the token’s embedded roles, scopes, and organizational claims (such as org_id or bic). This centralized model ensures consistent, role-based access control and secure interaction between all components within the shared environment. \ No newline at end of file From 298885f4b17379af0685c1fddfd519b365d24cb2 Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 13 Oct 2025 12:45:07 +0200 Subject: [PATCH 76/93] Atualizar o test --- test | 46 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/test b/test index 99fb47c..5db1f17 100644 --- a/test +++ b/test @@ -1,9 +1,45 @@ -Authentication Flow +sequenceDiagram + autonumber + title OIDC Authentication & MFA Flow (Validium/Paladin with Keycloak) -The authentication process is managed through Keycloak’s Single Sign-On (SSO) portal using the OpenID Connect (OIDC) protocol. When a user logs in, Keycloak validates the provided credentials and issues a set of session tokens based on OAuth 2.0 standards. These include an ID token that contains user identity claims and an access token used to request access to protected resources. Both tokens are encoded as JWTs and securely transmitted to the client application for use in subsequent API interactions. + participant B as User Browser + participant I as Ingress/NGINX + participant F as Frontend (SPA / Portal) + participant A as Backend (OIDC Client/API) + participant K as Keycloak (IdP) -⸻ + Note over F,A: Protected resource requested -Authorization Flow + B->>I: GET /app + I->>F: Serve app (no session) -Once authentication is complete, the issued access token is attached to each API request sent to the Validium and Paladin backend services. These services validate the token’s signature and claims through Keycloak’s JWKS endpoint to ensure its authenticity and integrity. Authorization decisions are then enforced based on the token’s embedded roles, scopes, and organizational claims (such as org_id or bic). This centralized model ensures consistent, role-based access control and secure interaction between all components within the shared environment. \ No newline at end of file + F-->>B: Redirect to Login (OIDC) + B->>K: GET /auth/realms//protocol/openid-connect/auth
?client_id=&response_type=code&scope=openid
&redirect_uri=&code_challenge=&code_challenge_method=S256 + + K-->>B: Render login page + + B->>K: POST credentials (username/password) + + alt MFA required (per user/group/policy) + K-->>B: Prompt MFA (TOTP / WebAuthn / SMS/Email) + B->>K: Submit second factor + K-->>K: Validate 2nd factor + else MFA not required + K-->>K: Continue flow + end + + K-->>B: 302 Redirect to ?code=&state= + B->>A: GET ?code=&state= + + A->>K: POST /protocol/openid-connect/token
grant_type=authorization_code
code=
redirect_uri=
client_id=
code_verifier= + K-->>A: 200 { access_token (JWT), id_token (JWT), refresh_token } + + A-->>A: Validate JWT (iss, aud, exp) via JWKS + A-->>F: Set app session / issue app cookie (httpOnly/SameSite) + F-->>B: App dashboard + + B->>A: Subsequent API calls with Authorization: Bearer + A-->>A: Enforce AuthZ (roles/scopes + org_id/bic claims) + A-->>B: 200 Response (authorized) + + Note over K: OIDC session managed by Keycloak (SSO) \ No newline at end of file From 64c5c8500277b48ee34a08eaf32a97ac7ed7f7f5 Mon Sep 17 00:00:00 2001 From: Arthur Date: Mon, 13 Oct 2025 13:13:06 +0200 Subject: [PATCH 77/93] Atualizar o test --- test | 47 ++--------------------------------------------- 1 file changed, 2 insertions(+), 45 deletions(-) diff --git a/test b/test index 5db1f17..d287cf7 100644 --- a/test +++ b/test @@ -1,45 +1,2 @@ -sequenceDiagram - autonumber - title OIDC Authentication & MFA Flow (Validium/Paladin with Keycloak) - - participant B as User Browser - participant I as Ingress/NGINX - participant F as Frontend (SPA / Portal) - participant A as Backend (OIDC Client/API) - participant K as Keycloak (IdP) - - Note over F,A: Protected resource requested - - B->>I: GET /app - I->>F: Serve app (no session) - - F-->>B: Redirect to Login (OIDC) - B->>K: GET /auth/realms//protocol/openid-connect/auth
?client_id=&response_type=code&scope=openid
&redirect_uri=&code_challenge=&code_challenge_method=S256 - - K-->>B: Render login page - - B->>K: POST credentials (username/password) - - alt MFA required (per user/group/policy) - K-->>B: Prompt MFA (TOTP / WebAuthn / SMS/Email) - B->>K: Submit second factor - K-->>K: Validate 2nd factor - else MFA not required - K-->>K: Continue flow - end - - K-->>B: 302 Redirect to ?code=&state= - B->>A: GET ?code=&state= - - A->>K: POST /protocol/openid-connect/token
grant_type=authorization_code
code=
redirect_uri=
client_id=
code_verifier= - K-->>A: 200 { access_token (JWT), id_token (JWT), refresh_token } - - A-->>A: Validate JWT (iss, aud, exp) via JWKS - A-->>F: Set app session / issue app cookie (httpOnly/SameSite) - F-->>B: App dashboard - - B->>A: Subsequent API calls with Authorization: Bearer - A-->>A: Enforce AuthZ (roles/scopes + org_id/bic claims) - A-->>B: 200 Response (authorized) - - Note over K: OIDC session managed by Keycloak (SSO) \ No newline at end of file +Multi-Factor Authentication (MFA) via OIDC +To enhance access security, the IAM layer integrates Multi-Factor Authentication (MFA) into the OpenID Connect (OIDC) flow through Keycloak. This approach adds an extra verification step beyond the standard username and password, ensuring that only verified users can access the Paladin and Validium environments. During the OIDC login process, Keycloak performs primary authentication using credentials or a federated IdP, followed by a secondary verification factor before issuing tokens. Supported MFA methods include TOTP codes generated by authenticator apps (such as Google or Microsoft Authenticator), as well as email or SMS-based verification, providing a robust and seamless security layer aligned with enterprise authentication standards \ No newline at end of file From e655102dd0bbefc7415110f6de60473d696d4a8b Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 14 Oct 2025 15:56:15 +0200 Subject: [PATCH 78/93] Atualizar o test --- test | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/test b/test index d287cf7..32af9f8 100644 --- a/test +++ b/test @@ -1,2 +1,42 @@ -Multi-Factor Authentication (MFA) via OIDC -To enhance access security, the IAM layer integrates Multi-Factor Authentication (MFA) into the OpenID Connect (OIDC) flow through Keycloak. This approach adds an extra verification step beyond the standard username and password, ensuring that only verified users can access the Paladin and Validium environments. During the OIDC login process, Keycloak performs primary authentication using credentials or a federated IdP, followed by a secondary verification factor before issuing tokens. Supported MFA methods include TOTP codes generated by authenticator apps (such as Google or Microsoft Authenticator), as well as email or SMS-based verification, providing a robust and seamless security layer aligned with enterprise authentication standards \ No newline at end of file +Identity & Access Management (IAM) – Requirements + +1. Identity Provider (IdP) + • Keycloak is the central IdP managing authentication and authorization for all participants. + • A single realm per environment (e.g., dev, test, prod) hosts all organizations (banks). + • Each organization is represented by a group or attribute (tenant_id, org_id, bic) within the realm. + • Clients (applications) are registered in Keycloak and authenticate using client_id and client_secret. + +⸻ + +2. Authentication (AuthN) + • Authentication is handled via OpenID Connect (OIDC) protocol. + • Single Sign-On (SSO) is enabled for Paladin and Validium applications through Keycloak. + • Keycloak validates user credentials and issues: + • ID Token → contains identity claims (username, roles, org, etc.) + • Access Token → used to request access to protected APIs + • Tokens are JWT-encoded and signed; validated by services via JWKS endpoint. + • Support for federated login (optional) via external IdPs if needed. + • Password policy enforcement (complexity, expiration, lockout). + +⸻ + +3. Multi-Factor Authentication (MFA) + • MFA integrated into OIDC login flow through Keycloak. + • Enforced per user/group or globally per realm. + • Supported methods: + • TOTP codes (Google or Microsoft Authenticator) + • Email or SMS verification (requires SMTP/SMS gateway configuration) + • Step-up MFA required for sensitive actions or admin roles. + +⸻ + +4. Authorization (AuthZ) + • Implement Role-Based Access Control (RBAC) via Keycloak realm roles: + • admin → Full access (all tenants, can register new organizations) + • auditor → Read-only access to organization data + • operator → Read/write access limited to own organization (tenant) + • Backend services validate: + • JWT signature (via JWKS) + • Token expiry, issuer, and audience + • Embedded claims (tenant_id, org_id, bic, roles, scopes) + • Centralized enforcement ensures consistent and secure access across Paladin and Validium. \ No newline at end of file From 7959bfcf08b37f6546cb21521d287f57cb029679 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 14 Oct 2025 16:55:38 +0200 Subject: [PATCH 79/93] Atualizar o test --- test | 62 +++++++++++++++++++++++++++--------------------------------- 1 file changed, 28 insertions(+), 34 deletions(-) diff --git a/test b/test index 32af9f8..6544e41 100644 --- a/test +++ b/test @@ -1,42 +1,36 @@ -Identity & Access Management (IAM) – Requirements +Identity & Access Management (IAM) Requirements -1. Identity Provider (IdP) - • Keycloak is the central IdP managing authentication and authorization for all participants. - • A single realm per environment (e.g., dev, test, prod) hosts all organizations (banks). - • Each organization is represented by a group or attribute (tenant_id, org_id, bic) within the realm. - • Clients (applications) are registered in Keycloak and authenticate using client_id and client_secret. +Infrastructure Configuration + • ✅ Setup Keycloak service as the central IdP managing AuthN (authentication) and AuthZ (authorization) for Paladin and Validium participants. + • ✅ Expose Keycloak BackOffice endpoint over TLS and share admin credentials securely. + • ✅ Setup SMTP server for 2FA (email verification) in authentication flow. ⸻ -2. Authentication (AuthN) - • Authentication is handled via OpenID Connect (OIDC) protocol. - • Single Sign-On (SSO) is enabled for Paladin and Validium applications through Keycloak. - • Keycloak validates user credentials and issues: - • ID Token → contains identity claims (username, roles, org, etc.) - • Access Token → used to request access to protected APIs - • Tokens are JWT-encoded and signed; validated by services via JWKS endpoint. - • Support for federated login (optional) via external IdPs if needed. - • Password policy enforcement (complexity, expiration, lockout). +🛠 Keycloak BackOffice Configuration + • ✅ A single realm per environment (e.g., test, prod) hosts all organizations. + • ✅ Each organization is represented by a group or attribute (org_id, bic, tenant_id) within the realm. + • ✅ Clients (applications) are registered in Keycloak and authenticate using client_id and client_secret via OpenID Connect (OIDC) protocol. +🟢 (Your original line was fine; I just corrected “clients d” → “client_id”). + • ✅ Authentication handled via OIDC protocol (no PKCE). + • ✅ Single Sign-On (SSO) enabled for Paladin and Validium applications through Keycloak. + • ✅ Keycloak validates user credentials and issues: + • ID Token containing identity claims (username, roles, org, bic, etc.) + • Access Token used to request access to protected APIs + • ✅ Tokens are JWT-encoded and signed; validated by backend services using Keycloak’s JWKS endpoint. + • ✅ Two-Factor Authentication (2FA) integrated into the OIDC login flow through Keycloak and enforced per user or per realm. + • ✅ 2FA supports email verification (requires SMTP server configuration). + • ✅ Mapped Role-Based Access Control (RBAC) via Keycloak realm roles: + • admin, auditor, and operator. ⸻ -3. Multi-Factor Authentication (MFA) - • MFA integrated into OIDC login flow through Keycloak. - • Enforced per user/group or globally per realm. - • Supported methods: - • TOTP codes (Google or Microsoft Authenticator) - • Email or SMS verification (requires SMTP/SMS gateway configuration) - • Step-up MFA required for sensitive actions or admin roles. +✅ Summary -⸻ - -4. Authorization (AuthZ) - • Implement Role-Based Access Control (RBAC) via Keycloak realm roles: - • admin → Full access (all tenants, can register new organizations) - • auditor → Read-only access to organization data - • operator → Read/write access limited to own organization (tenant) - • Backend services validate: - • JWT signature (via JWKS) - • Token expiry, issuer, and audience - • Embedded claims (tenant_id, org_id, bic, roles, scopes) - • Centralized enforcement ensures consistent and secure access across Paladin and Validium. \ No newline at end of file +✅ Your list covers all essential Keycloak minimum requirements for: + • Centralized IdP setup + • OIDC client registration (client_id/client_secret) + • JWT issuance and validation + • SSO and MFA + • Role-based access control + • Secure endpoint and SMTP setup \ No newline at end of file From b29e8d2862d1196db2e098f96bd63cb6ddd2ff4a Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 22 Oct 2025 13:05:42 +0200 Subject: [PATCH 80/93] Atualizar o test --- test | 37 +------------------------------------ 1 file changed, 1 insertion(+), 36 deletions(-) diff --git a/test b/test index 6544e41..638ce80 100644 --- a/test +++ b/test @@ -1,36 +1 @@ -Identity & Access Management (IAM) Requirements - -Infrastructure Configuration - • ✅ Setup Keycloak service as the central IdP managing AuthN (authentication) and AuthZ (authorization) for Paladin and Validium participants. - • ✅ Expose Keycloak BackOffice endpoint over TLS and share admin credentials securely. - • ✅ Setup SMTP server for 2FA (email verification) in authentication flow. - -⸻ - -🛠 Keycloak BackOffice Configuration - • ✅ A single realm per environment (e.g., test, prod) hosts all organizations. - • ✅ Each organization is represented by a group or attribute (org_id, bic, tenant_id) within the realm. - • ✅ Clients (applications) are registered in Keycloak and authenticate using client_id and client_secret via OpenID Connect (OIDC) protocol. -🟢 (Your original line was fine; I just corrected “clients d” → “client_id”). - • ✅ Authentication handled via OIDC protocol (no PKCE). - • ✅ Single Sign-On (SSO) enabled for Paladin and Validium applications through Keycloak. - • ✅ Keycloak validates user credentials and issues: - • ID Token containing identity claims (username, roles, org, bic, etc.) - • Access Token used to request access to protected APIs - • ✅ Tokens are JWT-encoded and signed; validated by backend services using Keycloak’s JWKS endpoint. - • ✅ Two-Factor Authentication (2FA) integrated into the OIDC login flow through Keycloak and enforced per user or per realm. - • ✅ 2FA supports email verification (requires SMTP server configuration). - • ✅ Mapped Role-Based Access Control (RBAC) via Keycloak realm roles: - • admin, auditor, and operator. - -⸻ - -✅ Summary - -✅ Your list covers all essential Keycloak minimum requirements for: - • Centralized IdP setup - • OIDC client registration (client_id/client_secret) - • JWT issuance and validation - • SSO and MFA - • Role-based access control - • Secure endpoint and SMTP setup \ No newline at end of file +The Keycloak Service is the central Identity and Access Management (IAM) and Identity Provider (IdP) of the system, managing authentication (AuthN) and authorization (AuthZ) for all applications. It offers a unified login page and uses the OpenID Connect (OIDC) protocol for secure token-based access. Keycloak integrates with the Mock Backoffice Application to authenticate users, issue tokens, and enforce consistent access policies through defined realms, roles, and groups. \ No newline at end of file From a23678bedc8980b073e6e78f0839e2858bfeff29 Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 23 Oct 2025 16:49:02 +0200 Subject: [PATCH 81/93] Update Keycloak Service description in test file --- test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test b/test index 638ce80..0c43291 100644 --- a/test +++ b/test @@ -1 +1 @@ -The Keycloak Service is the central Identity and Access Management (IAM) and Identity Provider (IdP) of the system, managing authentication (AuthN) and authorization (AuthZ) for all applications. It offers a unified login page and uses the OpenID Connect (OIDC) protocol for secure token-based access. Keycloak integrates with the Mock Backoffice Application to authenticate users, issue tokens, and enforce consistent access policies through defined realms, roles, and groups. \ No newline at end of file +The Mock Back Office application integrates with the RBAC Middleware via REST API. Once a user session is created, the system retrieves the corresponding API key from AWS Secret Manager based on the user’s role, enabling authorized access to the RBAC Middleware. From 4126126a510c5901e21dfd587fadd6e51540b532 Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 23 Oct 2025 17:10:21 +0200 Subject: [PATCH 82/93] Update test --- test | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/test b/test index 0c43291..e879f45 100644 --- a/test +++ b/test @@ -1 +1,10 @@ -The Mock Back Office application integrates with the RBAC Middleware via REST API. Once a user session is created, the system retrieves the corresponding API key from AWS Secret Manager based on the user’s role, enabling authorized access to the RBAC Middleware. +The Mock Back Office delegates deposit, tokenization, redemption, and settlement flows to the RBAC Middleware, which is responsible for interacting directly with the Validium network. + +To integrate, the Mock Back Office application connects to the RBAC Middleware via REST API. Once a user session is created, it retrieves the corresponding API key from AWS Secret Manager according to the user’s role, enabling secure and authorized access. + + + + +==== + +The service, developed by ConsenSys, is implemented in TypeScript with modular controllers and services designed for high availability and security. Controllers perform schema validation and enforce RBAC logic, while the service layer uses ethers.js (v6) to connect directly to Validium L2 RPC nodes and interact with smart contracts such as TokenBridge, ERC20/3643, and Settlement. The atomic swap settlement flow leverages EIP-712 typed data for deterministic signing and verification of cross-party transactions. Transactions are relayed through configured providers with explicit nonce control, gas management, and robust error handling. From 44180174bd052a85c4c808fb7fdb8f9be62bcaab Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 12 Nov 2025 13:00:08 +0100 Subject: [PATCH 83/93] Update Validium Technical Design document with clarifications Added detailed clarifications and updates to the Validium Technical Design document based on the latest internal review. Sections include finality, execution nodes, storage verification, and block explorer access control. --- test | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test b/test index e879f45..bc1b5a6 100644 --- a/test +++ b/test @@ -1,10 +1,21 @@ -The Mock Back Office delegates deposit, tokenization, redemption, and settlement flows to the RBAC Middleware, which is responsible for interacting directly with the Validium network. +Hi team, -To integrate, the Mock Back Office application connects to the RBAC Middleware via REST API. Once a user session is created, it retrieves the corresponding API key from AWS Secret Manager according to the user’s role, enabling secure and authorized access. +Following the latest internal review of the Validium Technical Design document, please find below the main sections that require clarification or complementary detail. These updates should be reflected in the next iteration of the application and infrastructure design. +1. Finality (Tracing, Proving, Posting) +Include a description of the Web3Signer component — how it integrates into the finality process and whether any security mechanism (HSM, KMS, or Secret Manager) is used to store and protect private keys used for transaction signing. +2. Execution / Linea Nodes -==== +Describe the roles of the three RPC node components — Forest Full Node, Bonsai Node, and Geth Client (Archive). Explain the purpose of each, how read/write operations are optimized, and how the Caddy proxy is used in this setup. -The service, developed by ConsenSys, is implemented in TypeScript with modular controllers and services designed for high availability and security. Controllers perform schema validation and enforce RBAC logic, while the service layer uses ethers.js (v6) to connect directly to Validium L2 RPC nodes and interact with smart contracts such as TokenBridge, ERC20/3643, and Settlement. The atomic swap settlement flow leverages EIP-712 typed data for deterministic signing and verification of cross-party transactions. Transactions are relayed through configured providers with explicit nonce control, gas management, and robust error handling. +3. Storage / Verification (Data Availability) + +Clarify the rationale for adopting EigenDA — how it operates as a data availability layer, associated costs and dependencies, and why an external cloud solution was preferred over hosting within AWS for security and compliance. + +4. Validium Block Explorer + +4.1 Solution Design: Specify whether the proposed solution is Blockscout or custom-built, how the indexing process is configured (parameters, database). + +4.2 Access Control: Describe how access control will be implemented so that each entity can only view its own transactions. From 17bc5a5bec1383fdde881330edbc25b13421f141 Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 20 Nov 2025 12:02:10 +0100 Subject: [PATCH 84/93] Atualizar o test --- test | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/test b/test index bc1b5a6..b3dd11d 100644 --- a/test +++ b/test @@ -1,21 +1,4 @@ -Hi team, - -Following the latest internal review of the Validium Technical Design document, please find below the main sections that require clarification or complementary detail. These updates should be reflected in the next iteration of the application and infrastructure design. - -1. Finality (Tracing, Proving, Posting) - -Include a description of the Web3Signer component — how it integrates into the finality process and whether any security mechanism (HSM, KMS, or Secret Manager) is used to store and protect private keys used for transaction signing. - -2. Execution / Linea Nodes - -Describe the roles of the three RPC node components — Forest Full Node, Bonsai Node, and Geth Client (Archive). Explain the purpose of each, how read/write operations are optimized, and how the Caddy proxy is used in this setup. - -3. Storage / Verification (Data Availability) - -Clarify the rationale for adopting EigenDA — how it operates as a data availability layer, associated costs and dependencies, and why an external cloud solution was preferred over hosting within AWS for security and compliance. - -4. Validium Block Explorer - -4.1 Solution Design: Specify whether the proposed solution is Blockscout or custom-built, how the indexing process is configured (parameters, database). - -4.2 Access Control: Describe how access control will be implemented so that each entity can only view its own transactions. +Hi team, I’ll be updating some points: + • Update the diagram considering our custom login page instead of Keycloak. + • Include more details in the infrastructure section regarding high availability and data availability. + • Explain how data segregation is structured (realm, database). \ No newline at end of file From 27bc6b0cccb05a557be6c77aab4fa5cd107a150e Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 20 Nov 2025 18:31:08 +0100 Subject: [PATCH 85/93] Atualizar o test --- test | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test b/test index b3dd11d..32d3943 100644 --- a/test +++ b/test @@ -1,4 +1,3 @@ -Hi team, I’ll be updating some points: - • Update the diagram considering our custom login page instead of Keycloak. - • Include more details in the infrastructure section regarding high availability and data availability. - • Explain how data segregation is structured (realm, database). \ No newline at end of file +Title: Data Segregation Strategy + +PostgreSQL data segregation is implemented by isolating each tenant’s information into its own database, ensuring that schemas, tables, and data remain fully separated at the storage and access-control level. This physical separation eliminates the risk of cross-tenant queries and simplifies backup, restore, and lifecycle management per tenant. Complementing this, Keycloak enforces identity and access segregation using realms, where each realm represents a completely isolated security domain with its own users, clients, roles, policies, and authentication flows. By aligning each PostgreSQL database with a corresponding Keycloak realm, the architecture guarantees strict isolation between entities both at the data layer and the identity/security layer, creating a robust multi-tenant foundation with strong boundaries across tenants. \ No newline at end of file From c30a1461c36858f5966a9c223a9ecec7f0703e98 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 2 Dec 2025 18:05:40 +0100 Subject: [PATCH 86/93] Add onboarding guide for Swift Digital Ledger Portal Added a comprehensive onboarding guide for institutions and users to the Swift Digital Ledger Portal, detailing the onboarding process, required information, and email templates. --- test | 139 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 137 insertions(+), 2 deletions(-) diff --git a/test b/test index 32d3943..78a560f 100644 --- a/test +++ b/test @@ -1,3 +1,138 @@ -Title: Data Segregation Strategy +Swift Digital Ledger – Institution & User Onboarding Guide + +Version 1.0 + +⸻ + +1. Introduction + +This guide provides a simple overview of how institutions and their users can onboard to the Swift Digital Ledger Portal. It explains the basic steps required to submit onboarding information, receive user credentials, and complete the first login. +Once onboarding is complete, users can log in to the Swift Digital Ledger application and access the main dashboard. From there, this guide will walk users through how to navigate the platform and provide an overview of the key features available. + +⸻ + +2. Onboarding Initiation + +The onboarding process consists of two simple steps: + +⸻ + +STEP 1 — Institution Sends Onboarding Information + +The institution must send one email to the Swift Digital Ledger Onboarding Team with the required onboarding details. + +Send email to: +📨 swiftdigitalledger-onboarding@swift.com + +The onboarding team will use this information to create all user accounts for the institution. + +Required Information + • Institution / Company Name + • BIC Code + • List of Users containing: + • Full Name + • Email Address + +⸻ + +Email Template for Institutions + +Subject: Onboarding Request + +To: swiftdigitalledger-onboarding@swift.com** + +Dear Swift Digital Ledger Team, + +We would like to onboard our institution to the Swift Digital Ledger Portal. +Please find below the required information: + +Institution Name: +[Insert Institution Name] + +BIC Code: +[Insert BIC] + +User List: + 1. Full Name: [Name] — Email: [Email] + 2. Full Name: [Name] — Email: [Email] + 3. Full Name: [Name] — Email: [Email] +(Add more users if needed) + +Please proceed with creating the user accounts. + +Thank you, +[Your Name] +[Your Position] +[Institution Name] + +⸻ + +STEP 2 — Each User Receives a Welcome Email + +Once the onboarding request is processed, each user listed by the institution will receive an individual Welcome Email. + +This email will contain: + • Their username (their email address) + • Their initial password (already set) + • Instructions for first-time login + • A link to the Swift Digital Ledger portal + +⸻ + +Email Template for Users (Welcome Email) + +Subject: Welcome to Swift Digital Ledger – Your Access Details + +Dear [User Name], + +Your access to the Swift Digital Ledger Portal has been created. +Below are your login credentials: + +Username: +[User Email] + +Password: +[Temporary Password] + +Please follow the instructions below to complete your first-time login. + +⸻ + +3. First-Time Login + +Once you receive your welcome email, follow the steps below to access the Swift Digital Ledger Portal for the first time. + +⸻ + +Step 1 — Go to the Login Page + +Open the Swift Digital Ledger Portal: + +🌐 https://portal.swiftdigitalledger.com +(Replace with the official portal URL if applicable) + +Enter your: + • Username (your email address) + • Password (provided in your welcome email) + +Click Sign In. + +⸻ + +Step 2 — Enter the OTP Code + +After signing in: + 1. You will receive a One-Time Password (OTP) by email. + 2. Look for the message titled: +“Swift Digital Ledger – Your Verification Code” + 3. Enter the 6-digit OTP on the login screen. + 4. Click Verify Code. + +⸻ + +Step 3 — Access Granted + +Once the OTP is verified, you will be redirected to the main dashboard and can start using the Swift Digital Ledger system. + + -PostgreSQL data segregation is implemented by isolating each tenant’s information into its own database, ensuring that schemas, tables, and data remain fully separated at the storage and access-control level. This physical separation eliminates the risk of cross-tenant queries and simplifies backup, restore, and lifecycle management per tenant. Complementing this, Keycloak enforces identity and access segregation using realms, where each realm represents a completely isolated security domain with its own users, clients, roles, policies, and authentication flows. By aligning each PostgreSQL database with a corresponding Keycloak realm, the architecture guarantees strict isolation between entities both at the data layer and the identity/security layer, creating a robust multi-tenant foundation with strong boundaries across tenants. \ No newline at end of file From 7f571a8a793e6623afa030050e000507430642ea Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 2 Dec 2025 18:16:14 +0100 Subject: [PATCH 87/93] Add minimum system requirements section Added minimum system requirements for the Swift Digital Ledger Portal. --- test | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test b/test index 78a560f..f1dfa73 100644 --- a/test +++ b/test @@ -135,4 +135,15 @@ Step 3 — Access Granted Once the OTP is verified, you will be redirected to the main dashboard and can start using the Swift Digital Ledger system. +Minimum System Requirements + +To ensure the Swift Digital Ledger Portal functions smoothly, users should meet the following minimum system requirements: + • Internet Connection: Stable broadband connection + • Supported Web Browsers: Latest versions of Chrome, Edge, Firefox, or Safari + • Device Compatibility: Desktop or laptop computer (recommended). Mobile and tablet access may have limited functionality. + • Email Access: Ability to receive verification and notification emails + • Security Settings: Cookies and JavaScript enabled + +These requirements help ensure reliable access and optimal performance of the Swift Digital Ledger application. + From f8aaf020508892d9d17759891f8a0bf69df9480f Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 2 Dec 2025 18:54:25 +0100 Subject: [PATCH 88/93] Enhance onboarding section with submission guidelines Add onboarding initiation process details. --- test | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test b/test index f1dfa73..d039137 100644 --- a/test +++ b/test @@ -13,6 +13,9 @@ Once onboarding is complete, users can log in to the Swift Digital Ledger applic 2. Onboarding Initiation +This section outlines how institutions should submit their onboarding request and what information must be included. +The onboarding initiation process begins when the institution submits its information to the Swift Digital Ledger team + The onboarding process consists of two simple steps: ⸻ From 8f5ec140c282a245e5fbf44fdaf520260a6d76ee Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 3 Dec 2025 14:05:45 +0100 Subject: [PATCH 89/93] Atualizar o test --- test | 153 +---------------------------------------------------------- 1 file changed, 1 insertion(+), 152 deletions(-) diff --git a/test b/test index d039137..683108a 100644 --- a/test +++ b/test @@ -1,152 +1 @@ -Swift Digital Ledger – Institution & User Onboarding Guide - -Version 1.0 - -⸻ - -1. Introduction - -This guide provides a simple overview of how institutions and their users can onboard to the Swift Digital Ledger Portal. It explains the basic steps required to submit onboarding information, receive user credentials, and complete the first login. -Once onboarding is complete, users can log in to the Swift Digital Ledger application and access the main dashboard. From there, this guide will walk users through how to navigate the platform and provide an overview of the key features available. - -⸻ - -2. Onboarding Initiation - -This section outlines how institutions should submit their onboarding request and what information must be included. -The onboarding initiation process begins when the institution submits its information to the Swift Digital Ledger team - -The onboarding process consists of two simple steps: - -⸻ - -STEP 1 — Institution Sends Onboarding Information - -The institution must send one email to the Swift Digital Ledger Onboarding Team with the required onboarding details. - -Send email to: -📨 swiftdigitalledger-onboarding@swift.com - -The onboarding team will use this information to create all user accounts for the institution. - -Required Information - • Institution / Company Name - • BIC Code - • List of Users containing: - • Full Name - • Email Address - -⸻ - -Email Template for Institutions - -Subject: Onboarding Request - -To: swiftdigitalledger-onboarding@swift.com** - -Dear Swift Digital Ledger Team, - -We would like to onboard our institution to the Swift Digital Ledger Portal. -Please find below the required information: - -Institution Name: -[Insert Institution Name] - -BIC Code: -[Insert BIC] - -User List: - 1. Full Name: [Name] — Email: [Email] - 2. Full Name: [Name] — Email: [Email] - 3. Full Name: [Name] — Email: [Email] -(Add more users if needed) - -Please proceed with creating the user accounts. - -Thank you, -[Your Name] -[Your Position] -[Institution Name] - -⸻ - -STEP 2 — Each User Receives a Welcome Email - -Once the onboarding request is processed, each user listed by the institution will receive an individual Welcome Email. - -This email will contain: - • Their username (their email address) - • Their initial password (already set) - • Instructions for first-time login - • A link to the Swift Digital Ledger portal - -⸻ - -Email Template for Users (Welcome Email) - -Subject: Welcome to Swift Digital Ledger – Your Access Details - -Dear [User Name], - -Your access to the Swift Digital Ledger Portal has been created. -Below are your login credentials: - -Username: -[User Email] - -Password: -[Temporary Password] - -Please follow the instructions below to complete your first-time login. - -⸻ - -3. First-Time Login - -Once you receive your welcome email, follow the steps below to access the Swift Digital Ledger Portal for the first time. - -⸻ - -Step 1 — Go to the Login Page - -Open the Swift Digital Ledger Portal: - -🌐 https://portal.swiftdigitalledger.com -(Replace with the official portal URL if applicable) - -Enter your: - • Username (your email address) - • Password (provided in your welcome email) - -Click Sign In. - -⸻ - -Step 2 — Enter the OTP Code - -After signing in: - 1. You will receive a One-Time Password (OTP) by email. - 2. Look for the message titled: -“Swift Digital Ledger – Your Verification Code” - 3. Enter the 6-digit OTP on the login screen. - 4. Click Verify Code. - -⸻ - -Step 3 — Access Granted - -Once the OTP is verified, you will be redirected to the main dashboard and can start using the Swift Digital Ledger system. - - -Minimum System Requirements - -To ensure the Swift Digital Ledger Portal functions smoothly, users should meet the following minimum system requirements: - • Internet Connection: Stable broadband connection - • Supported Web Browsers: Latest versions of Chrome, Edge, Firefox, or Safari - • Device Compatibility: Desktop or laptop computer (recommended). Mobile and tablet access may have limited functionality. - • Email Access: Ability to receive verification and notification emails - • Security Settings: Cookies and JavaScript enabled - -These requirements help ensure reliable access and optimal performance of the Swift Digital Ledger application. - - +After this step, you will be redirected to the Sign-In page. Enter the credentials you received by email. \ No newline at end of file From 642dc11ec96e2876caf933979d40ef6c66cef24c Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 3 Dec 2025 14:46:32 +0100 Subject: [PATCH 90/93] Atualizar o test --- test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test b/test index 683108a..ffcd48e 100644 --- a/test +++ b/test @@ -1 +1 @@ -After this step, you will be redirected to the Sign-In page. Enter the credentials you received by email. \ No newline at end of file +First, you will be redirected to a page requesting authentication due to restricted access. Use the following credentials: \ No newline at end of file From 4054d2dca3f50ead4827ce70a385e444d048706b Mon Sep 17 00:00:00 2001 From: Arthur Date: Wed, 3 Dec 2025 15:03:05 +0100 Subject: [PATCH 91/93] Atualizar o test --- test | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test b/test index ffcd48e..72d3dc4 100644 --- a/test +++ b/test @@ -1 +1,12 @@ -First, you will be redirected to a page requesting authentication due to restricted access. Use the following credentials: \ No newline at end of file +Once you enter your username and password and click Sign In: + 1. You will receive a One-Time Password (OTP) by email. + 2. Look for an email with the subject: +“Your Verification Code for SDL” + 3. Enter the 6-digit OTP on the screen. + 4. Click Verify Code. + +#include an image of the OTP page + +Access Granted + +Once the OTP is verified, you will be redirected to the main dashboard and can begin using the Swift Digital Ledger system. From e82cd02d5e6944f7aeddb99b201aef5174814167 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 23 Dec 2025 16:13:06 +0100 Subject: [PATCH 92/93] Actualizar test --- test | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/test b/test index 72d3dc4..b01c008 100644 --- a/test +++ b/test @@ -1,12 +1,13 @@ -Once you enter your username and password and click Sign In: - 1. You will receive a One-Time Password (OTP) by email. - 2. Look for an email with the subject: -“Your Verification Code for SDL” - 3. Enter the 6-digit OTP on the screen. - 4. Click Verify Code. +The Approval Flow allows authorized participants to review and approve pending payment transactions before they proceed to interbank settlement. +Each transaction must be approved by both the Credit Agent and the Debtor Agent to be finalized. -#include an image of the OTP page +The list displays all pending transactions awaiting approval. -Access Granted +Click the Select checkbox corresponding to the transaction you want to approve. -Once the OTP is verified, you will be redirected to the main dashboard and can begin using the Swift Digital Ledger system. +Click Approve to confirm the transaction. + +Approval is not completed with a single confirmation. + • The transaction must be approved by both parties: + • Credit Agent + • Correspondent Agent \ No newline at end of file From 91c19279fa5f2a0bd43cd49e13ce471d634b8c70 Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 9 Jan 2026 11:39:08 +0100 Subject: [PATCH 93/93] Implement InterbankLiabilityRegistry contract Added InterbankLiabilityRegistry contract with roles and functions for managing interbank liabilities, credit limits, and exposures. --- test | 220 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 211 insertions(+), 9 deletions(-) diff --git a/test b/test index b01c008..a991500 100644 --- a/test +++ b/test @@ -1,13 +1,215 @@ -The Approval Flow allows authorized participants to review and approve pending payment transactions before they proceed to interbank settlement. -Each transaction must be approved by both the Credit Agent and the Debtor Agent to be finalized. +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; -The list displays all pending transactions awaiting approval. +import "@openzeppelin/contracts/access/AccessControl.sol"; -Click the Select checkbox corresponding to the transaction you want to approve. +/** + * InterbankLiabilityRegistry (Record Only) + * + * PURPOSE: + * - Record interbank liabilities only (no settlement, no token movement) + * - Enforce bilateral credit limits + * - Track outstanding exposure + * + * ROLES: + * - DEFAULT_ADMIN_ROLE : governance / role management + * - ADMIN_ROLE : operational control + * - add/remove banks + * - record liabilities + * - BANK_ROLE : bank agents (debtor / creditor identities) + * - set credit limits + * + * MODEL: + * - creditLimit[debtor][creditor][currency] = max outstanding allowed + * - exposure[debtor][creditor][currency] = current outstanding + */ +contract InterbankLiabilityRegistry is AccessControl { + bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); + bytes32 public constant BANK_ROLE = keccak256("BANK_ROLE"); -Click Approve to confirm the transaction. + constructor(address[] memory admins, address[] memory bankAgents) { + _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); -Approval is not completed with a single confirmation. - • The transaction must be approved by both parties: - • Credit Agent - • Correspondent Agent \ No newline at end of file + for (uint256 i = 0; i < admins.length; i++) { + require(admins[i] != address(0), "BAD_ADMIN"); + _grantRole(ADMIN_ROLE, admins[i]); + } + + for (uint256 i = 0; i < bankAgents.length; i++) { + require(bankAgents[i] != address(0), "BAD_BANK"); + _grantRole(BANK_ROLE, bankAgents[i]); + } + } + + // ----------------------------- + // Bank management (ADMIN_ROLE) + // ----------------------------- + event BankAdded(address indexed bankAgent); + event BankRemoved(address indexed bankAgent); + + function addBank(address bankAgent) external onlyRole(ADMIN_ROLE) { + require(bankAgent != address(0), "BAD_BANK"); + _grantRole(BANK_ROLE, bankAgent); + emit BankAdded(bankAgent); + } + + function removeBank(address bankAgent) external onlyRole(ADMIN_ROLE) { + _revokeRole(BANK_ROLE, bankAgent); + emit BankRemoved(bankAgent); + } + + function isBank(address bankAgent) public view returns (bool) { + return hasRole(BANK_ROLE, bankAgent); + } + + // ----------------------------- + // Credit limits & exposure + // ----------------------------- + /** + * Dimension order: + * debtorAgent → creditorAgent → currency → amount + * + * creditLimit: + * - Maximum outstanding amount allowed from debtor to creditor in a given currency + */ + mapping(address => mapping(address => mapping(bytes32 => int256))) public creditLimit; + + /** + * exposure: + * - Current outstanding amount from debtor to creditor in a given currency + */ + mapping(address => mapping(address => mapping(bytes32 => int256))) public exposure; + + event CreditLimitSet( + address indexed debtorAgent, + address indexed creditorAgent, + bytes32 indexed currency, + int256 limit + ); + + /** + * Credit limit is set by BANK_ROLE + */ + function setCreditLimit( + address debtorAgent, + address creditorAgent, + bytes32 currency, + int256 limit + ) external onlyRole(BANK_ROLE) { + require(isBank(debtorAgent) && isBank(creditorAgent), "NOT_A_BANK"); + require(limit >= 0, "LIMIT_NEGATIVE"); + + int256 currentExposure = exposure[debtorAgent][creditorAgent][currency]; + require(limit >= currentExposure, "LIMIT_BELOW_EXPOSURE"); + + creditLimit[debtorAgent][creditorAgent][currency] = limit; + emit CreditLimitSet(debtorAgent, creditorAgent, currency, limit); + } + + function availableCredit( + address debtorAgent, + address creditorAgent, + bytes32 currency + ) external view returns (int256 limit, int256 used, int256 available) { + limit = creditLimit[debtorAgent][creditorAgent][currency]; + used = exposure[debtorAgent][creditorAgent][currency]; + available = limit - used; + } + + // ----------------------------- + // Liability records (immutable) + // ----------------------------- + struct Liability { + bytes32 id; + address debtorAgent; + address creditorAgent; + uint256 amount; + bytes32 currency; + bytes32 batchId; + } + + mapping(bytes32 => Liability) private liabilities; + + event LiabilityRecorded( + bytes32 indexed id, + address indexed debtorAgent, + address indexed creditorAgent, + uint256 amount, + bytes32 indexed currency, + bytes32 batchId, + int256 newExposure, + int256 limit + ); + + /** + * recordLiability + * - One-way record + * - Enforces creditLimit and updates exposure + * - Stores immutable record (no settlement) + */ + function recordLiability( + bytes32 id, + address debtorAgent, + address creditorAgent, + uint256 amount, + bytes32 currency, + bytes32 batchId + ) external onlyRole(ADMIN_ROLE) { + require(id != bytes32(0), "ID_REQUIRED"); + require(isBank(debtorAgent) && isBank(creditorAgent), "NOT_A_BANK"); + require(amount > 0, "AMOUNT_REQUIRED"); + require(liabilities[id].id == bytes32(0), "DUPLICATE_ID"); + + int256 limit = creditLimit[debtorAgent][creditorAgent][currency]; + require(limit > 0, "NO_CREDIT_LIMIT"); + + int256 currentExposure = exposure[debtorAgent][creditorAgent][currency]; + int256 delta = int256(amount); + require(currentExposure + delta <= limit, "CREDIT_LIMIT_EXCEEDED"); + + int256 newExposure = currentExposure + delta; + exposure[debtorAgent][creditorAgent][currency] = newExposure; + + liabilities[id] = Liability({ + id: id, + debtorAgent: debtorAgent, + creditorAgent: creditorAgent, + amount: amount, + currency: currency, + batchId: batchId + }); + + emit LiabilityRecorded( + id, + debtorAgent, + creditorAgent, + amount, + currency, + batchId, + newExposure, + limit + ); + } + + function getLiability(bytes32 id) external view returns (Liability memory) { + Liability memory l = liabilities[id]; + require(l.id != bytes32(0), "NOT_FOUND"); + return l; + } +} + + +//// +Whitelist the bank agent addresses (debtor/creditor agents). + • Store bilateral credit limits as: +limits[debtorAgent][creditorAgent][currency] = int256(limit) + • Track current exposure / outstanding as: +exposure[debtorAgent][creditorAgent][currency] = int256(currentOutstanding) + • When the debtor emits the token-escrow event, your Orchestrator observes it and calls the registry passing: + • debtorAgent + • creditorAgent + • amount + • currency + +The contract verifies: +exposure + amount <= limit and then records the interbank liability.