3 Commits

Author SHA1 Message Date
Jonas Linter
5f82de9c53 Merge branch 'db_fixes_plus_free_rooms' of https://gitea.99tales.net/jonas/alpinebits_python into db_fixes_plus_free_rooms 2025-12-03 22:37:08 +01:00
Jonas Linter
2eb6902d21 Reduced logging for conversion service 2025-12-02 17:03:07 +01:00
Jonas Linter
4765360a45 Replaced config auth with db auth 2025-12-02 16:43:56 +01:00
8 changed files with 84 additions and 31 deletions

View File

@@ -33,6 +33,7 @@ from .generated.alpinebits import (
OtaReadRq, OtaReadRq,
WarningStatus, WarningStatus,
) )
from .hotel_service import HotelService
from .reservation_service import ReservationService from .reservation_service import ReservationService
# Configure logging # Configure logging
@@ -413,20 +414,24 @@ def strip_control_chars(s):
return re.sub(r"[\x00-\x1F\x7F]", "", s) return re.sub(r"[\x00-\x1F\x7F]", "", s)
def validate_hotel_authentication( async def validate_hotel_authentication(
username: str, password: str, hotelid: str, config: dict username: str,
password: str,
hotelid: str,
config: dict,
dbsession=None,
) -> bool: ) -> bool:
"""Validate hotel authentication based on username, password, and hotel ID. """Validate hotel authentication against the database (fallback to config)."""
if dbsession is not None:
hotel_service = HotelService(dbsession)
hotel = await hotel_service.authenticate_hotel(username, password)
if hotel:
return hotel.hotel_id == hotelid
Example config # Fallback to config for legacy scenarios (e.g., during migration)
alpine_bits_auth:
- hotel_id: "123"
hotel_name: "Frangart Inn"
username: "alice"
password: !secret ALICE_PASSWORD
"""
if not config or "alpine_bits_auth" not in config: if not config or "alpine_bits_auth" not in config:
return False return False
auth_list = config["alpine_bits_auth"] auth_list = config["alpine_bits_auth"]
for auth in auth_list: for auth in auth_list:
if ( if (
@@ -488,8 +493,12 @@ class ReadAction(AlpineBitsAction):
HttpStatusCode.UNAUTHORIZED, HttpStatusCode.UNAUTHORIZED,
) )
if not validate_hotel_authentication( if not await validate_hotel_authentication(
client_info.username, client_info.password, hotelid, self.config client_info.username,
client_info.password,
hotelid,
self.config,
dbsession,
): ):
return AlpineBitsResponse( return AlpineBitsResponse(
f"Error: Unauthorized Read Request for this specific hotel {hotelname}. Check credentials", f"Error: Unauthorized Read Request for this specific hotel {hotelname}. Check credentials",
@@ -522,7 +531,7 @@ class ReadAction(AlpineBitsAction):
await reservation_service.get_unacknowledged_reservations( await reservation_service.get_unacknowledged_reservations(
username=client_info.username, username=client_info.username,
client_id=client_info.client_id, client_id=client_info.client_id,
hotel_code=hotelid hotel_code=hotelid,
) )
) )
else: else:
@@ -619,7 +628,9 @@ class NotifReportReadAction(AlpineBitsAction):
): # type: ignore ): # type: ignore
md5_unique_id = entry.unique_id.id md5_unique_id = entry.unique_id.id
await reservation_service.record_acknowledgement( await reservation_service.record_acknowledgement(
client_id=client_info.client_id, unique_id=md5_unique_id, username=client_info.username client_id=client_info.client_id,
unique_id=md5_unique_id,
username=client_info.username,
) )
return AlpineBitsResponse(response_xml, HttpStatusCode.OK) return AlpineBitsResponse(response_xml, HttpStatusCode.OK)
@@ -826,4 +837,4 @@ class AlpineBitsServer:
# Ensure FreeRoomsAction is registered with ServerCapabilities discovery # Ensure FreeRoomsAction is registered with ServerCapabilities discovery
#from .free_rooms_action import FreeRoomsAction # noqa: E402,F401 disable for now # from .free_rooms_action import FreeRoomsAction

