コード例 #1
0
ファイル: superuser.py プロジェクト: xzwupeng/quay
  def post(self, certpath):
    uploaded_file = request.files['file']
    if not uploaded_file:
      raise InvalidRequest('Missing certificate file')

    # Save the certificate.
    certpath = pathvalidate.sanitize_filename(certpath)
    if not certpath.endswith('.crt'):
      raise InvalidRequest('Invalid certificate file: must have suffix `.crt`')

    logger.debug('Saving custom certificate %s', certpath)
    cert_full_path = config_provider.get_volume_path(EXTRA_CA_DIRECTORY, certpath)
    config_provider.save_volume_file(cert_full_path, uploaded_file)
    logger.debug('Saved custom certificate %s', certpath)

    # Validate the certificate.
    try:
      logger.debug('Loading custom certificate %s', certpath)
      with config_provider.get_volume_file(cert_full_path) as f:
        load_certificate(f.read())
    except CertInvalidException:
      logger.exception('Got certificate invalid error for cert %s', certpath)
      return '', 204
    except IOError:
      logger.exception('Got IO error for cert %s', certpath)
      return '', 204

    # Call the update script with config dir location to install the certificate immediately.
    if not app.config['TESTING']:
      cert_dir = os.path.join(config_provider.get_config_dir_path(), EXTRA_CA_DIRECTORY)
      if subprocess.call([os.path.join(INIT_SCRIPTS_LOCATION, 'certs_install.sh')], env={ 'CERTDIR': cert_dir }) != 0:
        raise Exception('Could not install certificates')

    return '', 204
コード例 #2
0
ファイル: superuser.py プロジェクト: sabre1041/quay-1
    def post(self, certpath):
        uploaded_file = request.files["file"]
        if not uploaded_file:
            raise InvalidRequest("Missing certificate file")

        # Save the certificate.
        certpath = pathvalidate.sanitize_filename(certpath)
        if not certpath.endswith(".crt"):
            raise InvalidRequest("Invalid certificate file: must have suffix `.crt`")

        logger.debug("Saving custom certificate %s", certpath)
        cert_full_path = config_provider.get_volume_path(EXTRA_CA_DIRECTORY, certpath)
        filename = config_provider.save_volume_file(cert_full_path, uploaded_file)
        logger.debug("Saved custom certificate %s to %s", certpath, filename)

        # Validate the certificate.
        try:
            logger.debug("Loading custom certificate %s", certpath)
            with config_provider.get_volume_file(cert_full_path) as f:
                load_certificate(f.read())
        except CertInvalidException:
            logger.exception("Got certificate invalid error for cert %s", certpath)
            return "", 204
        except IOError:
            logger.exception("Got IO error for cert %s", certpath)
            return "", 204

        # Call the update script with config dir location to install the certificate immediately.
        # This is needed by the configuration application to verify connections to external services
        # which require a self-signed or otherwise user-managed certificate.
        if not app.config["TESTING"]:

            try:
                cert_dir = os.path.join(config_provider.get_config_dir_path(), EXTRA_CA_DIRECTORY)
                script_env = {"CERTDIR": cert_dir}
                logger.debug("Installing certificates from the directory: %s" % cert_dir)

                script_filename = os.path.join(INIT_SCRIPTS_LOCATION, "certs_install.sh")
                logger.debug("Running script to install all certificates: %s", script_filename)

                process = Popen([script_filename], stderr=PIPE, stdout=PIPE, env=script_env)
                output, err = process.communicate()
                return_code = process.returncode

                if return_code != 0:
                    raise Exception("Could not install certificates. Output: %s" % output)
                else:
                    logger.debug("Successfully installed certificates. Output: %s", output)

            except Exception as e:
                logger.exception("Unable to install certificates. Unexpected error: %s", e)

        else:
            msg = (
                "Quay is using the test configuration. Certificates will not be installed. "
                "This may break the configuration app's ability to verify certificates."
            )
            logger.warning(msg)

        return "", 204
コード例 #3
0
ファイル: __init__.py プロジェクト: zhangli19817/quay
 def wrapped(self, *args, **kwargs):
     schema = self.schemas[schema_name]
     try:
         json_data = request.get_json()
         if json_data is None:
             if not optional:
                 raise InvalidRequest("Missing JSON body")
         else:
             validate(json_data, schema)
         return func(self, *args, **kwargs)
     except ValidationError as ex:
         raise InvalidRequest(ex.message)
