Skip to content
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

(Chore) GoodID API unit tests & fixes #462

Merged
merged 2 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
225 changes: 225 additions & 0 deletions src/server/goodid/__tests__/goodidAPI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { get } from 'lodash'
import request from 'supertest'
import { sha3 } from 'web3-utils'

import UserDBPrivate from '../../db/mongo/user-privat-provider'

import makeServer from '../../server-test'
import { getCreds, getToken } from '../../__util__'

describe('goodidAPI', () => {
let server
let token
let creds
const issueLocationCertificateUri = '/goodid/certificate/location'
const verifyCertificateUri = '/goodid/certificate/verify'

const assertCountryCode =
code =>
({ body }) => {
const { countryCode } = get(body, 'ceriticate.credentialSubject', {})

if (countryCode !== code) {
throw new Error(`expected ${code}, got ${countryCode}`)
}
}

const setUserData = ({ mobile, ...data }) =>
UserDBPrivate.updateUser({
identifier: creds.address,
mobile: mobile ? sha3(mobile) : null,
...data
})

const testIPUA = '178.158.235.10'
const testIPBR = '130.185.238.1'

const testLocationPayloadUA = {
timestamp: 1707313563,
coords: {
longitude: 30.394171,
latitude: 50.328899,
accuracy: null,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null
}
}

const testUserPayloadUA = {
mobile: '+380639549357'
}

const testUserPayloadBR = {
mobile: '+5531971416384'
}

const testCertificate = {
credentialSubject: {
countryCode: 'UA',
id: 'did:ethr:0x7ac080f6607405705aed79675789701a48c76f55'
},
issuer: { id: 'did:key:z6MktGpZnw8NtAjmvQdsyiMAHwCJYzq5kBAS2yWyoX1DVoFe' },
type: ['VerifiableCredential', 'VerifiableLocationCredential'],
'@context': ['https://www.w3.org/2018/credentials/v1'],
issuanceDate: '2024-02-28T22:35:11.000Z',
proof: {
type: 'JwtProof2020',
jwt: 'eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJ2YyI6eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSJdLCJ0eXBlIjpbIlZlcmlmaWFibGVDcmVkZW50aWFsIiwiVmVyaWZpYWJsZUxvY2F0aW9uQ3JlZGVudGlhbCJdLCJjcmVkZW50aWFsU3ViamVjdCI6eyJjb3VudHJ5Q29kZSI6IlVBIn19LCJzdWIiOiJkaWQ6ZXRocjoweDdhYzA4MGY2NjA3NDA1NzA1YWVkNzk2NzU3ODk3MDFhNDhjNzZmNTUiLCJuYmYiOjE3MDkxNTk3MTEsImlzcyI6ImRpZDprZXk6ejZNa3RHcFpudzhOdEFqbXZRZHN5aU1BSHdDSll6cTVrQkFTMnlXeW9YMURWb0ZlIn0.VWQKMqFoZvpGzXheDV3H9N7XaVEe4E0jmQgRQ3isKfyJwHPQm5I0W77nRimYyd4Km9iz4UUTWhVrkXHVffj4Cw'
}
}

beforeAll(async () => {
jest.setTimeout(50000)
server = await makeServer()
creds = await getCreds()
token = await getToken(server, creds)

console.log('goodidAPI: server ready')
console.log({ server })
})

beforeEach(async () => {
await setUserData({
mobile: null,
smsValidated: false
})
})

afterAll(async () => {
await new Promise(res =>
server.close(err => {
console.log('verificationAPI: closing server', { err })
res()
})
)
})

test('GoodID endpoints returns 401 without credentials', async () => {
await Promise.all(
[issueLocationCertificateUri, verifyCertificateUri].map(uri => request(server).post(uri).send({}).expect(401))
)
})

test('Location certificate: should fail on empty data', async () => {
await request(server)
.post(issueLocationCertificateUri)
.send({})
.set('Authorization', `Bearer ${token}`)
.expect(400, {
success: false,
error: 'Failed to verify location: missing geolocation data'
})
})

test('Location certificate: should fail if geo data does not match IP', async () => {
await request(server)
.post(issueLocationCertificateUri)
.send({
geoposition: testLocationPayloadUA
})
.set('Authorization', `Bearer ${token}`)
.set('X-Forwarded-For', testIPBR)
.expect(400, {
success: false,
error: 'Country of Your IP address does not match geolocation data'
})
})

test('Location certificate: should issue from geo data', async () => {
await request(server)
.post(issueLocationCertificateUri)
.send({
geoposition: testLocationPayloadUA
})
.set('Authorization', `Bearer ${token}`)
.set('X-Forwarded-For', testIPUA)
.expect(200)
.expect(assertCountryCode('UA'))
})

test('Location certificate: should ignore mobile if not match', async () => {
await request(server)
.post(issueLocationCertificateUri)
.send({
user: testUserPayloadBR,
geoposition: testLocationPayloadUA
})
.set('Authorization', `Bearer ${token}`)
.set('X-Forwarded-For', testIPUA)
.expect(200)
.expect(assertCountryCode('UA'))
})

test('Location certificate: should ignore mobile if not verified', async () => {
await setUserData({
mobile: testUserPayloadBR.mobile,
smsValidated: false
})

await request(server)
.post(issueLocationCertificateUri)
.send({
user: testUserPayloadBR,
geoposition: testLocationPayloadUA
})
.set('Authorization', `Bearer ${token}`)
.set('X-Forwarded-For', testIPUA)
.expect(200)
.expect(assertCountryCode('UA'))
})

test('Location certificate: should issue from mobile ignoring geo data if it matches and verified', async () => {
await setUserData({
mobile: testUserPayloadBR.mobile,
smsValidated: true
})

await request(server)
.post(issueLocationCertificateUri)
.send({
user: testUserPayloadBR,
geoposition: testLocationPayloadUA
})
.set('Authorization', `Bearer ${token}`)
.set('X-Forwarded-For', testIPUA)
.expect(200)
.expect(assertCountryCode('BR'))

// should not throw because of IP => GEO mismatch
await setUserData({
mobile: testUserPayloadUA.mobile
})

await request(server)
.post(issueLocationCertificateUri)
.send({
user: testUserPayloadUA,
geoposition: testLocationPayloadUA
})
.set('Authorization', `Bearer ${token}`)
.set('X-Forwarded-For', testIPBR)
.expect(200)
.expect(assertCountryCode('UA'))
})

test('Verify certificate: should fail on empty data', async () => {
await request(server).post(verifyCertificateUri).send({}).set('Authorization', `Bearer ${token}`).expect(400, {
success: false,
error: 'Failed to verify credential: missing certificate data'
})
})

test('Verify certificate: should verify credential', async () => {
await request(server)
.post(verifyCertificateUri)
.send({
certificate: testCertificate
})
.set('Authorization', `Bearer ${token}`)
.expect(200, {
success: true
})
})
})
17 changes: 10 additions & 7 deletions src/server/goodid/goodid-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@
}

