예제 #1
0
 def setUp(self):
     super(ConfigTest, self).setUp()
     self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5))
     model.AuthGlobalConfig(
         key=model.root_key(),
         auth_db_rev=0,
     ).put()
예제 #2
0
 def make_auth_db():
   model.AuthGlobalConfig(key=model.root_key()).put()
   model.AuthIPWhitelistAssignments(
       key=model.ip_whitelist_assignments_key()).put()
   model.AuthGroup(key=model.group_key('A group')).put()
   model.AuthIPWhitelist(key=model.ip_whitelist_key('A whitelist')).put()
   model.replicate_auth_db()
예제 #3
0
    def test_update_oauth_config(self):
        self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5))

        @ndb.transactional
        def run(conf):
            return config._update_oauth_config(
                config.Revision('oauth_cfg_rev', 'http://url'), conf)

        model.AuthGlobalConfig(key=model.root_key()).put()
        # Pushing empty config to empty state -> no changes.
        self.assertFalse(run(config_pb2.OAuthConfig()))
        # Updating config.
        self.assertTrue(
            run(
                config_pb2.OAuthConfig(primary_client_id='a',
                                       primary_client_secret='b',
                                       client_ids=['c', 'd'])))
        self.assertEqual(
            {
                'auth_db_rev': 1,
                'auth_db_prev_rev': None,
                'modified_by': model.get_service_self_identity(),
                'modified_ts': datetime.datetime(2014, 1, 2, 3, 4, 5),
                'oauth_additional_client_ids': ['c', 'd'],
                'oauth_client_id': 'a',
                'oauth_client_secret': 'b',
            },
            model.root_key().get().to_dict())
        # Same config again -> no changes.
        self.assertFalse(
            run(
                config_pb2.OAuthConfig(primary_client_id='a',
                                       primary_client_secret='b',
                                       client_ids=['c', 'd'])))
    def test_works(self):
        PRIMARY_URL = 'https://primary'
        AUTH_DB_REV = 1234

        # Make some non-empty snapshot, its contents is not important.
        auth_db = replication.auth_db_snapshot_to_proto(
            make_snapshot_obj(global_config=model.AuthGlobalConfig(
                key=model.root_key(),
                oauth_client_id=u'some-client-id',
                oauth_client_secret=u'some-client-secret',
                oauth_additional_client_ids=[u'id1', u'id2'],
                token_server_url=u'https://example.com',
                security_config='security config blob')))

        # Store in 50-byte shards.
        shard_ids = replication.store_sharded_auth_db(auth_db, PRIMARY_URL,
                                                      AUTH_DB_REV, 50)
        self.assertEqual(2, len(shard_ids))

        # Verify keys look OK and the shard size is respected.
        for shard_id in shard_ids:
            self.assertEqual(len(shard_id), 16)
            shard = model.snapshot_shard_key(PRIMARY_URL, AUTH_DB_REV,
                                             shard_id).get()
            self.assertTrue(len(shard.blob) <= 50)

        # Verify it can be reassembled back.
        reassembled = replication.load_sharded_auth_db(PRIMARY_URL,
                                                       AUTH_DB_REV, shard_ids)
        self.assertEqual(reassembled, auth_db)
예제 #5
0
 def touch_all():
     make_group(
         name='A group',
         members=[ident('*****@*****.**'),
                  ident('*****@*****.**')],
         description='Blah',
         comment='New group')
     make_ip_whitelist(name='An IP whitelist',
                       subnets=['127.0.0.1/32'],
                       description='Bluh',
                       comment='New IP whitelist')
     a = model.AuthIPWhitelistAssignments(
         key=model.ip_whitelist_assignments_key(),
         assignments=[
             model.AuthIPWhitelistAssignments.Assignment(
                 identity=ident('*****@*****.**'),
                 ip_whitelist='An IP whitelist')
         ])
     a.record_revision(modified_by=ident('*****@*****.**'),
                       modified_ts=utils.utcnow(),
                       comment='New assignment')
     a.put()
     c = model.AuthGlobalConfig(key=model.root_key(),
                                oauth_client_id='client_id',
                                oauth_client_secret='client_secret',
                                oauth_additional_client_ids=['1', '2'])
     c.record_revision(modified_by=ident('*****@*****.**'),
                       modified_ts=utils.utcnow(),
                       comment='Config change')
     c.put()
