Skip to content

Commit

Permalink
feat(firebase-auth): added a new middleware to verify session with fi…
Browse files Browse the repository at this point in the history
…rebase-auth (#402)

* fix(firebase-auth): updated firebase-auth-cloudflare-workers

* add(firebase-auth): added a new `verifySessionCookieFirebaseAuth` middleware to verify w/ session cookie
  • Loading branch information
Code-Hex authored Feb 24, 2024
1 parent 9b455b5 commit c9f110d
Show file tree
Hide file tree
Showing 8 changed files with 1,044 additions and 552 deletions.
5 changes: 5 additions & 0 deletions .changeset/add-verify-session-cookie-firebase-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/firebase-auth': minor
---

added a new `verifySessionCookieFirebaseAuth` middleware to verify w/ session cookie.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ coverage
yarn-error.log

# for debug or playing
sandbox
sandbox
*.log
164 changes: 163 additions & 1 deletion packages/firebase-auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This is a Firebase Auth middleware library for [Hono](https://github.com/honojs/

Currently only Cloudflare Workers are supported officially. However, it may work in other environments as well, so please let us know in an issue if it works.

## Synopsis
## Synopsis (verify w/ authorization header)

### Module Worker Syntax (recommend)

Expand Down Expand Up @@ -100,6 +100,168 @@ You can specify a host for the Firebase Auth emulator. This config is mainly use

If not specified, check the [`FIREBASE_AUTH_EMULATOR_HOST` environment variable obtained from the request](https://github.com/Code-Hex/firebase-auth-cloudflare-workers#emulatorenv).

## Synopsis (verify w/ session cookie)

### Module Worker Syntax (recommend)

```ts
import { Hono } from 'hono'
import { setCookie } from 'hono/cookie';
import { csrf } from 'hono/csrf';
import { html } from 'hono/html';
import {
VerifySessionCookieFirebaseAuthConfig,
VerifyFirebaseAuthEnv,
verifySessionCookieFirebaseAuth,
getFirebaseToken,
} from '@hono/firebase-auth'
import { AdminAuthApiClient, ServiceAccountCredential } from 'firebase-auth-cloudflare-workers';

const config: VerifySessionCookieFirebaseAuthConfig = {
// specify your firebase project ID.
projectId: 'your-project-id',
redirects: {
signIn: "/login"
}
}

// You can specify here the extended VerifyFirebaseAuthEnv type.
//
// If you do not specify `keyStore` in the configuration, you need to set
// the variables `PUBLIC_JWK_CACHE_KEY` and `PUBLIC_JWK_CACHE_KV` in your
// wrangler.toml. This is because `WorkersKVStoreSingle` is used by default.
//
// For more details, please refer to: https://github.com/Code-Hex/firebase-auth-cloudflare-workers
type MyEnv = VerifyFirebaseAuthEnv & {
// See: https://github.com/Code-Hex/firebase-auth-cloudflare-workers?tab=readme-ov-file#adminauthapiclientgetorinitializeprojectid-string-credential-credential-retryconfig-retryconfig-adminauthapiclient
SERVICE_ACCOUNT_JSON: string
}

const app = new Hono<{ Bindings: MyEnv }>()

// set middleware
app.get('/login', csrf(), async c => {
// You can copy code from here
// https://github.com/Code-Hex/firebase-auth-cloudflare-workers/blob/0ce610fff257b0b60e2f8e38d89c8e012497d537/example/index.ts#L63C25-L63C37
const content = await html`...`
return c.html(content)
})

app.post('/login_session', csrf(), (c) => {
const json = await c.req.json();
const idToken = json.idToken;
if (!idToken || typeof idToken !== 'string') {
return c.json({ message: 'invalid idToken' }, 400);
}
// Set session expiration to 5 days.
const expiresIn = 60 * 60 * 24 * 5 * 1000;

// Create the session cookie. This will also verify the ID token in the process.
// The session cookie will have the same claims as the ID token.
// To only allow session cookie setting on recent sign-in, auth_time in ID token
// can be checked to ensure user was recently signed in before creating a session cookie.
const auth = AdminAuthApiClient.getOrInitialize(
c.env.PROJECT_ID,
new ServiceAccountCredential(c.env.SERVICE_ACCOUNT_JSON)
);
const sessionCookie = await auth.createSessionCookie(
idToken,
expiresIn,
);
setCookie(c, 'session', sessionCookie, {
maxAge: expiresIn,
httpOnly: true,
secure: true
});
return c.json({ message: 'success' });
})

app.use('/admin/*', csrf(), verifySessionCookieFirebaseAuth(config));
app.get('/admin/hello', (c) => {
const idToken = getFirebaseToken(c) // get id-token object.
return c.json(idToken)
})


export default app
```

## Config (`VerifySessionCookieFirebaseAuthConfig`)

### `projectId: string` (**required**)

This field indicates your firebase project ID.

### `redirects: object` (**required**)

This object has a property named redirects, which in turn has a property named `signIn` of type string.

The `signIn` property is expected to hold a string representing the path to redirect to after a user has failed to sign-in.

### `cookieName?: string` (optional)

Based on this configuration, the session token has created by firebase auth is looked for in the cookie. The default is "session".

### `keyStore?: KeyStorer` (optional)

This is used to cache the public key used to validate the Firebase ID token (JWT). This KeyStorer type has been defined in [firebase-auth-cloudflare-workers](https://github.com/Code-Hex/firebase-auth-cloudflare-workers/tree/main#keystorer) library.

If you don't specify the field, this library uses [WorkersKVStoreSingle](https://github.com/Code-Hex/firebase-auth-cloudflare-workers/tree/main#workerskvstoresinglegetorinitializecachekey-string-cfkvnamespace-kvnamespace-workerskvstoresingle) instead. You must fill in the fields defined in `VerifyFirebaseAuthEnv`.

### `keyStoreInitializer?: (c: Context) => KeyStorer` (optional)

Use this when initializing KeyStorer and environment variables, etc. are required.

If you don't specify the field, this library uses [WorkersKVStoreSingle](https://github.com/Code-Hex/firebase-auth-cloudflare-workers/tree/main#workerskvstoresinglegetorinitializecachekey-string-cfkvnamespace-kvnamespace-workerskvstoresingle) instead. You must fill in the fields defined in `VerifyFirebaseAuthEnv`.

### `firebaseEmulatorHost?: string` (optional)

You can specify a host for the Firebase Auth emulator. This config is mainly used when **Service Worker Syntax** is used.

If not specified, check the [`FIREBASE_AUTH_EMULATOR_HOST` environment variable obtained from the request](https://github.com/Code-Hex/firebase-auth-cloudflare-workers#emulatorenv).

### What content should I read?

- [Manage Session Cookies](https://firebase.google.com/docs/auth/admin/manage-cookies)

### Security Considerations when using session cookies

When considering that a web framework uses tokens via cookies, security measures related to traditional browsers and cookies should be considered.

1. CSRF (Cross-Site Request Forgery)
2. XSS (Cross-Site Scripting)
3. MitM (Man-in-the-middle attack)

Let's consider each:

**CSRF**

This is provided by hono as a standard middleware feature

https://hono.dev/middleware/builtin/csrf

**XSS**

An attacker can inject a script and steal JWTs stored in cookies. Set the httpOnly flag on the cookie to prevent access from JavaScript. Additionally, configure "Content Security Policy" (CSP) to prevent unauthorized script execution. It is recommeded to force httpOnly and the functionality here: https://hono.dev/middleware/builtin/secure-headers

**MitM**

If your cookie security settings are inappropriate, there is a risk that your cookies will be stolen by a MitM. Use Samesite (or hono csrf middleware) and `__Secure-` prefix and `__Host-` prefix attributes.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes

An example of good cookie settings:

```ts
const secureCookieSettings: CookieOptions = {
path: '/',
domain: <your_domain>,
secure: true,
httpOnly: true,
sameSite: 'Strict',
}
```

## Author

codehex <https://github.com/Code-Hex>
Expand Down
18 changes: 9 additions & 9 deletions packages/firebase-auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,19 @@
"access": "public"
},
"dependencies": {
"firebase-auth-cloudflare-workers": "^1.1.0"
"firebase-auth-cloudflare-workers": "^2.0.2"
},
"peerDependencies": {
"hono": ">=3.*"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20231025.0",
"firebase-tools": "^11.4.0",
"hono": "^3.11.7",
"miniflare": "^3.20231025.1",
"prettier": "^2.7.1",
"tsup": "^8.0.1",
"typescript": "^4.7.4",
"vitest": "^0.34.6"
"@cloudflare/workers-types": "^4.20240222.0",
"firebase-tools": "^13.3.1",
"hono": "3.12.12",
"miniflare": "^3.20240208.0",
"prettier": "^3.2.5",
"tsup": "^8.0.2",
"typescript": "^5.3.3",
"vitest": "^1.3.1"
}
}
79 changes: 70 additions & 9 deletions packages/firebase-auth/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getCookie } from 'hono/cookie'
import type { KeyStorer, FirebaseIdToken } from 'firebase-auth-cloudflare-workers'
import { Auth, WorkersKVStoreSingle } from 'firebase-auth-cloudflare-workers'
import type { Context, MiddlewareHandler } from 'hono'
Expand All @@ -24,7 +25,7 @@ const defaultKeyStoreInitializer = (c: Context<{ Bindings: VerifyFirebaseAuthEnv
const res = new Response('Not Implemented', {
status: 501,
})
throw new HTTPException(501, { res })
throw new HTTPException(res.status, { res })
}
return WorkersKVStoreSingle.getOrInitialize(
c.env.PUBLIC_JWK_CACHE_KEY ?? defaultKVStoreJWKCacheKey,
Expand All @@ -35,29 +36,32 @@ const defaultKeyStoreInitializer = (c: Context<{ Bindings: VerifyFirebaseAuthEnv
export const verifyFirebaseAuth = (userConfig: VerifyFirebaseAuthConfig): MiddlewareHandler => {
const config = {
projectId: userConfig.projectId,
AuthorizationHeaderKey: userConfig.authorizationHeaderKey ?? 'Authorization',
KeyStore: userConfig.keyStore,
authorizationHeaderKey: userConfig.authorizationHeaderKey ?? 'Authorization',
keyStore: userConfig.keyStore,
keyStoreInitializer: userConfig.keyStoreInitializer ?? defaultKeyStoreInitializer,
disableErrorLog: userConfig.disableErrorLog,
firebaseEmulatorHost: userConfig.firebaseEmulatorHost,
}
} satisfies VerifyFirebaseAuthConfig

// TODO(codehex): will be supported
const checkRevoked = false

return async (c, next) => {
const authorization = c.req.raw.headers.get(config.AuthorizationHeaderKey)
const authorization = c.req.raw.headers.get(config.authorizationHeaderKey)
if (authorization === null) {
const res = new Response('Bad Request', {
status: 400,
})
throw new HTTPException(400, { res })
throw new HTTPException(res.status, { res, message: 'authorization header is empty' })
}
const jwt = authorization.replace(/Bearer\s+/i, '')
const auth = Auth.getOrInitialize(
config.projectId,
config.KeyStore ?? config.keyStoreInitializer(c)
config.keyStore ?? config.keyStoreInitializer(c)
)

try {
const idToken = await auth.verifyIdToken(jwt, {
const idToken = await auth.verifyIdToken(jwt, checkRevoked, {
FIREBASE_AUTH_EMULATOR_HOST:
config.firebaseEmulatorHost ?? c.env.FIREBASE_AUTH_EMULATOR_HOST,
})
Expand All @@ -73,7 +77,10 @@ export const verifyFirebaseAuth = (userConfig: VerifyFirebaseAuthConfig): Middle
const res = new Response('Unauthorized', {
status: 401,
})
throw new HTTPException(401, { res })
throw new HTTPException(res.status, {
res,
message: `failed to verify the requested firebase token: ${String(err)}`,
})
}
await next()
}
Expand All @@ -90,3 +97,57 @@ export const getFirebaseToken = (c: Context): FirebaseIdToken | null => {
}
return idToken
}

export interface VerifySessionCookieFirebaseAuthConfig {
projectId: string
cookieName?: string
keyStore?: KeyStorer
keyStoreInitializer?: (c: Context) => KeyStorer
firebaseEmulatorHost?: string
redirects: {
signIn: string
}
}

export const verifySessionCookieFirebaseAuth = (
userConfig: VerifySessionCookieFirebaseAuthConfig
): MiddlewareHandler => {
const config = {
projectId: userConfig.projectId,
cookieName: userConfig.cookieName ?? 'session',
keyStore: userConfig.keyStore,
keyStoreInitializer: userConfig.keyStoreInitializer ?? defaultKeyStoreInitializer,
firebaseEmulatorHost: userConfig.firebaseEmulatorHost,
redirects: userConfig.redirects,
} satisfies VerifySessionCookieFirebaseAuthConfig

// TODO(codehex): will be supported
const checkRevoked = false

return async (c, next) => {
const auth = Auth.getOrInitialize(
config.projectId,
config.keyStore ?? config.keyStoreInitializer(c)
)
const session = getCookie(c, config.cookieName)
if (session === undefined) {
const res = c.redirect(config.redirects.signIn)
throw new HTTPException(res.status, { res, message: 'session is empty' })
}

try {
const idToken = await auth.verifySessionCookie(session, checkRevoked, {
FIREBASE_AUTH_EMULATOR_HOST:
config.firebaseEmulatorHost ?? c.env.FIREBASE_AUTH_EMULATOR_HOST,
})
setFirebaseToken(c, idToken)
} catch (err) {
const res = c.redirect(config.redirects.signIn)
throw new HTTPException(res.status, {
res,
message: `failed to verify the requested firebase token: ${String(err)}`,
})
}
await next()
}
}
Loading

0 comments on commit c9f110d

Please sign in to comment.