~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
177 lines · 7.7 KB Raw History
import { assert, assertEquals, assertRejects } from "@std/assert";
import { addressPrivate, Identity, IdentityError, normalizeHost } from "../hono-backend/identity.ts";

const PLC = "https://plc.test.example";

async function dpopPair() {
  const kp = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
  return {
    pub: await crypto.subtle.exportKey("jwk", kp.publicKey) as Record<string, string>,
    priv: await crypto.subtle.exportKey("jwk", kp.privateKey) as Record<string, string>,
  };
}

interface Harness {
  identity: Identity;
  fetched: string[];
  resolved: string[];
  restore: () => void;
}

function harness(dns: Record<string, string[]>, docs: Record<string, unknown> = {}, networkOrigins: string[] = []): Harness {
  const fetched: string[] = [];
  const resolved: string[] = [];
  const original = globalThis.fetch;
  globalThis.fetch = ((input: string | URL | Request) => {
    const url = String(input instanceof Request ? input.url : input);
    fetched.push(url);
    const doc = docs[url];
    return Promise.resolve(doc ? Response.json(doc) : new Response("{}", { status: 404 }));
  }) as typeof fetch;
  const identity = new Identity({
    plcUrl: PLC,
    networkOrigins,
    insecureLoopback: false,
    resolveHost: (host) => {
      resolved.push(host);
      return Promise.resolve(dns[host] ?? []);
    },
  });
  return { identity, fetched, resolved, restore: () => (globalThis.fetch = original) };
}

async function session(userDid: string, pds: string) {
  const { pub, priv } = await dpopPair();
  return { userDid, pds, accessJwt: "t", dpopPublicJwk: pub, dpopPrivateJwk: priv };
}

Deno.test("host names: trailing dot stripped, single labels, localhost and IP literals refused", () => {
  assertEquals(normalizeHost("PDS.Example.COM."), "pds.example.com");
  assertEquals(normalizeHost("intranet"), null);
  assertEquals(normalizeHost("localhost"), null);
  assertEquals(normalizeHost("a.localhost"), null);
  assertEquals(normalizeHost("127.0.0.1"), null);
  assertEquals(normalizeHost("10.0.0.1."), null);
  assertEquals(normalizeHost("[::1]"), null);
  assertEquals(normalizeHost("box.internal"), null);
});

Deno.test("private and reserved addresses are recognised", () => {
  for (const ip of ["10.1.2.3", "127.0.0.1", "169.254.169.254", "172.16.0.1", "192.168.1.1", "100.64.0.1", "0.0.0.0", "224.0.0.1",
    "::1", "::", "fc00::1", "fd12::1", "fe80::1", "::ffff:10.0.0.1", "::ffff:127.0.0.1", "64:ff9b::a00:1", "2001:db8::1"]) {
    assert(addressPrivate(ip), ip);
  }
  for (const ip of ["93.184.216.34", "1.1.1.1", "2606:4700:4700::1111", "::ffff:8.8.8.8"]) assert(!addressPrivate(ip), ip);
});

Deno.test("did:web user DIDs that name or resolve to private hosts are refused before any fetch", async () => {
  const h = harness({ "evil.example": ["10.0.0.5"], "mixed.example": ["93.184.216.34", "127.0.0.1"], "v6.example": ["fd00::1"] });
  try {
    for (const did of ["did:web:evil.example", "did:web:mixed.example", "did:web:v6.example", "did:web:localhost", "did:web:intranet",
      "did:web:127.0.0.1", "did:web:nothing.example"]) {
      const s = await session(did, "https://x.example");
      await assertRejects(() => h.identity.verifySession(s), IdentityError, undefined, did);
    }
    assertEquals(h.fetched, []);
  } finally {
    h.restore();
  }
});

Deno.test("a PDS endpoint on a private, http, odd-port or IP-literal host is refused before it is fetched", async () => {
  const did = "did:plc:abcdefghijklmnopqrstuvwx";
  for (const endpoint of ["https://10.0.0.1", "http://pds.example.com", "https://pds.example.com:8443", "https://inner.example", "https://localhost"]) {
    const h = harness({ "inner.example": ["192.168.0.10"], "pds.example.com": ["93.184.216.34"] }, {
      [`${PLC}/${did}`]: { id: did, service: [{ id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: endpoint }] },
    });
    try {
      const s = await session(did, endpoint);
      await assertRejects(() => h.identity.verifySession(s), IdentityError, undefined, endpoint);
      assertEquals(h.fetched, [`${PLC}/${did}`], endpoint);
    } finally {
      h.restore();
    }
  }
});