예제 #6
0
    def test_fetch_auth_db(self):
        # Create AuthGlobalConfig.
        global_config = model.AuthGlobalConfig(key=model.root_key())
        global_config.oauth_client_id = '1'
        global_config.oauth_client_secret = 'secret'
        global_config.oauth_additional_client_ids = ['2', '3']
        global_config.put()

        # Create a bunch of (empty) groups.
        groups = [
            model.AuthGroup(key=model.group_key('Group A')),
            model.AuthGroup(key=model.group_key('Group B')),
        ]
        for group in groups:
            group.put()

        # And a bunch of secrets (local and global).
        local_secrets = [
            model.AuthSecret.bootstrap('local%d' % i, 'local')
            for i in (0, 1, 2)
        ]
        global_secrets = [
            model.AuthSecret.bootstrap('global%d' % i, 'global')
            for i in (0, 1, 2)
        ]

        # And IP whitelist.
        ip_whitelist_assignments = model.AuthIPWhitelistAssignments(
            key=model.ip_whitelist_assignments_key(),
            assignments=[
                model.AuthIPWhitelistAssignments.Assignment(
                    identity=model.Anonymous,
                    ip_whitelist='some ip whitelist',
                ),
            ])
        ip_whitelist_assignments.put()
        some_ip_whitelist = model.AuthIPWhitelist(
            key=model.ip_whitelist_key('some ip whitelist'),
            subnets=['127.0.0.1/32'])
        bots_ip_whitelist = model.AuthIPWhitelist(
            key=model.ip_whitelist_key('bots'), subnets=['127.0.0.1/32'])
        some_ip_whitelist.put()
        bots_ip_whitelist.put()

        # This all stuff should be fetched into AuthDB.
        auth_db = api.fetch_auth_db()
        self.assertEqual(global_config, auth_db.global_config)
        self.assertEqual(set(g.key.id() for g in groups), set(auth_db.groups))
        self.assertEqual(set(s.key.id() for s in local_secrets),
                         set(auth_db.secrets['local']))
        self.assertEqual(set(s.key.id() for s in global_secrets),
                         set(auth_db.secrets['global']))
        self.assertEqual(ip_whitelist_assignments,
                         auth_db.ip_whitelist_assignments)
        self.assertEqual(
            {
                'bots': bots_ip_whitelist,
                'some ip whitelist': some_ip_whitelist
            }, auth_db.ip_whitelists)
예제 #7
0
 def test_global_config_serialization(self):
     """Serializing snapshot with non-trivial AuthGlobalConfig."""
     snapshot = make_snapshot_obj(global_config=model.AuthGlobalConfig(
         key=model.root_key(),
         oauth_client_id='some-client-id',
         oauth_client_secret='some-client-secret',
         oauth_additional_client_ids=['id1', 'id2']))
     self.assert_serialization_works(snapshot)
예제 #8
0
 def create():
     c = model.AuthGlobalConfig(key=model.root_key(),
                                oauth_client_id='client_id',
                                oauth_client_secret='client_secret',
                                oauth_additional_client_ids=['1', '2'])
     c.record_revision(modified_by=ident('*****@*****.**'),
                       modified_ts=utils.utcnow(),
                       comment='Config change')
     c.put()
예제 #9
0
 def modify(**kwargs):
   e = model.root_key().get() or model.AuthGlobalConfig(key=model.root_key())
   e.populate(**kwargs)
   e.record_revision(
       modified_by=model.Identity.from_bytes('user:[email protected]'),
       modified_ts=utils.utcnow(),
       comment='Comment')
   e.put()
   model.replicate_auth_db()
예제 #10
0
 def test_is_allowed_oauth_client_id(self):
     global_config = model.AuthGlobalConfig(
         oauth_client_id='1', oauth_additional_client_ids=['2', '3'])
     auth_db = api.AuthDB(global_config=global_config)
     self.assertFalse(auth_db.is_allowed_oauth_client_id(None))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('1'))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('2'))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('3'))
     self.assertFalse(auth_db.is_allowed_oauth_client_id('4'))
예제 #11
0
 def test_global_config_serialization(self):
     """Serializing snapshot with non-trivial AuthGlobalConfig."""
     snapshot = make_snapshot_obj(global_config=model.AuthGlobalConfig(
         key=model.root_key(),
         oauth_client_id=u'some-client-id',
         oauth_client_secret=u'some-client-secret',
         oauth_additional_client_ids=[u'id1', u'id2'],
         token_server_url=u'https://example.com',
         security_config='security config blob'))
     self.assert_serialization_works(snapshot)
예제 #12
0
 def test_is_allowed_oauth_client_id(self):
     global_config = model.AuthGlobalConfig(
         oauth_client_id='1', oauth_additional_client_ids=['2', '3'])
     auth_db = api.AuthDB(global_config=global_config,
                          additional_client_ids=['local'])
     self.assertFalse(auth_db.is_allowed_oauth_client_id(None))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('1'))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('2'))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('3'))
     self.assertTrue(auth_db.is_allowed_oauth_client_id('local'))
     self.assertTrue(
         auth_db.is_allowed_oauth_client_id(api.API_EXPLORER_CLIENT_ID))
     self.assertFalse(auth_db.is_allowed_oauth_client_id('4'))
예제 #13
0
def make_snapshot_obj(global_config=None,
                      groups=None,
                      ip_whitelists=None,
                      ip_whitelist_assignments=None):
    """Returns AuthDBSnapshot with omitted fields set to default values."""
    return replication.AuthDBSnapshot(
        global_config=global_config
        or model.AuthGlobalConfig(key=model.root_key()),
        groups=groups or [],
        ip_whitelists=ip_whitelists or [],
        ip_whitelist_assignments=(
            ip_whitelist_assignments or model.AuthIPWhitelistAssignments(
                key=model.ip_whitelist_assignments_key())),
    )
예제 #14
0
def make_snapshot_obj(global_config=None,
                      groups=None,
                      ip_whitelists=None,
                      ip_whitelist_assignments=None):
    """Returns AuthDBSnapshot with empty list of groups and whitelists."""
    return replication.AuthDBSnapshot(
        global_config=global_config
        or model.AuthGlobalConfig(key=model.root_key(),
                                  oauth_client_id='oauth client id',
                                  oauth_client_secret='oauth client secret',
                                  token_server_url='token server',
                                  security_config='security config blob'),
        groups=groups or [],
        ip_whitelists=ip_whitelists or [],
        ip_whitelist_assignments=(
            ip_whitelist_assignments or model.AuthIPWhitelistAssignments(
                key=model.ip_whitelist_assignments_key())),
    )
