Skip to content
Closed
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
13 changes: 11 additions & 2 deletions packages/logging/src/index.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,17 @@ test('serializes errors, causes, bigint and circular context safely',()=>{
assert.equal(record.context.error.message,'failure');assert.equal(record.context.error.cause.message,'root');
});
test('redacts URL credentials and query tokens in errors',()=>{
const {logger,records}=capture();logger.error('failed',new Error('https://user:secret@rpc.example/?token=hidden'));
const text=JSON.stringify(records);assert.ok(!text.includes('user:secret'));assert.ok(!text.includes('token=hidden'));
const {logger,records}=capture();logger.error('failed',new Error('https://user:secret@rpc.example/?token=hidden'));
const text=JSON.stringify(records);assert.ok(!text.includes('user:secret'));assert.ok(!text.includes('token=hidden'));
});
test('redacts URL query strings and fragments',()=>{
const {logger,records}=capture();logger.error('failed','https://api.example.com/path?query=value&param=test#fragment');
const text=JSON.stringify(records);assert.ok(!text.includes('query=value'));assert.ok(!text.includes('param=test'));assert.ok(!text.includes('#fragment'));
assert.ok(text.includes('[REDACTED]'));
});
test('redacts URL credentials and query strings together',()=>{
const {logger,records}=capture();logger.error('failed','https://user:pass@api.example.com/path?query=value#fragment');
const text=JSON.stringify(records);assert.ok(!text.includes('user:pass'));assert.ok(!text.includes('query=value'));assert.ok(!text.includes('#fragment'));
});
test('hostile accessors, circular arrays, deep context and broken sinks do not throw',()=>{
const {logger,records}=capture();const a=[];a.push(a);
Expand Down
12 changes: 9 additions & 3 deletions packages/logging/src/serialization.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ const sensitive = (key) => /secret|token|password|passwd|privatekey|credential|c

function scrubText(value, secrets) {
let text = value
.replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, '$1[REDACTED]@')
.replace(/([?&](?:[^=&\s]*(?:secret|token|password|credential|api[_-]?key)[^=&\s]*)=)[^&#\s]*/gi, '$1[REDACTED]')
// Redact username:password@ in URLs, and also redact query string and fragment
.replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@([^\s?#]+)(\?[^\s#]*)?(#[^\s]*)?/gi, '$1[REDACTED]@$2[REDACTED][REDACTED]')
// Also handle URLs without credentials but with query/fragment
.replace(/(https?:\/\/[^\s?#]+)(\?[^\s#]*)?(#[^\s]*)?/gi, (match, prefix, query, fragment) => {
// Don't double-redact if already handled above
if (match.includes('[REDACTED]@')) return match;
return prefix + (query ? '[REDACTED]' : '') + (fragment ? '[REDACTED]' : '');
})
.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/_=.-]+/gi, '$1 [REDACTED]')
.replace(/((?:[\w-]*(?:secret|token|password|credential|authorization|cookie|api[_-]?key)[\w-]*)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi, '$1[REDACTED]')
.replace(/\bS[A-Z2-7]{55}\b/g, REDACTED)
Expand Down Expand Up @@ -63,4 +69,4 @@ function redactValue(value) {
exports.redactValue = redactValue;
exports.collectSecrets = collectSecrets;
exports.scrubText = scrubText;
exports.serialize = serialize;
exports.serialize = serialize;
42 changes: 42 additions & 0 deletions packages/sdk/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,45 @@ export class SubRosaTimeoutError extends Error {
this.pollIntervalMs = params.pollIntervalMs;
}
}

export type PaginationErrorReason =
| "invalid_page"
| "repeated_bidder"
| "repeated_cursor";

export interface SubRosaPaginationErrorParams {
roundId: bigint;
reason: PaginationErrorReason;
bidder?: string;
}

/**
* Raised when paginating bidders fails due to an invalid or inconsistent page.
* The error carries the round ID and a machine-readable reason so callers can
* handle specific failure modes (e.g., retry vs. abort).
*/
export class SubRosaPaginationError extends Error {
readonly name = "SubRosaPaginationError";
readonly roundId: bigint;
readonly reason: PaginationErrorReason;
readonly bidder?: string;

constructor(params: SubRosaPaginationErrorParams) {
let message: string;
switch (params.reason) {
case "invalid_page":
message = `round ${params.roundId}: page token is invalid or out of range`;
break;
case "repeated_bidder":
message = `round ${params.roundId}: bidder ${params.bidder ?? "unknown"} appears multiple times in the index`;
break;
case "repeated_cursor":
message = `round ${params.roundId}: pagination cursor did not advance`;
break;
}
super(message);
this.roundId = params.roundId;
this.reason = params.reason;
this.bidder = params.bidder;
}
}
4 changes: 4 additions & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export {
SubRosaManifestError,
SubRosaMissingReturnValueError,
SubRosaNetworkMismatchError,
SubRosaPaginationError,
SubRosaPreflightError,
SubRosaSessionMismatchError,
SubRosaSubmitError,
Expand All @@ -49,8 +50,10 @@ export type {
ManifestErrorParams,
NetworkMismatchErrorParams,
NetworkMismatchReason,
PaginationErrorReason,
PreflightFailureKind,
SubRosaPreflightErrorParams,
SubRosaPaginationErrorParams,
TimeoutErrorParams,
} from "./errors.js";

Expand Down Expand Up @@ -138,6 +141,7 @@ export {
hasBlockingFailures,
nativeXlmSacId,
parseMainnetReadinessFixture,
parseMicroStroops,
readLiveDeployment,
runMainnetReadiness,
summarizeDeploymentValue,
Expand Down
4 changes: 3 additions & 1 deletion packages/sdk/src/public-api-snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const EXPECTED_EXPORTS = [
"SubRosaMissingReturnValueError",
"SubRosaNetworkMismatchError",
"SubRosaNetworkPassphraseMismatchError",
"SubRosaPaginationError",
"SubRosaPreflightError",
"SubRosaSessionMismatchError",
"SubRosaSubmitError",
Expand Down Expand Up @@ -87,6 +88,7 @@ const EXPECTED_EXPORTS = [
"networkDisplayName",
"parseMainnetManifest",
"parseMainnetReadinessFixture",
"parseMicroStroops",
"readLiveDeployment",
"networkFingerprint",
"networkPassphrasesMatch",
Expand Down Expand Up @@ -125,4 +127,4 @@ describe("SDK public API snapshot", () => {
const expected = [...EXPECTED_EXPORTS].sort();
assert.deepEqual(actual, expected);
});
});
});
4 changes: 2 additions & 2 deletions packages/tlock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
},
"main": "src/index.ts",
"scripts": {
"test": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/seal.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts",
"test": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/seal.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts src/http-client.test.ts",
"test:quicknet": "node --import tsx --test src/quicknet.test.ts",
"test:unit": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts",
"test:unit": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts src/http-client.test.ts",
"test:seal": "node --import tsx --test src/seal.test.ts",
"recover:identities": "node --import tsx src/recover-identities.cli.ts",
"typecheck": "tsc --noEmit -p tsconfig.json"
Expand Down
6 changes: 6 additions & 0 deletions packages/tlock/src/ciphertext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ const offlineClient = {
const ROUND = 1_234_567;
const VALUE = 8_675_309n;
const NONCE = new Uint8Array(NONCE_BYTES).fill(0x2a);
// Test fixture contract/bidder IDs (valid Soroban strkeys)
const TEST_CONTRACT_ID = "C0000000000000000000000000000000000000000000000000000000000000000";
const TEST_BIDDER_ID = "GB0000000000000000000000000000000000000000000000000000000000000000";

/** Seal a bid offline. Each call re-encrypts, so ciphertexts differ. */
async function sealFixture(overrides?: {
Expand All @@ -50,9 +53,12 @@ async function sealFixture(overrides?: {
round?: number;
}): Promise<SealedBid> {
return sealBid({
contractId: TEST_CONTRACT_ID,
bidderId: TEST_BIDDER_ID,
value: overrides?.value ?? VALUE,
nonce: overrides?.nonce ?? NONCE,
round: overrides?.round ?? ROUND,
revealRound: ROUND,
client: offlineClient,
});
}
Expand Down
70 changes: 70 additions & 0 deletions packages/tlock/src/http-client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright (c) 2026 Sub Rosa contributors
// Tests for HTTP client content-type validation.

import { test } from "node:test";
import assert from "node:assert/strict";

import {
validateContentType,
ValidatingHttpChainClient,
createValidatingQuicknetClient,
} from "./http-client.js";

test("validateContentType accepts application/json", () => {
assert.doesNotThrow(() => validateContentType("application/json"));
});

test("validateContentType accepts application/json with charset", () => {
assert.doesNotThrow(() => validateContentType("application/json; charset=utf-8"));
assert.doesNotThrow(() => validateContentType("application/json;charset=utf-8"));
assert.doesNotThrow(() => validateContentType("APPLICATION/JSON; CHARSET=UTF-8"));
});

test("validateContentType rejects text/html", () => {
assert.throws(
() => validateContentType("text/html"),
/Unexpected Content-Type: expected application\/json, got text\/html/,
);
});

test("validateContentType rejects text/plain", () => {
assert.throws(
() => validateContentType("text/plain"),
/Unexpected Content-Type: expected application\/json, got text\/plain/,
);
});

test("validateContentType rejects application/xml", () => {
assert.throws(
() => validateContentType("application/xml"),
/Unexpected Content-Type: expected application\/json, got application\/xml/,
);
});

test("validateContentType rejects missing content-type", () => {
assert.throws(
() => validateContentType(null),
/Missing Content-Type header in Drand response/,
);
});

test("validateContentType rejects empty content-type", () => {
assert.throws(
() => validateContentType(""),
/Unexpected Content-Type: expected application\/json, got /,
);
});

test("createValidatingQuicknetClient returns a ChainClient", () => {
const client = createValidatingQuicknetClient();
assert.ok(typeof client.get === "function");
assert.ok(typeof client.latest === "function");
assert.ok(typeof client.chain === "function");
});

test("ValidatingHttpChainClient validates content-type before parsing", async () => {
// This test would require a mock server. We test the validator directly above.
// The client integration is tested by the quicknet tests using the real network.
const client = createValidatingQuicknetClient();
assert.ok(client instanceof ValidatingHttpChainClient);
});
101 changes: 101 additions & 0 deletions packages/tlock/src/http-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright (c) 2026 Sub Rosa contributors
// HTTP client with content-type validation for Drand responses.

import {
Chain,
ChainClient,
ChainOptions,
defaultChainOptions,
RandomnessBeacon,
HttpCachingChain,
} from "drand-client";

const JSON_CONTENT_TYPE = "application/json";

export interface HttpOptions {
userAgent?: string;
headers?: Record<string, string>;
}

export const defaultHttpOptions: HttpOptions = {
userAgent: `sub-rosa-tlock/0.1.0`,
};

function parseMediaType(contentType: string): { type: string; charset?: string } {
const parts = contentType.split(";").map((p) => p.trim().toLowerCase());
const type = parts[0];
const charset = parts.find((p) => p.startsWith("charset="))?.split("=")[1];
return { type, charset };
}

export function validateContentType(contentType: string | null): void {
if (contentType === null || contentType === undefined) {
throw new Error("Missing Content-Type header in Drand response");
}
const { type } = parseMediaType(contentType);
if (type !== JSON_CONTENT_TYPE) {
throw new Error(`Unexpected Content-Type: expected ${JSON_CONTENT_TYPE}, got ${type}`);
}
}

export interface ValidatingHttpOptions extends HttpOptions {
validateContentType?: (contentType: string | null) => void;
}

export class ValidatingHttpChainClient implements ChainClient {
public readonly options: ChainOptions;

constructor(
private readonly chainInstance: Chain,
options: ChainOptions = defaultChainOptions,
private readonly httpOptions: ValidatingHttpOptions = defaultHttpOptions,
) {
this.options = options;
}

async get(roundNumber: number): Promise<RandomnessBeacon> {
const url = this.withCachingParams(`${this.chainInstance.baseUrl}/public/${roundNumber}`);
return await this.jsonOrError(url);
}

async latest(): Promise<RandomnessBeacon> {
const url = this.withCachingParams(`${this.chainInstance.baseUrl}/public/latest`);
return await this.jsonOrError(url);
}

chain(): Chain {
return this.chainInstance;
}

private withCachingParams(url: string): string {
if (this.options.noCache) {
return `${url}?${Date.now()}`;
}
return url;
}

private async jsonOrError(url: string): Promise<RandomnessBeacon> {
const headers = { ...this.httpOptions.headers };
if (this.httpOptions.userAgent) {
headers["User-Agent"] = this.httpOptions.userAgent;
}

const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Error response fetching ${url} - got ${response.status}`);
}

const contentType = response.headers.get("content-type");
const validator = this.httpOptions.validateContentType ?? validateContentType;
validator(contentType);

return await response.json();
}
}

const QUICKNET_CHAIN_URL = "https://api.drand.sh/52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971";

export function createValidatingQuicknetClient(options?: ChainOptions): ChainClient {
const chain = new HttpCachingChain(QUICKNET_CHAIN_URL, options ?? defaultChainOptions);
return new ValidatingHttpChainClient(chain, options ?? defaultChainOptions);
}
7 changes: 7 additions & 0 deletions packages/tlock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ export {
type DrandClient,
} from "./quicknet.js";

export {
createValidatingQuicknetClient,
ValidatingHttpChainClient,
validateContentType,
type ValidatingHttpOptions,
} from "./http-client.js";

export { drandSignatureToSoroban, encodeG1Soroban } from "./bls.js";

export {
Expand Down
7 changes: 4 additions & 3 deletions packages/tlock/src/quicknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@

import {
fetchBeacon,
quicknetClient,
roundAt as drandRoundAt,
type ChainClient,
} from "drand-client";

import { drandSignatureToSoroban, verifyDrandSignature } from "./bls.js";
import { assertBeacon, assertChainInfo } from "./validate.js";
import { systemClock, type Clock } from "@sub-rosa/time";
import { createValidatingQuicknetClient } from "./http-client.js";

export const QUICKNET_HASH =
"52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971";
Expand Down Expand Up @@ -47,10 +48,10 @@ export function assertQuicknetFixture(info: {
}
}

export type DrandClient = ReturnType<typeof quicknetClient>;
export type DrandClient = ChainClient;

export function quicknet(): DrandClient {
return quicknetClient();
return createValidatingQuicknetClient();
}

export async function chainInfo(client: DrandClient) {
Expand Down
Loading
Loading