示例#1
0
    def request(self, method, path, **kwargs):
        path = '{}{}'.format(self.api_root, path)

        if self.credentials and self.credentials.is_expired():
            self._refresh_access_token()

        try:
            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as sslError:
            msg = 'Connection to {} failed: {}'.format(self.address, sslError)
            six.raise_from(ConnectionFailure(msg), None)
        except requests.exceptions.ConnectionError:
            raise ConnectionFailure('Connection to {} refused'.format(
                self.address))

        if 200 <= response.status_code < 300:
            return response

        exception_message = rest_pb2.RestExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized('401 Client Error: Unauthorized')
        elif response.status_code == 404:
            raise NotFound('404 Client Error: {}'.format(
                exception_message.msg))
        elif 400 <= response.status_code < 500:
            raise YamcsError('{} Client Error: {}'.format(
                response.status_code, exception_message.msg))
        raise YamcsError('{} Server Error: {}'.format(response.status_code,
                                                      exception_message.msg))
示例#2
0
def _convert_user_credentials(session,
                              token_url,
                              username=None,
                              password=None,
                              refresh_token=None):
    """
    Converts username/password credentials to token credentials by
    using Yamcs as the authentication server.
    """
    if username and password:
        data = {
            "grant_type": "password",
            "username": username,
            "password": password
        }
    elif refresh_token:
        data = {"grant_type": "refresh_token", "refresh_token": refresh_token}
    else:
        raise NotImplementedError()

    response = session.post(token_url, data=data)
    if response.status_code == 401:
        raise Unauthorized("401 Client Error: Unauthorized")
    elif response.status_code == 200:
        d = response.json()
        expiry = datetime.utcnow() + timedelta(seconds=d["expires_in"])
        return Credentials(
            access_token=d["access_token"],
            refresh_token=d["refresh_token"],
            expiry=expiry,
        )
    else:
        raise YamcsError("{} Server Error".format(response.status_code))
示例#3
0
def _convert_user_credentials(session,
                              token_url,
                              username=None,
                              password=None,
                              refresh_token=None):
    """
    Converts username/password credentials to token credentials by
    using Yamcs as the authentication server.
    """
    if username and password:
        data = {
            'grant_type': 'password',
            'username': username,
            'password': password
        }
    elif refresh_token:
        data = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}
    else:
        raise NotImplementedError()

    response = session.post(token_url, data=data)
    if response.status_code == 401:
        raise Unauthorized('401 Client Error: Unauthorized')
    elif response.status_code == 200:
        d = response.json()
        expiry = datetime.utcnow() + timedelta(seconds=d['expires_in'])
        return Credentials(access_token=d['access_token'],
                           refresh_token=d['refresh_token'],
                           expiry=expiry)
    else:
        raise YamcsError('{} Server Error'.format(response.status_code))
示例#4
0
def _convert_service_account_credentials(session, token_url, client_id,
                                         client_secret, become):
    """
    Converts service account credentials to impersonated token credentials.
    """
    data = {"grant_type": "client_credentials", "become": become}

    response = session.post(token_url,
                            data=data,
                            auth=HTTPBasicAuth(client_id, client_secret))
    if response.status_code == 401:
        raise Unauthorized("401 Client Error: Unauthorized")
    elif response.status_code == 200:
        d = response.json()
        expiry = datetime.now(tz=timezone.utc) + timedelta(
            seconds=d["expires_in"])
        return Credentials(
            access_token=d["access_token"],
            client_id=client_id,
            client_secret=client_secret,
            become=become,
            expiry=expiry,
        )
    else:
        raise YamcsError("{} Server Error".format(response.status_code))
示例#5
0
    def request(self, method, path, **kwargs):
        path = "{}{}".format(self.api_root, path)

        if self.credentials:
            self.credentials.before_request(self.session, self.auth_root)

        try:
            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as sslError:
            msg = "Connection to {} failed: {}".format(self.address, sslError)
            six.raise_from(ConnectionFailure(msg), None)
        except requests.exceptions.ConnectionError as e:
            raise ConnectionFailure("Connection to {} failed: {}".format(
                self.address, e))

        if 200 <= response.status_code < 300:
            return response

        exception_message = exception_pb2.ExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized("401 Client Error: Unauthorized")
        elif response.status_code == 404:
            raise NotFound("404 Client Error: {}".format(
                getattr(exception_message, "msg")))
        elif 400 <= response.status_code < 500:
            raise YamcsError("{} Client Error: {}".format(
                response.status_code, getattr(exception_message, "msg")))
        raise YamcsError("{} Server Error: {}".format(
            response.status_code, getattr(exception_message, "msg")))
