diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..0d2f8f0c --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +test/data/equivalent-checks-cases.json linguist-generated=true diff --git a/Makefile b/Makefile index d43f4847..724dcb89 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ -.PHONY: sync test lint fmt fix check doc +.PHONY: sync test lint fmt fix check doc update-equivalent-checks-cases check-equivalent-checks-cases + +# openfga/language commit to copy the shared equivalent-checks cases from +LANGUAGE_REF ?= 41f78349717678d97aade591cf12c78541fae77f # Install/update dependencies sync: @@ -26,6 +29,15 @@ fix: uv run ruff check --fix . uv run ruff format . +# Copy the shared equivalent-checks cases from openfga/language +# Usage: make update-equivalent-checks-cases LANGUAGE_REF= +update-equivalent-checks-cases: + curl -fsSL https://raw.githubusercontent.com/openfga/language/$(LANGUAGE_REF)/tests/data/equivalent-checks-cases.json -o test/data/equivalent-checks-cases.json + +# Check that the committed equivalent-checks cases match openfga/language at LANGUAGE_REF +check-equivalent-checks-cases: + curl -fsSL https://raw.githubusercontent.com/openfga/language/$(LANGUAGE_REF)/tests/data/equivalent-checks-cases.json | diff -q - test/data/equivalent-checks-cases.json + # Run checks (lint + test) check: lint fmt test @@ -39,4 +51,6 @@ doc: @echo " fmt - Format code" @echo " fix - Fix fixable linting and formatting issues" @echo " check - Run both linting and tests" + @echo " update-equivalent-checks-cases - Copy the shared equivalent-checks cases from openfga/language (LANGUAGE_REF=)" + @echo " check-equivalent-checks-cases - Check the committed cases match openfga/language at LANGUAGE_REF" @echo " doc - Show this help message" diff --git a/README.md b/README.md index 90a65e86..b06adca2 100644 --- a/README.md +++ b/README.md @@ -965,6 +965,48 @@ response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), # ] ``` +###### Merge equivalent checks + +If you set `merge_equivalent_checks` to `True` in the options, the SDK sends checks that will get the same answer only once, then copies that answer back to each of them. You still get one result for every check you passed in. + +Two kinds of checks are merged: + +- Checks on a relation that is an alias of another one. With `define can_view: viewer`, a check on `can_view` and a check on `viewer` with the same user, object, context and contextual tuples become one check on `viewer`. Chains like `define can_share: can_view` are followed too. +- Exact repeats, with the same user, relation, object, context and contextual tuples. + +```python +options = { + # Required, either here or in the configuration + "authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", + "merge_equivalent_checks": True, +} +response = await fga_client.batch_check(ClientBatchCheckRequest(checks=checks), options) +# response.checks_sent is how many checks were sent to the server, or None when the option is off +``` + +The option is off by default. Leaving it out or setting it to `None` keeps it off. Any other value that isn't a bool, like `"true"`, fails with a validation error. + +To find aliases, the SDK reads the authorization model the first time it needs it and keeps it in memory, so create the client once and reuse it. Each client keeps up to 32 models and drops the least recently used one. The call fails before any check is sent when: + +- no authorization model ID is set +- the model or the store doesn't exist +- the SDK can't get an access token, after retrying as usual. The checks need the same token, so the call would fail with the option off too. +- the credentials can't read the model (a 401 or 403). If your credentials can only run checks, leave the option off. + +Calls running at the same time share one read, sent with the headers of the call that started it. If your calls pass different credentials in `headers`, a call can fail with the 401 or 403 of another call's read. + +If reading the model fails for another reason, such as a 429, a 5xx or a timeout, the SDK logs a warning and sends the checks without merging them. It doesn't retry this read, even if you set `retry_params`, so a failed read costs one request. The next call reads the model again. + +Compared with leaving the option off, a call: + +- makes one extra request the first time the client needs a model, to read it. Later calls use the copy in memory, and calls running at the same time share one read. +- spends a little time grouping the checks and copying the answers back. This happens in memory and is small next to a request. +- sends fewer checks when some of them merge, so the checks themselves can finish sooner. + +Each client reads each model once, unless it uses more than 32 models. Some services rate limit model reads much lower than checks, so if many clients start at the same time, some may get a 429. Those clients send checks unmerged and read the model again on each call until a read succeeds. + +If a merged check returns an error, every check it stands for gets that error. Correlation IDs must match `^[\w\d-]{1,36}$` (ASCII), and missing ones are generated. For metrics, see `fga-client.batch_check.*` and `fga-client.model_cache.lookup` in [OpenTelemetry](docs/opentelemetry.md). + ##### Client Batch Check diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md index ce4ca6be..630ba08e 100644 --- a/docs/opentelemetry.md +++ b/docs/opentelemetry.md @@ -21,17 +21,22 @@ If you configure the OpenTelemetry SDK, these metrics will be exported and sent ### Supported Metrics -| Metric Name | Type | Enabled by Default | Description | -| -------------------------------- | --------- | ------------------ | --------------------------------------------------------------------------------- | -| `fga-client.request.duration` | Histogram | Yes | Total request time for FGA requests, in milliseconds | -| `fga-client.query.duration` | Histogram | Yes | Time taken by the FGA server to process and evaluate the request, in milliseconds | -| `fga-client.credentials.request` | Counter | Yes | Total number of new token requests initiated using the Client Credentials flow | -| `fga-client.request` | Counter | No | Total number of requests made to the FGA server | +| Metric Name | Type | Enabled by Default | Description | +| ----------------------------------------- | --------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `fga-client.request.duration` | Histogram | Yes | Total request time for FGA requests, in milliseconds | +| `fga-client.query.duration` | Histogram | Yes | Time taken by the FGA server to process and evaluate the request, in milliseconds | +| `fga-client.credentials.request` | Counter | Yes | Total number of new token requests initiated using the Client Credentials flow | +| `fga-client.request` | Counter | No | Total number of requests made to the FGA server | +| `fga-client.batch_check.checks_requested` | Counter | Yes | Checks passed to `batch_check` with `merge_equivalent_checks` on | +| `fga-client.batch_check.checks_sent` | Counter | Yes | Checks actually sent by `batch_check` with `merge_equivalent_checks` on | +| `fga-client.batch_check.merge_fallback` | Counter | Yes | `batch_check` calls sent unmerged because the model read failed with an error that doesn't fail the call (such as a 429, a 5xx or a timeout), or the checks couldn't be grouped. Has the `http.response.status_code` of the failed read, when there is one | +| `fga-client.model_cache.lookup` | Counter | Yes | Authorization model cache lookups by `merge_equivalent_checks`, one per `batch_check` call, with a `hit` or `miss` result. Calls that wait for the same model read each count a miss, so there can be more misses than reads | ### Supported Attributes | Attribute Name | Type | Enabled by Default | Description | | ------------------------------------- | ------ | ------------------ | --------------------------------------------------------------------------------- | +| `fga-client.model_cache.result` | string | Yes | Result of an authorization model cache lookup (`hit`/`miss`) | | `fga-client.request.batch_check_size` | int | No | The total size of the `check` list in a `BatchCheck` call | | `fga-client.request.client_id` | string | Yes | Client ID associated with the request, if any | | `fga-client.request.method` | string | Yes | FGA method/action that was performed (e.g., Check, ListObjects) in TitleCase | diff --git a/openfga_sdk/client/_batch_check_merge.py b/openfga_sdk/client/_batch_check_merge.py new file mode 100644 index 00000000..8e894edd --- /dev/null +++ b/openfga_sdk/client/_batch_check_merge.py @@ -0,0 +1,102 @@ +""" +Steps of a BatchCheck call with `merge_equivalent_checks` on that are the same in the +async and sync clients. The model caches read the model, and the clients send the +checks. Not part of the public API. +""" + +import logging + +from openfga_sdk.client._equivalent_checks import ( + EquivalentCheckGroup, + resolve, + unmerged, +) +from openfga_sdk.client._model_cache_base import ( + ModelLookup, + TokenRequestError, + model_read_fails_call, +) +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.telemetry.attributes import TelemetryAttributes + + +logger = logging.getLogger(__name__) + + +def checks_to_send( + api_client, + store_id: str, + authorization_model_id: str, + lookup: ModelLookup, + checks: list[ClientBatchCheckItem], +) -> list[EquivalentCheckGroup]: + """ + Group the checks using the model from the cache, or send them unmerged if the model + couldn't be read or grouping failed. Raise if the model read error fails the call. + """ + metrics = _MergeMetrics(api_client, store_id, authorization_model_id) + metrics.model_cache_lookup(lookup.hit) + + if lookup.aliases is None: + error = lookup.error + if error is not None and model_read_fails_call(error): + # BatchCheck would fail too without a token or if the model is missing, and + # falling back on a 401 or 403 would hide wrong credentials. Fail before + # sending anything. + if isinstance(error, TokenRequestError): + raise error.error + raise error + groups = unmerged(checks) + metrics.fallback(getattr(error, "status", None)) + else: + try: + groups = resolve(lookup.aliases, checks) + except Exception: + logger.warning( + "merge_equivalent_checks: couldn't group the checks. Sending checks unmerged.", + exc_info=True, + ) + groups = unmerged(checks) + metrics.fallback(None) + + # Every chunk is sent even if another one fails, so count them up front. + metrics.checks(requested=len(checks), sent=len(groups)) + return groups + + +class _MergeMetrics: + def __init__(self, api_client, store_id: str, authorization_model_id: str) -> None: + self._metrics = api_client._telemetry.metrics + self._configuration = api_client.configuration.telemetry + self._attributes = { + TelemetryAttributes.fga_client_request_store_id: store_id, + TelemetryAttributes.fga_client_request_model_id: authorization_model_id, + } + + def model_cache_lookup(self, hit: bool) -> None: + self._metrics.modelCacheLookup( + attributes={ + **self._attributes, + TelemetryAttributes.fga_client_model_cache_result: ( + "hit" if hit else "miss" + ), + }, + configuration=self._configuration, + ) + + def fallback(self, status: int | None) -> None: + self._metrics.batchCheckMergeFallback( + attributes={ + **self._attributes, + TelemetryAttributes.http_response_status_code: status, + }, + configuration=self._configuration, + ) + + def checks(self, requested: int, sent: int) -> None: + self._metrics.batchCheckChecksRequested( + requested, attributes=self._attributes, configuration=self._configuration + ) + self._metrics.batchCheckChecksSent( + sent, attributes=self._attributes, configuration=self._configuration + ) diff --git a/openfga_sdk/client/_equivalent_checks.py b/openfga_sdk/client/_equivalent_checks.py new file mode 100644 index 00000000..6b2d611d --- /dev/null +++ b/openfga_sdk/client/_equivalent_checks.py @@ -0,0 +1,476 @@ +""" +Merge equivalent checks in BatchCheck (the `merge_equivalent_checks` option). + +Checks that are certain to get the same answer are sent once, and the answer is +copied back to every original check. Rules: https://github.com/openfga/rfcs/pull/40 +""" + +import math +import re +import struct +import uuid + +from collections import Counter +from dataclasses import dataclass + +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.batch_check_single_response import ( + ClientBatchCheckSingleResponse, +) +from openfga_sdk.exceptions import FgaValidationException +from openfga_sdk.models.authorization_model import AuthorizationModel +from openfga_sdk.models.batch_check_single_result import BatchCheckSingleResult +from openfga_sdk.models.check_error import CheckError +from openfga_sdk.models.userset import Userset + + +# Same rule the server applies to BatchCheckItem.correlation_id: +# https://github.com/openfga/api/blob/c0650ce2169bcb39a72d73841fb531c200e32248/openfga/v1/openfga_service.proto#L1447 +CORRELATION_ID_PATTERN = re.compile(r"^[\w\d-]{1,36}$", re.ASCII) + +_MISSING = ("missing",) +_UNCOMPARABLE = ("uncomparable",) + +# Values nested deeper than this are sent as is, so comparing them can't run out of stack. +_MAX_DEPTH = 100 + + +class _Unmergeable(Exception): + """A value the SDK can't compare exactly, so the check is sent as is.""" + + +@dataclass +class EquivalentCheckGroup: + """ + A check to send, and the original checks it answers. + """ + + check: ClientBatchCheckItem + members: list[ClientBatchCheckItem] + + +def merge_enabled(options: dict | None) -> bool: + """ + Return whether the `merge_equivalent_checks` option is on. Missing or None means off, + like other options. Raise for any other non-bool, so "true" can't silently leave it off. + """ + value = (options or {}).get("merge_equivalent_checks") + if value is not None and not isinstance(value, bool): + raise FgaValidationException( + f"merge_equivalent_checks must be a bool, got {type(value).__name__}" + ) + return value is True + + +def prepare_checks( + checks: list[ClientBatchCheckItem], authorization_model_id: str | None +) -> str: + """ + Check what merging needs before anything is sent: a model ID, and correlation IDs + that are valid and unique. Checks without a correlation ID get a generated one. + Return the model ID. + """ + if authorization_model_id is None: + raise FgaValidationException( + "authorization_model_id is required when merge_equivalent_checks is on" + ) + + for check in checks: + if check.correlation_id is None: + check.correlation_id = str(uuid.uuid4()) + validate_correlation_ids(checks) + return authorization_model_id + + +def validate_correlation_ids(checks: list[ClientBatchCheckItem]) -> None: + """ + Raise if a correlation ID doesn't match the API rule, or is used twice. + """ + seen: set[str] = set() + for check in checks: + correlation_id = check.correlation_id + # fullmatch, since `$` alone would also accept a trailing newline + if not isinstance(correlation_id, str) or not CORRELATION_ID_PATTERN.fullmatch( + correlation_id + ): + raise FgaValidationException( + f"correlation_id ({correlation_id}) is invalid: it must match {CORRELATION_ID_PATTERN.pattern}" + ) + if correlation_id in seen: + raise FgaValidationException( + f"Duplicate correlation_id ({correlation_id}) provided" + ) + seen.add(correlation_id) + + +def unmerged(checks: list[ClientBatchCheckItem]) -> list[EquivalentCheckGroup]: + """ + One group per check, sent as is. + """ + return [EquivalentCheckGroup(check=check, members=[check]) for check in checks] + + +class ModelAliases: + """ + Where every relation in a model ends after following its aliases. Worked out once + per model and kept in the model cache, so a call only looks relations up. + """ + + def __init__(self, model: AuthorizationModel | None) -> None: + if model is None: + raise ValueError("The authorization model response is empty") + + # type -> relation -> where it ends, or None if its chain points to a missing + # relation or loops. + self._types: dict[str, dict[str, _ResolvedRelation | None]] = {} + for type_definition in model.type_definitions or []: + self._types[type_definition.type] = _resolve_aliases( + type_definition.relations or {} + ) + + def final_relation(self, check: ClientBatchCheckItem) -> str | None: + """ + Return the relation to send the check with, or None to send it as is. + """ + if not all( + isinstance(value, str) + for value in (check.user, check.relation, check.object) + ): + return None + + object_type, separator, object_id = check.object.partition(":") + relations = self._types.get(object_type) + if not separator or relations is None or check.relation not in relations: + return None + + user_type, separator, user_rest = check.user.partition(":") + if not separator or user_type not in self._types: + return None + + user_id, userset_separator, user_relation = user_rest.partition("#") + if userset_separator and user_relation not in self._types[user_type]: + return None + + resolved = relations[check.relation] + if resolved is None: + return None + + # The legacy Check algorithm says a userset always has its own relation on its + # own object, at every step of a chain, so a merged check could get a different + # answer. The weighted graph algorithm drops this rule, so this check can go once + # supported servers no longer use the legacy one: + # https://openfga.dev/blog/weighted-graph-upcoming-changes#5-self-referential-usersets + if ( + userset_separator + and (user_type, user_id) == (object_type, object_id) + and resolved.passes_through(relations[user_relation]) + ): + return None + + # The server's answer can depend on which of these tuples it reads first. + # https://github.com/openfga/openfga/pull/3410 makes the server reject copies + # with different conditions, but servers without it still accept them. + tuple_keys = [ + (contextual_tuple.user, contextual_tuple.relation, contextual_tuple.object) + for contextual_tuple in check.contextual_tuples or [] + ] + if len(set(tuple_keys)) != len(tuple_keys): + return None + + return resolved.final + + +def resolve( + aliases: ModelAliases, checks: list[ClientBatchCheckItem] +) -> list[EquivalentCheckGroup]: + """ + Group checks that are certain to get the same answer, and build the checks to send. + + The result is deterministic: the same model and checks, in the same order, give the + same groups and IDs. Each group is placed at the position of its first check. + """ + checks_with_finals = [(aliases.final_relation(check), check) for check in checks] + + # Comparing context and contextual tuples is the slow part, so only do it for checks + # that share a final relation, user and object with another check. + shared = Counter( + (final_relation, check.user, check.object) + for final_relation, check in checks_with_finals + if final_relation is not None + ) + + # Keyed by final relation first, or None for a check sent as is. Groups keep the + # order of their first check. + groups: dict[tuple, list[ClientBatchCheckItem]] = {} + + for position, (final_relation, check) in enumerate(checks_with_finals): + key: tuple = (final_relation, position) + if final_relation is not None: + key = (final_relation, check.user, check.object) + if shared[key] > 1: + try: + key += ( + _context_key(check.context), + _contextual_tuples_key(check.contextual_tuples), + ) + except _Unmergeable: + # It can't be compared with the others, so it's a group of its own. + key += (_UNCOMPARABLE, position) + + groups.setdefault(key, []).append(check) + + caller_ids = {check.correlation_id for check in checks} + next_number = 1 + result: list[EquivalentCheckGroup] = [] + + for key, members in groups.items(): + first = members[0] + if key[0] is None: + result.append(EquivalentCheckGroup(check=first, members=members)) + continue + + if len(members) == 1: + correlation_id = first.correlation_id + else: + while f"merged-{next_number}" in caller_ids: + next_number += 1 + correlation_id = f"merged-{next_number}" + next_number += 1 + + result.append( + EquivalentCheckGroup( + check=ClientBatchCheckItem( + user=first.user, + relation=key[0], + object=first.object, + correlation_id=correlation_id, + contextual_tuples=first.contextual_tuples, + context=first.context, + ), + members=members, + ) + ) + + return result + + +def expand( + checks: list[ClientBatchCheckItem], + groups: list[EquivalentCheckGroup], + results: dict[str, BatchCheckSingleResult], +) -> list[ClientBatchCheckSingleResponse]: + """ + Copy each group's answer to every check in the group, in the order of `checks`. + + A group with no answer gives an error for every check in it. Answers with unknown + correlation IDs are ignored. + """ + responses: dict[str, ClientBatchCheckSingleResponse] = {} + + for group in groups: + sent_id = group.check.correlation_id + result = results.get(sent_id) + allowed = result.allowed if result is not None else None + error = ( + result.error + if result is not None + else CheckError( + message=f"No result returned for correlation_id ({sent_id})" + ) + ) + + for member in group.members: + responses[member.correlation_id] = ClientBatchCheckSingleResponse( + allowed=allowed, + request=member, + correlation_id=member.correlation_id, + error=error, + ) + + return [responses[check.correlation_id] for check in checks] + + +def _alias_target(rewrite: Userset | None) -> str | None: + """ + Return the relation an alias points to, or None if the rewrite isn't a lone computedUserset. + """ + if rewrite is None or rewrite.computed_userset is None: + return None + + if ( + rewrite.this is not None + or rewrite.tuple_to_userset is not None + or rewrite.union is not None + or rewrite.intersection is not None + or rewrite.difference is not None + ): + return None + + target = rewrite.computed_userset + if target.object or not target.relation: + return None + + return target.relation + + +@dataclass(frozen=True) +class _ResolvedRelation: + """ + Where a relation ends after following its aliases. + + The relations that end at the same final relation form a tree, with each relation + under the one it aliases. A depth-first walk of the tree gives each relation a + `start` when the walk reaches it, and an `end` when the walk has finished + everything under it. So the relations under a relation, and only those, have a + `start` in its [start, end). + + For example, with `define owner: [user]`, `define writer: owner`, + `define admin: owner` and `define member: writer`, the walk gives: + + owner [0, 4) + admin [1, 2) + writer [2, 4) + member [3, 4) + + Following member's aliases reaches writer, because 2 <= 3 < 4, and owner, because + 0 <= 3 < 4. It doesn't reach admin, because 3 isn't in [1, 2). + """ + + final: str + start: int + end: int + + def passes_through(self, other: "_ResolvedRelation | None") -> bool: + """ + Return whether following this relation's aliases reaches `other`. + """ + return other is not None and other.start <= self.start < other.end + + +def _resolve_aliases( + relations: dict[str, Userset], +) -> dict[str, _ResolvedRelation | None]: + """ + Follow the aliases of every relation of a type. A relation is None if its chain + points to a missing relation or loops. + + Each relation that isn't an alias is a final relation. A depth-first walk of its + tree of aliases numbers every relation in it, as described in `_ResolvedRelation`. + A chain that points to a missing relation or loops never reaches a final relation, + so its relations aren't in any tree and stay None. + + Each relation is visited at most twice and nothing recurses, so a long chain can't + make this slow or run out of stack. + """ + targets = { + relation: _alias_target(rewrite) for relation, rewrite in relations.items() + } + + aliased_by: dict[str, list[str]] = {} + for relation, target in targets.items(): + if target is not None: + aliased_by.setdefault(target, []).append(relation) + + # Walk each tree depth-first from its final relation to set each relation's + # [start, end). A relation stays on the stack until everything under it is done, + # so it's seen twice: first to set its start, then its end. A relation aliases + # only one relation, so no walk reaches a relation twice. + resolved: dict[str, _ResolvedRelation | None] = dict.fromkeys(relations) + starts: dict[str, int] = {} + position = 0 + for final, target in targets.items(): + if target is not None: + continue + stack = [final] + while stack: + relation = stack[-1] + if relation in starts: + # Everything under it is done. + stack.pop() + resolved[relation] = _ResolvedRelation( + final, starts[relation], position + ) + else: + starts[relation] = position + position += 1 + stack.extend(aliased_by.get(relation, [])) + + return resolved + + +def _context_key(context) -> tuple: + if context is None: + return _MISSING + + if not isinstance(context, dict): + raise _Unmergeable() + + return _canonical(context) + + +def _contextual_tuples_key(contextual_tuples) -> tuple | frozenset: + if contextual_tuples is None: + return _MISSING + + items = [] + for contextual_tuple in contextual_tuples: + condition = contextual_tuple.condition + condition_key: tuple = _MISSING + if condition is not None: + condition_key = (condition.name, _context_key(condition.context)) + + items.append( + ( + contextual_tuple.user, + contextual_tuple.relation, + contextual_tuple.object, + condition_key, + ) + ) + + return frozenset(Counter(items).items()) + + +def _canonical(value, depth: int = 0) -> tuple: + """ + A hashable form of a JSON value, equal only for values the server sees as equal. + Numbers compare as doubles, including the sign of zero. + """ + if depth > _MAX_DEPTH: + raise _Unmergeable() + + if value is None: + return ("null",) + + if isinstance(value, bool): + return ("bool", value) + + if isinstance(value, int | float): + try: + number = float(value) + except OverflowError as err: + raise _Unmergeable() from err + + if not math.isfinite(number): + raise _Unmergeable() + + return ("number", struct.pack(">d", number)) + + if isinstance(value, str): + return ("string", value) + + if isinstance(value, list): + return ("list", tuple(_canonical(item, depth + 1) for item in value)) + + if isinstance(value, dict): + if not all(isinstance(key, str) for key in value): + raise _Unmergeable() + + return ( + "object", + frozenset( + (key, _canonical(item, depth + 1)) for key, item in value.items() + ), + ) + + raise _Unmergeable() diff --git a/openfga_sdk/client/_model_cache.py b/openfga_sdk/client/_model_cache.py new file mode 100644 index 00000000..5e96cf64 --- /dev/null +++ b/openfga_sdk/client/_model_cache.py @@ -0,0 +1,128 @@ +""" +In-memory cache of authorization models for the async client, used by BatchCheck's +`merge_equivalent_checks` option. Calls for the same model share one in-flight read. +""" + +import asyncio + +from openfga_sdk.api.open_fga_api import OpenFgaApi +from openfga_sdk.client._equivalent_checks import ModelAliases +from openfga_sdk.client._model_cache_base import ( + MAX_MODELS, + ModelCacheBase, + ModelCacheKey, + ModelLookup, + TokenRequestError, + log_model_read_failure, + model_read_kwargs, + model_reader, +) + + +class ModelCache(ModelCacheBase): + """ + Model cache for the async client. + """ + + def __init__(self, max_models: int = MAX_MODELS) -> None: + super().__init__(max_models) + self._loading: dict[ModelCacheKey, asyncio.Task] = {} + + async def get( + self, + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None = None, + ) -> ModelLookup: + """ + Return the aliases of an authorization model, reading the model with `api` if + it isn't cached. If the read fails, the lookup has its error. Calls that overlap + share one read, sent with the options of the call that started it. + :param header(options) - Custom headers to send alongside the model read + """ + key = (store_id, authorization_model_id) + cached = self._cached(key) + if cached is not None: + return cached + + task = self._loading.get(key) + if task is None: + task = asyncio.create_task(self._load(key, api, options)) + task.add_done_callback(_retrieve_exception) + # An eager task can finish before it's registered, so don't keep a done one. + if not task.done(): + self._loading[key] = task + + # Shielded, so a cancelled caller doesn't cancel the read other callers share. + try: + return ModelLookup(aliases=await asyncio.shield(task)) + except Exception as error: + return ModelLookup(error=error) + + async def close(self) -> None: + """ + Cancel in-flight reads. + """ + tasks = list(self._loading.values()) + self._loading.clear() + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def _load( + self, + key: ModelCacheKey, + api: OpenFgaApi, + options: dict[str, int | str | dict[str, int | str]] | None, + ) -> ModelAliases: + try: + aliases = await self._read(api, *key, options) + self._store(key, aliases) + return aliases + finally: + if self._loading.get(key) is asyncio.current_task(): + del self._loading[key] + + async def _read( + self, + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None, + ) -> ModelAliases: + """ + Read the model and work out its aliases. The read is never retried. If the SDK + can't get an access token for it, the error is a TokenRequestError. + """ + try: + response = await model_reader(api, _TokenRequests).read_authorization_model( + authorization_model_id, **model_read_kwargs(options) + ) + return ModelAliases(response.authorization_model) + except Exception as error: + log_model_read_failure(error, store_id, authorization_model_id) + raise + + +class _TokenRequests: + """ + Gets access tokens with an OAuth2 client, and raises a TokenRequestError if it + can't, so the failure isn't mistaken for a failed model read. + """ + + def __init__(self, oauth2_client) -> None: + self._oauth2_client = oauth2_client + + async def get_authentication_header(self, client): + try: + return await self._oauth2_client.get_authentication_header(client) + except Exception as error: + raise TokenRequestError(error) from error + + +def _retrieve_exception(task: asyncio.Task) -> None: + # Marks the error as seen, so asyncio doesn't warn that it was never retrieved + # when every caller timed out before the shared read failed. + if not task.cancelled(): + task.exception() diff --git a/openfga_sdk/client/_model_cache_base.py b/openfga_sdk/client/_model_cache_base.py new file mode 100644 index 00000000..1db26142 --- /dev/null +++ b/openfga_sdk/client/_model_cache_base.py @@ -0,0 +1,138 @@ +""" +The parts of the BatchCheck model cache that the async and sync clients share. Not +part of the public API. + +A model never changes once it's written, so a cached model never goes stale. Only +successful reads are cached, so after a failure the next call reads again. +""" + +import copy +import logging + +from collections import OrderedDict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Protocol, TypeVar + +from openfga_sdk.client._equivalent_checks import ModelAliases +from openfga_sdk.configuration import RetryParams +from openfga_sdk.exceptions import ApiException + + +logger = logging.getLogger(__name__) + +MAX_MODELS = 32 +CREDENTIAL_FAILURE_STATUSES = frozenset({401, 403}) +NOT_FOUND_CODES = frozenset({"authorization_model_not_found", "store_id_not_found"}) + +ModelCacheKey = tuple[str, str] + + +class TokenRequestError(Exception): + """ + The model read failed because the SDK couldn't get an access token for it. The call + fails with `error`, as it would with the option off. + """ + + def __init__(self, error: Exception) -> None: + super().__init__(str(error)) + self.error = error + + +def model_read_fails_call(error: Exception | None) -> bool: + """ + Whether a model read error fails the BatchCheck call instead of sending the checks + unmerged: the SDK couldn't get an access token, the model or store doesn't exist, or + the credentials can't read the model (a 401 or 403). + """ + if isinstance(error, TokenRequestError): + return True + return isinstance(error, ApiException) and ( + error.code in NOT_FOUND_CODES or error.status in CREDENTIAL_FAILURE_STATUSES + ) + + +def model_read_kwargs( + options: dict[str, int | str | dict[str, int | str]] | None = None, +) -> dict[str, Any]: + """ + Return the kwargs for the authorization model read of a BatchCheck call: the + call's headers, and no retries. A failed read either fails the call (see + model_read_fails_call) or sends the checks unmerged right away. + """ + kwargs: dict[str, Any] = {"_retry_params": RetryParams(max_retry=0)} + if options is not None and options.get("headers"): + kwargs["_headers"] = options["headers"] + return kwargs + + +def log_model_read_failure( + error: Exception, store_id: str, authorization_model_id: str +) -> None: + """ + Warn that the checks go out unmerged, unless the error fails the call. + """ + if model_read_fails_call(error): + return + logger.warning( + "merge_equivalent_checks: couldn't read authorization model %s in store %s (status: %s). " + "Sending checks unmerged.", + authorization_model_id, + store_id, + getattr(error, "status", None), + ) + + +class _Api(Protocol): + _oauth2_client: Any + + +ApiT = TypeVar("ApiT", bound=_Api) + + +def model_reader(api: ApiT, token_requests: Callable[[Any], Any]) -> ApiT: + """ + Return a copy of `api` that gets its access token through `token_requests`, which + wraps the OAuth2 client and raises a TokenRequestError if it can't get one. The copy + shares the OAuth2 client, and so the token, with `api`. + """ + if api._oauth2_client is None: + return api + reader = copy.copy(api) + reader._oauth2_client = token_requests(api._oauth2_client) + return reader + + +@dataclass +class ModelLookup: + """ + The result of a cache lookup: the model's aliases, or the error from reading it. + `hit` is True only when they were already in the cache. + """ + + aliases: ModelAliases | None = None + hit: bool = False + error: Exception | None = None + + +class ModelCacheBase: + """ + The cached models. The async and sync caches add the reads. + """ + + def __init__(self, max_models: int = MAX_MODELS) -> None: + self._max_models = max_models + self._models: OrderedDict[ModelCacheKey, ModelAliases] = OrderedDict() + + def _cached(self, key: ModelCacheKey) -> ModelLookup | None: + aliases = self._models.get(key) + if aliases is None: + return None + self._models.move_to_end(key) + return ModelLookup(aliases=aliases, hit=True) + + def _store(self, key: ModelCacheKey, aliases: ModelAliases) -> None: + self._models[key] = aliases + self._models.move_to_end(key) + while len(self._models) > self._max_models: + self._models.popitem(last=False) diff --git a/openfga_sdk/client/client.py b/openfga_sdk/client/client.py index 899e36cd..3dc4abce 100644 --- a/openfga_sdk/client/client.py +++ b/openfga_sdk/client/client.py @@ -7,6 +7,13 @@ from openfga_sdk.api.open_fga_api import OpenFgaApi from openfga_sdk.api_client import ApiClient +from openfga_sdk.client._batch_check_merge import checks_to_send +from openfga_sdk.client._equivalent_checks import ( + expand, + merge_enabled, + prepare_checks, +) +from openfga_sdk.client._model_cache import ModelCache from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( @@ -50,7 +57,10 @@ UnauthorizedException, ) from openfga_sdk.models.assertion import Assertion +from openfga_sdk.models.batch_check_item import BatchCheckItem from openfga_sdk.models.batch_check_request import BatchCheckRequest +from openfga_sdk.models.batch_check_response import BatchCheckResponse +from openfga_sdk.models.batch_check_single_result import BatchCheckSingleResult from openfga_sdk.models.check_request import CheckRequest from openfga_sdk.models.contextual_tuple_keys import ContextualTupleKeys from openfga_sdk.models.create_store_request import CreateStoreRequest @@ -173,6 +183,7 @@ def __init__(self, configuration: ClientConfiguration): self._client_configuration = configuration self._api_client = ApiClient(configuration) self._api = OpenFgaApi(self._api_client) + self._model_cache = ModelCache() # Set default headers from configuration if configuration.headers: @@ -186,6 +197,7 @@ async def __aexit__(self, exc_type, exc_value, traceback): await self.close() async def close(self): + await self._model_cache.close() await self._api.close() def _get_authorization_model_id( @@ -781,6 +793,7 @@ async def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 + :param merge_equivalent_checks(options) - Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request @@ -810,6 +823,20 @@ async def batch_check( elif isinstance(options["max_batch_size"], int): max_batch_size = options["max_batch_size"] + if merge_enabled(options): + # Reading the model and sending the checks must use the same model and store. + authorization_model_id = prepare_checks( + body.checks, self._get_authorization_model_id(options) + ) + return await self._merged_batch_check( + body.checks, + self._api_client._get_store_id(), + authorization_model_id, + options, + max_parallel_requests, + max_batch_size, + ) + id_to_check: dict[str, ClientBatchCheckItem] = {} def track_and_transform(checks): @@ -835,8 +862,7 @@ def track_and_transform(checks): for i in range((len(body.checks) + max_batch_size - 1) // max_batch_size) ] - result = [] - sem = asyncio.Semaphore(max_parallel_requests) + result: list[ClientBatchCheckSingleResponse] = [] def map_response(id, result): check = id_to_check[id] @@ -847,25 +873,83 @@ def map_response(id, result): error=result.error, ) - async def coro(checks): - res = await self._single_batch_check( + for response in await self._send_batch_checks( + checks, + self._get_authorization_model_id(options), + options, + max_parallel_requests, + ): + result.extend( + map_response(c_id, c_result) + for c_id, c_result in response.result.items() + ) + + return ClientBatchCheckResponse(result) + + async def _send_batch_checks( + self, + chunks: list[list[BatchCheckItem]], + authorization_model_id: str | None, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + ) -> list[BatchCheckResponse]: + """ + Send each chunk of checks as one BatchCheck request, with at most + max_parallel_requests in flight, and return the responses in chunk order + """ + sem = asyncio.Semaphore(max_parallel_requests) + consistency = self._get_consistency(options) + + def send(checks): + return self._single_batch_check( BatchCheckRequest( checks=checks, - authorization_model_id=self._get_authorization_model_id(options), - consistency=self._get_consistency(options), + authorization_model_id=authorization_model_id, + consistency=consistency, ), sem, options, ) - result.extend( - [map_response(c_id, c_result) for c_id, c_result in res.result.items()] - ) + return await asyncio.gather(*[send(checks) for checks in chunks]) - batch_check_coros = [coro(request) for request in checks] - await asyncio.gather(*batch_check_coros) + async def _merged_batch_check( + self, + checks: list[ClientBatchCheckItem], + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + max_batch_size: int, + ) -> ClientBatchCheckResponse: + """ + Run a BatchCheck with merge_equivalent_checks on, for checks already validated + """ + if not checks: + return ClientBatchCheckResponse([], checks_sent=0) - return ClientBatchCheckResponse(result) + lookup = await self._model_cache.get( + self._api, store_id, authorization_model_id, options + ) + groups = checks_to_send( + self._api_client, store_id, authorization_model_id, lookup, checks + ) + + results: dict[str, BatchCheckSingleResult] = {} + for response in await self._send_batch_checks( + [ + [construct_batch_item(group.check) for group in chunk] + for chunk in _chuck_array(groups, max_batch_size) + ], + authorization_model_id, + options, + max_parallel_requests, + ): + results.update(response.result or {}) + + return ClientBatchCheckResponse( + expand(checks, groups, results), checks_sent=len(groups) + ) async def expand( self, diff --git a/openfga_sdk/client/models/batch_check_response.py b/openfga_sdk/client/models/batch_check_response.py index bef97aa3..decc654b 100644 --- a/openfga_sdk/client/models/batch_check_response.py +++ b/openfga_sdk/client/models/batch_check_response.py @@ -7,8 +7,10 @@ class ClientBatchCheckResponse: def __init__( self, result: list[ClientBatchCheckSingleResponse], + checks_sent: int | None = None, ) -> None: self._result = result + self._checks_sent = checks_sent @property def result(self) -> list[ClientBatchCheckSingleResponse]: @@ -23,3 +25,17 @@ def result(self, result: list[ClientBatchCheckSingleResponse]) -> None: Set result """ self._result = result + + @property + def checks_sent(self) -> int | None: + """ + Return how many checks this call sent. Set only when merge_equivalent_checks is on. + """ + return self._checks_sent + + @checks_sent.setter + def checks_sent(self, checks_sent: int | None) -> None: + """ + Set checks_sent + """ + self._checks_sent = checks_sent diff --git a/openfga_sdk/sync/client/_model_cache.py b/openfga_sdk/sync/client/_model_cache.py new file mode 100644 index 00000000..0474b698 --- /dev/null +++ b/openfga_sdk/sync/client/_model_cache.py @@ -0,0 +1,120 @@ +""" +In-memory cache of authorization models for the sync client, used by BatchCheck's +`merge_equivalent_checks` option. Calls for the same model share one in-flight read. +""" + +import threading + +from concurrent.futures import Future + +from openfga_sdk.client._equivalent_checks import ModelAliases +from openfga_sdk.client._model_cache_base import ( + MAX_MODELS, + ModelCacheBase, + ModelCacheKey, + ModelLookup, + TokenRequestError, + log_model_read_failure, + model_read_kwargs, + model_reader, +) +from openfga_sdk.sync.open_fga_api import OpenFgaApi + + +class ModelCache(ModelCacheBase): + """ + Model cache for the sync client. Safe to share across threads. + """ + + def __init__(self, max_models: int = MAX_MODELS) -> None: + super().__init__(max_models) + self._lock = threading.Lock() + self._loading: dict[ModelCacheKey, Future] = {} + + def get( + self, + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None = None, + ) -> ModelLookup: + """ + Return the aliases of an authorization model, reading the model with `api` if + it isn't cached. If the read fails, the lookup has its error. Calls that overlap + share one read, sent with the options of the call that started it. + :param header(options) - Custom headers to send alongside the model read + """ + key = (store_id, authorization_model_id) + with self._lock: + cached = self._cached(key) + if cached is not None: + return cached + + future = self._loading.get(key) + owner = future is None + if future is None: + future = Future() + self._loading[key] = future + + if not owner: + try: + return ModelLookup(aliases=future.result()) + except Exception as error: + return ModelLookup(error=error) + + try: + aliases = self._read(api, store_id, authorization_model_id, options) + except Exception as error: + with self._lock: + self._loading.pop(key, None) + future.set_exception(error) + return ModelLookup(error=error) + except BaseException: + with self._lock: + self._loading.pop(key, None) + future.set_exception( + RuntimeError("Reading the authorization model was interrupted") + ) + raise + + with self._lock: + self._store(key, aliases) + self._loading.pop(key, None) + future.set_result(aliases) + return ModelLookup(aliases=aliases) + + def _read( + self, + api: OpenFgaApi, + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]] | None, + ) -> ModelAliases: + """ + Read the model and work out its aliases. The read is never retried. If the SDK + can't get an access token for it, the error is a TokenRequestError. + """ + try: + response = model_reader(api, _TokenRequests).read_authorization_model( + authorization_model_id, **model_read_kwargs(options) + ) + return ModelAliases(response.authorization_model) + except Exception as error: + log_model_read_failure(error, store_id, authorization_model_id) + raise + + +class _TokenRequests: + """ + Gets access tokens with an OAuth2 client, and raises a TokenRequestError if it + can't, so the failure isn't mistaken for a failed model read. + """ + + def __init__(self, oauth2_client) -> None: + self._oauth2_client = oauth2_client + + def get_authentication_header(self, client): + try: + return self._oauth2_client.get_authentication_header(client) + except Exception as error: + raise TokenRequestError(error) from error diff --git a/openfga_sdk/sync/client/client.py b/openfga_sdk/sync/client/client.py index eec9725d..c4222358 100644 --- a/openfga_sdk/sync/client/client.py +++ b/openfga_sdk/sync/client/client.py @@ -5,6 +5,12 @@ from contextlib import closing from typing import Any +from openfga_sdk.client._batch_check_merge import checks_to_send +from openfga_sdk.client._equivalent_checks import ( + expand, + merge_enabled, + prepare_checks, +) from openfga_sdk.client.configuration import ClientConfiguration from openfga_sdk.client.models.assertion import ClientAssertion from openfga_sdk.client.models.batch_check_item import ( @@ -48,7 +54,10 @@ UnauthorizedException, ) from openfga_sdk.models.assertion import Assertion +from openfga_sdk.models.batch_check_item import BatchCheckItem from openfga_sdk.models.batch_check_request import BatchCheckRequest +from openfga_sdk.models.batch_check_response import BatchCheckResponse +from openfga_sdk.models.batch_check_single_result import BatchCheckSingleResult from openfga_sdk.models.check_request import CheckRequest from openfga_sdk.models.contextual_tuple_keys import ContextualTupleKeys from openfga_sdk.models.create_store_request import CreateStoreRequest @@ -71,6 +80,7 @@ ) from openfga_sdk.models.write_request import WriteRequest from openfga_sdk.sync.api_client import ApiClient +from openfga_sdk.sync.client._model_cache import ModelCache from openfga_sdk.sync.open_fga_api import OpenFgaApi from openfga_sdk.validation import is_well_formed_ulid_string @@ -173,6 +183,7 @@ def __init__(self, configuration: ClientConfiguration) -> None: self._client_configuration = configuration self._api_client = ApiClient(configuration) self._api = OpenFgaApi(self._api_client) + self._model_cache = ModelCache() # Set default headers from configuration if configuration.headers: @@ -777,6 +788,7 @@ def batch_check( :param authorization_model_id(options) - Overrides the authorization model id in the configuration :param max_parallel_requests(options) - Max number of requests to issue in parallel. Defaults to 10 :param max_batch_size(options) - Max number of checks to include in a request. Defaults to 50 + :param merge_equivalent_checks(options) - Send checks that are certain to get the same answer only once. Requires an authorization model id and read access to that model :param header(options) - Custom headers to send alongside the request :param retryParams(options) - Override the retry parameters for this request :param retryParams.maxRetry(options) - Override the max number of retries on each API request @@ -806,6 +818,20 @@ def batch_check( elif isinstance(options["max_batch_size"], int): max_batch_size = options["max_batch_size"] + if merge_enabled(options): + # Reading the model and sending the checks must use the same model and store. + authorization_model_id = prepare_checks( + body.checks, self._get_authorization_model_id(options) + ) + return self._merged_batch_check( + body.checks, + self._api_client._get_store_id(), + authorization_model_id, + options, + max_parallel_requests, + max_batch_size, + ) + id_to_check: dict[str, ClientBatchCheckItem] = {} def track_and_transform(checks): @@ -831,6 +857,8 @@ def track_and_transform(checks): for i in range((len(body.checks) + max_batch_size - 1) // max_batch_size) ] + result: list[ClientBatchCheckSingleResponse] = [] + def map_response(id, result): check = id_to_check[id] return ClientBatchCheckSingleResponse( @@ -840,30 +868,82 @@ def map_response(id, result): error=result.error, ) - def single_batch_check(checks): - res = self._single_batch_check( + for response in self._send_batch_checks( + checks, + self._get_authorization_model_id(options), + options, + max_parallel_requests, + ): + result.extend( + map_response(c_id, c_result) + for c_id, c_result in response.result.items() + ) + + return ClientBatchCheckResponse(result) + + def _send_batch_checks( + self, + chunks: list[list[BatchCheckItem]], + authorization_model_id: str | None, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + ) -> list[BatchCheckResponse]: + """ + Send each chunk of checks as one BatchCheck request, with at most + max_parallel_requests in flight, and return the responses in chunk order + """ + consistency = self._get_consistency(options) + + def send(checks): + return self._single_batch_check( BatchCheckRequest( checks=checks, - authorization_model_id=self._get_authorization_model_id(options), - consistency=self._get_consistency(options), + authorization_model_id=authorization_model_id, + consistency=consistency, ), options, ) - return res + with ThreadPoolExecutor(max_workers=max_parallel_requests) as executor: + return list(executor.map(send, chunks)) - result = [] + def _merged_batch_check( + self, + checks: list[ClientBatchCheckItem], + store_id: str, + authorization_model_id: str, + options: dict[str, int | str | dict[str, int | str]], + max_parallel_requests: int, + max_batch_size: int, + ) -> ClientBatchCheckResponse: + """ + Run a BatchCheck with merge_equivalent_checks on, for checks already validated + """ + if not checks: + return ClientBatchCheckResponse([], checks_sent=0) - with ThreadPoolExecutor(max_workers=max_parallel_requests) as executor: - for response in executor.map(single_batch_check, checks): - result.extend( - [ - map_response(c_id, c_result) - for c_id, c_result in response.result.items() - ] - ) + lookup = self._model_cache.get( + self._api, store_id, authorization_model_id, options + ) + groups = checks_to_send( + self._api_client, store_id, authorization_model_id, lookup, checks + ) - return ClientBatchCheckResponse(result) + results: dict[str, BatchCheckSingleResult] = {} + for response in self._send_batch_checks( + [ + [construct_batch_item(group.check) for group in chunk] + for chunk in _chuck_array(groups, max_batch_size) + ], + authorization_model_id, + options, + max_parallel_requests, + ): + results.update(response.result or {}) + + return ClientBatchCheckResponse( + expand(checks, groups, results), checks_sent=len(groups) + ) def expand( self, diff --git a/openfga_sdk/telemetry/attributes.py b/openfga_sdk/telemetry/attributes.py index 02451c1f..edb06b09 100644 --- a/openfga_sdk/telemetry/attributes.py +++ b/openfga_sdk/telemetry/attributes.py @@ -38,6 +38,9 @@ class TelemetryAttributes: fga_client_user: TelemetryAttribute = TelemetryAttribute( name="fga-client.user", ) + fga_client_model_cache_result: TelemetryAttribute = TelemetryAttribute( + name="fga-client.model_cache.result", + ) http_client_request_duration: TelemetryAttribute = TelemetryAttribute( name="http.client.request.duration", format="int", @@ -78,6 +81,7 @@ class TelemetryAttributes: fga_client_request_store_id, fga_client_response_model_id, fga_client_user, + fga_client_model_cache_result, http_client_request_duration, http_host, http_request_method, diff --git a/openfga_sdk/telemetry/configuration.py b/openfga_sdk/telemetry/configuration.py index 40958e88..b8922010 100644 --- a/openfga_sdk/telemetry/configuration.py +++ b/openfga_sdk/telemetry/configuration.py @@ -479,6 +479,7 @@ def clear(self) -> None: TelemetryAttributes.fga_client_request_store_id: False, TelemetryAttributes.fga_client_response_model_id: False, TelemetryAttributes.fga_client_user: False, + TelemetryAttributes.fga_client_model_cache_result: False, TelemetryAttributes.http_client_request_duration: False, TelemetryAttributes.http_host: False, TelemetryAttributes.http_request_method: False, @@ -616,6 +617,7 @@ def getSdkDefaults() -> dict[TelemetryAttribute | str, bool]: TelemetryAttributes.fga_client_request_store_id: True, TelemetryAttributes.fga_client_response_model_id: True, TelemetryAttributes.fga_client_user: False, + TelemetryAttributes.fga_client_model_cache_result: True, TelemetryAttributes.http_client_request_duration: False, TelemetryAttributes.http_host: True, TelemetryAttributes.http_request_method: True, @@ -828,6 +830,10 @@ def clear(self) -> None: TelemetryCounters.fga_client_credentials_request: None, TelemetryHistograms.fga_client_request_duration: None, TelemetryHistograms.fga_client_query_duration: None, + TelemetryCounters.fga_client_batch_check_checks_requested: None, + TelemetryCounters.fga_client_batch_check_checks_sent: None, + TelemetryCounters.fga_client_model_cache_lookup: None, + TelemetryCounters.fga_client_batch_check_merge_fallback: None, } self._valid = True @@ -990,6 +996,10 @@ def getSdkDefaults() -> dict[ TelemetryCounters.fga_client_credentials_request: TelemetryMetricConfiguration.getSdkDefaults(), TelemetryHistograms.fga_client_query_duration: TelemetryMetricConfiguration.getSdkDefaults(), TelemetryHistograms.fga_client_request_duration: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_batch_check_checks_requested: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_batch_check_checks_sent: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_model_cache_lookup: TelemetryMetricConfiguration.getSdkDefaults(), + TelemetryCounters.fga_client_batch_check_merge_fallback: TelemetryMetricConfiguration.getSdkDefaults(), } diff --git a/openfga_sdk/telemetry/counters.py b/openfga_sdk/telemetry/counters.py index 7e2e0ae0..17954bc8 100644 --- a/openfga_sdk/telemetry/counters.py +++ b/openfga_sdk/telemetry/counters.py @@ -18,9 +18,33 @@ class TelemetryCounters: description="Total number of requests made to the FGA server.", ) + fga_client_batch_check_checks_requested: TelemetryCounter = TelemetryCounter( + name="fga-client.batch_check.checks_requested", + description="Total number of checks passed to BatchCheck with merge_equivalent_checks on.", + ) + + fga_client_batch_check_checks_sent: TelemetryCounter = TelemetryCounter( + name="fga-client.batch_check.checks_sent", + description="Total number of checks sent by BatchCheck with merge_equivalent_checks on.", + ) + + fga_client_model_cache_lookup: TelemetryCounter = TelemetryCounter( + name="fga-client.model_cache.lookup", + description="Total number of authorization model cache lookups.", + ) + + fga_client_batch_check_merge_fallback: TelemetryCounter = TelemetryCounter( + name="fga-client.batch_check.merge_fallback", + description="Total number of BatchCheck calls sent unmerged because the authorization model read failed with an error that doesn't fail the call (such as a 429, a 5xx or a timeout), or the checks couldn't be grouped.", + ) + _counters: list[TelemetryCounter] = [ fga_client_credentials_request, fga_client_request, + fga_client_batch_check_checks_requested, + fga_client_batch_check_checks_sent, + fga_client_model_cache_lookup, + fga_client_batch_check_merge_fallback, ] @staticmethod diff --git a/openfga_sdk/telemetry/metrics.py b/openfga_sdk/telemetry/metrics.py index 3cc9d739..128583fb 100644 --- a/openfga_sdk/telemetry/metrics.py +++ b/openfga_sdk/telemetry/metrics.py @@ -63,6 +63,103 @@ def histogram(self, histogram: TelemetryHistogram) -> Histogram: return self._histograms[histogram.name] + def _add( + self, + counter: TelemetryCounter, + value: int, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None, + configuration: TelemetryConfiguration | None, + ) -> Counter: + instrument = self.counter(counter) + + if isMetricEnabled(configuration, counter): + attribute_filters = None + + if isinstance(configuration, TelemetryConfiguration) and isinstance( + configuration.metrics, TelemetryMetricsConfiguration + ): + metric_configuration = configuration.metrics.getMetrics( + filter_enabled=False + ).get(counter) + + if isinstance(metric_configuration, TelemetryMetricConfiguration): + attribute_filters = metric_configuration.getAttributes() + + prepared_attributes = TelemetryAttributes.prepare( + attributes, + filter=attribute_filters, + ) + + instrument.add(amount=value, attributes=prepared_attributes) + + return instrument + + def batchCheckChecksRequested( + self, + value: int, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record the checks passed to BatchCheck with merge_equivalent_checks on. + """ + return self._add( + TelemetryCounters.fga_client_batch_check_checks_requested, + value, + attributes, + configuration, + ) + + def batchCheckChecksSent( + self, + value: int, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record the checks sent by BatchCheck with merge_equivalent_checks on. + """ + return self._add( + TelemetryCounters.fga_client_batch_check_checks_sent, + value, + attributes, + configuration, + ) + + def modelCacheLookup( + self, + value: int = 1, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record an authorization model cache lookup. + """ + return self._add( + TelemetryCounters.fga_client_model_cache_lookup, + value, + attributes, + configuration, + ) + + def batchCheckMergeFallback( + self, + value: int = 1, + attributes: dict[TelemetryAttribute, str | bool | int | float] | None = None, + configuration: TelemetryConfiguration | None = None, + ) -> Counter: + """ + Record a BatchCheck call sent unmerged because the authorization model read + failed with an error that doesn't fail the call (such as a 429, a 5xx or a + timeout), or the checks couldn't be grouped. + """ + return self._add( + TelemetryCounters.fga_client_batch_check_merge_fallback, + value, + attributes, + configuration, + ) + def request( self, value: int = 1, diff --git a/test/client/batch_check_merge_test.py b/test/client/batch_check_merge_test.py new file mode 100644 index 00000000..220bdb8b --- /dev/null +++ b/test/client/batch_check_merge_test.py @@ -0,0 +1,936 @@ +import asyncio +import json + +from dataclasses import replace +from datetime import datetime +from unittest import IsolatedAsyncioTestCase +from unittest.mock import patch + +import aiohttp +import urllib3 + +from openfga_sdk import rest +from openfga_sdk.api_client import ApiClient +from openfga_sdk.client import ClientConfiguration +from openfga_sdk.client.client import OpenFgaClient +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest +from openfga_sdk.client.models.batch_check_response import ClientBatchCheckResponse +from openfga_sdk.configuration import RetryParams +from openfga_sdk.credentials import CredentialConfiguration, Credentials +from openfga_sdk.exceptions import ( + AuthenticationError, + FgaValidationException, + ForbiddenException, + NotFoundException, + RateLimitExceededError, + ServiceException, + UnauthorizedException, + ValidationException, +) +from openfga_sdk.models.consistency_preference import ConsistencyPreference +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.metrics import TelemetryMetrics + + +STORE_ID = "01YCP46JKYM8FJCQ37NMBYHE5X" +MODEL_ID = "01GXSA8YR785C4FYS3C0RTG7B1" +OTHER_MODEL_ID = "01HVMMBCMGZNT3SED4Z17ECXCA" +API_URL = "http://api.fga.example" +MODELS_URL = f"{API_URL}/stores/{STORE_ID}/authorization-models/" +BATCH_CHECK_URL = f"{API_URL}/stores/{STORE_ID}/batch-check" +TOKEN_URL = "https://issuer.fga.example/oauth/token" + +# define viewer: [user], can_view: viewer, can_share: can_view, editor: [user] +MODEL = { + "id": MODEL_ID, + "schema_version": "1.1", + "type_definitions": [ + {"type": "user"}, + { + "type": "document", + "relations": { + "viewer": {"this": {}}, + "can_view": {"computedUserset": {"relation": "viewer"}}, + "can_share": {"computedUserset": {"relation": "can_view"}}, + "editor": {"this": {}}, + }, + "metadata": { + "relations": { + "viewer": {"directly_related_user_types": [{"type": "user"}]}, + "can_view": {"directly_related_user_types": []}, + "can_share": {"directly_related_user_types": []}, + "editor": {"directly_related_user_types": [{"type": "user"}]}, + } + }, + }, + ], +} + + +def http_mock_response(body, status): + headers = urllib3.response.HTTPHeaderDict({"content-type": "application/json"}) + return urllib3.HTTPResponse( + body.encode("utf-8"), headers, status, preload_content=False + ) + + +def mock_response(body, status=200): + obj = http_mock_response(body, status) + return rest.RESTResponse(obj, obj.data) + + +def token_issued(): + return json.dumps({"access_token": "token", "expires_in": 3600}) + + +def short_lived_token_issued(): + # Expires within the SDK's renewal buffer, so every request gets a new token + return json.dumps({"access_token": "token", "expires_in": 300}) + + +def short_lived_tokens_then_rate_limited(count): + responses = iter([short_lived_token_issued] * count) + return lambda: next(responses, rate_limited)() + + +def no_token_issued(): + return "{}" + + +def token_due_for_renewal_when_used(client): + """ + Make the client's token due for renewal right when a request gets it, as if it got + there just after any earlier check. + """ + oauth2_client = client._api._oauth2_client + update_params_for_auth = ApiClient.update_params_for_auth + + async def renewal_due(api_client, *args, **kwargs): + oauth2_client._token_state = replace( + oauth2_client._token_state, expiry_time=datetime.now() + ) + return await update_params_for_auth(api_client, *args, **kwargs) + + return patch.object(ApiClient, "update_params_for_auth", renewal_due) + + +def token_configuration(): + """ + A configuration that gets a token from TOKEN_URL, and retries a failed token + request once. + """ + return ClientConfiguration( + api_url=API_URL, + store_id=STORE_ID, + authorization_model_id=MODEL_ID, + credentials=Credentials( + method="client_credentials", + configuration=CredentialConfiguration( + client_id="client-id", + client_secret="client-secret", + api_issuer=TOKEN_URL, + api_audience="audience", + ), + ), + retry_params=RetryParams(max_retry=1), + ) + + +def checks(): + return [ + ClientBatchCheckItem( + user="user:anne", relation="viewer", object="document:1", correlation_id="a" + ), + ClientBatchCheckItem( + user="user:anne", + relation="can_view", + object="document:1", + correlation_id="b", + ), + ClientBatchCheckItem( + user="user:anne", + relation="can_share", + object="document:1", + correlation_id="c", + ), + ClientBatchCheckItem( + user="user:anne", relation="editor", object="document:1", correlation_id="d" + ), + ] + + +class FakeServer: + """ + Answers token requests, model reads and BatchCheck requests, and records what was + sent. + """ + + respond = staticmethod(mock_response) + + def __init__( + self, model_error=None, answer=None, model_body=None, token=token_issued + ): + self.token = token + self.token_requests = 0 + self.model_error = model_error + self.model_body = ( + {"authorization_model": MODEL} if model_body is None else model_body + ) + self.answer = answer or ( + lambda check: {"allowed": check["tuple_key"]["relation"] == "viewer"} + ) + self.model_reads = 0 + self.model_ids_read = [] + self.model_read_headers = [] + self.sent = [] + + def __call__(self, method, url, **kwargs): + if method == "POST" and url == TOKEN_URL: + self.token_requests += 1 + body = self.token() + if isinstance(body, Exception): + raise body + return self.respond(body) + + if method == "GET" and url.startswith(MODELS_URL): + self.model_reads += 1 + self.model_ids_read.append(url.removeprefix(MODELS_URL)) + self.model_read_headers.append(kwargs.get("headers") or {}) + if self.model_error is not None: + raise self.model_error() + return self.respond(json.dumps(self.model_body)) + + if method == "POST" and url == BATCH_CHECK_URL: + body = kwargs["body"] + self.sent.append(body) + return self.respond( + json.dumps( + { + "result": { + check["correlation_id"]: self.answer(check) + for check in body["checks"] + } + } + ) + ) + + raise AssertionError(f"Unexpected request: {method} {url}") + + +def sent_checks(server): + return [ + ( + check["correlation_id"], + check["tuple_key"]["relation"], + ) + for body in server.sent + for check in body["checks"] + ] + + +def forbidden(): + return ForbiddenException(http_resp=http_mock_response("{}", 403)) + + +def unauthorized(): + return UnauthorizedException(http_resp=http_mock_response("{}", 401)) + + +def rate_limited(): + return RateLimitExceededError(http_resp=http_mock_response("{}", 429)) + + +def server_error(): + return ServiceException(http_resp=http_mock_response("{}", 500)) + + +def timed_out(): + return TimeoutError("timed out") + + +def connection_dropped(): + return aiohttp.ClientConnectionError("connection reset") + + +def store_not_found(): + body = {"code": "store_id_not_found", "message": f"Store '{STORE_ID}' not found"} + return NotFoundException(http_resp=http_mock_response(json.dumps(body), 404)) + + +def bad_request(): + return ValidationException(http_resp=http_mock_response("{}", 400)) + + +UNMERGED = [("a", "viewer"), ("b", "can_view"), ("c", "can_share"), ("d", "editor")] + + +def model_not_found(): + body = { + "code": "authorization_model_not_found", + "message": f"Authorization Model '{MODEL_ID}' not found", + } + return ValidationException(http_resp=http_mock_response(json.dumps(body), 400)) + + +class TestBatchCheckMergeEquivalentChecks(IsolatedAsyncioTestCase): + def setUp(self): + self.configuration = ClientConfiguration( + api_url=API_URL, + store_id=STORE_ID, + authorization_model_id=MODEL_ID, + ) + + async def batch_check(self, client, items, options=None): + return await client.batch_check( + ClientBatchCheckRequest(checks=items), + options={"merge_equivalent_checks": True, **(options or {})}, + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_merges_aliases_and_copies_the_answer_back(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + items = checks() + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, items) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(server.sent[0]["authorization_model_id"], MODEL_ID) + self.assertEqual(response.checks_sent, 2) + self.assertEqual( + [(r.correlation_id, r.allowed, r.error) for r in response.result], + [ + ("a", True, None), + ("b", True, None), + ("c", True, None), + ("d", False, None), + ], + ) + self.assertEqual([r.request for r in response.result], items) + + @patch.object(rest.RESTClientObject, "request") + async def test_merges_checks_that_would_land_in_different_batches( + self, mock_request + ): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check( + client, checks()[:3], options={"max_batch_size": 1} + ) + + self.assertEqual(sent_checks(server), [("merged-1", "viewer")]) + self.assertEqual(response.checks_sent, 1) + self.assertEqual(len(response.result), 3) + + @patch.object(rest.RESTClientObject, "request") + async def test_reads_the_model_once_for_parallel_and_later_calls( + self, mock_request + ): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await asyncio.gather( + *[self.batch_check(client, checks()) for _ in range(5)] + ) + await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(len(server.sent), 6) + + @patch.object(rest.RESTClientObject, "request") + async def test_requires_a_model_id(self, mock_request): + self.configuration.authorization_model_id = None + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, "authorization_model_id" + ): + await self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_requires_a_store_id(self, mock_request): + self.configuration.store_id = None + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex(FgaValidationException, "store_id"): + await self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_the_model_id_in_the_options_wins(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + await self.batch_check(client, checks()) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID, MODEL_ID]) + self.assertEqual( + [body["authorization_model_id"] for body in server.sent], + [OTHER_MODEL_ID, MODEL_ID], + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_uses_the_model_id_in_the_options_when_none_is_configured( + self, mock_request + ): + self.configuration.authorization_model_id = None + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID]) + self.assertEqual(server.sent[0]["authorization_model_id"], OTHER_MODEL_ID) + self.assertEqual(response.checks_sent, 2) + + @patch.object(rest.RESTClientObject, "request") + async def test_rejects_an_option_value_that_is_not_a_bool(self, mock_request): + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, "merge_equivalent_checks must be a bool" + ): + await self.batch_check( + client, checks(), options={"merge_equivalent_checks": "true"} + ) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_reads_the_model_with_the_callers_headers(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check( + client, checks(), options={"headers": {"X-Custom": "1"}} + ) + + self.assertEqual(server.model_read_headers[0].get("X-Custom"), "1") + + @patch.object(rest.RESTClientObject, "request") + async def test_sends_the_consistency_option(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check( + client, + checks(), + options={"consistency": ConsistencyPreference.HIGHER_CONSISTENCY}, + ) + + self.assertEqual(server.sent[0]["consistency"], "HIGHER_CONSISTENCY") + + @patch.object(rest.RESTClientObject, "request") + async def test_rejects_invalid_correlation_ids(self, mock_request): + for correlation_id in ["has space", "x" * 37, "é", "a\n"]: + items = checks() + items[0].correlation_id = correlation_id + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(FgaValidationException): + await self.batch_check(client, items) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_rejects_duplicate_correlation_ids(self, mock_request): + items = checks() + items[1].correlation_id = "a" + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, r"Duplicate correlation_id \(a\) provided" + ): + await self.batch_check(client, items) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_generates_missing_correlation_ids(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + items = checks() + items[3].correlation_id = None + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, items) + + self.assertIsNotNone(items[3].correlation_id) + self.assertEqual(response.result[3].correlation_id, items[3].correlation_id) + + def test_checks_sent_defaults_to_none_and_can_be_set(self): + response = ClientBatchCheckResponse([]) + self.assertIsNone(response.checks_sent) + + response.checks_sent = 3 + + self.assertEqual(response.checks_sent, 3) + + @patch.object(rest.RESTClientObject, "request") + async def test_no_checks_sends_nothing(self, mock_request): + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, []) + + self.assertEqual(response.result, []) + self.assertEqual(response.checks_sent, 0) + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_model_cannot_be_read(self, mock_request): + server = FakeServer(model_error=rate_limited) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ) as logs: + response = await self.batch_check(client, checks()) + second = await self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertIn(MODEL_ID, logs.output[0]) + self.assertIn(STORE_ID, logs.output[0]) + self.assertIn("429", logs.output[0]) + self.assertEqual(server.model_reads, 2) + self.assertEqual(sent_checks(server), UNMERGED * 2) + self.assertEqual(response.checks_sent, 4) + self.assertEqual(second.checks_sent, 4) + self.assertEqual( + [r.allowed for r in response.result], [True, False, False, False] + ) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_server_fails_or_times_out( + self, mock_request, mock_fallback + ): + for model_error, status in [(server_error, 500), (timed_out, None)]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + response = await self.batch_check(client, checks()) + await self.batch_check(client, checks()) + + self.assertEqual(sent_checks(server), UNMERGED * 2) + self.assertEqual(response.checks_sent, 4) + self.assertEqual(server.model_reads, 2) + self.assertEqual( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ], + status, + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_does_not_retry_the_model_read(self, mock_request): + retries = {"retry_params": RetryParams(max_retry=3, min_wait_in_ms=1)} + for model_error in [rate_limited, server_error, connection_dropped]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + await self.batch_check(client, checks(), retries) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch( + "openfga_sdk.client._batch_check_merge.resolve", + side_effect=RuntimeError("boom"), + ) + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_grouping_fails( + self, mock_request, _resolve, mock_fallback + ): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: + response = await self.batch_check(client, checks()) + + self.assertIn("couldn't group the checks", logs.output[0]) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + self.assertEqual( + [r.allowed for r in response.result], [True, False, False, False] + ) + self.assertIsNone( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ] + ) + + @patch.object(rest.RESTClientObject, "request") + async def test_fails_before_sending_when_the_store_does_not_exist( + self, mock_request + ): + server = FakeServer(model_error=store_not_found) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client._model_cache_base", "WARNING"): + with self.assertRaises(NotFoundException): + await self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_fails_like_the_option_off_when_the_token_request_fails( + self, mock_request, mock_fallback + ): + for token, error_type in [ + (unauthorized, UnauthorizedException), + (bad_request, ValidationException), + (rate_limited, RateLimitExceededError), + (server_error, ServiceException), + (connection_dropped, aiohttp.ClientConnectionError), + (no_token_issued, AuthenticationError), + ]: + with self.subTest(token=token.__name__): + token_requests = [] + for merge in [False, True]: + server = FakeServer(token=token) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + with self.assertRaises(error_type): + await client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(server.sent, []) + token_requests.append(server.token_requests) + + self.assertEqual(token_requests[1], token_requests[0]) + + mock_fallback.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + async def test_the_next_call_works_after_a_failed_token_request(self, mock_request): + server = FakeServer(token=rate_limited) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + with self.assertRaises(RateLimitExceededError): + await self.batch_check(client, checks()) + + server.token = token_issued + response = await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(response.checks_sent, 2) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_fails_when_the_model_read_cannot_renew_the_token( + self, mock_request, mock_fallback + ): + for renewals in [0, 1]: + with self.subTest(renewals_before_failing=renewals): + server = FakeServer(token=short_lived_token_issued) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + await client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = short_lived_tokens_then_rate_limited(renewals) + + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + await self.batch_check(client, checks()) + + server.token = short_lived_token_issued + response = await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(response.checks_sent, 2) + + mock_fallback.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_fails_like_the_option_off_when_the_token_is_due_just_before_the_read( + self, mock_request, mock_fallback + ): + token_requests = [] + for merge in [False, True]: + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + await client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = rate_limited + + with token_due_for_renewal_when_used(client): + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + await client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(len(server.sent), 1) + token_requests.append(server.token_requests) + + self.assertEqual(token_requests[1], token_requests[0]) + mock_fallback.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_read_fails_after_renewing_the_token( + self, mock_request, mock_fallback + ): + server = FakeServer(model_error=rate_limited, token=short_lived_token_issued) + mock_request.side_effect = server + + async with OpenFgaClient(token_configuration()) as client: + with self.assertLogs("openfga_sdk.client._model_cache_base", "WARNING"): + response = await self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + mock_fallback.assert_called_once() + + @patch.object(rest.RESTClientObject, "request") + async def test_fails_before_sending_when_the_model_does_not_exist( + self, mock_request + ): + server = FakeServer(model_error=model_not_found) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client._model_cache_base", "WARNING"): + for _ in range(2): + with self.assertRaises(ValidationException) as raised: + await self.batch_check(client, checks()) + self.assertEqual( + raised.exception.code, "authorization_model_not_found" + ) + + self.assertEqual(server.sent, []) + self.assertEqual(server.model_reads, 2) + + @patch.object(rest.RESTClientObject, "request") + async def test_fails_before_sending_when_the_credentials_cannot_read_the_model( + self, mock_request + ): + for model_error, error_type in [ + (unauthorized, UnauthorizedException), + (forbidden, ForbiddenException), + ]: + with self.subTest(status=error_type.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + for _ in range(2): + with self.assertRaises(error_type): + await self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + self.assertEqual(server.model_reads, 2) + + @patch.object(rest.RESTClientObject, "request") + async def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): + server = FakeServer(model_body={}) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ) as logs: + response = await self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + + @patch.object(rest.RESTClientObject, "request") + async def test_copies_an_error_to_every_check_in_the_group(self, mock_request): + server = FakeServer( + answer=lambda check: ( + {"error": {"message": "boom"}} + if check["correlation_id"] == "merged-1" + else {"allowed": True} + ) + ) + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, checks()) + + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual(result.error.message, "boom") + self.assertTrue(response.result[3].allowed) + self.assertIsNone(response.result[3].error) + + @patch.object(rest.RESTClientObject, "request") + async def test_a_missing_answer_is_an_error_and_unknown_answers_are_ignored( + self, mock_request + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + return mock_response( + json.dumps( + {"result": {"d": {"allowed": True}, "unknown": {"allowed": True}}} + ) + ) + + mock_request.side_effect = handle + + async with OpenFgaClient(self.configuration) as client: + response = await self.batch_check(client, checks()) + + self.assertEqual( + [r.correlation_id for r in response.result], ["a", "b", "c", "d"] + ) + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual( + result.error.message, "No result returned for correlation_id (merged-1)" + ) + self.assertTrue(response.result[3].allowed) + + @patch.object(rest.RESTClientObject, "request") + async def test_a_failed_request_fails_the_call(self, mock_request): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + raise ValidationException(http_resp=http_mock_response("{}", 400)) + + mock_request.side_effect = handle + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException): + await self.batch_check(client, checks()) + + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(rest.RESTClientObject, "request") + async def test_counts_checks_even_when_a_request_fails( + self, mock_request, mock_requested, mock_sent + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + raise ValidationException(http_resp=http_mock_response("{}", 400)) + + mock_request.side_effect = handle + + async with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException): + await self.batch_check(client, checks()) + + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_sent.call_args.args, (2,)) + + @patch.object(rest.RESTClientObject, "request") + async def test_option_off_is_unchanged(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + async with OpenFgaClient(self.configuration) as client: + response = await client.batch_check( + ClientBatchCheckRequest(checks=checks()) + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertIsNone(response.checks_sent) + + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(TelemetryMetrics, "modelCacheLookup") + @patch.object(rest.RESTClientObject, "request") + async def test_records_telemetry( + self, mock_request, mock_lookup, mock_fallback, mock_requested, mock_sent + ): + mock_request.side_effect = FakeServer() + attributes = { + TelemetryAttributes.fga_client_request_store_id: STORE_ID, + TelemetryAttributes.fga_client_request_model_id: MODEL_ID, + } + + async with OpenFgaClient(self.configuration) as client: + await self.batch_check(client, checks()) + await self.batch_check(client, checks()) + + self.assertEqual( + [ + call.kwargs["attributes"][ + TelemetryAttributes.fga_client_model_cache_result + ] + for call in mock_lookup.call_args_list + ], + ["miss", "hit"], + ) + mock_fallback.assert_not_called() + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_requested.call_args.kwargs["attributes"], attributes) + self.assertEqual(mock_sent.call_args.args, (2,)) + self.assertEqual(mock_sent.call_args.kwargs["attributes"], attributes) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + async def test_records_the_fallback_with_its_status_code( + self, mock_request, mock_fallback + ): + mock_request.side_effect = FakeServer(model_error=rate_limited) + + async with OpenFgaClient(self.configuration) as client: + with self.assertLogs("openfga_sdk.client._model_cache_base", "WARNING"): + await self.batch_check(client, checks()) + + attributes = mock_fallback.call_args.kwargs["attributes"] + self.assertEqual(attributes[TelemetryAttributes.http_response_status_code], 429) + self.assertEqual( + attributes[TelemetryAttributes.fga_client_request_model_id], MODEL_ID + ) diff --git a/test/client/equivalent_checks_cases_test.py b/test/client/equivalent_checks_cases_test.py new file mode 100644 index 00000000..eb4e38bb --- /dev/null +++ b/test/client/equivalent_checks_cases_test.py @@ -0,0 +1,110 @@ +""" +Runs the shared equivalent-checks cases from openfga/language against the Python resolver. + +The cases file is copied from openfga/language. Run `make update-equivalent-checks-cases` +to update it. +""" + +import json + +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openfga_sdk.client._equivalent_checks import ModelAliases, resolve +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.tuple import ClientTuple +from openfga_sdk.models.relationship_condition import RelationshipCondition +from openfga_sdk.sync.api_client import ApiClient + + +CASES_FILE = Path(__file__).parent.parent / "data" / "equivalent-checks-cases.json" +CASES = json.loads(CASES_FILE.read_text())["cases"] +MODEL_ID = "01GXSA8YR785C4FYS3C0RTG7B1" + + +def _model(model_json): + with ApiClient() as api_client: + return api_client.deserialize( + SimpleNamespace(data=json.dumps(dict(model_json, id=MODEL_ID))), + "AuthorizationModel", + ) + + +def _contextual_tuple(tuple_json): + condition = tuple_json.get("condition") + return ClientTuple( + user=tuple_json["user"], + relation=tuple_json["relation"], + object=tuple_json["object"], + condition=( + RelationshipCondition( + name=condition["name"], context=condition.get("context") + ) + if condition is not None + else None + ), + ) + + +def _check(check_json): + contextual_tuples = check_json.get("contextual_tuples") + return ClientBatchCheckItem( + user=check_json["user"], + relation=check_json["relation"], + object=check_json["object"], + correlation_id=check_json["id"], + context=check_json.get("context"), + contextual_tuples=( + [_contextual_tuple(item) for item in contextual_tuples] + if contextual_tuples is not None + else None + ), + ) + + +def _tuple_as_json(item): + result = {"user": item.user, "relation": item.relation, "object": item.object} + if item.condition is not None: + result["condition"] = {"name": item.condition.name} + if item.condition.context is not None: + result["condition"]["context"] = item.condition.context + return result + + +def _sent_as_json(group): + check = group.check + result = { + "id": check.correlation_id, + "user": check.user, + "relation": check.relation, + "object": check.object, + } + if check.context is not None: + result["context"] = check.context + if check.contextual_tuples is not None: + result["contextual_tuples"] = [ + _tuple_as_json(item) for item in check.contextual_tuples + ] + result["for"] = [member.correlation_id for member in group.members] + return result + + +def test_cases_file_is_not_empty(): + assert len(CASES) > 0 + + +@pytest.mark.parametrize("case", CASES, ids=[case["name"] for case in CASES]) +def test_equivalent_checks_case(case): + checks = [_check(check) for check in case["checks"]] + + groups = resolve(ModelAliases(_model(case["model"])), checks) + + assert [_sent_as_json(group) for group in groups] == case["expected_sent"] + + # `==` treats 1 and 1.0 as equal, so also make sure the first check's values are sent unchanged. + for group in groups: + first = group.members[0] + assert group.check.context is first.context + assert group.check.contextual_tuples is first.contextual_tuples diff --git a/test/client/equivalent_checks_test.py b/test/client/equivalent_checks_test.py new file mode 100644 index 00000000..b087bfb7 --- /dev/null +++ b/test/client/equivalent_checks_test.py @@ -0,0 +1,431 @@ +import datetime +import math + +import pytest + +from openfga_sdk.client._equivalent_checks import ( + EquivalentCheckGroup, + ModelAliases, + expand, + merge_enabled, + prepare_checks, + resolve, + unmerged, + validate_correlation_ids, +) +from openfga_sdk.client.models.batch_check_item import ClientBatchCheckItem +from openfga_sdk.client.models.tuple import ClientTuple +from openfga_sdk.exceptions import FgaValidationException +from openfga_sdk.models.authorization_model import AuthorizationModel +from openfga_sdk.models.batch_check_single_result import BatchCheckSingleResult +from openfga_sdk.models.check_error import CheckError +from openfga_sdk.models.object_relation import ObjectRelation +from openfga_sdk.models.relationship_condition import RelationshipCondition +from openfga_sdk.models.type_definition import TypeDefinition +from openfga_sdk.models.userset import Userset + + +# define viewer: [user], can_view: viewer +MODEL = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition( + type="document", + relations={ + "viewer": Userset(this={}), + "can_view": Userset( + computed_userset=ObjectRelation(object="", relation="viewer") + ), + }, + ), + ], +) +ALIASES = ModelAliases(MODEL) + + +def nested(depth): + value = 1 + for _ in range(depth): + value = {"k": value} + return value + + +def check(correlation_id, relation="can_view", context=None, contextual_tuples=None): + return ClientBatchCheckItem( + user="user:anne", + relation=relation, + object="document:1", + correlation_id=correlation_id, + context=context, + contextual_tuples=contextual_tuples, + ) + + +def sent(groups): + return [ + ( + group.check.correlation_id, + group.check.relation, + [member.correlation_id for member in group.members], + ) + for group in groups + ] + + +@pytest.mark.parametrize( + "value", + [ + math.nan, + math.inf, + 10**400, + (1, 2), + datetime.datetime(2026, 1, 1), + {1: "non-string key"}, + {"nested": [object()]}, + nested(600), + ], + ids=["nan", "inf", "huge-int", "tuple", "datetime", "int-key", "object", "deep"], +) +def test_values_that_cannot_be_compared_are_not_merged(value): + groups = resolve( + ALIASES, + [check("a", context={"x": value}), check("b", context={"x": value})], + ) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] + + +def test_a_context_that_is_not_an_object_is_not_merged(): + groups = resolve(ALIASES, [check("a", context=["x"]), check("b", context=["x"])]) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] + + +def test_a_value_that_cannot_be_compared_does_not_stop_other_checks_merging(): + groups = resolve( + ALIASES, + [check("a", context={"x": math.nan}), check("b"), check("c")], + ) + + assert sent(groups) == [("a", "viewer", ["a"]), ("merged-1", "viewer", ["b", "c"])] + + +class ContextThatMustNotBeRead(dict): + def items(self): + raise AssertionError("the context of a check with no match was read") + + +def test_only_compares_context_for_checks_that_could_merge(): + other_user = check("b", context=ContextThatMustNotBeRead(x=1)) + other_user.user = "user:bob" + + groups = resolve( + ALIASES, [check("a", context=ContextThatMustNotBeRead(x=1)), other_user] + ) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] + + +def test_values_in_a_condition_context_that_cannot_be_compared_are_not_merged(): + contextual_tuples = [ + ClientTuple( + user="user:anne", + relation="viewer", + object="document:2", + condition=RelationshipCondition(name="c", context={"x": math.nan}), + ) + ] + + groups = resolve( + ALIASES, + [ + check("a", contextual_tuples=contextual_tuples), + check("b", contextual_tuples=contextual_tuples), + ], + ) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "viewer", ["b"])] + + +def test_checks_that_are_not_strings_are_sent_as_is(): + item = check("a") + item.user = None + + assert sent(resolve(ALIASES, [item])) == [("a", "can_view", ["a"])] + + +def test_a_model_without_type_definitions_sends_everything_as_is(): + model = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", schema_version="1.1", type_definitions=[] + ) + + assert sent(resolve(ModelAliases(model), [check("a"), check("b")])) == [ + ("a", "can_view", ["a"]), + ("b", "can_view", ["b"]), + ] + + +def test_unmerged_sends_every_check_as_is(): + items = [check("a"), check("b")] + + assert sent(unmerged(items)) == [ + ("a", "can_view", ["a"]), + ("b", "can_view", ["b"]), + ] + + +@pytest.mark.parametrize( + "correlation_id", + ["", "has space", "x" * 37, "é", "a/b", "a\n", 1], +) +def test_validate_correlation_ids_rejects_invalid_ids(correlation_id): + with pytest.raises(FgaValidationException, match="is invalid"): + validate_correlation_ids([check(correlation_id)]) + + +@pytest.mark.parametrize( + "options, enabled", + [ + (None, False), + ({}, False), + ({"merge_equivalent_checks": None}, False), + ({"merge_equivalent_checks": False}, False), + ({"merge_equivalent_checks": True}, True), + ], +) +def test_merge_enabled(options, enabled): + assert merge_enabled(options) is enabled + + +@pytest.mark.parametrize("value", ["true", 1, "yes"]) +def test_merge_enabled_rejects_values_that_are_not_bools(value): + with pytest.raises( + FgaValidationException, match="merge_equivalent_checks must be a bool" + ): + merge_enabled({"merge_equivalent_checks": value}) + + +def test_validate_correlation_ids_accepts_valid_ids(): + validate_correlation_ids([check("a_b-1"), check("x" * 36)]) + + +def test_validate_correlation_ids_rejects_duplicates(): + with pytest.raises( + FgaValidationException, match=r"Duplicate correlation_id \(a\) provided" + ): + validate_correlation_ids([check("a"), check("a")]) + + +def test_expand_copies_answers_in_input_order(): + a, b, c = check("a"), check("b"), check("c", relation="viewer") + groups = [ + EquivalentCheckGroup(check=check("c", relation="viewer"), members=[c]), + EquivalentCheckGroup( + check=check("merged-1", relation="viewer"), members=[a, b] + ), + ] + error = CheckError(message="boom") + + responses = expand( + [a, b, c], + groups, + { + "merged-1": BatchCheckSingleResult(error=error), + "c": BatchCheckSingleResult(allowed=True), + "unknown": BatchCheckSingleResult(allowed=True), + }, + ) + + assert [(r.correlation_id, r.allowed, r.error) for r in responses] == [ + ("a", False, error), + ("b", False, error), + ("c", True, None), + ] + assert [r.request for r in responses] == [a, b, c] + + +def test_expand_turns_a_missing_answer_into_an_error(): + a, b = check("a"), check("b") + + responses = expand( + [a, b], + [EquivalentCheckGroup(check=check("merged-1"), members=[a, b])], + {}, + ) + + for response in responses: + assert response.allowed is False + assert response.error.message == ( + "No result returned for correlation_id (merged-1)" + ) + + +@pytest.mark.parametrize( + "can_view", + [ + Userset(computed_userset=ObjectRelation(object="parent", relation="viewer")), + Userset(this={}, computed_userset=ObjectRelation(object="", relation="viewer")), + ], + ids=["object-set", "mixed-rewrite"], +) +def test_rewrites_that_only_look_like_aliases_are_not_merged(can_view): + model = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition( + type="document", + relations={"viewer": Userset(this={}), "can_view": can_view}, + ), + ], + ) + + groups = resolve(ModelAliases(model), [check("a", relation="viewer"), check("b")]) + + assert sent(groups) == [("a", "viewer", ["a"]), ("b", "can_view", ["b"])] + + +def test_a_long_alias_chain_is_resolved(): + # r0 -> r1 -> ... -> r4999, deeper than Python's recursion limit. + length = 5000 + relations = { + f"r{i}": Userset( + computed_userset=ObjectRelation(object="", relation=f"r{i + 1}") + ) + for i in range(length - 1) + } + relations[f"r{length - 1}"] = Userset(this={}) + model = AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition(type="document", relations=relations), + ], + ) + + def userset_check(correlation_id, user_relation, relation): + return ClientBatchCheckItem( + user=f"document:1#{user_relation}", + relation=relation, + object="document:1", + correlation_id=correlation_id, + ) + + groups = resolve( + ModelAliases(model), + [ + check("a", relation="r0"), + userset_check("b", "r2500", "r0"), + userset_check("c", "r0", "r2500"), + ], + ) + + assert sent(groups) == [ + ("a", "r4999", ["a"]), + ("b", "r0", ["b"]), + ("c", "r4999", ["c"]), + ] + + +def alias(relation): + return Userset(computed_userset=ObjectRelation(object="", relation=relation)) + + +# Aliases are listed before the relations they point to, and there are two trees and a +# broken chain in the same type. +# define member: writer +# define writer: owner +# define admin: owner +# define owner: [user] +# define can_edit: editor +# define editor: [user] +# define via_stale: stale +# define stale: removed (missing) +ALIAS_TREES = ModelAliases( + AuthorizationModel( + id="01GXSA8YR785C4FYS3C0RTG7B1", + schema_version="1.1", + type_definitions=[ + TypeDefinition(type="user"), + TypeDefinition( + type="document", + relations={ + "member": alias("writer"), + "writer": alias("owner"), + "admin": alias("owner"), + "owner": Userset(this={}), + "can_edit": alias("editor"), + "editor": Userset(this={}), + "via_stale": alias("stale"), + "stale": alias("removed"), + }, + ), + ], + ) +) + + +@pytest.mark.parametrize( + "user, relation, final", + [ + ("user:anne", "member", "owner"), + ("user:anne", "can_edit", "editor"), + ("document:1#admin", "writer", "owner"), + ("document:1#admin", "member", "owner"), + ("document:1#member", "writer", "owner"), + ("document:1#writer", "member", None), + ("document:1#writer", "writer", None), + ("document:1#owner", "admin", None), + ("document:1#editor", "member", "owner"), + ("document:1#member", "can_edit", "editor"), + ("user:anne", "via_stale", None), + ("user:anne", "stale", None), + ("document:1#stale", "member", "owner"), + ], + ids=[ + "alias-listed-before-its-target", + "second-tree", + "userset-on-a-sibling-branch", + "userset-on-a-sibling-branch-of-a-chain", + "userset-under-the-relation-checked", + "userset-in-the-chain", + "userset-is-the-relation-checked", + "userset-is-the-final-relation", + "userset-in-another-tree", + "check-in-another-tree", + "alias-of-a-broken-chain", + "broken-chain", + "userset-on-a-broken-chain", + ], +) +def test_final_relation_with_several_alias_trees(user, relation, final): + item = ClientBatchCheckItem( + user=user, relation=relation, object="document:1", correlation_id="a" + ) + + assert ALIAS_TREES.final_relation(item) == final + + +def test_model_aliases_rejects_an_empty_model(): + with pytest.raises(ValueError, match="The authorization model response is empty"): + ModelAliases(None) + + +def test_prepare_checks_needs_a_model_id(): + with pytest.raises(FgaValidationException, match="authorization_model_id"): + prepare_checks([check("a")], None) + + +def test_prepare_checks_fills_in_missing_ids_and_validates_them(): + items = [check(None), check("b")] + prepare_checks(items, "01GXSA8YR785C4FYS3C0RTG7B1") + + assert items[0].correlation_id + assert items[1].correlation_id == "b" + + with pytest.raises(FgaValidationException): + prepare_checks([check("a"), check("a")], "01GXSA8YR785C4FYS3C0RTG7B1") diff --git a/test/client/model_cache_test.py b/test/client/model_cache_test.py new file mode 100644 index 00000000..32d5ebb8 --- /dev/null +++ b/test/client/model_cache_test.py @@ -0,0 +1,197 @@ +import asyncio +import sys + +from types import SimpleNamespace +from unittest import IsolatedAsyncioTestCase, TestCase, skipIf + +from openfga_sdk.client._model_cache import ModelCache +from openfga_sdk.client._model_cache_base import model_read_fails_call +from openfga_sdk.exceptions import ( + ForbiddenException, + NotFoundException, + RateLimitExceededError, + ServiceException, + UnauthorizedException, + ValidationException, +) + + +API = object() +KEY = ("store", "model") + + +def cache_reading(read, **kwargs): + """ + A cache that reads models with read(store_id, authorization_model_id), not the API. + """ + cache = ModelCache(**kwargs) + cache._read = lambda api, store_id, model_id, options: read(store_id, model_id) + return cache + + +class TestAsyncModelCache(IsolatedAsyncioTestCase): + async def test_parallel_lookups_share_one_read_and_later_lookups_hit(self): + release = asyncio.Event() + reads = 0 + + async def read(*_): + nonlocal reads + reads += 1 + await release.wait() + return "model" + + cache = cache_reading(read) + lookups = [asyncio.ensure_future(cache.get(API, *KEY)) for _ in range(3)] + await asyncio.sleep(0) + release.set() + results = await asyncio.gather(*lookups) + + self.assertEqual(reads, 1) + self.assertEqual([(r.aliases, r.hit) for r in results], [("model", False)] * 3) + + later = await cache.get(API, *KEY) + self.assertEqual((later.aliases, later.hit, reads), ("model", True, 1)) + + async def test_a_failed_read_is_not_cached(self): + reads = 0 + error = RateLimitExceededError(status=429) + + async def read(*_): + nonlocal reads + reads += 1 + raise error + + cache = cache_reading(read) + first = await cache.get(API, *KEY) + second = await cache.get(API, *KEY) + + self.assertIs(first.error, error) + self.assertIs(second.error, error) + self.assertIsNone(second.aliases) + self.assertEqual(reads, 2) + + @skipIf(sys.version_info < (3, 12), "eager tasks need Python 3.12+") + async def test_retries_a_failed_read_that_finished_eagerly(self): + asyncio.get_running_loop().set_task_factory(asyncio.eager_task_factory) + reads = 0 + + async def read(*_): + nonlocal reads + reads += 1 + raise RuntimeError("forbidden") + + cache = cache_reading(read) + await cache.get(API, *KEY) + self.assertEqual(cache._loading, {}) + + await cache.get(API, *KEY) + self.assertEqual(reads, 2) + + async def test_drops_the_least_recently_used_model(self): + async def read(store, model): + return f"{store}/{model}" + + cache = cache_reading(read, max_models=2) + + await cache.get(API, "a", "1") + await cache.get(API, "b", "1") + self.assertTrue((await cache.get(API, "a", "1")).hit) + await cache.get(API, "c", "1") + + self.assertTrue((await cache.get(API, "a", "1")).hit) + self.assertFalse((await cache.get(API, "b", "1")).hit) + + async def test_a_cancelled_caller_does_not_cancel_the_shared_read(self): + release = asyncio.Event() + + async def read(*_): + await release.wait() + return "model" + + cache = cache_reading(read) + cancelled = asyncio.ensure_future(cache.get(API, *KEY)) + waiting = asyncio.ensure_future(cache.get(API, *KEY)) + await asyncio.sleep(0) + cancelled.cancel() + release.set() + + self.assertEqual((await waiting).aliases, "model") + with self.assertRaises(asyncio.CancelledError): + await cancelled + + async def test_close_cancels_in_flight_reads_without_caching_them(self): + started = asyncio.Event() + hang = True + + async def read(*_): + if hang: + started.set() + await asyncio.Event().wait() + return "model" + + cache = cache_reading(read) + lookup = asyncio.ensure_future(cache.get(API, *KEY)) + await started.wait() + await cache.close() + + with self.assertRaises(asyncio.CancelledError): + await lookup + + hang = False + self.assertEqual((await cache.get(API, *KEY)).aliases, "model") + + async def test_keys_on_both_the_store_and_the_model(self): + reads = [] + errors = {("c", "1"): RateLimitExceededError(status=429)} + + async def read(store, model): + reads.append((store, model)) + if (store, model) in errors: + raise errors[(store, model)] + return f"{store}/{model}" + + cache = cache_reading(read) + + async def get(store, model): + return await cache.get(API, store, model) + + self.assertEqual((await get("a", "1")).aliases, "a/1") + self.assertEqual((await get("b", "1")).aliases, "b/1") + self.assertEqual((await get("a", "2")).aliases, "a/2") + self.assertTrue((await get("a", "1")).hit) + self.assertTrue((await get("b", "1")).hit) + self.assertTrue((await get("a", "2")).hit) + self.assertEqual(reads, [("a", "1"), ("b", "1"), ("a", "2")]) + + await get("c", "1") + self.assertEqual((await get("d", "1")).aliases, "d/1") + self.assertEqual((await get("c", "2")).aliases, "c/2") + self.assertEqual(reads[3:], [("c", "1"), ("d", "1"), ("c", "2")]) + + +def with_code(error, code): + error.parsed_exception = SimpleNamespace(code=code) + return error + + +class TestModelReadFailsCall(TestCase): + def test_fails_when_the_model_is_missing_or_the_credentials_cannot_read_it(self): + for error, fails in [ + ( + with_code( + ValidationException(status=400), "authorization_model_not_found" + ), + True, + ), + (with_code(NotFoundException(status=404), "store_id_not_found"), True), + (UnauthorizedException(status=401), True), + (ForbiddenException(status=403), True), + (with_code(ValidationException(status=400), "validation_error"), False), + (RateLimitExceededError(status=429), False), + (ServiceException(status=500), False), + (TimeoutError(), False), + (ValueError("The authorization model response is empty"), False), + (None, False), + ]: + with self.subTest(error=repr(error)): + self.assertEqual(model_read_fails_call(error), fails) diff --git a/test/data/equivalent-checks-cases.json b/test/data/equivalent-checks-cases.json new file mode 100644 index 00000000..6726874c --- /dev/null +++ b/test/data/equivalent-checks-cases.json @@ -0,0 +1,7112 @@ +{ + "note": "Generated from equivalent-checks-cases.yaml, with every model as JSON. It's committed because SDKs without a DSL parser download it from GitHub at a pinned commit. Don't edit this file: edit the YAML file and run `make -C pkg/go generate-equivalent-checks-json`.", + "cases": [ + { + "name": "merges an alias with the relation it points to", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges an alias chain into its final relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b", "c"] + }, + { + "id": "d", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["d"] + } + ] + }, + { + "name": "sends a lone alias check with its final relation and the caller's id", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + } + ] + }, + { + "name": "merges exact repeats", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "editor": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge checks that end at different relations", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_edit": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_edit": { + "computedUserset": { + "relation": "editor" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_edit", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge checks for different users", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge checks on different objects", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:2" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:2", + "for": ["b"] + } + ] + }, + { + "name": "follows the aliases of the object's type only", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "owner": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": {} + } + }, + "relations": { + "owner": { + "this": {} + }, + "viewer": { + "computedUserset": { + "relation": "owner" + } + } + }, + "type": "folder" + }, + { + "metadata": { + "relations": { + "owner": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "owner": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "folder:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "owner", + "object": "folder:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:anne", + "relation": "owner", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "owner", + "object": "folder:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "owner", + "object": "document:1", + "for": ["d"] + } + ] + }, + { + "name": "sends checks in the order of each group's first check", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "e", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "c"] + }, + { + "id": "merged-2", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["b", "d"] + }, + { + "id": "e", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["e"] + } + ] + }, + { + "name": "keeps a check sent as is in its place between merged groups", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_veiw", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "e", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a", "c"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_veiw", + "object": "document:1", + "for": ["b"] + }, + { + "id": "merged-2", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["d", "e"] + } + ] + }, + { + "name": "stops the chain at a union", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "union": { + "child": [ + { + "computedUserset": { + "relation": "viewer" + } + }, + { + "computedUserset": { + "relation": "editor" + } + } + ] + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at an intersection", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "intersection": { + "child": [ + { + "computedUserset": { + "relation": "viewer" + } + }, + { + "computedUserset": { + "relation": "editor" + } + } + ] + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at an exclusion", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "blocked": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "blocked": { + "this": {} + }, + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "difference": { + "base": { + "computedUserset": { + "relation": "viewer" + } + }, + "subtract": { + "computedUserset": { + "relation": "blocked" + } + } + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at a relation from a parent", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "viewer": { + "this": {} + } + }, + "type": "folder" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "parent": { + "directly_related_user_types": [ + { + "type": "folder" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "tupleToUserset": { + "computedUserset": { + "relation": "viewer" + }, + "tupleset": { + "relation": "parent" + } + } + }, + "parent": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at direct types combined with an alias", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "union": { + "child": [ + { + "this": {} + }, + { + "computedUserset": { + "relation": "viewer" + } + } + ] + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "stops the chain at a union with a single child", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": { + "directly_related_user_types": [] + }, + "can_view": { + "directly_related_user_types": [] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "union": { + "child": [ + { + "computedUserset": { + "relation": "viewer" + } + } + ] + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["a", "b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends checks as is when the alias chain points to a missing relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "missing" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_share", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends checks as is when the alias chain loops", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "loop_a": {}, + "loop_b": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "loop_a": { + "computedUserset": { + "relation": "loop_b" + } + }, + "loop_b": { + "computedUserset": { + "relation": "loop_a" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "loop_a", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "loop_b", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "loop_a", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "loop_b", + "object": "document:1", + "for": ["b"] + }, + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["c", "d"] + } + ] + }, + { + "name": "sends as is a userset on the same object whose relation is the one asked for", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_share", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#can_share", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a userset on the same object whose relation is in the chain", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "document:1#can_view", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "document:1#can_view", + "relation": "viewer", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends as is a userset on the same object whose relation is the final relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#viewer", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#viewer", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#viewer", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge repeats of a userset on the same object whose relation is in the chain", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "document:1#can_view", + "relation": "can_share", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "merges a userset on the same object whose relation isn't in the chain", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "editor", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#editor", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#editor", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "document:1#editor", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset on the same object whose relation is another alias of the final relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_read": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_read", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_read": { + "computedUserset": { + "relation": "viewer" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:1#can_read", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "document:1#can_read", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "document:1#can_read", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset on another object", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "can_view", + "type": "document" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "document:2#can_view", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "document:2#can_view", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "document:2#can_view", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset on an object of another type with the same id", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "viewer": { + "this": {} + } + }, + "type": "folder" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "viewer", + "type": "folder" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "folder:1#viewer", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "folder:1#viewer", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "folder:1#viewer", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a userset of another type", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "team:eng#member", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "team:eng#member", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a wildcard user", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "type": "user", + "wildcard": {} + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:*", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "b", + "user": "user:*", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "merges a user whose type is in the model but not allowed on the relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "team:eng", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "team:eng", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "team:eng", + "relation": "viewer", + "object": "document:1", + "for": ["a", "b"] + } + ] + }, + { + "name": "sends as is a check on an unknown object type", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "folder:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "folder:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a check with an unknown relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "sends as is a check with an unknown user type", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "employee:1", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "employee:*", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "employee:1#member", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "employee:1", + "relation": "can_view", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "employee:*", + "relation": "can_view", + "object": "document:1", + "for": ["b"] + }, + { + "id": "c", + "user": "employee:1#member", + "relation": "can_view", + "object": "document:1", + "for": ["c"] + } + ] + }, + { + "name": "sends as is a check with an unknown userset relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "team:eng#owner", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "team:eng#member", + "relation": "can_view", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "team:eng#owner", + "relation": "can_view", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "does not merge repeats of a check that isn't in the model", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_delete", + "object": "document:1", + "for": ["b"] + } + ] + }, + { + "name": "merges checks with the same context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "for": ["a", "b"] + } + ] + }, + { + "name": "merges context with keys in a different order", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\" && x > 0.0", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "x": 1.5 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1.5, + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "x": 1.5 + }, + "for": ["a", "b"] + } + ] + }, + { + "name": "merges 1 and 1.0", + "model": { + "conditions": { + "positive": { + "expression": "x > 0.0", + "name": "positive", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "positive", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": 1 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1.0 + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + }, + "for": ["a", "b"] + } + ] + }, + { + "name": "merges integers that are the same double", + "model": { + "conditions": { + "at_most": { + "expression": "x <= 9007199254740992.0", + "name": "at_most", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "at_most", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": 9007199254740993 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 9007199254740992 + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 9007199254740993 + }, + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge 0 and -0.0", + "model": { + "conditions": { + "negative_sign": { + "expression": "1.0 / x < 0.0", + "name": "negative_sign", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "negative_sign", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": 0 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": -0.0 + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 0 + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": -0.0 + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge true and 1", + "model": { + "conditions": { + "positive": { + "expression": "x > 0.0", + "name": "positive", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "positive", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": true + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": true + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge the string \"1\" and the number 1", + "model": { + "conditions": { + "positive": { + "expression": "x > 0.0", + "name": "positive", + "parameters": { + "x": { + "type_name": "TYPE_NAME_DOUBLE" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "positive", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "x": "1" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": "1" + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "x": 1 + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge when a field is missing", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "x": 1 + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "x": 1 + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge null and a missing field", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "x": null + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "x": null + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge no context and an empty context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": {} + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": {}, + "for": ["b"] + } + ] + }, + { + "name": "does not merge strings that differ by a trailing space", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu " + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu " + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge strings that differ only in Unicode form", + "model": { + "conditions": { + "in_city": { + "expression": "city == \"caf\\u00e9\"", + "name": "in_city", + "parameters": { + "city": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_city", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "city": "caf\u00e9" + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "city": "cafe\u0301" + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "city": "caf\u00e9" + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "city": "cafe\u0301" + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge lists in a different order", + "model": { + "conditions": { + "first_tag": { + "expression": "tags[0] == \"a\"", + "name": "first_tag", + "parameters": { + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "first_tag", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "tags": ["a", "b"] + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["b", "a"] + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["a", "b"] + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["b", "a"] + }, + "for": ["b"] + } + ] + }, + { + "name": "does not merge lists with a repeated item", + "model": { + "conditions": { + "one_tag": { + "expression": "size(tags) == 1", + "name": "one_tag", + "parameters": { + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "one_tag", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "tags": ["a"] + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["a", "a"] + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["a"] + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "tags": ["a", "a"] + }, + "for": ["b"] + } + ] + }, + { + "name": "merges nested values that match at every level", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "level": 1, + "items": [ + 1, + { + "k": "v", + "count": 2 + } + ] + } + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "meta": { + "items": [ + 1.0, + { + "count": 2.0, + "k": "v" + } + ], + "level": 1.0 + }, + "region": "eu" + } + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "level": 1, + "items": [ + 1, + { + "k": "v", + "count": 2 + } + ] + } + }, + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge nested values that differ", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [0] + } + } + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [-0.0] + } + } + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [false] + } + } + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [0] + } + }, + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [-0.0] + } + }, + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu", + "meta": { + "items": [false] + } + }, + "for": ["c"] + } + ] + }, + { + "name": "merges checks with the same contextual tuples", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "limits": { + "generic_types": [ + { + "type_name": "TYPE_NAME_DOUBLE" + } + ], + "type_name": "TYPE_NAME_MAP" + }, + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user", + "wildcard": {} + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "tags": ["x", "y"], + "limits": { + "write": 2.0, + "read": 1.0 + }, + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "tags": [], + "region": "us", + "limits": { + "read": 0.5 + } + } + } + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "limits": { + "read": 0.5 + }, + "tags": [], + "region": "us" + } + } + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "limits": { + "write": 2, + "read": 1 + }, + "region": "eu", + "tags": ["x", "y"] + } + } + }, + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["y", "x"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } + } + ], + "for": ["a", "b", "c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:*", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["y", "x"] + } + } + }, + { + "user": "user:bob", + "relation": "member", + "object": "team:eng", + "condition": { + "name": "in_region", + "context": { + "region": "us", + "limits": { + "read": 0.5 + }, + "tags": [] + } + } + } + ], + "for": ["d"] + } + ] + }, + { + "name": "merges contextual tuples in a different order", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + } + ] + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "member", + "object": "team:eng" + }, + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge contextual tuples with a different object, user or relation", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:2" + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:2" + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "editor", + "object": "document:1" + } + ], + "for": ["d"] + } + ] + }, + { + "name": "does not merge contextual tuples with a different userset or wildcard user", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "admin": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "member": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "admin": { + "this": {} + }, + "member": { + "this": {} + } + }, + "type": "team" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "type": "user", + "wildcard": {} + }, + { + "relation": "member", + "type": "team" + }, + { + "relation": "admin", + "type": "team" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#admin", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:*", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#member", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "team:eng#admin", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:*", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["d"] + } + ] + }, + { + "name": "does not merge no contextual tuples and some", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["b"] + } + ] + }, + { + "name": "does not merge no contextual tuples and an empty list", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [], + "for": ["b"] + } + ] + }, + { + "name": "sends as is a check whose contextual tuples repeat a tuple", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["c"] + } + ] + }, + { + "name": "does not merge a contextual tuple with and without a condition", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + }, + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "for": ["b"] + } + ] + }, + { + "name": "does not merge contextual tuples with different condition names", + "model": { + "conditions": { + "in_eu": { + "expression": "region == \"eu\"", + "name": "in_eu", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + }, + "in_us": { + "expression": "region == \"us\"", + "name": "in_us", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_eu", + "type": "user" + }, + { + "condition": "in_us", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ], + "for": ["b"] + } + ] + }, + { + "name": "does not merge contextual tuples with different condition context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], + "for": ["b"] + } + ] + }, + { + "name": "does not merge a contextual tuple condition with no context and an empty context", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region" + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": {} + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region" + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "context": { + "region": "eu" + }, + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": {} + } + } + ], + "for": ["b"] + } + ] + }, + { + "name": "merges contextual tuple condition context that matches at every level", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "limits": { + "generic_types": [ + { + "type_name": "TYPE_NAME_DOUBLE" + } + ], + "type_name": "TYPE_NAME_MAP" + }, + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "tags": ["x", "y"], + "limits": { + "write": 2.0, + "read": 1.0 + }, + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 1, + "write": 2 + }, + "tags": ["x", "y"] + } + } + } + ], + "for": ["a", "b"] + } + ] + }, + { + "name": "does not merge contextual tuple condition context that differs at a nested level", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "limits": { + "generic_types": [ + { + "type_name": "TYPE_NAME_DOUBLE" + } + ], + "type_name": "TYPE_NAME_MAP" + }, + "region": { + "type_name": "TYPE_NAME_STRING" + }, + "tags": { + "generic_types": [ + { + "type_name": "TYPE_NAME_STRING" + } + ], + "type_name": "TYPE_NAME_LIST" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 0 + }, + "tags": ["x"] + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": -0.0 + }, + "tags": ["x"] + } + } + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 0 + }, + "tags": ["y"] + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 0 + }, + "tags": ["x"] + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": -0.0 + }, + "tags": ["x"] + } + } + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu", + "limits": { + "read": 0 + }, + "tags": ["y"] + } + } + } + ], + "for": ["c"] + } + ] + }, + { + "name": "sends as is checks whose contextual tuples repeat a user, relation and object with the same condition", + "model": { + "conditions": { + "in_region": { + "expression": "region == \"eu\"", + "name": "in_region", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_region", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ] + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "us" + } + } + } + ], + "for": ["c"] + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_region", + "context": { + "region": "eu" + } + } + } + ], + "for": ["d"] + } + ] + }, + { + "name": "sends as is checks whose contextual tuples repeat a user, relation and object with different conditions", + "model": { + "conditions": { + "in_eu": { + "expression": "region == \"eu\"", + "name": "in_eu", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + }, + "in_us": { + "expression": "region == \"us\"", + "name": "in_us", + "parameters": { + "region": { + "type_name": "TYPE_NAME_STRING" + } + } + } + }, + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "condition": "in_eu", + "type": "user" + }, + { + "condition": "in_us", + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ] + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ], + "for": ["a"] + }, + { + "id": "b", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + } + ], + "for": ["b"] + }, + { + "id": "c", + "user": "user:anne", + "relation": "can_view", + "object": "document:1", + "contextual_tuples": [ + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_eu", + "context": { + "region": "eu" + } + } + }, + { + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "condition": { + "name": "in_us", + "context": { + "region": "eu" + } + } + } + ], + "for": ["c"] + } + ] + }, + { + "name": "numbers merged groups in order and skips groups of one", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_share": {}, + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_share": { + "computedUserset": { + "relation": "can_view" + } + }, + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "a", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + }, + { + "id": "b", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "d", + "user": "user:anne", + "relation": "can_share", + "object": "document:1" + }, + { + "id": "e", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "a", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["a"] + }, + { + "id": "merged-1", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["b", "c"] + }, + { + "id": "merged-2", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["d", "e"] + } + ] + }, + { + "name": "skips a generated id that matches a caller's id", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "editor": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "editor": { + "this": {} + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "editor", + "object": "document:1" + }, + { + "id": "b", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "c", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "editor", + "object": "document:1", + "for": ["merged-1"] + }, + { + "id": "merged-2", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["b", "c"] + } + ] + }, + { + "name": "skips generated ids that match caller ids inside merged groups", + "model": { + "schema_version": "1.1", + "type_definitions": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "can_view": {}, + "viewer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "can_view": { + "computedUserset": { + "relation": "viewer" + } + }, + "viewer": { + "this": {} + } + }, + "type": "document" + } + ] + }, + "checks": [ + { + "id": "merged-1", + "user": "user:anne", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "merged-2", + "user": "user:anne", + "relation": "viewer", + "object": "document:1" + }, + { + "id": "c", + "user": "user:bob", + "relation": "can_view", + "object": "document:1" + }, + { + "id": "d", + "user": "user:bob", + "relation": "viewer", + "object": "document:1" + } + ], + "expected_sent": [ + { + "id": "merged-3", + "user": "user:anne", + "relation": "viewer", + "object": "document:1", + "for": ["merged-1", "merged-2"] + }, + { + "id": "merged-4", + "user": "user:bob", + "relation": "viewer", + "object": "document:1", + "for": ["c", "d"] + } + ] + } + ] +} diff --git a/test/sync/client/batch_check_merge_test.py b/test/sync/client/batch_check_merge_test.py new file mode 100644 index 00000000..1382658d --- /dev/null +++ b/test/sync/client/batch_check_merge_test.py @@ -0,0 +1,660 @@ +import json + +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from datetime import datetime +from unittest import TestCase +from unittest.mock import patch + +import urllib3 + +from openfga_sdk.client import ClientConfiguration +from openfga_sdk.client.models.batch_check_request import ClientBatchCheckRequest +from openfga_sdk.configuration import RetryParams +from openfga_sdk.exceptions import ( + AuthenticationError, + FgaValidationException, + ForbiddenException, + NotFoundException, + RateLimitExceededError, + ServiceException, + UnauthorizedException, + ValidationException, +) +from openfga_sdk.sync import rest +from openfga_sdk.sync.api_client import ApiClient +from openfga_sdk.sync.client.client import OpenFgaClient +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.metrics import TelemetryMetrics +from test.client.batch_check_merge_test import ( + API_URL, + MODEL, + MODEL_ID, + OTHER_MODEL_ID, + STORE_ID, + UNMERGED, + bad_request, + checks, + forbidden, + http_mock_response, + model_not_found, + no_token_issued, + rate_limited, + sent_checks, + server_error, + short_lived_token_issued, + short_lived_tokens_then_rate_limited, + store_not_found, + timed_out, + token_configuration, + token_issued, + unauthorized, +) +from test.client.batch_check_merge_test import FakeServer as AsyncFakeServer + + +def connection_dropped(): + return urllib3.exceptions.ProtocolError("connection aborted") + + +def mock_response(body, status=200): + obj = http_mock_response(body, status) + return rest.RESTResponse(obj, obj.data) + + +def token_due_for_renewal_when_used(client): + """ + Make the client's token due for renewal right when a request gets it, as if it got + there just after any earlier check. + """ + oauth2_client = client._api._oauth2_client + update_params_for_auth = ApiClient.update_params_for_auth + + def renewal_due(api_client, *args, **kwargs): + oauth2_client._token_state = replace( + oauth2_client._token_state, expiry_time=datetime.now() + ) + return update_params_for_auth(api_client, *args, **kwargs) + + return patch.object(ApiClient, "update_params_for_auth", renewal_due) + + +class FakeServer(AsyncFakeServer): + respond = staticmethod(mock_response) + + +class TestSyncBatchCheckMergeEquivalentChecks(TestCase): + def setUp(self): + self.configuration = ClientConfiguration( + api_url=API_URL, + store_id=STORE_ID, + authorization_model_id=MODEL_ID, + ) + + def batch_check(self, client, items, options=None): + return client.batch_check( + ClientBatchCheckRequest(checks=items), + options={"merge_equivalent_checks": True, **(options or {})}, + ) + + @patch.object(rest.RESTClientObject, "request") + def test_merges_aliases_and_copies_the_answer_back(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + items = checks() + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, items) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(server.sent[0]["authorization_model_id"], MODEL_ID) + self.assertEqual(response.checks_sent, 2) + self.assertEqual( + [(r.correlation_id, r.allowed, r.error) for r in response.result], + [ + ("a", True, None), + ("b", True, None), + ("c", True, None), + ("d", False, None), + ], + ) + self.assertEqual([r.request for r in response.result], items) + + @patch.object(rest.RESTClientObject, "request") + def test_merges_checks_that_would_land_in_different_batches(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check( + client, checks()[:3], options={"max_batch_size": 1} + ) + + self.assertEqual(sent_checks(server), [("merged-1", "viewer")]) + self.assertEqual(response.checks_sent, 1) + self.assertEqual(len(response.result), 3) + + @patch.object(rest.RESTClientObject, "request") + def test_reads_the_model_once_across_threads_and_later_calls(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with ThreadPoolExecutor(max_workers=5) as executor: + list( + executor.map(lambda _: self.batch_check(client, checks()), range(5)) + ) + self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(len(server.sent), 6) + + @patch.object(rest.RESTClientObject, "request") + def test_requires_a_model_id(self, mock_request): + self.configuration.authorization_model_id = None + + with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, "authorization_model_id" + ): + self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_requires_a_store_id(self, mock_request): + self.configuration.store_id = None + + with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex(FgaValidationException, "store_id"): + self.batch_check(client, checks()) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_the_model_id_in_the_options_wins(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + self.batch_check(client, checks()) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID, MODEL_ID]) + self.assertEqual( + [body["authorization_model_id"] for body in server.sent], + [OTHER_MODEL_ID, MODEL_ID], + ) + + @patch.object(rest.RESTClientObject, "request") + def test_uses_the_model_id_in_the_options_when_none_is_configured( + self, mock_request + ): + self.configuration.authorization_model_id = None + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check( + client, checks(), {"authorization_model_id": OTHER_MODEL_ID} + ) + + self.assertEqual(server.model_ids_read, [OTHER_MODEL_ID]) + self.assertEqual(server.sent[0]["authorization_model_id"], OTHER_MODEL_ID) + self.assertEqual(response.checks_sent, 2) + + @patch.object(rest.RESTClientObject, "request") + def test_rejects_an_option_value_that_is_not_a_bool(self, mock_request): + with OpenFgaClient(self.configuration) as client: + with self.assertRaisesRegex( + FgaValidationException, "merge_equivalent_checks must be a bool" + ): + self.batch_check( + client, checks(), options={"merge_equivalent_checks": 1} + ) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_reads_the_model_with_the_callers_headers(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + self.batch_check(client, checks(), options={"headers": {"X-Custom": "1"}}) + + self.assertEqual(server.model_read_headers[0].get("X-Custom"), "1") + + @patch.object(rest.RESTClientObject, "request") + def test_rejects_invalid_and_duplicate_correlation_ids(self, mock_request): + invalid = checks() + invalid[0].correlation_id = "a\n" + duplicate = checks() + duplicate[1].correlation_id = "a" + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(FgaValidationException): + self.batch_check(client, invalid) + with self.assertRaisesRegex( + FgaValidationException, r"Duplicate correlation_id \(a\) provided" + ): + self.batch_check(client, duplicate) + + mock_request.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_generates_missing_correlation_ids(self, mock_request): + mock_request.side_effect = FakeServer() + items = checks() + items[3].correlation_id = None + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, items) + + self.assertIsNotNone(items[3].correlation_id) + self.assertEqual(response.result[3].correlation_id, items[3].correlation_id) + + @patch.object(rest.RESTClientObject, "request") + def test_no_checks_sends_nothing(self, mock_request): + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, []) + + self.assertEqual(response.result, []) + self.assertEqual(response.checks_sent, 0) + mock_request.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_model_cannot_be_read( + self, mock_request, mock_fallback + ): + server = FakeServer(model_error=rate_limited) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ) as logs: + response = self.batch_check(client, checks()) + self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertIn("429", logs.output[0]) + self.assertEqual(server.model_reads, 2) + self.assertEqual(sent_checks(server), UNMERGED * 2) + self.assertEqual(response.checks_sent, 4) + self.assertEqual(mock_fallback.call_count, 2) + self.assertEqual( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ], + 429, + ) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_server_fails_or_times_out( + self, mock_request, mock_fallback + ): + for model_error, status in [(server_error, 500), (timed_out, None)]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + response = self.batch_check(client, checks()) + self.batch_check(client, checks()) + + self.assertEqual(sent_checks(server), UNMERGED * 2) + self.assertEqual(response.checks_sent, 4) + self.assertEqual(server.model_reads, 2) + self.assertEqual( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ], + status, + ) + + @patch.object(rest.RESTClientObject, "request") + def test_does_not_retry_the_model_read(self, mock_request): + retries = {"retry_params": RetryParams(max_retry=3, min_wait_in_ms=1)} + for model_error in [rate_limited, server_error, connection_dropped]: + with self.subTest(error=model_error.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + self.batch_check(client, checks(), retries) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch( + "openfga_sdk.client._batch_check_merge.resolve", + side_effect=RuntimeError("boom"), + ) + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_grouping_fails( + self, mock_request, _resolve, mock_fallback + ): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._batch_check_merge", "WARNING" + ) as logs: + response = self.batch_check(client, checks()) + + self.assertIn("couldn't group the checks", logs.output[0]) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + self.assertIsNone( + mock_fallback.call_args.kwargs["attributes"][ + TelemetryAttributes.http_response_status_code + ] + ) + + @patch.object(rest.RESTClientObject, "request") + def test_fails_before_sending_when_the_store_does_not_exist(self, mock_request): + server = FakeServer(model_error=store_not_found) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs("openfga_sdk.client._model_cache_base", "WARNING"): + with self.assertRaises(NotFoundException): + self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_fails_like_the_option_off_when_the_token_request_fails( + self, mock_request, mock_fallback + ): + for token, error_type in [ + (unauthorized, UnauthorizedException), + (bad_request, ValidationException), + (rate_limited, RateLimitExceededError), + (server_error, ServiceException), + (connection_dropped, urllib3.exceptions.ProtocolError), + (no_token_issued, AuthenticationError), + ]: + with self.subTest(token=token.__name__): + token_requests = [] + for merge in [False, True]: + server = FakeServer(token=token) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + with self.assertRaises(error_type): + client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(server.sent, []) + token_requests.append(server.token_requests) + + self.assertEqual(token_requests[1], token_requests[0]) + + mock_fallback.assert_not_called() + + @patch.object(rest.RESTClientObject, "request") + def test_the_next_call_works_after_a_failed_token_request(self, mock_request): + server = FakeServer(token=rate_limited) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + with self.assertRaises(RateLimitExceededError): + self.batch_check(client, checks()) + + server.token = token_issued + response = self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), [("merged-1", "viewer"), ("d", "editor")]) + self.assertEqual(response.checks_sent, 2) + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_fails_when_the_model_read_cannot_renew_the_token( + self, mock_request, mock_fallback + ): + for renewals in [0, 1]: + with self.subTest(renewals_before_failing=renewals): + server = FakeServer(token=short_lived_token_issued) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = short_lived_tokens_then_rate_limited(renewals) + + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + self.batch_check(client, checks()) + + server.token = short_lived_token_issued + response = self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(response.checks_sent, 2) + + mock_fallback.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_fails_like_the_option_off_when_the_token_is_due_just_before_the_read( + self, mock_request, mock_fallback + ): + token_requests = [] + for merge in [False, True]: + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + client.batch_check(ClientBatchCheckRequest(checks=checks())) + server.token = rate_limited + + with token_due_for_renewal_when_used(client): + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + with self.assertRaises(RateLimitExceededError): + client.batch_check( + ClientBatchCheckRequest(checks=checks()), + options={"merge_equivalent_checks": merge}, + ) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(len(server.sent), 1) + token_requests.append(server.token_requests) + + self.assertEqual(token_requests[1], token_requests[0]) + mock_fallback.assert_not_called() + + @patch.object(TelemetryMetrics, "batchCheckMergeFallback") + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_read_fails_after_renewing_the_token( + self, mock_request, mock_fallback + ): + server = FakeServer(model_error=rate_limited, token=short_lived_token_issued) + mock_request.side_effect = server + + with OpenFgaClient(token_configuration()) as client: + with self.assertLogs("openfga_sdk.client._model_cache_base", "WARNING"): + response = self.batch_check(client, checks()) + + self.assertEqual(server.model_reads, 1) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + mock_fallback.assert_called_once() + + @patch.object(rest.RESTClientObject, "request") + def test_fails_before_sending_when_the_model_does_not_exist(self, mock_request): + server = FakeServer(model_error=model_not_found) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException) as raised: + self.batch_check(client, checks()) + + self.assertEqual(raised.exception.code, "authorization_model_not_found") + self.assertEqual(server.sent, []) + + @patch.object(rest.RESTClientObject, "request") + def test_fails_before_sending_when_the_credentials_cannot_read_the_model( + self, mock_request + ): + for model_error, error_type in [ + (unauthorized, UnauthorizedException), + (forbidden, ForbiddenException), + ]: + with self.subTest(status=error_type.__name__): + server = FakeServer(model_error=model_error) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertNoLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ): + for _ in range(2): + with self.assertRaises(error_type): + self.batch_check(client, checks()) + + self.assertEqual(server.sent, []) + self.assertEqual(server.model_reads, 2) + + @patch.object(rest.RESTClientObject, "request") + def test_sends_unmerged_when_the_model_response_is_empty(self, mock_request): + server = FakeServer(model_body={}) + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + with self.assertLogs( + "openfga_sdk.client._model_cache_base", "WARNING" + ) as logs: + response = self.batch_check(client, checks()) + + self.assertEqual(len(logs.records), 1) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertEqual(response.checks_sent, 4) + + @patch.object(rest.RESTClientObject, "request") + def test_copies_an_error_to_every_check_in_the_group(self, mock_request): + mock_request.side_effect = FakeServer( + answer=lambda check: ( + {"error": {"message": "boom"}} + if check["correlation_id"] == "merged-1" + else {"allowed": True} + ) + ) + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, checks()) + + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual(result.error.message, "boom") + self.assertTrue(response.result[3].allowed) + + @patch.object(rest.RESTClientObject, "request") + def test_a_missing_answer_is_an_error_and_unknown_answers_are_ignored( + self, mock_request + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + return mock_response( + json.dumps( + {"result": {"d": {"allowed": True}, "unknown": {"allowed": True}}} + ) + ) + + mock_request.side_effect = handle + + with OpenFgaClient(self.configuration) as client: + response = self.batch_check(client, checks()) + + self.assertEqual( + [r.correlation_id for r in response.result], ["a", "b", "c", "d"] + ) + for result in response.result[:3]: + self.assertFalse(result.allowed) + self.assertEqual( + result.error.message, "No result returned for correlation_id (merged-1)" + ) + self.assertTrue(response.result[3].allowed) + + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(rest.RESTClientObject, "request") + def test_a_failed_request_fails_the_call_and_still_counts_checks( + self, mock_request, mock_requested, mock_sent + ): + def handle(method, url, **kwargs): + if method == "GET": + return mock_response(json.dumps({"authorization_model": MODEL})) + raise ValidationException(http_resp=http_mock_response("{}", 400)) + + mock_request.side_effect = handle + + with OpenFgaClient(self.configuration) as client: + with self.assertRaises(ValidationException): + self.batch_check(client, checks()) + + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_sent.call_args.args, (2,)) + + @patch.object(rest.RESTClientObject, "request") + def test_option_off_is_unchanged(self, mock_request): + server = FakeServer() + mock_request.side_effect = server + + with OpenFgaClient(self.configuration) as client: + response = client.batch_check(ClientBatchCheckRequest(checks=checks())) + + self.assertEqual(server.model_reads, 0) + self.assertEqual(sent_checks(server), UNMERGED) + self.assertIsNone(response.checks_sent) + + @patch.object(TelemetryMetrics, "batchCheckChecksSent") + @patch.object(TelemetryMetrics, "batchCheckChecksRequested") + @patch.object(TelemetryMetrics, "modelCacheLookup") + @patch.object(rest.RESTClientObject, "request") + def test_records_telemetry( + self, mock_request, mock_lookup, mock_requested, mock_sent + ): + mock_request.side_effect = FakeServer() + + with OpenFgaClient(self.configuration) as client: + self.batch_check(client, checks()) + self.batch_check(client, checks()) + + self.assertEqual( + [ + call.kwargs["attributes"][ + TelemetryAttributes.fga_client_model_cache_result + ] + for call in mock_lookup.call_args_list + ], + ["miss", "hit"], + ) + self.assertEqual(mock_requested.call_args.args, (4,)) + self.assertEqual(mock_sent.call_args.args, (2,)) diff --git a/test/sync/client/model_cache_test.py b/test/sync/client/model_cache_test.py new file mode 100644 index 00000000..1e1f9ee8 --- /dev/null +++ b/test/sync/client/model_cache_test.py @@ -0,0 +1,163 @@ +import threading +import time + +from unittest import TestCase + +from openfga_sdk.exceptions import ( + ForbiddenException, + RateLimitExceededError, + ServiceException, + UnauthorizedException, + ValidationException, +) +from openfga_sdk.sync.client._model_cache import ModelCache + + +API = object() +KEY = ("store", "model") + + +def cache_reading(read, **kwargs): + """ + A cache that reads models with read(store_id, authorization_model_id), not the API. + """ + cache = ModelCache(**kwargs) + cache._read = lambda api, store_id, model_id, options: read(store_id, model_id) + return cache + + +class TestModelCache(TestCase): + def test_threads_share_one_read_and_later_lookups_hit(self): + started = threading.Event() + release = threading.Event() + reads = 0 + + def read(*_): + nonlocal reads + reads += 1 + started.set() + release.wait() + return "model" + + cache = cache_reading(read) + results = [] + owner = threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) + owner.start() + started.wait() + waiters = [ + threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) + for _ in range(3) + ] + for waiter in waiters: + waiter.start() + release.set() + for thread in [owner, *waiters]: + thread.join() + + self.assertEqual(reads, 1) + self.assertEqual([r.aliases for r in results], ["model"] * 4) + self.assertTrue(cache.get(API, *KEY).hit) + + def test_a_failed_read_is_not_cached(self): + for error in [ + RateLimitExceededError(status=429), + ForbiddenException(status=403), + UnauthorizedException(status=401), + ValidationException(status=400), + ServiceException(status=500), + TimeoutError(), + ]: + with self.subTest(error=type(error).__name__): + reads = 0 + + def read(*_): + nonlocal reads + reads += 1 + raise error + + cache = cache_reading(read) + self.assertIs(cache.get(API, *KEY).error, error) + self.assertIs(cache.get(API, *KEY).error, error) + self.assertEqual(reads, 2) + + def test_drops_the_least_recently_used_model(self): + cache = cache_reading(lambda store, model: f"{store}/{model}", max_models=2) + + cache.get(API, "a", "1") + cache.get(API, "b", "1") + self.assertTrue(cache.get(API, "a", "1").hit) + cache.get(API, "c", "1") + + self.assertTrue(cache.get(API, "a", "1").hit) + self.assertFalse(cache.get(API, "b", "1").hit) + + def test_threads_waiting_on_a_failed_read_get_its_error(self): + started = threading.Event() + release = threading.Event() + error = RuntimeError("forbidden") + + def read(*_): + started.set() + release.wait() + raise error + + cache = cache_reading(read) + results = [] + owner = threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) + owner.start() + started.wait() + waiters = [ + threading.Thread(target=lambda: results.append(cache.get(API, *KEY))) + for _ in range(3) + ] + for waiter in waiters: + waiter.start() + time.sleep(0.05) + release.set() + for thread in [owner, *waiters]: + thread.join() + + self.assertEqual([r.error for r in results], [error] * 4) + + def test_an_interrupted_read_is_not_cached(self): + interrupt = True + + def read(*_): + if interrupt: + raise KeyboardInterrupt() + return "model" + + cache = cache_reading(read) + with self.assertRaises(KeyboardInterrupt): + cache.get(API, *KEY) + + interrupt = False + self.assertEqual(cache.get(API, *KEY).aliases, "model") + + def test_keys_on_both_the_store_and_the_model(self): + reads = [] + errors = {("c", "1"): RateLimitExceededError(status=429)} + + def read(store, model): + reads.append((store, model)) + if (store, model) in errors: + raise errors[(store, model)] + return f"{store}/{model}" + + cache = cache_reading(read) + + def get(store, model): + return cache.get(API, store, model) + + self.assertEqual(get("a", "1").aliases, "a/1") + self.assertEqual(get("b", "1").aliases, "b/1") + self.assertEqual(get("a", "2").aliases, "a/2") + self.assertTrue(get("a", "1").hit) + self.assertTrue(get("b", "1").hit) + self.assertTrue(get("a", "2").hit) + self.assertEqual(reads, [("a", "1"), ("b", "1"), ("a", "2")]) + + get("c", "1") + self.assertEqual(get("d", "1").aliases, "d/1") + self.assertEqual(get("c", "2").aliases, "c/2") + self.assertEqual(reads[3:], [("c", "1"), ("d", "1"), ("c", "2")]) diff --git a/test/telemetry/configuration_test.py b/test/telemetry/configuration_test.py index 7b3761a4..48562217 100644 --- a/test/telemetry/configuration_test.py +++ b/test/telemetry/configuration_test.py @@ -282,18 +282,22 @@ def test_default_telemetry_metrics_configuration(): metrics_config = TelemetryMetricsConfiguration.getSdkDefaults() assert isinstance(metrics_config, dict) - assert len(metrics_config) == 3 + assert len(metrics_config) == 7 assert TelemetryCounters.fga_client_credentials_request in metrics_config assert TelemetryHistograms.fga_client_query_duration in metrics_config assert TelemetryHistograms.fga_client_request_duration in metrics_config + assert TelemetryCounters.fga_client_batch_check_checks_requested in metrics_config + assert TelemetryCounters.fga_client_batch_check_checks_sent in metrics_config + assert TelemetryCounters.fga_client_model_cache_lookup in metrics_config + assert TelemetryCounters.fga_client_batch_check_merge_fallback in metrics_config def test_default_telemetry_metric_configuration(): metric_config = TelemetryMetricConfiguration.getSdkDefaults() assert isinstance(metric_config, dict) - assert len(metric_config) == 16 + assert len(metric_config) == 17 assert ( metric_config[TelemetryAttributes.fga_client_request_batch_check_size] is False @@ -304,6 +308,7 @@ def test_default_telemetry_metric_configuration(): assert metric_config[TelemetryAttributes.fga_client_request_store_id] is True assert metric_config[TelemetryAttributes.fga_client_response_model_id] is True assert metric_config[TelemetryAttributes.fga_client_user] is False + assert metric_config[TelemetryAttributes.fga_client_model_cache_result] is True assert metric_config[TelemetryAttributes.http_client_request_duration] is False assert metric_config[TelemetryAttributes.http_host] is True assert metric_config[TelemetryAttributes.http_request_method] is True diff --git a/test/telemetry/metrics_test.py b/test/telemetry/metrics_test.py index 1de3af4c..93457f3a 100644 --- a/test/telemetry/metrics_test.py +++ b/test/telemetry/metrics_test.py @@ -4,6 +4,8 @@ from opentelemetry.metrics import Counter, Histogram, Meter +from openfga_sdk.telemetry.attributes import TelemetryAttributes +from openfga_sdk.telemetry.configuration import TelemetryConfiguration from openfga_sdk.telemetry.counters import TelemetryCounters from openfga_sdk.telemetry.histograms import TelemetryHistograms from openfga_sdk.telemetry.metrics import TelemetryMetrics @@ -80,3 +82,86 @@ def test_invalid_histogram_key(): telemetry = TelemetryMetrics() with pytest.raises(ValueError): telemetry.histogram("invalid_histogram_key") + + +@patch("openfga_sdk.telemetry.metrics.get_meter") +def test_batch_check_merge_counters_use_their_attribute_filters(mock_get_meter): + mock_meter = MagicMock(spec=Meter) + mock_counter = MagicMock(spec=Counter) + mock_get_meter.return_value = mock_meter + mock_meter.create_counter.return_value = mock_counter + + telemetry = TelemetryMetrics() + configuration = TelemetryConfiguration( + { + "metrics": { + "fga-client.model_cache.lookup": { + "fga-client.model_cache.result": True, + }, + } + } + ) + + telemetry.modelCacheLookup( + attributes={ + TelemetryAttributes.fga_client_model_cache_result: "hit", + TelemetryAttributes.fga_client_request_store_id: "store", + }, + configuration=configuration, + ) + mock_counter.add.assert_called_once_with( + amount=1, attributes={"fga-client.model_cache.result": "hit"} + ) + + # Not configured, so not recorded + mock_counter.add.reset_mock() + telemetry.batchCheckChecksSent(2, configuration=configuration) + telemetry.batchCheckChecksRequested(4, configuration=configuration) + telemetry.batchCheckMergeFallback(configuration=configuration) + mock_counter.add.assert_not_called() + + +@patch("openfga_sdk.telemetry.metrics.get_meter") +def test_batch_check_merge_counters_are_on_by_default(mock_get_meter): + mock_meter = MagicMock(spec=Meter) + mock_counter = MagicMock(spec=Counter) + mock_get_meter.return_value = mock_meter + mock_meter.create_counter.return_value = mock_counter + + telemetry = TelemetryMetrics() + configuration = TelemetryConfiguration(TelemetryConfiguration.getSdkDefaults()) + attributes = { + TelemetryAttributes.fga_client_request_store_id: "store", + TelemetryAttributes.fga_client_request_model_id: "model", + } + + telemetry.batchCheckChecksRequested(4, attributes, configuration) + telemetry.batchCheckChecksSent(2, attributes, configuration) + telemetry.batchCheckMergeFallback( + attributes={**attributes, TelemetryAttributes.http_response_status_code: 403}, + configuration=configuration, + ) + telemetry.modelCacheLookup( + attributes={ + **attributes, + TelemetryAttributes.fga_client_model_cache_result: "miss", + }, + configuration=configuration, + ) + + expected = { + "fga-client.request.store_id": "store", + "fga-client.request.model_id": "model", + } + assert [call.kwargs for call in mock_counter.add.call_args_list] == [ + {"amount": 4, "attributes": expected}, + {"amount": 2, "attributes": expected}, + { + "amount": 1, + "attributes": {**expected, "http.response.status_code": 403}, + }, + { + "amount": 1, + "attributes": {**expected, "fga-client.model_cache.result": "miss"}, + }, + ]