Skip to content

Utilise Eddsa & Public Keys - Part 2 #792

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9354954
Update public key param in bpiSubject model
biscuitdey Apr 1, 2024
9273b60
Handle Eddsa public keys in BpiSubject
biscuitdey Apr 1, 2024
35a2aa8
Update authAgent to handle publicKeys
biscuitdey Apr 1, 2024
e9c459e
Update message tests to handle public keys
biscuitdey Apr 1, 2024
d26e7e5
Use publicKeys in messaging
biscuitdey Apr 1, 2024
a770b95
Add comments on Ecdsa and Eddsa
biscuitdey Apr 12, 2024
9d781f9
Add publicKeyDto to BpiSubject
biscuitdey Apr 12, 2024
b3edae7
Add publicKeyDto to response bpiSubjectDto
biscuitdey Apr 12, 2024
b2080cc
Add publicKeyDto to commandHandler
biscuitdey Apr 12, 2024
9f3a896
Build fix
biscuitdey Apr 12, 2024
3d42679
Add valid Eddsa public key to seed.ts
biscuitdey Apr 15, 2024
47c2c14
Revert mapper changes
biscuitdey Apr 15, 2024
9897c83
Remove unnecessary code from updateBpiSubject
biscuitdey Apr 15, 2024
5965541
Revert unnecessary changes to updateBpiSubject
biscuitdey Apr 15, 2024
89eb98d
Change let to const in circuitInputParser
biscuitdey Apr 15, 2024
e964f80
Update publicKeys in bpiSubjectStorageAgent
biscuitdey Apr 15, 2024
7e1623d
Add MerkleTree agent, storageAgent, service as provider
biscuitdey Apr 15, 2024
3a52e5c
Bug fix updateBpiSubject test
biscuitdey Apr 15, 2024
7b845c4
Update transaction.spec.ts tests to accept publicKeys
biscuitdey Apr 15, 2024
e7b9532
Change updateMany to upsert in BpiSubjectStorage agent
biscuitdey Apr 15, 2024
ed13e53
Bug fix in updateBpiSubject
biscuitdey Apr 15, 2024
1bffe23
Update bpiSubject publicKeys
biscuitdey Apr 15, 2024
aac947f
Merge branch 'feature/759-public-key-test-pass-1' into feature/759-pu…
biscuitdey Apr 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 29 additions & 11 deletions examples/bri-3/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PrismaClient } from '@prisma/client';
import { PrismaClient, PublicKeyType } from '@prisma/client';
import { type } from 'os';

const prisma = new PrismaClient();

Expand All @@ -23,17 +24,34 @@ async function main() {

await prisma.bpiSubject.create({
data: {
name: 'BpiAdmin',
description: 'Internal Bpi Subject of this Bpi',
publicKey: '0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
// private key 0x0fbdb56ab0fecb2f406fa807d9e6558baedacc1c15c0e2703b77d4c08441e4fe, used for testing purposes only
loginNonce: '',
roles: {
connect: {
id: internalBpiSubjectRole.id
},
name: 'BpiAdmin',
description: 'Internal Bpi Subject of this Bpi',
publicKeys: {
createMany: {
data: [
{
type: PublicKeyType.ECDSA,
value:
'0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
},
// private key 0x0fbdb56ab0fecb2f406fa807d9e6558baedacc1c15c0e2703b77d4c08441e4fe, used for testing purposes only
{
type: PublicKeyType.EDDSA,
value:
'0x038a312f5b75fbd4f677c080c7f35089c898f2cb75002d659e051fdc1c6b3e06',
},
// TODO private key
],
},
}
},

loginNonce: '',
roles: {
connect: {
id: internalBpiSubjectRole.id,
},
},
},
});
}
main()
Expand Down
42 changes: 40 additions & 2 deletions examples/bri-3/src/bri/auth/agent/auth.agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { BpiSubject } from '../../../bri/identity/bpiSubjects/models/bpiSubject'
import { LoggingService } from '../../../shared/logging/logging.service';
import { INVALID_SIGNATURE, USER_NOT_AUTHORIZED } from '../api/err.messages';
import { jwtConstants } from '../constants';
import { buildBabyjub, buildEddsa } from 'circomlibjs';
import * as crypto from 'crypto';

