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
37 changes: 37 additions & 0 deletions src/__tests__/configManager.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import { ConfigManager, deepMerge } from "../configManager.js";
import { CsrfProtection } from "../csrf.js";

describe("ConfigManager", () => {
it("deep merges", () => {
Expand All @@ -23,3 +24,39 @@ describe("ConfigManager", () => {
expect(m.get()).toEqual({ rpcUrl: "x" });
});
});

describe("CsrfProtection", () => {
it("issues secure tokens and validates them strictly", () => {
const csrf = new CsrfProtection();
const token = csrf.issueToken();
expect(token.length).toBeGreaterThanOrEqual(32);
expect(csrf.validateToken(token)).toBe(true);
expect(csrf.validateToken("bogus")).toBe(false);
expect(csrf.validateToken(undefined)).toBe(false);
});

it("rejects reused tokens after consumption", () => {
const csrf = new CsrfProtection();
const token = csrf.issueToken();
expect(csrf.validateToken(token, { consume: true })).toBe(true);
expect(csrf.validateToken(token)).toBe(false);
});

it("refreshes tokens and tracks state", () => {
const csrf = new CsrfProtection();
const first = csrf.issueToken();
const refreshed = csrf.refreshToken(first);
expect(refreshed).not.toBe(first);
expect(csrf.validateToken(refreshed)).toBe(true);
expect(csrf.validateToken(first)).toBe(false);
expect(csrf.getStats().issued).toBe(2);
});

it("protects state-changing requests only", () => {
const csrf = new CsrfProtection();
const token = csrf.issueToken();
expect(csrf.protectRequest("GET", {})).toBe(true);
expect(csrf.protectRequest("POST", {})).toBe(false);
expect(csrf.protectRequest("POST", { "x-csrf-token": token })).toBe(true);
});
});
105 changes: 105 additions & 0 deletions src/__tests__/secretsManager.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { SecretsManager, SecretVersion, RotationPolicy } from '../secrets';

describe('SecretsManager', () => {
let manager: SecretsManager;

beforeEach(() => {
manager = new SecretsManager({ encryptionKey: 'test-encryption-key-32-bytes-long!' });
});

describe('storage', () => {
it('stores and retrieves a secret value', () => {
manager.set('api-key', 'super-secret-value');
expect(manager.get('api-key')).toBe('super-secret-value');
});

it('does not expose plaintext in the stored record', () => {
manager.set('api-key', 'super-secret-value');
const record = manager.describe('api-key');
expect(record).toBeDefined();
expect(JSON.stringify(record)).not.toContain('super-secret-value');
});

it('throws when retrieving an unknown secret', () => {
expect(() => manager.get('missing')).toThrow();
});

it('deletes a secret', () => {
manager.set('api-key', 'value');
manager.delete('api-key');
expect(manager.has('api-key')).toBe(false);
});
});

describe('versioning', () => {
it('creates a new version on each set', () => {
manager.set('api-key', 'v1');
manager.set('api-key', 'v2');
const versions = manager.listVersions('api-key');
expect(versions).toHaveLength(2);
expect(versions[0].version).toBe(1);
expect(versions[1].version).toBe(2);
});

it('retrieves a specific version', () => {
manager.set('api-key', 'v1');
manager.set('api-key', 'v2');
expect(manager.get('api-key', 1)).toBe('v1');
expect(manager.get('api-key', 2)).toBe('v2');
});

it('returns the current version by default', () => {
manager.set('api-key', 'v1');
manager.set('api-key', 'v2');
expect(manager.get('api-key')).toBe('v2');
expect(manager.currentVersion('api-key')).toBe(2);
});

it('keeps version history immutable', () => {
manager.set('api-key', 'v1');
manager.set('api-key', 'v2');
const versions: SecretVersion[] = manager.listVersions('api-key');
expect(versions[0].value).toBe('v1');
expect(versions[0].version).toBe(1);
});
});

describe('rotation', () => {
it('rotates a secret producing a new version', () => {
manager.set('api-key', 'v1');
const rotated = manager.rotate('api-key', () => 'v2-rotated');
expect(rotated.version).toBe(2);
expect(manager.get('api-key')).toBe('v2-rotated');
});

it('applies a rotation policy based on age', () => {
const policy: RotationPolicy = { maxAgeMs: 1000 };
manager.set('api-key', 'v1', { policy });
const due = manager.isRotationDue('api-key', Date.now() + 2000);
expect(due).toBe(true);
});

it('reports not due when within policy window', () => {
const policy: RotationPolicy = { maxAgeMs: 100000 };
manager.set('api-key', 'v1', { policy });
expect(manager.isRotationDue('api-key')).toBe(false);
});
});

describe('tracking', () => {
it('tracks metadata for each secret', () => {
manager.set('api-key', 'v1');
const record = manager.describe('api-key');
expect(record.name).toBe('api-key');
expect(record.currentVersion).toBe(1);
expect(record.createdAt).toBeInstanceOf(Date);
expect(record.updatedAt).toBeInstanceOf(Date);
});

it('lists all tracked secret names', () => {
manager.set('a', '1');
manager.set('b', '2');
expect(manager.list().sort()).toEqual(['a', 'b']);
});
});
});
146 changes: 146 additions & 0 deletions src/__tests__/validation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import {
validate,
string,
number,
address,
amount,
enumOf,
object,
array,
allOf,
optional,
registerRule,
getValidationStats,
resetValidationStats,
ValidationError,
} from "../validation";

describe("SDK input validation framework", () => {
beforeEach(() => {
resetValidationStats();
});

describe("built-in validators", () => {
it("validates strings with constraints", () => {
const v = string({ minLength: 2, maxLength: 4 });
expect(validate(v, "abc").ok).toBe(true);
expect(validate(v, "a").ok).toBe(false);
expect(validate(v, "abcde").ok).toBe(false);
expect(validate(v, 123).ok).toBe(false);
});

it("validates numbers with bounds", () => {
const v = number({ min: 0, max: 10, integer: true });
expect(validate(v, 5).ok).toBe(true);
expect(validate(v, 5.5).ok).toBe(false);
expect(validate(v, -1).ok).toBe(false);
expect(validate(v, 11).ok).toBe(false);
expect(validate(v, "5").ok).toBe(false);
});

it("validates addresses", () => {
const v = address();
expect(validate(v, "0x1234567890abcdef1234567890abcdef12345678").ok).toBe(
true
);
expect(validate(v, "0x1234").ok).toBe(false);
expect(validate(v, "not-an-address").ok).toBe(false);
});

it("validates amounts", () => {
const v = amount({ min: 0, max: 1000 });
expect(validate(v, 100).ok).toBe(true);
expect(validate(v, -5).ok).toBe(false);
expect(validate(v, 5000).ok).toBe(false);
expect(validate(v, NaN).ok).toBe(false);
});

it("validates enums", () => {
const v = enumOf(["a", "b", "c"] as const);
expect(validate(v, "a").ok).toBe(true);
expect(validate(v, "z").ok).toBe(false);
});
});

describe("composition", () => {
it("validates objects safely", () => {
const v = object({
name: string({ minLength: 1 }),
age: number({ min: 0 }),
});
expect(validate(v, { name: "alice", age: 30 }).ok).toBe(true);
expect(validate(v, { name: "", age: 30 }).ok).toBe(false);
expect(validate(v, { name: "alice" }).ok).toBe(false);
expect(validate(v, null).ok).toBe(false);
});

it("validates arrays", () => {
const v = array(number({ min: 0 }), { minItems: 1, maxItems: 3 });
expect(validate(v, [1, 2]).ok).toBe(true);
expect(validate(v, []).ok).toBe(false);
expect(validate(v, [1, 2, 3, 4]).ok).toBe(false);
expect(validate(v, [1, -1]).ok).toBe(false);
});

it("supports allOf composition", () => {
const v = allOf(string({ minLength: 3 }), string({ maxLength: 5 }));
expect(validate(v, "abcd").ok).toBe(true);
expect(validate(v, "ab").ok).toBe(false);
expect(validate(v, "abcdef").ok).toBe(false);
});

it("supports optional composition", () => {
const v = optional(string({ minLength: 1 }));
expect(validate(v, undefined).ok).toBe(true);
expect(validate(v, "x").ok).toBe(true);
expect(validate(v, "").ok).toBe(false);
});
});

describe("custom rules", () => {
it("registers and applies custom rules", () => {
registerRule("even", (value: unknown) =>
typeof value === "number" && value % 2 === 0
? null
: "must be even"
);
const v = number({ rules: ["even"] });
expect(validate(v, 4).ok).toBe(true);
const result = validate(v, 3);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.errors[0].message).toBe("must be even");
}
});
});

describe("tracking", () => {
it("tracks validation counts", () => {
const v = string({ minLength: 1 });
validate(v, "ok");
validate(v, "");
const stats = getValidationStats();
expect(stats.total).toBe(2);
expect(stats.passed).toBe(1);
expect(stats.failed).toBe(1);
});
});

describe("injection prevention", () => {
it("rejects prototype pollution keys", () => {
const v = object({ name: string() });
const payload = JSON.parse('{"__proto__": {"polluted": true}}');
const result = validate(v, payload);
expect(result.ok).toBe(false);
expect(({} as Record<string, unknown>).polluted).toBeUndefined();
});

it("throws ValidationError on assert", () => {
const v = string({ minLength: 1 });
expect(() => {
const r = validate(v, "");
if (!r.ok) throw new ValidationError(r.errors);
}).toThrow(ValidationError);
});
});
});
Loading