예제 #1
0
파일: reposcan.py 프로젝트: Josca/vmaas
    def get(self):
        """Download the package tree.
           ---
           description: Download the package tree.
           responses:
             200:
               description: The package tree
               schema:
                 $ref: "#/definitions/PkgTreeDownloadResponse"
             403:
               description: GitHub personal access token (PAT) was not provided for authorization.
             404:
               description: Package Tree file not found.  Has it been generated yet?  Try /sync/pkgtree first.
           tags:
             - pkgtree
        """
        if not self.is_authorized():
            FAILED_AUTH.inc()
            self.set_status(403, 'Valid authorization token was not provided')
            return

        try:
            with open(PKGTREE_FILE, 'rb') as pkgtree_file_reader:
                self.set_header("Content-Type", "application/json")
                self.set_header("Content-Encoding", "gzip")
                while True:
                    chunk = pkgtree_file_reader.read(self.chunk_size)
                    if not chunk:
                        break
                    self.write(chunk)
                self.flush()
        except FileNotFoundError:
            self.set_status(
                404, 'Package Tree file not found.  Has it been generated?')
            return
예제 #2
0
파일: reposcan.py 프로젝트: Josca/vmaas
 def delete(self, repo=None):
     """Delete repository.
        ---
        description: Delete repository
        parameters:
          - name: repo
            description: Repository name or POSIX regular expression pattern
            required: True
            type: string
            in: path
            x-example: rhel-6-server-rpms OR rhel-[4567]-.*-rpms OR rhel-\\d-server-rpms
        responses:
          200:
            description: Repository deletion started
            schema:
              $ref: "#/definitions/TaskStartResponse"
          429:
            description: Another task is already in progress
          403:
            description: GitHub personal access token (PAT) was not provided for authorization.
        tags:
          - repos
     """
     if not self.is_authorized():
         FAILED_AUTH.inc()
         self.set_status(403, 'Valid authorization token was not provided')
         return
     status_code, status_msg = self.start_task(repo=repo)
     self.set_status(status_code)
     self.write(status_msg)
예제 #3
0
파일: reposcan.py 프로젝트: Josca/vmaas
 def put(self):
     """Cancel currently running background task.
        ---
        description: Cancel currently running background task
        responses:
          200:
            description: Task canceled
            schema:
              $ref: "#/definitions/TaskStatusResponse"
          403:
            description: GitHub personal access token (PAT) was not provided for authorization.
        tags:
          - task
     """
     if not self.is_authorized():
         FAILED_AUTH.inc()
         self.set_status(403, 'Valid authorization token was not provided')
         return
     if SyncTask.is_running():
         SyncTask.cancel()
         LOGGER.warning("Background task terminated.")
     self.write(
         TaskStatusResponse(running=SyncTask.is_running(),
                            task_type=SyncTask.get_task_type()))
     self.flush()
예제 #4
0
def auth_admin(x_rh_identity, required_scopes=None):  # pylint: disable=unused-argument
    """
    Parses user name from the x-rh-identity header
    """
    identity = get_identity(x_rh_identity)
    user = identity.get("identity", {}).get("associate", {}).get("email")
    if user:
        LOGGER.info("User '%s' accessed admin API.", user)
        ADMIN_REQUESTS.inc()
        return {"uid": user}
    FAILED_AUTH.inc()
    return None
예제 #5
0
파일: reposcan.py 프로젝트: Josca/vmaas
    def is_authorized(self):
        """Authorization check routine

            only requests from the localhost are allowed w/o authorization token,
            otherwise, GitHub authorization token is required
        """

        host_request = self.request.host.split(':')[0]

        if host_request in ('localhost', '127.0.0.1'):
            return True

        github_token = self.request.headers.get('Authorization', None)
        if not github_token:
            FAILED_AUTH.inc()
            return False

        user_info_response = requests.get(
            'https://api.github.com/user',
            headers={'Authorization': github_token})

        if user_info_response.status_code != 200:
            FAILED_AUTH.inc()
            LOGGER.warning("Cannot execute github API with provided %s",
                           github_token)
            return False
        github_user_login = user_info_response.json()['login']
        orgs_response = requests.get('https://api.github.com/users/' +
                                     github_user_login + '/orgs',
                                     headers={'Authorization': github_token})

        if orgs_response.status_code != 200:
            FAILED_AUTH.inc()
            LOGGER.warning(
                "Cannot request github organizations for the user %s",
                github_user_login)
            return False

        for org_info in orgs_response.json():
            if org_info['login'] == 'RedHatInsights':
                request_str = str(self.request)
                LOGGER.warning("User %s (id %s) got an access to API: %s",
                               github_user_login,
                               user_info_response.json()['id'], request_str)
                return True

        FAILED_AUTH.inc()
        LOGGER.warning(
            "User %s does not belong to RedHatInsights organization",
            github_user_login)
        return False
예제 #6
0
def github_auth(github_token, required_scopes=None):
    """Performs authorization using github"""

    host_request = request.host.split(':')[0]

    if host_request in ('localhost', '127.0.0.1'):
        return {'scopes': ['local']}

    if not github_token:
        FAILED_AUTH.inc()
        return None

    user_info_response = requests.get('https://api.github.com/user',
                                      headers={'Authorization': github_token})

    if user_info_response.status_code != 200:
        FAILED_AUTH.inc()
        LOGGER.warning("Cannot execute github API with provided %s",
                       github_token)
        return None
    github_user_login = user_info_response.json()['login']
    orgs_response = requests.get('https://api.github.com/users/' +
                                 github_user_login + '/orgs',
                                 headers={'Authorization': github_token})

    if orgs_response.status_code != 200:
        FAILED_AUTH.inc()
        LOGGER.warning("Cannot request github organizations for the user %s",
                       github_user_login)
        return None

    authorized_org = os.getenv('AUTHORIZED_API_ORG',
                               DEFAULT_AUTHORIZED_API_ORG)

    for org_info in orgs_response.json():
        if org_info['login'] == authorized_org:
            request_str = str(request)
            LOGGER.warning("User %s (id %s) got an access to API: %s",
                           github_user_login,
                           user_info_response.json()['id'], request_str)
            return {'scopes': ['local', 'authorized']}

    FAILED_AUTH.inc()
    LOGGER.warning("User %s does not belong to %s organization",
                   authorized_org, github_user_login)
    return None
예제 #7
0
파일: reposcan.py 프로젝트: Josca/vmaas
 def put(self):
     """Sync repos + CVEs + CVEmap.
        ---
        description: Sync repositories stored in DB and CVE lists
        responses:
          200:
            description: Sync started
            schema:
              $ref: "#/definitions/TaskStartResponse"
          429:
            description: Another task is already in progress
          403:
            description: GitHub personal access token (PAT) was not provided for authorization.
        tags:
          - sync
     """
     if not self.is_authorized():
         FAILED_AUTH.inc()
         self.set_status(403, 'Valid authorization token was not provided')
         return
     status_code, status_msg = self.start_task()
     self.set_status(status_code)
     self.write(status_msg)
     self.flush()