コード例 #4
0
    def post(self):
        body = request.get_json()

        # Ensure we have a valid expiration date if specified.
        expiration_date = body.get("expiration", None)
        if expiration_date is not None:
            try:
                expiration_date = datetime.utcfromtimestamp(
                    float(expiration_date))
            except ValueError as ve:
                raise InvalidRequest("Invalid expiration date: %s" % ve)

            if expiration_date <= datetime.now():
                raise InvalidRequest("Expiration date cannot be in the past")

        # Create the metadata for the key.
        metadata = body.get("metadata", {})
        metadata.update({
            "created_by": "Quay Superuser Panel",
            "ip": request.remote_addr,
        })

        # Generate a key with a private key that we *never save*.
        (private_key, key_id) = pre_oci_model.generate_service_key(
            body["service"],
            expiration_date,
            metadata=metadata,
            name=body.get("name", ""))
        # Auto-approve the service key.
        pre_oci_model.approve_service_key(key_id,
                                          ServiceKeyApprovalType.SUPERUSER,
                                          notes=body.get("notes", ""))

        # Log the creation and auto-approval of the service key.
        key_log_metadata = {
            "kid": key_id,
            "preshared": True,
            "service": body["service"],
            "name": body.get("name", ""),
            "expiration_date": expiration_date,
            "auto_approved": True,
        }

        log_action("service_key_create", None, key_log_metadata)
        log_action("service_key_approve", None, key_log_metadata)

        return jsonify({
            "kid": key_id,
            "name": body.get("name", ""),
            "service": body["service"],
            "public_key": private_key.publickey().exportKey("PEM"),
            "private_key": private_key.exportKey("PEM"),
        })
コード例 #5
0
ファイル: superuser.py プロジェクト: xzwupeng/quay
  def post(self):
    body = request.get_json()

    # Ensure we have a valid expiration date if specified.
    expiration_date = body.get('expiration', None)
    if expiration_date is not None:
      try:
        expiration_date = datetime.utcfromtimestamp(float(expiration_date))
      except ValueError as ve:
        raise InvalidRequest('Invalid expiration date: %s' % ve)

      if expiration_date <= datetime.now():
        raise InvalidRequest('Expiration date cannot be in the past')

    # Create the metadata for the key.
    metadata = body.get('metadata', {})
    metadata.update({
      'created_by': 'Quay Superuser Panel',
      'ip': request.remote_addr,
    })

    # Generate a key with a private key that we *never save*.
    (private_key, key_id) = pre_oci_model.generate_service_key(body['service'], expiration_date,
                                                               metadata=metadata,
                                                               name=body.get('name', ''))
    # Auto-approve the service key.
    pre_oci_model.approve_service_key(key_id, ServiceKeyApprovalType.SUPERUSER,
                                      notes=body.get('notes', ''))

    # Log the creation and auto-approval of the service key.
    key_log_metadata = {
      'kid': key_id,
      'preshared': True,
      'service': body['service'],
      'name': body.get('name', ''),
      'expiration_date': expiration_date,
      'auto_approved': True,
    }

    log_action('service_key_create', None, key_log_metadata)
    log_action('service_key_approve', None, key_log_metadata)

    return jsonify({
      'kid': key_id,
      'name': body.get('name', ''),
      'service': body['service'],
      'public_key': private_key.publickey().exportKey('PEM'),
      'private_key': private_key.exportKey('PEM'),
    })
コード例 #6
0
    def post(self, certpath):
        uploaded_file = request.files["file"]
        if not uploaded_file:
            raise InvalidRequest("Missing certificate file")

        # Save the certificate.
        certpath = pathvalidate.sanitize_filename(certpath)
        if not certpath.endswith(".crt"):
            raise InvalidRequest(
                "Invalid certificate file: must have suffix `.crt`")

        logger.debug("Saving custom certificate %s", certpath)
        cert_full_path = config_provider.get_volume_path(
            EXTRA_CA_DIRECTORY, certpath)
        config_provider.save_volume_file(cert_full_path, uploaded_file)
        logger.debug("Saved custom certificate %s", certpath)

        # Validate the certificate.
        try:
            logger.debug("Loading custom certificate %s", certpath)
            with config_provider.get_volume_file(cert_full_path) as f:
                load_certificate(f.read())
        except CertInvalidException:
            logger.exception("Got certificate invalid error for cert %s",
                             certpath)
            return "", 204
        except IOError:
            logger.exception("Got IO error for cert %s", certpath)
            return "", 204

        # Call the update script with config dir location to install the certificate immediately.
        if not app.config["TESTING"]:
            cert_dir = os.path.join(config_provider.get_config_dir_path(),
                                    EXTRA_CA_DIRECTORY)
            if (subprocess.call(
                [os.path.join(INIT_SCRIPTS_LOCATION, "certs_install.sh")],
                    env={"CERTDIR": cert_dir},
            ) != 0):
                raise Exception("Could not install certificates")

        return "", 204