Skip to content
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
14 changes: 12 additions & 2 deletions src/protocol/sasl/scram-sha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const GS2_HEADER = 'n,,'
const GS2_HEADER_BASE64 = Buffer.from(GS2_HEADER).toString('base64')
const HMAC_CLIENT_KEY = 'Client Key'
const HMAC_SERVER_KEY = 'Server Key'
const PARAMETERS_PARSER = /([^=]+)=(.+)/
const PARAMETERS_PARSER = /([^=]+)=([^,]*)/

export interface ScramAlgorithmDefinition {
keyLength: number
Expand Down Expand Up @@ -52,9 +52,19 @@ export function sanitizeString (str: string): string {
export function parseParameters (data: Buffer): Record<string, string> {
const original = data.toString('utf-8')

const parsed = original.split(',').map(parameter => {
const match = parameter.match(PARAMETERS_PARSER)

if (!match) {
throw new AuthenticationError(`Malformed SCRAM parameter: ${parameter}`)
}

return match.slice(1, 3)
})

return {
__original: original,
...Object.fromEntries(original.split(',').map(param => param.match(PARAMETERS_PARSER)!.slice(1, 3)))
...Object.fromEntries(parsed)
}
}

Expand Down
24 changes: 24 additions & 0 deletions test/protocol/sasl/scram-sha.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ test('parseParameters should parse comma-separated key=value pairs', () => {
strictEqual(result.__original, 'a=1,b=2,c=value')
})

test('parseParameters should parse empty SCRAM values', () => {
const input = Buffer.from('r=clientNonce123serverNonce456,s=,i=4096')
const result = parseParameters(input)

strictEqual(result.r, 'clientNonce123serverNonce456')
strictEqual(result.s, '')
strictEqual(result.i, '4096')
strictEqual(result.__original, 'r=clientNonce123serverNonce456,s=,i=4096')
})

test('parseParameters should throw for malformed parameter entries', async () => {
const input = Buffer.from('r=nonce,s=,i=4096,bad-param')

await rejects(
async () => {
parseParameters(input)
},
(err: Error) => {
strictEqual(err instanceof AuthenticationError, true)
return true
}
)
})

// Test h (hash) function
test('h should hash data using the algorithm from the definition', () => {
const sha256Def = ScramAlgorithms['SHA-256']
Expand Down
Loading