Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • eclipse/xfsc/ocm/ocm-engine
  • zdravko61/ocm-engine
  • mjuergenscg/ocm-engine
  • tsabolov/ocm-engine
  • mikesell/ocm-engine
5 results
Show changes
import { registerAs } from '@nestjs/config';
export const tailsServerConfig = registerAs('tailsServer', () => ({
baseUrl: process.env.TAILS_SERVER_BASE_URL || '',
bucketName: process.env.TAILS_SERVER_BUCKET_NAME || '',
}));
import { AutoAcceptCredential } from '@credo-ts/core';
import Joi from 'joi';
export const validationSchema = Joi.object({
HTTP_HOSTNAME: Joi.string().optional(),
HTTP_PORT: Joi.number().optional(),
NATS_URL: Joi.string().required(),
PORT: Joi.number().required(),
NATS_USER: Joi.string().optional(),
NATS_PASSWORD: Joi.string().optional(),
NATS_MONITORING_URL: Joi.string().optional(),
TAILS_SERVER_BASE_URL: Joi.string().required(),
TAILS_SERVER_BUCKET_NAME: Joi.string().required(),
S3_SECRET: Joi.string().required(),
S3_ACCESS_KEY: Joi.string().required(),
AGENT_NAME: Joi.string().required(),
AGENT_WALLET_ID: Joi.string().required(),
......@@ -10,8 +22,22 @@ export const validationSchema = Joi.object({
AGENT_HOST: Joi.string().required(),
AGENT_INBOUND_PORT: Joi.string(),
AGENT_URL_PATH: Joi.string(),
AGENT_PUBLIC_DID_SEED: Joi.string().required(),
AGENT_AUTO_ACCEPT_CONNECTION: Joi.boolean().required(),
AGENT_AUTO_ACCEPT_CREDENTIAL: Joi.string().required(),
AGENT_ID_UNION_KEY: Joi.string(),
AGENT_AUTO_ACCEPT_CONNECTION: Joi.boolean().default(true),
AGENT_AUTO_ACCEPT_CREDENTIAL: Joi.string().default(
AutoAcceptCredential.ContentApproved,
),
AGENT_LEDGER_ID: Joi.string().required(),
AGENT_INDY_DID_SEED: Joi.string().required(),
AGENT_INDY_DID: Joi.string().optional(),
AGENT_WALLET_STORAGE_TYPE: Joi.valid('postgres'),
AGENT_WALLET_STORAGE_CONFIG_HOST: Joi.when('AGENT_WALLET_STORAGE_TYPE', {
is: 'postgres',
then: Joi.string().uri().required(),
}),
AGENT_WALLET_STORAGE_CONFIG_TIMEOUT: Joi.number(),
AGENT_WALLET_STORAGE_CREDENTIALS_ACCOUNT: Joi.string(),
AGENT_WALLET_STORAGE_CREDENTIALS_PASSWORD: Joi.string(),
AGENT_WALLET_STORAGE_CREDENTIALS_ADMIN_ACCOUNT: Joi.string(),
AGENT_WALLET_STORAGE_CREDENTIALS_ADMIN_PASSWORD: Joi.string(),
});
import type { MicroserviceOptions } from '@nestjs/microservices';
/* c8 ignore start */
import type { ConfigType } from '@nestjs/config';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { createApplicationLogger, initOpenTelemetry } from '@ocm/shared';
import { createRequire } from 'module';
import { resolve } from 'node:path';
import { AppModule } from './app.module.js';
import { config } from './config/config.js';
import { Application } from './application.js';
import { httpConfig } from './config/http.config.js';
import { natsConfig } from './config/nats.config.js';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.NATS,
options: {
servers: [config().nats.url],
},
const pkgPath = resolve('package.json');
const pkg = createRequire(import.meta.url)(pkgPath);
const { sdk, prometheusExporter } = initOpenTelemetry(pkg.name);
sdk.start();
const app = await NestFactory.create(Application, {
logger: createApplicationLogger(),
});
app.use('/metrics', (req: IncomingMessage, res: ServerResponse) => {
prometheusExporter.getMetricsRequestHandler(req, res);
});
const { url, user, password } = app.get(natsConfig.KEY) as ConfigType<
typeof natsConfig
>;
app.connectMicroservice({
transport: Transport.NATS,
options: {
servers: [url],
user,
pass: password,
},
);
});
await app.startAllMicroservices();
const { hostname, port } = app.get(httpConfig.KEY) as ConfigType<
typeof httpConfig
>;
await app.listen(port, hostname);
await app.listen();
Logger.log(`Application is running on: ${await app.getUrl()}`);
/* c8 ignore stop */
import { randomBytes } from 'node:crypto';
import { Wait, GenericContainer, Network } from 'testcontainers';
export default async function setup() {
const natsCredentials = {
user: 'nats_' + randomBytes(8).toString('hex'),
password: randomBytes(16).toString('hex'),
};
const s3Credentials = {
secretKey: randomBytes(16).toString('hex'),
accessKey: randomBytes(16).toString('hex'),
};
const network = await new Network().start();
const [nats, minio] = await Promise.all([
new GenericContainer('nats')
.withNetwork(network)
.withExposedPorts(4222, 8222)
.withCommand([
'--config',
'nats-server.conf',
'--debug',
'--trace',
'--user',
natsCredentials.user,
'--pass',
natsCredentials.password,
])
.withWaitStrategy(Wait.forLogMessage('Server is ready'))
.start(),
new GenericContainer('minio/minio')
.withNetwork(network)
.withExposedPorts(9000, 9001)
.withEnvironment({
MINIO_ROOT_USER: 'minio',
MINIO_ROOT_PASSWORD: 'minio123',
})
.withCommand(['server', '/data', '--console-address', ':9001'])
.withWaitStrategy(
Wait.forLogMessage('Status: 1 Online, 0 Offline.'),
)
.start(),
]);
const s3URL = new URL('http://' + minio.getIpAddress(network.getName()));
s3URL.port = '9000';
const initS3 = await new GenericContainer('minio/mc')
.withNetwork(network)
.withEntrypoint(['/bin/sh', '-c'])
.withCommand([
`
/usr/bin/mc config host add ssi-s3 ${s3URL.toString()} minio minio123;
/usr/bin/mc mb --ignore-existing ssi-s3/ssi;
/usr/bin/mc anonymous set download ssi-s3/ssi;
/usr/bin/mc admin user add ssi-s3 ${s3Credentials.accessKey} ${s3Credentials.secretKey};
/usr/bin/mc admin policy attach ssi-s3 readwrite --user=${s3Credentials.accessKey};
exit 0;
`,
])
.start();
const natsURL = new URL('nats://' + nats.getHost());
natsURL.port = nats.getMappedPort(4222).toString();
const natsMonitoringURL = new URL('http://' + nats.getHost());
natsMonitoringURL.port = nats.getMappedPort(8222).toString();
process.env.NATS_URL = natsURL.toString();
process.env.NATS_USER = natsCredentials.user;
process.env.NATS_PASSWORD = natsCredentials.password;
process.env.NATS_MONITORING_URL = natsMonitoringURL.toString();
const tailsServerURL = new URL('http://' + minio.getHost());
tailsServerURL.port = minio.getMappedPort(9000).toString();
process.env.TAILS_SERVER_BASE_URL = tailsServerURL.toString();
process.env.TAILS_SERVER_BUCKET_NAME = 'ssi';
process.env.S3_ACCESS_KEY = s3Credentials.accessKey;
process.env.S3_SECRET = s3Credentials.secretKey;
Reflect.defineProperty(global, '__TESTCONTAINERS__', [nats, minio, initS3]);
}
import type { StartedTestContainer } from 'testcontainers';
export default async function teardown() {
const globalTestcontainers: StartedTestContainer[] = Reflect.get(
global,
'__TESTCONTAINERS__',
);
if (!globalTestcontainers) {
return;
}
await Promise.all(globalTestcontainers.map((container) => container.stop()));
}
import type { INestApplication } from '@nestjs/common';
import type { ClientProxy } from '@nestjs/microservices';
import type { EventInfoPublicDid } from '@ocm/shared';
import { DidDocument } from '@aries-framework/core';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { Test } from '@nestjs/testing';
import { firstValueFrom, type Observable } from 'rxjs';
import { AgentModule } from '../src/agent/agent.module.js';
import { AgentService } from '../src/agent/agent.service.js';
import { mockConfigModule } from '../src/config/__tests__/mockConfig.js';
const mockDidDocument = {
'@context': ['https://w3id.org/did/v1'],
id: 'did:indy:bcovrin:test:7KuDTpQh3GJ7Gp6kErpWvM',
verificationMethod: [
{
id: 'did:indy:bcovrin:test:7KuDTpQh3GJ7Gp6kErpWvM#verkey',
type: 'Ed25519VerificationKey2018',
controller: 'did:indy:bcovrin:test:7KuDTpQh3GJ7Gp6kErpWvM',
publicKeyBase58: '4SySYXQUtuK26zfC7RpQpWYMThfbXphUf8LWyXXmxyTX',
},
],
authentication: ['did:indy:bcovrin:test:7KuDTpQh3GJ7Gp6kErpWvM#verkey'],
};
describe('Agent', () => {
const TOKEN = 'AGENT_CLIENT_SERVICE';
let app: INestApplication;
let client: ClientProxy;
beforeAll(async () => {
jest
.spyOn(AgentService.prototype, 'getPublicDid')
.mockImplementation(() =>
Promise.resolve(new DidDocument(mockDidDocument)),
);
const moduleRef = await Test.createTestingModule({
imports: [
mockConfigModule(3000),
AgentModule,
ClientsModule.register([{ name: TOKEN, transport: Transport.NATS }]),
],
}).compile();
app = moduleRef.createNestApplication();
app.connectMicroservice({ transport: Transport.NATS });
await app.startAllMicroservices();
await app.init();
client = app.get(TOKEN);
await client.connect();
});
it('info.publicDid', async () => {
const response$: Observable<EventInfoPublicDid> = client.send(
'info.publicDid',
{},
);
const response = await firstValueFrom(response$);
expect(response.data).toMatchObject({
didDocument: mockDidDocument,
});
});
afterAll(async () => {
await app.close();
client.close();
});
});
import type { INestApplication } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import type { ClientProxy } from '@nestjs/microservices';
import type {
EventAnonCredsCredentialOfferGetAllInput,
EventAnonCredsCredentialOfferGetByIdInput,
EventAnonCredsCredentialRequestGetAllInput,
EventAnonCredsCredentialRequestGetByIdInput,
EventAnonCredsCredentialsDeleteByIdInput,
EventAnonCredsCredentialsGetAllInput,
EventAnonCredsCredentialsGetByIdInput,
EventDidcommAnonCredsCredentialsAcceptOfferInput,
EventDidcommAnonCredsCredentialsOfferInput,
EventDidcommAnonCredsCredentialsOfferToSelfInput,
} from '@ocm/shared';
import {
AutoAcceptCredential,
CredentialExchangeRecord,
CredentialRole,
CredentialState,
} from '@credo-ts/core';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { Test } from '@nestjs/testing';
import {
EventDidcommAnonCredsCredentialsAcceptOffer,
EventAnonCredsCredentialOfferGetAll,
EventAnonCredsCredentialOfferGetById,
EventAnonCredsCredentialRequestGetAll,
EventAnonCredsCredentialRequestGetById,
EventAnonCredsCredentialsDeleteById,
EventAnonCredsCredentialsGetAll,
EventAnonCredsCredentialsGetById,
EventDidcommAnonCredsCredentialsOffer,
EventDidcommAnonCredsCredentialsOfferToSelf,
} from '@ocm/shared';
import assert from 'assert';
import { randomBytes } from 'crypto';
import { firstValueFrom } from 'rxjs';
import { AgentModule } from '../src/agent/agent.module.js';
import { AnonCredsCredentialsModule } from '../src/agent/anoncredsCredentials/anoncredsCredentials.module.js';
import { ConnectionsModule } from '../src/agent/connections/connections.module.js';
import { ConnectionsService } from '../src/agent/connections/connections.service.js';
import { CredentialDefinitionsModule } from '../src/agent/credentialDefinitions/credentialDefinitions.module.js';
import { CredentialDefinitionsService } from '../src/agent/credentialDefinitions/credentialDefinitions.service.js';
import { DidsModule } from '../src/agent/dids/dids.module.js';
import { DidsService } from '../src/agent/dids/dids.service.js';
import { SchemasModule } from '../src/agent/schemas/schemas.module.js';
import { SchemasService } from '../src/agent/schemas/schemas.service.js';
import { TenantsModule } from '../src/agent/tenants/tenants.module.js';
import { TenantsService } from '../src/agent/tenants/tenants.service.js';
import { mockConfigModule } from '../src/config/__tests__/mockConfig.js';
import { natsConfig } from '../src/config/nats.config.js';
describe('Credentials', () => {
const TOKEN = 'CREDENTIALS_CLIENT_SERVICE';
let app: INestApplication;
let client: ClientProxy;
let tenantId: string;
let tenantIdTwo: string;
let issuerDid: string;
let credentialDefinitionId: string;
let connectionId: string;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
mockConfigModule(3004, true),
AgentModule,
ConnectionsModule,
SchemasModule,
CredentialDefinitionsModule,
AnonCredsCredentialsModule,
TenantsModule,
DidsModule,
ClientsModule.registerAsync({
clients: [
{
name: TOKEN,
inject: [natsConfig.KEY],
useFactory: ({
url,
user,
password,
}: ConfigType<typeof natsConfig>) => ({
transport: Transport.NATS,
options: { servers: [url], user, pass: password },
}),
},
],
}),
],
}).compile();
app = moduleRef.createNestApplication();
const natsOptions = app.get(natsConfig.KEY);
app.connectMicroservice({
transport: Transport.NATS,
options: {
servers: [natsOptions.url],
user: natsOptions.user,
pass: natsOptions.password,
},
});
await app.startAllMicroservices();
await app.init();
client = app.get(TOKEN);
await client.connect();
const tenantsService = app.get(TenantsService);
const { id } = await tenantsService.create({ label: TOKEN });
tenantId = id;
const { id: tIdTwo } = await tenantsService.create({
label: `${TOKEN}-two`,
});
tenantIdTwo = tIdTwo;
const connectionsService = app.get(ConnectionsService);
await connectionsService.createConnectionWithSelf({ tenantId });
const ds = app.get(DidsService);
await ds.registerEndorserDids();
const [did] = await ds.registerDidIndyFromSeed({
tenantId,
seed: randomBytes(16).toString('hex'),
});
issuerDid = did;
const schemaService = app.get(SchemasService);
const { schemaId } = await schemaService.register({
issuerDid,
tenantId,
name: 'test-schema-name',
version: `1.${Date.now()}`,
attributeNames: ['Name', 'Age'],
});
const credentialDefinitionService = app.get(CredentialDefinitionsService);
const { credentialDefinitionId: cdi } =
await credentialDefinitionService.register({
supportsRevocation: false,
tenantId,
issuerDid,
schemaId,
tag: `default-${Date.now()}`,
});
credentialDefinitionId = cdi;
const connectionService = app.get(ConnectionsService);
const { invitationUrl } = await connectionService.createInvitation({
tenantId: tenantIdTwo,
});
const connectionRecord = await connectionService.receiveInvitationFromUrl({
tenantId,
invitationUrl,
});
connectionId = connectionRecord.id;
await connectionService.waitUntilComplete({ connectionId });
});
afterAll(async () => {
await app.close();
client.close();
});
it(EventAnonCredsCredentialsGetAll.token, async () => {
const response$ = client.send<
EventAnonCredsCredentialsGetAll,
EventAnonCredsCredentialsGetAllInput
>(EventAnonCredsCredentialsGetAll.token, { tenantId });
const response = await firstValueFrom(response$);
const eventInstance = EventAnonCredsCredentialsGetAll.fromEvent(response);
expect(eventInstance.instance).toEqual(expect.arrayContaining([]));
});
it(EventAnonCredsCredentialOfferGetAll.token, async () => {
const response$ = client.send<
EventAnonCredsCredentialOfferGetAll,
EventAnonCredsCredentialOfferGetAllInput
>(EventAnonCredsCredentialOfferGetAll.token, { tenantId });
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialOfferGetAll.fromEvent(response);
expect(eventInstance.instance).toEqual(expect.arrayContaining([]));
});
it(EventAnonCredsCredentialOfferGetById.token, async () => {
const response$ = client.send<
EventAnonCredsCredentialOfferGetById,
EventAnonCredsCredentialOfferGetByIdInput
>(EventAnonCredsCredentialOfferGetById.token, {
tenantId,
credentialOfferId: 'some-id-that-does-not-exist',
});
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialOfferGetById.fromEvent(response);
expect(eventInstance.instance).toBeNull();
});
it(EventAnonCredsCredentialRequestGetAll.token, async () => {
const response$ = client.send<
EventAnonCredsCredentialRequestGetAll,
EventAnonCredsCredentialRequestGetAllInput
>(EventAnonCredsCredentialRequestGetAll.token, { tenantId });
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialRequestGetAll.fromEvent(response);
expect(eventInstance.instance).toEqual(expect.arrayContaining([]));
});
it(EventAnonCredsCredentialRequestGetById.token, async () => {
const response$ = client.send<
EventAnonCredsCredentialRequestGetById,
EventAnonCredsCredentialRequestGetByIdInput
>(EventAnonCredsCredentialRequestGetById.token, {
tenantId,
credentialRequestId: 'some-id-that-does-not-exist',
});
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialRequestGetById.fromEvent(response);
expect(eventInstance.instance).toBeNull();
});
it(EventAnonCredsCredentialsGetById.token, async () => {
const response$ = client.send<
EventAnonCredsCredentialsGetById,
EventAnonCredsCredentialsGetByIdInput
>(EventAnonCredsCredentialsGetById.token, {
tenantId,
credentialRecordId: 'some-id',
});
const response = await firstValueFrom(response$);
const eventInstance = EventAnonCredsCredentialsGetById.fromEvent(response);
expect(eventInstance.instance).toEqual(null);
});
it(EventDidcommAnonCredsCredentialsOffer.token, async () => {
const attributes = [
{ name: 'Name', value: 'Berend' },
{ name: 'Age', value: '25' },
];
const response$ = client.send<
EventDidcommAnonCredsCredentialsOffer,
EventDidcommAnonCredsCredentialsOfferInput
>(EventDidcommAnonCredsCredentialsOffer.token, {
tenantId,
connectionId,
attributes,
credentialDefinitionId,
});
const response = await firstValueFrom(response$);
const eventInstance =
EventDidcommAnonCredsCredentialsOffer.fromEvent(response);
expect(eventInstance.instance).toMatchObject({
state: CredentialState.OfferSent,
});
const getAllOffersResponse$ = client.send<
EventAnonCredsCredentialOfferGetAll,
EventAnonCredsCredentialOfferGetAllInput
>(EventAnonCredsCredentialOfferGetAll.token, {
tenantId: tenantIdTwo,
});
const getAllOffersResponse = await firstValueFrom(getAllOffersResponse$);
const getAllOffersEventInstance =
EventAnonCredsCredentialOfferGetAll.fromEvent(getAllOffersResponse);
const receivedOffer = getAllOffersEventInstance.instance.find(
(o) => o.state === CredentialState.OfferReceived,
);
expect(receivedOffer).toMatchObject({
state: CredentialState.OfferReceived,
});
assert(receivedOffer);
const acceptResponse$ = client.send<
EventDidcommAnonCredsCredentialsAcceptOffer,
EventDidcommAnonCredsCredentialsAcceptOfferInput
>(EventDidcommAnonCredsCredentialsAcceptOffer.token, {
tenantId: tenantIdTwo,
credentialId: receivedOffer.id,
});
const acceptResponse = await firstValueFrom(acceptResponse$);
const acceptEventInstance =
EventDidcommAnonCredsCredentialsOffer.fromEvent(acceptResponse);
expect(acceptEventInstance.instance).toMatchObject({
state: CredentialState.RequestSent,
});
await new Promise((r) => setTimeout(r, 2000));
const getAllCredentialsResponse$ = client.send<
EventAnonCredsCredentialsGetAll,
EventAnonCredsCredentialsGetAllInput
>(EventAnonCredsCredentialsGetAll.token, {
tenantId: tenantIdTwo,
});
const getAllCredentialsResponse = await firstValueFrom(
getAllCredentialsResponse$,
);
const getAllCredentialsEventInstance =
EventAnonCredsCredentialsGetAll.fromEvent(getAllCredentialsResponse);
const credential = getAllCredentialsEventInstance.instance.find(
(c) => c.id === receivedOffer.id,
);
expect(credential).toMatchObject({
id: receivedOffer.id,
state: CredentialState.Done,
role: CredentialRole.Holder,
credentialAttributes: expect.arrayContaining([
expect.objectContaining({ name: 'Name', value: 'Berend' }),
expect.objectContaining({ name: 'Age', value: '25' }),
]),
});
});
it(EventDidcommAnonCredsCredentialsOfferToSelf.token, async () => {
const attributes = [
{ name: 'Name', value: 'Berend' },
{ name: 'Age', value: '25' },
];
const response$ = client.send<
EventDidcommAnonCredsCredentialsOfferToSelf,
EventDidcommAnonCredsCredentialsOfferToSelfInput
>(EventDidcommAnonCredsCredentialsOfferToSelf.token, {
tenantId,
credentialDefinitionId,
attributes,
});
const response = await firstValueFrom(response$);
const eventInstance =
EventDidcommAnonCredsCredentialsOfferToSelf.fromEvent(response);
expect(eventInstance.instance).toMatchObject({
autoAcceptCredential: AutoAcceptCredential.Always,
role: CredentialRole.Holder,
state: CredentialState.Done,
});
// Sleep is done here so the last message can be received and we do not end up in a broken state.
// Without the sleep the broken state is reached because we still have to send to `ack` but we already shut down the agent when the test is finished.
await new Promise((r) => setTimeout(r, 1000));
});
it(EventAnonCredsCredentialsDeleteById.token, async () => {
let credentialExchangeRecord: CredentialExchangeRecord | undefined =
undefined;
// GET ALL
{
const response$ = client.send<
EventAnonCredsCredentialsGetAll,
EventAnonCredsCredentialsGetAllInput
>(EventAnonCredsCredentialsGetAll.token, { tenantId });
const response = await firstValueFrom(response$);
const eventInstance = EventAnonCredsCredentialsGetAll.fromEvent(response);
expect(eventInstance.instance).toEqual(expect.arrayContaining([]));
}
// Offer a credential
{
const attributes = [
{ name: 'Name', value: 'Berend' },
{ name: 'Age', value: '25' },
];
const response$ = client.send<
EventDidcommAnonCredsCredentialsOfferToSelf,
EventDidcommAnonCredsCredentialsOfferToSelfInput
>(EventDidcommAnonCredsCredentialsOfferToSelf.token, {
tenantId,
credentialDefinitionId,
attributes,
});
const response = await firstValueFrom(response$);
const eventInstance =
EventDidcommAnonCredsCredentialsOfferToSelf.fromEvent(response);
expect(eventInstance.instance).toMatchObject({
autoAcceptCredential: AutoAcceptCredential.Always,
});
credentialExchangeRecord = eventInstance.instance;
}
// GET THE CREDENTIAL BY ID
{
const response$ = client.send<
EventAnonCredsCredentialsGetById,
EventAnonCredsCredentialsGetByIdInput
>(EventAnonCredsCredentialsGetById.token, {
tenantId,
credentialRecordId: credentialExchangeRecord.id,
});
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialsGetById.fromEvent(response);
expect(eventInstance.instance).toBeInstanceOf(CredentialExchangeRecord);
}
// DELETE THE CREDENTIAL
{
const response$ = client.send<
EventAnonCredsCredentialsDeleteById,
EventAnonCredsCredentialsDeleteByIdInput
>(EventAnonCredsCredentialsDeleteById.token, {
tenantId,
credentialRecordId: credentialExchangeRecord.id,
});
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialsDeleteById.fromEvent(response);
expect(eventInstance).toMatchObject({});
}
// GET THE CREDENTIAL BY ID
{
const response$ = client.send<
EventAnonCredsCredentialsGetById,
EventAnonCredsCredentialsGetByIdInput
>(EventAnonCredsCredentialsGetById.token, {
tenantId,
credentialRecordId: credentialExchangeRecord.id,
});
const response = await firstValueFrom(response$);
const eventInstance =
EventAnonCredsCredentialsGetById.fromEvent(response);
expect(eventInstance.instance).toBeNull();
}
});
});
import type { INestApplication } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import type { ClientProxy } from '@nestjs/microservices';
import type {
EventAnonCredsProofsGetAllInput,
EventAnonCredsProofsGetByIdInput,
EventDidcommAnonCredsProofsRequestInput,
} from '@ocm/shared';
import { ProofState } from '@credo-ts/core';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { Test } from '@nestjs/testing';
import {
EventAnonCredsProofsGetAll,
EventAnonCredsProofsGetById,
EventDidcommAnonCredsProofsRequest,
} from '@ocm/shared';
import { firstValueFrom } from 'rxjs';
import { natsConfig } from '../dist/config/nats.config.js';
import { AgentModule } from '../src/agent/agent.module.js';
import { AnonCredsProofsModule } from '../src/agent/anoncredsProofs/anoncredsProofs.module.js';
import { ConnectionsModule } from '../src/agent/connections/connections.module.js';
import { ConnectionsService } from '../src/agent/connections/connections.service.js';
import { DidsModule } from '../src/agent/dids/dids.module.js';
import { TenantsModule } from '../src/agent/tenants/tenants.module.js';
import { TenantsService } from '../src/agent/tenants/tenants.service.js';
import { mockConfigModule } from '../src/config/__tests__/mockConfig.js';
describe('Proofs', () => {
const TOKEN = 'PROOFS_CLIENT_SERVICE';
let app: INestApplication;
let client: ClientProxy;
let tenantId: string;
let connectionId: string;
let credentialDefinitionId: string;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
mockConfigModule(3004, true),
AgentModule,
ConnectionsModule,
AnonCredsProofsModule,
TenantsModule,
DidsModule,
ClientsModule.registerAsync({
clients: [
{
name: TOKEN,
inject: [natsConfig.KEY],
useFactory: ({
url,
user,
password,
}: ConfigType<typeof natsConfig>) => ({
transport: Transport.NATS,
options: { servers: [url], user, pass: password },
}),
},
],
}),
],
}).compile();
app = moduleRef.createNestApplication();
const natsOptions = app.get(natsConfig.KEY);
app.connectMicroservice({
transport: Transport.NATS,
options: {
servers: [natsOptions.url],
user: natsOptions.user,
pass: natsOptions.password,
},
});
await app.startAllMicroservices();
await app.init();
client = app.get(TOKEN);
await client.connect();
const tenantsService = app.get(TenantsService);
const { id: tId } = await tenantsService.create({ label: TOKEN });
tenantId = tId;
const connectionsService = app.get(ConnectionsService);
const { id } = await connectionsService.createConnectionWithSelf({
tenantId,
});
connectionId = id;
});
afterAll(async () => {
await app.close();
client.close();
});
it(EventAnonCredsProofsGetAll.token, async () => {
const response$ = client.send<
EventAnonCredsProofsGetAll,
EventAnonCredsProofsGetAllInput
>(EventAnonCredsProofsGetAll.token, { tenantId });
const response = await firstValueFrom(response$);
const eventInstance = EventAnonCredsProofsGetAll.fromEvent(response);
expect(eventInstance.instance).toEqual(expect.arrayContaining([]));
});
it(EventAnonCredsProofsGetById.token, async () => {
const response$ = client.send<
EventAnonCredsProofsGetById,
EventAnonCredsProofsGetByIdInput
>(EventAnonCredsProofsGetById.token, {
tenantId,
proofRecordId: 'some-id',
});
const response = await firstValueFrom(response$);
const eventInstance = EventAnonCredsProofsGetById.fromEvent(response);
expect(eventInstance.instance).toEqual(null);
});
it(EventDidcommAnonCredsProofsRequest.token, async () => {
const response$ = client.send<
EventDidcommAnonCredsProofsRequest,
EventDidcommAnonCredsProofsRequestInput
>(EventDidcommAnonCredsProofsRequest.token, {
tenantId,
name: 'My Test Proof Request',
connectionId,
requestedAttributes: {
Identity: {
names: ['Name'],
restrictions: [{ cred_def_id: credentialDefinitionId }],
},
},
requestedPredicates: {
'Age > 21': {
name: 'Age',
restrictions: [{ cred_def_id: credentialDefinitionId }],
predicateType: '>',
predicateValue: 21,
},
},
});
const response = await firstValueFrom(response$);
const eventInstance =
EventDidcommAnonCredsProofsRequest.fromEvent(response);
expect(eventInstance.instance).toMatchObject({
state: ProofState.RequestSent,
});
});
});