-
Notifications
You must be signed in to change notification settings - Fork 320
refactor: extract download token helpers #542
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
Open
zereight
wants to merge
3
commits into
main
Choose a base branch
from
refactor/download-token-helpers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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 hidden or 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 hidden or 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 hidden or 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,46 @@ | ||
| import { describe, test } from "node:test"; | ||
| import assert from "node:assert"; | ||
| import { createDownloadToken, decryptDownloadToken } from "../../utils/download-token.js"; | ||
|
|
||
| describe("download token helpers", () => { | ||
| test("round-trips auth, api URL, and resource binding", () => { | ||
| const token = createDownloadToken( | ||
| "Authorization", | ||
| "Bearer glpat-example-token", | ||
| "https://gitlab.example.com/api/v4", | ||
| { | ||
| type: "attachment", | ||
| params: { project_id: "group/project", secret: "abc", filename: "file.txt" }, | ||
| } | ||
| ); | ||
|
|
||
| const decrypted = decryptDownloadToken(token); | ||
|
|
||
| assert.deepStrictEqual(decrypted, { | ||
| header: "Authorization", | ||
| token: "Bearer glpat-example-token", | ||
| apiUrl: "https://gitlab.example.com/api/v4", | ||
| resourceType: "attachment", | ||
| resourceParams: { project_id: "group/project", secret: "abc", filename: "file.txt" }, | ||
| }); | ||
| }); | ||
|
|
||
| test("returns null for invalid tokens", () => { | ||
| assert.strictEqual(decryptDownloadToken("not-a-valid-token"), null); | ||
| }); | ||
|
|
||
| test("returns null for expired tokens", () => { | ||
| const originalNow = Date.now; | ||
| const issuedAt = 1_700_000_000_000; | ||
|
|
||
| try { | ||
| Date.now = () => issuedAt; | ||
| const token = createDownloadToken("Private-Token", "glpat-example-token"); | ||
|
|
||
| Date.now = () => issuedAt + 301_000; | ||
| assert.strictEqual(decryptDownloadToken(token), null); | ||
| } finally { | ||
| Date.now = originalNow; | ||
| } | ||
| }); | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or 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,90 @@ | ||
| import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"; | ||
|
|
||
| export interface DownloadTokenResource { | ||
| type: string; | ||
| params: Record<string, string>; | ||
| } | ||
|
|
||
| export interface DecryptedDownloadToken { | ||
| header: string; | ||
| token: string; | ||
| apiUrl?: string; | ||
| resourceType?: string; | ||
| resourceParams?: Record<string, string>; | ||
| } | ||
|
|
||
| /** | ||
| * Encryption key for download tokens. When DOWNLOAD_TOKEN_SECRET is set | ||
| * (recommended for HA deployments behind a load balancer) the key is | ||
| * derived from that value so all replicas share the same key. Otherwise | ||
| * a random key is generated per process (tokens are not portable across | ||
| * restarts or replicas). | ||
| */ | ||
| const DOWNLOAD_TOKEN_KEY: Buffer = (() => { | ||
| const secret = process.env.DOWNLOAD_TOKEN_SECRET; | ||
| if (secret) { | ||
| return createHash("sha256").update(secret).digest(); | ||
| } | ||
| return randomBytes(32); | ||
| })(); | ||
|
|
||
| /** Download token TTL in seconds (default 5 minutes). */ | ||
| const DEFAULT_DOWNLOAD_TOKEN_TTL = 300; | ||
| const parsedDownloadTokenTtl = Number.parseInt(process.env.DOWNLOAD_TOKEN_TTL || "", 10); | ||
| const DOWNLOAD_TOKEN_TTL = | ||
| Number.isFinite(parsedDownloadTokenTtl) && parsedDownloadTokenTtl > 0 | ||
| ? parsedDownloadTokenTtl | ||
| : DEFAULT_DOWNLOAD_TOKEN_TTL; | ||
|
|
||
| /** | ||
| * Create a self-contained encrypted download token for a specific GitLab resource. | ||
| */ | ||
| export function createDownloadToken( | ||
| header: string, | ||
| token: string, | ||
| apiUrl?: string, | ||
| resource?: DownloadTokenResource | ||
| ): string { | ||
| const iv = randomBytes(12); | ||
| const cipher = createCipheriv("aes-256-gcm", DOWNLOAD_TOKEN_KEY, iv); | ||
| const payload = JSON.stringify({ | ||
| h: header, | ||
| t: token, | ||
| e: Math.floor(Date.now() / 1000) + DOWNLOAD_TOKEN_TTL, | ||
| ...(apiUrl ? { u: apiUrl } : {}), | ||
| ...(resource ? { r: resource.type, p: resource.params } : {}), | ||
| }); | ||
| const encrypted = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]); | ||
| const tag = cipher.getAuthTag(); | ||
| return Buffer.concat([iv, tag, encrypted]).toString("base64url"); | ||
| } | ||
|
|
||
| /** | ||
| * Decrypt and validate a download token, returning null when it is invalid or expired. | ||
| */ | ||
| export function decryptDownloadToken(tokenStr: string): DecryptedDownloadToken | null { | ||
| try { | ||
| const buf = Buffer.from(tokenStr, "base64url"); | ||
| if (buf.length < 29) return null; | ||
| const iv = buf.subarray(0, 12); | ||
| const tag = buf.subarray(12, 28); | ||
| const encrypted = buf.subarray(28); | ||
| const decipher = createDecipheriv("aes-256-gcm", DOWNLOAD_TOKEN_KEY, iv); | ||
| decipher.setAuthTag(tag); | ||
| const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]); | ||
| const payload = JSON.parse(decrypted.toString("utf8")); | ||
| if (payload.e && Math.floor(Date.now() / 1000) > payload.e) { | ||
| return null; | ||
| } | ||
| if (typeof payload.h !== "string" || payload.h.length === 0) return null; | ||
| if (typeof payload.t !== "string" || payload.t.length === 0) return null; | ||
| return { | ||
| header: payload.h, | ||
| token: payload.t, | ||
| ...(payload.u ? { apiUrl: payload.u } : {}), | ||
| ...(payload.r ? { resourceType: payload.r, resourceParams: payload.p } : {}), | ||
| }; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.