@Injectable()
export class AuthAgent {
Expand All @@ -23,12 +25,14 @@ export class AuthAgent {
signature: string,
publicKey: string,
): void {
if (!this.verifySignatureAgainstPublicKey(message, signature, publicKey)) {
if (
!this.verifyEcdsaSignatureAgainstPublicKey(message, signature, publicKey)
) {
throw new UnauthorizedException(INVALID_SIGNATURE);
}
}

verifySignatureAgainstPublicKey(
verifyEcdsaSignatureAgainstPublicKey(
message: string,
signature: string,
senderPublicKey: string,
Expand Down Expand Up @@ -63,6 +67,40 @@ export class AuthAgent {
return isValid;
}

async verifyEddsaSignatureAgainstPublicKey(
message: string,
signature: string,
senderPublicKey: string,
): Promise<boolean> {
const eddsa = await buildEddsa();
const babyJub = await buildBabyjub();

const hashedPayload = crypto
.createHash(`${process.env.MERKLE_TREE_HASH_ALGH}`)
.update(JSON.stringify(message))
.digest();

const publicKey = Uint8Array.from(Buffer.from(signature, 'hex'));
const publicKeyPoints = babyJub.unpackPoint(publicKey);

const eddsaSignature = Uint8Array.from(Buffer.from(signature, 'hex'));
const unpackedSignature = eddsa.unpackSignature(eddsaSignature);

const isValid = eddsa.verifyPedersen(
hashedPayload,
unpackedSignature,
publicKeyPoints,
);

if (!isValid) {
this.logger.logWarn(
`Signature: ${signature} for public key ${senderPublicKey} is invalid.`,
);
}

return isValid;
}

async getBpiSubjectByPublicKey(publicKey: string) {
return this.bpiSubjectStorageAgent.getBpiSubjectByPublicKey(publicKey);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ import { MessageController } from './messages.controller';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { PrismaService } from '../../../shared/prisma/prisma.service';
import { PrismaClient } from '@prisma/client';
import {
PublicKey,
PublicKeyType,
} from '../../identity/bpiSubjects/models/publicKey';

describe('MessageController', () => {
let mController: MessageController;
Expand All @@ -52,20 +56,37 @@ describe('MessageController', () => {
});

beforeEach(async () => {
existingBpiSubject1 = new BpiSubject(
'',
'name',
'desc',
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
[],
);
existingBpiSubject2 = new BpiSubject(
'',
'name2',
'desc2',
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
[],
);
const publicKeys1 = [
new PublicKey(
'111',
PublicKeyType.ECDSA,
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
'123',
),
new PublicKey(
'112',
PublicKeyType.EDDSA,
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
'123',
),
];
existingBpiSubject1 = new BpiSubject('', 'name', 'desc', publicKeys1, []);

const publicKeys2 = [
new PublicKey(
'111',
PublicKeyType.ECDSA,
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
'123',
),
new PublicKey(
'112',
PublicKeyType.EDDSA,
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
'123',
),
];
existingBpiSubject2 = new BpiSubject('', 'name2', 'desc2', publicKeys2, []);

existingBpiMessage = new BpiMessage(
'f3e4295d-6a2a-4f04-8477-02f781eb93f8',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BpiMessageAgent } from '../../agents/bpiMessages.agent';
import { BpiMessageStorageAgent } from '../../agents/bpiMessagesStorage.agent';
import { MessagingAgent } from '../../agents/messaging.agent';
import { CreateBpiMessageCommand } from './createBpiMessage.command';
import { PublicKeyType } from '../../../identity/bpiSubjects/models/publicKey';

@CommandHandler(CreateBpiMessageCommand)
export class CreateBpiMessageCommandHandler
Expand All @@ -30,7 +31,9 @@ export class CreateBpiMessageCommandHandler
this.authAgent.throwIfSignatureVerificationFails(
command.content,
command.signature,
fromBpiSubject.publicKey,
fromBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.ECDSA,
)[0].value,
);

const newBpiMessageCandidate = this.agent.createNewBpiMessage(
Expand All @@ -47,7 +50,9 @@ export class CreateBpiMessageCommandHandler
);

await this.messagingAgent.publishMessage(
toBpiSubject.publicKey,
toBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.ECDSA,
)[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BpiMessageAgent } from '../../agents/bpiMessages.agent';
import { BpiMessageStorageAgent } from '../../agents/bpiMessagesStorage.agent';
import { MessagingAgent } from '../../agents/messaging.agent';
import { ProcessInboundBpiMessageCommand } from './processInboundMessage.command';
import { PublicKeyType } from '../../../identity/bpiSubjects/models/publicKey';

// Difference between this and the create bpi message command handler is that this one does not
// stop the execution flow by throwing a nestjs exception (which results in 404 response in the other handler)
Expand Down Expand Up @@ -31,11 +32,14 @@ export class ProcessInboundMessageCommandHandler
return false;
}

const isSignatureValid = this.authAgent.verifySignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKey,
);
const isSignatureValid =
this.authAgent.verifyEddsaSignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.EDDSA,
)[0].value,
);

if (!isSignatureValid) {
return false;
Expand All @@ -55,7 +59,9 @@ export class ProcessInboundMessageCommandHandler
);

await this.messagingAgent.publishMessage(
toBpiSubject.publicKey,
toBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.ECDSA,
)[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { SubjectsProfile } from '../../bpiSubjects/subjects.profile';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { BpiSubjectAccount } from '../models/bpiSubjectAccount';
import { uuid } from 'uuidv4';
import { PublicKey, PublicKeyType } from '../../bpiSubjects/models/publicKey';

describe('SubjectAccountController', () => {
let subjectAccountController: SubjectAccountController;
Expand Down Expand Up @@ -70,14 +71,14 @@ describe('SubjectAccountController', () => {
'123',
'owner',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '123')],
[],
);
const creatorBpiSubject = new BpiSubject(
'321',
'creator',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '321')],
[],
);

Expand Down Expand Up @@ -195,7 +196,7 @@ describe('SubjectAccountController', () => {
'123',
'owner',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '123')],
[],
);
const creatorBpiSubjectId = 'not-existing-id';
Expand All @@ -219,7 +220,7 @@ describe('SubjectAccountController', () => {
'123',
'creator',
'desc',
'publicKey',
[new PublicKey('223', PublicKeyType.ECDSA, 'publicKey', '123')],
[],
);
const ownerBpiSubjectId = 'not-existing-id';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
} from '../api/err.messages';
import { BpiSubjectStorageAgent } from './bpiSubjectsStorage.agent';
import { BpiSubjectRoleName } from '../models/bpiSubjectRole';
import { PublicKeyDto } from '../api/dtos/request/publicKey.dto';
import { PublicKey, PublicKeyType } from '../models/publicKey';

// Agent methods have extremely declarative names and perform a single task
@Injectable()
Expand All @@ -27,12 +29,36 @@ export class BpiSubjectAgent {
public async createNewExternalBpiSubject(
name: string,
description: string,
publicKey: string,
publicKeys: PublicKeyDto[],
): Promise<BpiSubject> {
const externalRole = await this.storageAgent.getBpiSubjectRoleByName(
BpiSubjectRoleName.EXTERNAL_BPI_SUBJECT,
);
return new BpiSubject(v4(), name, description, publicKey, [externalRole]);

const bpiSubjectId = v4();

const publicKeyCandidates = publicKeys.map((key) => {
let publicKeyType;

switch (key.type.toLowerCase()) {
case 'ecdsa':
publicKeyType = PublicKeyType.ECDSA;
break;
case 'eddsa':
publicKeyType = PublicKeyType.EDDSA;
break;
default:
}
return new PublicKey(v4(), publicKeyType, key.value, bpiSubjectId);
});

return new BpiSubject(
bpiSubjectId,
name,
description,
publicKeyCandidates,
[externalRole],
);
}

public async fetchUpdateCandidateAndThrowIfUpdateValidationFails(
Expand Down Expand Up @@ -64,11 +90,11 @@ export class BpiSubjectAgent {
bpiSubjectToUpdate: BpiSubject,
name: string,
description: string,
publicKey: string,
publicKeys: PublicKeyDto[],
) {
bpiSubjectToUpdate.updateName(name);
bpiSubjectToUpdate.updateDescription(description);
bpiSubjectToUpdate.updatePublicKey(publicKey);
bpiSubjectToUpdate.updatePublicKeys(publicKeys);
}

public async fetchDeleteCandidateAndThrowIfDeleteValidationFails(
Expand Down
Loading
Loading