Support the HTTPRequest ProxyConditionRecordType and checks for special effective agent ids
187082
def set_http_request(self, http_request):
        """"""
        self._http_request = http_request
        if 'HTTP_LTI_USER_ID' in http_request.META:
            try:
                authority = http_request.META['HTTP_LTI_TOOL_CONSUMER_INSTANCE_GUID']
            except (AttributeError, KeyError):
                authority = 'unknown_lti_consumer_instance'
            self.set_effective_agent_id(Id(
                authority=authority,
                namespace='agent.Agent',
                identifier=http_request.META['HTTP_LTI_USER_ID']))
403630
function(proxies, namespace, serverType, proxy) {
  proxies[namespace] = proxies[namespace] || {};
  if (proxies[namespace][serverType]) {
    for (let attr in proxy) {
      proxies[namespace][serverType][attr] = proxy[attr];
    }
  } else {
    proxies[namespace][serverType] = proxy;
  }
}
365558
function(agent, id, type, pid, info, socket) {
  let record = {
    id: id,
    type: type,
    pid: pid,
    info: info,
    socket: socket
  };
  if (type === 'client') {
    agent.clients[id] = record;
  } else {
    if (!agent.idMap[id]) {
      agent.idMap[id] = record;
      let list = agent.typeMap[type] = agent.typeMap[type] || [];
      list.push(record);
    } else {
      let slaves = agent.slaveMap[id] = agent.slaveMap[id] || [];
      slaves.push(record);
    }
  }
  return record;
}
865484
private ProxyLogicHandler getProxyHandler(final IoSession session) {
        ProxyLogicHandler handler = ((ProxyIoSession) session
                .getAttribute(ProxyIoSession.PROXY_SESSION)).getHandler();

        if (handler == null) {
            throw new IllegalStateException();
        }

        // Sanity check
        if (handler.getProxyIoSession().getProxyFilter() != this) {
            throw new IllegalArgumentException("Not managed by this filter.");
        }

        return handler;
    }
1350189
private void executeProxyRequest(HttpMethod httpMethodProxyRequest,
                                     HttpServletRequest httpServletRequest,
                                     HttpServletResponse httpServletResponse, History history) {
        try {
            RequestInformation requestInfo = requestInformation.get();

            // Execute the request

            // set virtual host so the server knows how to direct the request
            // If the host header exists then this uses that value
            // Otherwise the hostname from the URL is used
            processVirtualHostName(httpMethodProxyRequest, httpServletRequest);
            cullDisabledPaths();

            // check for existence of ODO_PROXY_HEADER
            // finding it indicates a bad loop back through the proxy
            if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {
                logger.error("Request has looped back into the proxy.  This will not be executed: {}", httpServletRequest.getRequestURL());
                return;
            }

            // set ODO_PROXY_HEADER
            httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, "proxied");

            requestInfo.blockRequest = hasRequestBlock();
            PluginResponse responseWrapper = new PluginResponse(httpServletResponse);
            requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);

            if (!requestInfo.blockRequest) {
                logger.info("Sending request to server");

                history.setModified(requestInfo.modified);
                history.setRequestSent(true);

                executeRequest(httpMethodProxyRequest,
                               httpServletRequest,
                               responseWrapper,
                               history);
            } else {
                history.setRequestSent(false);
            }

            logOriginalResponseHistory(responseWrapper, history);
            applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);
            // store history
            history.setModified(requestInfo.modified);
            logRequestHistory(httpMethodProxyRequest, responseWrapper, history);

            writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
