diff --git a/.coderabbit.yaml b/.coderabbit.yaml index afc8b2182f..46ccd26870 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -91,7 +91,6 @@ reviews: tools: phpstan: enabled: true - config_file: "phpstan.neon" phpcs: enabled: false phpmd: diff --git a/.cursor/rules/coderabbit-fixes-stay-local.mdc b/.cursor/rules/coderabbit-fixes-stay-local.mdc new file mode 100644 index 0000000000..e80257f4e6 --- /dev/null +++ b/.cursor/rules/coderabbit-fixes-stay-local.mdc @@ -0,0 +1,12 @@ +--- +description: Do not push CodeRabbit fixes until the user has seen the diff +alwaysApply: true +--- + +# CodeRabbit fixes stay local + +When the work is fixing CodeRabbit comments, do not push the branch. + +Make the changes and stop. Leave them unpushed so the user can read the diff. A CodeRabbit review, a red check, or "fix the comments" is not permission to push, force-push, or open a pull request. + +Push only after the user explicitly says to push in that conversation, once they have seen what changed. diff --git a/config-dist.php b/config-dist.php index fddd1383b6..1d341341db 100644 --- a/config-dist.php +++ b/config-dist.php @@ -174,6 +174,10 @@ function __the_end(){ // $CFG->home_path = 'https://example.com/'; // Legacy: $CFG->setExtension('home_path', $CFG->apphome); +// Temporary log when a launch or Plus token takes LTI config from lti_registration +// instead of lti_key. On unless set false. Remove by February 2027. +// $CFG->setExtension('log_registration_keys', false); + // Temporary ReqScope dump at /reqscope and tool/reqscope. Remove around December 2026. // /admin lists this with the QA settings when it is on. // $CFG->setExtension('reqscope_debug', true); diff --git a/lib/src/Controllers/Admin/Key.php b/lib/src/Controllers/Admin/Key.php index 12a6a08f4c..f867a2c5c4 100644 --- a/lib/src/Controllers/Admin/Key.php +++ b/lib/src/Controllers/Admin/Key.php @@ -18,6 +18,10 @@ public static function routes(Application $app) { self::map($app, self::class, 'clientCheck', self::paths('key/client-id-check')); self::map($app, self::class, 'add', self::paths('key/key-add')); self::map($app, self::class, 'detail', self::paths('key/key-detail')); + self::map($app, self::class, 'registrations', self::paths('key/registrations')); + self::map($app, self::class, 'registrationAdd', self::paths('key/registration-add')); + self::map($app, self::class, 'registrationDetail', self::paths('key/registration-detail')); + self::map($app, self::class, 'registrationFromKey', self::paths('key/registration-from-key')); self::map($app, self::class, 'settings', self::paths('key/key-settings')); self::map($app, self::class, 'requests', self::paths('key/requests')); self::map($app, self::class, 'request', self::paths('key/request-detail')); @@ -46,6 +50,26 @@ public function detail() { $this->view('key/key-detail.php'); } + public function registrations() { + if ( $r = $this->gate('keys.view') ) return $r; + $this->view('key/registrations.php'); + } + + public function registrationAdd() { + if ( $r = $this->gate('keys.add') ) return $r; + $this->view('key/registration-add.php'); + } + + public function registrationDetail() { + if ( $r = $this->gate('keys.detail') ) return $r; + $this->view('key/registration-detail.php'); + } + + public function registrationFromKey() { + if ( $r = $this->gate('keys.add') ) return $r; + $this->view('key/registration-from-key.php'); + } + public function settings() { if ( $r = $this->gate('keys.settings') ) return $r; $this->view('key/key-settings.php'); diff --git a/lib/src/Controllers/Instructor.php b/lib/src/Controllers/Instructor.php index 2dbd0b7b6d..7cf791cd9f 100644 --- a/lib/src/Controllers/Instructor.php +++ b/lib/src/Controllers/Instructor.php @@ -1211,6 +1211,9 @@ public function keyDetail(Request $request) $query_fields, $allow_edit, $allow_delete); if ( $row === CrudForm::CRUD_FAIL || $row === CrudForm::CRUD_SUCCESS ) { + if ( $row === CrudForm::CRUD_SUCCESS && isset($_POST['doUpdate']) ) { + LTIX::clearKeysetCache(U::get($_REQUEST, 'key_id')); + } return new RedirectResponse($from_location); } if ( ! is_array($row) ) { diff --git a/lib/src/Controllers/Settings.php b/lib/src/Controllers/Settings.php index 8fc9dbcb53..4e402d53b1 100644 --- a/lib/src/Controllers/Settings.php +++ b/lib/src/Controllers/Settings.php @@ -1348,6 +1348,9 @@ public function keyDetail(Request $request) $query_fields, $allow_edit, $allow_delete); if ( $row === CrudForm::CRUD_FAIL || $row === CrudForm::CRUD_SUCCESS ) { + if ( $row === CrudForm::CRUD_SUCCESS && isset($_POST['doUpdate']) ) { + LTIX::clearKeysetCache(U::get($_REQUEST, 'key_id')); + } return new RedirectResponse($from_location); } if ( ! is_array($row) ) { diff --git a/lib/src/Controllers/templates/Admin/key/blackboard-detail.php b/lib/src/Controllers/templates/Admin/key/blackboard-detail.php index 622f4917e0..0bcbe65644 100644 --- a/lib/src/Controllers/templates/Admin/key/blackboard-detail.php +++ b/lib/src/Controllers/templates/Admin/key/blackboard-detail.php @@ -1,10 +1,9 @@
-Blackboard uses a single issuer for all tenants, but +Blackboard uses one issuer for every school, but since the Blackboard developer portal assigns a Well-Known/KeySet URL that is unique -to each Client ID, it is best to skip creating a reusable Issuer in Tsugi, and instead create a Key for each Tenant, -select "No Global Issuer Selected" and set all the issuer values here -to create a Tenant key. +to each Client ID, skip a reusable issuer in Tsugi and create a key for each client id. +Leave the LTI 1.3 registration unset and set all the issuer values on that key. The Deployment ID is provided when you place Tsugi into a Blackboard instance using the Client ID. For Blackboard, the following are the typical values for the Tsugi items: diff --git a/lib/src/Controllers/templates/Admin/key/canvas-detail.php b/lib/src/Controllers/templates/Admin/key/canvas-detail.php index e12ccda612..06924c2149 100644 --- a/lib/src/Controllers/templates/Admin/key/canvas-detail.php +++ b/lib/src/Controllers/templates/Admin/key/canvas-detail.php @@ -1,10 +1,10 @@
-To use LTI 1.3 in Canvas, first create a Tsugi Tenant using a temporary +To use LTI 1.3 in Canvas, first create a Tsugi key using a temporary Client ID such as temporary-42-oertufgh. Make sure it is random enough to be unique across issuers as Tsugi prohibits duplicate (issuer, client_id) records system wide. -Save the Tenant in Tsugi and use the +Save the key in Tsugi and use the LTI values like JWKs URL shown by Tsugi to create a Developer Key in Canvas.
@@ -12,8 +12,8 @@When the Developer Key is created, Canvas will assign a real Client ID (for example -38288000000000436). Edit the Tsugi Tenant and replace the -temporary Client ID with the value assigned by Canvas and save the Tenant. +38288000000000436). Edit the Tsugi key and replace the +temporary Client ID with the value assigned by Canvas and save the key.
@@ -26,7 +26,7 @@
The Deployment ID is optional in Tsugi and may be left blank to accept launches from any Canvas deployment using that issuer/client pair. -If you enter a Deployment ID on the Tenant, launches will be restricted +If you enter a Deployment ID on the key, launches will be restricted to that specific Canvas deployment (i.e. it might just be one course).
To use LTI 1.1 in Canvas, create your key with a title, key, and secret and come back here to view the XML-based Canvas auto-installation URL. Auto-installation of LTI 1.1 tools -in Canvas is on a per-Tenant basis. +in Canvas is on a per-key basis. diff --git a/lib/src/Controllers/templates/Admin/key/client-id-check.php b/lib/src/Controllers/templates/Admin/key/client-id-check.php index eed0c204bd..b63ce07c4c 100644 --- a/lib/src/Controllers/templates/Admin/key/client-id-check.php +++ b/lib/src/Controllers/templates/Admin/key/client-id-check.php @@ -41,7 +41,7 @@ echo \Tsugi\Services\Admin\AdminService::issuerClientDuplicateNotice(); ?>- Tenant Keys + Keys Client Id Check Admin
diff --git a/lib/src/Controllers/templates/Admin/key/index.php b/lib/src/Controllers/templates/Admin/key/index.php index 77ea72a933..82e64a792a 100644 --- a/lib/src/Controllers/templates/Admin/key/index.php +++ b/lib/src/Controllers/templates/Admin/key/index.php @@ -16,12 +16,15 @@ $rows = $PDOX->queryDie($patch_sql); $query_parms = array(); -$searchfields = array("K.key_id", "key_title", "key_key", "deploy_key", "K.login_at", "K.updated_at", "K.user_id", "K.lms_client"); +$searchfields = array("K.key_id", "key_title", "key_key", "deploy_key", "K.login_at", "K.updated_at", "K.user_id", "K.lms_client", "R.issuer", "R.client_id"); $sql = "SELECT K.key_id AS key_id, key_title, key_key, secret, lms_issuer, K.lms_client AS lms_client, lms_oidc_auth, lms_keyset_url, lms_token_url, deploy_key, K.login_at AS login_at, K.updated_at as updated_at, - K.user_id AS user_id + K.user_id AS user_id, K.lti_registration_id AS lti_registration_id, + R.issuer AS registration_issuer, R.client_id AS registration_client FROM {$CFG->dbprefix}lti_key AS K + LEFT JOIN {$CFG->dbprefix}lti_registration AS R + ON R.lti_registration_id = K.lti_registration_id "; $newsql = Table::pagedQuery($sql, $query_parms, $searchfields); @@ -34,8 +37,13 @@ $newrow['key'] = $row['key_key']; if ( !empty($row['key_title']) ) $newrow['key'] = $row['key_title']; $newrow['key_type'] = \Tsugi\Services\Admin\AdminService::keyTypeLabel($row); + $newrow['_html_key_type'] = \Tsugi\Services\Admin\AdminService::keyTypeHtml($row); $issuer_key = $row['lms_issuer']; $client_id = $row['lms_client']; + if ( empty($issuer_key) && empty($client_id) && ! empty($row['registration_issuer']) ) { + $issuer_key = $row['registration_issuer']; + $client_id = $row['registration_client']; + } $issuer_display = ''; if ( !empty($issuer_key) || !empty($client_id) ) { if ( !empty($issuer_key) ) { @@ -64,9 +72,10 @@ $OUTPUT->flashMessages(); echo \Tsugi\Services\Admin\AdminService::clientIdCheckNotices(); ?> -- Tenant Keys + Registrations + Keys providekeys ) { ?> Key Requests @@ -75,11 +84,12 @@
-You have no Tenant keys for this system. +You have no keys for this system.
"key-add" + "Insert Registration" => "registration-add", + "Insert Key" => "key-add" ); Table::pagedTable($newrows, $searchfields, false, "key-detail", false, $extra_buttons); // echo("\n");print_r($newrows);echo("\n");
diff --git a/lib/src/Controllers/templates/Admin/key/key-add.php b/lib/src/Controllers/templates/Admin/key/key-add.php
index 2453f21d6a..9332426f7c 100644
--- a/lib/src/Controllers/templates/Admin/key/key-add.php
+++ b/lib/src/Controllers/templates/Admin/key/key-add.php
@@ -17,13 +17,12 @@
$from_location = LTIX::curPageUrlFolder();
$tablename = "{$CFG->dbprefix}lti_key";
-$fields = array('key_title', 'plus', 'key_key', 'key_sha256', 'secret',
+$fields = array('key_title', 'plus', 'user_id', 'key_key', 'key_sha256', 'secret',
'lms_issuer', 'lms_issuer_sha256',
'lms_client',
'deploy_key', 'deploy_sha256',
'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience',
'created_at', 'updated_at',
- 'user_id',
);
$titles = array(
@@ -65,6 +64,10 @@
}
if ( isset($_POST['doSave']) && count($_POST) > 0 ) {
+ if ( ! \Tsugi\Services\Admin\AdminService::applyPostedRegistrationToKey() ) {
+ header("Location: key-add");
+ return;
+ }
$lms_issuer = U::get($_POST, 'lms_issuer');
$lms_client = U::get($_POST, 'lms_client');
$identity_message = LTI::ascii255First(array(
@@ -99,7 +102,9 @@
if ( isset($_POST['doSave']) ) {
$binaryHex['guid'] = \Tsugi\Core\Guid::uuid7();
}
-$retval = CrudForm::handleInsert($tablename, $fields, $binaryHex);
+$save_fields = $fields;
+$save_fields[] = 'lti_registration_id';
+$retval = CrudForm::handleInsert($tablename, $save_fields, $binaryHex);
if ( $retval == CrudForm::CRUD_SUCCESS || $retval == CrudForm::CRUD_FAIL ) {
header("Location: $from_location");
return;
@@ -111,7 +116,7 @@
$OUTPUT->flashMessages();
?>
-No keys point at this registration.
+ ++Issuer is required. Client id and the other fields can wait until the platform assigns them. +
+ diff --git a/lib/src/Controllers/templates/Admin/key/registration-from-key.php b/lib/src/Controllers/templates/Admin/key/registration-from-key.php new file mode 100644 index 0000000000..4a0530750e --- /dev/null +++ b/lib/src/Controllers/templates/Admin/key/registration-from-key.php @@ -0,0 +1,14 @@ + false, 'error' => 'Missing or invalid CSRF token.')); + return; +} + +$create = isset($_POST['doCreate']) && (string) $_POST['doCreate'] === '1'; +echo json_encode(AdminService::registrationFromKeyRequest($_POST, $create)); diff --git a/lib/src/Controllers/templates/Admin/key/registrations.php b/lib/src/Controllers/templates/Admin/key/registrations.php new file mode 100644 index 0000000000..0676dabba3 --- /dev/null +++ b/lib/src/Controllers/templates/Admin/key/registrations.php @@ -0,0 +1,55 @@ +dbprefix}lti_registration +"; + +$newsql = Table::pagedQuery($sql, $query_parms, $searchfields); +$rows = $PDOX->allRowsDie($newsql, $query_parms); +$newrows = array(); +foreach ( $rows as $row ) { + $newrow = array(); + $newrow['lti_registration_id'] = $row['lti_registration_id']; + $newrow['title'] = $row['title']; + $newrow['issuer'] = $row['issuer']; + $newrow['client'] = $row['client_id']; + $newrow['_header_client'] = 'Client ID'; + $newrow['updated_at'] = $row['updated_at']; + $newrows[] = $newrow; +} + +$OUTPUT->header(); +$OUTPUT->bodyStart(); +$OUTPUT->topNav(); +$OUTPUT->flashMessages(); +?> ++ Registrations + Keys + Admin +
++A registration needs an issuer. Client id and the platform URLs can wait until the platform assigns them. +A key can point at one and leave its own LTI 1.3 platform fields empty. +
+ +You have no registrations yet.
+ "registration-add" +); +Table::pagedTable($newrows, $searchfields, false, "registration-detail", false, $extra_buttons); + +$OUTPUT->footer(); diff --git a/lib/src/Controllers/templates/Admin/key/requests.php b/lib/src/Controllers/templates/Admin/key/requests.php index 5385f06061..c6f43c1ce3 100644 --- a/lib/src/Controllers/templates/Admin/key/requests.php +++ b/lib/src/Controllers/templates/Admin/key/requests.php @@ -51,7 +51,7 @@ ?>
- Tenant Keys
+ Keys
providekeys ) { ?>
Key Requests
diff --git a/lib/src/Core/LTIX.php b/lib/src/Core/LTIX.php
index 0a03a4ffea..4d5300715a 100644
--- a/lib/src/Core/LTIX.php
+++ b/lib/src/Core/LTIX.php
@@ -750,7 +750,7 @@ public static function getPlatformPublicKey($key_id, $request_kid, $our_kid, $pu
if ( $decoded && isset($decoded->keys) && is_array($decoded->keys) ) {
$PDOX->queryDie("UPDATE {$CFG->dbprefix}lti_key
SET lms_cache_keyset=:KS, updated_at=NOW() WHERE key_id = :ID",
- array(':ID' => $key_id, ':KS' => $our_keyset) );
+ array(':ID' => $key_id, ':KS' => self::keysetCacheForUrl($our_keyset_url, $our_keyset)) );
error_log("Updated lms_cache_keyset $key_id from $our_keyset_url\n");
} else {
self::abort_with_error_log("Failure loading keyset from ".$our_keyset_url,
@@ -1151,6 +1151,187 @@ public static function displayNameFromClaim($claim) {
return $retval;
}
+ /**
+ * Columns and LEFT JOIN that load a registration beside its key.
+ * Both strings are empty when lti_registration does not exist.
+ * $keyAlias is the lti_key alias already used in the query.
+ *
+ * @param string $prefix
+ * @param string $keyAlias
+ * @return array{select: string, join: string}
+ */
+ public static function inboundRegistrationSql($prefix, $keyAlias) {
+ // TODO: Remove this lti_registration existence gate by February 2027.
+ if ( ! self::ltiRegistrationTableExists($prefix) ) {
+ return array('select' => '', 'join' => '');
+ }
+ return array(
+ 'select' => 'reg.issuer AS reg_issuer, reg.client_id AS reg_client_id, '
+ .'reg.oidc_auth_url AS reg_oidc_auth_url, reg.keyset_url AS reg_keyset_url, '
+ .'reg.token_url AS reg_token_url, reg.token_audience AS reg_token_audience',
+ 'join' => "LEFT JOIN {$prefix}lti_registration AS reg ON reg.lti_registration_id = {$keyAlias}.lti_registration_id",
+ );
+ }
+
+ /**
+ * True when this install has the inbound registration table.
+ * A missing table means the upgrade has not run, so launch keeps using lti_key.
+ */
+ public static function ltiRegistrationTableExists($prefix) {
+ // TODO: Remove this lti_registration existence gate by February 2027.
+ static $seen = array();
+ if ( array_key_exists($prefix, $seen) ) return $seen[$prefix];
+ $PDOX = self::getConnection();
+ $seen[$prefix] = $PDOX->metadata($prefix.'lti_registration') !== false;
+ return $seen[$prefix];
+ }
+
+ /**
+ * Use the registration's platform fields, or leave the key's fields untouched.
+ *
+ * Both sets are already on $row. This is not a per-field coalesce.
+ * The registration wins only when issuer, client id, OIDC URL, keyset URL,
+ * and token URL are all set. Audience is copied with that set and may be null.
+ * Deployment id stays on the key. The cached key is kept when the key's
+ * own keyset URL matches, or when the cache was fetched from the
+ * registration URL. Any other cache is dropped from this row so the next
+ * fetch uses the registration URL. The key's stored platform fields stay
+ * in the database.
+ *
+ * @param array '.$text.implode(', ', $links).'. The issuer, client id, and platform URLs below stay on this key unless you empty them. After you have associated this key with a registration, you can empty the issuer, client id, and platform URLs on this key. Checked, these fields are cleared when you save. Unchecked, they stay on the key. LTI 1.3 registration None LTI 1.3 registration Missing registration ".$selectedId." LTI 1.3 registration\n");var_dump($row);die(); // Debug
+ if ( is_array($row) ) $row = self::applyInboundRegistration($row);
if ( $LTI13 && is_array($row) ) {
$row['issuer_key'] = $row['lms_issuer'];
diff --git a/lib/src/Services/Admin/AdminService.php b/lib/src/Services/Admin/AdminService.php
index 9e39a4d202..f800ad3684 100644
--- a/lib/src/Services/Admin/AdminService.php
+++ b/lib/src/Services/Admin/AdminService.php
@@ -1306,9 +1306,9 @@ public static function validate_issuer_client_unique($lms_issuer, $lms_client, $
if ( $row ) {
$label = U::isNotEmpty($row['key_title']) ? $row['key_title'] : ('key_id '.$row['key_id']);
if ( $deploy === null ) {
- U::flashError('A tenant/key with this LTI 1.3 issuer, client id, and a blank deployment id already exists ('.$label.')');
+ U::flashError('A key with this LTI 1.3 issuer, client id, and a blank deployment id already exists ('.$label.')');
} else {
- U::flashError('A tenant/key with this LTI 1.3 issuer, client id, and deployment id already exists ('.$label.')');
+ U::flashError('A key with this LTI 1.3 issuer, client id, and deployment id already exists ('.$label.')');
}
return false;
}
@@ -1346,12 +1346,537 @@ public static function keyTypeLabel(array $row) {
}
}
+ $registration_id = (int) U::get($row, 'lti_registration_id');
+ if ( $registration_id > 0 ) {
+ $parts[] = 'Registration';
+ }
+
if ( $draft || count($parts) < 1 ) {
$parts[] = 'Draft';
}
return implode(' / ', $parts);
}
+ /**
+ * keyTypeLabel with the Registration word linked to that registration.
+ *
+ * @param array
\n";
+ return $html;
+ }
+
+ /**
+ * Select or read-only link for the key form. Does not show unused columns.
+ *
+ * @param int $selectedId
+ * @param bool $edit
+ */
+ public static function inboundRegistrationControl($selectedId, $edit) {
+ $selectedId = (int) $selectedId;
+ if ( ! $edit ) {
+ if ( $selectedId < 1 ) {
+ return "
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
+ if ( $table === 'lti_key' && $column === 'lti_registration_id' && ! $q->success ) {
+ die("Unable to add lti_key.lti_registration_id: ".$q->errorImplode."
\n");
+ }
}
// Generally wait a while to drop the fields - there is no rush
@@ -1817,12 +1923,16 @@
// The unique guid key is added later in this upgrade. This pass must not
// drop it when the table already has it.
$keep_guid_index = $CFG->dbprefix."lti_key_const_guid";
+ // InnoDB names the registration foreign key's supporting index after the
+ // constraint. Dropping it fails on every upgrade and looks like a problem.
+ $keep_registration_fk = $CFG->dbprefix."lti_key_ibfk_1";
foreach($indexes as $index) {
if ( strcasecmp($index, "PRIMARY") == 0 ) continue;
if ( strcasecmp($index, "ibfk") == 0 ) continue;
// lti_key_const_2 backs issuer_id until lti_issuer phase 3 (2026-10-01 UTC)
if ( $keep_issuer_index && $index === $CFG->dbprefix."lti_key_const_2" ) continue;
if ( $index === $keep_guid_index ) continue;
+ if ( $index === $keep_registration_fk ) continue;
$command = isset($needed_indexes[$index]) ? $needed_indexes[$index] : null;
if ( is_string($command) ) continue;
$sql = "DROP INDEX ".$index." ON ".$CFG->dbprefix."lti_key";
@@ -2444,6 +2554,27 @@
return is_array($row);
};
+ // ON DELETE SET NULL: removing a registration detaches its keys.
+ $key_table = "{$p}lti_key";
+ $inbound_table = "{$p}lti_registration";
+ $key_registration_fk = "{$p}lti_key_ibfk_1";
+ if ( $PDOX->metadata($key_table) !== false
+ && $PDOX->metadata($inbound_table) !== false ) {
+ if ( ! $PDOX->columnExists('lti_registration_id', $key_table) ) {
+ die("lti_registration exists but lti_key.lti_registration_id is missing. The foreign key was not added.
\n");
+ }
+ if ( ! $constraint_exists($key_table, $key_registration_fk) ) {
+ $sql = "ALTER TABLE {$key_table} ADD CONSTRAINT `{$key_registration_fk}`
+ FOREIGN KEY (`lti_registration_id`)
+ REFERENCES `{$inbound_table}` (`lti_registration_id`)
+ ON DELETE SET NULL ON UPDATE CASCADE";
+ echo("Upgrading: ".$sql."
\n");
+ error_log("Upgrading: ".$sql);
+ $q = $PDOX->queryReturnError($sql);
+ if ( ! $q->success ) die("Unable to add {$key_registration_fk}: ".$q->errorImplode."
\n");
+ }
+ }
+
if ( $PDOX->metadata($org_table) !== false && $PDOX->columnExists('org_id', $context_table) ) {
$org_index = "{$p}lti_context_indx_1";
if ( ! $PDOX->indexExists($org_index, $context_table) ) {
@@ -2863,14 +2994,13 @@
// One column at a time. Count values longer than 255 characters and values
// with a character outside ASCII. Alter only when both counts are zero and
// the column is not already varchar(255) ascii_bin. A column already in
- // that form is reported and left alone. A dirty column is reported and
+ // that form is left alone with no message. A dirty column is reported and
// left alone so a later upgrade can alter it after the data is cleaned.
$identity_note = function($message) {
error_log($message);
echo(htmlentities($message)."
\n");
};
$identity_ascii_columns = \Tsugi\Services\Admin\AdminService::identityAsciiColumns();
- $identity_note('Checking identity columns for varchar(255) character set ascii collation ascii_bin.');
$identity_described = array();
foreach ( $identity_ascii_columns as $identity_column ) {
$identity_table = $identity_column[0];
@@ -2955,7 +3085,6 @@
continue;
}
if ( $identity_already ) {
- $identity_note($identity_summary.' Already varchar(255) character set ascii collation ascii_bin.');
continue;
}
$identity_nullable = strtoupper((string) \Tsugi\Util\U::getIgnoreCase($identity_field_meta, 'Null')) === 'YES';
diff --git a/lib/src/Services/Plus/GradeSync.php b/lib/src/Services/Plus/GradeSync.php
index 66df975680..49f2fa9232 100644
--- a/lib/src/Services/Plus/GradeSync.php
+++ b/lib/src/Services/Plus/GradeSync.php
@@ -750,23 +750,28 @@ private static function loadResult($resultId) {
$PDOX = LTIX::getConnection();
global $CFG;
$p = $CFG->dbprefix;
- $row = $PDOX->rowDie(
- "SELECT R.result_id, R.link_id, R.user_id, R.result_maximum AS result_maximum,
+ $registration_sql = LTIX::inboundRegistrationSql($p, 'K');
+ // TODO: Remove this lti_registration existence gate by February 2027.
+ $sql = "SELECT R.result_id, R.link_id, R.user_id, R.result_maximum AS result_maximum,
U.subject_key AS subject_key,
L.title, L.score_maximum, L.lti13_lineitem, L.grades_released, L.end_datetime,
C.context_id, C.plus_course, C.plus_launch_link_id, C.lti13_lineitems,
C.lti13_deployment_id, C.timezone,
- K.lms_token_url, K.lms_token_audience, K.lms_client
+ K.key_id, K.lms_token_url, K.lms_token_audience, K.lms_client";
+ if ( $registration_sql['select'] !== '' ) {
+ $sql .= ', '.$registration_sql['select'];
+ }
+ $sql .= "
FROM {$p}lti_result AS R
JOIN {$p}lti_link AS L ON L.link_id = R.link_id
JOIN {$p}lti_user AS U ON U.user_id = R.user_id
JOIN {$p}lti_context AS C ON C.context_id = L.context_id
JOIN {$p}lti_key AS K ON K.key_id = C.key_id
+ ".$registration_sql['join']."
WHERE R.result_id = :RID
- LIMIT 1",
- array(':RID' => $resultId)
- );
- return is_array($row) ? $row : null;
+ LIMIT 1";
+ $row = $PDOX->rowDie($sql, array(':RID' => $resultId));
+ return is_array($row) ? LTIX::applyInboundRegistration($row) : null;
}
/**
@@ -781,19 +786,24 @@ private static function loadLink($linkId) {
$PDOX = LTIX::getConnection();
global $CFG;
$p = $CFG->dbprefix;
- $row = $PDOX->rowDie(
- "SELECT L.link_id, L.title, L.score_maximum, L.lti13_lineitem, L.grades_released, L.end_datetime,
+ $registration_sql = LTIX::inboundRegistrationSql($p, 'K');
+ // TODO: Remove this lti_registration existence gate by February 2027.
+ $sql = "SELECT L.link_id, L.title, L.score_maximum, L.lti13_lineitem, L.grades_released, L.end_datetime,
C.context_id, C.plus_course, C.plus_launch_link_id, C.lti13_lineitems,
C.lti13_deployment_id, C.timezone,
- K.lms_token_url, K.lms_token_audience, K.lms_client
+ K.key_id, K.lms_token_url, K.lms_token_audience, K.lms_client";
+ if ( $registration_sql['select'] !== '' ) {
+ $sql .= ', '.$registration_sql['select'];
+ }
+ $sql .= "
FROM {$p}lti_link AS L
JOIN {$p}lti_context AS C ON C.context_id = L.context_id
JOIN {$p}lti_key AS K ON K.key_id = C.key_id
+ ".$registration_sql['join']."
WHERE L.link_id = :LID
- LIMIT 1",
- array(':LID' => $linkId)
- );
- return is_array($row) ? $row : null;
+ LIMIT 1";
+ $row = $PDOX->rowDie($sql, array(':LID' => $linkId));
+ return is_array($row) ? LTIX::applyInboundRegistration($row) : null;
}
/**
diff --git a/lib/src/Services/Plus/RosterSync.php b/lib/src/Services/Plus/RosterSync.php
index 4b6c1dc003..93e37618c1 100644
--- a/lib/src/Services/Plus/RosterSync.php
+++ b/lib/src/Services/Plus/RosterSync.php
@@ -900,18 +900,23 @@ private static function contextRow($contextId) {
global $CFG;
$PDOX = LTIX::getConnection();
$p = $CFG->dbprefix;
- $row = $PDOX->rowDie(
- "SELECT c.context_id, c.key_id, c.plus_course, c.plus_launch_link_id,
+ $registration_sql = LTIX::inboundRegistrationSql($p, 'k');
+ // TODO: Remove this lti_registration existence gate by February 2027.
+ $sql = "SELECT c.context_id, c.key_id, c.plus_course, c.plus_launch_link_id,
c.lti13_membership_url, c.lti13_deployment_id, c.nrps_at,
TIMESTAMPDIFF(SECOND, c.nrps_at, NOW()) AS nrps_age,
- k.lms_client, k.lms_token_url, k.lms_token_audience
+ k.lms_client, k.lms_token_url, k.lms_token_audience";
+ if ( $registration_sql['select'] !== '' ) {
+ $sql .= ', '.$registration_sql['select'];
+ }
+ $sql .= "
FROM {$p}lti_context AS c
JOIN {$p}lti_key AS k ON k.key_id = c.key_id
+ ".$registration_sql['join']."
WHERE c.context_id = :CID
- AND (c.deleted IS NULL OR c.deleted = 0)",
- array(':CID' => (int) $contextId)
- );
- return is_array($row) ? $row : null;
+ AND (c.deleted IS NULL OR c.deleted = 0)";
+ $row = $PDOX->rowDie($sql, array(':CID' => (int) $contextId));
+ return is_array($row) ? LTIX::applyInboundRegistration($row) : null;
}
/**
diff --git a/lib/src/Services/Settings/DynamicRegistration.php b/lib/src/Services/Settings/DynamicRegistration.php
index 29d568f8b5..5a3d49773e 100644
--- a/lib/src/Services/Settings/DynamicRegistration.php
+++ b/lib/src/Services/Settings/DynamicRegistration.php
@@ -440,6 +440,10 @@ public static function run($user_id, $tsugi_key, $unlock_code, $openid_configura
$issuer_sha256 = hash('sha256', trim($issuer));
+ // TODO: Dynamic registration still writes the new client id onto the key only.
+ // A complete linked registration keeps its own client id, and launch uses that.
+ // Handle the linked registration when dynamic registration is updated.
+
$sql = "UPDATE {$CFG->dbprefix}lti_key SET
lms_issuer = :lms_issuer,
lms_issuer_sha256 = :lms_issuer_sha256,
@@ -468,6 +472,7 @@ public static function run($user_id, $tsugi_key, $unlock_code, $openid_configura
echo("Unable to store LMS platform configuration on the key\n");
return '';
}
+ LTIX::clearKeysetCache($tsugi_key);
error_log("Stored issuer $issuer / $client_id in lti_key table");
diff --git a/lib/src/UI/CrudForm.php b/lib/src/UI/CrudForm.php
index 60b565e9f0..7d85c229ed 100644
--- a/lib/src/UI/CrudForm.php
+++ b/lib/src/UI/CrudForm.php
@@ -57,9 +57,10 @@ class CrudForm {
* @param $titles An array of fields->titles
* @param $fields_defaults An array of fields>default values
*/
- public static function insertForm($fields, $from_location, $titles=false, $fields_defaults=false, $checkboxes=false) {
+ public static function insertForm($fields, $from_location, $titles=false, $fields_defaults=false, $checkboxes=false, $extraHtml='') {
echo(''."\n");
return true;
@@ -496,6 +501,18 @@ private static function echoSensitiveInput($field, $preserve_on_empty=false, $va
echo(">\n");
}
+ /**
+ * A string is printed once at the top. An array is printed after the named field.
+ *
+ * @param mixed $extraHtml
+ * @param string $field
+ */
+ private static function echoHtmlAfterField($extraHtml, $field) {
+ if ( ! is_array($extraHtml) ) return;
+ $html = U::get($extraHtml, $field);
+ if ( is_string($html) && $html !== '' ) echo($html);
+ }
+
/**
* Maps a field name to a presentable title.
*
diff --git a/lib/tests/Core/InboundRegistrationTest.php b/lib/tests/Core/InboundRegistrationTest.php
new file mode 100644
index 0000000000..481e79983a
--- /dev/null
+++ b/lib/tests/Core/InboundRegistrationTest.php
@@ -0,0 +1,425 @@
+ 3,
+ 'deploy_key' => 'deploy-kept',
+ 'lms_cache_kid' => 'key-kid',
+ 'lms_issuer' => 'https://key.example',
+ 'lms_client' => 'key-client',
+ 'lms_oidc_auth' => 'https://key.example/oidc',
+ 'lms_keyset_url' => 'https://reg.example/keyset',
+ 'lms_token_url' => 'https://key.example/token',
+ 'lms_token_audience' => 'https://key.example/audience',
+ 'reg_issuer' => 'https://reg.example',
+ 'reg_client_id' => 'reg-client',
+ 'reg_oidc_auth_url' => 'https://reg.example/oidc',
+ 'reg_keyset_url' => 'https://reg.example/keyset',
+ 'reg_token_url' => 'https://reg.example/token',
+ 'reg_token_audience' => null,
+ ));
+
+ $this->assertSame('https://reg.example', $row['lms_issuer']);
+ $this->assertSame('reg-client', $row['lms_client']);
+ $this->assertSame('https://reg.example/oidc', $row['lms_oidc_auth']);
+ $this->assertSame('https://reg.example/keyset', $row['lms_keyset_url']);
+ $this->assertSame('https://reg.example/token', $row['lms_token_url']);
+ $this->assertNull($row['lms_token_audience']);
+ $this->assertSame('deploy-kept', $row['deploy_key']);
+ $this->assertSame('key-kid', $row['lms_cache_kid']);
+ $this->assertArrayNotHasKey('reg_issuer', $row);
+ $this->assertArrayNotHasKey('reg_token_url', $row);
+ $this->assertArrayNotHasKey('reg_token_audience', $row);
+ }
+
+ public function testDifferentKeysetUrlDropsTheCachedKid() {
+ $row = LTIX::applyInboundRegistration(array(
+ 'deploy_key' => 'deploy-kept',
+ 'lms_cache_keyset' => '{"keys":[]}',
+ 'lms_cache_pubkey' => 'cached-key',
+ 'lms_cache_kid' => 'key-kid',
+ 'lms_issuer' => 'https://key.example',
+ 'lms_client' => 'key-client',
+ 'lms_oidc_auth' => 'https://key.example/oidc',
+ 'lms_keyset_url' => 'https://key.example/keyset',
+ 'lms_token_url' => 'https://key.example/token',
+ 'lms_token_audience' => 'https://key.example/audience',
+ 'reg_issuer' => 'https://reg.example',
+ 'reg_client_id' => 'reg-client',
+ 'reg_oidc_auth_url' => 'https://reg.example/oidc',
+ 'reg_keyset_url' => 'https://reg.example/keyset',
+ 'reg_token_url' => 'https://reg.example/token',
+ 'reg_token_audience' => null,
+ ));
+
+ $this->assertNull($row['lms_cache_keyset']);
+ $this->assertNull($row['lms_cache_pubkey']);
+ $this->assertNull($row['lms_cache_kid']);
+ $this->assertSame('https://reg.example/keyset', $row['lms_keyset_url']);
+ $this->assertSame('deploy-kept', $row['deploy_key']);
+ }
+
+ public function testCacheFetchedFromTheRegistrationUrlIsKept() {
+ $cached = '{"keys":[],"tsugi_keyset_url":"https://reg.example/keyset"}';
+ $row = LTIX::applyInboundRegistration(array(
+ 'key_id' => 3,
+ 'deploy_key' => 'deploy-kept',
+ 'lms_cache_keyset' => $cached,
+ 'lms_cache_pubkey' => 'cached-key',
+ 'lms_cache_kid' => 'key-kid',
+ 'lms_issuer' => 'https://key.example',
+ 'lms_client' => 'key-client',
+ 'lms_oidc_auth' => 'https://key.example/oidc',
+ 'lms_keyset_url' => 'https://key.example/keyset',
+ 'lms_token_url' => 'https://key.example/token',
+ 'lms_token_audience' => 'https://key.example/audience',
+ 'reg_issuer' => 'https://reg.example',
+ 'reg_client_id' => 'reg-client',
+ 'reg_oidc_auth_url' => 'https://reg.example/oidc',
+ 'reg_keyset_url' => 'https://reg.example/keyset',
+ 'reg_token_url' => 'https://reg.example/token',
+ 'reg_token_audience' => null,
+ ));
+
+ $this->assertSame($cached, $row['lms_cache_keyset']);
+ $this->assertSame('cached-key', $row['lms_cache_pubkey']);
+ $this->assertSame('key-kid', $row['lms_cache_kid']);
+ $this->assertSame('https://reg.example', $row['lms_issuer']);
+ $this->assertSame('https://reg.example/keyset', $row['lms_keyset_url']);
+ $this->assertSame('deploy-kept', $row['deploy_key']);
+ }
+
+ public function testCacheFetchedFromAnotherUrlIsDropped() {
+ $row = LTIX::applyInboundRegistration(array(
+ 'deploy_key' => 'deploy-kept',
+ 'lms_cache_keyset' => '{"keys":[],"tsugi_keyset_url":"https://other.example/keyset"}',
+ 'lms_cache_pubkey' => 'cached-key',
+ 'lms_cache_kid' => 'key-kid',
+ 'lms_keyset_url' => 'https://key.example/keyset',
+ 'lms_issuer' => 'https://key.example',
+ 'lms_client' => 'key-client',
+ 'lms_oidc_auth' => 'https://key.example/oidc',
+ 'lms_token_url' => 'https://key.example/token',
+ 'reg_issuer' => 'https://reg.example',
+ 'reg_client_id' => 'reg-client',
+ 'reg_oidc_auth_url' => 'https://reg.example/oidc',
+ 'reg_keyset_url' => 'https://reg.example/keyset',
+ 'reg_token_url' => 'https://reg.example/token',
+ ));
+
+ $this->assertNull($row['lms_cache_keyset']);
+ $this->assertNull($row['lms_cache_pubkey']);
+ $this->assertNull($row['lms_cache_kid']);
+ $this->assertSame('https://reg.example/keyset', $row['lms_keyset_url']);
+ }
+
+ public function testIncompleteRegistrationLeavesTheKey() {
+ $row = LTIX::applyInboundRegistration(array(
+ 'lms_issuer' => 'https://key.example',
+ 'lms_client' => 'key-client',
+ 'lms_oidc_auth' => 'https://key.example/oidc',
+ 'lms_keyset_url' => 'https://key.example/keyset',
+ 'lms_token_url' => 'https://key.example/token',
+ 'lms_token_audience' => 'https://key.example/audience',
+ 'reg_issuer' => 'https://reg.example',
+ 'reg_client_id' => 'reg-client',
+ 'reg_oidc_auth_url' => 'https://reg.example/oidc',
+ 'reg_keyset_url' => 'https://reg.example/keyset',
+ 'reg_token_url' => '',
+ 'reg_token_audience' => 'https://reg.example/audience',
+ ));
+
+ $this->assertSame('https://key.example', $row['lms_issuer']);
+ $this->assertSame('key-client', $row['lms_client']);
+ $this->assertSame('https://key.example/oidc', $row['lms_oidc_auth']);
+ $this->assertSame('https://key.example/keyset', $row['lms_keyset_url']);
+ $this->assertSame('https://key.example/token', $row['lms_token_url']);
+ $this->assertSame('https://key.example/audience', $row['lms_token_audience']);
+ $this->assertArrayNotHasKey('reg_issuer', $row);
+ $this->assertArrayNotHasKey('reg_token_audience', $row);
+ }
+
+ public function testLoadAllDataUsesTheRegistrationWhenTheKeyFieldsDiffer() {
+ $pdo = $this->beginFixtureTransaction();
+ if ( $pdo === null ) {
+ $this->markTestSkipped('Database not available for registration fixtures.');
+ }
+ $p = $this->prefix();
+ if ( ! LTIX::ltiRegistrationTableExists($p) || ! $pdo->columnExists('lti_registration_id', $p.'lti_key') ) {
+ $pdo->rollBack();
+ $this->markTestSkipped('lti_registration is not installed.');
+ }
+ try {
+ $stamp = 'reg'.bin2hex(random_bytes(6));
+ $issuer = 'http://'.$stamp.'.example';
+ $client = $stamp.'-client';
+ $pdo->queryDie(
+ "INSERT INTO {$p}lti_registration
+ (issuer, client_id, oidc_auth_url, keyset_url, token_url, token_audience, created_at)
+ VALUES (:ISS, :CLIENT, :OIDC, :KEYSET, :TOKEN, NULL, NOW())",
+ array(
+ ':ISS' => $issuer,
+ ':CLIENT' => $client,
+ ':OIDC' => 'http://'.$stamp.'.example/oidc',
+ ':KEYSET' => 'http://'.$stamp.'.example/keyset',
+ ':TOKEN' => 'http://'.$stamp.'.example/token',
+ )
+ );
+ $registrationId = (int) $pdo->lastInsertId();
+ $keyIssuer = 'http://key-'.$stamp.'.example';
+ $pdo->queryDie(
+ "INSERT INTO {$p}lti_key
+ (key_key, key_sha256, deploy_key, lms_issuer, lms_issuer_sha256, lms_client,
+ lms_oidc_auth, lms_keyset_url, lms_token_url, lms_token_audience, lms_cache_kid,
+ lti_registration_id, created_at, updated_at)
+ VALUES (:K, :SHA, :DEP, :ISS, :ISHA, :CLIENT, :OIDC, :KEYSET, :TOKEN, :AUD, :KID, :RID, NOW(), NOW())",
+ array(
+ ':K' => $stamp,
+ ':SHA' => hash('sha256', $stamp),
+ ':DEP' => 'deploy-kept',
+ ':ISS' => $keyIssuer,
+ ':ISHA' => hash('sha256', $keyIssuer),
+ ':CLIENT' => $stamp.'-key-client',
+ ':OIDC' => 'http://key.example/oidc',
+ ':KEYSET' => 'http://key.example/keyset',
+ ':TOKEN' => 'http://key.example/token',
+ ':AUD' => 'http://key.example/audience',
+ ':KID' => 'key-kid',
+ ':RID' => $registrationId,
+ )
+ );
+ $keyId = (int) $pdo->lastInsertId();
+
+ $loaded = LTIX::loadAllData($p, false, array(
+ 'issuer_key' => $issuer,
+ 'issuer_sha256' => hash('sha256', $issuer),
+ 'issuer_client' => $client,
+ 'nonce' => 'nonce-'.$stamp,
+ 'context_id' => 'context-'.$stamp,
+ 'link_id' => 'link-'.$stamp,
+ 'user_id' => 'user-'.$stamp,
+ ));
+
+ $this->assertIsArray($loaded);
+ $this->assertSame($keyId, (int) $loaded['key_id']);
+ $this->assertSame($issuer, $loaded['lms_issuer']);
+ $this->assertSame($client, $loaded['lms_client']);
+ $this->assertSame('http://'.$stamp.'.example/oidc', $loaded['lms_oidc_auth']);
+ $this->assertSame('http://'.$stamp.'.example/keyset', $loaded['lms_keyset_url']);
+ $this->assertSame('http://'.$stamp.'.example/token', $loaded['lms_token_url']);
+ $this->assertNull($loaded['lms_token_audience']);
+ $this->assertSame($issuer, $loaded['issuer_key']);
+ $this->assertSame($client, $loaded['issuer_client']);
+ $this->assertSame('http://'.$stamp.'.example/token', $loaded['lti13_token_url']);
+ $this->assertSame('deploy-kept', $loaded['deploy_key']);
+ $this->assertNull($loaded['lms_cache_kid']);
+ $this->assertArrayNotHasKey('reg_token_url', $loaded);
+
+ $stored = $pdo->rowDie(
+ "SELECT lms_issuer, lms_client, lms_token_url, lms_token_audience
+ FROM {$p}lti_key WHERE key_id = :KID",
+ array(':KID' => $keyId)
+ );
+ $this->assertSame($keyIssuer, $stored['lms_issuer']);
+ $this->assertSame($stamp.'-key-client', $stored['lms_client']);
+ $this->assertSame('http://key.example/token', $stored['lms_token_url']);
+ $this->assertSame('http://key.example/audience', $stored['lms_token_audience']);
+ } finally {
+ $pdo->rollBack();
+ }
+ }
+
+ public function testLookupUsesRegistrationIdentityOnlyWhenTheRegistrationIsComplete() {
+ $pdo = $this->beginFixtureTransaction();
+ if ( $pdo === null ) {
+ $this->markTestSkipped('Database not available for registration fixtures.');
+ }
+ $p = $this->prefix();
+ if ( ! LTIX::ltiRegistrationTableExists($p) || ! $pdo->columnExists('lti_registration_id', $p.'lti_key') ) {
+ $pdo->rollBack();
+ $this->markTestSkipped('lti_registration is not installed.');
+ }
+ try {
+ $stamp = 'gap'.bin2hex(random_bytes(6));
+ $issuer = 'http://'.$stamp.'.example';
+ $client = $stamp.'-client';
+ $pdo->queryDie(
+ "INSERT INTO {$p}lti_registration
+ (issuer, client_id, oidc_auth_url, keyset_url, token_url, created_at)
+ VALUES (:ISS, :CLIENT, :OIDC, :KEYSET, NULL, NOW())",
+ array(
+ ':ISS' => $issuer,
+ ':CLIENT' => $client,
+ ':OIDC' => 'http://'.$stamp.'.example/oidc',
+ ':KEYSET' => 'http://'.$stamp.'.example/keyset',
+ )
+ );
+ $registrationId = (int) $pdo->lastInsertId();
+ $keyClient = $stamp.'-key-client';
+ $pdo->queryDie(
+ "INSERT INTO {$p}lti_key
+ (key_key, key_sha256, lms_issuer, lms_issuer_sha256, lms_client, lms_token_url,
+ lti_registration_id, created_at, updated_at)
+ VALUES (:K, :SHA, :ISS, :ISHA, :CLIENT, :TOKEN, :RID, NOW(), NOW())",
+ array(
+ ':K' => $stamp,
+ ':SHA' => hash('sha256', $stamp),
+ ':ISS' => 'http://key-'.$stamp.'.example',
+ ':ISHA' => hash('sha256', 'http://key-'.$stamp.'.example'),
+ ':CLIENT' => $keyClient,
+ ':TOKEN' => 'http://key.example/token',
+ ':RID' => $registrationId,
+ )
+ );
+ $incompleteKeyId = (int) $pdo->lastInsertId();
+ $byRegistration = LTIX::loadAllData($p, false, $this->launchPost($issuer, $client));
+ $this->assertTrue(! is_array($byRegistration) || (int) $byRegistration['key_id'] !== $incompleteKeyId);
+
+ $pdo->queryDie(
+ "UPDATE {$p}lti_registration
+ SET token_url = :TOKEN, updated_at = NOW()
+ WHERE lti_registration_id = :RID",
+ array(
+ ':TOKEN' => 'http://'.$stamp.'.example/token',
+ ':RID' => $registrationId,
+ )
+ );
+ $byOldKey = LTIX::loadAllData($p, false, $this->launchPost('http://key-'.$stamp.'.example', $keyClient));
+ $this->assertTrue(! is_array($byOldKey) || (int) $byOldKey['key_id'] !== $incompleteKeyId);
+
+ $byNewRegistration = LTIX::loadAllData($p, false, $this->launchPost($issuer, $client));
+ $this->assertIsArray($byNewRegistration);
+ $this->assertSame($incompleteKeyId, (int) $byNewRegistration['key_id']);
+ $this->assertSame('http://'.$stamp.'.example/token', $byNewRegistration['lms_token_url']);
+ } finally {
+ $pdo->rollBack();
+ }
+ }
+
+ public function testASaveDropsTheKeysetCache() {
+ $pdo = $this->beginFixtureTransaction();
+ if ( $pdo === null ) {
+ $this->markTestSkipped('Database not available for registration fixtures.');
+ }
+ $p = $this->prefix();
+ if ( ! LTIX::ltiRegistrationTableExists($p) || ! $pdo->columnExists('lti_registration_id', $p.'lti_key') ) {
+ $pdo->rollBack();
+ $this->markTestSkipped('lti_registration is not installed.');
+ }
+ try {
+ $stamp = 'cache'.bin2hex(random_bytes(4));
+ $pdo->queryDie(
+ "INSERT INTO {$p}lti_registration
+ (issuer, client_id, oidc_auth_url, keyset_url, token_url, created_at, updated_at)
+ VALUES (:ISS, :CLIENT, :OIDC, :KEYSET, :TOKEN, NOW(), NOW())",
+ array(
+ ':ISS' => 'http://'.$stamp.'.example',
+ ':CLIENT' => $stamp.'-client',
+ ':OIDC' => 'http://'.$stamp.'.example/oidc',
+ ':KEYSET' => 'http://'.$stamp.'.example/keyset',
+ ':TOKEN' => 'http://'.$stamp.'.example/token',
+ )
+ );
+ $registrationId = (int) $pdo->lastInsertId();
+ $pdo->queryDie(
+ "INSERT INTO {$p}lti_registration
+ (issuer, client_id, created_at, updated_at)
+ VALUES (:ISS, :CLIENT, NOW(), NOW())",
+ array(
+ ':ISS' => 'http://other-'.$stamp.'.example',
+ ':CLIENT' => $stamp.'-other',
+ )
+ );
+ $otherRegistrationId = (int) $pdo->lastInsertId();
+ $linked = $this->insertCachedKey($pdo, $p, $stamp.'-linked', $registrationId);
+ $other = $this->insertCachedKey($pdo, $p, $stamp.'-other', $otherRegistrationId);
+ $plain = $this->insertCachedKey($pdo, $p, $stamp.'-plain', null);
+
+ LTIX::clearKeysetCache($plain);
+ $this->assertNull($this->cachedKid($pdo, $p, $plain));
+ $this->assertSame('kid-'.$stamp.'-linked', $this->cachedKid($pdo, $p, $linked));
+
+ LTIX::clearKeysetCacheForRegistration($registrationId);
+ $this->assertNull($this->cachedKid($pdo, $p, $linked));
+ $this->assertSame('kid-'.$stamp.'-other', $this->cachedKid($pdo, $p, $other));
+ } finally {
+ $pdo->rollBack();
+ }
+ }
+
+ private function insertCachedKey($pdo, $prefix, $stamp, $registrationId) {
+ $pdo->queryDie(
+ "INSERT INTO {$prefix}lti_key
+ (key_key, key_sha256, lms_cache_keyset, lms_cache_pubkey, lms_cache_kid,
+ lti_registration_id, created_at, updated_at)
+ VALUES (:K, :SHA, :KS, :PK, :KID, :RID, NOW(), NOW())",
+ array(
+ ':K' => $stamp,
+ ':SHA' => hash('sha256', $stamp),
+ ':KS' => '{"keys":[]}',
+ ':PK' => 'cached-key',
+ ':KID' => 'kid-'.$stamp,
+ ':RID' => $registrationId,
+ )
+ );
+ return (int) $pdo->lastInsertId();
+ }
+
+ private function cachedKid($pdo, $prefix, $keyId) {
+ $row = $pdo->rowDie(
+ "SELECT lms_cache_keyset, lms_cache_pubkey, lms_cache_kid
+ FROM {$prefix}lti_key WHERE key_id = :ID",
+ array(':ID' => $keyId)
+ );
+ $this->assertIsArray($row);
+ if ( $row['lms_cache_kid'] === null ) {
+ $this->assertNull($row['lms_cache_keyset']);
+ $this->assertNull($row['lms_cache_pubkey']);
+ }
+ return $row['lms_cache_kid'];
+ }
+
+ private function launchPost($issuer, $client) {
+ $stamp = bin2hex(random_bytes(4));
+ return array(
+ 'issuer_key' => $issuer,
+ 'issuer_sha256' => hash('sha256', $issuer),
+ 'issuer_client' => $client,
+ 'nonce' => 'nonce-'.$stamp,
+ 'context_id' => 'context-'.$stamp,
+ 'link_id' => 'link-'.$stamp,
+ 'user_id' => 'user-'.$stamp,
+ );
+ }
+
+ private function beginFixtureTransaction() {
+ global $CFG, $PDOX;
+ $config = dirname(__DIR__, 3).'/config.php';
+ if ( ! is_file($config) ) {
+ return null;
+ }
+ if ( ! isset($CFG) || ! is_object($CFG) ) {
+ require_once $config;
+ }
+ try {
+ if ( ! defined('PDO_WILL_CATCH') ) define('PDO_WILL_CATCH', true);
+ $PDOX = LTIX::getConnection();
+ if ( ! is_object($PDOX) ) {
+ return null;
+ }
+ $PDOX->beginTransaction();
+ } catch ( \Throwable $ex ) {
+ return null;
+ }
+ return $PDOX;
+ }
+
+ private function prefix() {
+ global $CFG;
+ return $CFG->dbprefix;
+ }
+}
diff --git a/lib/tests/Services/Admin/AdminServiceKeyTypeTest.php b/lib/tests/Services/Admin/AdminServiceKeyTypeTest.php
index 960d77f687..a466567fa8 100644
--- a/lib/tests/Services/Admin/AdminServiceKeyTypeTest.php
+++ b/lib/tests/Services/Admin/AdminServiceKeyTypeTest.php
@@ -57,6 +57,18 @@ public function testIssuerMissingClientKeysetOrTokenIsLti13Draft() {
$this->assertSame('LTI 1.3 / Draft', AdminService::keyTypeLabel($no_oidc));
}
+ public function testRegistrationLinkIsNotADraft() {
+ $this->assertSame('Registration', AdminService::keyTypeLabel(array(
+ 'lti_registration_id' => 4,
+ 'deploy_key' => 'deploy-1',
+ )));
+ $this->assertSame('LTI 1.1 / Registration', AdminService::keyTypeLabel(array(
+ 'key_key' => 'school',
+ 'secret' => 's3cret',
+ 'lti_registration_id' => 4,
+ )));
+ }
+
public function testDeploymentWithoutIssuerIsDraft() {
$this->assertSame('Draft', AdminService::keyTypeLabel(array(
'deploy_key' => 'deploy-1',
diff --git a/lti/oidc_login.php b/lti/oidc_login.php
index 1cc2888837..bd205138b9 100644
--- a/lti/oidc_login.php
+++ b/lti/oidc_login.php
@@ -57,15 +57,28 @@
error_log("key_id=$key_id iss=".$iss." sha256=".$key_sha256);
+$registration_sql = LTIX::inboundRegistrationSql($CFG->dbprefix, 'K');
+// TODO: Remove this lti_registration existence gate by February 2027.
$sql = "SELECT key_id,
lms_issuer, lms_client, lms_oidc_auth, lms_keyset_url,
- lms_token_url, lms_token_audience, lms_cache_keyset, lms_cache_pubkey, lms_cache_kid
- FROM {$CFG->dbprefix}lti_key AS K
+ lms_token_url, lms_token_audience, lms_cache_keyset, lms_cache_pubkey, lms_cache_kid";
+if ( $registration_sql['select'] !== '' ) {
+ $sql .= ",
+ ".$registration_sql['select'];
+}
+$sql .= "
+ FROM {$CFG->dbprefix}lti_key AS K";
+if ( $registration_sql['join'] !== '' ) {
+ $sql .= "
+ ".$registration_sql['join'];
+}
+$sql .= "
WHERE K.key_id = :KID AND (K.deleted IS NULL OR K.deleted = 0)";
$row = $PDOX->rowDie($sql, array(":KID" => $key_id));
if ( ! is_array($row) || count($row) < 1 ) {
LTIX::abort_with_error_log('Login could not find key '.htmlentities($key_id)." for iss=".htmlentities($iss));
}
+$row = LTIX::applyInboundRegistration($row);
$row['issuer_client'] = $row['lms_client'];
$row['lti13_oidc_auth'] = $row['lms_oidc_auth'];
@@ -81,7 +94,7 @@
$issuer_key = $row['issuer_key'];
$platform_public_key = $row['lti13_platform_pubkey'];
$our_kid = $row['lti13_kid'];
-$our_keyset_url = $row['lti13_keyset'];
+$our_keyset_url = $row['lti13_keyset_url'];
$our_keyset = $row['lti13_keyset'];
$signature = \Tsugi\Core\LTIX::getBrowserSignature();
diff --git a/qa/tests/AdminTest.php b/qa/tests/AdminTest.php
index 8e1949b683..094dd85880 100644
--- a/qa/tests/AdminTest.php
+++ b/qa/tests/AdminTest.php
@@ -2,6 +2,7 @@
require_once __DIR__ . '/Support/TsugiPantherTestCase.php';
+use Facebook\WebDriver\Exception\NoSuchAlertException;
use Facebook\WebDriver\WebDriverBy;
final class AdminTest extends TsugiPantherTestCase
@@ -40,11 +41,11 @@ public function testAdminKeyDetailUrlOpensTheKey(): void
$driver = $client->getWebDriver();
$driver->get($this->uri('admin/key'));
- $page = $this->waitForAdminText($client, 'LTI Tenants', 'admin/key');
+ $page = $this->waitForAdminText($client, 'Keys / Deployments', 'admin/key');
$listUrl = $driver->getCurrentURL();
$this->assertMatchesRegularExpression('#/admin/key/($|\?)#', $listUrl);
- $add = $driver->findElement(WebDriverBy::linkText('Insert Tenant'));
+ $add = $driver->findElement(WebDriverBy::linkText('Insert Key'));
$this->assertStringContainsString('/admin/key/key-add', $this->resolvedHref($driver, $add));
$detailLinks = $driver->findElements(WebDriverBy::cssSelector('a[href*="key-detail"]'));
@@ -53,11 +54,113 @@ public function testAdminKeyDetailUrlOpensTheKey(): void
}
$this->assertStringContainsString('/admin/key/key-detail', $this->resolvedHref($driver, $detailLinks[0]));
$detailLinks[0]->click();
- $page = $this->waitForAdminText($client, 'Tenant Details', 'admin/key/key-detail');
+ $page = $this->waitForAdminText($client, 'Key status:', 'admin/key/key-detail');
$this->assertPageHasNoPhpError($page, $driver->getCurrentURL());
$this->captureScreenshot($client, 'admin-key-detail');
}
+ /**
+ * Create, edit, and delete a registration, and point a new key at it.
+ * The empty-fields checkbox stays unchecked, so the key keeps its own platform fields.
+ */
+ public function testRegistrationCrudAndKeyLink(): void
+ {
+ $client = $this->unlockAdmin();
+ $driver = $client->getWebDriver();
+ $stamp = 'panther-reg-'.bin2hex(random_bytes(4));
+ $title = 'Panther '.$stamp;
+ $issuer = 'https://'.$stamp.'.example';
+ $clientId = $stamp.'-client';
+ $notes = 'notes '.$stamp;
+ $edited = 'edited '.$stamp;
+ $keyTitle = 'Panther key '.$stamp;
+
+ $driver->get($this->uri('admin/key/registrations'));
+ $this->waitForAdminText($client, 'LTI 1.3 Registrations', 'admin/key/registrations');
+ $driver->findElement(WebDriverBy::linkText('Insert Registration'))->click();
+ $this->waitForAdminText($client, 'Adding LTI 1.3 Registration', 'admin/key/registration-add');
+
+ $driver->findElement(WebDriverBy::id('title'))->sendKeys($title);
+ $driver->findElement(WebDriverBy::id('issuer'))->sendKeys($issuer);
+ $driver->findElement(WebDriverBy::id('client_id'))->sendKeys($clientId);
+ $driver->findElement(WebDriverBy::id('notes'))->sendKeys($notes);
+ $driver->findElement(WebDriverBy::name('doSave'))->click();
+
+ $page = $this->waitForAdminText($client, 'Registration Details', 'admin/key/registration-detail');
+ $this->assertStringContainsString($title, $page);
+ $this->assertStringContainsString($issuer, $page);
+ $this->assertStringContainsString($clientId, $page);
+ $this->assertStringContainsString($notes, $page);
+ $this->assertPageHasNoPhpError($page, 'registration-detail');
+
+ $driver->findElement(WebDriverBy::linkText('Edit'))->click();
+ $this->waitForAdminText($client, 'name="notes"', 'admin/key/registration-detail edit');
+ $notesField = $driver->findElement(WebDriverBy::id('notes'));
+ $notesField->clear();
+ $notesField->sendKeys($edited);
+ $driver->findElement(WebDriverBy::name('doSave'))->click();
+
+ $page = $this->waitForAdminText($client, $edited, 'admin/key/registration-detail updated');
+ $this->assertStringContainsString($title, $page);
+ $this->assertStringNotContainsString($notes, $page);
+ $this->assertPageHasNoPhpError($page, 'registration-detail updated');
+
+ $driver->get($this->uri('admin/key/key-add'));
+ $this->waitForAdminText($client, 'Adding Key', 'admin/key/key-add');
+ $driver->findElement(WebDriverBy::id('key_title'))->sendKeys($keyTitle);
+ $chosen = $driver->executeScript(
+ 'const select = document.getElementById("lti_registration_id");'
+ .'if (!select) return false;'
+ .'const option = Array.from(select.options).find((item) => item.textContent.includes(arguments[0]));'
+ .'if (!option) return false;'
+ .'select.value = option.value;'
+ .'select.dispatchEvent(new Event("change", {bubbles: true}));'
+ .'return select.value !== "";',
+ [$title]
+ );
+ $this->assertTrue($chosen, 'The new registration was not in the key form.');
+ $box = $driver->findElements(WebDriverBy::id('empty_key_lti13_fields'));
+ $this->assertNotEmpty($box);
+ $this->assertFalse($box[0]->isSelected());
+ $driver->findElement(WebDriverBy::name('doSave'))->click();
+
+ $this->waitForAdminText($client, 'Keys / Deployments', 'admin/key after insert');
+ $driver->get($this->uri('admin/key/?search_text='.rawurlencode($keyTitle)));
+ $page = $this->waitForAdminText($client, $keyTitle, 'admin/key search');
+ $this->assertPageHasNoPhpError($page, 'admin/key search');
+ $driver->findElement(WebDriverBy::linkText($keyTitle))->click();
+ $page = $this->waitForAdminText($client, 'Key status:', 'admin/key/key-detail');
+ $this->assertStringContainsString('registration-detail?lti_registration_id=', $page);
+ $this->assertSame('', trim($driver->findElement(WebDriverBy::id('lms_issuer'))->getText()));
+ $this->assertSame('', trim($driver->findElement(WebDriverBy::id('lms_client'))->getText()));
+ $this->assertPageHasNoPhpError($page, 'key linked to registration');
+
+ $driver->findElement(WebDriverBy::linkText('Registration'))->click();
+ $page = $this->waitForAdminText($client, $keyTitle, 'registration lists its key');
+ $this->assertStringContainsString('Keys
', $page);
+
+ $driver->findElement(WebDriverBy::linkText($keyTitle))->click();
+ $this->waitForAdminText($client, 'Key status:', 'admin/key/key-detail before delete');
+ $this->clickClearOfNavbar($driver, $driver->findElement(WebDriverBy::name('doDelete')));
+ $this->acceptAdminAlert($driver, 'delete this record');
+ $this->waitForAdminText($client, 'Keys / Deployments', 'admin/key after key delete');
+ $driver->get($this->uri('admin/key/?search_text='.rawurlencode($keyTitle)));
+ $page = $this->waitForAdminText($client, 'Keys / Deployments', 'admin/key search after delete');
+ $this->assertEmpty($driver->findElements(WebDriverBy::linkText($keyTitle)));
+
+ $driver->get($this->uri('admin/key/registrations?search_text='.rawurlencode($title)));
+ $this->waitForAdminText($client, $title, 'admin/key/registrations before delete');
+ $driver->findElement(WebDriverBy::linkText($title))->click();
+ $this->waitForAdminText($client, 'Registration Details', 'registration before delete');
+ $this->clickClearOfNavbar($driver, $driver->findElement(WebDriverBy::name('doDelete')));
+ $this->acceptAdminAlert($driver, 'delete this registration');
+ $this->waitForAdminText($client, 'LTI 1.3 Registrations', 'admin/key/registrations after delete');
+ $driver->get($this->uri('admin/key/registrations?search_text='.rawurlencode($title)));
+ $page = $this->waitForAdminText($client, 'LTI 1.3 Registrations', 'admin/key/registrations search after delete');
+ $this->assertEmpty($driver->findElements(WebDriverBy::linkText($title)));
+ $this->assertPageHasNoPhpError($page, 'registrations after delete');
+ }
+
/**
* Open each console section from its menu link, then one safe child.
* Skips upgrade, delete, expire, blob cleanup, and mail send.
@@ -127,7 +230,8 @@ private function adminSmokePages(): array
'admin/catalog' => 'Course catalog',
'admin/org/' => 'Pick a tenant',
'admin/catalog/edit.php' => 'Add catalog listing',
- 'admin/key/' => 'LTI Tenants',
+ 'admin/key/' => 'Keys / Deployments',
+ 'admin/key/registrations' => 'LTI 1.3 Registrations',
'admin/expire/' => 'Manage Data Expiry',
'admin/context/' => ['members', 'Nothing to display.'],
'admin/activity/' => ['link_title', 'Nothing to display.'],
@@ -187,11 +291,11 @@ private function adminConsoleSteps(): array
],
[
'link' => 'Manage Access Keys',
- 'marker' => 'LTI Tenants',
+ 'marker' => 'Keys / Deployments',
'href' => '/admin/key/',
'next' => [
- 'link' => 'Insert Tenant',
- 'marker' => 'Adding Tsugi Tenant/Key',
+ 'link' => 'Insert Key',
+ 'marker' => 'Adding Key',
'href' => '/admin/key/key-add',
],
],
@@ -279,6 +383,23 @@ private function adminConsoleSteps(): array
];
}
+ private function acceptAdminAlert(\Facebook\WebDriver\WebDriver $driver, string $needle): void
+ {
+ $deadline = microtime(true) + 15;
+ while (microtime(true) < $deadline) {
+ try {
+ $alert = $driver->switchTo()->alert();
+ $text = $alert->getText();
+ $alert->accept();
+ $this->assertStringContainsString($needle, strtolower($text));
+ return;
+ } catch (NoSuchAlertException $exception) {
+ usleep(200000);
+ }
+ }
+ $this->fail('Timed out waiting for an alert containing '.$needle);
+ }
+
private function unlockAdmin(): \Symfony\Component\Panther\Client
{
$passphrase = getenv('TSUGI_ADMIN_PW');
diff --git a/qa/tests/CourseToolLoopbackTest.php b/qa/tests/CourseToolLoopbackTest.php
index 1d2d19a0bd..c424aad6ff 100644
--- a/qa/tests/CourseToolLoopbackTest.php
+++ b/qa/tests/CourseToolLoopbackTest.php
@@ -70,19 +70,19 @@ private function draftKeyRegistrationUrl(\Symfony\Component\Panther\Client $clie
{
$driver = $client->getWebDriver();
$driver->get($this->uri('admin/key/key-add'));
- $this->waitForPageText($client, 'Adding Tsugi Tenant/Key');
+ $this->waitForPageText($client, 'Adding Key');
$driver->findElement(WebDriverBy::id('key_title'))->sendKeys($title);
$driver->findElement(WebDriverBy::id('lms_issuer'))->sendKeys($this->baseUri());
$driver->findElement(WebDriverBy::id('lms_client'))->sendKeys('panther-client-'.date('YmdHis'));
$driver->findElement(WebDriverBy::name('doSave'))->click();
- $this->waitForPageText($client, 'LTI Tenants');
+ $this->waitForPageText($client, 'Keys / Deployments');
$this->openKey($client, $title);
$driver->findElement(WebDriverBy::linkText('Edit'))->click();
$this->waitForPageText($client, 'name="unlock_code"');
$driver->findElement(WebDriverBy::id('unlock_code'))->sendKeys($unlock);
- $driver->findElement(WebDriverBy::name('doUpdate'))->click();
- $this->waitForPageText($client, 'LTI Tenants');
+ $this->clickClearOfNavbar($driver, $driver->findElement(WebDriverBy::name('doUpdate')));
+ $this->waitForPageText($client, 'Keys / Deployments');
$this->openKey($client, $title);
$this->waitForPageText($client, 'LTI Advantage Dynamic Registration URL');
@@ -100,7 +100,7 @@ private function openKey(\Symfony\Component\Panther\Client $client, string $titl
$driver->findElement(WebDriverBy::xpath(
"//tr[contains(., '".$title."')]//a[contains(@href, 'key-detail')]"
))->click();
- $this->waitForPageText($client, 'Tenant Details');
+ $this->waitForPageText($client, 'Key status:');
$this->waitForPageText($client, $title);
}
}
diff --git a/qa/tests/Support/TsugiPantherTestCase.php b/qa/tests/Support/TsugiPantherTestCase.php
index a7f15d6380..31b8ea9b40 100644
--- a/qa/tests/Support/TsugiPantherTestCase.php
+++ b/qa/tests/Support/TsugiPantherTestCase.php
@@ -32,6 +32,15 @@ protected static function baseUri(): string
return rtrim($base, '/');
}
+ /**
+ * A fixed navbar covers a button that Selenium scrolls to the top of the window.
+ */
+ protected function clickClearOfNavbar(\Facebook\WebDriver\WebDriver $driver, \Facebook\WebDriver\WebDriverElement $element): void
+ {
+ $driver->executeScript('arguments[0].scrollIntoView({block:"center"});', [$element]);
+ $element->click();
+ }
+
protected function uri(string $path): string
{
$trimmed = ltrim($path, '/');