MDL Shield

Restriction by cohort

availability_cohort

Print Report
Plugin Information

Availability condition plugin that restricts access to course activities and sections based on site or category cohort membership, either a specific cohort or "any cohort" visible in the course's context hierarchy. It also offers opt-in cleanup of orphaned restrictions when a cohort is deleted or a course is restored.

Privacy API
Unit Tests
Behat Tests
Reviewed:2026-11-10
17 files·2,411 lines
Grade Justification

No exploitable vulnerability was found. All database access goes through the $DB API with placeholders. Concatenated SQL fragments come only from get_in_or_equal() or from unique_sql_parameter() in core. Cohort names reach the YUI form only after format_string(), which escapes HTML (verified in lib/classes/formatting.php). The plugin has no pages, forms or web services of its own, so there is no unchecked entry point, and the selectable cohorts come from core's capability-aware cohort_get_available_cohorts().

The review found three low-severity issues:

  • An editing teacher who tampers with the availability JSON can resolve the name of any cohort on the site. Filtered user lists then show which of their enrolled users belong to it. The author documents this as an accepted risk. It needs editing rights and request tampering, and it exposes only names and membership of users already in the course.
  • The opt-in cohort-deletion cleanup changes the meaning of NOT-AND (!&) trees, which can restrict an activity that was available to everyone.
  • is_available() runs uncached queries on every evaluation.

None of these can be used against other users without elevated roles, and the code is well tested with PHPUnit and Behat.

AI Summary

availability_cohort is a small availability condition plugin of about 600 lines of production PHP plus a YUI form module. It restricts activities and sections to members of a specific cohort or of any cohort in the course's context hierarchy. Two opt-in admin settings remove orphaned restrictions when a cohort is deleted or a course is restored. It has no pages, forms, web services or tables of its own. It ships PHPUnit and Behat coverage for the condition, restore handling and the deletion observer.

The security posture is good. All SQL is parameterised, and cohort names are escaped by format_string() before the JavaScript builds HTML from them. The cohorts offered to teachers come from core's capability-aware cohort_get_available_cohorts(). Privacy is handled correctly with a null provider, since the plugin stores no personal data.

Two findings deserve attention:

  • Cohort name and membership disclosure. The stored cohort id is never validated against the course context, so an editing teacher who tampers with the availability JSON can resolve the names of hidden cohorts in other categories. Filtered user lists then reveal which enrolled users belong to them. The author documents this as an accepted risk, and the impact is limited.
  • Deletion cleanup can change restriction logic. The opt-in observer drops conditions without accounting for negation. In a NOT-AND (!&) tree, an activity that became open to everyone once the cohort was deleted can end up restricted after the cleanup runs. That is the opposite of what the setting is for.

The remaining finding is a performance note about uncached per-evaluation queries in is_available().

Findings

securityLow
Cohort id not checked against course context; hidden cohort names exposed
Exploitable by:
editingteacher

The condition accepts any integer cohort id from the saved availability JSON. get_description() looks up the name of that cohort site-wide, with no check on the cohort's context or visibility. get_cohort_members_sql() and is_available() likewise match membership of any cohort. The form only offers cohorts that cohort_get_available_cohorts() lets the current user see. However, the JSON is posted from the client, and core's report_validation_errors() gives the plugin no server-side hook to reject ids. An editing teacher can therefore set ids for cohorts they cannot view, such as hidden cohorts in other categories. The restriction text then shows those cohorts' names, and participant or grader lists filtered by the condition reveal which enrolled users are members. The author acknowledges this in the code comment at line 239.

Risk Assessment

Low risk. Exploitation needs activity-editing rights and request tampering, and it only exposes cohort names and the cohort membership of users already enrolled in the teacher's course. That can still be sensitive where cohorts encode personal circumstances, for example a support-needs cohort, so the trade-off is worth stating explicitly for admins.

Context

Core availability plugins have no server-side validation step for condition parameters, so each plugin must constrain ids itself when evaluating them. The core availability_group condition limits name resolution to the groups of the item's course; this plugin deliberately evaluates cohorts site-wide so that restored or admin-set restrictions keep working.

Proof of Concept

Open an activity's edit form as an editing teacher and submit the form with the hidden field changed to availabilityconditionsjson={"op":"&","c":[{"type":"cohort","id":42}],"showc":[true]}, where 42 is a hidden category cohort the teacher cannot view. The course page then shows "You belong to <cohort 42 name>", and filtered participant or grading lists show which enrolled students are members.

Identified Code
$cohorts = $DB->get_records('cohort', ['id' => $this->cohortid], '', 'id, name');
foreach ($cohorts as $rec) {
    self::$cohortnames[$rec->id] = $rec->name;
}
Suggested Fix

Only resolve the name when the cohort lives in the course's context hierarchy (the cohorts the form can offer). Otherwise show the generic missing string, or a neutral "(Restricted cohort)" string:

$context = \context_course::instance($info->get_course()->id);
[$insql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED);
$params['id'] = $this->cohortid;
$cohorts = $DB->get_records_select('cohort', "id = :id AND contextid $insql", $params, '', 'id, name');
Identified Code
$sql = "SELECT cm.userid
          FROM {cohort_members} cm
         WHERE cm.cohortid = " . self::unique_sql_parameter($params, $this->cohortid);
Suggested Fix

If cohorts outside the course's context hierarchy do not need to be supported, apply the same context restriction here and in is_available() so that evaluation and user-list filtering stay consistent. Otherwise, document the trade-off in the README so site admins know editing teachers can probe arbitrary cohorts.

code qualityLow
Deletion cleanup changes meaning of NOT-AND restriction trees

After a cohort is deleted, a condition requiring it is always false, and true when negated. The observer simply drops such leaves, and drops subtrees that become empty, from every tree. Dropping is only harmless when the removed value does not decide the outcome. Core's get_logic_flags() evaluates a !& node as NOT A OR NOT B. A !& tree containing the deleted cohort therefore evaluates to true for everyone after deletion. Once the cohort leaf is removed, the remaining siblings decide alone, and the activity becomes restricted. The same happens when a negated subtree containing only that cohort sits inside an OR parent. verify_cohort_removal() checks only that the other leaves survive, not that the logic is unchanged.

Risk Assessment

Low risk. This is a correctness bug, not a vulnerability. It only occurs with the opt-in setting and negated restriction sets. The effect is that content which had become open to students silently becomes restricted, the opposite of what the admin asked for.

Context

cohort_deleted() runs only when the admin enables cleanuponcohortdeletion. It rewrites availability in course_modules and course_sections site-wide inside a transaction, then rebuilds course caches. The setting is meant to stop orphaned restrictions from hiding content from everyone.

Identified Code
} else if (
    isset($child->type) && $child->type === 'cohort'
        && isset($child->id) && (int)$child->id === $cohortid
) {
    // The child is a condition which requires the deleted cohort, so we drop it.
    // Note: An 'any cohort' condition does not hold an id and is therefore intentionally kept.
    $changed = true;
Suggested Fix

Pass the effective negation state down the recursion, toggling it on !& and !| nodes. When the dropped leaf is effectively true and the node combines its children with OR (an effective |, or a !& under non-negation), replace the whole node with "no restriction" instead of removing just the leaf. Alternatively, skip and log trees containing !& or !| and leave them for manual review.

best practiceLow
is_available() runs uncached queries on every evaluation

Core calls is_available() once per restricted activity or section for every page that builds availability information, such as course pages, the dashboard and navigation. For a specific cohort it calls cohort_is_member(), one query per call. For "any cohort" it loads full cohort records for all parent contexts through availability_cohort_cohort_get_cohorts() and then runs a second membership query. The $grabthelot hint is ignored and nothing is cached, so a course with many cohort-restricted items adds two queries per item per page load. The comment in get_description() claims it fetches all cohorts at once, but it also queries one cohort per id.

Risk Assessment

Low risk. This is a performance issue, not a security one. On sites with many cohort-restricted activities it adds a noticeable number of queries per page view.

Context

is_available() sits on the hot path of course rendering through core_availability\info. The uncached pattern here contrasts with the plugin's own filter_user_list(), which is already written to batch queries.

Identified Code
if ($this->cohortid) {
    // User is member of the given cohort.
    $allow = cohort_is_member($this->cohortid, $userid);
} else {
    // Cohort condition is set to "any cohort".
    $allcohorts = availability_cohort_cohort_get_cohorts(\context_course::instance($course->id));
    foreach ($allcohorts["cohorts"] as $cohort) {
        $cohortids[] = $cohort->id;
    }
    $allow = availability_cohort_is_member($userid, $cohortids);
}
Suggested Fix

Cache the user's cohort memberships per request, for example in a static array keyed by user id. Fill it with one query when $grabthelot is true or on first use, and answer both modes from the cache, as core availability_group does with its course-group cache.

Identified Code
$cohorts = $DB->get_records_list('cohort', 'contextid', $contextids);
Suggested Fix

If kept, fetch only ids ($DB->get_fieldset_select() or a fields argument of 'id'), or fold this into a single EXISTS join against {cohort_members}.

Additional AI Notes

Verified safe patterns. Cohort names are passed through format_string() before the YUI form concatenates them into <option> HTML. In Moodle 5.3, format_string() escapes </> or runs clean_text(), depending on formatstringstriptags. The get_description() output uses description_format_string(), which is formatted later by info::format_info().

Restore handling is careful. include_after_restore() / update_after_restore() replace a cohort id coming from a different site with -1 instead of letting it silently map to an unrelated local cohort. That prevents a restored backup from granting access through a coincidentally matching id.

Minor tidy-ups. In classes/frontend.php, the $allcohorts property is declared but never used, and cohort_get_available_cohorts() runs twice per form render (allow_add() and get_javascript_init_params()). Caching the result in the property would remove the duplicate query.

This review was generated by an AI system and may contain inaccuracies. Findings should be verified by a human reviewer before acting on them.