/*
Verify the 'Docker-Content-Digest' header for a getManifest response.

@throws {BadDigestError} if the digest doesn't check out.
977266
function _verifyManifestDockerContentDigest(res, jws) {
    var dcdInfo = _parseDockerContentDigest(
        res.headers['docker-content-digest']);

    dcdInfo.hash.update(jws.payload);
    var digest = dcdInfo.hash.digest('hex');
    if (dcdInfo.expectedDigest !== digest) {
        res.log.trace({expectedDigest: dcdInfo.expectedDigest,
            header: dcdInfo.raw, digest: digest},
            'Docker-Content-Digest failure');
        throw new restifyErrors.BadDigestError('Docker-Content-Digest');
    }
}
154369
function digestFromManifestStr(manifestStr) {
    assert.string(manifestStr, 'manifestStr');

    var hash = crypto.createHash('sha256');
    var digestPrefix = 'sha256:';

    var manifest;
    try {
        manifest = JSON.parse(manifestStr);
    } catch (err) {
        throw new restifyErrors.InvalidContentError(err, fmt(
            'could not parse manifest: %s', manifestStr));
    }
    if (manifest.schemaVersion === 1) {
        try {
            var manifestBuffer = Buffer(manifestStr);
            var jws = _jwsFromManifest(manifest, manifestBuffer);
            hash.update(jws.payload, 'binary');
            return digestPrefix + hash.digest('hex');
        } catch (verifyErr) {
            if (!(verifyErr instanceof restifyErrors.InvalidContentError)) {
                throw verifyErr;
            }
            // Couldn't parse (or doesn't have) the signatures section,
            // fall through.
        }
    }
    hash.update(manifestStr);
    return digestPrefix + hash.digest('hex');
}
910350
function () {
        var contentEncoding = this.headers.get(CONTENT_ENCODING),
            body = this.stream || this.body,
            source;

        if (contentEncoding) {
            source = HEADER;
        }

        // if the encoding is not found, we check
        else if (body) { // @todo add detection for deflate
            // eslint-disable-next-line lodash/prefer-matches
            if (body[0] === 0x1F && body[1] === 0x8B && body[2] === 0x8) {
                contentEncoding = GZIP;
            }

            if (contentEncoding) {
                source = BODY;
            }
        }

        return {
            format: contentEncoding,
            source: source
        };
    }
299329
function checkInContainer () {
  const fs = require('fs')
  if (fs.existsSync(`/proc/1/cgroup`)) {
    const content = fs.readFileSync(`/proc/1/cgroup`, 'utf-8')
    return /:\/(lxc|docker|kubepods)\//.test(content)
  }
}
882875
function (response) {
        var contentType = response.headers.get(HEADERS.CONTENT_TYPE),
            contentDisposition = response.headers.get(HEADERS.CONTENT_DISPOSITION),
            mimeInfo = getMimeInfo(contentType, response.stream || response.body),
            fileName = getFileNameFromDispositionHeader(contentDisposition),
            fileExtension = mimeInfo.extension,

            /**
             * @typedef Response~ResponseContentInfo
             *
             * @property {String} mimeType sanitized mime type
             * @property {String} mimeFormat format for the identified mime type
             * @property {String} charset the normalized character set
             * @property {String} fileExtension extension identified from the mime type
             * @property {String} fileName file name extracted from disposition header
             */
            contentInfo = {};


        // if file name is not present in the content disposition headers, use a default file name
        if (!fileName) {
            fileName = DEFAULT_RESPONSE_FILENAME;
            // add extension to default if present
            fileExtension && (fileName += (DOT + fileExtension));
        }

        // create a compacted list of content info from mime info and file name
        mimeInfo.mimeType && (contentInfo.mimeType = mimeInfo.mimeType);
        mimeInfo.mimeFormat && (contentInfo.mimeFormat = mimeInfo.mimeFormat);
        mimeInfo.charset && (contentInfo.charset = mimeInfo.charset);
        fileExtension && (contentInfo.fileExtension = fileExtension);
        fileName && (contentInfo.fileName = fileName);

        return contentInfo;
    }
1352919
function validateContentsZip(contentsZip) {
  return preprocessToRezip(contentsZip).then(
    ({ entries, manifestJson, manifestPath }) =>
      validateManifest(entries, manifestJson, manifestPath)
  );
}
351903
async function() {
    const oThis = this
    ;
    const addressObj = new generateAddress({chain: 'utility', passphrase: oThis.reservePassphrase})
      , addressResponse = await addressObj.perform();
    if (addressResponse.isFailure()) {
      logger.error("* Reserve address generation failed with error:", addressResponse);
      process.exit(1);
    }
    return Promise.resolve(addressResponse);
  }
920890
private boolean responseIsInValid() {
        if (response == null) {
            return true;
        }
        else if (!response.isHeadless() && validityCheck) {
            return request.getTransactionID() != response.getTransactionID();
        }
        else {
            return false;
        }
    }
1277307
def _get_dcd(self, alias):
        
        # https://docs.docker.com/registry/spec/api/#deleting-an-image
        # Note When deleting a manifest from a registry version 2.3 or later,
        # the following header must be used when HEAD or GET-ing the manifest
        # to obtain the correct digest to delete:
        # Accept: application/vnd.docker.distribution.manifest.v2+json
        return self._request(
            'head',
            'manifests/{}'.format(alias),
            headers={'Accept': _schema2_mimetype},
        ).headers.get('Docker-Content-Digest')
