From e4218aa2cc2271f6397aa89168db83670d6307b5 Mon Sep 17 00:00:00 2001
From: Charles Severance
Date: Sat, 21 Nov 2026 12:49:36 -0500
Subject: [PATCH 1/5] Add a dormant inbound LTI 1.3 registration, and drop the
CodeRabbit PHPStan setting it no longer accepts.
Co-authored-by: Cursor
---
.coderabbit.yaml | 1 -
lib/src/Services/Lti/database.php | 121 ++++++++++++++++++++++++++++++
2 files changed, 121 insertions(+), 1 deletion(-)
diff --git a/.coderabbit.yaml b/.coderabbit.yaml
index afc8b2182..46ccd2687 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/lib/src/Services/Lti/database.php b/lib/src/Services/Lti/database.php
index ff5959ad1..26095f9d6 100644
--- a/lib/src/Services/Lti/database.php
+++ b/lib/src/Services/Lti/database.php
@@ -40,6 +40,8 @@
"drop table if exists {$CFG->dbprefix}lti_issuer",
"drop table if exists {$CFG->dbprefix}lti_keyset",
"drop table if exists {$CFG->dbprefix}lti_key",
+// After lti_key. A later foreign key on lti_key will require that order.
+"drop table if exists {$CFG->dbprefix}lti_registration",
"drop table if exists {$CFG->dbprefix}lti_nonce",
"drop table if exists {$CFG->dbprefix}lti_message",
"drop table if exists {$CFG->dbprefix}lti_domain",
@@ -70,6 +72,79 @@
CONSTRAINT `{$CFG->dbprefix}lti_keyset_const_pk` PRIMARY KEY (keyset_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
+// Inbound LTI 1.3 registration. Tsugi is the tool.
+// lti_tool_registration is the other direction, where Tsugi is the platform.
+// One row is one OAuth client (issuer + client_id). Deployments stay on lti_key.
+// Created before lti_key so a later foreign key can live in the lti_key CREATE.
+// Nothing reads this table yet. Launch and dynamic registration still use lti_key.
+array( "{$CFG->dbprefix}lti_registration",
+"create table {$CFG->dbprefix}lti_registration (
+ lti_registration_id INTEGER NOT NULL AUTO_INCREMENT,
+
+ -- Row guid. An omitted value gets an unswapped MySQL UUID() (version 1).
+ -- Same bytes as UUID_TO_BIN(UUID()). Inserts pass Guid::uuid7().
+ -- UNHEX, REPLACE, and UUID are allowed in a default on MySQL 8.0.13+ and
+ -- MariaDB 10.5. UUID_TO_BIN is not allowed in a MariaDB 10.5 default.
+ -- Explicit NULL stays NULL. The unique key allows more than one NULL.
+ -- This is not tool_platform.guid. That value is platform_guid.
+ guid BINARY(16) NULL DEFAULT (UNHEX(REPLACE(UUID(), '-', ''))),
+
+ -- Human label. Not part of the OAuth identity. Copied from key_title
+ -- when a registration is created from a key.
+ title TEXT NULL,
+ notes TEXT NULL,
+
+ -- Issuer is required. client_id stays NULL until the platform assigns one.
+ issuer VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+ client_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
+
+ -- The first completed (issuer, client_id) owns these four values.
+ -- Later deployments of that client reuse this row. They do not get another copy.
+ -- Canvas cloud shares the issuer and these URLs, so the client id separates schools.
+ -- Blackboard SaaS shares https://blackboard.com. The authorize, token, and
+ -- keyset URLs are on the school host, and the token audience is often a
+ -- different gateway value. The first row to store that client freezes them.
+ -- A hostname change, or another key entered with different URLs, has nowhere
+ -- else to go. Handle this when dynamic registration writes this table.
+ -- Do not copy the first lti_key lms_* values and assume the other keys agree.
+ oidc_auth_url TEXT NULL,
+ keyset_url TEXT NULL,
+ token_url TEXT NULL,
+ -- OpenID authorization_server, stored verbatim. Often not the token URL.
+ token_audience TEXT NULL,
+
+ -- One-time dynamic registration code. Same column as lti_key.unlock_code.
+ -- Dynamic registration still checks the code on the key.
+ unlock_code MEDIUMTEXT NULL,
+ -- NULL until a later dynamic registration flow records the unlock. Nothing writes this yet.
+ dynamic_registration_unlocked_at TIMESTAMP NULL,
+
+ product_family_code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+ -- tool_platform.guid from a launch. Registration usually does not have it yet.
+ platform_guid VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
+
+ -- Future values: manual, dynamic. Nothing reads these yet.
+ registration_method VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'manual',
+ -- Future values: pending, active, disabled.
+ registration_status VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'pending',
+ -- Future values: automatic, approval, reject. Default is approval.
+ new_deployment_policy VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'approval',
+
+ -- Provenance only. Not a foreign key and not deployment ownership.
+ created_by_user_id INTEGER NULL,
+
+ json MEDIUMTEXT NULL,
+
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP NULL,
+
+ -- NULLs are distinct, so pending rows can share an issuer while client_id
+ -- is still NULL. A completed (issuer, client_id) pair cannot be repeated.
+ CONSTRAINT `{$CFG->dbprefix}lti_registration_const_1` UNIQUE (issuer, client_id),
+ CONSTRAINT `{$CFG->dbprefix}lti_registration_const_guid` UNIQUE (`guid`),
+ CONSTRAINT `{$CFG->dbprefix}lti_registration_const_pk` PRIMARY KEY (lti_registration_id)
+ ) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
+
// https://stackoverflow.com/questions/28418360/jwt-json-web-token-audience-aud-versus-client-id-whats-the-difference
// Key is in effect "tenant" (like a billing endpoint)
@@ -111,6 +186,17 @@
lms_token_url TEXT NULL,
lms_token_audience TEXT NULL,
+ -- Inbound registration. NULL means this key is not in that model yet.
+ -- ON DELETE SET NULL detaches the key when the registration is removed.
+ -- deployment_status NULL means the approval workflow does not apply.
+ -- Future values: pending, active, blocked.
+ -- platform_guid is tool_platform.guid from a launch, not this row's guid.
+ lti_registration_id INTEGER NULL,
+ deployment_status VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NULL,
+ -- NULL until a later approval workflow sets it. Existing keys stay NULL.
+ deployment_approved_at TIMESTAMP NULL,
+ platform_guid VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
+
-- Default IANA zone copied onto a new Plus context. Existing courses keep their own.
timezone VARCHAR(64) NULL,
@@ -123,6 +209,8 @@
lms_cache_kid TEXT NULL,
unlock_code MEDIUMTEXT NULL,
+ -- NULL until a later dynamic registration flow records the unlock. Nothing writes this yet.
+ dynamic_registration_unlocked_at TIMESTAMP NULL,
json MEDIUMTEXT NULL,
user_json MEDIUMTEXT NULL,
@@ -148,6 +236,10 @@
-- allows multiple rows per key_sha256 in typical MySQL UNIQUE-with-NULL semantics.
CONSTRAINT `{$CFG->dbprefix}lti_key_const_1` UNIQUE(key_sha256, deploy_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_key_const_guid` UNIQUE (`guid`),
+ CONSTRAINT `{$CFG->dbprefix}lti_key_ibfk_1`
+ FOREIGN KEY (`lti_registration_id`)
+ REFERENCES `{$CFG->dbprefix}lti_registration` (`lti_registration_id`)
+ ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_key_const_pk` PRIMARY KEY (key_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
@@ -1717,6 +1809,17 @@
// 2026-10-27 Last Classroom refresh error, and the last successful check.
array('lti_user', 'gc_status', 'VARCHAR(512) NULL'),
array('lti_user', 'gc_checked_at', 'TIMESTAMP NULL'),
+
+ // 2026-11-21 Inbound LTI 1.3 registration. Existing keys stay NULL.
+ // The foreign key is added below. platform_guid is tool_platform.guid, not lti_key.guid.
+ // lti_registration itself is created from DATABASE_INSTALL.
+ array('lti_key', 'lti_registration_id', 'INTEGER NULL'),
+ array('lti_key', 'deployment_status', 'VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NULL'),
+ array('lti_key', 'deployment_approved_at', 'TIMESTAMP NULL'),
+ array('lti_key', 'platform_guid', 'VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL'),
+ array('lti_key', 'dynamic_registration_unlocked_at', 'TIMESTAMP NULL'),
+ array('lti_registration', 'title', 'TEXT NULL'),
+ array('lti_registration', 'notes', 'TEXT NULL'),
);
foreach ( $add_some_fields as $add_field ) {
@@ -2444,6 +2547,24 @@
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
+ && $PDOX->columnExists('lti_registration_id', $key_table)
+ && ! $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) ) {
From 57f9e0db651290a99a2e282f63e93d18b1dbd3b3 Mon Sep 17 00:00:00 2001
From: Charles Severance
Date: Sat, 21 Nov 2026 16:44:07 -0500
Subject: [PATCH 2/5] Use a complete inbound registration for admin, launch,
login, and Plus tokens.
A launch matches the registration only when its issuer, client id, and platform URLs are all set. A keyset cache is reused when it was fetched from that registration URL, and the key row keeps its own platform fields in the database.
Co-authored-by: Cursor
---
config-dist.php | 4 +
lib/src/Controllers/Admin/Key.php | 24 +
.../templates/Admin/key/blackboard-detail.php | 7 +-
.../templates/Admin/key/canvas-detail.php | 12 +-
.../templates/Admin/key/client-id-check.php | 2 +-
.../Controllers/templates/Admin/key/index.php | 22 +-
.../templates/Admin/key/key-add.php | 38 +-
.../templates/Admin/key/key-detail.php | 222 +++++++-
.../templates/Admin/key/registration-add.php | 46 ++
.../Admin/key/registration-detail.php | 129 +++++
.../Admin/key/registration-fields.php | 37 ++
.../Admin/key/registration-from-key.php | 14 +
.../templates/Admin/key/registrations.php | 55 ++
.../templates/Admin/key/requests.php | 2 +-
lib/src/Core/LTIX.php | 194 ++++++-
lib/src/Services/Admin/AdminService.php | 528 +++++++++++++++++-
lib/src/Services/Plus/GradeSync.php | 38 +-
lib/src/Services/Plus/RosterSync.php | 19 +-
lib/src/UI/CrudForm.php | 21 +-
lib/tests/Core/InboundRegistrationTest.php | 342 ++++++++++++
.../Admin/AdminServiceKeyTypeTest.php | 12 +
lti/oidc_login.php | 19 +-
qa/tests/AdminTest.php | 135 ++++-
qa/tests/CourseToolLoopbackTest.php | 10 +-
qa/tests/Support/TsugiPantherTestCase.php | 9 +
25 files changed, 1837 insertions(+), 104 deletions(-)
create mode 100644 lib/src/Controllers/templates/Admin/key/registration-add.php
create mode 100644 lib/src/Controllers/templates/Admin/key/registration-detail.php
create mode 100644 lib/src/Controllers/templates/Admin/key/registration-fields.php
create mode 100644 lib/src/Controllers/templates/Admin/key/registration-from-key.php
create mode 100644 lib/src/Controllers/templates/Admin/key/registrations.php
create mode 100644 lib/tests/Core/InboundRegistrationTest.php
diff --git a/config-dist.php b/config-dist.php
index fddd1383b..1d341341d 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 12a6a08f4..f867a2c5c 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/templates/Admin/key/blackboard-detail.php b/lib/src/Controllers/templates/Admin/key/blackboard-detail.php
index 622f4917e..0bcbe6564 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 @@
LTI 1.3
-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 e12ccda61..06924c214 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 @@
Canvas LTI 1.3
-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 eed0c204b..b63ce07c4 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 77ea72a93..82e64a792 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();
?>
-LTI Tenants (Keys)
+Keys / Deployments
- 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 2453f21d6..9332426f7 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();
?>
-Adding Tsugi Tenant/Key
+Adding Key
Exit
@@ -129,29 +134,32 @@
or this form. Tsugi solves this with a concept called "Draft Keys" where you can create a key
with minimal information and then edit it later (perhaps by dynamic registration) to fill in the
remaining details. For LTI 1.3, you can leave LTI 1.3 Deployment Id blank so the key accepts any value from the LMS; launches then
-match on issuer and client id only. Set a specific value when you want this tenant to accept only
+match on issuer and client id only. Set a specific value when you want this key to accept only
that deployment. Dynamic registration can still fill in or change deployment later.
See "About Keys" tab for detail on how to create a draft key.
+To keep the platform values on a registration instead, create one by hand and choose it here.
+After you choose a registration, leave the platform fields on this key, or check the box to empty them and keep the deployment id only.
$registration_html));
?>
-
Tenant Key Options
+
Key Options
-A single entry in this table defines a "distinct tenant" in Tsugi.
-Data in Tsugi is isolated to a tenant. For a key to work it must have at least one of
+A single entry in this table is one key.
+Data in Tsugi is isolated to a key. For a key to work it must have at least one of
An LTI 1.1 oauth_consumer_key that must be unique in this system and
a secret
For an LMS that supports LTI 1.3 and Dynamic Registration, enter the issuer and unlock_key
-and leave the other fields blank. Optionally set deployment_id if you want this tenant to match only that deployment.
+and leave the other fields blank. Optionally set deployment_id if you want this key to match only that deployment.
If you do not know the deployment_id or it will be set automatically later using Dynamic Registration, leave
Deployment Id blank to accept any value from the LMS, or enter a placeholder that you edit after registration.
@@ -161,7 +169,7 @@
should be able to give you the rest of the values and you can come back and edit the entry here.
-Some tenants can have both LTI 1.1 and LTI 1.3 values if you want to have automatic conversion of accounts
+Some keys can have both LTI 1.1 and LTI 1.3 values if you want to have automatic conversion of accounts
created in Tsugi using LTI 1.1 and letting them be converted to support LTI 1.3 without creating a second account.
LTI 1.3 Dynamic Registration
@@ -182,8 +190,8 @@
LTI 1.1 to LTI 1.3 Migration
-To receive both LTI 1.1 and LTI 1.3 launches to this "tenant", simply set all four fields.
-If you are adding LTI 1.3 to a pre-existing LTI 1.1 tenant, the LMS must
+To receive both LTI 1.1 and LTI 1.3 launches to this key, simply set all four fields.
+If you are adding LTI 1.3 to a pre-existing LTI 1.1 key, the LMS must
support
LTI Advantage legacy LTI 1.1 support as described in the
@@ -220,7 +228,7 @@
LTI 1.1
-Create a Tenant key with the LTI key and secret. Then come back here and view the key to
+Create a key with the LTI key and secret. Then come back here and view the key to
see the various URLs you can use to install Tsugi in your LMS.
@@ -238,7 +246,7 @@
LTI 1.1
-Create a Tenant key with the LTI key and secret. Then come back here and view the key
+Create a key with the LTI key and secret. Then come back here and view the key
to see the various URLs you can use to install Tsugi in Blackboard.
diff --git a/lib/src/Controllers/templates/Admin/key/key-detail.php b/lib/src/Controllers/templates/Admin/key/key-detail.php
index 9bcb70024..e3999416b 100644
--- a/lib/src/Controllers/templates/Admin/key/key-detail.php
+++ b/lib/src/Controllers/templates/Admin/key/key-detail.php
@@ -23,18 +23,18 @@
$allow_edit = true;
$where_clause = '';
$query_fields = array();
-$fields = array('key_id', 'key_title', 'plus', 'key_key', 'secret',
+$fields = array('key_id', 'key_title', 'plus', 'user_id', 'key_key', 'secret',
'lms_issuer', 'lms_client',
'deploy_key', 'unlock_code',
'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience',
- 'created_at', 'updated_at', 'user_id',
+ 'created_at', 'updated_at',
);
$realfields = array('key_id', 'key_title', 'plus', 'key_key', 'key_sha256', 'secret',
'lms_issuer', 'lms_issuer_sha256', 'lms_client',
'deploy_key', 'deploy_sha256', 'unlock_code',
'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience',
- 'created_at', 'updated_at', 'user_id',
+ 'created_at', 'updated_at', 'user_id', 'lti_registration_id',
);
$titles = array(
@@ -72,6 +72,12 @@
// Check the complex validation
if ( count($_POST) > 0 && U::get($_POST,'doUpdate') && !empty($key_id) ) {
+ if ( ! \Tsugi\Services\Admin\AdminService::applyPostedRegistrationToKey() ) {
+ $redir = U::add_url_parm('key-detail', 'key_id', $key_id);
+ $redir = U::add_url_parm($redir, 'edit', 'yes');
+ header("Location: ".$redir);
+ return;
+ }
$row = $PDOX->rowDie( "SELECT * FROM {$CFG->dbprefix}lti_key
WHERE key_id = :key_id",
array(':key_id' => $key_id)
@@ -130,21 +136,20 @@
return;
}
-$key_type = \Tsugi\Services\Admin\AdminService::keyTypeLabel($row);
-
$OUTPUT->header();
$OUTPUT->bodyStart();
$OUTPUT->topNav();
$OUTPUT->flashMessages();
?>
-
-Key status: = $key_type ?>
+Key status: = \Tsugi\Services\Admin\AdminService::keyTypeHtml($row) ?>
Key Data
@@ -162,7 +167,19 @@
$extra_buttons=false;
$row['lti13_tool_keyset_url'] = $CFG->wwwroot . '/lti/keyset';
$from_location = null;
-$retval = CrudForm::updateForm($row, $fields, $current, $from_location, $allow_edit, $allow_delete, $extra_buttons, $titles, array('plus'));
+$registration_html = \Tsugi\Services\Admin\AdminService::matchingRegistrationNote($row);
+$registration_html .= \Tsugi\Services\Admin\AdminService::inboundRegistrationControl(
+ (int) U::get($row, 'lti_registration_id'),
+ $inedit == 'yes'
+);
+$after_fields = array('secret' => $registration_html);
+if ( $inedit == 'yes' ) {
+ $after_fields['lms_token_audience'] = ''
+ .'Create Registration From This Data '
+ .'
'
+ .'
';
+}
+$retval = CrudForm::updateForm($row, $fields, $current, $from_location, $allow_edit, $allow_delete, $extra_buttons, $titles, array('plus'), $after_fields);
if ( is_string($retval) ) die($retval);
echo("\n");
$dynamicConfigUrl = null;
@@ -191,12 +208,12 @@ function showDynamicConfig($url) {
?>
-
Tenant Key Options
+
Key Options
-A single entry in this table defines a "distinct tenant" in Tsugi.
-Data in Tsugi is isolated to a tenant. You can route both
-LTI 1.1 and LTI 1.3 launches to one tenant by setting fields on
-this entry properly. If a tenant key is in "Draft" status - launches
+A single entry in this table is one key.
+Data in Tsugi is isolated to a key. You can route both
+LTI 1.1 and LTI 1.3 launches to one key by setting fields on
+this entry properly. If a key is in "Draft" status, launches
will not work.
@@ -204,19 +221,19 @@ function showDynamicConfig($url) {
For LTI 1.3, you can either
-(a) create a global issuer and select it here, and then set the deployment_id if you want this tenant to match only that deployment,
+(a) create a global issuer and select it here, and then set the deployment_id if you want this key to match only that deployment,
or you can
(b) leave the global issuer unset and set all of the LMS values in this screen. If you mix
-a global issuer and per-key LTI 1.3 settings, you will most likely end up with a tenant that
+a global issuer and per-key LTI 1.3 settings, you will most likely end up with a key that
won't be able to receive launches.
For the LTI 1.3 Deployment ID field on this key: leave blank to accept any value from the LMS
(Tsugi still uses the deployment id from the launch for services such as grading).
-Enter a specific deployment id when you want this tenant to accept only that deployment.
+Enter a specific deployment id when you want this key to accept only that deployment.
-If this is a pre-existing LTI 1.1 tenant, the LMS must provide the oauth_consumer_key
+If this is a pre-existing LTI 1.1 key, the LMS must provide the oauth_consumer_key
and secret connected to its LTI 1.3 launches, and then Tsugi can link the accounts
and courses regardless of the type of launch. For this to work, the LMS must support
LTI Advantage legacy LTI 1.1 support.
@@ -233,9 +250,9 @@ function showDynamicConfig($url) {
LTI Dynamic Registration
process. This process takes
a draft Tsugi key, and sends its data to the LMS and the LMS responds with all of its values
-and Tsugi automatically updates the Tenant key with the LMS values. It is basically a one-click
+and Tsugi automatically updates the key with the LMS values. It is basically a one-click
LTI Advantage install.
-Create a tenant key with at least a title and issuer (or start from a draft key), then use the Dynamic Registration URL below in the LMS.
+Create a key with at least a title and issuer (or start from a draft key), then use the Dynamic Registration URL below in the LMS.
@@ -245,11 +262,11 @@ function showDynamicConfig($url) {
the new issuer data will be added to this key.
-A secondary and optional part of Dynamic Registration is to communicate the Deployment ID for this tenant / key.
+A secondary and optional part of Dynamic Registration is to communicate the Deployment ID for this key.
Sometimes this is included in the dynamic registration exchange (Sakai, Moodle, and Brightspace for example).
For other LMS's you may need to run the dynamic registration process, and then manually enter the Deployment Id
later if you want a specific deployment. You can also leave Deployment ID blank so the key accepts any value from the LMS.
-Many single-tenant Sakai or Moodle installs still send a concrete deployment id in launches (for example 1 );
+Many single-site Sakai or Moodle installs still send a concrete deployment id in launches (for example 1 );
a blank Deployment ID field accepts that without storing it on the key row.
@@ -327,8 +344,8 @@ function showDynamicConfig($url) {
-Sakai supports the optional part of Dynamic Registration and so it provides the Deployment ID for this tenant / key
-in the Dynamic Registration process so once the process is done - the Tenant should be fully configured and ready to launch.
+Sakai supports the optional part of Dynamic Registration and so it provides the Deployment ID for this key
+in the Dynamic Registration process so once the process is done, the key should be fully configured and ready to launch.
You may leave Deployment ID blank on the Tsugi key so it accepts any value from the LMS; Sakai often sends deployment_id 1 in launches, which is fine when this field is blank.
@@ -368,8 +385,8 @@ function showDynamicConfig($url) {
-Moodle supports the optional part of Dynamic Registration and so it provides the Deployment ID for this tenant / key
-in the Dynamic Registration process so once the process is done - the Tenant should be fully configured and ready to launch.
+Moodle supports the optional part of Dynamic Registration and so it provides the Deployment ID for this key
+in the Dynamic Registration process so once the process is done, the key should be fully configured and ready to launch.
You may leave Deployment ID blank on the Tsugi key so it accepts any value from the LMS; Moodle may still send a concrete deployment id in launches.
@@ -477,6 +494,159 @@ function showDynamicConfig($url) {
+
+
+
+
footerStart();
$OUTPUT->footerEnd();
diff --git a/lib/src/Controllers/templates/Admin/key/registration-add.php b/lib/src/Controllers/templates/Admin/key/registration-add.php
new file mode 100644
index 000000000..7a721d2a6
--- /dev/null
+++ b/lib/src/Controllers/templates/Admin/key/registration-add.php
@@ -0,0 +1,46 @@
+wwwroot.'/admin/key/';
+
+if ( count($_POST) > 0 ) {
+ if ( \Tsugi\Controllers\Tool::csrfRedirect($key_admin.'registration-add') ) return;
+}
+
+$registration_values = array();
+if ( isset($_POST['doSave']) ) {
+ $id = AdminService::saveInboundRegistration(null, $_POST);
+ if ( $id ) {
+ header('Location: '.$key_admin.'registration-detail?lti_registration_id='.(int) $id);
+ return;
+ }
+ $registration_values = $_POST;
+}
+
+$OUTPUT->header();
+$OUTPUT->bodyStart();
+$OUTPUT->topNav();
+$OUTPUT->flashMessages();
+?>
+Adding LTI 1.3 Registration
+Exit
+
+
+These are the same platform values a key used to store itself.
+
+
+footer();
diff --git a/lib/src/Controllers/templates/Admin/key/registration-detail.php b/lib/src/Controllers/templates/Admin/key/registration-detail.php
new file mode 100644
index 000000000..b5d9cbf5e
--- /dev/null
+++ b/lib/src/Controllers/templates/Admin/key/registration-detail.php
@@ -0,0 +1,129 @@
+wwwroot.'/admin/key/';
+$from_location = $key_admin.'registrations';
+$registration_id = (int) U::get($_REQUEST, 'lti_registration_id');
+if ( $registration_id < 1 ) {
+ U::flashError('Missing registration');
+ header('Location: '.$from_location);
+ return;
+}
+$detail_location = $key_admin.'registration-detail?lti_registration_id='.$registration_id;
+
+if ( isset($_POST['doSave']) || isset($_POST['doDelete']) ) {
+ if ( \Tsugi\Controllers\Tool::csrfRedirect($detail_location) ) return;
+}
+
+if ( isset($_POST['doDelete']) ) {
+ $gone = $PDOX->queryReturnError(
+ "DELETE FROM {$CFG->dbprefix}lti_registration WHERE lti_registration_id = :id",
+ array(':id' => $registration_id)
+ );
+ if ( ! $gone->success ) {
+ U::flashError('Could not delete registration');
+ header('Location: '.$detail_location);
+ return;
+ }
+ U::flashSuccess('Registration deleted. Keys that pointed at it are detached.');
+ header('Location: '.$from_location);
+ return;
+}
+
+$editing = U::get($_REQUEST, 'edit') == 'yes';
+if ( isset($_POST['doSave']) ) {
+ $saved = AdminService::saveInboundRegistration($registration_id, $_POST);
+ if ( $saved ) {
+ header('Location: '.$detail_location);
+ return;
+ }
+ $editing = true;
+}
+
+$row = AdminService::inboundRegistrationById($registration_id);
+if ( ! is_array($row) ) {
+ U::flashError('Registration not found');
+ header('Location: '.$from_location);
+ return;
+}
+
+$OUTPUT->header();
+$OUTPUT->bodyStart();
+$OUTPUT->topNav();
+$OUTPUT->flashMessages();
+?>
+Registration Details
+ All Registrations
+ All Keys
+
+
+= htmlspecialchars(AdminService::inboundRegistrationLabel($row), ENT_QUOTES, 'UTF-8') ?>
+
+
+
+Edit
+
+Title
+= htmlspecialchars((string) $row['title'], ENT_QUOTES, 'UTF-8') ?>
+Issuer
+= htmlspecialchars((string) $row['issuer'], ENT_QUOTES, 'UTF-8') ?>
+LTI 1.3: Dynamic Registration Unlock Code (one time use)
+= htmlspecialchars((string) $row['unlock_code'], ENT_QUOTES, 'UTF-8') ?>
+Client id
+= htmlspecialchars((string) $row['client_id'], ENT_QUOTES, 'UTF-8') ?>
+OIDC login / authorization URL
+= htmlspecialchars((string) $row['oidc_auth_url'], ENT_QUOTES, 'UTF-8') ?>
+Keyset URL
+= htmlspecialchars((string) $row['keyset_url'], ENT_QUOTES, 'UTF-8') ?>
+Token URL
+= htmlspecialchars((string) $row['token_url'], ENT_QUOTES, 'UTF-8') ?>
+LTI 1.3 Platform Audience (optional)
+= htmlspecialchars((string) $row['token_audience'], ENT_QUOTES, 'UTF-8') ?>
+Notes
+= htmlspecialchars((string) $row['notes'], ENT_QUOTES, 'UTF-8') ?>
+
+
+Keys
+
+No keys point at this registration.
+
+
+
+footer();
diff --git a/lib/src/Controllers/templates/Admin/key/registration-fields.php b/lib/src/Controllers/templates/Admin/key/registration-fields.php
new file mode 100644
index 000000000..4aef0722e
--- /dev/null
+++ b/lib/src/Controllers/templates/Admin/key/registration-fields.php
@@ -0,0 +1,37 @@
+ 'Title',
+ 'issuer' => 'LTI 1.3 Platform Issuer URL (required)',
+ 'unlock_code' => 'LTI 1.3: Dynamic Registration Unlock Code (one time use)',
+ 'client_id' => 'LTI 1.3 Platform Client ID - usually a GUID',
+ 'oidc_auth_url' => 'LTI 1.3 Platform OIDC Login / Authorization Endpoint URL',
+ 'keyset_url' => 'LTI 1.3 Platform KeySet URL',
+ 'token_url' => 'LTI 1.3 Platform Token URL',
+ 'token_audience' => 'LTI 1.3 Platform Audience (optional)',
+ 'notes' => 'Notes',
+);
+$registration_action = isset($registration_action) ? $registration_action : '';
+?>
+
+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 000000000..4a0530750
--- /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 000000000..0676dabba
--- /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();
+?>
+LTI 1.3 Registrations
+
+ 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 5385f0606..c6f43c1ce 100644
--- a/lib/src/Controllers/templates/Admin/key/requests.php
+++ b/lib/src/Controllers/templates/Admin/key/requests.php
@@ -51,7 +51,7 @@
?>
LTI Key Requests
- Tenant Keys
+ Keys
providekeys ) { ?>
Key Requests
diff --git a/lib/src/Core/LTIX.php b/lib/src/Core/LTIX.php
index 0a03a4ffe..a500e9dea 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,149 @@ 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 $row
+ * @return array
+ */
+ public static function applyInboundRegistration(array $row) {
+ $required = array('reg_issuer', 'reg_client_id', 'reg_oidc_auth_url', 'reg_keyset_url', 'reg_token_url');
+ foreach ( $required as $field ) {
+ if ( ! U::isNotEmpty(U::get($row, $field)) ) {
+ self::clearInboundRegistrationColumns($row);
+ return $row;
+ }
+ }
+ $keyset = U::get($row, 'lms_keyset_url');
+ $reg_keyset = trim((string) $row['reg_keyset_url']);
+ $keyset_same = is_string($keyset) && trim($keyset) === $reg_keyset;
+ $cache_same = self::cachedKeysetUrl(U::get($row, 'lms_cache_keyset')) === $reg_keyset;
+ if ( ! $keyset_same && ! $cache_same ) {
+ $row['lms_cache_keyset'] = null;
+ $row['lms_cache_pubkey'] = null;
+ $row['lms_cache_kid'] = null;
+ }
+ $row['lms_issuer'] = $row['reg_issuer'];
+ $row['lms_client'] = $row['reg_client_id'];
+ $row['lms_oidc_auth'] = $row['reg_oidc_auth_url'];
+ $row['lms_keyset_url'] = $row['reg_keyset_url'];
+ $row['lms_token_url'] = $row['reg_token_url'];
+ $row['lms_token_audience'] = array_key_exists('reg_token_audience', $row) ? $row['reg_token_audience'] : null;
+ self::logRegistrationConfig($row);
+ self::clearInboundRegistrationColumns($row);
+ return $row;
+ }
+
+ /**
+ * Temporary. Remove this log by February 2027.
+ *
+ * @param array $row
+ */
+ private static function logRegistrationConfig(array $row) {
+ global $CFG;
+ // TODO: Remove this registration-source log by February 2027.
+ if ( ! isset($CFG) || ! is_object($CFG) || $CFG->getExtension('log_registration_keys', true) !== true ) {
+ return;
+ }
+ $key_id = U::get($row, 'key_id');
+ error_log('LTI config taken from registration'
+ .' key_id='.(is_numeric($key_id) ? (int) $key_id : '')
+ .' issuer='.$row['reg_issuer']
+ .' client_id='.$row['reg_client_id']);
+ }
+
+ /**
+ * Remember which URL a cached keyset came from without changing the key's own URL.
+ *
+ * @param mixed $url
+ * @param mixed $keyset
+ * @return mixed
+ */
+ private static function keysetCacheForUrl($url, $keyset) {
+ if ( ! is_string($keyset) || ! is_string($url) || trim($url) === '' ) {
+ return $keyset;
+ }
+ $decoded = json_decode($keyset, true);
+ if ( ! is_array($decoded) || ! isset($decoded['keys']) || ! is_array($decoded['keys']) ) {
+ return $keyset;
+ }
+ $decoded['tsugi_keyset_url'] = trim($url);
+ $encoded = json_encode($decoded, JSON_UNESCAPED_SLASHES);
+ return is_string($encoded) ? $encoded : $keyset;
+ }
+
+ /**
+ * @param mixed $keyset
+ */
+ private static function cachedKeysetUrl($keyset) {
+ if ( ! is_string($keyset) || $keyset === '' ) return null;
+ $decoded = json_decode($keyset, true);
+ if ( ! is_array($decoded) || ! isset($decoded['tsugi_keyset_url']) || ! is_string($decoded['tsugi_keyset_url']) ) {
+ return null;
+ }
+ $url = trim($decoded['tsugi_keyset_url']);
+ return $url === '' ? null : $url;
+ }
+
+ /**
+ * @param array $row
+ */
+ private static function clearInboundRegistrationColumns(array &$row) {
+ unset(
+ $row['reg_issuer'],
+ $row['reg_client_id'],
+ $row['reg_oidc_auth_url'],
+ $row['reg_keyset_url'],
+ $row['reg_token_url'],
+ $row['reg_token_audience']
+ );
+ }
+
/**
* Load the data from our lti_ tables using one long LEFT JOIN
*
@@ -1173,10 +1316,18 @@ public static function loadAllData($p, $profile_table, $post) {
$sql = "SELECT ";
}
+ $registration_sql = self::inboundRegistrationSql($p, 'k');
+ // TODO: Remove this lti_registration existence gate by February 2027.
+ $have_registration = $registration_sql['join'] !== '';
$sql .= "k.key_id, k.key_key, k.secret, k.new_secret, k.settings_url AS key_settings_url,
k.login_at AS key_login_at, k.settings AS key_settings,
k.lms_issuer, k.lms_client, k.lms_oidc_auth, k.lms_keyset_url,
- k.lms_token_url, k.lms_token_audience, k.lms_cache_keyset, k.lms_cache_pubkey, k.lms_cache_kid,
+ k.lms_token_url, k.lms_token_audience, k.lms_cache_keyset, k.lms_cache_pubkey, k.lms_cache_kid,";
+ if ( $have_registration ) {
+ $sql .= "
+ ".$registration_sql['select'].",";
+ }
+ $sql .= "
n.nonce,
c.context_id, c.title AS context_title, context_sha256, c.context_key as context_key,
c.settings_url AS context_settings_url,
@@ -1226,6 +1377,9 @@ public static function loadAllData($p, $profile_table, $post) {
}
$sql .="\nFROM {$p}lti_key AS k";
+ if ( $have_registration ) {
+ $sql .= "\n".$registration_sql['join'];
+ }
// TODO: Collapse a few weeks after 05-27-2019
if ( $LTI13 ) {
@@ -1268,12 +1422,41 @@ public static function loadAllData($p, $profile_table, $post) {
// Add the WHERE clause
if ( $LTI13 ) {
// TODO: Index lms_issuer_sha256
- // Match tenant by issuer + client_id only; accept any deployment_id from the LMS.
+ // Match by issuer + client_id only; accept any deployment_id from the LMS.
// The launch JWT's deployment_id is still copied into $row at runtime for LTI 1.3
// services (e.g. AGS token requests).
+ // A complete registration is found by its own issuer and client.
+ // An incomplete one stays on the key identity, so it cannot answer
+ // for a different platform. A complete registration's old key
+ // identity is not eligible either.
$sql .= "\nWHERE (
- (k.lms_issuer_sha256 IS NULL OR k.lms_issuer_sha256 = :issuer_sha256)
- AND k.lms_client = :issuer_client
+ ";
+ if ( $have_registration ) {
+ $sql .= "(
+ (
+ reg.issuer IS NULL OR reg.issuer = ''
+ OR reg.client_id IS NULL OR reg.client_id = ''
+ OR reg.oidc_auth_url IS NULL OR reg.oidc_auth_url = ''
+ OR reg.keyset_url IS NULL OR reg.keyset_url = ''
+ OR reg.token_url IS NULL OR reg.token_url = ''
+ )
+ AND (k.lms_issuer_sha256 IS NULL OR k.lms_issuer_sha256 = :issuer_sha256)
+ AND k.lms_client = :issuer_client
+ )
+ OR (
+ reg.issuer IS NOT NULL AND reg.issuer <> ''
+ AND reg.client_id IS NOT NULL AND reg.client_id <> ''
+ AND reg.oidc_auth_url IS NOT NULL AND reg.oidc_auth_url <> ''
+ AND reg.keyset_url IS NOT NULL AND reg.keyset_url <> ''
+ AND reg.token_url IS NOT NULL AND reg.token_url <> ''
+ AND SHA2(reg.issuer, 256) = :issuer_sha256
+ AND reg.client_id = :issuer_client
+ )";
+ } else {
+ $sql .= "(k.lms_issuer_sha256 IS NULL OR k.lms_issuer_sha256 = :issuer_sha256)
+ AND k.lms_client = :issuer_client";
+ }
+ $sql .= "
)
AND (k.deleted IS NULL OR k.deleted = 0)
";
@@ -1352,6 +1535,7 @@ public static function loadAllData($p, $profile_table, $post) {
// die(); // Debug
$row = $PDOX->rowDie($sql, $parms);
// echo("\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 9e39a4d20..81414ad16 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,536 @@ 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 $row
+ */
+ public static function keyTypeHtml(array $row) {
+ $label = htmlspecialchars(self::keyTypeLabel($row), ENT_QUOTES, 'UTF-8');
+ $id = (int) U::get($row, 'lti_registration_id');
+ if ( $id < 1 ) {
+ return $label;
+ }
+ $href = 'registration-detail?lti_registration_id='.$id;
+ $link = 'Registration ';
+ return str_replace('Registration', $link, $label);
+ }
+
+ /**
+ * Hand-entered inbound registrations for the key admin screens.
+ *
+ * @return array>
+ */
+ public static function inboundRegistrationChoices() {
+ global $PDOX, $CFG;
+
+ $rows = $PDOX->allRowsDie(
+ "SELECT lti_registration_id, title, issuer, client_id
+ FROM {$CFG->dbprefix}lti_registration
+ ORDER BY title, issuer, client_id, lti_registration_id",
+ array()
+ );
+ return is_array($rows) ? $rows : array();
+ }
+
+ /**
+ * @param int $id
+ * @return array|null
+ */
+ public static function inboundRegistrationById($id) {
+ global $PDOX, $CFG;
+
+ $id = (int) $id;
+ if ( $id < 1 ) {
+ return null;
+ }
+ $row = $PDOX->rowDie(
+ "SELECT lti_registration_id, title, notes, issuer, client_id, oidc_auth_url, keyset_url,
+ token_url, token_audience, unlock_code
+ FROM {$CFG->dbprefix}lti_registration
+ WHERE lti_registration_id = :id",
+ array(':id' => $id)
+ );
+ return is_array($row) ? $row : null;
+ }
+
+ /**
+ * Keys that point at one inbound registration.
+ *
+ * @param int $id
+ * @return array>
+ */
+ public static function keysForInboundRegistration($id) {
+ global $PDOX, $CFG;
+
+ $id = (int) $id;
+ if ( $id < 1 ) {
+ return array();
+ }
+ $rows = $PDOX->allRowsDie(
+ "SELECT key_id, key_title, key_key, secret, lms_issuer, lms_client,
+ lms_oidc_auth, lms_keyset_url, lms_token_url, deploy_key, lti_registration_id
+ FROM {$CFG->dbprefix}lti_key
+ WHERE lti_registration_id = :id
+ ORDER BY key_title, key_id",
+ array(':id' => $id)
+ );
+ return is_array($rows) ? $rows : array();
+ }
+
+ /**
+ * Registrations with this key's issuer, client id, and platform URLs.
+ *
+ * @param array $key
+ * @return array>
+ */
+ public static function registrationsMatchingKeyPlatform(array $key) {
+ global $PDOX, $CFG;
+
+ $issuer = self::trimToNull(U::get($key, 'lms_issuer'));
+ $client = self::trimToNull(U::get($key, 'lms_client'));
+ $oidc = self::trimToNull(U::get($key, 'lms_oidc_auth'));
+ $keyset = self::trimToNull(U::get($key, 'lms_keyset_url'));
+ $token = self::trimToNull(U::get($key, 'lms_token_url'));
+ if ( $issuer === null || $client === null || $oidc === null || $keyset === null || $token === null ) {
+ return array();
+ }
+ $rows = $PDOX->allRowsDie(
+ "SELECT lti_registration_id, title, issuer, client_id, oidc_auth_url, keyset_url, token_url
+ FROM {$CFG->dbprefix}lti_registration
+ WHERE issuer = :issuer AND client_id = :client",
+ array(':issuer' => $issuer, ':client' => $client)
+ );
+ if ( ! is_array($rows) ) {
+ return array();
+ }
+ $matches = array();
+ foreach ( $rows as $row ) {
+ if ( self::trimToNull(U::get($row, 'oidc_auth_url')) !== $oidc ) continue;
+ if ( self::trimToNull(U::get($row, 'keyset_url')) !== $keyset ) continue;
+ if ( self::trimToNull(U::get($row, 'token_url')) !== $token ) continue;
+ $matches[] = $row;
+ }
+ return $matches;
+ }
+
+ /**
+ * Note when a saved key already lines up with a registration.
+ *
+ * @param array $key
+ */
+ public static function matchingRegistrationNote(array $key) {
+ $matches = self::registrationsMatchingKeyPlatform($key);
+ if ( count($matches) < 1 ) {
+ return '';
+ }
+ $links = array();
+ foreach ( $matches as $match ) {
+ $id = (int) U::get($match, 'lti_registration_id');
+ $href = 'registration-detail?lti_registration_id='.$id;
+ $label = htmlspecialchars(self::inboundRegistrationLabel($match), ENT_QUOTES, 'UTF-8');
+ $links[] = ''.$label.' ';
+ }
+ $linked = (int) U::get($key, 'lti_registration_id');
+ $same = count($matches) === 1 && $linked > 0 && (int) U::get($matches[0], 'lti_registration_id') === $linked;
+ if ( $same ) {
+ $text = 'This registration matches this key\'s issuer, client id, and platform URLs: ';
+ } else if ( count($matches) === 1 ) {
+ $text = 'A registration already matches this key\'s issuer, client id, and platform URLs: ';
+ } else {
+ $text = 'These registrations match this key\'s issuer, client id, and platform URLs: ';
+ }
+ return ''.$text.implode(', ', $links).'.
'."\n";
+ }
+
+ /**
+ * @param array $row
+ */
+ public static function inboundRegistrationLabel(array $row) {
+ $issuer = (string) U::get($row, 'issuer', '');
+ $client = U::get($row, 'client_id');
+ $title = self::trimToNull(U::get($row, 'title'));
+ $client_label = U::isNotEmpty($client) ? (string) $client : '(no client id)';
+ $parts = array();
+ if ( $title !== null ) $parts[] = $title;
+ if ( $issuer !== '' ) $parts[] = $issuer;
+ $parts[] = $client_label;
+ return implode(' / ', $parts);
+ }
+
+ /**
+ * Platform columns copied onto a key. Emptying a registration link clears these.
+ *
+ * @return array
+ */
+ public static function keyPlatformFields() {
+ return array('lms_issuer', 'lms_client', 'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience');
+ }
+
+ /**
+ * Shown under the registration control. The rule separates it from the platform fields.
+ *
+ * @param bool $edit
+ * @param int $selectedId
+ */
+ private static function registrationPlatformFieldsNote($edit, $selectedId = 0) {
+ $html = '';
+ if ( ! $edit ) {
+ $html .= "The issuer, client id, and platform URLs below stay on this key unless you empty them.
\n";
+ }
+ if ( $edit ) {
+ $shown = ((int) $selectedId) > 0 ? '' : ' style="display:none"';
+ $html .= "\n"
+ ."
After you have associated this key with a registration, you can empty the issuer, client id, and platform URLs on this key.
\n"
+ ."
\n
\n"
+ ." \n"
+ ."Empty the issuer, client id, and platform URLs on this key\n"
+ ." \n"
+ ."
Checked, these fields are cleared when you save. Unchecked, they stay on the key.
\n"
+ ."
\n"
+ ."
\n"
+ ."\n";
+ }
+ $html .= " \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 "LTI 1.3 registration
\nNone
\n"
+ .self::registrationPlatformFieldsNote(false);
+ }
+ $row = self::inboundRegistrationById($selectedId);
+ if ( ! is_array($row) ) {
+ return "LTI 1.3 registration
\nMissing registration ".$selectedId."
\n"
+ .self::registrationPlatformFieldsNote(false);
+ }
+ $href = 'registration-detail?lti_registration_id='.$selectedId;
+ $label = htmlspecialchars(self::inboundRegistrationLabel($row), ENT_QUOTES, 'UTF-8');
+ return "LTI 1.3 registration
\n{$label}
\n"
+ .self::registrationPlatformFieldsNote(false);
+ }
+
+ $choices = self::inboundRegistrationChoices();
+ $html = "\nLTI 1.3 registration \n";
+ $html .= "\n";
+ if ( count($choices) < 1 ) {
+ $html .= "No Registrations Available \n";
+ } else {
+ $placeholder = $selectedId < 1 ? ' selected' : '';
+ $html .= "Select \n";
+ foreach ( $choices as $choice ) {
+ $id = (int) U::get($choice, 'lti_registration_id');
+ $selected = $id === $selectedId ? ' selected' : '';
+ $label = htmlspecialchars(self::inboundRegistrationLabel($choice), ENT_QUOTES, 'UTF-8');
+ $html .= "{$label} \n";
+ }
+ }
+ $html .= " \n \n
\n";
+ $html .= self::registrationPlatformFieldsNote(true, $selectedId);
+ return $html;
+ }
+
+ /**
+ * Store the chosen registration id. Empty the key's platform fields only when asked.
+ *
+ * @return bool False when the posted id is not a registration.
+ */
+ public static function applyPostedRegistrationToKey() {
+ if ( ! array_key_exists('lti_registration_id', $_POST) ) {
+ U::flashError('Choose a registration from the list.');
+ return false;
+ }
+ $raw = $_POST['lti_registration_id'];
+ if ( $raw === null || $raw === '' || $raw === '0' ) {
+ $_POST['lti_registration_id'] = null;
+ return true;
+ }
+ $raw = trim((string) $raw);
+ $registration = ctype_digit($raw) && (int) $raw > 0 ? self::inboundRegistrationById((int) $raw) : null;
+ if ( ! is_array($registration) ) {
+ U::flashError('Choose a registration from the list.');
+ return false;
+ }
+ $_POST['lti_registration_id'] = (int) $raw;
+ if ( (string) U::get($_POST, 'empty_key_lti13_fields') === '1' ) {
+ if ( ! self::registrationCanReplaceKey($registration) ) {
+ U::flashError('This registration needs an issuer, client id, and the platform URLs before the key fields can be emptied.');
+ return false;
+ }
+ foreach ( self::keyPlatformFields() as $field ) {
+ $_POST[$field] = null;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * A registration can stand in for the key only when the launch would use it.
+ *
+ * @param array $row
+ */
+ private static function registrationCanReplaceKey(array $row) {
+ foreach ( array('issuer', 'client_id', 'oidc_auth_url', 'keyset_url', 'token_url') as $field ) {
+ if ( ! U::isNotEmpty(U::get($row, $field)) ) return false;
+ }
+ return true;
+ }
+
+ /**
+ * Insert or update a hand-entered registration. Unused columns stay at their defaults.
+ *
+ * @param int|null $id Null inserts.
+ * @param array $post
+ * @return int|false
+ */
+ public static function saveInboundRegistration($id, array $post, $announce = true) {
+ global $PDOX, $CFG;
+
+ $issuer = self::trimToNull(U::get($post, 'issuer'));
+ $client = self::trimToNull(U::get($post, 'client_id'));
+ $values = array(
+ ':issuer' => $issuer,
+ ':client' => $client,
+ ':oidc' => self::trimToNull(U::get($post, 'oidc_auth_url')),
+ ':keyset' => self::trimToNull(U::get($post, 'keyset_url')),
+ ':token' => self::trimToNull(U::get($post, 'token_url')),
+ ':audience' => self::trimToNull(U::get($post, 'token_audience')),
+ ':unlock' => self::trimToNull(U::get($post, 'unlock_code')),
+ ':title' => self::trimToNull(U::get($post, 'title')),
+ ':notes' => self::trimToNull(U::get($post, 'notes')),
+ );
+ if ( $issuer === null ) {
+ if ( $announce ) U::flashError('Issuer is required');
+ return false;
+ }
+ $identity = \Tsugi\Util\LTI::ascii255First(array(
+ 'Issuer' => $issuer,
+ 'Client id' => $client,
+ ));
+ if ( is_string($identity) ) {
+ if ( $announce ) U::flashError($identity);
+ return false;
+ }
+ if ( $client !== null ) {
+ $dup_sql = "SELECT lti_registration_id FROM {$CFG->dbprefix}lti_registration
+ WHERE issuer = :issuer AND client_id = :client";
+ $dup_parms = array(':issuer' => $issuer, ':client' => $client);
+ if ( $id ) {
+ $dup_sql .= " AND lti_registration_id <> :id";
+ $dup_parms[':id'] = (int) $id;
+ }
+ $existing = $PDOX->rowDie($dup_sql, $dup_parms);
+ if ( is_array($existing) ) {
+ if ( $announce ) U::flashError('A registration with this issuer and client id already exists');
+ return false;
+ }
+ }
+
+ $table = "{$CFG->dbprefix}lti_registration";
+ if ( $id ) {
+ $values[':id'] = (int) $id;
+ $sql = "UPDATE {$table} SET
+ title = :title, notes = :notes,
+ issuer = :issuer, client_id = :client, oidc_auth_url = :oidc,
+ keyset_url = :keyset, token_url = :token, token_audience = :audience,
+ unlock_code = :unlock, updated_at = NOW()
+ WHERE lti_registration_id = :id";
+ $q = $PDOX->queryReturnError($sql, $values);
+ if ( ! $q->success ) {
+ if ( $announce ) U::flashError('Could not update registration');
+ return false;
+ }
+ if ( $announce ) U::flashSuccess('Registration updated');
+ return (int) $id;
+ }
+
+ $user_id = null;
+ if ( \Tsugi\Core\ReqScope::isLoggedInLegacy() ) {
+ $logged_in = (int) \Tsugi\Core\ReqScope::loggedInUserIdLegacy();
+ if ( $logged_in > 0 ) $user_id = $logged_in;
+ }
+ $values[':guid'] = \Tsugi\Core\Guid::uuid7();
+ $values[':user'] = $user_id;
+ $sql = "INSERT INTO {$table}
+ (guid, title, notes, issuer, client_id, oidc_auth_url, keyset_url, token_url, token_audience,
+ unlock_code, registration_method, created_by_user_id, created_at, updated_at)
+ VALUES (UNHEX(:guid), :title, :notes, :issuer, :client, :oidc, :keyset, :token, :audience,
+ :unlock, 'manual', :user, NOW(), NOW())";
+ $q = $PDOX->queryReturnError($sql, $values);
+ if ( ! $q->success ) {
+ if ( $announce ) U::flashError('Could not insert registration');
+ return false;
+ }
+ if ( $announce ) U::flashSuccess('Registration inserted');
+ return (int) $PDOX->lastInsertId();
+ }
+
+ /**
+ * Check or create a registration from the LTI 1.3 fields on a key form.
+ * Does not update the key. Audience and unlock code are copied when present.
+ *
+ * @param array $source Key form fields (lms_*) or registration fields.
+ * @param bool $create
+ * @return array
+ */
+ public static function registrationFromKeyRequest(array $source, $create) {
+ global $PDOX, $CFG;
+
+ $post = array(
+ 'issuer' => self::trimToNull(U::get($source, 'lms_issuer', U::get($source, 'issuer'))),
+ 'client_id' => self::trimToNull(U::get($source, 'lms_client', U::get($source, 'client_id'))),
+ 'oidc_auth_url' => self::trimToNull(U::get($source, 'lms_oidc_auth', U::get($source, 'oidc_auth_url'))),
+ 'keyset_url' => self::trimToNull(U::get($source, 'lms_keyset_url', U::get($source, 'keyset_url'))),
+ 'token_url' => self::trimToNull(U::get($source, 'lms_token_url', U::get($source, 'token_url'))),
+ 'token_audience' => self::trimToNull(U::get($source, 'lms_token_audience', U::get($source, 'token_audience'))),
+ 'unlock_code' => self::trimToNull(U::get($source, 'unlock_code')),
+ 'title' => self::trimToNull(U::get($source, 'key_title', U::get($source, 'title'))),
+ 'notes' => self::trimToNull(U::get($source, 'notes')),
+ );
+ $required = array(
+ 'issuer' => 'Issuer',
+ 'client_id' => 'Client id',
+ 'oidc_auth_url' => 'OIDC login URL',
+ 'keyset_url' => 'Keyset URL',
+ 'token_url' => 'Token URL',
+ );
+ $missing = array();
+ foreach ( $required as $key => $label ) {
+ if ( $post[$key] === null ) $missing[] = $label;
+ }
+ $shown = array(
+ 'Title' => $post['title'],
+ 'Issuer' => $post['issuer'],
+ 'Client id' => $post['client_id'],
+ 'OIDC login URL' => $post['oidc_auth_url'],
+ 'Keyset URL' => $post['keyset_url'],
+ 'Token URL' => $post['token_url'],
+ 'Token audience' => $post['token_audience'],
+ 'Unlock code' => $post['unlock_code'],
+ );
+ if ( count($missing) > 0 ) {
+ return array(
+ 'ok' => false,
+ 'error' => 'Required fields are missing: '.implode(', ', $missing).'.',
+ 'fields' => $shown,
+ );
+ }
+ $identity = \Tsugi\Util\LTI::ascii255First(array(
+ 'Issuer' => $post['issuer'],
+ 'Client id' => $post['client_id'],
+ ));
+ if ( is_string($identity) ) {
+ return array('ok' => false, 'error' => $identity, 'fields' => $shown);
+ }
+ $existing = $PDOX->rowDie(
+ "SELECT lti_registration_id FROM {$CFG->dbprefix}lti_registration
+ WHERE issuer = :issuer AND client_id = :client",
+ array(':issuer' => $post['issuer'], ':client' => $post['client_id'])
+ );
+ if ( is_array($existing) ) {
+ return array(
+ 'ok' => false,
+ 'error' => 'A registration with this issuer and client id already exists.',
+ 'existing_id' => (int) $existing['lti_registration_id'],
+ 'fields' => $shown,
+ );
+ }
+ if ( ! $create ) {
+ return array('ok' => true, 'fields' => $shown);
+ }
+ $id = self::saveInboundRegistration(null, $post, false);
+ if ( ! $id ) {
+ return array('ok' => false, 'error' => 'Could not create registration.', 'fields' => $shown);
+ }
+ $row = self::inboundRegistrationById($id);
+ $label = is_array($row) ? self::inboundRegistrationLabel($row) : (string) $id;
+ return array('ok' => true, 'id' => (int) $id, 'label' => $label, 'fields' => $shown);
+ }
+
+ /**
+ * @param mixed $value
+ * @return string|null
+ */
+ private static function trimToNull($value) {
+ if ( ! is_string($value) ) {
+ return null;
+ }
+ $value = trim($value);
+ return $value === '' ? null : $value;
+ }
+
/**
* Pre-save checks for a tenant key.
*
diff --git a/lib/src/Services/Plus/GradeSync.php b/lib/src/Services/Plus/GradeSync.php
index 66df97568..49f2fa923 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 4b6c1dc00..93e37618c 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/UI/CrudForm.php b/lib/src/UI/CrudForm.php
index 60b565e9f..7d85c229e 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");
echo(\Tsugi\Controllers\Tool::csrfField()."\n");
+ if ( is_string($extraHtml) && $extraHtml !== '' ) echo($extraHtml);
for($i=0; $i < count($fields); $i++ ) {
$field = $fields[$i];
@@ -80,6 +81,7 @@ public static function insertForm($fields, $from_location, $titles=false, $field
echo(' '."\n");
}
echo("\n");
+ self::echoHtmlAfterField($extraHtml, $field);
}
echo(' '."\n");
@@ -210,7 +212,7 @@ public static function handleInsert($tablename, $fields, $binaryHex = array()) {
* @param $titles An array of fields->titles
*/
public static function updateForm($row, $fields, $current, $from_location,
- $allow_edit=false, $allow_delete=false, $extra_buttons=false, $titles=false, $checkboxes=false)
+ $allow_edit=false, $allow_delete=false, $extra_buttons=false, $titles=false, $checkboxes=false, $extraHtml='')
{
$key = $fields['0'];
if ( !isset($_REQUEST[$key]) ) {
@@ -246,6 +248,7 @@ public static function updateForm($row, $fields, $current, $from_location,
}
echo("\n");
+ if ( is_string($extraHtml) && $extraHtml !== '' ) echo($extraHtml);
for($i=0; $i < count($fields); $i++ ) {
$field = $fields[$i];
@@ -263,6 +266,7 @@ public static function updateForm($row, $fields, $current, $from_location,
} else {
echo('
'.htmlent_utf8($value)."
\n");
}
+ self::echoHtmlAfterField($extraHtml, $field);
continue;
}
@@ -291,6 +295,7 @@ public static function updateForm($row, $fields, $current, $from_location,
echo(' '."\n");
}
echo("\n");
+ self::echoHtmlAfterField($extraHtml, $field);
}
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 000000000..6842e4c1c
--- /dev/null
+++ b/lib/tests/Core/InboundRegistrationTest.php
@@ -0,0 +1,342 @@
+ 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();
+ }
+ }
+
+ 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 960d77f68..a466567fa 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 1cc288883..bd205138b 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 8e1949b68..094dd8588 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 1d2d19a0b..c424aad6f 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 a7f15d638..31b8ea9b4 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, '/');
From fe5b3533745369a5393313773f18588c97d3af3b Mon Sep 17 00:00:00 2001
From: Charles Severance
Date: Sat, 21 Nov 2026 22:42:28 -0500
Subject: [PATCH 3/5] Drop the platform keyset cache when a key or registration
is saved.
The upgrade stops if the registration column cannot be added, so a missing column is not recorded as success. Dynamic registration still writes the new client id on the key only.
Co-authored-by: Cursor
---
.cursor/rules/coderabbit-fixes-stay-local.mdc | 12 +++
lib/src/Controllers/Instructor.php | 3 +
lib/src/Controllers/Settings.php | 3 +
.../templates/Admin/key/key-detail.php | 3 +
.../templates/Admin/key/key-settings.php | 2 +
.../Admin/key/registration-detail.php | 1 +
lib/src/Core/LTIX.php | 38 +++++++++
lib/src/Services/Admin/AdminService.php | 1 +
lib/src/Services/Lti/database.php | 28 ++++---
.../Services/Settings/DynamicRegistration.php | 5 ++
lib/tests/Core/InboundRegistrationTest.php | 83 +++++++++++++++++++
11 files changed, 168 insertions(+), 11 deletions(-)
create mode 100644 .cursor/rules/coderabbit-fixes-stay-local.mdc
diff --git a/.cursor/rules/coderabbit-fixes-stay-local.mdc b/.cursor/rules/coderabbit-fixes-stay-local.mdc
new file mode 100644
index 000000000..e80257f4e
--- /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/lib/src/Controllers/Instructor.php b/lib/src/Controllers/Instructor.php
index 2dbd0b7b6..7cf791cd9 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 8fc9dbcb5..4e402d53b 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/key-detail.php b/lib/src/Controllers/templates/Admin/key/key-detail.php
index e3999416b..108a9db4c 100644
--- a/lib/src/Controllers/templates/Admin/key/key-detail.php
+++ b/lib/src/Controllers/templates/Admin/key/key-detail.php
@@ -127,6 +127,9 @@
$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($key_id);
+ }
header('Location: '.$from_location);
return;
}
diff --git a/lib/src/Controllers/templates/Admin/key/key-settings.php b/lib/src/Controllers/templates/Admin/key/key-settings.php
index 23b478c68..d5e6d3bd8 100644
--- a/lib/src/Controllers/templates/Admin/key/key-settings.php
+++ b/lib/src/Controllers/templates/Admin/key/key-settings.php
@@ -45,6 +45,7 @@
);
if ( $stmt->success ) {
+ LTIX::clearKeysetCache($key_id);
U::flashSuccess("Key settings updated successfully");
} else {
U::flashError("Failed to update settings");
@@ -59,6 +60,7 @@
);
if ( $stmt->success ) {
+ LTIX::clearKeysetCache($key_id);
U::flashSuccess("Key settings cleared successfully");
} else {
U::flashError("Failed to clear settings");
diff --git a/lib/src/Controllers/templates/Admin/key/registration-detail.php b/lib/src/Controllers/templates/Admin/key/registration-detail.php
index b5d9cbf5e..d36127483 100644
--- a/lib/src/Controllers/templates/Admin/key/registration-detail.php
+++ b/lib/src/Controllers/templates/Admin/key/registration-detail.php
@@ -27,6 +27,7 @@
}
if ( isset($_POST['doDelete']) ) {
+ LTIX::clearKeysetCacheForRegistration($registration_id);
$gone = $PDOX->queryReturnError(
"DELETE FROM {$CFG->dbprefix}lti_registration WHERE lti_registration_id = :id",
array(':id' => $registration_id)
diff --git a/lib/src/Core/LTIX.php b/lib/src/Core/LTIX.php
index a500e9dea..4d5300715 100644
--- a/lib/src/Core/LTIX.php
+++ b/lib/src/Core/LTIX.php
@@ -1247,6 +1247,44 @@ private static function logRegistrationConfig(array $row) {
.' client_id='.$row['reg_client_id']);
}
+ /**
+ * Drop a stored platform keyset. The next launch fetches it again.
+ *
+ * Call this when a key or a registration is saved. A launch's login
+ * timestamp and the cache fill itself are not saves.
+ *
+ * @param mixed $key_id
+ */
+ public static function clearKeysetCache($key_id) {
+ global $PDOX, $CFG;
+ $id = (int) $key_id;
+ if ( $id < 1 || ! isset($PDOX) || ! $PDOX || ! isset($CFG) ) return;
+ $PDOX->queryDie(
+ "UPDATE {$CFG->dbprefix}lti_key
+ SET lms_cache_keyset = NULL, lms_cache_pubkey = NULL, lms_cache_kid = NULL
+ WHERE key_id = :ID",
+ array(':ID' => $id)
+ );
+ }
+
+ /**
+ * Drop the stored platform keyset on every key that points at a registration.
+ *
+ * @param mixed $registration_id
+ */
+ public static function clearKeysetCacheForRegistration($registration_id) {
+ global $PDOX, $CFG;
+ $id = (int) $registration_id;
+ if ( $id < 1 || ! isset($PDOX) || ! $PDOX || ! isset($CFG) ) return;
+ if ( ! $PDOX->columnExists('lti_registration_id', $CFG->dbprefix.'lti_key') ) return;
+ $PDOX->queryDie(
+ "UPDATE {$CFG->dbprefix}lti_key
+ SET lms_cache_keyset = NULL, lms_cache_pubkey = NULL, lms_cache_kid = NULL
+ WHERE lti_registration_id = :ID",
+ array(':ID' => $id)
+ );
+ }
+
/**
* Remember which URL a cached keyset came from without changing the key's own URL.
*
diff --git a/lib/src/Services/Admin/AdminService.php b/lib/src/Services/Admin/AdminService.php
index 81414ad16..f800ad368 100644
--- a/lib/src/Services/Admin/AdminService.php
+++ b/lib/src/Services/Admin/AdminService.php
@@ -1757,6 +1757,7 @@ public static function saveInboundRegistration($id, array $post, $announce = tru
if ( $announce ) U::flashError('Could not update registration');
return false;
}
+ \Tsugi\Core\LTIX::clearKeysetCacheForRegistration((int) $id);
if ( $announce ) U::flashSuccess('Registration updated');
return (int) $id;
}
diff --git a/lib/src/Services/Lti/database.php b/lib/src/Services/Lti/database.php
index 26095f9d6..14e116a06 100644
--- a/lib/src/Services/Lti/database.php
+++ b/lib/src/Services/Lti/database.php
@@ -1836,6 +1836,9 @@
echo("Upgrading: ".$sql." \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
@@ -2552,17 +2555,20 @@
$inbound_table = "{$p}lti_registration";
$key_registration_fk = "{$p}lti_key_ibfk_1";
if ( $PDOX->metadata($key_table) !== false
- && $PDOX->metadata($inbound_table) !== false
- && $PDOX->columnExists('lti_registration_id', $key_table)
- && ! $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");
+ && $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) ) {
diff --git a/lib/src/Services/Settings/DynamicRegistration.php b/lib/src/Services/Settings/DynamicRegistration.php
index 29d568f8b..5a3d49773 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/tests/Core/InboundRegistrationTest.php b/lib/tests/Core/InboundRegistrationTest.php
index 6842e4c1c..481e79983 100644
--- a/lib/tests/Core/InboundRegistrationTest.php
+++ b/lib/tests/Core/InboundRegistrationTest.php
@@ -300,6 +300,89 @@ public function testLookupUsesRegistrationIdentityOnlyWhenTheRegistrationIsCompl
}
}
+ 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(
From fce1cbe9a867ea5043eff5fe4e7ff6461f963cbe Mon Sep 17 00:00:00 2001
From: Charles Severance
Date: Sat, 21 Nov 2026 23:15:14 -0500
Subject: [PATCH 4/5] Keep the registration foreign key index so upgrade stops
trying to drop it.
Co-authored-by: Cursor
---
lib/src/Services/Lti/database.php | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/lib/src/Services/Lti/database.php b/lib/src/Services/Lti/database.php
index 14e116a06..98b238ea5 100644
--- a/lib/src/Services/Lti/database.php
+++ b/lib/src/Services/Lti/database.php
@@ -1923,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";
From 79272db9f25f639e2da4ac9fda82cad1b80a5126 Mon Sep 17 00:00:00 2001
From: Charles Severance
Date: Sat, 21 Nov 2026 23:16:43 -0500
Subject: [PATCH 5/5] Stop reporting identity columns that are already
varchar(255) ascii.
Co-authored-by: Cursor
---
lib/src/Services/Lti/database.php | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/lib/src/Services/Lti/database.php b/lib/src/Services/Lti/database.php
index 98b238ea5..1d53d7c3b 100644
--- a/lib/src/Services/Lti/database.php
+++ b/lib/src/Services/Lti/database.php
@@ -2994,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];
@@ -3086,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';