Exemple #1
0
    def wsgi_app(self, environ, start_response):
        # response = BaseResponse('hello world')
        # return response(environ, start_response)
        # request = BaseRequest(environ)
        if BaseRequest(environ).path == '/favicon.ico':
            response = BaseResponse('ico')
        else:

            request = Request(BaseRequest(environ))

            response = self.kernel.handle(request)

        return response(environ, start_response)
Exemple #2
0
    def __call__(self, environ, start_response):
        req = BaseRequest(environ)
        url = req.path
        method = req.method.lower()
        url_dict = self.URL_MAP.get(url)

        if url_dict:
            allowed_methods = [
                m for m in self.URL_MAP.get(url, {}).get("methods", {})
            ]
            if method not in allowed_methods:
                response = BaseResponse(
                    '<h1>405 Method Not Allowed<h1>',
                    content_type='text/html; charset=UTF-8',
                    status=405)
            else:
                args = req.args.to_dict()
                view = url_dict.get("methods", {}).get(method,
                                                       {}).get("function")
                response = view(**args)
                response = BaseResponse(response)
        else:
            response = BaseResponse('<h1>404 Source Not Found<h1>',
                                    content_type='text/html; charset=UTF-8',
                                    status=404)
        return response(environ, start_response)
Exemple #3
0
def application(environ, start_response):
    req = BaseRequest(environ)
    if req.method == 'POST':
        resp = view_file(req)
    else:
        resp = upload_file(req)
    return resp(environ, start_response)
Exemple #4
0
 def application(environ, start_response):
     request = BaseRequest(environ)
     try:
         return view(request)
     except NotFound as e:
         return not_found(request)
     except HTTPException as e:
         return e
Exemple #5
0
def make_environ(event):
    environ = {}
    headers = event['headers'] or {}

    for hdr_name, hdr_value in headers.items():
        hdr_name = hdr_name.replace('-', '_').upper()
        if hdr_name in ['CONTENT_TYPE', 'CONTENT_LENGTH']:
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = 'HTTP_%s' % hdr_name
        environ[http_hdr_name] = hdr_value
    if 'HTTP_X_FORWARDED_PORT' not in environ:
            environ['HTTP_X_FORWARDED_PORT'] = '443'
    if 'HTTP_X_FORWARDED_PROTO' not in environ:
        environ['HTTP_X_FORWARDED_PROTO'] = 'https'


    qs = event['queryStringParameters']

    environ['REQUEST_METHOD'] = event['httpMethod']
    environ['PATH_INFO'] = event['path']
    environ['QUERY_STRING'] = urlencode(qs) if qs else ''
    environ['REMOTE_ADDR'] = event['requestContext']['identity']['sourceIp']
    environ['HOST'] = '%(HTTP_HOST)s:%(HTTP_X_FORWARDED_PORT)s' % environ
    environ['SCRIPT_NAME'] = ''

    environ['SERVER_PORT'] = environ['HTTP_X_FORWARDED_PORT']
    environ['SERVER_PROTOCOL'] = 'HTTP/1.1'

    if 'isBase64Encoded' in event and event['isBase64Encoded'] is True:
        if 'body' in event and event['body'] is not None and 0 < len(event['body']):
            tmp_body = base64.b64decode(event['body'])
            environ['CONTENT_LENGTH'] = str(len(tmp_body))
            environ['wsgi.input'] = StringIO(tmp_body.decode('utf-8'))
        else:
            environ['CONTENT_LENGTH'] = '0'
            environ['wsgi.input'] = StringIO('')
    else:
        environ['CONTENT_LENGTH'] = str(
            len(event['body']) if event['body'] else ''
        )
        environ['wsgi.input'] = StringIO(event['body'] or '')


    environ['wsgi.url_scheme'] = environ['HTTP_X_FORWARDED_PROTO']
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.multithread'] = False
    environ['wsgi.run_once'] = True
    environ['wsgi.multiprocess'] = False

    if 'Content-Type' in headers:
        environ['CONTENT_TYPE'] = headers['Content-Type']

    BaseRequest(environ)

    return environ
def application(environ, start_response):
	request = BaseRequest(environ)
	app.logger.debug('An error occurred')
	try:
		return view(request)
	except NotFound as e:
		return not_found(request)
	except HTTPException as e:
		return e