View File

@@ -664,7 +664,8 @@ async def detect_language(
async def validate_basic_auth( async def validate_basic_auth(
credentials: HTTPBasicCredentials = Depends(security_basic), credentials: HTTPBasicCredentials = Depends(security_basic),
) -> str: db_session=Depends(get_async_session),
) -> tuple[str, str]:
"""Validate basic authentication for AlpineBits protocol. """Validate basic authentication for AlpineBits protocol.
Returns username if valid, raises HTTPException if not. Returns username if valid, raises HTTPException if not.
@@ -676,26 +677,40 @@ async def validate_basic_auth(
detail="ERROR: Authentication required", detail="ERROR: Authentication required",
headers={"WWW-Authenticate": "Basic"}, headers={"WWW-Authenticate": "Basic"},
) )
valid = False hotel_service = HotelService(db_session)
config = app.state.config hotel = await hotel_service.authenticate_hotel(
credentials.username, credentials.password
)
for entry in config["alpine_bits_auth"]: if hotel:
_LOGGER.info(
"AlpineBits authentication successful for user: %s (from database)",
credentials.username,
)
return credentials.username, credentials.password
# Fallback to config-defined credentials for legacy scenarios
config = app.state.config
valid = False
for entry in config.get("alpine_bits_auth", []):
if ( if (
credentials.username == entry["username"] credentials.username == entry.get("username")
and credentials.password == entry["password"] and credentials.password == entry.get("password")
): ):
valid = True valid = True
_LOGGER.warning(
"AlpineBits authentication for user %s matched legacy config entry",
credentials.username,
)
break break
if not valid: if not valid:
raise HTTPException( raise HTTPException(
status_code=401, status_code=401,
detail="ERROR: Invalid credentials", detail="ERROR: Invalid credentials",
headers={"WWW-Authenticate": "Basic"}, headers={"WWW-Authenticate": "Basic"},
) )
_LOGGER.info(
"AlpineBits authentication successful for user: %s (from config)",
credentials.username,
)
return credentials.username, credentials.password return credentials.username, credentials.password

View File

@@ -918,7 +918,7 @@ class ConversionService:
) )
existing_conversion.updated_at = datetime.now() existing_conversion.updated_at = datetime.now()
conversion = existing_conversion conversion = existing_conversion
_LOGGER.info( _LOGGER.debug(
"Updated conversion %s (pms_id=%s)", "Updated conversion %s (pms_id=%s)",
conversion.id, conversion.id,
pms_reservation_id, pms_reservation_id,

View File

@@ -125,11 +125,12 @@ class FreeRoomsAction(AlpineBitsAction):
code="401", code="401",
) )
if not validate_hotel_authentication( if not await validate_hotel_authentication(
client_info.username, client_info.username,
client_info.password, client_info.password,
hotel_code, hotel_code,
self.config, self.config,
dbsession,
): ):
raise FreeRoomsProcessingError( raise FreeRoomsProcessingError(
f"Unauthorized FreeRooms notification for hotel {hotel_code}", f"Unauthorized FreeRooms notification for hotel {hotel_code}",

View File

@@ -244,3 +244,26 @@ class HotelService:
) )
) )
return result.scalar_one_or_none() return result.scalar_one_or_none()
async def authenticate_hotel(self, username: str, password: str) -> Hotel | None:
"""Authenticate a hotel using username and password.
Args:
username: AlpineBits username
password: Plain text password submitted via HTTP basic auth
Returns:
Hotel instance if the credentials are valid and the hotel is active,
otherwise None.
"""
hotel = await self.get_hotel_by_username(username)
if not hotel:
return None
if not password:
return None
if verify_password(password, hotel.password_hash):
return hotel
return None

View File

