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
48 changes: 42 additions & 6 deletions src/integration/anchors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,20 @@ import { fetchStellarToml } from "./sep1Toml";
describe("getAnchorInfo", () => {
beforeEach(() => clearAnchorCache());

it("reuses cached anchor information for the same domain", async () => {
it("reuses cached anchor information for the same domain when verification is disabled", async () => {
const resolve = vi.spyOn(StellarToml.Resolver, "resolve").mockResolvedValue({
TRANSFER_SERVER: "https://anchor.example.com/sep6",
} as never);

const first = await getAnchorInfo("example.com", { verifyOnCacheHit: false });
const second = await getAnchorInfo("example.com", { verifyOnCacheHit: false });

expect(first.status).toBe("ok");
expect(second.status).toBe("ok");
expect(resolve).toHaveBeenCalledTimes(1);
});

it("by default, re-verifies a cache hit against a fresh resolve (#837)", async () => {
const resolve = vi.spyOn(StellarToml.Resolver, "resolve").mockResolvedValue({
TRANSFER_SERVER: "https://anchor.example.com/sep6",
} as never);
Expand All @@ -16,7 +29,30 @@ describe("getAnchorInfo", () => {

expect(first.status).toBe("ok");
expect(second.status).toBe("ok");
expect(resolve).toHaveBeenCalledTimes(1);
expect(resolve).toHaveBeenCalledTimes(2);
});

it("invalidates the cache and warns when re-verification reveals a changed SIGNING_KEY (#837)", async () => {
const resolve = vi
.spyOn(StellarToml.Resolver, "resolve")
.mockResolvedValueOnce({ SIGNING_KEY: "GOLDKEY00000000000000000000000000000000000000000000" } as never)
.mockResolvedValueOnce({ SIGNING_KEY: "GATTACKER0000000000000000000000000000000000000000000" } as never);
const warn = vi.fn();

const first = await getAnchorInfo("example.com");
if (first.status === "ok") expect(first.data.SIGNING_KEY).toContain("GOLDKEY");

const second = await getAnchorInfo("example.com", {
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() },
});

expect(resolve).toHaveBeenCalledTimes(2);
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("diverged"),
expect.objectContaining({ domain: "example.com" }),
);
expect(second.status).toBe("ok");
if (second.status === "ok") expect(second.data.SIGNING_KEY).toContain("GATTACKER");
});

it("fetches anchor information again after the configured TTL expires", async () => {
Expand All @@ -41,9 +77,9 @@ describe("getAnchorInfo", () => {
TRANSFER_SERVER: "https://anchor.example.com/sep6",
} as never);

await getAnchorInfo("example.com");
await getAnchorInfo("example.com", { verifyOnCacheHit: false });
clearAnchorCache();
await getAnchorInfo("example.com");
await getAnchorInfo("example.com", { verifyOnCacheHit: false });

expect(resolve).toHaveBeenCalledTimes(2);
});
Expand All @@ -54,8 +90,8 @@ describe("getAnchorInfo", () => {
} as never);
const fetcher = vi.fn();

await getAnchorInfo("example.com");
const result = await fetchStellarToml("example.com", { fetch: fetcher });
await getAnchorInfo("example.com", { verifyOnCacheHit: false });
const result = await fetchStellarToml("example.com", { fetch: fetcher, verifyOnCacheHit: false });

expect(result.status).toBe("ok");
if (result.status === "ok") {
Expand Down
46 changes: 44 additions & 2 deletions src/integration/anchors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import {
cacheStellarToml,
clearStellarTomlCache,
getCachedStellarToml,
detectStellarTomlConflict,
DEFAULT_STELLAR_TOML_CACHE_TTL_MS,
} from "./sep1Toml";
import type { StellarToml as StellarTomlData } from "./sep1Toml";
import type { SorokitLogger } from "../shared/logger";

export interface AnchorAsset {
code: string;
Expand Down Expand Up @@ -63,8 +65,23 @@ function asUrl(value: string): URL | null {
export interface GetAnchorInfoOptions {
ttlMs?: number;
timeoutMs?: number;
/** See FetchStellarTomlOptions.verifyOnCacheHit in ./sep1Toml (#837). Defaults to true. */
verifyOnCacheHit?: boolean;
/** Logger for conflict warnings when verifyOnCacheHit detects a divergence. */
logger?: SorokitLogger;
}

async function resolveAnchorToml(homeDomain: string, timeoutMs: number): Promise<StellarTomlData> {
return StellarToml.Resolver.resolve(homeDomain, { timeout: timeoutMs }) as Promise<StellarTomlData>;
}

const NOOP_LOGGER: SorokitLogger = {
debug: () => undefined,
info: () => undefined,
warn: () => undefined,
error: () => undefined,
};

export async function getAnchorInfo(
homeDomain: string,
options: GetAnchorInfoOptions = {},
Expand All @@ -79,10 +96,35 @@ export async function getAnchorInfo(
}

const cached = getCachedStellarToml(homeDomain);
if (cached) return ok(cached);
if (cached) {
const verifyOnCacheHit = options.verifyOnCacheHit ?? true;
if (!verifyOnCacheHit) return ok(cached);

// #837: re-verify against a fresh resolve before trusting the cache,
// the same protection fetchStellarToml applies to its own cache.
let fresh: StellarTomlData;
try {
fresh = await resolveAnchorToml(homeDomain, timeoutMs);
} catch {
// Re-verification itself failed — serve the (unproven-stale) cache
// rather than failing the call outright.
return ok(cached);
}

const conflict = detectStellarTomlConflict(cached, fresh);
if (conflict) {
(options.logger ?? NOOP_LOGGER).warn(
`Anchor stellar.toml for "${homeDomain}" diverged from cached data: ${conflict}. Invalidating cache.`,
{ domain: homeDomain, conflict },
);
clearStellarTomlCache(homeDomain);
}
cacheStellarToml(homeDomain, fresh, ttlMs);
return ok(fresh);
}

try {
const data = await StellarToml.Resolver.resolve(homeDomain, { timeout: timeoutMs }) as StellarTomlData;
const data = await resolveAnchorToml(homeDomain, timeoutMs);
cacheStellarToml(homeDomain, data, ttlMs);
return ok(data);
} catch (cause) {
Expand Down
78 changes: 76 additions & 2 deletions src/integration/sep1Toml.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,90 @@ describe("fetchStellarToml", () => {
if (result.status === "error") expect(result.error.code).toBe("INVALID_CONFIG");
});

it("caches successful results for the configured TTL", async () => {
it("caches successful results for the configured TTL, used as a fallback if verification is unavailable", async () => {
const fetcher = vi.fn().mockResolvedValue(new Response('AUTH_SERVER = "https://auth.example.com"'));
const options = { fetch: fetcher, ttlMs: 60_000 };
const options = { fetch: fetcher, ttlMs: 60_000, verifyOnCacheHit: false };

await fetchStellarToml("https://example.com", options);
await fetchStellarToml("example.com", options);

// With verification explicitly disabled, a cache hit is trusted
// immediately without a second network call.
expect(fetcher).toHaveBeenCalledTimes(1);
});

it("by default, re-verifies a cache hit against a fresh fetch (#837)", async () => {
const fetcher = vi.fn().mockResolvedValue(new Response('AUTH_SERVER = "https://auth.example.com"'));
const options = { fetch: fetcher, ttlMs: 60_000 };

await fetchStellarToml("https://example.com", options);
const second = await fetchStellarToml("example.com", options);

// Verification happens on every cache hit by default — the fresh data
// agrees with the cached data, so the result is still served correctly.
expect(fetcher).toHaveBeenCalledTimes(2);
expect(second.status).toBe("ok");
if (second.status === "ok") {
expect(second.data.auth_server).toBe("https://auth.example.com");
}
});

it("invalidates the cache and warns when a re-verification fetch reveals a changed SIGNING_KEY (#837)", async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce(new Response('SIGNING_KEY = "GOLDKEY00000000000000000000000000000000000000000000"'))
.mockResolvedValueOnce(new Response('SIGNING_KEY = "GATTACKER0000000000000000000000000000000000000000000"'));
const warn = vi.fn();
const options = {
fetch: fetcher,
ttlMs: 60_000,
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() },
};

const first = await fetchStellarToml("example.com", options);
expect(first.status).toBe("ok");
if (first.status === "ok") expect(first.data.SIGNING_KEY).toContain("GOLDKEY");

const second = await fetchStellarToml("example.com", options);

expect(fetcher).toHaveBeenCalledTimes(2);
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("diverged"),
expect.objectContaining({ domain: "example.com" }),
);
expect(second.status).toBe("ok");
if (second.status === "ok") {
// Returns the fresh (correct) data, not the stale cached one.
expect(second.data.SIGNING_KEY).toContain("GATTACKER");
}

// A third call must see the (now updated) cache agree with another
// fresh fetch and must not warn again.
const thirdFetcher = vi.fn().mockResolvedValue(
new Response('SIGNING_KEY = "GATTACKER0000000000000000000000000000000000000000000"'),
);
const third = await fetchStellarToml("example.com", { ...options, fetch: thirdFetcher });
expect(third.status).toBe("ok");
expect(warn).toHaveBeenCalledTimes(1);
});

it("falls back to the cached value when the re-verification fetch itself fails", async () => {
const fetcher = vi
.fn()
.mockResolvedValueOnce(new Response('AUTH_SERVER = "https://auth.example.com"'))
.mockRejectedValueOnce(new Error("network blip"));
const options = { fetch: fetcher, ttlMs: 60_000 };

const first = await fetchStellarToml("example.com", options);
expect(first.status).toBe("ok");

const second = await fetchStellarToml("example.com", options);
expect(second.status).toBe("ok");
if (second.status === "ok") {
expect(second.data.auth_server).toBe("https://auth.example.com");
}
});

it("fetches again after the configured TTL expires", async () => {
vi.useFakeTimers();
try {
Expand Down
Loading
Loading