Security
Design permissions, protect business rules and private data, and test how your Canton application handles failures.
Authored bySecurity Model
New to Canton? Start with About Canton and Canton Architecture.
Secure application design starts with who may act, which outcomes are valid, and who may see the resulting data.
Canton checks transactions against the applicable ledger rules. Your contracts define the business rules, while your application protects user requests, credentials, and data outside the ledger.
An authorized action can still produce an unwanted result. For example, a split can create excess units when its contract never checks the output total.
Use these practices when designing, implementing, and reviewing an application. Each topic explains a failure, the control that prevents it, and tests for the intended behavior.
Start by defining the business action, then work through permissions, business rules, application operations, and testing.
Start With a Business Action
Consider a transfer of 10 units from Alice to Bob. The application needs to establish who requested it, which asset moves, and whether Alice can authorize that transfer.
The contract needs rules for the amount, recipient, and any fee. The backend needs to handle a lost response without sending another transfer.
For each action you build, identify the permitted actor, affected contracts, resulting amounts, and information each participant should receive. Include failure and cancellation outcomes.
Permissions and Control
Define who can act, the limits of delegated authority, and who can intervene during an incident.
Bind Requests to Authorized Parties
A party is an identity used in Daml authorization and visibility rules. An application account and a ledger party are separate identities.
A signatory authorizes contract creation. A choice's controllers supply the authority required to exercise it. An observer receives visibility without gaining controller authority.
Ledger API rights control what a service may request. Rights to act as a party permit submissions for that party; read rights permit reading data visible to it.
A Backend Acts for the Wrong Customer
A backend serves Alice and Bob. Its service identity can submit for both parties.
Alice signs in and sends a transfer request containing Bob's party identifier. The backend copies that identifier into its submission without checking Alice's entitlement.
The ledger can accept the request because the backend has Bob's submission rights and supplies the authority required by the contract. The backend has allowed Alice to use authority intended for Bob.
Resolve permitted parties from the authenticated account and current permissions. Validate the requested action and affected object before submitting.
If a user can represent several parties, validate their selection against that permitted set. Restrict service rights to the parties the service needs.
Try Alice's request using Bob's party and contract identifier. It should fail before submission and leave Bob's holdings unchanged.
Then submit Alice's permitted transfer and check its result. Separately confirm that a service with only read rights cannot submit the transfer.
Restrict Delegated Authority
A choice can exercise another choice. Its immediate consequences receive authority from the exercised contract's signatories and the choice's controllers.
Fetching a permission contract does not itself add its signatories' authority to later actions. Follow the exercises through the workflow to understand whose authority each action receives.
An Agent Exceeds Its Mandate
Alice authorizes an agent to transfer up to 10 units of one instrument to an approved recipient. An instrument identifies the asset being transferred.
Alice signs a grant contract. The agent controls a choice on that grant, which performs the transfer.
If the choice accepts any amount, instrument, or recipient, the agent can request a transfer outside Alice's intended mandate. The nested action can still be authorized.
Store the mandate in the grant and check every transfer against it. Bind the grant to Alice, the agent, the instrument, and the permitted recipient.
A limit of 10 units per transfer allows repeated transfers of 10. A lifetime allowance needs state that changes when used.
Provide an authorized revocation action. Every later use must depend on the live grant or its correctly tracked remaining allowance.
An allowed transfer of 5 units should succeed. A transfer of 11 units, a different instrument, or a different recipient should fail.
For a lifetime limit, a second transfer must not exceed the remainder. After revocation commits, another use must fail.
If earlier choices created independent permissions, those permissions need their own revocation rule.
Give Each Operator a Defined Permission
A licensing service lets an operator issue licenses for one registry. That permission should not allow the operator to change prices or administer another registry.
OpenZeppelin's Scoped Authorization Grant provides a reusable credential for this boundary. A grant identifies its authority, grantee, resource scope, permission, and optional validity window.
The protected choice makes the acting party a controller. It derives the expected authority and scope from trusted application state, then validates the presented grant. Taking the expected policy from the caller would let the caller decide which permission is sufficient.
The operator also needs visibility of the protected resource. A stakeholder can provide explicit disclosure when the operator is not a stakeholder.
A guarded use can require the grant authority's participant to confirm the transaction. Prefer an authority already involved in the workflow, and test its availability.
Use the licensing example to follow issuance through a guarded operation. The treasury example maps business roles to permissions with separate authorities.
Your application still defines role administration and offboarding. A grant has no spending counter. For a cumulative limit, maintain and check a separate allowance.
A grant can remain active after its validity window ends or fail the resource's current policy. Validate it when the protected operation executes; discovering its contract ID is insufficient.
Test a grant from the wrong authority, for another operator, and for another resource. Also test the validity boundaries and use after revocation. Duplicate grants remain independent, so offboarding must invalidate every applicable permission.
Transfer Administrative Responsibility
Decide who may replace an administrator and what happens to pending work during the handoff. If a successor contract adds a signatory, that party must authorize its creation.
For scoped permissions, update the resource's trusted authority through an authorized workflow and issue replacement grants. Advance the policy epoch to invalidate permissions using the previous policy. Reusing an earlier epoch can make old grants valid again.
An offer and acceptance workflow can collect the incoming administrator's consent. Define whether operations continue while that offer is pending, and how cancellation restores the intended state.
Test that the incoming administrator can perform the intended actions after acceptance. Old grants should fail against the new policy, while unfinished workflows follow their explicit migration or cancellation rules.
Control Operations During an Incident
A registry discovers a pricing error. It needs to stop new issuance while preserving an authorized recovery path.
Choose which operations must stop, which must remain available, and who may pause and resume them. A pause affects only choices that check its state.
OpenZeppelin's Pausable packages supply an interface and reusable guards. Your template stores the pause flag, implements the interface, and defines the choices that change it.
Call the guard on the protected contract's own state before changing that state. A caller-selected contract containing an unpaused flag would let the caller choose a different switch.
The registry and vault examples demonstrate different control policies. Use them when implementing incident controls, after deciding the application's authority model.
Pause guards check the flag. An operation that reduces a balance must also reject non-positive amounts and amounts above the available balance. Test these rules while unpaused so a pause rejection cannot hide an amount-validation defect.
Signatories can directly create and archive their contracts. Account for that authority when deciding who can change the pause state. Pausing does not reverse completed transactions.
Test that ordinary operations succeed before a pause, fail while paused, and succeed after an authorized resume. Test unauthorized pause and resume attempts, repeated transitions, and any recovery action allowed during the pause.
A consuming pause choice creates a successor contract with a new identifier. Check that the backend follows that successor and that attempts using the archived identifier fail.
Business Rules
Specify valid amounts, prices, deadlines, and data inputs before implementing the choices that use them.
Preserve Asset Accounting
A holding is a contract recording an amount of an asset. A consuming choice archives its input contract as part of the transaction.
A split consumes one holding and creates replacement holdings. This example uses one issuer and instrument, with no fees, issuance, or redemption.
A Split Creates Extra Units
Alice holds 100 units and controls the split choice. She supplies replacement amounts of 60 and 60.
The choice checks that both amounts are positive but never compares their sum with the input. It creates holdings totaling 120 units.
Require positive outputs whose sum equals the consumed amount. Preserve the issuer and instrument identity on every output.
For other operations, write the accounting rule separately. Include recipient amounts, change, fees, authorized issuance, and redemption without mixing different instruments.
Direct creation, archival, and alternative choices also affect supply. A correct split does not prevent another authorized path from issuing or destroying units.
Check the Resulting Holdings
A split into 60 and 40 should succeed. Splitting into 60 and 60 should fail, as should negative outputs, zero outputs, and an empty split under this model.
A rejected split must leave the original holding active and create no replacements. Repeat the accounting checks across the other paths that move or change supply.
Validate Prices and Amounts
An asset amount needs a defined unit and precision. A price needs a defined quotation currency and amount per unit.
Specify the rounding rule and who receives any remainder. A positive value alone does not establish a valid business amount.
A Configurable Price Stops Quotes
A price publisher creates a contract containing a price per unit. A quoting choice divides a payment amount by that price.
A payment of 100 at a price of 5 produces 20 units. A price of zero makes the division fail.
The request returns no quote. In this example, the failure is unhandled, so the transaction commits no changes.
Reject non-positive prices when creating replacement price contracts. Validate the permitted range and any derived divisor before division.
A template's ensure condition constrains contract creation. Assertions in a choice check the particular action, including its arguments and fetched inputs.
Check Configuration Changes and Rounding
Try zero and negative prices, valid prices, and values near the supported numeric boundaries. Repeat these tests for configuration updates.
Also use a calculation that requires rounding. The rounded result and remainder should match the agreed rule.
Enforce Settlement Windows
Ledger time is the time used by the contract's transaction logic. A browser clock or request-arrival timestamp does not establish that a settlement meets its ledger deadline.
Settlement Requires One Exact Timestamp
A payer controls settlement of an agreed obligation. The choice accepts only when ledger time equals one stored timestamp.
A valid request arriving outside that instant fails. Repeated retries cannot guarantee execution at the required time.
Define the business window explicitly. For this example, settlement is allowed at opening and stops immediately before closing.
Check that rule when settlement executes. Checking only that opening precedes closing when creating the obligation does not enforce the execution deadline.
A wider window changes the agreement. Choose its boundaries from the business requirement.
Check Boundaries and Expiry
Try settlement immediately before opening, at opening, inside the window, at closing, and after closing. Opening should succeed; closing should fail.
An authorized cancellation or expiry path lets unfinished obligations recover. It must release reserved assets only when permitted and cannot undo a completed settlement.
Select and Validate Price Data
A backend may query several price contracts before submitting a trade. Response position is not a business rule for choosing a price.
The First Result Becomes the Price
A trader's backend receives two quotes and selects the first. Reversing the response changes the submitted price.
Sorting by round makes selection repeatable, but the highest round could belong to another publisher, another instrument, or an outdated feed.
Define the accepted publisher, instrument, quotation units, freshness limit, and policy for conflicting quotes.
Validate those fields in the settlement logic wherever they affect settlement. A caller must not bypass the rule by supplying a different contract identifier.
These are input-selection and validation failures. They do not establish nondeterministic execution of Daml code.
Check Quote Selection and Freshness
Try every permutation of a small result set. Each permutation should select the same acceptable quote or reject the same ambiguity.
Reject an untrusted publisher with a higher round, a stale quote, mismatched units, and conflicting quotes that violate the selection policy.
A trusted quote inside the freshness limit should succeed. Try it again after it becomes stale, including a delay between selection and settlement.
Application Operations
Plan how the application handles uncertain outcomes, private data, upgrades, and credentials.
Recover Without Repeating Actions
A transport timeout can leave your application uncertain whether a requested change committed. That uncertainty matters when repeating the request could create another order or transfer.
A Timeout Creates a Second Order
A customer requests an order. The ledger creates it, but the backend loses the response.
The backend retries with a new command ID. If the creation remains valid, the ledger can create another order.
A command ID identifies the intended ledger change. Persist it with the business operation before submitting, and reuse it when retrying that same change.
Each submission attempt also has a submission ID. Give each attempt a fresh submission ID so you can distinguish its result from earlier attempts.
Command deduplication rejects repeated submissions within its supported scope and period. It considers the command ID, submitting user, and actAs parties.
Its protection also depends on the submitting participant and effective deduplication period. Changing the submitting identity or participant can change whether a request is recognized as a duplicate.
A completion reports the result of a submission. Track completions and save your progress so the application can recover after restarting.
An acknowledgement from the submission service is not a successful completion. When protection has expired or submission moves to another participant, establish the original outcome before issuing another business action.
Simulate a lost response after commitment and a restart before the result is recorded. Both should resolve to the original order.
Two Requests Use the Same Holding
Two concurrent transfers try to consume the same holding. They cannot both consume that contract successfully.
After a conflict, reload state and establish what happened to the original operation. Automatically switching to another holding can repeat a transfer that already succeeded.
The failed attempt should create no recipient holding and trigger no second payment.
An External Payment Repeats
A worker pays an external provider after observing a ledger result. It crashes before recording that payment locally.
Replaying the event can pay again. Ledger command deduplication does not deduplicate the provider's payment request.
Use a durable record of the work and the provider's supported idempotency mechanism. This lets repeated requests refer to the same payment.
If the payment outcome is uncertain, establish whether it succeeded before repeating it. Simulate a crash after the provider accepts payment: recovery should record the existing payment rather than create another.
Protect Data After Reading It
A backend may legitimately read data for several parties. Its customers must still receive only data they are entitled to access.
One Customer Receives Another Customer's Data
Bob's contract data enters a shared cache. Alice requests the same endpoint, and the backend returns Bob's cached response.
The backend exposed information it was allowed to retrieve. Ledger read controls do not decide which customer should receive a cached response.
Authorize each response and export. Scope database queries and caches to the relevant permissions, and handle changes to those permissions.
Use different Alice and Bob records. Warm the cache as Bob, then request the same object and export as Alice.
Alice must receive no Bob-only data. Bob's permitted request must still succeed.
Exclude access tokens, signing secrets, and unnecessary contract payloads from logs. Trigger an error containing sensitive test data and inspect the resulting logs.
A Composed Transaction Reveals More Than Expected
A workflow creates confidential terms inside a choice visible to an additional participant. That participant can learn about consequences of the enclosing action.
Checking only the new contract's observer list misses this disclosure. Inspect the full transaction from each participant's view, including nested actions.
Restructure the workflow or its data so each participant receives only the intended information.
Explicit contract disclosure also supplies contract data outside ordinary stakeholder subscription. Control who receives that data; disclosure does not grant unrestricted authority to exercise choices.
The intended recipient should be able to use a permitted disclosed input while an unauthorized exercise remains rejected.
Read the Canton privacy model for transaction visibility mechanics.
Test Existing Contracts Across Upgrades
A package contains compiled Daml definitions. An upgrade can pass compatibility checks while changing a workflow's business behavior.
Old Contracts Become Unusable
Version one permits a contract value of zero. Version two strengthens the template condition to require a positive value.
An existing zero-valued contract fails the target template's condition when retrieved through that upgrade path. Compiling the new package does not demonstrate that old workflows remain usable.
Use actual contracts created with the old package in upgrade tests. Include their boundary values and unfinished workflows.
The package versions requested by your backend affect which behavior runs. Test the versions that can coexist across participants during rollout.
Coordinate package availability and vetting with the participants involved. Follow the package-selection rules when deciding which version each client uses.
Check agreed amounts, permissions, deadlines, and visibility after each transition. Where old behavior must change, define the transition and recovery policy explicitly.
An existing valid workflow that should continue must still succeed. An invalid new action must fail. Also test old clients against data introduced by the new version.
Uploading a new package alone does not establish that every caller uses its corrected behavior.
Protect Credentials and Signing Keys
A service credential determines which API requests your backend can make. Signing keys authorize signed operations. Protect both according to the authority they grant.
Development Access Reaches a Shared Environment
A service starts in a shared environment with a development credential or administrative access it does not need.
An attacker who obtains that credential can use the granted rights. Contract authorization cannot identify the attacker as a different application user.
Use separate credentials for each environment and service role. Development credentials should fail in the shared environment, and the application service should not perform administrative operations.
Then verify that the restricted service can complete its permitted workflow.
For externally signed transactions, the signer needs to check the transaction being approved. API authentication alone does not establish that the signer intended its amounts and recipients.
Try signing requests with changed recipients or amounts and confirm that the signer rejects them. Protect recovery material according to the chosen custody arrangement.
Your application team owns its login system, service credentials, request authorization, and off-ledger storage. A validator operator owns the infrastructure it runs.
If you use a hosted validator, establish who manages node keys, administrative access, monitoring, and recovery with the provider.
Use Ship to MainNet for deployment procedures and provider-specific configuration.
Testing and Review
Select tests for the contracts, services, and participant interactions that make up your application.
Choose Tests for Each Boundary
Use Daml Script to exercise contract creation, choice outcomes, rejected actions, and business boundaries.
During implementation, daml-lint scans Daml source for supported patterns, including unguarded division and order-dependent query selection. Review each finding against the code; a clean result does not establish conservation of assets.
For calculations and state transitions, daml-props generates inputs and action sequences for properties you write in Daml. Its sequence runner checks the state-transition model you supply, so test that model against real contract executions as well.
For a narrowly defined invariant, daml-verify checks hand-written symbolic models with the Z3 solver. A proof covers the model and its assumptions; it does not automatically verify your Daml source, authorization, or ledger integration.
When developers use AI assistants, an MCP gate such as Daml Reason can check drafts against a promoted pattern corpus before merge. It does not replace Daml Script, negative authorization tests, or the checks in this guide. See Build with AI for setup.
Backend integration tests check login-to-party mapping, API rights, response authorization, retries, caches, and external effects.
Tests across participants check visibility, distributed workflows, package availability, and configuration-dependent behavior. Upgrade regression tests cover existing contracts and unfinished workflows under the intended version combinations.
A negative test must fail for the intended reason. A missing permission can hide a broken amount check.
For each rejected action, inspect the remaining contracts and external effects. For each permitted action, verify the resulting business state.
Passing tests establishes evidence for the cases exercised. It does not establish that every possible workflow is safe.
Related
- Testing Daml Contracts: write contract tests with Daml Script.
- Command Deduplication: implement recovery for uncertain submissions.
- OWASP ASVS Stable Release: select verification requirements for the web application.
- OWASP Logging Guidance: retain useful security events without exposing secrets.