api-request-trust.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /**
  2. * Browser-trust fence for every /api request. Defends the two confused-deputy
  3. * paths a browser opens against a local HTTP API — DNS rebinding (Host names
  4. * the attacker's domain while the socket reaches this server) and cross-site
  5. * requests fired from a malicious page. The Host fence binds every request,
  6. * browser-looking or not: over plain HTTP a browser attaches neither Origin
  7. * nor Fetch-Metadata to reads (images and navigations — those
  8. * headers go only to trustworthy destinations), so an unmarked request may
  9. * still be a rebound browser read and Host is the one header rebinding cannot
  10. * forge. Non-browser and remote clients pass the same fence via loopback,
  11. * deployment-derived LAN IP literals, or a declared `trustedHosts` authority.
  12. * Network reachability and authentication stay out of scope: binding policy
  13. * belongs to the webserver config, and this fence is not an auth layer.
  14. */
  15. import { isLoopbackHostname } from './loopback-hostname.ts'
  16. import type { ConnectionTrustRequest } from './rpc.ts'
  17. function header(headers: ConnectionTrustRequest['headers'], name: string): string | undefined {
  18. if (headers instanceof Headers) return headers.get(name) ?? undefined
  19. const value = headers[name]
  20. return typeof value === 'string' ? value : undefined
  21. }
  22. /** Normalized URL of a Host-header authority (hostname lowercased, default port stripped, IPv6 bracketed), or undefined when unparsable. */
  23. function parseAuthority(authority: string): URL | undefined {
  24. try {
  25. // http: is a WHATWG "special scheme": parsing yields a non-empty hostname or throws.
  26. return new URL(`http://${authority}`)
  27. } catch {
  28. return undefined
  29. }
  30. }
  31. /**
  32. * Assert one configured `trustedHosts` entry is a bare authority (`host` or
  33. * `host:port`) in canonical form: it must survive WHATWG parsing unchanged
  34. * (case aside). Anything parsing would silently rewrite is refused as a typo
  35. * that must fail the load loudly instead of being ignored until requests 403
  36. * or quietly changing the grant: URL parts beyond the authority
  37. * (`harness.internal/path`, `user@harness.internal` — which would authorize
  38. * the embedded hostname), stripped whitespace, a dangling colon or
  39. * zero-padded port (which would broaden an intended exact-port grant to every
  40. * port), and non-canonical host spellings (`0x7f.0.0.1`, percent-encoding,
  41. * unbracketed IPv6; IDN hosts are declared in punycode, the form the wire
  42. * carries).
  43. * @param entry - the configured value, verbatim.
  44. */
  45. export function assertTrustedAuthority(entry: string): void {
  46. const entryUrl = parseAuthority(entry)
  47. if (entryUrl !== undefined && canonicalAuthority(entry, entryUrl) === entry.toLowerCase()) return
  48. throw new Error(`client-connection: trustedHosts entry ${JSON.stringify(entry)} is not a bare host[:port] authority`)
  49. }
  50. /**
  51. * Canonical form of a parsed authority: `hostname` when no port was written,
  52. * else `hostname:port`. The port is judged from URL parses under both special
  53. * schemes (their default ports differ, so `:80` and `:443` still count as
  54. * explicit), never from the raw string, where WHATWG trimming would misread
  55. * shapes like `host:port ` as port-less.
  56. */
  57. function canonicalAuthority(entry: string, entryUrl: URL): string {
  58. // An authority that parsed under http cannot fail under https.
  59. const port = entryUrl.port !== '' ? entryUrl.port : new URL(`https://${entry}`).port
  60. return port === '' ? entryUrl.hostname : `${entryUrl.hostname}:${port}`
  61. }
  62. /**
  63. * Whether the request authority matches a `trustedHosts` entry. An entry with
  64. * an explicit port matches that exact authority; a port-less entry matches the
  65. * hostname on any port (the shape the CLI derives for IP-literal LAN serving,
  66. * where the bound port may be OS-assigned). Both sides compare through WHATWG
  67. * normalization, so case and a redundant `:80` never decide trust.
  68. */
  69. function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): boolean {
  70. return trustedHosts.some((entry) => {
  71. const entryUrl = parseAuthority(entry)
  72. if (entryUrl === undefined) return false
  73. return canonicalAuthority(entry, entryUrl) === entryUrl.hostname
  74. ? entryUrl.hostname === hostUrl.hostname
  75. : entryUrl.host === hostUrl.host
  76. })
  77. }
  78. /**
  79. * Decide whether one /api request may reach the RPC bridge.
  80. * @param request - Node HTTP or Fetch request facts (headers).
  81. * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port.
  82. * @returns true when the Host is ours (loopback or trusted) and any attached browser markers are same-origin.
  83. */
  84. export function isTrustedApiRequest(request: ConnectionTrustRequest, trustedHosts: readonly string[]): boolean {
  85. // Host fence (DNS-rebinding defense), applied to every request: the browser
  86. // fills Host from the URL it believes it is talking to, so a rebound page
  87. // carries the attacker's domain here even though the socket lands on this
  88. // server. There is no marker shortcut — a browser read over plain HTTP
  89. // (images and navigations) arrives with neither Origin nor
  90. // Fetch-Metadata, indistinguishable from curl, and its response is readable
  91. // by the rebound page.
  92. const host = header(request.headers, 'host')
  93. if (host === undefined) return false
  94. const hostUrl = parseAuthority(host)
  95. if (hostUrl === undefined) return false
  96. if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false
  97. // Cross-site fence: modern browsers label the initiator relationship on
  98. // every fetch; an explicit cross-site marker is refused regardless of Origin.
  99. if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false
  100. // Origin fence: when a browser attaches an Origin it must be exactly this
  101. // authority (compared through the same normalization as the Host). Absent
  102. // Origin is fine — the Host fence above already bound the request. The
  103. // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused.
  104. const origin = header(request.headers, 'origin')
  105. if (origin === undefined) return true
  106. try {
  107. return new URL(origin).host === hostUrl.host
  108. } catch {
  109. return false
  110. }
  111. }