-
Notifications
You must be signed in to change notification settings - Fork 0
Credential hash: constant-time comparison + HMAC-SHA-256 with pepper #98
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
Merged
Merged
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
16 changes: 16 additions & 0 deletions
16
apps/api/migrations/0002_invalidate_non_hmac_credentials.sql
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,16 @@ | ||
| -- This pre-release migration intentionally invalidates credential formats that | ||
| -- cannot be verified with the required server-side pepper. | ||
| DELETE FROM endpoint_secrets | ||
| WHERE status != 'active' | ||
| AND NOT ( | ||
| length(secret_hash) = 76 | ||
| AND substr(secret_hash, 1, 12) = 'hmac-sha256$' | ||
| AND substr(secret_hash, 13) NOT GLOB '*[^0-9a-f]*' | ||
| ); | ||
|
|
||
| DELETE FROM tokens | ||
| WHERE NOT ( | ||
| length(token_hash) = 76 | ||
| AND substr(token_hash, 1, 12) = 'hmac-sha256$' | ||
| AND substr(token_hash, 13) NOT GLOB '*[^0-9a-f]*' | ||
| ); | ||
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,102 @@ | ||
| import { readFileSync } from "node:fs"; | ||
| import { DatabaseSync } from "node:sqlite"; | ||
|
|
||
| import { afterEach, describe, expect, it } from "vitest"; | ||
|
|
||
| const readMigration = (name: string) => | ||
| readFileSync(new URL(name, import.meta.url), "utf8"); | ||
|
|
||
| describe("credential hash migration", () => { | ||
| let database: DatabaseSync | undefined; | ||
|
|
||
| afterEach(() => { | ||
| database?.close(); | ||
| }); | ||
|
|
||
| it("invalidates non-HMAC credentials without leaving private ingest unguarded", () => { | ||
| database = new DatabaseSync(":memory:"); | ||
| database.exec(readMigration("0001_initial_schema.sql")); | ||
| database.exec(` | ||
| INSERT INTO endpoints ( | ||
| id, account_id, name, mode, status, public_read, event_count, | ||
| event_limit, expires_at, created_at, updated_at | ||
| ) VALUES ( | ||
| 'ep_migration', 'acc_mvp', 'migration', 'private', 'active', 0, 1, | ||
| 1000, '2026-07-12T12:00:00.000Z', '2026-07-05T12:00:00.000Z', | ||
| '2026-07-05T12:00:00.000Z' | ||
| ); | ||
|
|
||
| INSERT INTO events ( | ||
| id, endpoint_id, received_at, method, ingest_path, request_path, | ||
| query_json, allowlist_headers_json, sensitive_header_names_json, | ||
| content_type, content_length, user_agent, body_size, body_sha256, | ||
| body_r2_key, request_r2_key, secret_verification_status, | ||
| matched_secret_id, created_at | ||
| ) VALUES ( | ||
| 'evt_migration', 'ep_migration', '2026-07-05T12:00:00.000Z', 'POST', | ||
| '/ep_migration', '/', '{}', '{}', '[]', NULL, NULL, NULL, 0, 'body-hash', | ||
| 'events/body.raw', 'events/request.json', 'matched', 'sec_legacy_sha', | ||
| '2026-07-05T12:00:00.000Z' | ||
| ); | ||
| `); | ||
|
|
||
| const insertToken = database.prepare(` | ||
| INSERT INTO tokens ( | ||
| id, account_id, name, token_hash, status, created_at, | ||
| last_used_at, revoked_at | ||
| ) VALUES (?, 'acc_mvp', NULL, ?, 'active', '2026-07-05T12:00:00.000Z', NULL, NULL) | ||
| `); | ||
| insertToken.run("tok_legacy_sha", "a".repeat(64)); | ||
| insertToken.run( | ||
| "tok_pbkdf2", | ||
| `pbkdf2-sha256$600000$${"b".repeat(32)}$${"c".repeat(64)}`, | ||
| ); | ||
| insertToken.run("tok_malformed", `hmac-sha256$${"G".repeat(64)}`); | ||
| insertToken.run("tok_hmac", `hmac-sha256$${"d".repeat(64)}`); | ||
|
|
||
| const insertEndpointSecret = database.prepare(` | ||
| INSERT INTO endpoint_secrets ( | ||
| id, endpoint_id, secret_hash, status, created_at, | ||
| last_used_at, revoked_at | ||
| ) VALUES (?, 'ep_migration', ?, ?, '2026-07-05T12:00:00.000Z', NULL, NULL) | ||
| `); | ||
| insertEndpointSecret.run("sec_legacy_sha", "e".repeat(64), "active"); | ||
| insertEndpointSecret.run( | ||
| "sec_malformed", | ||
| "not-a-credential-hash", | ||
| "active", | ||
| ); | ||
| insertEndpointSecret.run("sec_revoked_legacy", "1".repeat(64), "revoked"); | ||
| insertEndpointSecret.run( | ||
| "sec_hmac", | ||
| `hmac-sha256$${"f".repeat(64)}`, | ||
| "active", | ||
| ); | ||
|
|
||
| database.exec(readMigration("0002_invalidate_non_hmac_credentials.sql")); | ||
|
|
||
| expect(database.prepare("SELECT id FROM tokens ORDER BY id").all()).toEqual( | ||
| [{ id: "tok_hmac" }], | ||
| ); | ||
| expect( | ||
| database.prepare("SELECT id FROM endpoint_secrets ORDER BY id").all(), | ||
| ).toEqual([ | ||
| { id: "sec_hmac" }, | ||
| { id: "sec_legacy_sha" }, | ||
| { id: "sec_malformed" }, | ||
| ]); | ||
| expect( | ||
| database | ||
| .prepare( | ||
| "SELECT COUNT(*) AS count FROM endpoint_secrets WHERE endpoint_id = 'ep_migration' AND status = 'active'", | ||
| ) | ||
| .get(), | ||
| ).toEqual({ count: 3 }); | ||
| expect(database.prepare("SELECT id FROM endpoints").all()).toEqual([ | ||
| { id: "ep_migration" }, | ||
| ]); | ||
| expect(database.prepare("SELECT id FROM events").all()).toEqual([ | ||
| { id: "evt_migration" }, | ||
| ]); | ||
| }); | ||
| }); |
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,138 @@ | ||
| import { | ||
| assertStoredTokenId, | ||
| type TokenId, | ||
| testTokenId, | ||
| } from "@barestash/shared"; | ||
| import { describe, expect, it } from "vitest"; | ||
|
|
||
| import type { TokenRepository } from "../domain/ports.js"; | ||
| import { hasBootstrapAuth, verifyRequestAuthentication } from "./auth.js"; | ||
| import { hashCredential } from "./credential-hash.js"; | ||
|
|
||
| const TEST_BOOTSTRAP_TOKEN = "bootstrap-secret-for-local-staging-tests-ok"; | ||
|
|
||
| describe("hasBootstrapAuth", () => { | ||
| it("rejects configured bootstrap tokens shorter than the minimum length", () => { | ||
| expect( | ||
| hasBootstrapAuth( | ||
| true, | ||
| TEST_BOOTSTRAP_TOKEN, | ||
| "too-short-for-bootstrap-token", | ||
| ), | ||
| ).toBe(false); | ||
| }); | ||
|
|
||
| it("accepts matching bootstrap tokens with constant-time comparison", () => { | ||
| expect( | ||
| hasBootstrapAuth(true, TEST_BOOTSTRAP_TOKEN, TEST_BOOTSTRAP_TOKEN), | ||
| ).toBe(true); | ||
| expect( | ||
| hasBootstrapAuth(true, `${TEST_BOOTSTRAP_TOKEN}x`, TEST_BOOTSTRAP_TOKEN), | ||
| ).toBe(false); | ||
| }); | ||
| }); | ||
|
|
||
| describe("verifyRequestAuthentication", () => { | ||
| it("authenticates PAT bearer tokens by token id and derived secret hash", async () => { | ||
| const tokenId = testTokenId("auth"); | ||
| const secretSuffix = "abcdefghijklmnopqrstuvwxyz012345"; | ||
| const bearerToken = `bst_pat_${tokenId.slice("tok_".length)}_${secretSuffix}`; | ||
| const tokenHash = await hashCredential(secretSuffix, { pepper: "" }); | ||
| const tokenRepository = { | ||
| async findActiveTokenById() { | ||
| return { | ||
| id: tokenId, | ||
| name: "test token", | ||
| status: "active" as const, | ||
| created_at: "2026-07-05T12:00:00.000Z", | ||
| last_used_at: null, | ||
| revoked_at: null, | ||
| account_id: "acc_mvp", | ||
| token_hash: tokenHash, | ||
| }; | ||
| }, | ||
| } as unknown as TokenRepository; | ||
|
|
||
| await expect( | ||
| verifyRequestAuthentication(`Bearer ${bearerToken}`, tokenRepository, { | ||
| pepper: "", | ||
| }), | ||
| ).resolves.toEqual({ | ||
| kind: "ok", | ||
| value: { | ||
| accountId: "acc_mvp", | ||
| tokenId, | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it("rejects bearer tokens with an invalid secret hash", async () => { | ||
| const tokenId = testTokenId("invalid"); | ||
| const secretSuffix = "abcdefghijklmnopqrstuvwxyz012345"; | ||
| const bearerToken = `bst_pat_${tokenId.slice("tok_".length)}_${secretSuffix}`; | ||
| const tokenRepository = { | ||
| async findActiveTokenById() { | ||
| return { | ||
| id: tokenId, | ||
| name: "test token", | ||
| status: "active" as const, | ||
| created_at: "2026-07-05T12:00:00.000Z", | ||
| last_used_at: null, | ||
| revoked_at: null, | ||
| account_id: "acc_mvp", | ||
| token_hash: await hashCredential("different-secret", { pepper: "" }), | ||
| }; | ||
| }, | ||
| } as unknown as TokenRepository; | ||
|
|
||
| await expect( | ||
| verifyRequestAuthentication(`Bearer ${bearerToken}`, tokenRepository, { | ||
| pepper: "", | ||
| }), | ||
| ).resolves.toEqual({ | ||
| kind: "error", | ||
| code: "not_authenticated", | ||
| message: "Authentication is required.", | ||
| status: 401, | ||
| }); | ||
| }); | ||
|
|
||
| it.each([ | ||
| "-", | ||
| "_", | ||
| ])("authenticates stored PAT ids containing a legacy %s suffix character", async (legacyCharacter) => { | ||
| const tokenIdSuffix = `${"A".repeat(23)}${legacyCharacter}`; | ||
| const tokenId = assertStoredTokenId(`tok_${tokenIdSuffix}`); | ||
| const secretSuffix = "abcdefghijklmnopqrstuvwxyz012345"; | ||
| const bearerToken = `bst_pat_${tokenIdSuffix}_${secretSuffix}`; | ||
| const tokenHash = await hashCredential(secretSuffix, { pepper: "" }); | ||
| const tokenRepository = { | ||
| async findActiveTokenById(candidateTokenId: TokenId) { | ||
| expect(candidateTokenId).toBe(tokenId); | ||
|
|
||
| return { | ||
| id: tokenId, | ||
| name: "legacy id token", | ||
| status: "active" as const, | ||
| created_at: "2026-07-05T12:00:00.000Z", | ||
| last_used_at: null, | ||
| revoked_at: null, | ||
| account_id: "acc_mvp", | ||
| token_hash: tokenHash, | ||
| }; | ||
| }, | ||
| } as unknown as TokenRepository; | ||
|
|
||
| await expect( | ||
| verifyRequestAuthentication(`Bearer ${bearerToken}`, tokenRepository, { | ||
| pepper: "", | ||
| }), | ||
| ).resolves.toEqual({ | ||
| kind: "ok", | ||
| value: { | ||
| accountId: "acc_mvp", | ||
| tokenId, | ||
| }, | ||
| }); | ||
| }); | ||
| }); |
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.
Uh oh!
There was an error while loading. Please reload this page.