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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .coderabbit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ reviews:
tools:
phpstan:
enabled: true
config_file: "phpstan.neon"
phpcs:
enabled: false
phpmd:
Expand Down
12 changes: 12 additions & 0 deletions .cursor/rules/ask-before-commit.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
description: Ask before any commit or push
alwaysApply: true
---

# Ask before commit or push

Do not run `git commit`, `git push`, or open a pull request at the end of other work.

When the work is ready, stop and ask. Commit, push, or open a pull request only after an explicit approval in that same conversation. Approval sounds like "commit this", "push it", or "open the PR". Finishing the task is not approval.

"Commit and push" and "open the PR" are approval for that request. Do not wait for a second confirmation.
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ File-based lessons (`$CFG->lessons`, no `manifest_id`) must keep working.
- **App Store test harness (no login):** anything under `mod/` and anything under `tool/` can be launched from the store without signing in. Start at `$CFG->wwwroot/tool` (redirects to the store) or go directly to `$CFG->wwwroot/store/test/{name}` (for example `/tsugi/store/test/trophy`). Use **Try It**, pick an identity (Jane Instructor or a student), and exercise the tool in the iframe. Some instructor views (Trophy is one) show a launch var dump — that is expected, not a broken page. Do not assume a site login is required for this path.

## Commit & Pull Request Guidelines
- Do not commit, push, or open a pull request when a task is finished, unless this conversation already approved it. Stop and ask when that approval is absent. Approval sounds like "commit this", "push it", or "open the PR". "Commit and push" and "open the PR" are approval for that request. Do not wait for a second confirmation. See `.cursor/rules/ask-before-commit.mdc`.
- Recent commits are short, sentence-style summaries (e.g., “Add item to headers.”). Keep messages concise and action-oriented.
- PRs go through GitHub and require a CLA before acceptance (see `CONTRIBUTING.md`).
- If you touch vendored libraries in `vendor/`, include clear notes in the PR so maintainers can propagate changes across related repos.
Expand Down
4 changes: 2 additions & 2 deletions lib/include/setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
// upgrade checking - don't change this unless you want to trigger
// database upgrade messages it should be the max of all versions in
// all database.php files.
$CFG->dbversion = 202611200002;
$CFG->dbversion = 202611220002;