예제 #15
0
 def test_global_config_serialization(self):
     """Serializing snapshot with non-trivial AuthGlobalConfig."""
     auth_db = make_auth_db_proto(global_config=model.AuthGlobalConfig(
         key=model.root_key(),
         oauth_client_id=u'some-client-id',
         oauth_client_secret=u'some-client-secret',
         oauth_additional_client_ids=[u'id1', u'id2'],
         token_server_url=u'https://example.com',
         security_config='security config blob'))
     self.assertEqual(
         auth_db,
         replication_pb2.AuthDB(
             oauth_client_id=u'some-client-id',
             oauth_client_secret=u'some-client-secret',
             oauth_additional_client_ids=[u'id1', u'id2'],
             token_server_url=u'https://example.com',
             security_config='security config blob',
             realms={'api_version': realms.API_VERSION},
         ))
    def test_success(self):
        self.mock_now(datetime.datetime(2015, 1, 1))

        def totimestamp(datetimeobj):
            return utils.datetime_to_timestamp(datetimeobj) / 10**6

        @ndb.tasklet
        def urlfetch(url, payload, **_rest):
            urlfetch.called = True
            self.assertEqual(
                url,
                'https://tokens.example.com/prpc/tokenserver.minter.TokenMinter/'
                'MintProjectToken')
            payload = json.loads(payload)
            self.assertEqual(payload, urlfetch.expected_payload)
            expiry = utils.utcnow() + datetime.timedelta(seconds=1800)
            res = {
                'accessToken': 'deadbeef',
                'serviceAccountEmail': '*****@*****.**',
                'expiry': expiry.isoformat('T') + 'Z',
            }

            raise ndb.Return(
                self.Response(200, json.dumps(res, sort_keys=True)))

        urlfetch.expected_payload = {
            u'luci_project': u'test-project',
            u'oauth_scope': [
                u'https://www.googleapis.com/auth/cloud-platform',
            ],
            u'min_validity_duration': 300,
            u'audit_tags': [],
        }

        urlfetch.called = False

        self.mock(service_account, '_urlfetch_async', urlfetch)

        model.AuthReplicationState(
            key=model.replication_state_key(),
            primary_url='https://auth.example.com',
            primary_id='example-app-id',
        ).put()
        model.AuthGlobalConfig(
            key=model.root_key(),
            token_server_url='https://tokens.example.com',
        ).put()

        args = {
            'project_id': 'test-project',
            'oauth_scopes': [
                u'https://www.googleapis.com/auth/cloud-platform',
            ],
            'min_validity_duration_sec': 300,
            'auth_request_func': service_account.authenticated_request_async,
        }
        result = project_tokens.project_token(**args)
        self.assertTrue(urlfetch.called)
        self.assertEqual(result['access_token'], 'deadbeef')
        self.assertEqual(
            result['exp_ts'],
            totimestamp(utils.utcnow() + datetime.timedelta(seconds=1800)))
