import pytest from app import create_app, db from app.models import User, Agent @pytest.fixture def client(): app = create_app('testing') app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' with app.test_client() as client: with app.app_context(): db.create_all() # Create users admin = User(username='admin', role='admin', email='admin@example.com') admin.set_password('admin123') user1 = User(username='user1', role='user', email='user1@example.com') user1.set_password('user123') db.session.add_all([admin, user1]) # Create agents a1 = Agent(name='A1', dify_app_id='app1') a2 = Agent(name='A2', dify_app_id='app2') db.session.add_all([a1, a2]) # Grant A1 to user1, but not A2 user1.agents.append(a1) db.session.commit() yield client db.session.remove() db.drop_all() def get_headers(client, username, password): res = client.post('/api/user/login', json={'username': username, 'password': password}) data = res.get_json() return { 'X-User-Id': str(data['id']), 'X-Username': data['username'], 'X-Role': data['role'], 'Content-Type': 'application/json' } def test_agent_permission_check(client): headers_user = get_headers(client, 'user1', 'user123') headers_admin = get_headers(client, 'admin', 'admin123') with client.application.app_context(): a1_id = Agent.query.filter_by(name='A1').first().id a2_id = Agent.query.filter_by(name='A2').first().id # 1. User access allowed agent res = client.get(f'/api/user/agents/{a1_id}', headers=headers_user) assert res.status_code == 200 # 2. User access denied agent res = client.get(f'/api/user/agents/{a2_id}', headers=headers_user) assert res.status_code == 403 # 3. Admin access any agent res = client.get(f'/api/user/agents/{a2_id}', headers=headers_admin) assert res.status_code == 200