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

fix: update inbound message validation #678

Merged
merged 4 commits into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
17 changes: 12 additions & 5 deletions packages/core/src/agent/MessageReceiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { AriesFrameworkError } from '../error'
import { ConnectionRepository } from '../modules/connections'
import { DidRepository } from '../modules/dids/repository/DidRepository'
import { ProblemReportError, ProblemReportMessage, ProblemReportReason } from '../modules/problem-reports'
import { isValidJweStructure } from '../utils/JWE'
import { JsonTransformer } from '../utils/JsonTransformer'
import { MessageValidator } from '../utils/MessageValidator'
import { replaceLegacyDidSovPrefixOnMessage } from '../utils/messageType'
Expand Down Expand Up @@ -66,11 +67,12 @@ export class MessageReceiver {
*/
public async receiveMessage(inboundMessage: unknown, session?: TransportSession) {
this.logger.debug(`Agent ${this.config.label} received message`)

if (this.isPlaintextMessage(inboundMessage)) {
if (this.isEncryptedMessage(inboundMessage)) {
await this.receiveEncryptedMessage(inboundMessage as EncryptedMessage, session)
Comment on lines +70 to +71
Copy link
Contributor

Choose a reason for hiding this comment

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

Similar logic is already present in the http / ws outbound transport:

          if (!isValidJweStucture(encryptedMessage)) {
            this.logger.error(
              `Received a response from the other agent but the structure of the incoming message is not a DIDComm message: ${responseMessage}`
            )
            return
          }

Could you remove the checks there and reuse the isValidJweStucture method that is already available? (and fix the typo in the method name 😄 )

} else if (this.isPlaintextMessage(inboundMessage)) {
await this.receivePlaintextMessage(inboundMessage)
} else {
await this.receiveEncryptedMessage(inboundMessage as EncryptedMessage, session)
throw new AriesFrameworkError('Unable to parse incoming message: unrecognized format')
}
}

Expand Down Expand Up @@ -143,12 +145,17 @@ export class MessageReceiver {

private isPlaintextMessage(message: unknown): message is PlaintextMessage {
if (typeof message !== 'object' || message == null) {
throw new AriesFrameworkError('Invalid message received. Message should be object')
return false
}
// If the message does have an @type field we assume the message is in plaintext and it is not encrypted.
// If the message has a @type field we assume the message is in plaintext and it is not encrypted.
return '@type' in message
}

private isEncryptedMessage(message: unknown): message is EncryptedMessage {
// If the message does has valid JWE structure, we can assume the message is encrypted.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// If the message does has valid JWE structure, we can assume the message is encrypted.
// If the message has a valid JWE structure, we can assume the message is encrypted.

return isValidJweStructure(message)
}

private async transformAndValidate(
plaintextMessage: PlaintextMessage,
connection?: ConnectionRecord | null
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/transport/HttpOutboundTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { AbortController } from 'abort-controller'

import { AgentConfig } from '../agent/AgentConfig'
import { AriesFrameworkError } from '../error/AriesFrameworkError'
import { isValidJweStucture, JsonEncoder } from '../utils'
import { isValidJweStructure, JsonEncoder } from '../utils'

export class HttpOutboundTransport implements OutboundTransport {
private agent!: Agent
Expand Down Expand Up @@ -78,7 +78,7 @@ export class HttpOutboundTransport implements OutboundTransport {

try {
const encryptedMessage = JsonEncoder.fromString(responseMessage)
if (!isValidJweStucture(encryptedMessage)) {
if (!isValidJweStructure(encryptedMessage)) {
this.logger.error(
`Received a response from the other agent but the structure of the incoming message is not a DIDComm message: ${responseMessage}`
)
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/transport/WsOutboundTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type WebSocket from 'ws'
import { AgentConfig } from '../agent/AgentConfig'
import { EventEmitter } from '../agent/EventEmitter'
import { AriesFrameworkError } from '../error/AriesFrameworkError'
import { isValidJweStucture, JsonEncoder } from '../utils'
import { isValidJweStructure, JsonEncoder } from '../utils'
import { Buffer } from '../utils/buffer'

import { TransportEventTypes } from './TransportEventTypes'
Expand Down Expand Up @@ -103,7 +103,7 @@ export class WsOutboundTransport implements OutboundTransport {
private handleMessageEvent = (event: any) => {
this.logger.trace('WebSocket message event received.', { url: event.target.url, data: event.data })
const payload = JsonEncoder.fromBuffer(event.data)
if (!isValidJweStucture(payload)) {
if (!isValidJweStructure(payload)) {
throw new Error(
`Received a response from the other agent but the structure of the incoming message is not a DIDComm message: ${payload}`
)
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/utils/JWE.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { EncryptedMessage } from '../types'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isValidJweStucture(message: any): message is EncryptedMessage {
export function isValidJweStructure(message: any): message is EncryptedMessage {
return message && typeof message === 'object' && message.protected && message.iv && message.ciphertext && message.tag
}
6 changes: 3 additions & 3 deletions packages/core/src/utils/__tests__/JWE.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { isValidJweStucture } from '../JWE'
import { isValidJweStructure } from '../JWE'

describe('ValidJWEStructure', () => {
test('throws error when the response message has an invalid JWE structure', async () => {
const responseMessage = 'invalid JWE structure'
await expect(isValidJweStucture(responseMessage)).toBeFalsy()
await expect(isValidJweStructure(responseMessage)).toBeFalsy()
})

test('valid JWE structure', async () => {
Expand All @@ -14,6 +14,6 @@ describe('ValidJWEStructure', () => {
ciphertext: 'mwRMpVg9wkF4rIZcBeWLcc0fWhs=',
tag: '0yW0Lx8-vWevj3if91R06g==',
}
await expect(isValidJweStucture(responseMessage)).toBeTruthy()
await expect(isValidJweStructure(responseMessage)).toBeTruthy()
})
})