Exemple #7
0
 def application(self, environ, start_response):
     req = BaseRequest(environ)
     if req.method == 'POST':
         resp = self.post_handler(req)
     elif req.method == 'GET':
         resp = self.get_handler(req)
     else:
         return BaseResponse('HTTP method not supported',
                             mimetype='text/plain')
     return resp(environ, start_response)
    def __call__(self, environ, start_response):
        req = BaseRequest(environ)

        if req.method != 'POST':
            return redirect_homepage(start_response)

        logger.debug(req.headers)

        payload = self.create_payload(json.load(req.stream))
        url = 'https://hooks.slack.com/services/%s' % (req.path.lstrip('/'))
        self.send_payload(payload, url, "#software")
        return response(start_response)
 def test_logout(self):
     """
         need new Client b/c using the same client can mess up other tests
         since order of tests is not guaranteed
     """
     c = Client(ag.wsgi_test_app, BaseResponse)
     login_client_with_permissions(c)
     environ, r = c.get('/users/logout',
                        as_tuple=True,
                        follow_redirects=True)
     assert r.status_code == 200, r.status
     assert BaseRequest(environ).url == 'http://localhost/users/login'
Exemple #10
0
def make_environ(event):
    environ = {}

    if os.environ.get("LOG_LEVEL") == "DEBUG":
        print('event: "{}"'.format(event))

    # key might be there but set to None
    headers = event.get('headers', {}) or {}
    for hdr_name, hdr_value in headers.items():
        hdr_name = hdr_name.replace('-', '_').upper()
        if hdr_name in ['CONTENT_TYPE', 'CONTENT_LENGTH']:
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = 'HTTP_{}'.format(hdr_name)
        environ[http_hdr_name] = hdr_value

    qs = event['queryStringParameters']

    for k, v in qs.items():
        qs[k] = unquote(v)

    environ['REQUEST_METHOD'] = event['httpMethod']
    environ['PATH_INFO'] = event['path']
    environ['QUERY_STRING'] = urlencode(qs) if qs else ''

    environ['REMOTE_ADDR'] = environ.get('X_FORWARDED_FOR')

    environ['HOST'] = '{}:{}'.format(
        environ.get('HTTP_HOST', ''),
        environ.get('HTTP_X_FORWARDED_PORT', ''),
    )
    environ['SCRIPT_NAME'] = ''
    environ['SERVER_NAME'] = 'SERVER_NAME'

    environ['SERVER_PORT'] = environ.get('HTTP_X_FORWARDED_PORT', '')
    environ['SERVER_PROTOCOL'] = 'HTTP/1.1'

    environ['CONTENT_LENGTH'] = str(
        len(event['body']) if event['body'] else '')

    environ['wsgi.url_scheme'] = environ.get('HTTP_X_FORWARDED_PROTO', '')
    environ['wsgi.input'] = StringIO(event['body'] or '')
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.multithread'] = False
    environ['wsgi.run_once'] = True
    environ['wsgi.multiprocess'] = False

    BaseRequest(environ)

    return environ
Exemple #11
0
def request_test_app(environ, start_response):
    """Small test app."""
    request = BaseRequest(environ)
    assert 'werkzeug.request' in environ
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return [pickle.dumps({
        'args':             request.args,
        'args_as_list':     request.args.lists(),
        'form':             request.form,
        'form_as_list':     request.form.lists(),
        'environ':          prepare_environ_pickle(request.environ),
        'data':             request.data
    })]