예제 #17
0
    def test_non_empty(self):
        self.mock_now(datetime.datetime(2014, 1, 1, 1, 1, 1))

        state = model.AuthReplicationState(key=model.replication_state_key(),
                                           primary_id='blah',
                                           primary_url='https://blah',
                                           auth_db_rev=123)
        state.put()

        global_config = model.AuthGlobalConfig(
            key=model.root_key(),
            modified_ts=utils.utcnow(),
            modified_by=model.Identity.from_bytes('user:[email protected]'),
            oauth_client_id='oauth_client_id',
            oauth_client_secret='oauth_client_secret',
            oauth_additional_client_ids=['a', 'b'],
            token_server_url='https://token-server',
            security_config='security config blob')
        global_config.put()

        group = model.AuthGroup(
            key=model.group_key('Some group'),
            members=[model.Identity.from_bytes('user:[email protected]')],
            globs=[model.IdentityGlob.from_bytes('user:*@example.com')],
            nested=[],
            description='Some description',
            owners='owning-group',
            created_ts=utils.utcnow(),
            created_by=model.Identity.from_bytes('user:[email protected]'),
            modified_ts=utils.utcnow(),
            modified_by=model.Identity.from_bytes('user:[email protected]'))
        group.put()

        another = model.AuthGroup(key=model.group_key('Another group'),
                                  nested=['Some group'])
        another.put()

        ip_whitelist = model.AuthIPWhitelist(
            key=model.ip_whitelist_key('bots'),
            subnets=['127.0.0.1/32'],
            description='Some description',
            created_ts=utils.utcnow(),
            created_by=model.Identity.from_bytes('user:[email protected]'),
            modified_ts=utils.utcnow(),
            modified_by=model.Identity.from_bytes('user:[email protected]'))
        ip_whitelist.put()

        ip_whitelist_assignments = model.AuthIPWhitelistAssignments(
            key=model.ip_whitelist_assignments_key(),
            modified_ts=utils.utcnow(),
            modified_by=model.Identity.from_bytes('user:[email protected]'),
            assignments=[
                model.AuthIPWhitelistAssignments.Assignment(
                    identity=model.Identity.from_bytes(
                        'user:[email protected]'),
                    ip_whitelist='bots',
                    comment='some comment',
                    created_ts=utils.utcnow(),
                    created_by=model.Identity.from_bytes(
                        'user:[email protected]')),
            ])
        ip_whitelist_assignments.put()

        realms_globals = model.AuthRealmsGlobals(
            key=model.realms_globals_key(),
            permissions=[
                realms_pb2.Permission(name='luci.dev.p1'),
                realms_pb2.Permission(name='luci.dev.p2'),
            ])
        realms_globals.put()

        model.AuthProjectRealms(key=model.project_realms_key('proj_id1'),
                                realms=realms_pb2.Realms(api_version=1234),
                                config_rev='rev1',
                                perms_rev='rev1').put()
        model.AuthProjectRealms(key=model.project_realms_key('proj_id2'),
                                realms=realms_pb2.Realms(api_version=1234),
                                config_rev='rev2',
                                perms_rev='rev2').put()

        captured_state, snapshot = replication.new_auth_db_snapshot()

        expected_state = {
            'auth_db_rev': 123,
            'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
            'primary_id': u'blah',
            'primary_url': u'https://blah',
            'shard_ids': [],
        }
        self.assertEqual(expected_state, captured_state.to_dict())

        expected_snapshot = {
            'global_config': {
                '__id__':
                'root',
                '__parent__':
                None,
                'auth_db_rev':
                None,
                'auth_db_prev_rev':
                None,
                'modified_by':
                model.Identity(kind='user', name='*****@*****.**'),
                'modified_ts':
                datetime.datetime(2014, 1, 1, 1, 1, 1),
                'oauth_additional_client_ids': [u'a', u'b'],
                'oauth_client_id':
                u'oauth_client_id',
                'oauth_client_secret':
                u'oauth_client_secret',
                'security_config':
                'security config blob',
                'token_server_url':
                u'https://token-server',
            },
            'groups': [
                {
                    '__id__': 'Another group',
                    '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
                    'auth_db_rev': None,
                    'auth_db_prev_rev': None,
                    'created_by': None,
                    'created_ts': None,
                    'description': u'',
                    'globs': [],
                    'members': [],
                    'modified_by': None,
                    'modified_ts': None,
                    'nested': [u'Some group'],
                    'owners': u'administrators',
                },
                {
                    '__id__':
                    'Some group',
                    '__parent__':
                    ndb.Key('AuthGlobalConfig', 'root'),
                    'auth_db_rev':
                    None,
                    'auth_db_prev_rev':
                    None,
                    'created_by':
                    model.Identity(kind='user', name='*****@*****.**'),
                    'created_ts':
                    datetime.datetime(2014, 1, 1, 1, 1, 1),
                    'description':
                    u'Some description',
                    'globs':
                    [model.IdentityGlob(kind='user', pattern='*@example.com')],
                    'members':
                    [model.Identity(kind='user', name='*****@*****.**')],
                    'modified_by':
                    model.Identity(kind='user', name='*****@*****.**'),
                    'modified_ts':
                    datetime.datetime(2014, 1, 1, 1, 1, 1),
                    'nested': [],
                    'owners':
                    u'owning-group',
                },
            ],
            'ip_whitelists': [
                {
                    '__id__':
                    'bots',
                    '__parent__':
                    ndb.Key('AuthGlobalConfig', 'root'),
                    'auth_db_rev':
                    None,
                    'auth_db_prev_rev':
                    None,
                    'created_by':
                    model.Identity(kind='user', name='*****@*****.**'),
                    'created_ts':
                    datetime.datetime(2014, 1, 1, 1, 1, 1),
                    'description':
                    u'Some description',
                    'modified_by':
                    model.Identity(kind='user', name='*****@*****.**'),
                    'modified_ts':
                    datetime.datetime(2014, 1, 1, 1, 1, 1),
                    'subnets': [u'127.0.0.1/32'],
                },
            ],
            'ip_whitelist_assignments': {
                '__id__':
                'default',
                '__parent__':
                ndb.Key('AuthGlobalConfig', 'root'),
                'assignments': [
                    {
                        'comment':
                        u'some comment',
                        'created_by':
                        model.Identity(kind='user',
                                       name='*****@*****.**'),
                        'created_ts':
                        datetime.datetime(2014, 1, 1, 1, 1, 1),
                        'identity':
                        model.Identity(kind='user',
                                       name='*****@*****.**'),
                        'ip_whitelist':
                        u'bots',
                    },
                ],
                'auth_db_rev':
                None,
                'auth_db_prev_rev':
                None,
                'modified_by':
                model.Identity(kind='user', name='*****@*****.**'),
                'modified_ts':
                datetime.datetime(2014, 1, 1, 1, 1, 1),
            },
            'realms_globals': {
                '__id__':
                'globals',
                '__parent__':
                ndb.Key('AuthGlobalConfig', 'root'),
                'auth_db_prev_rev':
                None,
                'auth_db_rev':
                None,
                'modified_by':
                None,
                'modified_ts':
                None,
                'permissions': [
                    realms_pb2.Permission(name='luci.dev.p1'),
                    realms_pb2.Permission(name='luci.dev.p2'),
                ],
            },
            'project_realms': [{
                '__id__':
                'proj_id1',
                '__parent__':
                ndb.Key('AuthGlobalConfig', 'root'),
                'auth_db_prev_rev':
                None,
                'auth_db_rev':
                None,
                'config_rev':
                u'rev1',
                'perms_rev':
                u'rev1',
                'modified_by':
                None,
                'modified_ts':
                None,
                'realms':
                realms_pb2.Realms(api_version=1234),
            }, {
                '__id__':
                'proj_id2',
                '__parent__':
                ndb.Key('AuthGlobalConfig', 'root'),
                'auth_db_prev_rev':
                None,
                'auth_db_rev':
                None,
                'config_rev':
                u'rev2',
                'perms_rev':
                u'rev2',
                'modified_by':
                None,
                'modified_ts':
                None,
                'realms':
                realms_pb2.Realms(api_version=1234),
            }],
        }
        self.assertEqual(expected_snapshot, snapshot_to_dict(snapshot))
