From ebba6c3f824fcf8211600087722000b7ad5a5c5f Mon Sep 17 00:00:00 2001 From: Magzhan Zhumabayev Date: Mon, 11 May 2026 16:01:57 +0500 Subject: [PATCH] Allow tenant header for bearer-authenticated requests --- services/shared/security.py | 2 +- tests/test_security_track1.py | 46 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/services/shared/security.py b/services/shared/security.py index 8925554..71825df 100644 --- a/services/shared/security.py +++ b/services/shared/security.py @@ -131,7 +131,7 @@ def get_actor( payload = decode_app_token(value.strip()) tenant_id = str(payload.get("tenant_id") or "").strip() tenant_source = "token" if tenant_id else None - if not tenant_id and legacy_header_auth_allowed(): + if not tenant_id: tenant_id = str(x_tenant_id or "").strip() tenant_source = "header" if tenant_id else None return { diff --git a/tests/test_security_track1.py b/tests/test_security_track1.py index ccdae4b..b771832 100644 --- a/tests/test_security_track1.py +++ b/tests/test_security_track1.py @@ -57,6 +57,52 @@ def test_legacy_header_auth_can_be_disabled(monkeypatch): assert response.status_code == 403 +def test_bearer_token_can_use_tenant_header_when_legacy_auth_disabled(monkeypatch): + monkeypatch.setenv('APP_TOKEN_SECRET', 'track1-secret') + monkeypatch.setenv('ALLOW_LEGACY_HEADER_AUTH', '0') + client = TestClient(build_app()) + token = issue_app_token( + subject='usr_1', + username='alice', + role='admin', + auth_source='local', + ) + + response = client.get( + '/actor', + headers={'Authorization': f'Bearer {token}', 'X-Tenant-ID': 'default'}, + ) + + assert response.status_code == 200 + body = response.json() + assert body['user'] == 'alice' + assert body['role'] == 'admin' + assert body['tenant_id'] == 'default' + assert body['tenant_source'] == 'header' + + +def test_bearer_token_tenant_takes_precedence_over_header(monkeypatch): + monkeypatch.setenv('APP_TOKEN_SECRET', 'track1-secret') + client = TestClient(build_app()) + token = issue_app_token( + subject='usr_1', + username='alice', + role='admin', + auth_source='oidc', + tenant_id='token-tenant', + ) + + response = client.get( + '/actor', + headers={'Authorization': f'Bearer {token}', 'X-Tenant-ID': 'header-tenant'}, + ) + + assert response.status_code == 200 + body = response.json() + assert body['tenant_id'] == 'token-tenant' + assert body['tenant_source'] == 'token' + + def test_legacy_header_auth_still_works_when_enabled(monkeypatch): monkeypatch.setenv('ALLOW_LEGACY_HEADER_AUTH', '1') client = TestClient(build_app())