function die_with_error_log($msg, $extra=false, $prefix="DIE:") {
error_log($prefix.' '.$msg.' '.$extra);
Expand Down Expand Up @@ -177,7 +177,7 @@ function isCli() {
$LINK = false;

if (!defined('TSUGI_VERSION')) {
define('TSUGI_VERSION', '26.11.7'); // ← update this occasionally
define('TSUGI_VERSION', '26.11.9'); // ← update this occasionally
}

if (!defined('TSUGI_MINIMUM_PHP')) {
Expand Down
137 changes: 91 additions & 46 deletions lib/src/Core/LTIX.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use \Tsugi\Crypt\AesOpenSSL;
use \Tsugi\Services\Plus\GradeSync;
use \Tsugi\Services\Plus\PlusShell;
use \Tsugi\Services\Admin\AdminService;

use \Firebase\JWT\JWT;

Expand Down Expand Up @@ -1472,6 +1473,7 @@ public static function adjustData($p, &$row, $post, $needed) {
// $post['user_subject'] is the user_subject from the launch
// $row['subject_key'] is the subject from the row
if ( $row['user_id'] === null && isset($post['user_id']) && U::isNotEmpty($post['user_id']) ) {
self::requireNaturalKey('user_key', $post['user_id']);
$sql = "INSERT INTO {$p}lti_user
/*PDOX pk: user_id lk: user_sha256,key_id */
( guid, user_key, user_sha256, displayname, email, image, locale, key_id, created_at, updated_at ) VALUES
Expand All @@ -1497,24 +1499,29 @@ public static function adjustData($p, &$row, $post, $needed) {

// TODO: Combine this into the previous query after user_subject migrations run - 28-May-2019
if ( U::isNotEmpty($post_user_subject) ) {
$sql = "UPDATE {$p}lti_user SET
subject_key = :subject_key,
subject_sha256 = :subject_sha256,
updated_at = NOW()
WHERE user_id = :UID";

$stmt = $PDOX->queryReturnError($sql, array(
':UID' => $row['user_id'],
':subject_key' => $post_user_subject,
':subject_sha256' => lti_sha256($post_user_subject),
)
);

if ( $stmt->success ) {
$row['subject_key'] = $post_user_subject;
$actions[] = "=== Added subject to new user id=".$row['user_id']." ".$row['user_email'];
$subject_problem = AdminService::naturalKeyProblem('subject_key', $post_user_subject);
if ( $subject_problem !== null ) {
error_log($subject_problem);
} else {
error_log("Unable to update user_subject - please upgrade database email=".$row['user_email']);
$sql = "UPDATE {$p}lti_user SET
subject_key = :subject_key,
subject_sha256 = :subject_sha256,
updated_at = NOW()
WHERE user_id = :UID";

$stmt = $PDOX->queryReturnError($sql, array(
':UID' => $row['user_id'],
':subject_key' => $post_user_subject,
':subject_sha256' => lti_sha256($post_user_subject),
)
);

if ( $stmt->success ) {
$row['subject_key'] = $post_user_subject;
$actions[] = "=== Added subject to new user id=".$row['user_id']." ".$row['user_email'];
} else {
error_log("Unable to update user_subject - please upgrade database email=".$row['user_email']);
}
}
}
}
Expand All @@ -1523,6 +1530,8 @@ public static function adjustData($p, &$row, $post, $needed) {
$lti11_transition_user_id = isset($post['lti11_transition_user_id']) ? $post['lti11_transition_user_id'] : null;
$lti11_transition_user_id_sha256 = $lti11_transition_user_id === null ? null : lti_sha256($lti11_transition_user_id);
if ( $row['user_id'] === null && U::isNotEmpty($post_user_subject) ) {
self::requireNaturalKey('subject_key', $post_user_subject);
self::requireNaturalKey('user_key', $lti11_transition_user_id);
$sql = "INSERT INTO {$p}lti_user
/*PDOX pk: user_id lk: subject_sha256,user_sha256,key_id */
( guid, user_key, user_sha256, subject_key, subject_sha256, displayname, email, image, locale, key_id, created_at, updated_at ) VALUES
Expand Down Expand Up @@ -1554,43 +1563,53 @@ public static function adjustData($p, &$row, $post, $needed) {
// Note that we will forever check for errors because of duplicate key possibilities
if ( $row['user_id'] > 0 && U::isNotEmpty($post_user_subject) && U::isNotEmpty($lti11_transition_user_id) &&
$row['user_key'] != $lti11_transition_user_id) {
$sql = "UPDATE {$p}lti_user
SET user_key = :user_key, user_sha256 = :user_sha256, updated_at = NOW()
WHERE user_id = :uid";
$stmt = $PDOX->queryReturnError($sql, array(
':uid' => $row['user_id'],
':user_key' => $lti11_transition_user_id,
':user_sha256' => $lti11_transition_user_id_sha256,
)
);

if ( $stmt->success ) {
$row['user_key'] = $lti11_transition_user_id;
$actions[] = "=== Updated user_key for id=".$row['user_id']." subject=".$post_user_subject.
" transition_user_uid=".$lti11_transition_user_id;
$user_key_problem = AdminService::naturalKeyProblem('user_key', $lti11_transition_user_id);
if ( $user_key_problem !== null ) {
error_log($user_key_problem);
} else {
error_log("Unable to update user_key - transition problem subject=$post_user_subject user_id=".$row['user_id']);
$sql = "UPDATE {$p}lti_user
SET user_key = :user_key, user_sha256 = :user_sha256, updated_at = NOW()
WHERE user_id = :uid";
$stmt = $PDOX->queryReturnError($sql, array(
':uid' => $row['user_id'],
':user_key' => $lti11_transition_user_id,
':user_sha256' => $lti11_transition_user_id_sha256,
)
);

if ( $stmt->success ) {
$row['user_key'] = $lti11_transition_user_id;
$actions[] = "=== Updated user_key for id=".$row['user_id']." subject=".$post_user_subject.
" transition_user_uid=".$lti11_transition_user_id;
} else {
error_log("Unable to update user_key - transition problem subject=$post_user_subject user_id=".$row['user_id']);
}
}
}

// If we already have a user_key and we just got a new post_user_subject
// Always check and log errors in case the transition went badly and then was reconfigured
$row_subject_key = U::get($row, 'subject_key');
if ( $row['user_id'] > 0 && U::isNotEmpty($post_user_subject) && $post_user_subject != $row_subject_key ) {
$sql = "UPDATE {$p}lti_user
SET subject_key = :subject_key, subject_sha256 = :subject_sha256, updated_at = NOW()
WHERE user_id = :uid";
$stmt = $PDOX->queryReturnError($sql, array(
':uid' => $row['user_id'],
':subject_key' => $post_user_subject,
':subject_sha256' => lti_sha256($post_user_subject),
)
);
if ( $stmt->success ) {
$row['subject_key'] = $post_user_subject;
$actions[] = "=== Updated subject_key for id=".$row['user_id']." post_user_subject=".$post_user_subject;
$subject_problem = AdminService::naturalKeyProblem('subject_key', $post_user_subject);
if ( $subject_problem !== null ) {
error_log($subject_problem);
} else {
error_log("Unable to update subject_key - transition problems post_user_subject=".$post_user_subject." user_id=".$row['user_id']);
$sql = "UPDATE {$p}lti_user
SET subject_key = :subject_key, subject_sha256 = :subject_sha256, updated_at = NOW()
WHERE user_id = :uid";
$stmt = $PDOX->queryReturnError($sql, array(
':uid' => $row['user_id'],
':subject_key' => $post_user_subject,
':subject_sha256' => lti_sha256($post_user_subject),
)
);
if ( $stmt->success ) {
$row['subject_key'] = $post_user_subject;
$actions[] = "=== Updated subject_key for id=".$row['user_id']." post_user_subject=".$post_user_subject;
} else {
error_log("Unable to update subject_key - transition problems post_user_subject=".$post_user_subject." user_id=".$row['user_id']);
}
}
}

Expand All @@ -1616,6 +1635,7 @@ public static function adjustData($p, &$row, $post, $needed) {
// This is for LTI 1.x only as service is not used for LTI 2.x
$oldserviceid = $row['service_id'];
if ( $row['service_id'] === null && $post['service'] ) {
self::requireNaturalKey('service_key', $post['service']);
$sql = "INSERT INTO {$p}lti_service
( service_key, service_sha256, key_id, created_at, updated_at ) VALUES
( :service_key, :service_sha256, :key_id, NOW(), NOW() )
Expand Down Expand Up @@ -3066,6 +3086,22 @@ public static function noteLoggedIn($row)
}
}

/**
* Stop before the insert when a natural key cannot be stored.
* The column would reject it, and the launch would die as a database failure.
*
* @param string $column
* @param mixed $value
*/
private static function requireNaturalKey($column, $value) {
$problem = AdminService::naturalKeyProblem($column, $value);
if ( $problem === null ) {
return;
}
error_log($problem);
die($problem);
}

/**
* populateRoster
*
Expand Down Expand Up @@ -3112,11 +3148,20 @@ public static function populateRoster($groups=false, $insert=false) {
$key = $PDOX->rowDie("SELECT key_id
FROM {$CFG->dbprefix}lti_key WHERE key_key = :key",
array(':key' => $TSUGI_LAUNCH->context->key));
if (! $key ) return false;
if (! $key ) {
$PDOX->setAttribute(\PDO::ATTR_ERRMODE, $errormode);
return false;
}

$insertUserArray = [];
$insertUserMembershipArray = [];
foreach($ROSTER->data as $user) {
$user_key_problem = AdminService::naturalKeyProblem('user_key', isset($user['user_id']) ? $user['user_id'] : null);
if ( $user_key_problem !== null ) {
error_log($user_key_problem);
$PDOX->setAttribute(\PDO::ATTR_ERRMODE, $errormode);
return false;
}
array_push($insertUserArray,
"(UNHEX('".Guid::uuid7()."'), '". $user['user_id'] ."', '".
lti_sha256($user['user_id']) ."', '".
Expand Down
85 changes: 85 additions & 0 deletions lib/src/Services/Admin/AdminService.php
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,91 @@ public static function identityAsciiColumns() {
);
}

/**
* Natural keys the upgrade narrows to ascii_bin. The fourth value is the varchar length.
*
* subject_key is an LTI 1.3 sub, so it matches the other identity columns at 255.
* user_key and profile_key also store googlemail: plus an email. An email can be
* 254 characters, so 255 would reject a legal value. 512 covers it.
* service_key is lis_outcome_service_url. 1024. A COMPACT index holds 767 bytes,
* and 1024 plus key_id does not fit, so that alter waits until the table is DYNAMIC.
* string_text stays TEXT. A translation string is not one of these columns.
*
* The fifth value is the unique constraint name without the database prefix.
* The sixth is the unique column list. ascii_bin ignores trailing spaces, so the
* unique is on a generated VARBINARY column of the exact bytes, named column_bin.
* The seventh value is true when the varchar accepts NULL.
* NULL user_key and NULL subject_key stay allowed more than once per key.
*
* @return array<int, array{0:string,1:string,2:string,3:int,4:string,5:array<int,string>,6:bool}>
*/
public static function naturalKeyAsciiColumns() {
return array(
array('lti_user', 'subject_key', 'user_id', 255, 'lti_user_const_subject_key', array('key_id', 'subject_key_bin'), true),
array('lti_user', 'user_key', 'user_id', 512, 'lti_user_const_user_key', array('key_id', 'user_key_bin'), true),
array('profile', 'profile_key', 'profile_id', 512, 'profile_const_key', array('profile_key_bin'), false),
array('lti_service', 'service_key', 'service_id', 1024, 'lti_service_const_key', array('key_id', 'service_key_bin'), false),
);
}

/**
* Why this value cannot be stored in a natural-key column, or null when it can.
*
* Null is allowed for user_key and subject_key. A leading or trailing space
* is rejected, and so is a non-printing character, same as an issuer or client id.
* A space in the middle is kept. The value itself is left out of the message,
* because user_key and profile_key can be an email address.
*
* @param string $column
* @param mixed $value
* @return string|null
*/
public static function naturalKeyProblem($column, $value) {
$spec = null;
foreach ( self::naturalKeyAsciiColumns() as $natural ) {
if ( $natural[1] === $column ) {
$spec = $natural;
break;
}
}
if ( $spec === null ) {
return $column.' is not a natural key column.';
}
$width = (int) $spec[3];
$nullable = ! empty($spec[6]);
if ( $value === null ) {
return $nullable ? null : $column.' has no value.';
}
if ( ! is_string($value) ) {
return $column.' is not text.';
}
$reasons = array();
if ( preg_match('/[^\x00-\x7F]/', $value) === 1 ) {
$reasons[] = 'has a character outside ASCII';
}
$length = strlen($value);
if ( $reasons && function_exists('mb_strlen') ) {
$counted = mb_strlen($value, 'UTF-8');
if ( is_int($counted) ) $length = $counted;
}
if ( $length > $width ) {
$reasons[] = 'is '.$length.' characters and the limit is '.$width;
}
if ( preg_match('/^ /', $value) === 1 ) {
$reasons[] = 'has a leading space';
}
if ( preg_match('/ $/', $value) === 1 ) {
$reasons[] = 'has a trailing space';
}
if ( preg_match('/[\x00-\x1F\x7F]/', $value) === 1 ) {
$reasons[] = 'contains a non-printing character';
}
if ( count($reasons) < 1 ) return null;
if ( count($reasons) === 1 ) return $column.' '.$reasons[0].'.';
$last = array_pop($reasons);
return $column.' '.implode(', ', $reasons).' and '.$last.'.';
}

/**
* Identity columns that are not yet varchar(255) character set ascii collation ascii_bin.
* A missing table or column is included. Names are table.column without the database prefix.
Expand Down
7 changes: 7 additions & 0 deletions lib/src/Services/Login/GoogleLoginService.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use \Tsugi\Core\Cache;
use \Tsugi\Core\User;
use \Tsugi\Controllers\Login;
use Tsugi\Services\Admin\AdminService;
use Tsugi\Services\Permissions\PermissionTables;

/**
Expand Down Expand Up @@ -146,6 +147,12 @@ public static function establishSiteSession($user_key, $userEmail, $displayName,
global $CFG, $PDOX;

$result = new GoogleLoginResult();
$user_problem = AdminService::naturalKeyProblem('user_key', $user_key);
$profile_problem = AdminService::naturalKeyProblem('profile_key', $user_key);
if ( $user_problem !== null || $profile_problem !== null ) {
$result->error = $user_problem !== null ? $user_problem : $profile_problem;
return $result;
}
if ( session_id() == "" ) {
session_start();
}
Expand Down
Loading
Loading