예제 #18
0
  def test_non_empty(self):
    self.mock_now(datetime.datetime(2014, 1, 1, 1, 1, 1))

    state = model.AuthReplicationState(
        key=model.replication_state_key(),
        primary_id='blah',
        primary_url='https://blah',
        auth_db_rev=123)
    state.put()

    global_config = model.AuthGlobalConfig(
        key=model.root_key(),
        modified_ts=utils.utcnow(),
        modified_by=model.Identity.from_bytes('user:[email protected]'),
        oauth_client_id='oauth_client_id',
        oauth_client_secret='oauth_client_secret',
        oauth_additional_client_ids=['a', 'b'])
    global_config.put()

    group = model.AuthGroup(
        key=model.group_key('Some group'),
        members=[model.Identity.from_bytes('user:[email protected]')],
        globs=[model.IdentityGlob.from_bytes('user:*@example.com')],
        nested=[],
        description='Some description',
        owners='owning-group',
        created_ts=utils.utcnow(),
        created_by=model.Identity.from_bytes('user:[email protected]'),
        modified_ts=utils.utcnow(),
        modified_by=model.Identity.from_bytes('user:[email protected]'))
    group.put()

    another = model.AuthGroup(
        key=model.group_key('Another group'),
        nested=['Some group'])
    another.put()

    global_secret = model.AuthSecret(
        id='global_secret',
        parent=model.secret_scope_key('global'),
        values=['1234', '5678'],
        modified_ts=utils.utcnow(),
        modified_by=model.Identity.from_bytes('user:[email protected]'))
    global_secret.put()

    # Local secret should not appear in a snapshot.
    local_secret = model.AuthSecret(
        id='local_secret',
        parent=model.secret_scope_key('local'),
        values=['1234', '5678'],
        modified_ts=utils.utcnow(),
        modified_by=model.Identity.from_bytes('user:[email protected]'))
    local_secret.put()

    ip_whitelist = model.AuthIPWhitelist(
        key=model.ip_whitelist_key('bots'),
        subnets=['127.0.0.1/32'],
        description='Some description',
        created_ts=utils.utcnow(),
        created_by=model.Identity.from_bytes('user:[email protected]'),
        modified_ts=utils.utcnow(),
        modified_by=model.Identity.from_bytes('user:[email protected]'))
    ip_whitelist.put()

    ip_whitelist_assignments = model.AuthIPWhitelistAssignments(
        key=model.ip_whitelist_assignments_key(),
        modified_ts=utils.utcnow(),
        modified_by=model.Identity.from_bytes('user:[email protected]'),
        assignments=[
          model.AuthIPWhitelistAssignments.Assignment(
            identity=model.Identity.from_bytes('user:[email protected]'),
            ip_whitelist='bots',
            comment='some comment',
            created_ts=utils.utcnow(),
            created_by=model.Identity.from_bytes('user:[email protected]')),
        ])
    ip_whitelist_assignments.put()

    captured_state, snapshot = replication.new_auth_db_snapshot()

    expected_state =  {
      'auth_db_rev': 123,
      'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
      'primary_id': u'blah',
      'primary_url': u'https://blah',
    }
    self.assertEqual(expected_state, captured_state.to_dict())

    expected_snapshot = {
      'global_config': {
        '__id__': 'root',
        '__parent__': None,
        'auth_db_rev': None,
        'auth_db_prev_rev': None,
        'modified_by': model.Identity(kind='user', name='*****@*****.**'),
        'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
        'oauth_additional_client_ids': [u'a', u'b'],
        'oauth_client_id': u'oauth_client_id',
        'oauth_client_secret': u'oauth_client_secret',
      },
      'groups': [
        {
          '__id__': 'Another group',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': None,
          'description': u'',
          'globs': [],
          'members': [],
          'modified_by': None,
          'modified_ts': None,
          'nested': [u'Some group'],
          'owners': u'administrators',
        },
        {
          '__id__': 'Some group',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': model.Identity(kind='user', name='*****@*****.**'),
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'Some description',
          'globs': [model.IdentityGlob(kind='user', pattern='*@example.com')],
          'members': [model.Identity(kind='user', name='*****@*****.**')],
          'modified_by': model.Identity(
              kind='user', name='*****@*****.**'),
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'nested': [],
          'owners': u'owning-group',
        },
      ],
      'secrets': [
        {
          '__id__': 'global_secret',
          '__parent__': ndb.Key(
              'AuthGlobalConfig', 'root', 'AuthSecretScope', 'global'),
          'modified_by': model.Identity(
              kind='user', name='*****@*****.**'),
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'values': ['1234', '5678'],
        },
      ],
      'ip_whitelists': [
        {
          '__id__': 'bots',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': model.Identity(kind='user', name='*****@*****.**'),
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'Some description',
          'modified_by': model.Identity(
              kind='user', name='*****@*****.**'),
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'subnets': [u'127.0.0.1/32'],
        },
      ],
      'ip_whitelist_assignments': {
        '__id__': 'default',
        '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
        'assignments': [
          {
            'comment': u'some comment',
            'created_by': model.Identity(
                kind='user', name='*****@*****.**'),
            'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
            'identity': model.Identity(
                kind='user', name='*****@*****.**'),
            'ip_whitelist': u'bots',
          },
        ],
        'auth_db_rev': None,
        'auth_db_prev_rev': None,
        'modified_by': model.Identity(kind='user', name='*****@*****.**'),
        'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
      },
    }
    self.assertEqual(expected_snapshot, snapshot_to_dict(snapshot))