Deno.test("failed host lookups are cached so a bad DID does not cost a resolution per request", async () => {
  const h = harness({ "evil.example": ["10.0.0.5"] });
  try {
    const s = await session("did:web:evil.example", "https://x.example");
    for (let i = 0; i < 3; i++) {
      await assertRejects(() => h.identity.verifySession(s), IdentityError, "private address");
    }
    assertEquals(h.resolved, ["evil.example"]);
  } finally {
    h.restore();
  }
});

Deno.test("service auth issuers other than did:key are refused without any network", async () => {
  const h = harness({});
  try {
    const head = btoa(JSON.stringify({ alg: "ES256K" })).replace(/=+$/, "");
    const now = Math.floor(Date.now() / 1000);
    for (const iss of ["did:plc:abcdefghijklmnopqrstuvwx", "did:web:attacker.example"]) {
      const body = btoa(JSON.stringify({ iss, aud: "did:web:qr.fedfork.com", lxm: "x", exp: now + 60, iat: now, jti: "abcdefghij" }))
        .replace(/=+$/, "");
      await assertRejects(
        () => h.identity.verifyServiceAuth(`${head}.${body}.AAAA`, { aud: "did:web:qr.fedfork.com", lxm: "x", maxLifetimeS: 120, skewS: 30 }, now),
        IdentityError,
      );
    }
    assertEquals(h.fetched, []);
    assertEquals(h.resolved, []);
  } finally {
    h.restore();
  }
});

Deno.test("a network origin is fetched without a public-address check; the session is verified at that PDS", async () => {
  const did = "did:plc:abcdefghijklmnopqrstuvwx";
  const pds = "https://pds-bob.stg.test";
  const h = harness({ "pds-bob.stg.test": ["10.44.0.1"] }, {
    [`${PLC}/${did}`]: { id: did, service: [{ id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: pds }] },
    [`${pds}/xrpc/com.atproto.server.getSession`]: { did, handle: "bob.test" },
  }, [pds]);
  try {
    assertEquals(await h.identity.verifySession(await session(did, pds)), { did, handle: "bob.test" });
    assertEquals(h.fetched, [`${PLC}/${did}`, `${pds}/xrpc/com.atproto.server.getSession`]);
    assertEquals(h.resolved, []);
  } finally {
    h.restore();
  }
});

Deno.test("with a network origin set, every other private, http, odd-port or sibling host is still refused", async () => {
  const did = "did:plc:abcdefghijklmnopqrstuvwx";
  const network = "https://pds-bob.stg.test";
  for (const endpoint of ["https://pds-alice.stg.test", "http://pds-bob.stg.test", "https://pds-bob.stg.test:8443", "https://x.pds-bob.stg.test",
    "https://10.44.0.1", "https://inner.example"]) {
    const h = harness({ "pds-alice.stg.test": ["10.44.0.1"], "x.pds-bob.stg.test": ["10.44.0.1"], "inner.example": ["192.168.0.10"] }, {
      [`${PLC}/${did}`]: { id: did, service: [{ id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: endpoint }] },
    }, [network]);
    try {
      const s = await session(did, endpoint);
      await assertRejects(() => h.identity.verifySession(s), IdentityError, undefined, endpoint);
      assertEquals(h.fetched, [`${PLC}/${did}`], endpoint);
    } finally {
      h.restore();
    }
  }
});

Deno.test("no network origin set: a PDS that resolves privately is refused, as before", async () => {
  const did = "did:plc:abcdefghijklmnopqrstuvwx";
  const pds = "https://pds-bob.stg.test";
  const h = harness({ "pds-bob.stg.test": ["10.44.0.1"] }, {
    [`${PLC}/${did}`]: { id: did, service: [{ id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: pds }] },
  });
  try {
    const s = await session(did, pds);
    await assertRejects(() => h.identity.verifySession(s), IdentityError, "private address");
    assertEquals(h.fetched, [`${PLC}/${did}`]);
  } finally {
    h.restore();
  }
});