1373316
function endpointInvalidHeaders(endpoint) {
  const invalid = []

  for (const path of Object.keys(endpoint.headers)) {
    let pathIsUseful = false
    for (const useful of UsefulHeaders) {
      if (path === useful) {
        pathIsUseful = true
        break
      }
    }
    if (!pathIsUseful) invalid.push(path)
  }

  return invalid.length === 0 ? null : `${endpoint.path} (${invalid.join(', ')})`
}
412901
def validate_content_type!(response)
      return unless media_type

      response_content_type = response.content_type
      expected_content_type = Praxis::MediaTypeIdentifier.load(media_type.identifier)

      unless expected_content_type.match(response_content_type)
        raise Exceptions::Validation.new(
          "Bad Content-Type header. #{response_content_type}" +
          " is incompatible with #{expected_content_type} as described in response: #{self.name}"
        )
      end
    end
122174
protected void viaLastaDiContext(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        final LaContainer container = SingletonLaContainerFactory.getContainer();
        final ExternalContext externalContext = container.getExternalContext();
        if (externalContext == null) {
            throw new IllegalStateException("The externalContext should not be null from the container: " + container);
        }
        final Object prevoiusRequest = externalContext.getRequest();
        final Object previousResponse = externalContext.getResponse();
        try {
            externalContext.setRequest(request);
            externalContext.setResponse(response);
            viaHotdeploy(request, response, chain); // #to_action
        } finally {
            externalContext.setRequest(prevoiusRequest);
            externalContext.setResponse(previousResponse);
        }
    }
736447
function checkCacheResponse(key, err, result, type, cacheIndex){
    if(err){
      log(true, 'Error when getting key ' + key + ' from cache of type ' + type + ':', err);

      if(cacheIndex < self.caches.length - 1){
        return {status:'continue'};
      }
    }
    //THIS ALLOWS false AS A VALID CACHE VALUE, BUT DO I WANT null TO BE VALID AS WELL?
    if(result !== null && typeof result !== 'undefined'){
      log(false, 'Key found:', {key: key, value: result});
      return {status: 'break', result: result};
    }
    var curCache = self.caches[cacheIndex];
    for(var i = cacheIndex + 1; i < self.cachesLength; i++) {
      var nextCache = self.caches[i];
      if(nextCache.checkOnPreviousEmpty || nextCache.expiration > curCache.expiration){
        return {status:'continue', toIndex: i};
      }
    }
    return {status: 'else'};
  }
717224
protected function checkDigestSupport()
	{
		// ensure that the selected digest method is supported by the current PHP version
		if (!in_array($this->digestMethod, hash_algos()))
		{
			trigger_error(sprintf('This installation of PHP does not support the %s hashing algorithm', $this->digestMethod), E_USER_ERROR);
		}
	}
46517
public function syncManifest()
    {
        $this->validateName();

        if ($this->manifest) {
            $headers = $this->getNewHeaders();
            $headers['Content-Length'] = '0';

            $this->container->getConnection()->makeRequest(
                Client::PUT,
                array($this->container->getName(), $this->name),
                $headers
            );
        }
    }
1227968
def ValidateCSRFTokenOrRaise(request):
  """"""

  # CSRF check doesn't make sense for GET/HEAD methods, because they can
  # (and are) used when downloading files through <a href> links - and
  # there's no way to set X-CSRFToken header in this case.
  if request.method in ("GET", "HEAD"):
    return

  # In the ideal world only JavaScript can be used to add a custom header, and
  # only within its origin. By default, browsers don't allow JavaScript to
  # make cross origin requests.
  #
  # Unfortunately, in the real world due to bugs in browsers plugins, it can't
  # be guaranteed that a page won't set an HTTP request with a custom header
  # set. That's why we also check the contents of a header via an HMAC check
  # with a server-stored secret.
  #
  # See for more details:
  # https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
  # (Protecting REST Services: Use of Custom Request Headers).
  csrf_token = request.headers.get("X-CSRFToken", "").encode("ascii")
  if not csrf_token:
    logging.info("Did not find headers CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("CSRF token is missing")

  try:
    decoded = base64.urlsafe_b64decode(csrf_token + b"==")
    digest, token_time = decoded.rsplit(CSRF_DELIMITER, 1)
    token_time = int(token_time)
  except (TypeError, ValueError):
    logging.info("Malformed CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Malformed CSRF token")

  if len(digest) != hashlib.sha256().digest_size:
    logging.info("Invalid digest size for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Malformed CSRF token digest")

  expected = GenerateCSRFToken(request.user, token_time)
  if not constant_time.bytes_eq(csrf_token, expected):
    logging.info("Non-matching CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Non-matching CSRF token")

  current_time = rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch()
  if current_time - token_time > CSRF_TOKEN_DURATION.microseconds:
    logging.info("Expired CSRF token for: %s", request.path)
    raise werkzeug_exceptions.Forbidden("Expired CSRF token")
62542
function computeDependencyDigest(self) {
  return _.reduce(self.requiredAssets, function (digest, asset) {
    return digest.update(asset.digest);
  }, self.environment.digest).digest('hex');
}