atproto/packages/crypto/tests/signatures.test.ts
Matthieu Sieben f689bd51a2
Build system rework (#2169)
* refactor(crypto): remove circular dependency

* refactor(crypto): expose compress/decompress as part of the DidKeyPlugin interface

* fix(crypto): remove import from private file

* refactor: isolate tsconfig

* fix: remove unused bench file

* chore(repo): remove unused deps

* fix(ozone): properly list dependencies

* fix(services): do lint js files

* fix(services/pds): remove unused deps

* chore(pds): remove bench

* chore(dev-env): remove unused deps

* chore(api): remove bench

* remove unused babel.config.js files

* fix: remove .ts extension from import

* fix(pds): remove imports of src files

* fix(tsconfig): properly list all projects

* fix(dev-env): remove imports of src files

* fix(bsky): remove direct import to crypto src

* fix(api): remove imports to api internals

* chore(build): prevent bundling of built output

* chore(dev): add "dev" script to build in watch mode

* chore(deps): move ts-node dependency where it is actually used

* fix(deps): add dev-env as project dependency

* fix(xrpc-server): properly type kexicon

* fix(bsky): improve typings

* fix(pds): fully type formatRecordEmbedInternal return value

* fix(repo): remove imports from @ipld/car/api

* feat(dev-env): re-export BskyIngester

* fix: properly lint & type jest config & test files

* fix(ci): test after build

* fix(types): use NodeJS.Timeout instead of NodeJS.Timer

* fix(bsky): make types exportable

* fix(ozone): make types exportable

* fix(xrpc-server): make types exportable

* fix(xprc-server): make code compliant with "node" types

* fix(xrpc-server): avoid accessing properties of unknown

* chore(deps): update @types/node

* feat(tsconfig): narrow down available types depending on the package's target environment

* fix(pds): remove unused prop

* fix(bsync): Database's migrator not always initialized

* fix(dev-env): remove unreachable code

* fix(xrpc-server): remove unused import

* fix(xrpc-server): mark header property as abstract

* fix(pds): initialize LeakyTxPlugin's txOver property

* fix(bsky): initialize LeakyTxPlugin's txOver property

* fix(bsky): remove unused migrator from DatabaseCoordinator

* fix(bsky): Properly initialize LabelService's cache property

* fix(ozone): Database's migrator not initialized

* fix(ozone): initialize LeakyTxPlugin's txOver property

* fix(crypto): ignore unused variable error

* feat(tsconfig): use stricter rules

* feat(tsconfig): enable useDefineForClassFields

* feat(xrpc-server): add support for brotli incoming payload

* fix(xrpc-server): properly parse & process content-encoding

* fix(common:stream): always call cb in _transform

* tidy/fix tests and service entrypoints

* Revert "fix(xrpc-server): properly parse & process content-encoding"

This reverts commit 2b1c66e153820d3e128fc839fcc1834d52a66686.

* Revert "feat(xrpc-server): add support for brotli incoming payload"

This reverts commit e710c21e6118214ddf215b0515e68cb87299a952.

* remove special node env for tests (defaults to jest val of "test")

* kill mute sync handler on disconnect

* work around connect-es bug w/ request aborts

* style(crypto): rename imports from uint8arrays

* fix update package-lock

* fix lint

* force hbs files to be bundled as cjs

* fix: use concurrently instead of npm-run-all

npm-run-all seems not to be maintained anymore. Additionally, concurrently better forwards signals to child processes.

* remove concurrently alltogether

* ignore sqlite files in services/pds

* fix verify

* fix verify

* tidy, fix verify

* fix blob diversion test

* build rework changeset

---------

Co-authored-by: Devin Ivy <devinivy@gmail.com>
2024-03-18 17:10:58 -04:00

298 lines
8.9 KiB
TypeScript

import fs from 'node:fs'
import * as uint8arrays from 'uint8arrays'
import { secp256k1 as nobleK256 } from '@noble/curves/secp256k1'
import { p256 as nobleP256 } from '@noble/curves/p256'
import { cborEncode } from '@atproto/common'
import EcdsaKeypair from '../src/p256/keypair'
import Secp256k1Keypair from '../src/secp256k1/keypair'
import * as p256 from '../src/p256/operations'
import * as secp from '../src/secp256k1/operations'
import {
bytesToMultibase,
multibaseToBytes,
parseDidKey,
P256_JWT_ALG,
SECP256K1_JWT_ALG,
sha256,
} from '../src'
describe('signatures', () => {
let vectors: TestVector[]
beforeAll(() => {
vectors = JSON.parse(
fs.readFileSync(`${__dirname}/signature-fixtures.json`).toString(),
)
})
it('verifies secp256k1 and P-256 test vectors', async () => {
for (const vector of vectors) {
const messageBytes = uint8arrays.fromString(
vector.messageBase64,
'base64',
)
const signatureBytes = uint8arrays.fromString(
vector.signatureBase64,
'base64',
)
const keyBytes = multibaseToBytes(vector.publicKeyMultibase)
const didKey = parseDidKey(vector.publicKeyDid)
expect(uint8arrays.equals(keyBytes, didKey.keyBytes))
if (vector.algorithm === P256_JWT_ALG) {
const verified = await p256.verifySig(
keyBytes,
messageBytes,
signatureBytes,
)
expect(verified).toEqual(vector.validSignature)
} else if (vector.algorithm === SECP256K1_JWT_ALG) {
const verified = await secp.verifySig(
keyBytes,
messageBytes,
signatureBytes,
)
expect(verified).toEqual(vector.validSignature)
} else {
throw new Error('Unsupported test vector')
}
}
})
it('verifies high-s signatures with explicit option', async () => {
const highSVectors = vectors.filter((vec) => vec.tags.includes('high-s'))
expect(highSVectors.length).toBeGreaterThanOrEqual(2)
for (const vector of highSVectors) {
const messageBytes = uint8arrays.fromString(
vector.messageBase64,
'base64',
)
const signatureBytes = uint8arrays.fromString(
vector.signatureBase64,
'base64',
)
const keyBytes = multibaseToBytes(vector.publicKeyMultibase)
const didKey = parseDidKey(vector.publicKeyDid)
expect(uint8arrays.equals(keyBytes, didKey.keyBytes))
if (vector.algorithm === P256_JWT_ALG) {
const verified = await p256.verifySig(
keyBytes,
messageBytes,
signatureBytes,
{ allowMalleableSig: true },
)
expect(verified).toEqual(true)
expect(vector.validSignature).toEqual(false) // otherwise would fail per low-s requirement
} else if (vector.algorithm === SECP256K1_JWT_ALG) {
const verified = await secp.verifySig(
keyBytes,
messageBytes,
signatureBytes,
{ allowMalleableSig: true },
)
expect(verified).toEqual(true)
expect(vector.validSignature).toEqual(false) // otherwise would fail per low-s requirement
} else {
throw new Error('Unsupported test vector')
}
}
})
it('verifies der-encoded signatures with explicit option', async () => {
const DERVectors = vectors.filter((vec) => vec.tags.includes('der-encoded'))
expect(DERVectors.length).toBeGreaterThanOrEqual(2)
for (const vector of DERVectors) {
const messageBytes = uint8arrays.fromString(
vector.messageBase64,
'base64',
)
const signatureBytes = uint8arrays.fromString(
vector.signatureBase64,
'base64',
)
const keyBytes = multibaseToBytes(vector.publicKeyMultibase)
const didKey = parseDidKey(vector.publicKeyDid)
expect(uint8arrays.equals(keyBytes, didKey.keyBytes))
if (vector.algorithm === P256_JWT_ALG) {
const verified = await p256.verifySig(
keyBytes,
messageBytes,
signatureBytes,
{ allowMalleableSig: true },
)
expect(verified).toEqual(true)
expect(vector.validSignature).toEqual(false) // otherwise would fail per low-s requirement
} else if (vector.algorithm === SECP256K1_JWT_ALG) {
const verified = await secp.verifySig(
keyBytes,
messageBytes,
signatureBytes,
{ allowMalleableSig: true },
)
expect(verified).toEqual(true)
expect(vector.validSignature).toEqual(false) // otherwise would fail per low-s requirement
} else {
throw new Error('Unsupported test vector')
}
}
})
})
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function generateTestVectors(): Promise<TestVector[]> {
const p256Key = await EcdsaKeypair.create({ exportable: true })
const secpKey = await Secp256k1Keypair.create({ exportable: true })
const messageBytes = cborEncode({ hello: 'world' })
const messageBase64 = uint8arrays.toString(messageBytes, 'base64')
return [
{
messageBase64,
algorithm: P256_JWT_ALG, // "ES256" / ecdsa p-256
publicKeyDid: p256Key.did(),
publicKeyMultibase: bytesToMultibase(
p256Key.publicKeyBytes(),
'base58btc',
),
signatureBase64: uint8arrays.toString(
await p256Key.sign(messageBytes),
'base64',
),
validSignature: true,
tags: [],
},
{
messageBase64,
algorithm: SECP256K1_JWT_ALG, // "ES256K" / secp256k
publicKeyDid: secpKey.did(),
publicKeyMultibase: bytesToMultibase(
secpKey.publicKeyBytes(),
'base58btc',
),
signatureBase64: uint8arrays.toString(
await secpKey.sign(messageBytes),
'base64',
),
validSignature: true,
tags: [],
},
// these vectors test to ensure we don't allow high-s signatures
{
messageBase64,
algorithm: P256_JWT_ALG, // "ES256" / ecdsa p-256
publicKeyDid: p256Key.did(),
publicKeyMultibase: bytesToMultibase(
p256Key.publicKeyBytes(),
'base58btc',
),
signatureBase64: await makeHighSSig(
messageBytes,
await p256Key.export(),
P256_JWT_ALG,
),
validSignature: false,
tags: ['high-s'],
},
{
messageBase64,
algorithm: SECP256K1_JWT_ALG, // "ES256K" / secp256k
publicKeyDid: secpKey.did(),
publicKeyMultibase: bytesToMultibase(
secpKey.publicKeyBytes(),
'base58btc',
),
signatureBase64: await makeHighSSig(
messageBytes,
await secpKey.export(),
SECP256K1_JWT_ALG,
),
validSignature: false,
tags: ['high-s'],
},
// these vectors test to ensure we don't allow der-encoded signatures
{
messageBase64,
algorithm: P256_JWT_ALG, // "ES256" / ecdsa p-256
publicKeyDid: p256Key.did(),
publicKeyMultibase: bytesToMultibase(
p256Key.publicKeyBytes(),
'base58btc',
),
signatureBase64: await makeDerEncodedSig(
messageBytes,
await p256Key.export(),
P256_JWT_ALG,
),
validSignature: false,
tags: ['der-encoded'],
},
{
messageBase64,
algorithm: SECP256K1_JWT_ALG, // "ES256K" / secp256k
publicKeyDid: secpKey.did(),
publicKeyMultibase: bytesToMultibase(
secpKey.publicKeyBytes(),
'base58btc',
),
signatureBase64: await makeDerEncodedSig(
messageBytes,
await secpKey.export(),
SECP256K1_JWT_ALG,
),
validSignature: false,
tags: ['der-encoded'],
},
]
}
async function makeHighSSig(
msgBytes: Uint8Array,
keyBytes: Uint8Array,
alg: string,
): Promise<string> {
const hash = await sha256(msgBytes)
let sig: string | undefined
do {
if (alg === SECP256K1_JWT_ALG) {
const attempt = await nobleK256.sign(hash, keyBytes, { lowS: false })
if (attempt.hasHighS()) {
sig = uint8arrays.toString(attempt.toCompactRawBytes(), 'base64')
}
} else {
const attempt = await nobleP256.sign(hash, keyBytes, { lowS: false })
if (attempt.hasHighS()) {
sig = uint8arrays.toString(attempt.toCompactRawBytes(), 'base64')
}
}
} while (sig === undefined)
return sig
}
async function makeDerEncodedSig(
msgBytes: Uint8Array,
keyBytes: Uint8Array,
alg: string,
): Promise<string> {
const hash = await sha256(msgBytes)
let sig: string
if (alg === SECP256K1_JWT_ALG) {
const attempt = await nobleK256.sign(hash, keyBytes, { lowS: true })
sig = uint8arrays.toString(attempt.toDERRawBytes(), 'base64')
} else {
const attempt = await nobleP256.sign(hash, keyBytes, { lowS: true })
sig = uint8arrays.toString(attempt.toDERRawBytes(), 'base64')
}
return sig
}
type TestVector = {
algorithm: string
publicKeyDid: string
publicKeyMultibase: string
messageBase64: string
signatureBase64: string
validSignature: boolean
tags: string[]
}