604856
function (id, request, protocolProfileBehavior, callback) {
        var self = this,
            cookieJar,
            requestOptions,
            networkOptions = self.options.network || {},
            startTime = Date.now(),
            startTimer = now(), // high-resolution time
            hostname,

            complete = function (error, response, cookies, history) {
                self.emit(id, error, self.trace.cursor, self.trace, response, request, cookies, history);

                return callback(error, response, request, cookies, history);
            };

        // at this point the request could have come from collection, auth or sandbox
        // we can't trust the integrity of this request
        // bail out if request url is empty
        if (!(request && request.url && request.url.toString && request.url.toString())) {
            return complete(new Error('runtime:extenstions~request: request url is empty'));
        }

        cookieJar = self.options.cookieJar;
        requestOptions = core.getRequestOptions(request, self.options, protocolProfileBehavior);
        hostname = request.url.getHost();

        // check if host is on the `restrictedAddresses`
        if (networkOptions.restrictedAddresses && core.isAddressRestricted(hostname, networkOptions)) {
            return complete(new Error(ERROR_RESTRICTED_ADDRESS + hostname));
        }

        return requests(request, requestOptions, function (err, res, resBody, debug) {
            if (err) {
                // bubble up http errors
                // @todo - Should we send an empty sdk Response here?
                return complete(err);
            }

            var responseString,
                responseTime,
                responseJSON,
                keepAlive,
                response,
                cookies,
                header,
                history = {
                    execution: {
                        verbose: Boolean(requestOptions.verbose),
                        sessions: requestOptions.verbose ? {} : undefined,
                        data: []
                    }
                };

            // holds the response as a string
            // eslint-disable-next-line lodash/prefer-is-nil
            responseString = ((resBody !== null && resBody !== undefined) && resBody.toString) ?
                resBody.toString() : resBody;
            if (responseString === '[object ArrayBuffer]') {
                responseString = core.arrayBufferToString(resBody);
            }

            // This helps us to unify the information from XHR or Node calls.
            responseJSON = core.jsonifyResponse(res, requestOptions, responseString);

            // Pull out cookies from the cookie jar, and make them chrome compatible.
            cookies = (cookieJar && _.isFunction(cookieJar.getCookies)) ?
                _.transform(cookieJar.getCookies(requestOptions.url), function (acc, cookie) {
                    acc.push(toChromeCookie(cookie));
                }, []) : [];

            // Calculate the time taken for us to get the response.
            responseTime = Date.now() - startTime;

            if (res && res.timings) {
                // update response time to actual response end time
                // of the final request in the redirect chain.
                responseTime = Math.ceil(res.timings.end);
            }

            // prepare history from request debug data
            if (Array.isArray(debug)) {
                debug.forEach(function (debugData) {
                    // cache connection sessions, to be referred later
                    if (debugData.session && !debugData.session.reused) {
                        history.execution.sessions[debugData.session.id] = debugData.session.data;
                    }

                    history.execution.data.push({
                        request: debugData.request,
                        response: debugData.response,
                        timings: debugData.timings && {
                            // runtime start time
                            start: startTime,
                            // request start time
                            requestStart: debugData.timingStart,
                            // offsets calculated are relative to runtime start time
                            offset: calcTimingsOffset(startTimer, debugData.timingStartTimer, debugData.timings)
                        },
                        session: debugData.session && {
                            id: debugData.session.id,
                            // is connection socket reused
                            reused: debugData.session.reused
                        }
                    });
                });
            }

            // Response in the SDK format
            response = new sdk.Response({ // @todo get rid of jsonifyResponse
                code: responseJSON.statusCode,
                status: res && res.statusMessage,
                header: _.transform(responseJSON.headers, transformMultiValueHeaders, []),
                stream: resBody,
                responseTime: responseTime
            });

            // Insert the missing sent headers in the request object, so that they get bubbled up into the UI
            _.forOwn(responseJSON.request && responseJSON.request.headers, function (value, key) {
                header = request.headers.one(key);

                // neither request nor runtime overwrites user-defined headers
                // so instead of upsert, just add missing headers to the list
                // with system: true flag.
                if (!header) {
                    request.headers.add({key: key, value: value, system: true});

                    return;
                }

                // update headers which gets overwritten by the requester
                if (OVERWRITTEN_HEADERS[key.toLowerCase()] && value !== header.value) {
                    header.update({key: key, value: value, system: true});
                }
            });

            keepAlive = _.get(requestOptions, 'agentOptions.keepAlive');

            // @note Connection header is added by Node based on the agent's
            // keepAlive option. Don't add if custom is defined already.
            if (!request.headers.has(CONNECTION_HEADER.key)) {
                request.headers.add({
                    key: CONNECTION_HEADER.key,
                    value: keepAlive ? CONNECTION_HEADER.keepAlive : CONNECTION_HEADER.close,
                    system: true
                });
            }

            complete(null, response, cookies, history);
        });
    }
