企业微信
This commit is contained in:
1 parent
46ac70f4c5
commit
a9fc852abb
33 files changed
+4875
-106
No files matched your search
@@ -1,9 +1,26 @@
|
||||
import pytest
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_persisted_settings(monkeypatch, tmp_path):
|
||||
"""Prevent tests from inheriting the developer's local ``backend/.env``.
|
||||
|
||||
``apply_env_settings`` is called eagerly in ``create_app`` and on every
|
||||
request via the ``before_request`` hook. If the dev's real ``backend/.env``
|
||||
contains ``WECOM_AUTO_CREATE_USER=true`` (or any other WECOM_* override),
|
||||
those values would silently overwrite the explicit ``app.config.update(...)``
|
||||
calls inside test fixtures. Routing reads to a tmp path makes every test
|
||||
start from a clean slate.
|
||||
"""
|
||||
from app import env_persistence
|
||||
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', tmp_path / 'isolated.env')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
from app import create_app, db
|
||||
|
||||
app = create_app('testing')
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
@@ -11,10 +28,12 @@ def app():
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
return app.test_client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers():
|
||||
return {
|
||||
@@ -23,6 +42,7 @@ def admin_headers():
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_headers():
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
def test_login_succeeds_when_login_audit_insert_fails(app, client, monkeypatch):
|
||||
with app.app_context():
|
||||
admin = User(
|
||||
username='admin',
|
||||
email='admin@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
employee_id='EMP-ADMIN',
|
||||
)
|
||||
admin.set_password('admin123')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
|
||||
def _raise_audit_error(payload):
|
||||
raise RuntimeError('simulated audit insert failure')
|
||||
|
||||
monkeypatch.setattr(user_api, '_execute_login_audit_insert', _raise_audit_error)
|
||||
|
||||
response = client.post('/api/user/login', json={
|
||||
'username': 'admin',
|
||||
'password': 'admin123',
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()
|
||||
assert data['username'] == 'admin'
|
||||
assert data['role'] == 'admin'
|
||||
@@ -0,0 +1,21 @@
|
||||
import base64
|
||||
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
|
||||
|
||||
|
||||
def test_wecom_aes_roundtrip():
|
||||
corp_id = 'ww1234567890abcdef'
|
||||
aes_key_b64 = base64.b64encode(b'0' * 32).decode('ascii').rstrip('=')
|
||||
xml = '<xml><MsgType><![CDATA[event]]></MsgType></xml>'
|
||||
cipher = encrypt_wecom_aes(xml, aes_key_b64, corp_id)
|
||||
plain = decrypt_wecom_aes(cipher, aes_key_b64, corp_id)
|
||||
assert plain == xml
|
||||
|
||||
|
||||
def test_wecom_msg_signature():
|
||||
token = 'hxops-token'
|
||||
ts = '123'
|
||||
nonce = 'abc'
|
||||
encrypt = 'cipher-text'
|
||||
sig = sha1_hex([token, ts, nonce, encrypt])
|
||||
assert sha1_hex([token, ts, nonce, encrypt]) == sig
|
||||
@@ -0,0 +1,96 @@
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.api import admin as admin_api
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
class DummyResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
def test_wecom_debug_user_by_code_returns_raw_user_and_match_preview(client, app, admin_headers, monkeypatch):
|
||||
app.config.update(
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
WECOM_AUTO_CREATE_USER=False,
|
||||
WECOM_MATCH_RULES='employee_id',
|
||||
WECOM_MATCH_OPERATOR='AND',
|
||||
WECOM_EMPLOYEE_ID_SOURCE='userid',
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1')
|
||||
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': 'EMP001'})
|
||||
if 'cgi-bin/user/get' in url:
|
||||
return DummyResponse({
|
||||
'errcode': 0,
|
||||
'userid': 'EMP001',
|
||||
'name': '王超',
|
||||
'mobile': '13800138000',
|
||||
'email': 'emp001@example.com',
|
||||
})
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(admin_api.requests, 'get', fake_get)
|
||||
|
||||
res = client.post(
|
||||
'/api/admin/wecom/debug-user-by-code',
|
||||
json={'code': 'real-code-from-wecom'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['auth_info']['userid'] == 'EMP001'
|
||||
assert data['wecom_user']['name'] == '王超'
|
||||
assert data['normalized_identity']['employee_id'] == 'EMP001'
|
||||
assert data['match_preview']['decision'] == 'matched_existing_user'
|
||||
assert data['match_preview']['matched_users'][0]['username'] == 'emp001'
|
||||
|
||||
|
||||
def test_wecom_debug_user_by_code_returns_scope_error_when_only_openid(client, app, admin_headers, monkeypatch):
|
||||
app.config.update(
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1')
|
||||
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'})
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(admin_api.requests, 'get', fake_get)
|
||||
|
||||
res = client.post(
|
||||
'/api/admin/wecom/debug-user-by-code',
|
||||
json={'code': 'code-out-of-scope'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 401
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert data['openid'] == 'oExternal_xx'
|
||||
@@ -0,0 +1,247 @@
|
||||
import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
class DummyResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wecom_input_verify_client():
|
||||
app = create_app('testing')
|
||||
app.config.update(
|
||||
TESTING=True,
|
||||
SQLALCHEMY_DATABASE_URI='sqlite:///:memory:',
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
WECOM_REDIRECT_URI='https://example.com/workspace',
|
||||
WECOM_AUTO_CREATE_USER=False,
|
||||
WECOM_MATCH_RULES='employee_id,mobile',
|
||||
WECOM_MATCH_OPERATOR='AND',
|
||||
WECOM_FIRST_LOGIN_BIND_MODE='input_verify',
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS='employee_id,mobile,email',
|
||||
WECOM_EMPLOYEE_ID_SOURCE='userid',
|
||||
WECOM_MOBILE_NORMALIZE=True,
|
||||
)
|
||||
with app.test_client() as client:
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_BIND_SESSION_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
yield client, app
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_BIND_SESSION_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
|
||||
|
||||
def _issue_state(client):
|
||||
res = client.get('/api/user/wecom/authorize-url', query_string={'redirect_uri': 'https://example.com/workspace'})
|
||||
assert res.status_code == 200
|
||||
return res.get_json()['state']
|
||||
|
||||
|
||||
def _mock_wecom_requests(monkeypatch, userid, *, name='Test User', mobile=None, email=None):
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/gettoken' in url:
|
||||
return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200})
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': userid})
|
||||
if 'cgi-bin/user/get' in url:
|
||||
payload = {'errcode': 0, 'userid': userid, 'name': name}
|
||||
if mobile is not None:
|
||||
payload['mobile'] = mobile
|
||||
if email is not None:
|
||||
payload['email'] = email
|
||||
return DummyResponse(payload)
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(user_api.requests, 'get', fake_get)
|
||||
|
||||
|
||||
def _start_input_verify_login(client, monkeypatch, *, userid, name='Test User', mobile=None, email=None):
|
||||
_mock_wecom_requests(monkeypatch, userid=userid, name=name, mobile=mobile, email=email)
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-input-verify', 'state': state})
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_BIND_INPUT_REQUIRED'
|
||||
assert data['binding_token']
|
||||
return data
|
||||
|
||||
|
||||
def test_wecom_login_returns_input_verify_prompt_on_first_login(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP001',
|
||||
name='王超',
|
||||
mobile='13800138000',
|
||||
email='emp001@example.com',
|
||||
)
|
||||
|
||||
assert data['allowed_fields'] == ['employee_id', 'mobile', 'email']
|
||||
assert data['wecom_name'] == '王超'
|
||||
assert data['wecom_userid'] == 'EMP001'
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='emp001').first()
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
def test_wecom_complete_bind_binds_user_by_selected_field(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
login_data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP001',
|
||||
name='王超',
|
||||
mobile='13800138000',
|
||||
email='emp001@example.com',
|
||||
)
|
||||
|
||||
bind_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'employee_id',
|
||||
'value': 'EMP001',
|
||||
})
|
||||
assert bind_res.status_code == 200
|
||||
bind_data = bind_res.get_json()
|
||||
assert bind_data['username'] == 'emp001'
|
||||
assert bind_data['source'] == 'wecom'
|
||||
assert bind_data['bind_status'] == 'input_verified_and_bound'
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='emp001').first()
|
||||
assert user.wecom_userid == 'EMP001'
|
||||
assert user.real_name == '王超'
|
||||
|
||||
expired_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'employee_id',
|
||||
'value': 'EMP001',
|
||||
})
|
||||
assert expired_res.status_code == 400
|
||||
assert expired_res.get_json()['error_code'] == 'WECOM_BIND_SESSION_EXPIRED'
|
||||
|
||||
|
||||
def test_wecom_complete_bind_returns_not_found_when_value_does_not_match(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
login_data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP001',
|
||||
name='王超',
|
||||
mobile='13800138000',
|
||||
email='emp001@example.com',
|
||||
)
|
||||
|
||||
bind_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'email',
|
||||
'value': 'missing@example.com',
|
||||
})
|
||||
assert bind_res.status_code == 404
|
||||
bind_data = bind_res.get_json()
|
||||
assert bind_data['error_code'] == 'WECOM_BIND_INPUT_NOT_FOUND'
|
||||
|
||||
|
||||
def test_wecom_complete_bind_returns_ambiguous_for_mobile_raw_and_normalized_duplicates(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user1 = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user1.set_password('pwd')
|
||||
user2 = User(
|
||||
username='emp002',
|
||||
email='emp002@example.com',
|
||||
employee_id='EMP002',
|
||||
phone_number='+86 13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user2.set_password('pwd')
|
||||
db.session.add_all([user1, user2])
|
||||
db.session.commit()
|
||||
|
||||
login_data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP009',
|
||||
name='李雷',
|
||||
mobile='13800990000',
|
||||
email='emp009@example.com',
|
||||
)
|
||||
|
||||
bind_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'mobile',
|
||||
'value': '+86 13800138000',
|
||||
})
|
||||
assert bind_res.status_code == 409
|
||||
bind_data = bind_res.get_json()
|
||||
assert bind_data['error_code'] == 'WECOM_BIND_INPUT_AMBIGUOUS'
|
||||
assert bind_data['candidate_count'] == 2
|
||||
@@ -0,0 +1,195 @@
|
||||
import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
class DummyResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wecom_client():
|
||||
app = create_app('testing')
|
||||
app.config.update(
|
||||
TESTING=True,
|
||||
SQLALCHEMY_DATABASE_URI='sqlite:///:memory:',
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
WECOM_REDIRECT_URI='https://example.com/workspace',
|
||||
WECOM_AUTO_CREATE_USER=False,
|
||||
WECOM_MATCH_RULES='employee_id,mobile',
|
||||
WECOM_MATCH_OPERATOR='AND',
|
||||
WECOM_EMPLOYEE_ID_SOURCE='userid',
|
||||
WECOM_MOBILE_NORMALIZE=True,
|
||||
)
|
||||
with app.test_client() as client:
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
yield client, app
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
|
||||
|
||||
def _issue_state(client):
|
||||
res = client.get('/api/user/wecom/authorize-url', query_string={'redirect_uri': 'https://example.com/workspace'})
|
||||
assert res.status_code == 200
|
||||
return res.get_json()['state']
|
||||
|
||||
|
||||
def _mock_wecom_requests(monkeypatch, userid, mobile=None, email=None):
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/gettoken' in url:
|
||||
return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200})
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
# 真实 WeCom /cgi-bin/auth/getuserinfo 返回的是小写 userid (企业成员),
|
||||
# 外部联系人/不在可见范围则返回 openid 而无 userid。
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': userid})
|
||||
if 'cgi-bin/user/get' in url:
|
||||
payload = {'errcode': 0, 'userid': userid, 'name': 'Test User'}
|
||||
if mobile is not None:
|
||||
payload['mobile'] = mobile
|
||||
if email is not None:
|
||||
payload['email'] = email
|
||||
return DummyResponse(payload)
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(user_api.requests, 'get', fake_get)
|
||||
|
||||
|
||||
def test_wecom_login_match_existing_user_by_employee_and_mobile(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP001', mobile='13800138000', email='emp001@example.com')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-1', 'state': state})
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['bind_status'] == 'matched_and_bound'
|
||||
assert data['username'] == 'emp001'
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='emp001').first()
|
||||
assert user.wecom_userid == 'EMP001'
|
||||
|
||||
|
||||
def test_wecom_login_bind_required_when_no_match(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP404', mobile='13800999999', email='emp404@example.com')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-2', 'state': state})
|
||||
assert res.status_code == 403
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_BIND_REQUIRED'
|
||||
assert data['reason'] == 'bind_required'
|
||||
|
||||
with app.app_context():
|
||||
assert db.session.query(User).count() == 0
|
||||
|
||||
|
||||
def test_wecom_login_ambiguous_match_returns_409(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
with app.app_context():
|
||||
app.config['WECOM_MATCH_OPERATOR'] = 'OR'
|
||||
user1 = User(
|
||||
username='u1',
|
||||
email='u1@example.com',
|
||||
employee_id='EMP777',
|
||||
phone_number='13900000001',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user1.set_password('pwd')
|
||||
user2 = User(
|
||||
username='u2',
|
||||
email='u2@example.com',
|
||||
employee_id='EMP888',
|
||||
phone_number='13888888888',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user2.set_password('pwd')
|
||||
db.session.add_all([user1, user2])
|
||||
db.session.commit()
|
||||
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP777', mobile='13888888888')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-3', 'state': state})
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_MATCH_AMBIGUOUS'
|
||||
assert data['reason'] == 'ambiguous_match'
|
||||
assert data['candidate_count'] == 2
|
||||
|
||||
|
||||
def test_wecom_login_missing_match_attr_returns_422(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='u3',
|
||||
email='u3@example.com',
|
||||
employee_id='EMP003',
|
||||
phone_number='13800380000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP003', mobile=None, email='u3@example.com')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-4', 'state': state})
|
||||
assert res.status_code == 422
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_MATCH_ATTR_MISSING'
|
||||
assert data['missing_field'] == 'mobile'
|
||||
|
||||
|
||||
def test_wecom_login_returns_clear_error_when_user_not_in_agent_scope(wecom_client, monkeypatch):
|
||||
"""当 /auth/getuserinfo 返回 errcode=0 但只有 openid(登录者不在自建应用的可见范围)时,
|
||||
必须给出明确的中文提示而不是 'WeCom auth failed: ok'。
|
||||
"""
|
||||
client, app = wecom_client
|
||||
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/gettoken' in url:
|
||||
return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200})
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'})
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(user_api.requests, 'get', fake_get)
|
||||
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-out-of-scope', 'state': state})
|
||||
assert res.status_code == 401
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert '可见范围' in data['error']
|
||||
assert 'WeCom auth failed: ok' not in data['error']
|
||||
@@ -0,0 +1,107 @@
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def test_wecom_provision_create_bind_and_set_permissions(client, app, admin_headers):
|
||||
with app.app_context():
|
||||
a1 = Agent(name='A1', type='api', dify_app_id='app-a1', dify_api_key='k-a1', is_active=True)
|
||||
a2 = Agent(name='A2', type='api', dify_app_id='app-a2', dify_api_key='k-a2', is_active=True)
|
||||
db.session.add_all([a1, a2])
|
||||
db.session.commit()
|
||||
a1_id, a2_id = a1.id, a2.id
|
||||
|
||||
payload = {
|
||||
'create_user': True,
|
||||
'user': {
|
||||
'username': 'emp2001',
|
||||
'real_name': 'Emp 2001',
|
||||
'employee_id': 'EMP2001',
|
||||
'phone_number': '13800111222',
|
||||
'email': 'emp2001@example.com',
|
||||
'department': 'IT',
|
||||
'role': 'user',
|
||||
'status': 'active',
|
||||
},
|
||||
'bind': {
|
||||
'wecom_userid': 'EMP2001',
|
||||
'wecom_unionid': 'UNION-2001',
|
||||
},
|
||||
'agent_ids': [a1_id, a2_id],
|
||||
}
|
||||
res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 201
|
||||
body = res.get_json()
|
||||
assert body['status'] == 'ok'
|
||||
assert body['permission_updated'] is True
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, body['user_id'])
|
||||
assert user is not None
|
||||
assert user.wecom_userid == 'EMP2001'
|
||||
assert user.wecom_unionid == 'UNION-2001'
|
||||
assert sorted([a.id for a in user.agents]) == sorted([a1_id, a2_id])
|
||||
|
||||
|
||||
def test_wecom_provision_conflict_should_not_create_new_user(client, app, admin_headers):
|
||||
with app.app_context():
|
||||
existing = User(username='bound_user', email='bound@example.com', role='user', status='active', wecom_userid='WX-DUP')
|
||||
existing.set_password('pwd')
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
payload = {
|
||||
'create_user': True,
|
||||
'user': {
|
||||
'username': 'new_to_rollback',
|
||||
'email': 'new_to_rollback@example.com',
|
||||
},
|
||||
'bind': {
|
||||
'wecom_userid': 'WX-DUP',
|
||||
},
|
||||
'agent_ids': [],
|
||||
}
|
||||
res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 400
|
||||
assert 'already bound to user' in res.get_json()['error']
|
||||
|
||||
with app.app_context():
|
||||
should_not_exist = db.session.query(User).filter_by(username='new_to_rollback').first()
|
||||
assert should_not_exist is None
|
||||
|
||||
|
||||
def test_wecom_provision_bind_existing_user(client, app, admin_headers):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='existing_user',
|
||||
email='existing@example.com',
|
||||
employee_id='EMP3001',
|
||||
phone_number='13800990011',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
agent = Agent(name='A3', type='api', dify_app_id='app-a3', dify_api_key='k-a3', is_active=True)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
user_id = user.id
|
||||
agent_id = agent.id
|
||||
|
||||
payload = {
|
||||
'create_user': False,
|
||||
'user_id': user_id,
|
||||
'bind': {
|
||||
'wecom_userid': 'EMP3001',
|
||||
},
|
||||
'agent_ids': [agent_id],
|
||||
}
|
||||
res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()
|
||||
assert body['binding'] == 'updated'
|
||||
assert body['permission_updated'] is True
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, user_id)
|
||||
assert user.wecom_userid == 'EMP3001'
|
||||
assert [a.id for a in user.agents] == [agent_id]
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
from dotenv import dotenv_values
|
||||
|
||||
from app import db, env_persistence
|
||||
from app.models import AppSetting
|
||||
|
||||
|
||||
def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path):
|
||||
env_file = tmp_path / '.env'
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
|
||||
|
||||
payload = {
|
||||
'enabled': True,
|
||||
'corp_id': 'ww-persisted',
|
||||
'agent_id': '1000999',
|
||||
'secret': 'persist-secret',
|
||||
'redirect_uri': 'https://example.com/workspace',
|
||||
'auto_create_user': False,
|
||||
'match_rules': 'employee_id,email',
|
||||
'match_operator': 'OR',
|
||||
'employee_id_source': 'extattr:job_no',
|
||||
'mobile_normalize': False,
|
||||
'callback_token': 'cb-token',
|
||||
'encoding_aes_key': 'enc-key',
|
||||
'callback_url': 'https://example.com/api/user/wecom/callback',
|
||||
'homepage_url': 'https://example.com/workspace',
|
||||
'trusted_domain': 'example.com',
|
||||
'public_base_url': 'https://example.com',
|
||||
}
|
||||
|
||||
res = client.put('/api/admin/wecom/system-settings', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
|
||||
saved = dotenv_values(env_file)
|
||||
assert saved['WECOM_ENABLED'] == 'true'
|
||||
assert saved['WECOM_CORP_ID'] == 'ww-persisted'
|
||||
assert saved['WECOM_MATCH_OPERATOR'] == 'OR'
|
||||
assert saved['WECOM_PUBLIC_BASE_URL'] == 'https://example.com'
|
||||
|
||||
with app.app_context():
|
||||
rows = {row.key: row.value for row in db.session.query(AppSetting).all()}
|
||||
assert rows['WECOM_ENABLED'] == 'true'
|
||||
assert rows['WECOM_CORP_ID'] == 'ww-persisted'
|
||||
assert rows['WECOM_MATCH_OPERATOR'] == 'OR'
|
||||
assert rows['WECOM_PUBLIC_BASE_URL'] == 'https://example.com'
|
||||
|
||||
with app.app_context():
|
||||
app.config['WECOM_ENABLED'] = False
|
||||
app.config['WECOM_CORP_ID'] = ''
|
||||
app.config['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
app.config['WECOM_PUBLIC_BASE_URL'] = ''
|
||||
|
||||
res = client.get('/api/admin/wecom/system-settings', headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['enabled'] is True
|
||||
assert data['corp_id'] == 'ww-persisted'
|
||||
assert data['match_operator'] == 'OR'
|
||||
assert data['public_base_url'] == 'https://example.com'
|
||||
|
||||
|
||||
def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path):
|
||||
env_file = tmp_path / '.env'
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
|
||||
|
||||
payload = {
|
||||
'enabled': False,
|
||||
'base_url': 'https://notify.example.com',
|
||||
'events': ['task_completed', 'permission_batch_updated'],
|
||||
}
|
||||
|
||||
res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
|
||||
saved = dotenv_values(env_file)
|
||||
assert saved['WECOM_NOTIFY_ENABLED'] == 'false'
|
||||
assert saved['WECOM_NOTIFY_BASE_URL'] == 'https://notify.example.com'
|
||||
assert saved['WECOM_NOTIFY_EVENTS'] == 'task_completed,permission_batch_updated'
|
||||
|
||||
with app.app_context():
|
||||
rows = {row.key: row.value for row in db.session.query(AppSetting).all()}
|
||||
assert rows['WECOM_NOTIFY_ENABLED'] == 'false'
|
||||
assert rows['WECOM_NOTIFY_BASE_URL'] == 'https://notify.example.com'
|
||||
assert rows['WECOM_NOTIFY_EVENTS'] == 'task_completed,permission_batch_updated'
|
||||
|
||||
with app.app_context():
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
app.config['WECOM_NOTIFY_BASE_URL'] = ''
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = ''
|
||||
|
||||
res = client.get('/api/admin/wecom/notify-settings', headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['enabled'] is False
|
||||
assert data['base_url'] == 'https://notify.example.com'
|
||||
assert data['events'] == ['task_completed', 'permission_batch_updated']
|
||||
|
||||
|
||||
def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin_headers, monkeypatch, tmp_path):
|
||||
"""Simulate a container rebuild that wipes backend/.env. The DB row must
|
||||
still drive the runtime configuration."""
|
||||
env_file = tmp_path / '.env'
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
|
||||
|
||||
res = client.put(
|
||||
'/api/admin/wecom/system-settings',
|
||||
json={'corp_id': 'ww-from-db-only', 'enabled': True},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
# Wipe the env file the way a fresh container build would.
|
||||
if env_file.exists():
|
||||
env_file.unlink()
|
||||
|
||||
# Reset in-memory config to defaults to prove the next request reloads
|
||||
# values from the database rather than the (now empty) env file.
|
||||
with app.app_context():
|
||||
app.config['WECOM_CORP_ID'] = ''
|
||||
app.config['WECOM_ENABLED'] = False
|
||||
|
||||
res = client.get('/api/admin/wecom/system-settings', headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['corp_id'] == 'ww-from-db-only'
|
||||
assert data['enabled'] is True
|
||||
Reference in new issue
Block a user