Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion components/lif/composer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ def add_fragment_items_to_list(list_to_update: list, new_items: list):
if isinstance(new_item, dict):
list_to_update.append(new_item)
else:
msg = f"Input should be a valid dictionary: {new_item}"
# The type, not the item: the item is a learner value (#1351).
msg = f"Input should be a valid dictionary, got {type(new_item).__name__}"
logger.error(msg)
raise ValueError(msg)
22 changes: 16 additions & 6 deletions components/lif/query_cache_service/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
and filter conversion.
"""

import traceback
from typing import Any, Dict, List

from pymongo import ReturnDocument
Expand Down Expand Up @@ -141,6 +142,15 @@ def extract_updated_fields(update_fields):
return result


def log_failure(label: str, error: Exception) -> None:
"""Log a failure's type and stack, but not its message (#1351).

The message can quote the filter or a learner value: a Mongo DuplicateKeyError quotes the key.
"""
stack = "".join(traceback.format_tb(error.__traceback__)).rstrip()
logger.error("%s: %s\n%s", label, type(error).__name__, stack)


# -------------------------------------------------------------------------
# Main function to run a query (ASYNC)
# -------------------------------------------------------------------------
Expand Down Expand Up @@ -176,7 +186,7 @@ async def query(query: LIFQuery) -> List[LIFRecord]:
logger.info(f"===> QUERY CACHE RETURNING {len(results)} record(s)")
return results
except Exception as e:
logger.exception("Query Exception: %s", e)
log_failure("Query Exception", e)
raise


Expand Down Expand Up @@ -258,10 +268,10 @@ async def update(lif_update: LIFUpdate) -> LIFRecord:
# ty doesn't model pydantic's populate_by_name aliasing; `person` is the
# field name (alias "Person") and is valid at runtime.
return LIFRecord(person=doc[PERSON_KEY_PASCAL]) # ty: ignore[unknown-argument]
raise ResourceNotFoundException(resource_id=None, message=f"No matching record after update: {filter_dict}")
raise ResourceNotFoundException(resource_id=None, message="No matching record after update")

except Exception as e:
logger.exception("Update Exception: %s", e)
log_failure("Update Exception", e)
raise


Expand All @@ -288,7 +298,7 @@ async def add(lif_record: LIFRecord) -> LIFRecord:
return lif_record
raise ResourceNotFoundException("Failed to add record, no inserted ID returned.")
except Exception as e:
logger.exception("Add Exception: %s", e)
log_failure("Add Exception", e)
raise


Expand All @@ -312,7 +322,7 @@ async def save(lif_query_filter: LIFQueryFilter, lif_fragments: List[LIFFragment
async for doc in cursor:
results.append(doc)
if len(results) > 1:
raise ValueError(f"Cannot save -- multiple records found for the given filter: {lif_query_filter}")
raise ValueError("Cannot save -- multiple records found for the given filter")

person_identifiers: LIFPersonIdentifiers = LIFPersonIdentifiers(
Identifier=lif_query_filter.root.person.Identifier
Expand All @@ -334,5 +344,5 @@ async def save(lif_query_filter: LIFQueryFilter, lif_fragments: List[LIFFragment
)
logger.debug(f"MONGO UPDATE RESPONSE: {mongo_update_response}")
except Exception as e:
logger.exception("Save Exception: %s", e)
log_failure("Save Exception", e)
raise
15 changes: 15 additions & 0 deletions test/components/lif/composer/test_core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import datetime
import json
import logging

import pytest

from lif.composer.core import (
add_fragment_items_to_list,
compose_json_with_fragment_list,
compose_json_with_single_fragment,
compose_with_fragment_list,
Expand Down Expand Up @@ -407,3 +411,14 @@ def test_compose_with_fragment_list_does_not_mutate_the_input_record():
)

assert lif_record.person[0]["identifier"] == [identifier_1_dict]


def test_a_non_object_item_is_refused_without_logging_its_value(caplog):
# The item is a learner value, and the message is logged and reaches the Query Cache's response (#1351).
with caplog.at_level(logging.INFO, logger="lif.composer.core"):
with pytest.raises(ValueError) as raised:
add_fragment_items_to_list([], ["Marigold"])

assert "Input should be a valid dictionary, got str" in caplog.text
assert "Marigold" not in caplog.text
assert "Marigold" not in str(raised.value)
85 changes: 84 additions & 1 deletion test/components/lif/query_cache_service/test_log_redaction.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
The Query Cache keeps learner identifiers and field values out of its logs (#1319).
The Query Cache keeps learner identifiers and field values out of its logs (#1319, #1351).

Each test drives a path that logs, asserts that it did log, and asserts that a known identifier
and field value appear nowhere in the captured output.
Expand All @@ -9,9 +9,13 @@
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
from pymongo.errors import DuplicateKeyError, OperationFailure

from lif.datatypes import LIFPersonIdentifier, LIFPersonIdentifiers, LIFQuery, LIFQueryFilter, LIFQueryPersonFilter
from lif.datatypes import LIFRecord, LIFUpdate
from lif.datatypes.core import LIFUpdatePersonPayload
from lif.exceptions.core import ResourceNotFoundException
from lif.query_cache_service import core

IDENTIFIER = "SENTINEL-ID-4471"
Expand Down Expand Up @@ -81,3 +85,82 @@ async def test_add_logs_no_learner_data(caplog):
await core.add(lif_record=record)

_assert_logged_without_learner_data(caplog, "CALL MADE TO ADD")


# Error paths (#1351): the exception's message can carry the filter or a learner value, so each
# failure logs the exception's type and stack but not its message.


def _identifier_query():
return LIFQuery(
filter=LIFQueryFilter(
root=LIFQueryPersonFilter(
person=LIFPersonIdentifiers(
Identifier=LIFPersonIdentifier(identifier=IDENTIFIER, identifierType="School-assigned number")
)
)
),
selected_fields=["Person.Name"],
)


def _assert_failure_logged_without_learner_data(caplog, label, error_type, function):
_assert_logged_without_learner_data(caplog, f"{label}: {error_type}")
# The stack is kept, so the failing frame can still be found.
assert f"in {function}" in caplog.text


async def test_query_failure_logs_no_learner_data(caplog):
mock_collection = MagicMock()
mock_collection.find = MagicMock(side_effect=OperationFailure(f"bad filter value {IDENTIFIER!r}"))

with patch.object(core, "collection", mock_collection), caplog.at_level(logging.INFO, logger=LOGGER):
with pytest.raises(OperationFailure):
await core.query(_identifier_query())

_assert_failure_logged_without_learner_data(caplog, "Query Exception", "OperationFailure", "query")


async def test_update_with_no_match_logs_no_learner_data(caplog):
lif_update = LIFUpdate(
updatePerson=LIFUpdatePersonPayload(
filter={"Person": {"Identifier": {"identifier": IDENTIFIER}}}, input={"Person": {"nickname": FIELD_VALUE}}
)
)
mock_collection = MagicMock()
mock_collection.find_one_and_update = AsyncMock(return_value=None)

with patch.object(core, "collection", mock_collection), caplog.at_level(logging.INFO, logger=LOGGER):
with pytest.raises(ResourceNotFoundException) as raised:
await core.update(lif_update)

_assert_failure_logged_without_learner_data(caplog, "Update Exception", "ResourceNotFoundException", "update")
# The API returns this message as the 404 body.
assert IDENTIFIER not in str(raised.value)


async def test_add_failure_logs_no_learner_data(caplog):
record = LIFRecord(person=PERSON_DOC["Person"])
mock_collection = MagicMock()
mock_collection.insert_one = AsyncMock(
side_effect=DuplicateKeyError(f'E11000 duplicate key error dup key: {{ identifier: "{IDENTIFIER}" }}')
)

with patch.object(core, "collection", mock_collection), caplog.at_level(logging.INFO, logger=LOGGER):
with pytest.raises(DuplicateKeyError):
await core.add(lif_record=record)

_assert_failure_logged_without_learner_data(caplog, "Add Exception", "DuplicateKeyError", "add")


async def test_save_with_several_matches_logs_no_learner_data(caplog):
lif_query_filter = _identifier_query().filter
mock_collection = MagicMock()
mock_collection.find = MagicMock(return_value=_async_cursor([PERSON_DOC, PERSON_DOC]))

with patch.object(core, "collection", mock_collection), caplog.at_level(logging.INFO, logger=LOGGER):
with pytest.raises(ValueError) as raised:
await core.save(lif_query_filter=lif_query_filter, lif_fragments=[])

_assert_failure_logged_without_learner_data(caplog, "Save Exception", "ValueError", "save")
assert IDENTIFIER not in str(raised.value)
Loading