135445
function getAgentByUrl (requestUrl) {
  if (!requestUrl) {
    return null;
  }
  var parsedRequestUrl = url.parse(requestUrl);
  var proxyUrl = getSystemProxyByUrl(parsedRequestUrl);
  if (!proxyUrl) {
    log.debug('No system proxy');
    return null;
  }

  log.debug('Detect system proxy Url: ' + proxyUrl);
  var parsedProxyUrl = url.parse(proxyUrl);
  var tunnelOptions = getTunnelOptionsByProxy(parsedProxyUrl, parsedRequestUrl);
  if (tunnelOptions) {
    var tunnelFnName = getTunnelFnName(parsedProxyUrl, parsedRequestUrl);
    log.debug('Tunnel name is ' + tunnelFnName);
    return tunnel[tunnelFnName](tunnelOptions);
  }
}
1175897
private static InetSocketAddress overrideProxy(String proxyHostPort) {
    if (proxyHostPort == null) {
      return null;
    }

    String[] parts = proxyHostPort.split(":", 2);
    int port = 80;
    if (parts.length > 1) {
      port = Integer.parseInt(parts[1]);
    }
    log.warning(
        "Detected GRPC_PROXY_EXP and will honor it, but this feature will "
            + "be removed in a future release. Use the JVM flags "
            + "\"-Dhttps.proxyHost=HOST -Dhttps.proxyPort=PORT\" to set the https proxy for "
            + "this JVM.");
    return new InetSocketAddress(parts[0], port);
  }
1311016
function proxy() {
  const defaultProxy = {
    changeOrigin: true,
    ws: true,
    logLevel: 'info',
    xfwd: true,
    logProvider() {
      return {
        log(...args) {
          Logger.log(proxyLogRewrite(args));
        },
        debug(...args) {
          Logger.debug(proxyLogRewrite(args));
        },
        info(...args) {
          Logger.info(proxyLogRewrite(args));
        },
        warn(...args) {
          Logger.warn(proxyLogRewrite(args));
        },
        error(...args) {
          Logger.error(proxyLogRewrite(args));
        }
      };
    }
  };

  const { proxies } = settings.configuration;

  if (!proxies) {
    return null;
  }

  const config = [];

  // Iterate through each proxy configuration
  proxies.forEach(proxyConfiguration => {
    // Merge in defaults including custom Logger and custom request/response function
    const proxyConfig = merge({}, defaultProxy, proxyConfiguration, {
      onProxyReq: (proxyReq, req) => {
        onRequest(proxyConfiguration, proxyReq, req);
        if (typeof proxyConfiguration.onProxyReq === 'function') {
          proxyConfiguration.onProxyReq(proxyReq, req);
        }
      },

      onProxyRes: (proxyRes, req, res) => {
        onResponse(proxyConfiguration, proxyRes, req, res);
        if (typeof proxyConfiguration.onProxyRes === 'function') {
          proxyConfiguration.onProxyRes(proxyRes, req, res);
        }
      },

      onError: (err, req, res) => {
        onProxyError(proxyConfiguration, err, req, res);
        if (typeof proxyConfiguration.onError === 'function') {
          proxyConfiguration.onError(err, req, res);
        }
      }
    });

    const proxyContext = Array.isArray(proxyConfig.context) ? proxyConfig.context[0] : proxyConfig.context;

    // Only create proxy if enabled
    if (proxyConfig.enabled) {
      config.push(proxyConfig);
    } else {
      Logger.info(
        `Proxy with context: ${chalk.dim(proxyContext)} and target: ${chalk.dim(proxyConfig.target)} is ${chalk.magenta(
          'DISABLED'
        )}`
      );
    }
  });

  // return null if the array is 0 to make the checks easier upstream
  return config.length === 0 ? null : config;
}
594654
def ssl_proxy(self, value):
        
        self._verify_proxy_type_compatibility(ProxyType.MANUAL)
        self.proxyType = ProxyType.MANUAL
        self.sslProxy = value
