Skip to content

Commit

Permalink
cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
r-marques committed Jan 24, 2023
1 parent d1cbe82 commit 9410d70
Show file tree
Hide file tree
Showing 9 changed files with 14 additions and 237 deletions.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@nestjs/typeorm": "^8.0.3",
"@nevermined-io/argo-workflows-api": "^0.1.3",
"@nevermined-io/nevermined-sdk-dtp": "0.3.0-rc11",
"@nevermined-io/nevermined-sdk-js": "1.0.0-rc14",
"@nevermined-io/passport-nevermined": "^0.1.0",
"@sideway/address": "^4.1.3",
"@sideway/formula": "^3.0.0",
Expand All @@ -50,7 +51,7 @@
"formdata-polyfill": "^4.0.10",
"ipfs-http-client-lite": "^0.3.0",
"joi": "^17.6.0",
"jose": "^4.6.0",
"jose": "^4.11.2",
"js-yaml": "4.1.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
Expand Down Expand Up @@ -102,6 +103,9 @@
"tslint-to-eslint-config": "^2.12.3",
"uuid": "^8.3.2"
},
"resolutions": {
"@nevermined-io/nevermined-sdk-js": "1.0.0-rc14"
},
"lint-staged": {
"src/**/*.{js,json}": [
"prettier --write",
Expand Down
3 changes: 2 additions & 1 deletion src/auth/auth.service.mock.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { decodeJwt, JWTPayload } from 'jose'
import { CLIENT_ASSERTION_TYPE, EthSignJWT } from '../common/guards/shared/jwt.utils'
import { CLIENT_ASSERTION_TYPE } from '../common/guards/shared/jwt.utils'
import { ethers } from 'ethers'
import { EthSignJWT } from '@nevermined-io/nevermined-sdk-js'

/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument */

Expand Down
123 changes: 0 additions & 123 deletions src/common/guards/shared/jwt.utils.ts
Original file line number Diff line number Diff line change
@@ -1,124 +1 @@
import {
decodeJwt,
decodeProtectedHeader,
JWSHeaderParameters,
JWTPayload,
ProtectedHeaderParameters,
SignJWT,
} from 'jose'
import { ethers } from 'ethers'

export const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'

// TODO: Used only for testing and copied from the sdk
// expose from the SDK side
export class EthSignJWT extends SignJWT {
protectedHeader: JWSHeaderParameters

setProtectedHeader(protectedHeader: JWSHeaderParameters) {
this.protectedHeader = protectedHeader
return this
}

public async ethSign(wallet: ethers.Wallet): Promise<string> {
const encoder = new TextEncoder()
const decoder = new TextDecoder()

const encodedPayload = encoder.encode(this.base64url(JSON.stringify(this._payload)))
const encodedHeader = encoder.encode(this.base64url(JSON.stringify(this.protectedHeader)))
const data = this.concat(encodedHeader, encoder.encode('.'), encodedPayload)

const sign = await wallet.signMessage(decoder.decode(data))

const signed = this.base64url(ethers.utils.arrayify(sign))
const grantToken = `${decoder.decode(encodedHeader)}.${decoder.decode(
encodedPayload,
)}.${signed}`

return grantToken
}

private base64url(input: Uint8Array | string): string {
return Buffer.from(input)
.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
}

private concat(...buffers: Uint8Array[]): Uint8Array {
const size = buffers.reduce((acc, { length }) => acc + length, 0)
const buf = new Uint8Array(size)
let i = 0
buffers.forEach((buffer) => {
buf.set(buffer, i)
i += buffer.length
})
return buf
}
}

export const recoverPublicKey = (protectedHeader: string, payload: string, signature: string) => {
const signatureInput = `${protectedHeader}.${payload}`
const signatureDecoded = `0x${Buffer.from(signature, 'base64').toString('hex')}`

const address = ethers.utils.verifyMessage(signatureInput, signatureDecoded)
return ethers.utils.getAddress(address)
}

// TODO: A lot of this functionality should maybe be turned
// into a passport strategy
// Verify a jwt with an ethereum signature
export const jwtEthVerify = (jwt: string) => {
const { 0: protectedHeader, 1: payload, 2: signature, length } = jwt.split('.')

if (length !== 3) {
throw new Error('Invalid Compact JWS')
}

// decode and validate protected header
let parsedProtectedHeader: ProtectedHeaderParameters
try {
parsedProtectedHeader = decodeProtectedHeader(jwt)
} catch (error) {
throw new Error(`ProtectedHeader: Failed to decode header (${(error as Error).message})`)
}
if (parsedProtectedHeader.alg !== 'ES256K') {
throw new Error('ProtectedHeader: Invalid algorithm')
}

// recover public key from signature
// This is the de-facto signature validation
let publicKey: string
try {
publicKey = recoverPublicKey(protectedHeader, payload, signature)
} catch (error) {
throw new Error(`Signature: Failed to validate signature (${(error as Error).message})`)
}

// verify the payload
let parsedPayload: JWTPayload
try {
parsedPayload = decodeJwt(jwt)
} catch (error) {
throw new Error(`Payload: Failed to decode payload (${(error as Error).message})`)
}
if (!parsedPayload.iss) {
throw new Error('Payload: "iss" field is required')
}

const isValidAddress = ethers.utils.isAddress(parsedPayload.iss)
if (!isValidAddress) {
throw new Error('Payload: "iss" field must be a valid ethereum address')
}
const isChecksumAddress = ethers.utils.getAddress(parsedPayload.iss) === parsedPayload.iss
if (!isChecksumAddress) {
throw new Error('Payload: "iss" field must be a checksum address')
}

if (parsedPayload.iss !== publicKey) {
throw new Error(`Payload: "iss" is not the signer of the payload ${publicKey}`)
}

return parsedPayload
}
76 changes: 0 additions & 76 deletions src/common/guards/shared/jwtValidation.spec.ts

This file was deleted.

21 changes: 0 additions & 21 deletions src/common/guards/shared/jwtValidation.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/common/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { JWTPayload } from 'jose'
import { JWTPayload } from '@nevermined-io/passport-nevermined'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { ConfigService } from '../../shared/config/config.service'

Expand Down
7 changes: 0 additions & 7 deletions src/compute/compute.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,6 @@ describe('ComputeService Testing', () => {
{
index: 0,
stageType: 'Filtering',
requirements: {
container: {
image: 'openjdk',
tag: '14-jdl',
checksum: 'sha256:53ad3a03b2fb240b6c494339821e6638cd44c989bcf26ec4d51a6a52f7518c1d',
},
},
input: [
{
index: 0,
Expand Down
3 changes: 1 addition & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@
"esModuleInterop": true,
"resolveJsonModule": true,
"composite": true,
"allowJs": true
},
"include": ["next-env.d.ts", "**/*.ts", "./src/compute/argo-workflows-templates/*.yaml"],
"include": ["next-env.d.ts", "./src/**/*.ts", "./src/compute/argo-workflows-templates/*.yaml"],
"exclude": ["node_modules"]
}
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1207,10 +1207,10 @@
snarkjs "^0.4.26"
web3-utils "^1.7.4"

"@nevermined-io/nevermined-sdk-js@1.0.0-rc12":
version "1.0.0-rc12"
resolved "https://registry.yarnpkg.com/@nevermined-io/nevermined-sdk-js/-/nevermined-sdk-js-1.0.0-rc12.tgz#eaaa8a1a748ad81a97bad314aaf84cc487a3cb9a"
integrity sha512-eDZqd3rjVFVAQcJ/iRgixeG9lQFElIwEwR6DHUx6qL/tmSUECOLYUq19CPDy8JDov7UJGjPjp9b+eL1ZsMEyoQ==
"@nevermined-io/nevermined-sdk-js@1.0.0-rc12", "@nevermined-io/nevermined-sdk-js@1.0.0-rc14":
version "1.0.0-rc14"
resolved "https://registry.yarnpkg.com/@nevermined-io/nevermined-sdk-js/-/nevermined-sdk-js-1.0.0-rc14.tgz#c18208ffc3b3eecd7d4b79a23f347c29a04dc60d"
integrity sha512-ieH58UZ7GOilBWaQhPq4V8uLMaD8yGdIhQHdvVdEBSpfTL1DE2Xrzzk/X9bLxTM/rAhS3up5gcVgHeH/DQ5hLQ==
dependencies:
"@nevermined-io/subgraphs" "0.5.0-rc1"
assert "^2.0.0"
Expand Down Expand Up @@ -5359,7 +5359,7 @@ jose@^4.11.2:
resolved "https://registry.yarnpkg.com/jose/-/jose-4.11.2.tgz#d9699307c02e18ff56825843ba90e2fae9f09e23"
integrity sha512-njj0VL2TsIxCtgzhO+9RRobBvws4oYyCM8TpvoUQwl/MbIM3NFJRR9+e6x0sS5xXaP1t6OCBkaBME98OV9zU5A==

jose@^4.5.1, jose@^4.6.0:
jose@^4.5.1:
version "4.11.1"
resolved "https://registry.yarnpkg.com/jose/-/jose-4.11.1.tgz#8f7443549befe5bddcf4bae664a9cbc1a62da4fa"
integrity sha512-YRv4Tk/Wlug8qicwqFNFVEZSdbROCHRAC6qu/i0dyNKr5JQdoa2pIGoS04lLO/jXQX7Z9omoNewYIVIxqZBd9Q==
Expand Down

0 comments on commit 9410d70

Please sign in to comment.