Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions apps/api/migrations/0002_invalidate_non_hmac_credentials.sql
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
Comment thread
codemountains marked this conversation as resolved.
WHERE NOT (
length(token_hash) = 76
AND substr(token_hash, 1, 12) = 'hmac-sha256$'
AND substr(token_hash, 13) NOT GLOB '*[^0-9a-f]*'
);
102 changes: 102 additions & 0 deletions apps/api/migrations/credential-hash-migration.test.ts
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" },
]);
});
});
30 changes: 27 additions & 3 deletions apps/api/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ describe("API Worker", () => {
error: {
code: "internal_error",
message:
"Required runtime bindings are not configured: DB, REQUEST_BODIES, ABUSE_IP_RATE_LIMITER, INGEST_ENDPOINT_RATE_LIMITER, ENDPOINT_CREATION_RATE_LIMITER, AUTH_RATE_LIMITER, MCP_RATE_LIMITER, WRITE_RATE_LIMITER, SSE_RATE_LIMITER.",
"Required runtime bindings are not configured: DB, REQUEST_BODIES, BARESTASH_CREDENTIAL_PEPPER, ABUSE_IP_RATE_LIMITER, INGEST_ENDPOINT_RATE_LIMITER, ENDPOINT_CREATION_RATE_LIMITER, AUTH_RATE_LIMITER, MCP_RATE_LIMITER, WRITE_RATE_LIMITER, SSE_RATE_LIMITER.",
},
});
expect(error).toHaveBeenCalledWith(
Expand All @@ -123,6 +123,7 @@ describe("API Worker", () => {
missing_bindings: [
"DB",
"REQUEST_BODIES",
"BARESTASH_CREDENTIAL_PEPPER",
"ABUSE_IP_RATE_LIMITER",
"INGEST_ENDPOINT_RATE_LIMITER",
"ENDPOINT_CREATION_RATE_LIMITER",
Expand Down Expand Up @@ -150,8 +151,30 @@ describe("API Worker", () => {
});

it.each([
[{ DB: {} as D1Database, ...configuredRateLimiters }, "REQUEST_BODIES"],
[{ REQUEST_BODIES: {} as R2Bucket, ...configuredRateLimiters }, "DB"],
[
{
DB: {} as D1Database,
BARESTASH_CREDENTIAL_PEPPER: "test-pepper",
...configuredRateLimiters,
},
"REQUEST_BODIES",
],
[
{
REQUEST_BODIES: {} as R2Bucket,
BARESTASH_CREDENTIAL_PEPPER: "test-pepper",
...configuredRateLimiters,
},
"DB",
],
[
{
DB: {} as D1Database,
REQUEST_BODIES: {} as R2Bucket,
...configuredRateLimiters,
},
"BARESTASH_CREDENTIAL_PEPPER",
],
])("identifies an individually missing binding", async (env, missing) => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const app = createApiApp();
Expand Down Expand Up @@ -186,6 +209,7 @@ describe("API Worker", () => {
const env: Record<string, unknown> = {
DB: {} as D1Database,
REQUEST_BODIES: {} as R2Bucket,
BARESTASH_CREDENTIAL_PEPPER: "test-pepper",
...configuredRateLimiters,
};
delete env[missing];
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,13 @@ export function createApiApp(options: CreateApiAppOptions = {}): Hono<ApiEnv> {
return;
}

const credentialPepper = context.env?.BARESTASH_CREDENTIAL_PEPPER;
const missingBindings = [
context.env?.DB === undefined ? "DB" : undefined,
context.env?.REQUEST_BODIES === undefined ? "REQUEST_BODIES" : undefined,
credentialPepper === undefined || credentialPepper === ""
? "BARESTASH_CREDENTIAL_PEPPER"
: undefined,
context.env?.BARESTASH_API_HOSTNAME !== undefined &&
context.env?.BARESTASH_INGEST_HOSTNAME === undefined
? "BARESTASH_INGEST_HOSTNAME"
Expand Down
138 changes: 138 additions & 0 deletions apps/api/src/application/auth.test.ts
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,
},
});
});
});
Loading
Loading