Exemple #12
0
def make_environ(event):
    environ = {"CONTENT_TYPE": "application/json"}

    headers = event.get('headers', {})

    for hdr_name, hdr_value in headers.items():
        hdr_name = hdr_name.replace('-', '_').upper()
        if hdr_name in ['CONTENT_TYPE', 'CONTENT_LENGTH']:
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = 'HTTP_%s' % hdr_name
        environ[http_hdr_name] = hdr_value

    qs = event.get('queryStringParameters', {})
    rc = event.get('requestContext', {})
    identity = rc.get('identity', {})

    http_host_hdr = headers.get("Host", "127.0.0.1")
    http_x_forwarded_port_hdr = headers.get("X-Forwarded-Port", "80")

    environ['REQUEST_METHOD'] = event.get('httpMethod', "GET")
    environ['PATH_INFO'] = event.get('path', "/")
    environ['QUERY_STRING'] = urlencode(qs) if qs else ''
    environ['REMOTE_ADDR'] = identity.get('sourceIp', '127.0.0.1')
    environ['HOST'] = '%s:%s' % (http_host_hdr, http_x_forwarded_port_hdr)
    environ['SCRIPT_NAME'] = ''

    environ['SERVER_PORT'] = headers.get('HTTP_X_FORWARDED_PORT', "80")
    environ['SERVER_PROTOCOL'] = 'HTTP/1.1'
    environ['SERVER_NAME'] = http_host_hdr

    environ['CONTENT_LENGTH'] = str(
        len(event['body']) if event['body'] else '')

    environ['wsgi.url_scheme'] = environ.get('HTTP_X_FORWARDED_PROTO')
    environ['wsgi.input'] = StringIO(event['body'] or '')
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.multithread'] = False
    environ['wsgi.run_once'] = True
    environ['wsgi.multiprocess'] = False

    BaseRequest(environ)

    return environ
Exemple #13
0
def make_environ(event):
    environ = {}
    print("resource:", event["resource"], "path:", event["path"])
    # key might be there but set to None
    headers = event.get("headers", {}) or {}
    for hdr_name, hdr_value in headers.items():
        hdr_name = hdr_name.replace("-", "_").upper()
        if hdr_name in ["CONTENT_TYPE", "CONTENT_LENGTH"]:
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = "HTTP_{}".format(hdr_name)
        environ[http_hdr_name] = hdr_value

    qs = event["queryStringParameters"]

    environ["REQUEST_METHOD"] = event["httpMethod"]
    environ["PATH_INFO"] = event["path"]
    environ["QUERY_STRING"] = urlencode(qs) if qs else ""

    environ["REMOTE_ADDR"] = environ.get("X_FORWARDED_FOR")

    environ["HOST"] = "{}:{}".format(
        environ.get("HTTP_HOST", ""),
        environ.get("HTTP_X_FORWARDED_PORT", ""),
    )
    environ["SCRIPT_NAME"] = ""
    environ["SERVER_NAME"] = "SERVER_NAME"

    environ["SERVER_PORT"] = environ.get("HTTP_X_FORWARDED_PORT", "")
    environ["SERVER_PROTOCOL"] = "HTTP/1.1"

    environ["CONTENT_LENGTH"] = str(
        len(event["body"]) if event["body"] else "")

    environ["wsgi.url_scheme"] = environ.get("HTTP_X_FORWARDED_PROTO")
    environ["wsgi.input"] = StringIO(event["body"] or "")
    environ["wsgi.version"] = (1, 0)
    environ["wsgi.errors"] = sys.stderr
    environ["wsgi.multithread"] = False
    environ["wsgi.run_once"] = True
    environ["wsgi.multiprocess"] = False

    BaseRequest(environ)

    return environ
Exemple #14
0
    def __call__(self, environ, start_response):
        req = BaseRequest(environ)

        if req.method != 'POST':
            return redirect_homepage(start_response)

        event = req.headers.get('X-Tower-Event')
        if not event:
            return bad_request(start_response)

        signature = req.headers.get('X-Tower-Signature')
        if signature and signature[0] not in ('@', '#'):
            signature = None

        payload = self.create_payload(json.load(req.stream), event)
        url = 'https://hooks.slack.com/services/%s' % (req.path.lstrip('/'))
        self.send_payload(payload, url, signature)
        return response(start_response)
Exemple #15
0
    def wsgi_app(self, environ, start_response):
        """WSGI middleware main entry point.
        """
        request = BaseRequest(environ)

        if request.method in self.unprotected_methods:
            return self._wrapped(environ, start_response)

        if not self.protected_paths_re.match(request.path):
            return self._wrapped(environ, start_response)

        if (self.unprotected_paths_re is not None and
                self.unprotected_paths_re.match(request.path)):
            return self._wrapped(environ, start_response)

        _LOGGER.info('Authenticating access to %s', request.path)
        app = self._auth_spnego(request)
        return app(environ, start_response)
