|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +import json |
| 18 | +import logging |
| 19 | + |
| 20 | +import atr.log as log |
| 21 | + |
| 22 | + |
| 23 | +def _capture_auth_log() -> list[str]: |
| 24 | + captured: list[str] = [] |
| 25 | + |
| 26 | + class _Handler(logging.Handler): |
| 27 | + def emit(self, record: logging.LogRecord) -> None: |
| 28 | + captured.append(record.getMessage()) |
| 29 | + |
| 30 | + logger = logging.getLogger("atr.auth") |
| 31 | + logger.handlers.clear() |
| 32 | + logger.addHandler(_Handler()) |
| 33 | + logger.setLevel(logging.INFO) |
| 34 | + logger.propagate = False |
| 35 | + return captured |
| 36 | + |
| 37 | + |
| 38 | +def test_auth_log_omits_request_fields_when_no_request_context_is_bound() -> None: |
| 39 | + log.clear_context() |
| 40 | + captured = _capture_auth_log() |
| 41 | + |
| 42 | + log.auth_success(type="oauth", asfuid="alice") |
| 43 | + |
| 44 | + entry = json.loads(captured[-1]) |
| 45 | + assert "request_id" not in entry |
| 46 | + assert "source_ip" not in entry |
| 47 | + |
| 48 | + |
| 49 | +def test_auth_log_carries_request_id_and_source_ip_from_the_log_context() -> None: |
| 50 | + log.clear_context() |
| 51 | + log.add_context(request_id="req-123", source_ip="203.0.113.7") |
| 52 | + captured = _capture_auth_log() |
| 53 | + try: |
| 54 | + log.auth_failure(type="jwt", reason="bad token", asfuid="bob") |
| 55 | + |
| 56 | + entry = json.loads(captured[-1]) |
| 57 | + assert entry["request_id"] == "req-123" |
| 58 | + assert entry["source_ip"] == "203.0.113.7" |
| 59 | + finally: |
| 60 | + log.clear_context() |
0 commit comments