@@ -17,6 +17,7 @@ from alpine_bits_python.alpinebits_server import AlpineBitsServer
from alpine_bits_python.api import app from alpine_bits_python.api import app
from alpine_bits_python.const import HttpStatusCode from alpine_bits_python.const import HttpStatusCode
from alpine_bits_python.db import Base, Hotel, RoomAvailability from alpine_bits_python.db import Base, Hotel, RoomAvailability
from alpine_bits_python.hotel_service import hash_password
def build_request_xml(body: str, include_unique_id: bool = True) -> str: def build_request_xml(body: str, include_unique_id: bool = True) -> str:
@@ -118,7 +119,7 @@ def seed_hotel_if_missing(client: TestClient):
hotel_id="HOTEL123", hotel_id="HOTEL123",
hotel_name="Integration Hotel", hotel_name="Integration Hotel",
username="testuser", username="testuser",
password_hash="integration-hash", password_hash=hash_password("testpass"),
created_at=datetime.now(UTC), created_at=datetime.now(UTC),
updated_at=datetime.now(UTC), updated_at=datetime.now(UTC),
is_active=True, is_active=True,

View File

@@ -12,6 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asyn
from alpine_bits_python.alpinebits_server import AlpineBitsClientInfo, Version from alpine_bits_python.alpinebits_server import AlpineBitsClientInfo, Version
from alpine_bits_python.const import HttpStatusCode from alpine_bits_python.const import HttpStatusCode
from alpine_bits_python.db import Base, Hotel, HotelInventory, RoomAvailability from alpine_bits_python.db import Base, Hotel, HotelInventory, RoomAvailability
from alpine_bits_python.hotel_service import hash_password
from alpine_bits_python.free_rooms_action import FreeRoomsAction from alpine_bits_python.free_rooms_action import FreeRoomsAction
@@ -78,7 +79,7 @@ async def insert_test_hotel(session: AsyncSession, hotel_id: str = "TESTHOTEL"):
hotel_id=hotel_id, hotel_id=hotel_id,
hotel_name="Unit Test Hotel", hotel_name="Unit Test Hotel",
username="testuser", username="testuser",
password_hash="bcrypt-hash", password_hash=hash_password("testpass"),
created_at=datetime.now(UTC), created_at=datetime.now(UTC),
updated_at=datetime.now(UTC), updated_at=datetime.now(UTC),
is_active=True, is_active=True,

View File

@@ -23,6 +23,7 @@ from alpine_bits_python.api import app
from alpine_bits_python.const import WebhookStatus from alpine_bits_python.const import WebhookStatus
from alpine_bits_python.db import Base, Reservation, WebhookRequest from alpine_bits_python.db import Base, Reservation, WebhookRequest
from alpine_bits_python.db_setup import reprocess_stuck_webhooks from alpine_bits_python.db_setup import reprocess_stuck_webhooks
from alpine_bits_python.hotel_service import hash_password
from alpine_bits_python.schemas import WebhookRequestData from alpine_bits_python.schemas import WebhookRequestData
from alpine_bits_python.webhook_processor import initialize_webhook_processors, webhook_registry from alpine_bits_python.webhook_processor import initialize_webhook_processors, webhook_registry
@@ -206,7 +207,7 @@ class TestWebhookReprocessing:
hotel_id="HOTEL123", hotel_id="HOTEL123",
hotel_name="Test Hotel", hotel_name="Test Hotel",
username="testuser", username="testuser",
password_hash="dummy", password_hash=hash_password("testpass"),
created_at=datetime.now(UTC), created_at=datetime.now(UTC),
updated_at=datetime.now(UTC), updated_at=datetime.now(UTC),
is_active=True, is_active=True,
@@ -291,7 +292,7 @@ class TestWebhookReprocessingNeverBlocksStartup:
hotel_id="HOTEL123", hotel_id="HOTEL123",
hotel_name="Test Hotel", hotel_name="Test Hotel",
username="testuser", username="testuser",
password_hash="dummy", password_hash=hash_password("testpass"),
created_at=datetime.now(UTC), created_at=datetime.now(UTC),
updated_at=datetime.now(UTC), updated_at=datetime.now(UTC),
is_active=True, is_active=True,