예제 #19
0
  def test_works(self):
    self.mock_now(datetime.datetime(2014, 1, 1, 1, 1, 1))
    self.configure_as_replica(0)

    # Prepare auth db state.
    model.AuthGlobalConfig(
        key=model.root_key(),
        modified_ts=utils.utcnow(),
        oauth_client_id='oauth_client_id',
        oauth_client_secret='oauth_client_secret',
        oauth_additional_client_ids=['a', 'b']).put()

    def group(name, **kwargs):
      return model.AuthGroup(
          key=model.group_key(name),
          created_ts=utils.utcnow(),
          modified_ts=utils.utcnow(),
          **kwargs)
    group('Modify').put()
    group('Delete').put()
    group('Keep').put()

    def secret(name, scope, **kwargs):
      return model.AuthSecret(
          id=name, parent=model.secret_scope_key(scope), **kwargs)
    secret('modify', 'global').put()
    secret('delete', 'global').put()
    secret('keep', 'global').put()
    secret('local', 'local').put()

    def ip_whitelist(name, **kwargs):
      return model.AuthIPWhitelist(
          key=model.ip_whitelist_key(name),
          created_ts=utils.utcnow(),
          modified_ts=utils.utcnow(),
          **kwargs)
    ip_whitelist('modify').put()
    ip_whitelist('delete').put()
    ip_whitelist('keep').put()

    def assignment(ident, ip_whitelist):
      return model.AuthIPWhitelistAssignments.Assignment(
          identity=model.Identity.from_bytes(ident),
          ip_whitelist=ip_whitelist,
          created_ts=utils.utcnow(),
          comment='comment')
    model.AuthIPWhitelistAssignments(
        key=model.ip_whitelist_assignments_key(),
        modified_ts=utils.utcnow(),
        assignments=[
          assignment('user:[email protected]', 'modify'),
          assignment('user:[email protected]', 'delete'),
          assignment('user:[email protected]', 'keep'),
        ]).put()

    # Prepare snapshot.
    snapshot = replication.AuthDBSnapshot(
        global_config=model.AuthGlobalConfig(
            key=model.root_key(),
            modified_ts=utils.utcnow(),
            oauth_client_id='another_oauth_client_id',
            oauth_client_secret='another_oauth_client_secret',
            oauth_additional_client_ids=[]),
        groups=[
          group('New'),
          group('Modify', description='blah', owners='some-other-owners'),
          group('Keep'),
        ],
        secrets=[
          secret('new', 'global'),
          secret('modify', 'global', values=['1234']),
          secret('keep', 'global'),
        ],
        ip_whitelists=[
          ip_whitelist('new', subnets=['1.1.1.1/32']),
          ip_whitelist('modify', subnets=['127.0.0.1/32', '192.168.0.1/32']),
          ip_whitelist('keep'),
        ],
        ip_whitelist_assignments=model.AuthIPWhitelistAssignments(
            key=model.ip_whitelist_assignments_key(),
            assignments=[
              assignment('user:[email protected]', 'new'),
              assignment('user:[email protected]', 'modify'),
              assignment('user:[email protected]', 'keep'),
            ],
        ),
    )

    # Push it.
    updated, state = replication.replace_auth_db(
        auth_db_rev=1234,
        modified_ts=datetime.datetime(2014, 1, 1, 1, 1, 1),
        snapshot=snapshot)
    self.assertTrue(updated)
    expected_state = {
      'auth_db_rev': 1234,
      'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
      'primary_id': u'primary',
      'primary_url': u'https://primary',
    }
    self.assertEqual(expected_state, state.to_dict())

    # Verify expected Auth db state.
    current_state, current_snapshot = replication.new_auth_db_snapshot()
    self.assertEqual(expected_state, current_state.to_dict())

    expected_auth_db = {
      'global_config': {
        '__id__': 'root',
        '__parent__': None,
        'auth_db_rev': None,
        'auth_db_prev_rev': None,
        'modified_by': None,
        'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
        'oauth_additional_client_ids': [],
        'oauth_client_id': u'another_oauth_client_id',
        'oauth_client_secret': u'another_oauth_client_secret'},
      'groups': [
        {
          '__id__': 'Keep',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'',
          'globs': [],
          'members': [],
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'nested': [],
          'owners': u'administrators',
        },
        {
          '__id__': 'Modify',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'blah',
          'globs': [],
          'members': [],
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'nested': [],
          'owners': u'some-other-owners',
        },
        {
          '__id__': 'New',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'',
          'globs': [],
          'members': [],
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'nested': [],
          'owners': u'administrators',
        },
      ],
      'secrets': [
        {
          '__id__': 'keep',
          '__parent__': ndb.Key(
              'AuthGlobalConfig', 'root', 'AuthSecretScope', 'global'),
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'values': [],
        },
        {
          '__id__': 'modify',
          '__parent__': ndb.Key(
              'AuthGlobalConfig', 'root', 'AuthSecretScope', 'global'),
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'values': ['1234'],
        },
        {
          '__id__': 'new',
          '__parent__': ndb.Key(
              'AuthGlobalConfig', 'root', 'AuthSecretScope', 'global'),
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'values': [],
        },
      ],
      'ip_whitelists': [
        {
          '__id__': 'keep',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'',
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'subnets': [],
        },
        {
          '__id__': 'modify',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'',
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'subnets': [u'127.0.0.1/32', u'192.168.0.1/32'],
        },
        {
          '__id__': 'new',
          '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
          'auth_db_rev': None,
          'auth_db_prev_rev': None,
          'created_by': None,
          'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'description': u'',
          'modified_by': None,
          'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
          'subnets': [u'1.1.1.1/32'],
        },
      ],
      'ip_whitelist_assignments': {
        '__id__': 'default',
        '__parent__': ndb.Key('AuthGlobalConfig', 'root'),
        'assignments': [
          {
            'comment': u'comment',
            'created_by': None,
            'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
            'identity': model.Identity(kind='user', name='*****@*****.**'),
            'ip_whitelist': u'new',
          },
          {
            'comment': u'comment',
            'created_by': None,
            'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
            'identity': model.Identity(kind='user', name='*****@*****.**'),
            'ip_whitelist': u'modify',
          },
          {
            'comment': u'comment',
            'created_by': None,
            'created_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
            'identity': model.Identity(kind='user', name='*****@*****.**'),
            'ip_whitelist': u'keep',
          },
        ],
        'auth_db_rev': None,
        'auth_db_prev_rev': None,
        'modified_by': None,
        'modified_ts': None, # not transfered currently in proto
      },
    }
    self.assertEqual(expected_auth_db, snapshot_to_dict(current_snapshot))

    # Ensure local secret was left intact.
    local_secrets = model.AuthSecret.query(
        ancestor=model.secret_scope_key('local'))
    expected_local_secrets = [
      {
        '__id__': 'local',
        '__parent__': ndb.Key(
            'AuthGlobalConfig', 'root', 'AuthSecretScope', 'local'),
        'modified_by': None,
        'modified_ts': datetime.datetime(2014, 1, 1, 1, 1, 1),
        'values': [],
      },
    ]
    self.assertEqual(
        expected_local_secrets, [entity_to_dict(s) for s in local_secrets])