762302
function findProxyObject(uri, proxyName, callback) {
    var proxyObject = {},
        folderUri = path.join(uri, proxyName)

    iterateFiles(folderUri, function (fileName) {
        var relativePropertyName = path.relative(folderUri, fileName),
            relativeValue = path.relative(uri, fileName)

        relativePropertyName = relativePropertyName.replace(isFile, "")
        var props = relativePropertyName.split("/")

        props.reduce(function (memo, value, index) {
            if (index === props.length - 1) {
                memo[value] = relativeValue
            } else {
                return (memo[value] = memo[value] || {})
            }
        }, proxyObject)

    }, function (err) {
        callback(err, proxyObject)
    })

    //fs.readdir(folderUri, mapIntoProxyObject)

    function mapIntoProxyObject(err, files) {
        if (err) {
            return callback(err)
        }
        files.filter(isFileFunction).forEach(addToProxyObject)
        callback(null, proxyObject)
    }

    function addToProxyObject(fileName) {
        var propertyName = fileName.replace(isFile, "")

        proxyObject[propertyName] = 
            path.join(proxyName, fileName)
    }
}
123096
function setupForCorporateProxy(proxyConfig) {
  if (!Array.isArray(proxyConfig)) {
    proxyConfig = [proxyConfig];
  }

  const proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
  let agent = null;

  if (proxyServer) {
    console.log(`Using corporate proxy server: ${proxyServer}`);
    agent = new HttpsProxyAgent(proxyServer);
    proxyConfig.forEach(entry => { entry.agent = agent; });
  }

  return proxyConfig;
}
345593
public static void disableProxy() {
        System.clearProperty("http.proxyHost");
        System.clearProperty("http.proxyPort");
        System.clearProperty("http.proxyUserName");
        System.clearProperty("http.proxyUser");
        System.clearProperty("http.proxyPassword");
        System.clearProperty("https.proxyHost");
        System.clearProperty("https.proxyPort");
        System.clearProperty("https.proxyUserName");
        System.clearProperty("https.proxyUser");
        System.clearProperty("https.proxyPassword");

        _url = null;
        _port = null;
        _user = null;
        _pwd = null;
        hasProxy = false;
    }
1313993
private void checkHttpMethod(R pRequest) {
        if (!restrictor.isHttpMethodAllowed(pRequest.getHttpMethod())) {
            throw new SecurityException("HTTP method " + pRequest.getHttpMethod().getMethod() +
                    " is not allowed according to the installed security policy");
        }
    }
1223267
public static ProtocolNegotiator httpProxy(final SocketAddress proxyAddress,
      final @Nullable String proxyUsername, final @Nullable String proxyPassword,
      final ProtocolNegotiator negotiator) {
    final AsciiString scheme = negotiator.scheme();
    Preconditions.checkNotNull(proxyAddress, "proxyAddress");
    Preconditions.checkNotNull(negotiator, "negotiator");
    class ProxyNegotiator implements ProtocolNegotiator {
      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler http2Handler) {
        HttpProxyHandler proxyHandler;
        if (proxyUsername == null || proxyPassword == null) {
          proxyHandler = new HttpProxyHandler(proxyAddress);
        } else {
          proxyHandler = new HttpProxyHandler(proxyAddress, proxyUsername, proxyPassword);
        }
        return new BufferUntilProxyTunnelledHandler(
            proxyHandler, negotiator.newHandler(http2Handler));
      }

      @Override
      public AsciiString scheme() {
        return scheme;
      }

      // This method is not normally called, because we use httpProxy on a per-connection basis in
      // NettyChannelBuilder. Instead, we expect `negotiator' to be closed by NettyTransportFactory.
      @Override
      public void close() {
        negotiator.close();
      }
    }

    return new ProxyNegotiator();
  }
1335625
function(client, record, context) {
  if (!record) {
    return;
  }
  let res, name;
  let modules = Loader.load(record.path, context);
  if (modules) {
    res = {};
    for (name in modules) {
      res[name] = Proxy.create({
        service: name,
        origin: modules[name],
        attach: record,
        proxyCB: proxyCB.bind(null, client)
      });
    }
  }
  return res;
}
52640
private void resolveProxyKeyUsage() {

    boolean[] keyUsages = proxyCredential.getCertificate().getKeyUsage();

    if (keyUsages != null) {
      int index = 0;

      for (boolean key : keyUsages) {

        if (key)
          proxyKeyUsageList.add(keyUsagesValues[index]);
        index++;

      }
    }

  }