import { Eltro as t, assert} from 'eltro' import { createContext } from '../helper.server.mjs' import { verifyToken } from '../../api/media/security.mjs' import { HttpError } from '../../api/error.mjs' import encode from '../../api/jwt/encode.mjs' import config from '../../api/config.mjs' t.describe('#verifyToken()', function() { t.before(function() { config.set('sites', { justatest: { 'default@HS512': 'mysharedkey' }, }) }) t.test('should fail if query token is missing', function() { let ctx = createContext({ }) ctx.query.delete('token') assert.throws(function() { verifyToken(ctx) }, function(err) { assert.ok(err instanceof HttpError) assert.ok(err instanceof Error) assert.strictEqual(err.status, 422) assert.match(err.message, /[Qq]uery/) assert.match(err.message, /[Tt]oken/) return true }) }) function assertInvalidToken(err) { assert.ok(err instanceof HttpError) assert.ok(err instanceof Error) assert.strictEqual(err.status, 422) assert.match(err.message, /[Ii]nvalid/) assert.match(err.message, /[Tt]oken/) return true } t.test('should fail if token is invalid', function() { let ctx = createContext({ }) ctx.query.set('token', 'asdfasdgassdga') assert.throws(function() { verifyToken(ctx) }, assertInvalidToken) assert.ok(ctx.log.error.lastCall) assert.match(ctx.log.error.lastCall[0].message, /3 dots/) ctx.query.set('token', 'asdfasdgassdga.asdfasdg.sadfsadfas') assert.throws(function() { verifyToken(ctx) }, assertInvalidToken) assert.match(ctx.log.error.lastCall[0].message, /[Ii]nvalid/) ctx.query.set('token', encode( { typ: 'JWT', alg: 'HS256' }, { iss: 'justatest' }, 'mysharedkey' )) assert.throws(function() { verifyToken(ctx) }, assertInvalidToken) assert.match(ctx.log.error.lastCall[0].message, /pubkey/) ctx.query.set('token', encode( { typ: 'JWT', alg: 'HS512' }, { iss: 'notexist' }, 'mysharedkey' )) assert.throws(function() { verifyToken(ctx) }, assertInvalidToken) assert.match(ctx.log.error.lastCall[0].message, /notexist/) ctx.query.set('token', encode( { typ: 'JWT', alg: 'HS512' }, { iss: 'justatest' }, 'mysharedkey2' )) assert.throws(function() { verifyToken(ctx) }, assertInvalidToken) assert.match(ctx.log.error.lastCall[0].message, /HS512/) assert.match(ctx.log.error.lastCall[0].message, /[vV]erification/) }) t.test('should otherwise return the issuer', function() { let ctx = createContext({ }) ctx.query.set('token', encode( { typ: 'JWT', alg: 'HS512' }, { iss: 'justatest' }, 'mysharedkey' )) let site = verifyToken(ctx) assert.strictEqual(site, 'justatest') }) })