Test mediator connection
Send a test message through your DIDComm mediator, Affinidi-hosted or self-hosted, to confirm that clients can reach it, authenticate to it, and exchange messages through it.
This guide checks that the mediator reports itself ready, then runs a short sample in Rust or in Dart. The sample creates new test identities on your mediator, rather than using your clients’ own, and authenticates them. Each sample sends a message from one identity, Alice, to another, Bob, through the mediator. The Rust sample also sends the mediator a trust ping and waits for its reply. For what a mediator does, see DIDComm Mediator.
A running mediator also needs its DID to resolve, its endpoint to be reachable, and its access control lists (ACLs) to admit the sender. A full message exchange confirms all three, which is the quickest way to find out whether a client can use it.
Use this guide when:
- You have just deployed a mediator in Affinidi Portal or self-hosted one.
- You changed a mediator’s configuration, such as its ACLs or operating mode, and want to check that messages still get through.
- A client has trouble connecting, and you want to check whether the mediator is the cause.
The samples on this page were tested against an Affinidi-hosted mediator at Version v3.0.0 in Affinidi Portal, which runs mediator release 0.33.1 as readyz reports it, and against self-hosted mediator releases 0.48.0 and 0.53.0.
Prerequisites
- Your mediator’s DID:
- Affinidi-hosted: the Mediator DID shown on your mediator’s page in Affinidi Portal.
- AWS Marketplace: the contents of
mediator_did.txt, the MediatorDID you gave the stack. - Self-hosted: the DID you configured for your mediator.
- A mediator that lets new DIDs connect and use it. The samples create new DIDs on each run, so the mediator must accept them:
- Affinidi-hosted: Mediator ACL mode on your mediator’s page in Affinidi Portal is Explicit Deny.
- AWS Marketplace: the template sets
explicit_denyand grants new DIDs the permissions the samples need, so no change is needed. - Self-hosted:
mediator_acl_modeisexplicit_deny, andglobal_acl_defaultgrantsSELF_MANAGE_LIST,SEND_FORWARDEDandRECEIVE_FORWARDED. The setup wizard’s open network posture, the default for a local deployment, writesALLOW_ALL, which grants all three. For the configuration file shipped in the mediator’s repository, add them toglobal_acl_default, for exampleDENY_ALL,LOCAL,SEND_MESSAGES,RECEIVE_MESSAGES,SELF_MANAGE_LIST,SEND_FORWARDED,RECEIVE_FORWARDED. For what each setting does, see Supported ACLs.
- Network access from your machine to the mediator’s endpoint.
- For the Rust sample: Rust 1.95.0 or later.
- For the Dart sample: the Dart SDK 3.6.0 or later. The DIDComm library for Dart connects only to
https://endpoints, so serve a self-hosted mediator over HTTPS and list thehttps://endpoint in its DID, as Test 3 on the open-source deployment page describes.
Check that the mediator is ready
The mediator reports its health on the readyz path of its service URL, without authentication. Find the service URL in your mediator’s DID document: it is the http:// or https:// URI under the DIDCommMessaging service, not the ws:// or wss:// one.
- Affinidi-hosted: the mediator’s base URL, for example
https://<your-mediator-host>. - AWS Marketplace: the mediator’s host name with no prefix, for example
https://mediator.goodcompany.com. - Self-hosted: your public URL with the API prefix, by default
/mediator/v1, for examplehttp://localhost:7037/mediator/v1.
Request the readyz path under the service URL, for example:
# Affinidi-hosted or AWS Marketplace
curl https://<your-mediator-host>/readyz
# Self-hosted with the default API prefix
curl http://localhost:7037/mediator/v1/readyzThe response is a JSON object, abridged in the example below. Its version field shows the mediator release, and its status field is one of the following:
ready: the mediator is serving requests.degraded: the mediator is serving requests, but a component that is not essential to message delivery has stopped. The samples can still run.not_ready: the mediator is not serving requests, and the response has the HTTP status code 503.
{"status":"ready","version":"0.33.1", ...}Then test a message exchange with one of the samples below.
Test with Affinidi TDK for Rust
This sample is a self-contained program that uses the Affinidi Trust Development Kit (TDK) for Rust. It creates throwaway did:peer identities for Alice and Bob on your mediator and authenticates both. Alice sends the mediator a trust ping and waits for its reply. Bob then updates his access list so that Alice can message him, using a Trust Task, a signed management message to the mediator. Alice then sends Bob an encrypted message through the mediator, using authenticated encryption so that Bob can confirm it came from her.
Create the project
cargo new mediator-test
cd mediator-testReplace the contents of Cargo.toml with the following. The affinidi-tdk requirement keeps the sample on the 0.49 release line it was tested with.
[package]
name = "mediator-test"
version = "0.1.0"
edition = "2024"
[dependencies]
affinidi-tdk = "0.49"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }Create the test program
Replace the contents of src/main.rs with the following code.
use affinidi_tdk::{
TDK,
common::{config::TDKConfig, profiles::TDKProfile},
didcomm::message::Message,
dids::{DID, KeyType, PeerKeyRole},
messaging::{
ATM, errors::ATMError, profiles::ATMProfile,
tasks::messaging::account::get::v0_2::MediatorAclAccessListMode,
},
};
use serde_json::json;
use std::{
env,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), ATMError> {
let mediator_did = env::args()
.nth(1)
.expect("Usage: cargo run -- <MEDIATOR_DID>");
// Start the TDK with its messaging client. No environments file is needed.
let tdk = TDK::new(
TDKConfig::builder()
.with_load_environment(false)
.with_use_atm(true)
.build()?,
None,
)
.await?;
let atm = tdk.atm.clone().expect("messaging client is enabled");
// Create throwaway identities for Alice and Bob that use your mediator,
// authenticate both, and open a WebSocket connection for each.
let alice = create_identity(&tdk, &atm, "Alice", &mediator_did).await?;
let bob = create_identity(&tdk, &atm, "Bob", &mediator_did).await?;
// 1. Alice pings the mediator, which answers with a pong.
let ping = atm
.trust_ping()
.send_ping(&alice, &mediator_did, true, true, false)
.await?;
let pong = atm
.message_pickup()
.live_stream_get(
&alice,
&ping.message_id,
Some(Duration::from_secs(10)),
true,
)
.await?;
if pong.is_none() {
println!("Trust ping: no pong within 10 seconds");
atm.graceful_shutdown().await;
std::process::exit(1);
}
println!("Trust ping: the mediator answered Alice's ping");
// 2. Bob lets Alice message him.
allow_sender(&atm, &bob, &alice).await?;
// 3. Alice sends Bob an encrypted message through the mediator, using
// authenticated encryption so that Bob can confirm it came from her.
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let message = Message::build(
Uuid::new_v4().to_string(),
"https://didcomm.org/basicmessage/2.0/message".to_string(),
json!({ "content": "Hello, Bob!" }),
)
.from(alice.inner.did.to_string())
.to(bob.inner.did.to_string())
.created_time(now)
.expires_time(now + 60)
.finalize();
let message_id = message.id.clone();
let (packed, _) = atm
.pack_encrypted(&message, &bob.inner.did, Some(&alice.inner.did), None)
.await?;
let (_, forward) = atm
.routing()
.forward_message(
&alice,
false,
&packed,
&mediator_did,
&bob.inner.did,
None,
None,
)
.await?;
atm.send_message(&alice, &forward, &message_id, false, false)
.await?;
// 4. Bob receives and decrypts Alice's message.
let received = atm
.message_pickup()
.live_stream_get(&bob, &message_id, Some(Duration::from_secs(10)), true)
.await?;
atm.graceful_shutdown().await;
match received {
Some((received, _)) => {
println!("Message: Bob received from Alice: {}", received.body);
Ok(())
}
None => {
println!("Message: Bob received nothing within 10 seconds");
std::process::exit(1);
}
}
}
/// Lets `sender` message `owner`. A new account's access list is either an
/// allow list or a deny list, depending on the mediator's configuration, so
/// add the sender to an allow list or remove it from a deny list.
async fn allow_sender(
atm: &ATM,
owner: &Arc<ATMProfile>,
sender: &Arc<ATMProfile>,
) -> Result<(), ATMError> {
let account = atm.trust_tasks().account_get(owner, None).await?;
// Access lists hold DID hashes: get the sender's from its own account.
let sender_hash = atm
.trust_tasks()
.account_get(sender, None)
.await?
.did
.as_str()
.to_string();
let (add, remove) = match account.acl.access_list_mode {
Some(MediatorAclAccessListMode::ExplicitAllow) => (vec![sender_hash], vec![]),
_ => (vec![], vec![sender_hash]),
};
atm.trust_tasks()
.access_list_update(owner, None, false, add, remove)
.await?;
Ok(())
}
async fn create_identity(
tdk: &TDK,
atm: &ATM,
name: &str,
mediator_did: &str,
) -> Result<Arc<ATMProfile>, ATMError> {
let (did, secrets) = DID::generate_did_peer(
vec![
(PeerKeyRole::Verification, KeyType::Ed25519),
(PeerKeyRole::Encryption, KeyType::X25519),
],
Some(mediator_did.to_string()),
)?;
println!("{name} DID: {did}");
let profile = TDKProfile::new(name, &did, Some(mediator_did), secrets);
tdk.add_profile(&profile).await;
atm.profile_add(&ATMProfile::from_tdk_profile(atm, &profile).await?, true)
.await
}Run the program
Replace <REPLACE_MEDIATOR_DID> with your mediator’s DID and run:
cargo run -- "<REPLACE_MEDIATOR_DID>"The first run downloads and compiles the dependencies, which takes a few minutes.
The program prints the DIDs it created for Alice and Bob, then the result of each test:
Alice DID: did:peer:2.Vz6Mk...
Bob DID: did:peer:2.Vz6Mk...
Trust ping: the mediator answered Alice's ping
Message: Bob received from Alice: {"content":"Hello, Bob!"}The first result line confirms that Alice authenticated and the mediator answered her. The second confirms that the mediator delivered Alice’s message to Bob.
If a test fails, the program exits with status 1, so you can also run it as a check in a script.
Test with DIDComm library for Dart
This sample uses the DIDComm library for Dart. Bob sends the mediator two Trust Tasks, the signed management messages a DID sends to its mediator, to set up his access list so that Alice can message him. Alice then sends Bob a signed and encrypted message through the mediator, and Bob fetches and decrypts it.
Create the project
Create a folder for the test and go to it:
mkdir mediator
cd mediatorCreate a pubspec.yaml file with the following content. The constraints keep each library on the major version the sample was written for.
name: mediator
description: Test mediator connection
version: 1.0.0
environment:
sdk: ^3.6.0
dependencies:
didcomm: ^2.4.0
ssi: ^3.9.4
uuid: ^4.5.1Install the dependencies:
dart pub getCreate the test script
Create a mediator.dart file with the following code, then replace <REPLACE_MEDIATOR_DID> with your mediator’s DID.
import 'dart:io';
import 'package:didcomm/didcomm.dart';
import 'package:ssi/ssi.dart';
import 'package:uuid/uuid.dart';
void main() async {
const mediatorDid = '<REPLACE_MEDIATOR_DID>';
final aliceKeyStore = InMemoryKeyStore();
final aliceWallet = PersistentWallet(aliceKeyStore);
final bobKeyStore = InMemoryKeyStore();
final bobWallet = PersistentWallet(bobKeyStore);
final aliceDidManager = DidKeyManager(
wallet: aliceWallet,
store: InMemoryDidStore(),
);
final bobDidManager = DidKeyManager(
wallet: bobWallet,
store: InMemoryDidStore(),
);
// Ed25519 test keys, generated on each run. Their did:key identities use
// X25519 for key agreement, which mediators support.
final aliceKeyId = 'alice-key-1';
await aliceWallet.generateKey(keyId: aliceKeyId, keyType: KeyType.ed25519);
await aliceDidManager.addVerificationMethod(aliceKeyId);
final aliceDidDocument = await aliceDidManager.getDidDocument();
prettyPrint(
'Alice DID',
object: aliceDidDocument.id,
);
final aliceSigner = await aliceDidManager.getSigner(
aliceDidDocument.assertionMethod.first.id,
);
final bobKeyId = 'bob-key-1';
await bobWallet.generateKey(keyId: bobKeyId, keyType: KeyType.ed25519);
await bobDidManager.addVerificationMethod(bobKeyId);
final bobDidDocument = await bobDidManager.getDidDocument();
prettyPrint(
'Bob DID',
object: bobDidDocument.id,
);
final bobMediatorDocument =
await UniversalDIDResolver.defaultResolver.resolveDid(mediatorDid);
final alicePlainTextMessage = PlainTextMessage(
id: const Uuid().v4(),
from: aliceDidDocument.id,
to: [bobDidDocument.id],
type: Uri.parse('https://didcomm.org/example/1.0/message'),
body: {'content': 'Hello, Bob!'},
);
alicePlainTextMessage['custom-header'] = 'custom-value';
prettyPrint(
'Plain Text Message for Bob',
object: alicePlainTextMessage,
);
// Alice signs the message, then encrypts it for Bob with authenticated
// encryption (authcrypt), so that Bob can confirm it came from her.
final aliceKeyAgreementId = aliceDidDocument.keyAgreement.first.id;
final aliceSignedAndEncryptedMessage =
await DidcommMessage.packIntoSignedAndEncryptedMessages(
alicePlainTextMessage,
keyPair: await aliceDidManager.getKeyPairByDidKeyId(aliceKeyAgreementId),
didKeyId: aliceKeyAgreementId,
recipientDidDocuments: [bobDidDocument],
keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdh1Pu,
encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
signer: aliceSigner,
);
prettyPrint(
'Encrypted and Signed Message by Alice',
object: aliceSignedAndEncryptedMessage,
);
final createdTime = DateTime.now().toUtc();
final expiresTime = createdTime.add(const Duration(seconds: 60));
final forwardMessage = ForwardMessage(
id: const Uuid().v4(),
to: [bobMediatorDocument.id],
from: aliceDidDocument.id,
next: bobDidDocument.id,
expiresTime: expiresTime,
attachments: [
Attachment(
mediaType: 'application/json',
data: AttachmentData(
base64: base64UrlEncodeNoPadding(
aliceSignedAndEncryptedMessage.toJsonBytes(),
),
),
),
],
);
prettyPrint(
'Forward Message for Mediator that wraps Encrypted Message for Bob',
object: forwardMessage,
);
// Alice is going to use Bob's Mediator to send him a message
final aliceMediatorClient = await MediatorClient.init(
mediatorDidDocument: bobMediatorDocument,
didManager: aliceDidManager,
authorizationProvider: await AffinidiAuthorizationProvider.init(
mediatorDidDocument: bobMediatorDocument,
didManager: aliceDidManager,
),
forwardMessageOptions: const ForwardMessageOptions(
shouldSign: true,
keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdhEs,
encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
),
);
// Bob signs what he sends to the mediator too: by default, the mediator
// rejects anonymous messages, including Trust Tasks.
final bobMediatorClient = await MediatorClient.init(
mediatorDidDocument: bobMediatorDocument,
didManager: bobDidManager,
authorizationProvider: await AffinidiAuthorizationProvider.init(
mediatorDidDocument: bobMediatorDocument,
didManager: bobDidManager,
),
forwardMessageOptions: const ForwardMessageOptions(
shouldSign: true,
keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdhEs,
encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
),
);
// Bob puts his access list in allow-list mode, so that only DIDs on it can
// message him, then adds Alice. Mediators differ in the mode they give a new
// DID, so setting it first makes the result the same on every mediator.
final bobAccountUpdateMessage = TrustTaskMessage(
id: const Uuid().v4(),
document: AccountUpdateTask(
issuer: bobDidDocument.id,
mediatorDid: bobMediatorDocument.id,
acl: const MediatorAcl(accessListMode: AccessListMode.explicitAllow),
),
expiresTime: expiresTime,
);
await bobMediatorClient.sendTrustTask(bobAccountUpdateMessage);
final bobAccessListUpdateMessage = TrustTaskMessage(
id: const Uuid().v4(),
document: AccessListUpdateTask(
issuer: bobDidDocument.id,
mediatorDid: bobMediatorDocument.id,
add: [aliceDidDocument.id],
),
expiresTime: expiresTime,
);
await bobMediatorClient.sendTrustTask(bobAccessListUpdateMessage);
final sentMessage = await aliceMediatorClient.sendMessage(
forwardMessage,
);
prettyPrint(
'Encrypted and Signed Forward Message',
object: sentMessage,
);
prettyPrint('Bob is fetching messages...');
// Bob checks his inbox once a second, for up to 10 seconds, until Alice's
// message arrives. Each fetch removes the messages it returns.
var receivedAliceMessage = false;
for (var attempt = 0; attempt < 10 && !receivedAliceMessage; attempt++) {
if (attempt > 0) {
await Future<void>.delayed(const Duration(seconds: 1));
}
final messages = await bobMediatorClient.fetchMessages();
for (final message in messages) {
final plainTextMessage = await DidcommMessage.unpackToPlainTextMessage(
message: message,
recipientDidManager: bobDidManager,
expectedMessageWrappingTypes: [
// Alice's message: signed by Alice, then encrypted for Bob.
MessageWrappingType.authcryptSignPlaintext,
// The mediator's responses to Bob's Trust Tasks.
MessageWrappingType.authcryptPlaintext,
],
);
prettyPrint(
'Message received by Bob via Mediator',
object: plainTextMessage,
);
if (plainTextMessage.type == alicePlainTextMessage.type) {
receivedAliceMessage = true;
}
}
}
if (!receivedAliceMessage) {
prettyPrint('Bob received nothing from Alice within 10 seconds');
exit(1);
}
}Run the script
dart run mediator.dartThe script prints each stage of the exchange. At the end, Bob fetches three messages from his inbox, in any order: the mediator’s responses to his two Trust Tasks, and Alice’s message.
Bob is fetching messages...
Message received by Bob via Mediator:
{
...
"body": {
...
"payload": {
"account": {
...
"acl": {
"accessListMode": "explicitAllow",
...
"type": "https://trusttasks.org/spec/messaging/account/update/0.1#response"
}
}
Message received by Bob via Mediator:
{
...
"body": {
...
"payload": {
"accessListCount": 1,
...
"type": "https://trusttasks.org/spec/messaging/access-list/update/0.1#response"
}
}
Message received by Bob via Mediator:
{
"type": "https://didcomm.org/example/1.0/message",
...
"body": {
"content": "Hello, Bob!"
},
"custom-header": "custom-value"
}Seeing Hello, Bob! confirms that both identities authenticated to the mediator and that it delivered Alice’s message to Bob’s inbox.
On a mediator that requires a proof on every Trust Task, the two responses are trust-task-error documents with the code proofRequired instead. Alice’s message can still arrive, as Troubleshooting explains.
If Alice’s message does not arrive within 10 seconds, the script prints Bob received nothing from Alice within 10 seconds and exits with status 1.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
readyz reports not_ready, returns HTTP 503, or does not respond. | The mediator is still starting, or a component it needs to deliver messages is down. | Wait a minute and retry. For a self-hosted mediator, check its logs. A degraded status still lets you run the samples. |
Both samples: e.p.authentication.blocked with “DID is blocked”. In Rust, the error names the authenticate/challenge request. | The mediator is in Explicit Allow mode (explicit_allow), so it accepts only DIDs an administrator has registered, and the test DIDs are new. | Affinidi-hosted: the ACL mode is fixed when you create the mediator in Affinidi Portal, so create one with Explicit Deny. Self-hosted: set mediator_acl_mode to explicit_deny, then restart the mediator. |
Both samples: e.p.authorization.account.denied with “this account may not self-manage its access list”. | The mediator’s default ACL for new DIDs does not grant SELF_MANAGE_LIST, so Bob cannot update his access list. | On a self-hosted mediator, add SELF_MANAGE_LIST to global_acl_default, then restart it. |
Dart: Status code: 403 with e.p.authorization.send_forwarded. Rust: Message: Bob received nothing within 10 seconds, and the mediator logs e.p.authorization.send_forwarded. | The default ACL does not grant SEND_FORWARDED, so Alice cannot send a message through the mediator. | Add SEND_FORWARDED to global_acl_default, then restart the mediator. |
Dart: Status code: 403 with e.p.delivery.refused. Rust: Message: Bob received nothing within 10 seconds. | The mediator refused to deliver the message to Bob. The reason appears only in the mediator’s log, for example “recipient is not accepting forwarded messages” when the default ACL does not grant RECEIVE_FORWARDED. | Add RECEIVE_FORWARDED to global_acl_default, then restart the mediator. If you changed the samples, keep Bob’s access list step: in the Dart sample, set allow-list mode (explicitAllow) before adding Alice, and in Rust, pass access_list_update the SHA-256 hash of each DID, which account_get returns, not the DID itself. |
Dart: Status code: 400 with w.m.message.anonymous and “Mediator is not allowing anonymous messages”. | A MediatorClient created without shouldSign: true sends unsigned messages, which the mediator rejects by default. | Pass forwardMessageOptions with shouldSign: true to every MediatorClient.init call, as the sample does for both Alice and Bob. |
Dart: MessageWrappingType.authcryptPlaintext in not in expected list. | Bob’s inbox also holds the mediator’s responses to his Trust Tasks, which use a different message wrapping from Alice’s message. | List both authcryptSignPlaintext and authcryptPlaintext in expectedMessageWrappingTypes, as the sample does. |
Dart: No suitable key found for key agreement with the mediator. | Alice’s and Bob’s keys have no key agreement type in common with the mediator’s DID. | Use Ed25519 keys, as the sample does. Their X25519 key agreement keys work with Affinidi mediators. |
Dart: Can not find https endpoint in DIDCommMessaging service. | The mediator’s DID lists only an http:// endpoint. | Serve the mediator over HTTPS, and list the https:// URL in its DID. |
| Both samples: Bob received nothing within 10 seconds, with no error from the mediator. | The mediator accepted Alice’s message but did not deliver it to Bob in time, or refused delivery and reported the reason only in its log. | Check that readyz reports ready or degraded, then run the sample again. For a self-hosted mediator, check its log for e.p.delivery.refused or e.p.authorization.send_forwarded. |
Dart: Bob’s two Trust Task responses are trust-task-error documents with the code proofRequired and “this Trust Task type requires a proof”. | The mediator’s trust_task_verification setting is enforce, which the mediator’s setup wizard writes, and the DIDComm library for Dart sends Trust Tasks without a proof. | If Hello, Bob! still arrives, Bob’s access list already accepted Alice, and the mediator works. Otherwise use the Rust sample, which signs its Trust Tasks, or on a test mediator set trust_task_verification to warn and restart it. |
Rust: Trust ping: no pong within 10 seconds. | The mediator accepted Alice’s connection but did not answer in time. | Check that readyz reports ready or degraded, then run the program again. |
What’s next
Related
Glad to hear it. Thanks for letting us know.
Sorry to hear that. Thanks for letting us know.
Still stuck? Ask the community on Discord or contact us.