예제 #20
0
    def test_success(self):
        self.mock_now(datetime.datetime(2015, 1, 1))

        @ndb.tasklet
        def urlfetch(url, payload, **_rest):
            urlfetch.called = True
            self.assertEqual(
                url,
                'https://tokens.example.com/prpc/tokenserver.minter.TokenMinter/'
                'MintDelegationToken')
            payload = json.loads(payload)
            self.assertEqual(payload, urlfetch.expected_payload)
            res = {
                'token': 'deadbeef',
                'serviceVersion': 'app-id/version-id',
                'delegationSubtoken': {
                    'kind': 'BEARER_DELEGATION_TOKEN',
                    'validityDuration': payload['validityDuration'],
                    'subtokenId': '12345',
                },
            }
            raise ndb.Return(
                self.Response(200, ")]}'\n" + json.dumps(res, sort_keys=True)))

        urlfetch.expected_payload = {
            u'audience': [
                u'REQUESTOR',
                u'group:g',
                u'user:[email protected]',
                u'user:[email protected]',
            ],
            u'services': [u'https://example.com', u'service:1', u'service:2'],
            u'delegatedIdentity':
            u'user:[email protected]',
            u'tags': [u'a:b', u'c:d'],
            u'validityDuration':
            3000,
        }
        urlfetch.called = False

        self.mock(delegation, '_urlfetch_async', urlfetch)

        model.AuthReplicationState(
            key=model.replication_state_key(),
            primary_url='https://auth.example.com',
            primary_id='example-app-id',
        ).put()
        model.AuthGlobalConfig(
            key=model.root_key(),
            token_server_url='https://tokens.example.com',
        ).put()

        args = {
            'audience': [
                'user:[email protected]',
                model.Identity('user', '*****@*****.**'),
                'group:g',
                'REQUESTOR',
            ],
            'services': [
                'service:1',
                model.Identity('service', '2'),
                'https://example.com',
            ],
            'max_validity_duration_sec':
            3000,
            'impersonate':
            model.Identity('user', '*****@*****.**'),
            'tags': ['c:d', 'a:b'],
        }
        result = delegation.delegate(**args)
        self.assertTrue(urlfetch.called)
        self.assertEqual(result.token, 'deadbeef')
        self.assertEqual(result.expiry,
                         utils.utcnow() + datetime.timedelta(seconds=3000))

        # Get from cache.
        urlfetch.called = False
        delegation.delegate(**args)
        self.assertFalse(urlfetch.called)

        # Get from cache with larger validity duration.
        urlfetch.called = False
        args['min_validity_duration_sec'] = 5000
        args['max_validity_duration_sec'] = 5000
        urlfetch.expected_payload['validityDuration'] = 5000
        result = delegation.delegate(**args)
        self.assertTrue(urlfetch.called)
        self.assertEqual(result.token, 'deadbeef')
        self.assertEqual(result.expiry,
                         utils.utcnow() + datetime.timedelta(seconds=5000))
        self.assertTrue(urlfetch.called)