Exemple #16
0
def make_environ(event):
    environ = {}

    for hdr_name, hdr_value in event['headers'].items():
        hdr_name = hdr_name.replace('-', '_').upper()
        if hdr_name in ['CONTENT_TYPE', 'CONTENT_LENGTH']:
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = 'HTTP_%s' % hdr_name
        environ[http_hdr_name] = hdr_value

    apigateway_qs = event['queryStringParameters']
    request_qs = event['queryString']
    qs = apigateway_qs.copy()
    qs.update(request_qs)

    body = ''
    if 'body' in event:
        body = event['body']

    environ['REQUEST_METHOD'] = event['httpMethod']
    environ['PATH_INFO'] = event['path']
    environ['QUERY_STRING'] = urlencode(qs) if qs else ''
    environ['REMOTE_ADDR'] = 80
    environ['HOST'] = event['headers']['host']
    environ['SCRIPT_NAME'] = ''

    environ['SERVER_PORT'] = 80
    environ['SERVER_PROTOCOL'] = 'HTTP/1.1'

    environ['CONTENT_LENGTH'] = str(len(body))

    environ['wsgi.url_scheme'] = ''
    environ['wsgi.input'] = StringIO(body)
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.multithread'] = False
    environ['wsgi.run_once'] = True
    environ['wsgi.multiprocess'] = False

    BaseRequest(environ)

    return environ
Exemple #17
0
def make_environ(event):
    environ = {}

    for hdr_name, hdr_value in event['headers'].items():
        hdr_name = hdr_name.replace('-', '_').upper()
        if hdr_name in ['CONTENT_TYPE', 'CONTENT_LENGTH']:
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = 'HTTP_%s' % hdr_name
        environ[http_hdr_name] = hdr_value

    qs = event['queryStringParameters']
    environ['HTTP_HOST'] = environ.get('HTTP_HOST') or 'localhost'
    environ['HTTP_X_FORWARDED_PORT'] = environ.get(
        'HTTP_X_FORWARDED_PORT') or 8888
    environ['HTTP_X_FORWARDED_PROTO'] = environ.get(
        'HTTP_X_FORWARDED_PROTO') or 8888

    environ['REQUEST_METHOD'] = event['httpMethod']
    environ['PATH_INFO'] = event['path']
    environ['QUERY_STRING'] = urlencode(qs) if qs else ''
    environ['REMOTE_ADDR'] = event['requestContext']['identity']['sourceIp']
    environ['HOST'] = '%(HTTP_HOST)s:%(HTTP_X_FORWARDED_PORT)s' % environ
    environ['SCRIPT_NAME'] = ''

    environ['SERVER_PORT'] = environ['HTTP_X_FORWARDED_PORT']
    environ['SERVER_PROTOCOL'] = 'HTTP/1.1'

    environ['CONTENT_LENGTH'] = str(
        len(event['body']) if event['body'] else '')

    environ['wsgi.url_scheme'] = environ['HTTP_X_FORWARDED_PROTO']
    environ['wsgi.input'] = StringIO(event['body'] or '')
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.multithread'] = False
    environ['wsgi.run_once'] = True
    environ['wsgi.multiprocess'] = False

    BaseRequest(environ)

    return environ
Exemple #18
0
def login_client_as_user(client,
                         username,
                         password,
                         validate_login_response=True):
    topost = {
        'login_id': username,
        'password': password,
        'login-form-submit-flag': '1'
    }
    if isinstance(client, (Client, WerkzeugClient)):
        if isinstance(client, Client):
            # blazeweb client handles follow_redirects differently
            req, resp = client.post('users/login',
                                    data=topost,
                                    follow_redirects=True)
        else:
            # werkzeug Client
            environ, resp = client.post('users/login',
                                        data=topost,
                                        as_tuple=True,
                                        follow_redirects=True)
            req = BaseRequest(environ)
        if validate_login_response:
            assert resp.status_code == 200, resp.status
            assert b'You logged in successfully!' in resp.data, resp.data[
                0:500]
            assert req.url.endswith(
                after_login_url()), '%s != %s' % (req.url, after_login_url())
        return req, resp
    elif isinstance(client, (paste.fixture.TestApp, TestApp)):
        res = client.post('/users/login', params=topost)
        res = res.follow()
        if validate_login_response:
            assert res.request.url.endswith(after_login_url()), \
                '%s != %s' % (res.request.url, after_login_url())
            res.mustcontain('You logged in successfully!')
        return res
    else:
        raise TypeError('client is of an unexpected type: %s' %
                        client.__class__)