示例#6
0
 def fetch_authorization_code(self, session, auth_url):
     auth = HTTPSPNEGOAuth(opportunistic_auth=True)
     response = session.get(auth_url + "/spnego", auth=auth)
     if response.status_code == 401:
         raise Unauthorized("401 Client Error: Unauthorized")
     elif response.status_code == 200:
         return response.text
     else:
         raise YamcsError("{} Server Error".format(response.status_code))
示例#7
0
 def convert_authorization_code(self, session, auth_url, code):
     data = {"grant_type": "authorization_code", "code": code}
     response = session.post(auth_url + "/token", data=data)
     if response.status_code == 401:
         raise Unauthorized("401 Client Error: Unauthorized")
     elif response.status_code == 200:
         d = response.json()
         expiry = datetime.utcnow() + timedelta(seconds=d["expires_in"])
         return Credentials(
             access_token=d["access_token"],
             refresh_token=d["refresh_token"],
             expiry=expiry,
         )
     else:
         raise YamcsError("{} Server Error".format(response.status_code))
示例#8
0
    def request(self, method, path, **kwargs):
        path = f"{self.api_root}{path}"

        try:
            if self.credentials:
                self.credentials.before_request(self.session, self.auth_root)

            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as ssl_error:
            msg = f"Connection to {self.url} failed: {ssl_error}"
            raise ConnectionFailure(msg) from None
        except requests.exceptions.ConnectionError as e:
            # Requests gives us a horribly confusing error when a connection
            # is refused. Confirm and unwrap.
            if e.args and isinstance(e.args[0], urllib3.exceptions.MaxRetryError):
                # This is a string (which is still confusing ....)
                msg = e.args[0].args[0]
                if "refused" in msg:
                    msg = f"Connection to {self.url} failed: connection refused"
                    raise ConnectionFailure(msg) from None
                elif "not known" in msg:
                    msg = f"Connection to {self.url} failed: could not resolve hostname"
                    raise ConnectionFailure(msg) from None

            raise ConnectionFailure(f"Connection to {self.url} failed: {e}")

        if 200 <= response.status_code < 300:
            return response

        exception_message = exception_pb2.ExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized("401 Client Error: Unauthorized")
        elif response.status_code == 404:
            msg = getattr(exception_message, "msg")
            raise NotFound(f"404 Client Error: {msg}")
        elif 400 <= response.status_code < 500:
            msg = getattr(exception_message, "msg")
            raise YamcsError(f"{response.status_code} Client Error: {msg}")
        msg = getattr(exception_message, "msg")
        raise YamcsError(f"{response.status_code} Server Error: {msg}")
    def request(self, method, path, **kwargs):
        path = "{}{}".format(self.api_root, path)

        if self.credentials:
            self.credentials.before_request(self.session, self.auth_root)

        try:
            response = self.session.request(method, path, **kwargs)
        except requests.exceptions.SSLError as sslError:
            msg = "Connection to {} failed: {}".format(self.address, sslError)
            raise ConnectionFailure(msg) from None
        except requests.exceptions.ConnectionError as e:
            # Requests gives us a horribly confusing error when a connection
            # is refused. Confirm and unwrap.
            if e.args and isinstance(e.args[0],
                                     urllib3.exceptions.MaxRetryError):
                # This is a string (which is still confusing ....)
                msg = e.args[0].args[0]
                if "refused" in msg:
                    msg = "Connection to {} failed: connection refused".format(
                        self.address)
                    raise ConnectionFailure(msg) from None

            raise ConnectionFailure("Connection to {} failed: {}".format(
                self.address, e))

        if 200 <= response.status_code < 300:
            return response

        exception_message = exception_pb2.ExceptionMessage()
        try:
            exception_message.ParseFromString(response.content)
        except DecodeError:
            pass

        if response.status_code == 401:
            raise Unauthorized("401 Client Error: Unauthorized")
        elif response.status_code == 404:
            raise NotFound("404 Client Error: {}".format(
                getattr(exception_message, "msg")))
        elif 400 <= response.status_code < 500:
            raise YamcsError("{} Client Error: {}".format(
                response.status_code, getattr(exception_message, "msg")))
        raise YamcsError("{} Server Error: {}".format(
            response.status_code, getattr(exception_message, "msg")))
示例#10
0
def _convert_service_account_credentials(session, token_url, client_id,
                                         client_secret, become):
    """
    Converts service account credentials to impersonated token credentials.
    """
    data = {'grant_type': 'client_credentials', 'become': become}

    response = session.post(token_url,
                            data=data,
                            auth=HTTPBasicAuth(client_id, client_secret))
    if response.status_code == 401:
        raise Unauthorized('401 Client Error: Unauthorized')
    elif response.status_code == 200:
        d = response.json()
        expiry = datetime.utcnow() + timedelta(seconds=d['expires_in'])
        return Credentials(access_token=d['access_token'],
                           client_id=client_id,
                           client_secret=client_secret,
                           become=become,
                           expiry=expiry)
    else:
        raise YamcsError('{} Server Error'.format(response.status_code))