예제 #21
0
    def test_success(self):

        model.AuthReplicationState(
            key=model.replication_state_key(),
            primary_url='https://auth.example.com',
            primary_id='example-app-id',
        ).put()
        model.AuthGlobalConfig(
            key=model.root_key(),
            token_server_url='https://tokens.example.com',
        ).put()

        calls = []

        @ndb.tasklet
        def mocked_urlfetch_async(*args, **_):
            mocked_urlfetch_async.called = True
            calls.append(('urlfetch', args))
            expiry = utils.utcnow() + datetime.timedelta(seconds=1800)
            res = {
                'accessToken': 'someaccesstoken',
                'serviceAccountEmail': '*****@*****.**',
                'expiry': expiry.isoformat('T') + 'Z'
            }
            raise ndb.Return(
                self.Response(200, json.dumps(res, sort_keys=True)))

        self.mock(service_account, '_urlfetch_async', mocked_urlfetch_async)

        # non-cached
        token = service_account.get_project_access_token(
            project_id='project1',
            scopes=['https://www.googleapis.com/auth/cloud-platform'],
        )
        self.assertEqual(token[0], 'someaccesstoken')
        self.assertEqual(
            token[1],
            self.totimestamp(utils.utcnow() +
                             datetime.timedelta(seconds=1800)))
        self.assertTrue(mocked_urlfetch_async.called)
        mocked_urlfetch_async.called = False

        # cached
        token = service_account.get_project_access_token(
            project_id='project1',
            scopes=['https://www.googleapis.com/auth/cloud-platform'],
        )
        self.assertEqual(token[0], 'someaccesstoken')
        self.assertEqual(
            token[1],
            self.totimestamp(utils.utcnow() +
                             datetime.timedelta(seconds=1800)))
        self.assertFalse(mocked_urlfetch_async.called)

        # cache expired
        token = service_account.get_project_access_token(
            project_id='project1',
            scopes=['https://www.googleapis.com/auth/cloud-platform'],
            min_lifetime_sec=1800,
        )
        self.assertEqual(token[0], 'someaccesstoken')
        self.assertEqual(
            token[1],
            self.totimestamp(utils.utcnow() +
                             datetime.timedelta(seconds=1800)))
        self.assertTrue(mocked_urlfetch_async.called)
예제 #22
0
    def test_fetch_auth_db(self):
        # Client IDs callback. Disable config.ensure_configured() since it overrides
        # _additional_client_ids_cb after we mock it.
        self.mock(config, 'ensure_configured', lambda: None)
        self.mock(api, '_additional_client_ids_cb',
                  lambda: ['', 'cb_client_id'])
        self.mock(api, 'get_web_client_id', lambda: 'web_client_id')

        # Create AuthGlobalConfig.
        global_config = model.AuthGlobalConfig(key=model.root_key())
        global_config.oauth_client_id = '1'
        global_config.oauth_client_secret = 'secret'
        global_config.oauth_additional_client_ids = ['2', '3']
        global_config.put()

        # Create a bunch of (empty) groups.
        groups = [
            model.AuthGroup(key=model.group_key('Group A')),
            model.AuthGroup(key=model.group_key('Group B')),
        ]
        for group in groups:
            group.put()

        # And a bunch of secrets.
        secrets = [
            model.AuthSecret.bootstrap('local%d' % i) for i in (0, 1, 2)
        ]

        # And IP whitelist.
        ip_whitelist_assignments = model.AuthIPWhitelistAssignments(
            key=model.ip_whitelist_assignments_key(),
            assignments=[
                model.AuthIPWhitelistAssignments.Assignment(
                    identity=model.Anonymous,
                    ip_whitelist='some ip whitelist',
                ),
            ])
        ip_whitelist_assignments.put()
        some_ip_whitelist = model.AuthIPWhitelist(
            key=model.ip_whitelist_key('some ip whitelist'),
            subnets=['127.0.0.1/32'])
        bots_ip_whitelist = model.AuthIPWhitelist(
            key=model.ip_whitelist_key('bots'), subnets=['127.0.0.1/32'])
        some_ip_whitelist.put()
        bots_ip_whitelist.put()

        # This all stuff should be fetched into AuthDB.
        auth_db = api.fetch_auth_db()
        self.assertEqual(global_config, auth_db.global_config)
        self.assertEqual(set(g.key.id() for g in groups), set(auth_db.groups))
        self.assertEqual(set(s.key.id() for s in secrets),
                         set(auth_db.secrets))
        self.assertEqual(ip_whitelist_assignments,
                         auth_db.ip_whitelist_assignments)
        self.assertEqual(
            {
                'bots': bots_ip_whitelist,
                'some ip whitelist': some_ip_whitelist
            }, auth_db.ip_whitelists)
        self.assertTrue(auth_db.is_allowed_oauth_client_id('1'))
        self.assertTrue(auth_db.is_allowed_oauth_client_id('cb_client_id'))
        self.assertTrue(auth_db.is_allowed_oauth_client_id('web_client_id'))
        self.assertFalse(auth_db.is_allowed_oauth_client_id(''))