resolveAndValidate method

Future<List<InternetAddress>> resolveAndValidate(
  1. Uri uri
)

Resolves uri and returns only after every candidate address passes policy. A pinned socket transport must connect directly to one of these returned addresses instead of resolving the hostname again.

Implementation

Future<List<InternetAddress>> resolveAndValidate(Uri uri) async {
  // 1. Protocol validation
  final scheme = uri.scheme.toLowerCase();
  if (scheme != 'http' && scheme != 'https') {
    throw SecurityException(
      'Disallowed protocol: "$scheme". Only HTTP and HTTPS are permitted.',
    );
  }

  if (uri.userInfo.isNotEmpty || uri.hasFragment) {
    throw const SecurityException(
      'Target URL must not contain user info or a fragment.',
    );
  }
  final host = uri.host.trim().toLowerCase().replaceFirst(RegExp(r'\.$'), '');
  if (host.isEmpty) {
    throw const SecurityException('Target URL host is missing.');
  }

  // 2. Strict cloud metadata host check
  if (host == '169.254.169.254' ||
      host == 'metadata.google.internal' ||
      host.endsWith('.metadata.google.internal')) {
    throw SecurityException(
      'Access to cloud metadata endpoints is strictly blocked: $host',
    );
  }

  // 3. Hostname allowlist check
  if (allowedHosts.isNotEmpty && !allowedHosts.contains(host)) {
    throw SecurityException(
      'Host "$host" is not present in the allowed outbound host whitelist.',
    );
  }

  // 4. Resolve IP addresses and inspect against private ranges
  try {
    final literal = InternetAddress.tryParse(host);
    final addresses = literal == null ? await resolver(host) : [literal];
    if (addresses.isEmpty) {
      throw SecurityException('Unable to resolve host: $host');
    }

    for (final addr in addresses) {
      if (addr.isLoopback && !allowLocalhostInDev) {
        throw SecurityException(
          'Target resolves to a loopback address: ${addr.address}',
        );
      }

      if (addr.isLinkLocal) {
        throw SecurityException(
          'Target resolves to a link-local address: ${addr.address}',
        );
      }

      if (_isForbiddenAddress(addr) &&
          !(allowLocalhostInDev && addr.isLoopback)) {
        throw SecurityException(
          'Target resolves to a private network address: ${addr.address}',
        );
      }
    }
    return List.unmodifiable(addresses);
  } on SocketException {
    throw SecurityException('DNS resolution failed for "$host".');
  }
}