# Read grants for the data warehouse das computes, for each user, a set of **read grants**: OData `$filter` expressions that reproduce das's v1 read rules for events, subjects, observations, patrols, patrol segments, patrol types and segment types. das acts as the facade for data warehouse (DWH) reads: it proxies each request to the DWH and passes the grants in the request body, so the DWH scopes rows exactly as das would. Patrols are the exception until the das patrol view fix (ERA-14496) lands: their grants follow the target rules (see [Patrols](#patrols)). The property vocabulary and types the filters use are defined in the spec: [OData Filters in ER & DWH → Domain vocabulary](https://allenai.atlassian.net/wiki/spaces/ER/pages/31738822669/OData+Filters+in+ER+DWH#Domain-vocabulary). The grants are computed by `compute_grants`: ```python from accounts.authz_grants import compute_grants envelope = compute_grants(request.user) ``` It must run with the user's tenant as the current tenant (as it is during a request); otherwise it raises `ValueError`. ## Envelope ```json { "v": 1, "tenant": "c0973be2-8e11-4cb8-8463-897fb96391d0", "grants": [ {"type": "er.events", "filter": "(event_category in ('monitoring','security')) and ((not related_subjects/any()) or (related_subjects/any(s: s/groups/any(g: g eq '6f1c…'))))"}, {"type": "er.subjects", "filter": "(groups/any(g: g eq '6f1c…')) or (id eq '93d2…')"}, {"type": "er.patrols", "filter": "true"}, {"type": "er.patrol_segments", "filter": "(leader eq null) or ((leader/groups/any(g: g eq '6f1c…')) or (leader/id eq '93d2…'))"}, {"type": "er.patrol_types", "filter": "true"} ] } ``` - `v`: envelope version, always `1`. - `tenant`: the user's tenant id. - `grants`: a list of `{type, filter}`. Several grants of one type are OR-combined. A type with no grant is denied. Rules that hold for every grant: - A grant is issued only when the user holds the resource-level permission das checks (see the table). Otherwise it is left out, which denies that type. - Superusers get `true` for every type. Inactive users get an empty `grants` list. - Filters reference subject groups and source groups, never lists of subjects. The only subject id that appears is the user's own linked subject. - Subject groups are expanded to all their descendants; source groups are not (except for observations, see below). - A single-element list is written with `eq` instead of `in`, because the odata-query 0.10.0 parser (the DWH's) rejects a one-element `in` list. ## Grants | Type | Issued when the user has | Filter | das rule it reproduces | |---|---|---|---| | `er.events` | `_read` on at least one active category | `event_category in (...)` and `not related_subjects/any() or related_subjects/any(s: s/groups/any(g: g in (...)))` | `GET /activity/events` (`events_in_permitted_categories`, `events_with_visible_subjects`) | | `er.subjects` | `view_subject` or `view_source`; or a linked subject | `groups/any(g: g in (...))` or `id eq ''` or `sources/any(src: src/groups/any(g: g in (...)))` | `GET /subjects` (`SubjectsView`) | | `er.observations` | `view_observation`, an `access_begins_*` and an `access_ends_*` permission | `subject/groups/any(...)` or (`not (subject eq null)` and `source/groups/any(...)`), and `recorded_at ge now() sub duration'PD'`, `recorded_at le now() sub duration'PD'`, `recorded_at le ` | subject tracks (`SubjectTracksView`, `calculate_track_range`) | | `er.patrols` | `activity.view_patrol` | `true` | target rule A: every patrol is listed (das views differ until ERA-14496, see below) | | `er.patrol_segments` | `activity.view_patrol` | `leader eq null` or `leader/groups/any(g: g in (...))` or `leader/id eq ''` | target rules A and B: a leg is shown only when its own leader is unset, not a subject, or visible (das views differ until ERA-14496, see below) | | `er.patrol_types` | `activity.view_patroltype` or `activity.view_patrol` | `true` | `PatrolTypePermissions` | | `er.segment_types` | `activity.view_patroltype` or `activity.view_patrol` | `true` | `SegmentTypeViewSet` uses `PatrolTypePermissions` | ### Events Only `_read` counts. das's events list also shows a category the user can only see geographically (`view__gd`), but only near the location the client sends. That is out of scope for v1, so those categories are left out: supporting them needs the location forwarded through the proxy and geo functions in the DWH translator. Related subjects use the user's subject groups only: no linked subject and no source groups, as in `Subject.objects.by_user_subjects`. ### Subjects The three subject conditions are OR-ed. Source groups are those attached to the user's permission sets, not expanded. Without `view_subject` or `view_source` das still returns the linked subject, so the grant is just `id eq ''`. The window permissions (`access_begins_*`, `access_ends_*`) do not open the subjects list: `VIEW_SUBJECT_PERMS` lists them as `(name, days)` tuples, which `has_any_perms` never matches. ### Observations An observation is matched through its subject assignment: `subject` is the subject its source was assigned to at `recorded_at`, and null when no assignment covers that time. The DWH must resolve `subject` per observation timestamp. The filter follows the subject track view rather than the subjects list: - A subject group counts only when a permission set of the user that holds `view_subject` is attached to it (or to an ancestor group), directly or as an ancestor permission set. That is the object-level `view_subject` check the track view makes. - Source groups are expanded to their descendants (`SourceGroup.get_all_sources`). The condition is on the observation's own source and requires an assigned subject, `not (subject eq null) and source/groups/any(g: g in (...))`: for a subject reached only through a source group, the track view serves only the observations of the permitted sources, within their assignment to the subject. `source` is an addition to the spec's `er.observations` vocabulary, which the DWH translator must support. - The linked subject is not included. - `recorded_at ge now() sub duration'PD'` is the widest `access_begins_*` window, and `recorded_at le now() sub duration'PD'` the shortest `access_ends_*` delay. With no delay (`access_ends_0`) there is no upper bound, because das lets real-time users read future data. - The MOU expiry (`user.additional["expiry"]`, UTC when it has no zone) is an absolute upper bound. An expiry past the last UTC date (e.g. `9999-12-31T23:00:00-05:00`) adds no bound. The user gets no `er.observations` grant (the other grants are unaffected) when the expiry cannot be applied: das cannot parse it, it is not a string, `additional` is not an object, or it falls before year 1000, the earliest datetime odata-query 0.10.0 accepts (das serves nothing for such a long-expired MOU). The window and MOU limits also apply to subjects reached through a source group. das's track view does not limit those tracks, so the grant is stricter there. ### Patrols The grants follow the patrol read rules product has set as the target: - **A. Patrols list**: every patrol, each with only the segments (legs) the user may see. A patrol with no visible leg is still listed, with no segments. - **B. Patrol detail**: always served, without the legs the user may not see. The current das views do not follow these rules yet: the list and the detail decide on whole patrols by their leaders. That is a das bug tracked in ERA-14496; the grants already follow A and B. `er.patrols` is `true`: with `activity.view_patrol` every patrol is readable. `er.patrol_segments` decides each leg on the leg's own leader. `leader` is null when the leg has no leader or its leader is not a subject (e.g. a user), and such a leg is visible. Otherwise the leader must be in one of the user's subject groups (expanded to descendants) or be the user's linked subject. Source groups do not make a leader visible. The order of the legs does not matter. `er.patrol_segments` is an addition to the spec's vocabulary, which the DWH translator must support. `er.patrols` being `true` is only safe together with `er.patrol_segments`. A translator must reject (fail closed) any grant type it cannot apply rather than ignore it, otherwise every leg would leak. A missing `er.patrol_segments` grant denies every leg: patrols are returned with no legs. How the DWH is expected to apply them: - `er.patrols` goes in the patrol query's `WHERE`. `er.patrol_segments` filters the segment rows the patrol `LEFT JOIN`s, e.g. in the `WHERE` of a segment subquery that is `LEFT JOIN`ed. That is equivalent to putting it in the join's `ON` clause, which BigQuery rejects when the grant needs table subqueries. It must not go in the outer `WHERE`, so a patrol with no visible leg is kept, with no segments. - `leader` is the leader id whenever the leader's content type is a subject, whether or not that subject row exists in the DWH. A dangling subject id stays non-null and so hides the leg. - Query filters on legs (patrol type, leader, dates) match visible legs only: a patrol matches when one of its visible legs does. - Events nested in a visible leg are filtered by `er.events`. - The members and assets of a visible leg are always shown. - Patrol-level fields (title, objective, notes, files, state, times) are always shown. Derived state and times are computed from all legs, including hidden ones. ## Implementation - `accounts/authz_grants.py`: `compute_grants`, the provider registry and `GrantContext`. - `activity/authz_grants.py`: `er.events`, `er.patrols`, `er.patrol_segments`, `er.patrol_types`, `er.segment_types`. - `observations/authz_grants.py`: `er.subjects`, `er.observations` and the shared subject conditions. - `utils/odata.py`: literal quoting and `and`/`or`/`in` builders. Providers are listed in `settings.AUTHZ_GRANT_PROVIDERS`. A provider takes a `GrantContext` and returns a list of grants. `GrantContext` loads the user's permission sets, their ancestors and their permissions once, walking the permission set and group hierarchies in memory from one edge query each, so the number of queries does not depend on how many groups or permission sets a user has. Providers share derived data, such as the expanded subject groups, through `GrantContext.memoize`. ## Cost A normal user costs at most 10 queries and a superuser none. Measured on a large tenant fixture (2,000 subject groups, 200 source groups, 60 readable event categories, a chain of 200 permission sets; see `accounts/tests/test_authz_grants.py::TestLargeTenantMeasurement`, run with `pytest -m perf`): | Queries | Time | Envelope size | Largest grant | |---|---|---|---| | 10 | 210 ms | 329 KB | 86 KB (`er.subjects`, `er.observations`) | Measured on a local Docker test database. Size grows with the number of subject groups a user can see (about 40 bytes per group id per grant that lists it); `er.events`, `er.subjects`, `er.observations` and `er.patrol_segments` each list them. Grants are not cached; a short per-user cache can be added if this cost shows up in proxied requests. ## Tests The parity tests apply each grant with odata-query's Django backend to das querysets (via `observations/tests/authz_grants_harness.py`) and compare the rows with das's own endpoints: the events list, the subjects list, subject tracks and the patrols list. The patrols list and detail parity tests for a user without full access are skipped until the das views follow rules A and B; until then, `PatrolSegment` and `Patrol` are checked against the expected rows directly.