Esempio n. 1
0
  def test_not_allowed_account(self):
    now = datetime.datetime(2010, 1, 2, 3, 4, 5)
    self.mock_now(now)

    self.mock_json_request(
        expected_url='https://tokens.example.com/prpc/'
            'tokenserver.minter.TokenMinter/MintOAuthTokenGrant',
        expected_payload=None,
      response=net.Error('bad', 403, 'Token server error message'))

    with self.assertRaises(auth.AuthorizationError) as err:
      service_accounts.get_oauth_token_grant(
          '*****@*****.**', datetime.timedelta(seconds=3600))
    self.assertEqual('Token server error message', str(err.exception))
Esempio n. 2
0
    def new(self, request):
        """Creates a new task.

    The task will be enqueued in the tasks list and will be executed at the
    earliest opportunity by a bot that has at least the dimensions as described
    in the task request.
    """
        sb = (request.properties.secret_bytes
              if request.properties is not None else None)
        if sb is not None:
            request.properties.secret_bytes = "HIDDEN"
        logging.debug('%s', request)
        if sb is not None:
            request.properties.secret_bytes = sb

        try:
            request_obj, secret_bytes = message_conversion.new_task_request_from_rpc(
                request, utils.utcnow())
            for index in xrange(request_obj.num_task_slices):
                apply_server_property_defaults(
                    request_obj.task_slice(index).properties)
            task_request.init_new_request(
                request_obj, acl.can_schedule_high_priority_tasks())
            # We need to call the ndb.Model pre-put check earlier because the
            # following checks assume that the request itself is valid and could crash
            # otherwise.
            request_obj._pre_put_hook()
        except (datastore_errors.BadValueError, TypeError, ValueError) as e:
            logging.exception(
                'Here\'s what was wrong in the user new task request:')
            raise endpoints.BadRequestException(e.message)

        # Make sure the caller is actually allowed to schedule the task before
        # asking the token server for a service account token.
        task_scheduler.check_schedule_request_acl(request_obj)

        # If request_obj.service_account is an email, contact the token server to
        # generate "OAuth token grant" (or grab a cached one). By doing this we
        # check that the given service account usage is allowed by the token server
        # rules at the time the task is posted. This check is also performed later
        # (when running the task), when we get the actual OAuth access token.
        if service_accounts.is_service_account(request_obj.service_account):
            if not service_accounts.has_token_server():
                raise endpoints.BadRequestException(
                    'This Swarming server doesn\'t support task service accounts '
                    'because Token Server URL is not configured')
            max_lifetime_secs = request_obj.max_lifetime_secs
            try:
                # Note: this raises AuthorizationError if the user is not allowed to use
                # the requested account or service_accounts.InternalError if something
                # unexpected happens.
                duration = datetime.timedelta(seconds=max_lifetime_secs)
                request_obj.service_account_token = (
                    service_accounts.get_oauth_token_grant(
                        service_account=request_obj.service_account,
                        validity_duration=duration))
            except service_accounts.InternalError as exc:
                raise endpoints.InternalServerErrorException(exc.message)

        # If the user only wanted to evaluate scheduling the task, but not actually
        # schedule it, return early without a task_id.
        if request.evaluate_only:
            request_obj._pre_put_hook()
            return swarming_rpcs.TaskRequestMetadata(
                request=message_conversion.task_request_to_rpc(request_obj))

        try:
            result_summary = task_scheduler.schedule_request(
                request_obj, secret_bytes)
        except (datastore_errors.BadValueError, TypeError, ValueError) as e:
            raise endpoints.BadRequestException(e.message)

        previous_result = None
        if result_summary.deduped_from:
            previous_result = message_conversion.task_result_to_rpc(
                result_summary, False)

        return swarming_rpcs.TaskRequestMetadata(
            request=message_conversion.task_request_to_rpc(request_obj),
            task_id=task_pack.pack_result_summary_key(result_summary.key),
            task_result=previous_result)
Esempio n. 3
0
  def test_happy_path(self):
    now = datetime.datetime(2010, 1, 2, 3, 4, 5)
    self.mock_now(now)

    expiry = now + datetime.timedelta(seconds=7200)
    calls = self.mock_json_request(
        expected_url='https://tokens.example.com/prpc/'
            'tokenserver.minter.TokenMinter/MintOAuthTokenGrant',
        expected_payload={
          'auditTags': [
            'swarming:gae_request_id:7357B3D7091D',
            'swarming:service_version:sample-app/v1a',
          ],
          'endUser': '******',
          'serviceAccount': '*****@*****.**',
          'validityDuration': 7200,
        },
        response={
          'grantToken': 'totally_real_token',
          'serviceVersion': 'token-server-id/ver',
          'expiry': expiry.isoformat() + 'Z',
        })

    # Minting new one.
    tok = service_accounts.get_oauth_token_grant(
        '*****@*****.**', datetime.timedelta(seconds=3600))
    self.assertEqual('totally_real_token', tok)
    self.assertEqual(1, len(calls))

    # Using cached one.
    tok = service_accounts.get_oauth_token_grant(
        '*****@*****.**', datetime.timedelta(seconds=3600))
    self.assertEqual('totally_real_token', tok)
    self.assertEqual(1, len(calls))  # no new calls

    # Minting another one when the cache expires.
    now += datetime.timedelta(seconds=7200)
    self.mock_now(now)

    expiry = now + datetime.timedelta(seconds=7200)
    calls = self.mock_json_request(
        expected_url='https://tokens.example.com/prpc/'
            'tokenserver.minter.TokenMinter/MintOAuthTokenGrant',
        expected_payload={
          'auditTags': [
            'swarming:gae_request_id:7357B3D7091D',
            'swarming:service_version:sample-app/v1a',
          ],
          'endUser': '******',
          'serviceAccount': '*****@*****.**',
          'validityDuration': 7200,
        },
        response={
          'grantToken': 'another_totally_real_token',
          'serviceVersion': 'token-server-id/ver',
          'expiry': expiry.isoformat() + 'Z',
        })

    tok = service_accounts.get_oauth_token_grant(
        '*****@*****.**', datetime.timedelta(seconds=3600))
    self.assertEqual('another_totally_real_token', tok)
    self.assertEqual(1, len(calls))