-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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
feat: env leak detection #11203
Closed
Closed
feat: env leak detection #11203
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
351298d
feat: experiment with leak detection
florian-lefebvre 400b480
Merge branch 'main' into feat/astro-env-leak-protection
florian-lefebvre 0ad25c7
feat: new implementation
florian-lefebvre 9ab6fec
Discard changes to packages/astro/src/core/app/types.ts
florian-lefebvre 649422f
Discard changes to packages/astro/templates/env/module.mjs
florian-lefebvre cbf63e2
feat: add test
florian-lefebvre 28221b0
Discard changes to examples/basics/astro.config.mjs
florian-lefebvre c7d23e0
feat: add jsdoc and changeset
florian-lefebvre 5c37da6
Merge branch 'main' into feat/astro-env-leak-protection
florian-lefebvre 86c86df
Update .changeset/forty-crabs-judge.md
florian-lefebvre 4974954
fix: typos
florian-lefebvre 4eee601
feat: update config reference
florian-lefebvre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
--- | ||
'astro': patch | ||
--- | ||
|
||
Adds an optional middleware for usage with `astro:env` | ||
|
||
If you're using `astro:env`, you can now use a middleware to detect server envrionment variables leaks on the client: | ||
|
||
```ts | ||
// src/middleware.js | ||
|
||
import { leakDetectionMiddleware } from 'astro/env/middleware' | ||
import { sequence, defineMiddleware } from 'astro:middleware' | ||
|
||
const userMiddleware = defineMiddleware((_, next) => { | ||
return next() | ||
}) | ||
|
||
export const onRequest = sequence( | ||
// It's important to use use it first to be able to catch the returned response last | ||
leakDetectionMiddleware(), | ||
userMiddleware | ||
); | ||
``` | ||
|
||
An error will be thrown instead of rendering the page if a leak is detected. | ||
|
||
You can pass 2 options: | ||
|
||
1. `filterContentType`: filters what response content type should trigger the check. Defaults to the content type starting with `text/` or `application/json` | ||
2. `excludeKeys`: by default, all server environment variables are checked. However, you may have variables whose value is really likely to end up on the client but not because it leaked (eg. `test`). In this case, you can exclude those keys. | ||
|
||
```ts | ||
import { leakDetectionMiddleware } from 'astro/env/middleware' | ||
|
||
export const onRequest = leakDetectionMiddleware({ | ||
// Do not filter json response | ||
filterContentType: (contentType) => contentType.startsWith('text/'), | ||
excludeKeys: ['PORT'] | ||
}) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 2 additions & 2 deletions
4
packages/astro/src/env/runtime.ts → packages/astro/src/env/runtime/index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import type { MiddlewareHandler } from '../../@types/astro.js'; | ||
|
||
interface MiddewareOptions { | ||
/** | ||
* Filters what response content type should trigger the check. Defaults to the content type | ||
* starting with `/text` or `application/json` | ||
*/ | ||
filterContentType?: (contentType: string) => boolean; | ||
/** | ||
* By default, all server environment variables are checked. However, you may have variables | ||
* whose value is really likely to end up on the client but not because it leaked (eg. `test`). | ||
* In this case, you can exclude those keys. | ||
*/ | ||
// @ts-ignore | ||
excludeKeys?: Array<keyof Omit<typeof import('astro:env/server'), 'getSecret'>>; | ||
} | ||
|
||
/** | ||
* This middleware will throw if a response with the specified content type contains a server | ||
* environment variable. | ||
*/ | ||
export function leakDetectionMiddleware({ | ||
filterContentType = (v) => v.startsWith('text/') || v.startsWith('application/json'), | ||
excludeKeys = [], | ||
}: MiddewareOptions = {}): MiddlewareHandler { | ||
return async (_, next) => { | ||
const response = await next(); | ||
|
||
const contentType = response.headers.get('Content-Type'); | ||
florian-lefebvre marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (contentType && filterContentType(contentType)) { | ||
const content = await response.clone().text(); | ||
const { getSecret, ...secrets }: Record<string, string | undefined> = await import( | ||
// @ts-ignore | ||
'astro:env/server' | ||
); | ||
for (const [key, value] of Object.entries(secrets)) { | ||
if (excludeKeys.includes(key) || value === undefined) { | ||
continue; | ||
} | ||
if (content.includes(value)) { | ||
throw new Error(`[astro:env] \`${key}\` leaked client-side.`); | ||
} | ||
} | ||
} | ||
|
||
return response; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
export { setGetEnv, type GetEnv } from './runtime.js'; | ||
export { setGetEnv, type GetEnv } from './runtime/index.js'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import assert from 'node:assert/strict'; | ||
import { describe, it } from 'node:test'; | ||
import { loadFixture } from './test-utils.js'; | ||
|
||
describe('astro:env leak detection', () => { | ||
it('should fail if a secret is sent to the client', async () => { | ||
const fixture = await loadFixture({ | ||
root: './fixtures/astro-env-leak-detection/', | ||
}); | ||
|
||
let error; | ||
try { | ||
await fixture.build(); | ||
} catch (err) { | ||
error = err; | ||
} | ||
|
||
assert.equal(error instanceof Error, true); | ||
assert.equal(error.message.includes('leaked client-side'), true); | ||
}); | ||
}); |
16 changes: 16 additions & 0 deletions
16
packages/astro/test/fixtures/astro-env-leak-detection/astro.config.mjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { defineConfig, envField } from 'astro/config'; | ||
|
||
// https://astro.build/config | ||
export default defineConfig({ | ||
experimental: { | ||
env: { | ||
schema: { | ||
FOO: envField.string({ | ||
context: 'server', | ||
access: 'secret', | ||
default: 'this is a secret' | ||
}), | ||
}, | ||
} | ||
} | ||
}); |
8 changes: 8 additions & 0 deletions
8
packages/astro/test/fixtures/astro-env-leak-detection/package.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"name": "@test/astro-env-leak-detection", | ||
"version": "0.0.0", | ||
"private": true, | ||
"dependencies": { | ||
"astro": "workspace:*" | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
packages/astro/test/fixtures/astro-env-leak-detection/src/middleware.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import { leakDetectionMiddleware } from 'astro/env/middleware' | ||
|
||
export const onRequest = leakDetectionMiddleware() |
4 changes: 4 additions & 0 deletions
4
packages/astro/test/fixtures/astro-env-leak-detection/src/pages/index.astro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
--- | ||
import { FOO } from "astro:env/server" | ||
--- | ||
<p>{FOO}</p> |
3 changes: 3 additions & 0 deletions
3
packages/astro/test/fixtures/astro-env-leak-detection/tsconfig.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"extends": "astro/tsconfigs/base" | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if we should make this
astro:env/middleware
instead?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it makes things a bit more complicated. There's no codegen involved for the middleware code so I'm a bit reluctant to move it to a virtual import. We were also doing this for
astro:env/setup
and ended up moving it toastro/env/setup