const clientIp = requestIp.getClientIp(req)

log.debug('Getting country data', { clientIp, longitude, latitude })

const [countryCodeFromIP, countryCodeFromLocation] = await Promise.all([
utils.getCountryCodeFromIPAddress(clientIp),
utils.getCountryCodeFromGeoLocation(latitude, longitude)
Expand Down Expand Up @@ -143,20 +146,20 @@
passport.authenticate('jwt', { session: false }),
wrapAsync(async (req, res) => {
const { body, log } = req
const { ceriticate } = body ?? {}

if (!ceriticate) {
throw new Error('Failed to verify credential: missing certificate data')
}
const { certificate } = body ?? {}

try {
const success = await utils.verifyCertificate(ceriticate)
if (!certificate) {

Check failure

Code scanning / CodeQL

User-controlled bypass of security check High

This condition guards a sensitive
action
, but a
user-provided value
controls it.
throw new Error('Failed to verify credential: missing certificate data')
}

const success = await utils.verifyCertificate(certificate)

res.status(200).json({ success })
} catch (exception) {
const { message } = exception

log.error('Failed to verify ceritifate:', message, exception, { ceriticate })
log.error('Failed to verify ceritifate:', message, exception, { certificate })
res.status(400).json({ success: false, error: message })
}
})
Expand Down
14 changes: 8 additions & 6 deletions src/server/goodid/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export class GoodIDUtils {

async getCountryCodeFromIPAddress(ip) {
const countryCode = await this.http
.get('https://get.geojs.io/v1/ip/country/:ip.json', { ip })
.then(response => get(response, 'country_3'))
.get('https://get.geojs.io/v1/ip/country/:ip.json', { params: { ip } })
.then(response => get(response, 'country'))

if (!countryCode) {
throw new Error(`Failed to get country code from IP address '${ip}': response is empty or invalid`)
Expand All @@ -33,9 +33,11 @@ export class GoodIDUtils {
async getCountryCodeFromGeoLocation(latitude, longitude) {
const countryCode = await this.http
.get('https://nominatim.openstreetmap.org/reverse', {
format: 'jsonv2',
lat: latitude,
lon: longitude
params: {
format: 'jsonv2',
lat: latitude,
lon: longitude
}
})
.then(response => get(response, 'address.country_code'))
.then(toUpper)
Expand Down Expand Up @@ -79,7 +81,7 @@ export class GoodIDUtils {

async verifyCertificate(certificate) {
const agent = await this.getVeramoAgent()
const { verified } = await agent.verfyCredential(certificate)
const { verified } = await agent.verifyCredential({ credential: certificate })

return verified
}
Expand Down
18 changes: 13 additions & 5 deletions src/server/goodid/veramo.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ export const getAgent = once(async () => {
{ CredentialPlugin },
{ DIDResolverPlugin },
{ Resolver },
{ getResolver: keyDidResolver }
{ getResolver: keyDidResolver },
{ CredentialIssuerLD, LdDefaultContexts, VeramoEcdsaSecp256k1RecoverySignature2020, VeramoEd25519Signature2018 }
] = await Promise.all([
import('@veramo/core'),
import('@veramo/did-manager'),
Expand All @@ -31,7 +32,8 @@ export const getAgent = once(async () => {
import('@veramo/credential-w3c'),
import('@veramo/did-resolver'),
import('did-resolver'),
import('key-did-resolver')
import('key-did-resolver'),
import('@veramo/credential-ld')
])

const agent = createAgent({
Expand All @@ -56,15 +58,21 @@ export const getAgent = once(async () => {
...keyDidResolver()
})
}),
new CredentialPlugin()
new CredentialPlugin(),
new CredentialIssuerLD({
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this wasn't documented. found it in the veramo packages' sources, inside tests folder

contextMaps: [LdDefaultContexts],
suites: [new VeramoEd25519Signature2018(), new VeramoEcdsaSecp256k1RecoverySignature2020()]
})
]
})

await MultiWallet.ready

const { wallet } = MultiWallet.mainWallet.web3.eth.accounts
const privateKeyHex = wallet
.slice(0, 2)

const privateKeyHex = Array(2)
.fill(null)
.map((_, index) => wallet[index])
.map(({ privateKey }) => privateKey.toLowerCase().replace('0x', ''))
.join('')

Expand Down
Loading