def testRaisesIfUsernameSetInRequest(self): user = user_plugin.ApiGrrUser(username=u"foo") with self.assertRaises(ValueError): self.handler.Handle( user, context=api_call_context.ApiCallContext(username="******")) user = user_plugin.ApiGrrUser(username=u"bar") with self.assertRaises(ValueError): self.handler.Handle( user, context=api_call_context.ApiCallContext(username=u"foo"))
def testRendersTraitsPassedInConstructor(self): result = self.handler.Handle( None, context=api_call_context.ApiCallContext(username=u"foo")) self.assertFalse(result.interface_traits.create_hunt_action_enabled) handler = user_plugin.ApiGetOwnGrrUserHandler( interface_traits=user_plugin.ApiGrrUserInterfaceTraits( create_hunt_action_enabled=True)) result = handler.Handle( None, context=api_call_context.ApiCallContext(username=u"foo")) self.assertTrue(result.interface_traits.create_hunt_action_enabled)
def GrantCronJobApproval(self, cron_job_id, requestor=None, approval_id=None, approver="approver", admin=True): """Grants an approval for a given cron job.""" if not requestor: requestor = self.token.username if not approval_id: raise ValueError("approval_id can't be empty.") self.CreateUser(requestor) if admin: self.CreateAdminUser(approver) else: self.CreateUser(approver) args = api_user.ApiGrantCronJobApprovalArgs(cron_job_id=cron_job_id, username=requestor, approval_id=approval_id) handler = api_user.ApiGrantCronJobApprovalHandler() handler.Handle( args, context=api_call_context.ApiCallContext(username=approver))
def RequestCronJobApproval(self, cron_job_id, requestor=None, reason=None, email_cc_address=None, approver=u"approver"): """Request cron job approval for a given cron job.""" if not requestor: requestor = self.token.username if not reason: reason = self.token.reason self.CreateUser(requestor) self.CreateUser(approver) args = api_user.ApiCreateCronJobApprovalArgs( cron_job_id=cron_job_id, approval=api_user.ApiCronJobApproval( reason=reason, notified_users=[approver], email_cc_addresses=([email_cc_address] if email_cc_address else []))) handler = api_user.ApiCreateCronJobApprovalHandler() result = handler.Handle( args, context=api_call_context.ApiCallContext(username=requestor)) return result.id
def testRendersSettingsForUserCorrespondingToContext(self): data_store.REL_DB.WriteGRRUser("foo", ui_mode="ADVANCED", canary_mode=True) result = self.handler.Handle( None, context=api_call_context.ApiCallContext(username=u"foo")) self.assertEqual(result.settings.mode, "ADVANCED") self.assertEqual(result.settings.canary_mode, True)
def FlowHasBeenStarted(): handler = api_flow.ApiListFlowsHandler() flows = handler.Handle(api_flow.ApiListFlowsArgs( client_id=self.client_id, top_flows_only=True), context=api_call_context.ApiCallContext( username=self.test_username)).items return flows[0] if len(flows) == 1 else None
def GrantHuntApproval(self, hunt_id, requestor=None, approval_id=None, approver=u"approver", admin=True): """Grants an approval for a given hunt.""" if not approval_id: raise ValueError("approval_id can't be empty.") if not requestor: requestor = self.test_username self.CreateUser(requestor) if admin: self.CreateAdminUser(approver) else: self.CreateUser(approver) args = api_user.ApiGrantHuntApprovalArgs(hunt_id=hunt_id, username=requestor, approval_id=approval_id) handler = api_user.ApiGrantHuntApprovalHandler() handler.Handle( args, context=api_call_context.ApiCallContext(username=approver))
def setUp(self): super().setUp() self.handler = hunt_plugin.ApiCreatePerClientFileCollectionHuntHandler( ) self.context = api_call_context.ApiCallContext(username="******") self.client_id = db_test_utils.InitializeClient(data_store.REL_DB)
def RequestHuntApproval(self, hunt_id, requestor=None, reason="Running tests", email_cc_address=None, approver=u"approver"): """Request hunt approval for a given hunt.""" if not requestor: requestor = self.test_username self.CreateUser(requestor) self.CreateUser(approver) args = api_user.ApiCreateHuntApprovalArgs( hunt_id=hunt_id, approval=api_user.ApiHuntApproval( reason=reason, notified_users=[approver], email_cc_addresses=([email_cc_address] if email_cc_address else []))) handler = api_user.ApiCreateHuntApprovalHandler() result = handler.Handle( args, context=api_call_context.ApiCallContext(username=requestor)) return result.id
def RequestClientApproval(self, client_id, reason=None, requestor=None, email_cc_address=None, approver=u"approver"): """Create an approval request to be sent to approver.""" if not requestor: requestor = self.token.username if not reason: reason = self.token.reason self.CreateUser(requestor) self.CreateUser(approver) args = api_user.ApiCreateClientApprovalArgs( client_id=client_id, approval=api_user.ApiClientApproval( reason=reason, notified_users=[approver], email_cc_addresses=([email_cc_address] if email_cc_address else []))) handler = api_user.ApiCreateClientApprovalHandler() result = handler.Handle( args, context=api_call_context.ApiCallContext(username=requestor)) return result.id
def testDeleteHuntIsAccessCheckedIfUserIsNotCreator(self): hunt_id = self.CreateHunt(creator=self.context.username) args = api_hunt.ApiDeleteHuntArgs(hunt_id=hunt_id) self.CheckMethodIsAccessChecked( self.router.DeleteHunt, "CheckHuntAccess", args=args, context=api_call_context.ApiCallContext("foo"))
def testClientApprovalMultiLabel(self): """Multi-label client approval test. This client requires one legal and two prod admin approvals. The requester must also be in the prod admin group. """ self.TouchFile(self.client_prod_id, "fs/os/foo") self.context = api_call_context.ApiCallContext("prod1") webauth.WEBAUTH_MANAGER.SetUserName(self.context.username) # No approvals yet, this should fail. self.assertRaises( grr_api_errors.AccessForbiddenError, self.api.Client(self.client_prod_id).File("fs/os/foo").Get) approval_id = self.RequestAndGrantClientApproval( self.client_prod_id, requestor=self.context.username) # This approval from "approver" isn't enough. self.assertRaises( grr_api_errors.AccessForbiddenError, self.api.Client(self.client_prod_id).File("fs/os/foo").Get) # Grant an approval from a user in the legal_approval list in # approvers.yaml self.GrantClientApproval(self.client_prod_id, requestor=self.context.username, approval_id=approval_id, approver=u"legal1") # We have "approver", "legal1": not enough. self.assertRaises( grr_api_errors.AccessForbiddenError, self.api.Client(self.client_prod_id).File("fs/os/foo").Get) # Grant an approval from a user in the prod_admin_approval list in # approvers.yaml self.GrantClientApproval(self.client_prod_id, requestor=self.context.username, approval_id=approval_id, approver=u"prod2") # We have "approver", "legal1", "prod2": not enough. self.assertRaises( grr_api_errors.AccessForbiddenError, self.api.Client(self.client_prod_id).File("fs/os/foo").Get) self.GrantClientApproval(self.client_prod_id, requestor=self.context.username, approval_id=approval_id, approver=u"prod3") # We have "approver", "legal1", "prod2", "prod3": we should have # access. self.api.Client(self.client_prod_id).File("fs/os/foo").Get()
def testSetsSettingsForUserCorrespondingToToken(self): settings = user_plugin.GUISettings(mode="ADVANCED", canary_mode=True) user = user_plugin.ApiGrrUser(settings=settings) self.handler.Handle( user, context=api_call_context.ApiCallContext(username=u"foo")) u = data_store.REL_DB.ReadGRRUser(u"foo") self.assertEqual(settings.mode, u.ui_mode) self.assertEqual(settings.canary_mode, u.canary_mode)
def setUp(self): super().setUp() self.client_id = test_lib.TEST_CLIENT_ID self.context = api_call_context.ApiCallContext("test") self.delegate_mock = mock.MagicMock() self.access_checker_mock = mock.MagicMock() self.router = api_router.ApiCallRouterWithApprovalChecks( delegate=self.delegate_mock, access_checker=self.access_checker_mock)
def _BuildContext(self, request): """Build the API call context from the request.""" # We assume that request.user contains the username that we can trust. # No matter what authentication method is used, the WebAuthManager is # responsible for authenticating the userand setting request.user to # a correct value (see gui/webauth.py). # # The context that's built here will be later used to find an API router, # get the ApiCallHandler from the router, and then to call the handler's # Handle() method. API router will be responsible for all the ACL checks. return api_call_context.ApiCallContext(request.user)
def testNestedFlowsAppearCorrectlyAfterAutoRefresh(self): self.Open("/#/clients/%s" % self.client_id) # Ensure auto-refresh updates happen every second. self.GetJavaScriptValue( "grrUi.flow.flowsListDirective.setAutoRefreshInterval(1000);") flow_1 = flow_test_lib.StartFlow( gui_test_lib.FlowWithOneLogStatement, self.client_id, creator=self.token.username) # Go to the flows page without refreshing the page, so that # AUTO_REFRESH_INTERVAL_MS setting is not reset and wait # until flow_1 is visible. self.Click("css=a[grrtarget='client.flows']") self.WaitUntil(self.IsElementPresent, "css=tr:contains('%s')" % flow_1) # Create a recursive flow_2 that will appear after auto-refresh. flow_2 = flow_test_lib.StartFlow( gui_test_lib.RecursiveTestFlow, self.client_id, creator=self.token.username) # Check that the flow we started in the background appears in the list. self.WaitUntil(self.IsElementPresent, "css=tr:contains('%s')" % flow_2) # Check that flow_2 is the row 1 (row 0 is the table header). self.WaitUntil( self.IsElementPresent, "css=grr-client-flows-list tr:nth(1):contains('%s')" % flow_2) # Click on a nested flow. self.Click("css=tr:contains('%s') span.tree_branch" % flow_2) # Check that flow_2 is still row 1 and that nested flows occupy next # rows. self.WaitUntil( self.IsElementPresent, "css=grr-client-flows-list tr:nth(1):contains('%s')" % flow_2) flow_data = api_flow.ApiGetFlowHandler().Handle( api_flow.ApiGetFlowArgs(client_id=self.client_id, flow_id=flow_2), context=api_call_context.ApiCallContext("test")) for index, nested_flow in enumerate(flow_data.nested_flows): self.WaitUntil( self.IsElementPresent, "css=grr-client-flows-list tr:nth(%d):contains('%s')" % (index + 2, nested_flow.flow_id))
def setUp(self): super(ApiGetExportedHuntResultsHandlerTest, self).setUp() self.handler = hunt_plugin.ApiGetExportedHuntResultsHandler() self.context = api_call_context.ApiCallContext("test") self.hunt_id = self.StartHunt( flow_runner_args=rdf_flow_runner.FlowRunnerArgs( flow_name=flow_test_lib.DummyFlowWithSingleReply.__name__), client_rate=0) self.client_ids = self.SetupClients(5) # Ensure that clients are processed sequentially - this way the test won't # depend on the order of results in the collection (which is normally # random). for cid in self.client_ids: self.RunHunt(client_ids=[cid], failrate=-1)
def testLogHttpAdminUIAccess(self): request = wsgiapp.HttpRequest({ "wsgi.url_scheme": "http", "SERVER_NAME": "foo.bar", "SERVER_PORT": "1234" }) request.user = "******" response = http_response.HttpResponse( status=202, headers={"X-API-Method": "TestMethod"}, context=api_call_context.ApiCallContext( username=request.user, approval=acl_test_lib.BuildClientApprovalRequest( reason="foo/test1234", requestor_username=request.user))) self.l.LogHttpAdminUIAccess(request, response) self.assertIn("foo/test1234", self.log)
def testApproverInputShowsAutocompletion(self): self.CreateUser("sanchezrick") # add decoy user, to assure that autocompletion results are based on the # query self.CreateUser("aaa") client_id = self.SetupClient(0) self.Open("/#/clients/%s/host-info" % client_id) # We do not have an approval, so we need to request one. self.Click("css=button[name=requestApproval]") input_selector = "css=grr-approver-input input" self.Type(input_selector, "sanchez") self.WaitUntil(self.IsElementPresent, "css=[uib-typeahead-popup]:contains(sanchezrick)") self.GetElement(input_selector).send_keys(keys.Keys.ENTER) self.WaitUntilEqual("sanchezrick, ", self.GetValue, input_selector + ":text") self.Type("css=grr-request-approval-dialog input[name=acl_reason]", "Test") self.Click( "css=grr-request-approval-dialog button[name=Proceed]:not([disabled])" ) # "Request Approval" dialog should go away self.WaitUntilNot(self.IsVisible, "css=.modal-open") handler = user_plugin.ApiListClientApprovalsHandler() args = user_plugin.ApiListClientApprovalsArgs(client_id=client_id) res = handler.Handle(args=args, context=api_call_context.ApiCallContext( self.test_username)) self.assertLen(res.items, 1) self.assertLen(res.items[0].notified_users, 1) self.assertEqual(res.items[0].notified_users[0], "sanchezrick")
def main(argv=None): del argv # Unused. if flags.FLAGS.version: print("GRR API shell {}".format( config_server.VERSION["packageversion"])) return config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT) config.CONFIG.AddContext( contexts.CONSOLE_CONTEXT, "Context applied when running the console binary.") server_startup.Init() fleetspeak_connector.Init() username = flags.FLAGS.username if not username: username = os.environ["USER"] if not username: print("Username has to be specified with either --username flag or " "USER environment variable.") sys.exit(1) grrapi = api.GrrApi(connector=api_shell_raw_access_lib.RawConnector( context=api_call_context.ApiCallContext(username=username), page_size=flags.FLAGS.page_size)) if flags.FLAGS.exec_code and flags.FLAGS.exec_file: print("--exec_code --exec_file flags can't be supplied together.") sys.exit(1) elif flags.FLAGS.exec_code: # pylint: disable=exec-used exec(flags.FLAGS.exec_code, dict(grrapi=grrapi)) # pylint: enable=exec-used elif flags.FLAGS.exec_file: api_shell_lib.ExecFile(flags.FLAGS.exec_file, grrapi) else: api_shell_lib.IPShell([sys.argv[0]], user_ns=dict(grrapi=grrapi))
def GrantClientApproval(self, client_id, requestor=None, approval_id=None, approver=u"approver", admin=True): """Grant an approval from approver to delegate. Args: client_id: Client id. requestor: username string of the user receiving approval. approval_id: id of the approval to grant. approver: username string of the user granting approval. admin: If True, make approver an admin user. Raises: ValueError: if approval_id is empty. """ if not approval_id: raise ValueError("approval_id can't be empty.") if not requestor: requestor = self.token.username self.CreateUser(requestor) if admin: self.CreateAdminUser(approver) else: self.CreateUser(approver) if not requestor: requestor = self.token.username args = api_user.ApiGrantClientApprovalArgs(client_id=client_id, username=requestor, approval_id=approval_id) handler = api_user.ApiGrantClientApprovalHandler() handler.Handle( args, context=api_call_context.ApiCallContext(username=approver))
def setUp(self): super(ApiIntegrationTest, self).setUp() api_auth_manager.InitializeApiAuthManager() self.context = api_call_context.ApiCallContext("api_test_robot_user") self.token.username = self.context.username try: webauth.WEBAUTH_MANAGER.SetUserName(self.context.username) except AttributeError: # Only the NullWebAuthManager supports SetUserName pass self.CreateUser(self.context.username) self.port = ApiIntegrationTest.server_port self.endpoint = "http://localhost:%s" % self.port self.api = grr_api.InitHttp(api_endpoint=self.endpoint) poll_stubber = utils.MultiStubber( (grr_api_utils, "DEFAULT_POLL_INTERVAL", 0.1), (grr_api_utils, "DEFAULT_POLL_TIMEOUT", 10)) poll_stubber.Start() self.addCleanup(poll_stubber.Stop)
def ListCronJobApprovals(self, requestor=None): requestor = requestor or self.token.username handler = api_user.ApiListCronJobApprovalsHandler() return handler.Handle( api_user.ApiListCronJobApprovalsArgs(), context=api_call_context.ApiCallContext(username=requestor)).items
def setUp(self): super(ApiListArtifactsHandlerTest, self).setUp() self.handler = artifact_plugin.ApiListArtifactsHandler() self.context = api_call_context.ApiCallContext("test")
def setUp(self): super(ApiCallHandlerTest, self).setUp() # The user we use for API tests. self.context = api_call_context.ApiCallContext("api_test_user") self.token.username = self.context.username acl_test_lib.CreateUser(self.context.username)
def testRaisesIfTraitsSetInRequest(self): user = user_plugin.ApiGrrUser( interface_traits=user_plugin.ApiGrrUserInterfaceTraits()) with self.assertRaises(ValueError): self.handler.Handle( user, context=api_call_context.ApiCallContext(username=u"foo"))
def setUp(self): super().setUp() self.client_id = self.SetupClient(0) self.context = api_call_context.ApiCallContext("test")
def setUp(self): super().setUp() self.client_id = self.SetupClient(0) self.context = api_call_context.ApiCallContext("test") self.another_username = "******" self.CreateUser(self.another_username)
def _CreateContext( db: abstract_db.Database) -> api_call_context.ApiCallContext: username = "".join(random.choice("abcdef") for _ in range(8)) db.WriteGRRUser(username) return api_call_context.ApiCallContext(username)
def setUp(self): super().setUp() self.handler = flow_plugin.ApiGetExportedFlowResultsHandler() self.client_id = self.SetupClient(0) self.context = api_call_context.ApiCallContext("test")