honojs-middleware/packages/firebase-auth/test/index.test.ts

323 lines
8.6 KiB
TypeScript
Raw Normal View History

2023-02-04 19:20:42 +08:00
import type { KeyStorer } from 'firebase-auth-cloudflare-workers'
import { Auth, WorkersKVStoreSingle } from 'firebase-auth-cloudflare-workers'
import { Hono } from 'hono'
import type { VerifyFirebaseAuthEnv } from '../src'
import { verifyFirebaseAuth, getFirebaseToken } from '../src'
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
describe('verifyFirebaseAuth middleware', () => {
const emulatorHost = '127.0.0.1:9099'
const validProjectId = 'example-project12345' // see package.json
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
2022-07-28 13:58:54 +08:00
// @ts-ignore
2023-02-04 19:20:42 +08:00
const { PUBLIC_JWK_CACHE_KV } = getMiniflareBindings()
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
let user: signUpResponse
2022-07-28 13:58:54 +08:00
beforeAll(async () => {
2023-02-04 19:20:42 +08:00
await deleteAccountEmulator(emulatorHost, validProjectId)
2022-07-28 13:58:54 +08:00
user = await signUpEmulator(emulatorHost, {
2023-02-04 19:20:42 +08:00
email: 'codehex@hono.js',
password: 'honojs',
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
await sleep(1000) // wait for iat
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
describe('service worker syntax', () => {
test('valid case, should be 200', async () => {
const app = new Hono()
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
resetAuth()
2022-07-29 22:03:09 +08:00
// This is assumed to be obtained from an environment variable.
2023-02-04 19:20:42 +08:00
const PUBLIC_JWK_CACHE_KEY = 'testing-cache-key'
2022-07-29 22:03:09 +08:00
app.use(
2023-02-04 19:20:42 +08:00
'*',
2022-07-29 22:03:09 +08:00
verifyFirebaseAuth({
2022-07-28 13:58:54 +08:00
projectId: validProjectId,
2023-02-04 19:20:42 +08:00
keyStore: WorkersKVStoreSingle.getOrInitialize(PUBLIC_JWK_CACHE_KEY, PUBLIC_JWK_CACHE_KV),
2022-07-29 22:03:09 +08:00
disableErrorLog: true,
firebaseEmulatorHost: emulatorHost,
})
2023-02-04 19:20:42 +08:00
)
app.get('/hello', (c) => c.json(getFirebaseToken(c)))
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
const req = new Request('http://localhost/hello', {
2022-07-29 22:03:09 +08:00
headers: {
Authorization: `Bearer ${user.idToken}`,
2022-07-28 13:58:54 +08:00
},
2023-02-04 19:20:42 +08:00
})
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
const res = await app.request(req)
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
expect(res).not.toBeNull()
expect(res.status).toBe(200)
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
const json = await res.json<{ aud: string; email: string }>()
expect(json.aud).toBe(validProjectId)
expect(json.email).toBe('codehex@hono.js')
})
})
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
describe('module worker syntax', () => {
2022-07-29 22:03:09 +08:00
test.each([
[
2023-02-04 19:20:42 +08:00
'valid case, should be 200',
2022-07-29 22:03:09 +08:00
{
2023-02-04 19:20:42 +08:00
headerKey: 'Authorization',
2022-07-29 22:03:09 +08:00
env: {
2023-02-04 19:20:42 +08:00
FIREBASE_AUTH_EMULATOR_HOST: 'localhost:9099',
PUBLIC_JWK_CACHE_KEY: 'testing-cache-key',
2022-07-29 22:03:09 +08:00
PUBLIC_JWK_CACHE_KV,
},
config: {
projectId: validProjectId,
},
wantStatus: 200,
2022-07-28 13:58:54 +08:00
},
2022-07-29 22:03:09 +08:00
],
[
2023-02-04 19:20:42 +08:00
'valid specified headerKey, should be 200',
2022-07-29 22:03:09 +08:00
{
2023-02-04 19:20:42 +08:00
headerKey: 'X-Authorization',
2022-07-29 22:03:09 +08:00
env: {
2023-02-04 19:20:42 +08:00
FIREBASE_AUTH_EMULATOR_HOST: 'localhost:9099',
PUBLIC_JWK_CACHE_KEY: 'testing-cache-key',
2022-07-29 22:03:09 +08:00
PUBLIC_JWK_CACHE_KV,
},
config: {
projectId: validProjectId,
2023-02-04 19:20:42 +08:00
authorizationHeaderKey: 'X-Authorization',
2022-07-29 22:03:09 +08:00
},
wantStatus: 200,
2022-07-28 13:58:54 +08:00
},
2022-07-29 22:03:09 +08:00
],
[
2023-02-04 19:20:42 +08:00
'invalid authorization header, should be 400',
2022-07-29 22:03:09 +08:00
{
2023-02-04 19:20:42 +08:00
headerKey: 'X-Authorization',
2022-07-29 22:03:09 +08:00
env: {
2023-02-04 19:20:42 +08:00
FIREBASE_AUTH_EMULATOR_HOST: 'localhost:9099',
PUBLIC_JWK_CACHE_KEY: 'testing-cache-key',
2022-07-29 22:03:09 +08:00
PUBLIC_JWK_CACHE_KV,
},
config: {
projectId: validProjectId, // see package.json
// No specified header key.
},
wantStatus: 400,
2022-07-28 13:58:54 +08:00
},
2022-07-29 22:03:09 +08:00
],
[
2023-02-04 19:20:42 +08:00
'invalid project ID, should be 401',
2022-07-29 22:03:09 +08:00
{
2023-02-04 19:20:42 +08:00
headerKey: 'Authorization',
2022-07-29 22:03:09 +08:00
env: {
2023-02-04 19:20:42 +08:00
FIREBASE_AUTH_EMULATOR_HOST: 'localhost:9099',
PUBLIC_JWK_CACHE_KEY: 'testing-cache-key',
2022-07-29 22:03:09 +08:00
PUBLIC_JWK_CACHE_KV,
},
config: {
2023-02-04 19:20:42 +08:00
projectId: 'invalid-projectId',
2022-07-29 22:03:09 +08:00
},
wantStatus: 401,
2022-07-28 13:58:54 +08:00
},
2022-07-29 22:03:09 +08:00
],
2023-02-04 19:20:42 +08:00
])('%s', async (_, { headerKey, env, config, wantStatus }) => {
const app = new Hono<{ Bindings: VerifyFirebaseAuthEnv }>()
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
resetAuth()
2022-07-29 22:03:09 +08:00
app.use(
2023-02-04 19:20:42 +08:00
'*',
2022-07-29 22:03:09 +08:00
verifyFirebaseAuth({
...config,
disableErrorLog: true,
})
2023-02-04 19:20:42 +08:00
)
app.get('/hello', (c) => c.text('OK'))
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
const req = new Request('http://localhost/hello', {
2022-07-29 22:03:09 +08:00
headers: {
[headerKey]: `Bearer ${user.idToken}`,
2022-07-28 13:58:54 +08:00
},
2023-02-04 19:20:42 +08:00
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
const res = await app.fetch(req, env)
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
expect(res).not.toBeNull()
expect(res.status).toBe(wantStatus)
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
test('specified keyStore is used', async () => {
const testingJWT = generateDummyJWT()
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
const nopKeyStore = new NopKeyStore()
const getSpy = jest.spyOn(nopKeyStore, 'get')
const putSpy = jest.spyOn(nopKeyStore, 'put')
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
const app = new Hono<{ Bindings: VerifyFirebaseAuthEnv }>()
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
resetAuth()
2022-07-28 13:58:54 +08:00
2022-07-29 22:03:09 +08:00
app.use(
2023-02-04 19:20:42 +08:00
'*',
2022-07-29 22:03:09 +08:00
verifyFirebaseAuth({
projectId: validProjectId,
keyStore: nopKeyStore,
disableErrorLog: true,
})
2023-02-04 19:20:42 +08:00
)
app.get('/hello', (c) => c.text('OK'))
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
const req = new Request('http://localhost/hello', {
2022-07-29 22:03:09 +08:00
headers: {
Authorization: `Bearer ${testingJWT}`,
},
2023-02-04 19:20:42 +08:00
})
2022-07-28 13:58:54 +08:00
2022-07-29 22:03:09 +08:00
// not use firebase emulator to check using key store
const res = await app.fetch(req, {
FIREBASE_AUTH_EMULATOR_HOST: undefined,
2023-02-04 19:20:42 +08:00
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(getSpy).toHaveBeenCalled()
expect(putSpy).toHaveBeenCalled()
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
test('usable id-token in main handler', async () => {
const testingJWT = generateDummyJWT()
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
const nopKeyStore = new NopKeyStore()
const app = new Hono<{ Bindings: VerifyFirebaseAuthEnv }>()
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
resetAuth()
2022-07-28 13:58:54 +08:00
2022-07-29 22:03:09 +08:00
app.use(
2023-02-04 19:20:42 +08:00
'*',
2022-07-29 22:03:09 +08:00
verifyFirebaseAuth({
projectId: validProjectId,
keyStore: nopKeyStore,
disableErrorLog: true,
})
2023-02-04 19:20:42 +08:00
)
app.get('/hello', (c) => c.json(getFirebaseToken(c)))
2022-07-29 22:03:09 +08:00
2023-02-04 19:20:42 +08:00
const req = new Request('http://localhost/hello', {
2022-07-29 22:03:09 +08:00
headers: {
Authorization: `Bearer ${testingJWT}`,
},
2023-02-04 19:20:42 +08:00
})
2022-07-28 13:58:54 +08:00
2022-07-29 22:03:09 +08:00
const res = await app.fetch(req, {
FIREBASE_AUTH_EMULATOR_HOST: emulatorHost,
2023-02-04 19:20:42 +08:00
})
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
expect(res).not.toBeNull()
expect(res.status).toBe(200)
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
const json = await res.json<{ aud: string; email: string }>()
expect(json.aud).toBe(validProjectId)
expect(json.email).toBe('codehex@hono.js')
})
})
})
2022-07-28 13:58:54 +08:00
class NopKeyStore implements KeyStorer {
2023-02-04 19:20:42 +08:00
// eslint-disable-next-line @typescript-eslint/no-empty-function
2022-07-28 13:58:54 +08:00
constructor() {}
get(): Promise<null> {
2023-02-04 19:20:42 +08:00
return new Promise((resolve) => resolve(null))
2022-07-28 13:58:54 +08:00
}
put(): Promise<void> {
2023-02-04 19:20:42 +08:00
return new Promise((resolve) => resolve())
2022-07-28 13:58:54 +08:00
}
}
2023-02-04 19:20:42 +08:00
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
2022-07-28 13:58:54 +08:00
// magic to reset state of static object for "firebase-auth-cloudflare-workers"
2023-02-04 19:20:42 +08:00
const resetAuth = () => delete Auth['instance']
2022-07-28 13:58:54 +08:00
const generateDummyJWT = () => {
const header = JSON.stringify({
2023-02-04 19:20:42 +08:00
alg: 'RS256',
kid: 'kid',
typ: 'JWT',
})
const now = Math.floor(Date.now() / 1000)
2022-07-28 13:58:54 +08:00
const payload = JSON.stringify({
2023-02-04 19:20:42 +08:00
iss: 'https://securetoken.google.com/example-project12345',
aud: 'example-project12345',
2022-07-28 13:58:54 +08:00
auth_time: now - 1000,
2023-02-04 19:20:42 +08:00
user_id: 't1aLdTkAs0S0J0P6TNbjwbmry5B3',
sub: 't1aLdTkAs0S0J0P6TNbjwbmry5B3',
2022-07-28 13:58:54 +08:00
iat: now - 1000,
exp: now + 3000, // + 3s
2023-02-04 19:20:42 +08:00
email: 'codehex@hono.js',
2022-07-28 13:58:54 +08:00
email_verified: false,
firebase: {
identities: {
2023-02-04 19:20:42 +08:00
email: ['codehex@hono.js'],
2022-07-28 13:58:54 +08:00
},
2023-02-04 19:20:42 +08:00
sign_in_provider: 'password',
2022-07-28 13:58:54 +08:00
},
2023-02-04 19:20:42 +08:00
})
return `${btoa(header)}.${btoa(payload)}.`
}
2022-07-28 13:58:54 +08:00
interface EmailPassword {
2023-02-04 19:20:42 +08:00
email: string
password: string
2022-07-28 13:58:54 +08:00
}
export interface signUpResponse {
2023-02-04 19:20:42 +08:00
kind: string
localId: string
email: string
idToken: string
refreshToken: string
expiresIn: string
2022-07-28 13:58:54 +08:00
}
const signUpEmulator = async (
emulatorHost: string,
body: EmailPassword
): Promise<signUpResponse> => {
// http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signUp?key=dummy
2023-02-04 19:20:42 +08:00
const url = `http://${emulatorHost}/identitytoolkit.googleapis.com/v1/accounts:signUp?key=dummy`
2022-07-28 13:58:54 +08:00
const resp = await fetch(url, {
2023-02-04 19:20:42 +08:00
method: 'POST',
2022-07-28 13:58:54 +08:00
headers: {
2023-02-04 19:20:42 +08:00
'Content-Type': 'application/json',
2022-07-28 13:58:54 +08:00
},
body: JSON.stringify({
...body,
returnSecureToken: true,
}),
2023-02-04 19:20:42 +08:00
})
2022-07-28 13:58:54 +08:00
if (resp.status !== 200) {
2023-02-04 19:20:42 +08:00
console.log({ status: resp.status })
throw new Error('error')
2022-07-28 13:58:54 +08:00
}
2023-02-04 19:20:42 +08:00
return await resp.json()
}
2022-07-28 13:58:54 +08:00
2023-02-04 19:20:42 +08:00
const deleteAccountEmulator = async (emulatorHost: string, projectId: string): Promise<void> => {
2022-07-28 13:58:54 +08:00
// https://firebase.google.com/docs/reference/rest/auth#section-auth-emulator-clearaccounts
2023-02-04 19:20:42 +08:00
const url = `http://${emulatorHost}/emulator/v1/projects/${projectId}/accounts`
2022-07-28 13:58:54 +08:00
const resp = await fetch(url, {
2023-02-04 19:20:42 +08:00
method: 'DELETE',
})
2022-07-28 13:58:54 +08:00
if (resp.status !== 200) {
2023-02-04 19:20:42 +08:00
console.log({ status: resp.status })
throw new Error('error when clear accounts')
2022-07-28 13:58:54 +08:00
}
2023-02-04 19:20:42 +08:00
return
}