Exemple #19
0
def make_environ(event):
    environ = {}

    for hdr_name, hdr_value in event["headers"].items():
        hdr_name = hdr_name.replace("-", "_").upper()
        if hdr_name in ("CONTENT_TYPE", "CONTENT_LENGTH"):
            environ[hdr_name] = hdr_value
            continue

        http_hdr_name = f"HTTP_{hdr_name}"
        environ[http_hdr_name] = hdr_value

    qs = event["queryStringParameters"]

    environ["REQUEST_METHOD"] = event["httpMethod"]
    environ["PATH_INFO"] = event["path"]
    environ["QUERY_STRING"] = urlencode(qs) if qs else ""
    environ["REMOTE_ADDR"] = event["requestContext"]["identity"]["sourceIp"]
    environ["USER_ID"] = (event["requestContext"].get("authorizer", {}).get(
        "claims", {}).get("sub", "None"))
    environ["HOST"] = "%(HTTP_HOST)s:%(HTTP_X_FORWARDED_PORT)s" % environ
    environ["SCRIPT_NAME"] = ""

    environ["SERVER_PORT"] = environ["HTTP_X_FORWARDED_PORT"]
    environ["SERVER_PROTOCOL"] = "HTTP/1.1"

    environ["CONTENT_LENGTH"] = str(
        len(event["body"]) if event["body"] else "")

    environ["wsgi.url_scheme"] = environ["HTTP_X_FORWARDED_PROTO"]
    environ["wsgi.input"] = StringIO(event["body"] or "")
    environ["wsgi.version"] = (1, 0)
    environ["wsgi.errors"] = sys.stderr
    environ["wsgi.multithread"] = False
    environ["wsgi.run_once"] = True
    environ["wsgi.multiprocess"] = False

    BaseRequest(environ)

    return environ
Exemple #20
0
 def wsgi_app(self, environ, start_response) -> Iterable[bytes]:
     request = BaseRequest(environ)
     parts = request.path.lstrip("/").split("/")
     qual_name = QualName(parts[:-1], parts[-1])
     handler = self.transport.ask(qual_name, self.handle_encoding)
     if handler is None:
         raise NotFound
     meta = dict()
     for k, v in request.headers.items():
         meta[k] = v
     data = json.load(request.stream)
     r_with_meta = handler(WithMeta(meta, data))
     serialized = json.dumps(
         r_with_meta.data,
         ensure_ascii=False,
     )
     r = BaseResponse(serialized,
                      status=200,
                      content_type="application/json")
     for k, v in r_with_meta.meta.items():
         r.headers[k] = v
     return r(environ, start_response)
 def __init__(self, environ, url_map):
     BaseRequest.__init__(self, environ)
     self.url_adapter = url_map.bind_to_environ(environ)
Exemple #22
0
 def __init__(self, environ):
     BaseRequest.__init__(self, environ)
     self.session = SecureCookie.load_cookie(self, secret_key=SECRET_KEY)
Exemple #23
0
 def __init__(self, environ, url_adapter):
     BaseRequest.__init__(self, environ)
     self.url_adapter = url_adapter
     local.request = self
Exemple #24
0
 def from_request(cls, request: BaseRequest):
     return cls(content_type=request.environ.get('CONTENT_TYPE'),
                content_length=request.environ.get('CONTENT_LENGTH'),
                data_dump=request.get_data())
Exemple #25
0
 def __init__(self, environ, url_adapter):
     BaseRequest.__init__(self, environ)
     self.url_adapter = url_adapter
     local.request = self
Exemple #26
0
def default_app(environ, start_response):
    request = BaseRequest(environ)
    try:
        return view(request)
    except HTTPException as e:
        return e
Exemple #27
0
def application(environ, start_response):
    request = BaseRequest(environ)
    return response('This is a Test.', 'text/plain')
Exemple #28
0
 def __init__(self, environ):
     BaseRequest.__init__(self, environ)
     self.session = SecureCookie.load_cookie(self, secret_key=SECRET_KEY)