def testProcessesRequestWithEmail_configEnabled(self): environ = werkzeug_test.EnvironBuilder( environ_base={ "REMOTE_ADDR": "127.0.0.1", "HTTP_X_REMOTE_USER": "******", "HTTP_X_REMOTE_EXTRA_EMAIL": "*****@*****.**", }).get_environ() request = wsgiapp.HttpRequest(environ) with test_lib.ConfigOverrider( {"Email.enable_custom_email_address": True}): response = self.manager.SecurityCheck(self.HandlerStub, request) self.assertEqual(request.email, "*****@*****.**") self.assertEqual(response, self.success_response)
def testCsp_globalDomainWhiteList(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, '<b>hello</b>', 'text/html', csp_scripts_sha256s=['abcd']) expected_csp = ( "default-src 'self';font-src 'self';frame-ancestors *;" "frame-src 'self';img-src 'self' data: blob: https://example.com;" "object-src 'none';style-src https://www.gstatic.com data: " "'unsafe-inline' https://googol.com;script-src " "https://tensorflow.org/tensorboard 'self' 'unsafe-eval' 'sha256-abcd'" ) self.assertEqual(r.headers.get('Content-Security-Policy'), expected_csp)
def testNoHeader(self): """Test requests sent to the Admin UI without an IAP Header.""" environ = werkzeug_test.EnvironBuilder(path="/").get_environ() request = wsgiapp.HttpRequest(environ) def Handler(request, *args, **kwargs): del request, args, kwargs # Unused. return werkzeug_wrappers.Response("foobar", status=200) manager = webauth.IAPWebAuthManager() response = manager.SecurityCheck(Handler, request) self.assertEqual(response.status_code, 401)
def testPrecompressedResponse_streamingDecompression_catchesBadSize(self): orig_text = b"hello hello hello world" gzip_text = _gzip(orig_text) # Corrupt the gzipped data's stored content size (last 4 bytes). bad_text = gzip_text[:-4] + _bitflip(gzip_text[-4:]) q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, bad_text, "text/plain", content_encoding="gzip") # Streaming gunzip defers actual unzipping until response is used; once # we iterate over the whole file-wrapper application iterator, the # underlying GzipFile should be closed, and throw the size check error. with six.assertRaisesRegex(self, IOError, "Incorrect length"): _ = list(r.response)
def testSuccessfulKey(self, mock_method): """Validate account creation upon successful JWT Authentication.""" environ = werkzeug_test.EnvironBuilder( path="/", headers={ "X-Goog-IAP-JWT-Assertion": ("valid_key") }).get_environ() request = wsgiapp.HttpRequest(environ) def Handler(request, *args, **kwargs): del args, kwargs # Unused. self.assertEqual(request.user, "temp") return http_response.HttpResponse("success", status=200) manager = webauth.IAPWebAuthManager() response = manager.SecurityCheck(Handler, request) self.assertEqual(response.status_code, 200)
def testFailedSignatureKey(self, mock_get): """Test requests with an invalid JWT Token.""" mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = { "6BEeoA": ("-----BEGIN PUBLIC KEY-----\n" "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAElmi1hJdqtbvdX1INOf5B9dWvkydY\n" "oowHUXiw8ELWzk/YHESNr8vXQoyOuLOEtLZeCQbFkeLUqxYp1sTArKNu/A==\n" "-----END PUBLIC KEY-----\n"), } assertion_header = ( "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsI" "mtpZCI6IjZCRWVvQSJ9.eyJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20" "vaWFwIiwic3ViIjoiYWNjb3VudHMuZ29vZ2xlLaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaDciLCJlbWFpbCI6ImFaaaaaaaazaaaaaaaaaaaaaaaaaaaaaa8iLCJhd" "WQiOiIvcHJvamVjdaaaaaaaaaaaaaaaaaayaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaayOegyMzkzOTQ2NCIsImV4cCI6MTU0Njk4MDUwNiwiaWF0Ijo" "xNTQ2OTc5OTA2LCJaaCI6InNwb3apaaaaaaaaaaaaaaapayJ9.NZwDs0U_fubYS" "OmYNJAI9ufgoC84zXOCzZkxclWBVXhb1dBVQHpO-VZW-lworDvKxX_BWqagKYTq" "wc4ELBcKTQ") environ = werkzeug_test.EnvironBuilder( path="/", headers={ "X-Goog-IAP-JWT-Assertion": assertion_header }, ).get_environ() request = wsgiapp.HttpRequest(environ) def Handler(request, *args, **kwargs): del request, args, kwargs # Unused. self.fail("Handler shouldn't have been executed.") manager = webauth.IAPWebAuthManager() response = manager.SecurityCheck(Handler, request) mock_get.assert_called_once_with( "https://www.gstatic.com/iap/verify/public_key") self.assertEqual(response.status_code, 401)
def environ(path='/', base_url=None, query_string=None, method='GET', input_stream=None, content_length=None, headers=None, data=None, charset='utf-8', mimetype=None): headers = headers or {} environ_builder = werkzeug_test.EnvironBuilder( path=path, base_url=base_url, query_string=query_string, method=method, input_stream=input_stream, content_length=content_length, headers=headers, data=data, charset=charset, mimetype=mimetype) return environ_builder.get_environ()
def setUp(self): self.app = Application( Leaf(endpoint='root', url='/', name='', handler=RootHandler), ) self.request_miss = test_utils.EnvironBuilder( path='/miss').get_request() self.request = test_utils.EnvironBuilder(path='/').get_request()
def testPassesThroughHomepageWhenAuthorizationHeaderIsMissing(self): environ = werkzeug_test.EnvironBuilder().get_environ() request = wsgiapp.HttpRequest(environ) response = self.manager.SecurityCheck(self.HandlerStub, request) self.assertEqual(response, self.success_response)
def testPlainText_appendsUtf8ToContentType(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, 'hello', 'text/plain') h = r.headers self.assertEqual(h.get('Content-Type'), 'text/plain; charset=utf-8')
def testHelloWorld(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, '<b>hello world</b>', 'text/html') self.assertEqual(r.status_code, 200) self.assertEqual(r.response[0], six.b('<b>hello world</b>'))
def testExpires_setsCruiseControl(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, '<b>hello world</b>', 'text/html', expires=60) self.assertEqual(r.headers.get('Cache-Control'), 'private, max-age=60')
def testJson_getsAutoSerialized(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, [1, 2, 3], 'application/json') self.assertEqual(r.response[0], b'[1, 2, 3]')
def test_select_http_method_post(self): request = test_utils.EnvironBuilder(method='POST') value = Handler(None, request).entrypoint() self.assertEqual(value, 'post')
def testHelloWorld(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, "<b>hello world</b>", "text/html") self.assertEqual(r.status_code, 200) self.assertEqual(r.response, [six.b("<b>hello world</b>")]) self.assertEqual(r.headers.get("Content-Length"), "18")
def testCsp_badGlobalDomainWhiteList(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) configs = [ "_CSP_SCRIPT_DOMAINS_WHITELIST", "_CSP_IMG_DOMAINS_WHITELIST", "_CSP_STYLE_DOMAINS_WHITELIST", "_CSP_FONT_DOMAINS_WHITELIST", "_CSP_FRAME_DOMAINS_WHITELIST", ] for config in configs: with mock.patch.object(http_util, config, ["http://tensorflow.org"]): with self.assertRaisesRegex( ValueError, "^Expected all whitelist to be a https URL"): http_util.Respond( q, "<b>hello</b>", "text/html", csp_scripts_sha256s=["abcd"], ) # Cannot grant more trust to a script from a remote source. with mock.patch.object( http_util, config, ["'strict-dynamic' 'unsafe-eval' https://tensorflow.org/"], ): with self.assertRaisesRegex( ValueError, "^Expected all whitelist to be a https URL"): http_util.Respond( q, "<b>hello</b>", "text/html", csp_scripts_sha256s=["abcd"], ) # Attempt to terminate the script-src to specify a new one that allows ALL! with mock.patch.object(http_util, config, ["https://tensorflow.org;script-src *"]): with self.assertRaisesRegex( ValueError, '^Expected whitelist domain to not contain ";"'): http_util.Respond( q, "<b>hello</b>", "text/html", csp_scripts_sha256s=["abcd"], ) # Attempt to use whitespace, delimit character, to specify a new one. with mock.patch.object(http_util, config, ["https://tensorflow.org *"]): with self.assertRaisesRegex( ValueError, "^Expected whitelist domain to not contain a whitespace", ): http_util.Respond( q, "<b>hello</b>", "text/html", csp_scripts_sha256s=["abcd"], )
def setUp(self): request = test_utils.EnvironBuilder().get_request() self.handler = Handler(None, request)
def testHelloWorld(self): q = wrappers.Request(wtest.EnvironBuilder().get_environ()) r = http_util.Respond(q, '<b>hello world</b>', 'text/html') self.assertEqual(r.status_code, 200) self.assertEqual(r.response, [six.b('<b>hello world</b>')]) self.assertEqual(r.headers.get('Content-Length'), '18')
def testAcceptGzip_alreadyCompressed_sendsPrecompressedResponse(self): gzip_text = _gzip(b'hello hello hello world') e = wtest.EnvironBuilder(headers={'Accept-Encoding': 'gzip'}).get_environ() q = wrappers.Request(e) r = http_util.Respond(q, gzip_text, 'text/plain', content_encoding='gzip') self.assertEqual(r.response, [gzip_text]) # Still singly zipped
def test_select_http_method_put(self): request = test_utils.EnvironBuilder(method='PUT') with self.assertRaises(exceptions.MethodNotAllowed): value = Handler(None, request).entrypoint()