first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Turnitin, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+13
View File
@@ -0,0 +1,13 @@
# LTI 1.3 Tool Library
A library used for building IMS-certified LTI 1.3 tool providers in PHP.
This library is a fork of the [packbackbooks/lti-1-3-php-library](https://github.com/packbackbooks/lti-1-3-php-library), patched specifically for use in [Moodle](https://github.com/moodle/moodle).
It is currently based on version [6.0.0 of the packbackbooks/lti-1-3-php-library](https://github.com/packbackbooks/lti-1-3-php-library/releases/tag/v6.0.0) library.
The following changes are included so that the library may be used with Moodle:
* Replace the phpseclib dependency with openssl equivalent call in public key generation code.
Please see the original [README](https://github.com/packbackbooks/lti-1-3-php-library/blob/master/README.md) for more information about the upstream library.
+20
View File
@@ -0,0 +1,20 @@
LTI 1.3 Tool Library import instructions
This library is a patched for use in Moodle - it requires the following changes be applied on top of the packback upstream base:
1. Removal of phpseclib dependency (replaces a single call with openssl equivalent)
To upgrade to a new version of this library:
1. Clone the latest version of the upstream library from github:
https://github.com/packbackbooks/lti-1-3-php-library/tags
2. Apply the changes mentioned above from the moodle-fixes branch of this repository:
https://github.com/snake/lti-1-3-php-library/tree/moodle-fixes
Apply these commits on top of the upstream clone.
3. Replace lib/lti1p3/src/ with the library's /src directory
4. Copy LICENSE.md to lib/lti1p3/
5. Copy README.md to lib/lti1p3/
6. Update the library entry in lib/thirdpartylibs.xml
7. Update the dependency note in lib/php-jwt/readme_moodle.txt, recording the version of php-jwt lib/lti1p3 depends on, if needed.
8. Check the upstream library's release notes and UPGRADES.md for any backwards incompatible changes to names, etc.
Moodle's calling code may require updates if changes are breaking - so check this and make any changes if needed.
9. Run all unit tests in enrol/lti and auth/lti.
10. Regression test Moodle-to-Moodle LTI using LTI Advantage (not legacy) using the relevant MDLQA tests as a guide.
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace Packback\Lti1p3\Concerns;
use Packback\Lti1p3\Helpers\Helpers;
trait Arrayable
{
abstract public function getArray(): array;
public function toArray(): array
{
return Helpers::filterOutNulls($this->getArray());
}
}
@@ -0,0 +1,13 @@
<?php
namespace Packback\Lti1p3\Concerns;
trait JsonStringable
{
use Arrayable;
public function __toString(): string
{
return json_encode($this->toArray());
}
}
@@ -0,0 +1,74 @@
<?php
namespace Packback\Lti1p3\DeepLinkResources;
use DateTime;
use Packback\Lti1p3\Concerns\Arrayable;
use Packback\Lti1p3\LtiException;
class DateTimeInterval
{
use Arrayable;
public const ERROR_NO_START_OR_END = 'Either a start or end time must be specified.';
public const ERROR_START_GT_END = 'The start time cannot be greater than end time.';
public function __construct(
private ?DateTime $start = null,
private ?DateTime $end = null
) {
$this->validateStartAndEnd();
}
public static function new(): self
{
return new DateTimeInterval();
}
public function getArray(): array
{
if (!isset($this->start) && !isset($this->end)) {
throw new LtiException(self::ERROR_NO_START_OR_END);
}
$this->validateStartAndEnd();
return [
'startDateTime' => $this->start?->format(DateTime::ATOM),
'endDateTime' => $this->end?->format(DateTime::ATOM),
];
}
public function setStart(?DateTime $start): self
{
$this->start = $start;
return $this;
}
public function getStart(): ?DateTime
{
return $this->start;
}
public function setEnd(?DateTime $end): self
{
$this->end = $end;
return $this;
}
public function getEnd(): ?DateTime
{
return $this->end;
}
/**
* @throws LtiException
*/
private function validateStartAndEnd(): void
{
if (isset($this->start) && isset($this->end) && $this->start > $this->end) {
throw new LtiException(self::ERROR_START_GT_END);
}
}
}
@@ -0,0 +1,30 @@
<?php
namespace Packback\Lti1p3\DeepLinkResources;
trait HasDimensions
{
public function setWidth(?int $width): self
{
$this->width = $width;
return $this;
}
public function getWidth(): ?int
{
return $this->width;
}
public function setHeight(?int $height): self
{
$this->height = $height;
return $this;
}
public function getHeight(): ?int
{
return $this->height;
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Packback\Lti1p3\DeepLinkResources;
use Packback\Lti1p3\Concerns\Arrayable;
class Icon
{
use Arrayable, HasDimensions;
public function __construct(
private string $url,
private int $width,
private int $height
) {
}
public static function new(string $url, int $width, int $height): self
{
return new Icon($url, $width, $height);
}
public function getArray(): array
{
return [
'url' => $this->url,
'width' => $this->width,
'height' => $this->height,
];
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getUrl(): string
{
return $this->url;
}
}
@@ -0,0 +1,43 @@
<?php
namespace Packback\Lti1p3\DeepLinkResources;
use Packback\Lti1p3\Concerns\Arrayable;
class Iframe
{
use Arrayable, HasDimensions;
public function __construct(
private ?string $src = null,
private ?int $width = null,
private ?int $height = null
) {
}
public static function new(): self
{
return new Iframe();
}
public function getArray(): array
{
return [
'width' => $this->width,
'height' => $this->height,
'src' => $this->src,
];
}
public function setSrc(?string $src): self
{
$this->src = $src;
return $this;
}
public function getSrc(): ?string
{
return $this->src;
}
}
@@ -0,0 +1,210 @@
<?php
namespace Packback\Lti1p3\DeepLinkResources;
use Packback\Lti1p3\Concerns\Arrayable;
use Packback\Lti1p3\LtiConstants;
use Packback\Lti1p3\LtiLineitem;
class Resource
{
use Arrayable;
private string $type = LtiConstants::DL_RESOURCE_LINK_TYPE;
private ?string $title = null;
private ?string $text = null;
private ?string $url = null;
private ?LtiLineitem $line_item = null;
private ?Icon $icon = null;
private ?Icon $thumbnail = null;
private array $custom_params = [];
private string $target = 'iframe';
private ?Iframe $iframe = null;
private ?Window $window = null;
private ?DateTimeInterval $availability_interval = null;
private ?DateTimeInterval $submission_interval = null;
public static function new(): self
{
return new Resource();
}
public function getArray(): array
{
$resource = [
'type' => $this->type,
'title' => $this->title,
'text' => $this->text,
'url' => $this->url,
'icon' => $this->icon?->toArray(),
'thumbnail' => $this->thumbnail?->toArray(),
'iframe' => $this->iframe?->toArray(),
'window' => $this->window?->toArray(),
'available' => $this->availability_interval?->toArray(),
'submission' => $this->submission_interval?->toArray(),
];
if (!empty($this->custom_params)) {
$resource['custom'] = $this->custom_params;
}
if (isset($this->line_item)) {
$resource['lineItem'] = [
'scoreMaximum' => $this->line_item->getScoreMaximum(),
'label' => $this->line_item->getLabel(),
];
}
// Kept for backwards compatibility
if (!isset($this->iframe) && !isset($this->window)) {
$resource['presentation'] = [
'documentTarget' => $this->target,
];
}
return $resource;
}
public function getType(): string
{
return $this->type;
}
public function setType(string $value): self
{
$this->type = $value;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $value): self
{
$this->title = $value;
return $this;
}
public function getText(): ?string
{
return $this->text;
}
public function setText(?string $value): self
{
$this->text = $value;
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(?string $value): self
{
$this->url = $value;
return $this;
}
public function getLineItem(): ?LtiLineitem
{
return $this->line_item;
}
public function setLineItem(?LtiLineitem $value): self
{
$this->line_item = $value;
return $this;
}
public function setIcon(?Icon $icon): self
{
$this->icon = $icon;
return $this;
}
public function getIcon(): ?Icon
{
return $this->icon;
}
public function setThumbnail(?Icon $thumbnail): self
{
$this->thumbnail = $thumbnail;
return $this;
}
public function getThumbnail(): ?Icon
{
return $this->thumbnail;
}
public function getCustomParams(): array
{
return $this->custom_params;
}
public function setCustomParams(array $value): self
{
$this->custom_params = $value;
return $this;
}
public function getIframe(): ?Iframe
{
return $this->iframe;
}
public function setIframe(?Iframe $iframe): self
{
$this->iframe = $iframe;
return $this;
}
public function getWindow(): ?Window
{
return $this->window;
}
public function setWindow(?Window $window): self
{
$this->window = $window;
return $this;
}
public function getAvailabilityInterval(): ?DateTimeInterval
{
return $this->availability_interval;
}
public function setAvailabilityInterval(?DateTimeInterval $availabilityInterval): self
{
$this->availability_interval = $availabilityInterval;
return $this;
}
public function getSubmissionInterval(): ?DateTimeInterval
{
return $this->submission_interval;
}
public function setSubmissionInterval(?DateTimeInterval $submissionInterval): self
{
$this->submission_interval = $submissionInterval;
return $this;
}
}
@@ -0,0 +1,57 @@
<?php
namespace Packback\Lti1p3\DeepLinkResources;
use Packback\Lti1p3\Concerns\Arrayable;
class Window
{
use Arrayable, HasDimensions;
public function __construct(
private ?string $target_name = null,
private ?int $width = null,
private ?int $height = null,
private ?string $window_features = null
) {
}
public static function new(): self
{
return new Window();
}
public function getArray(): array
{
return [
'targetName' => $this->target_name,
'width' => $this->width,
'height' => $this->height,
'windowFeatures' => $this->window_features,
];
}
public function setTargetName(?string $targetName): self
{
$this->target_name = $targetName;
return $this;
}
public function getTargetName(): ?string
{
return $this->target_name;
}
public function setWindowFeatures(?string $windowFeatures): self
{
$this->window_features = $windowFeatures;
return $this;
}
public function getWindowFeatures(): ?string
{
return $this->window_features;
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace Packback\Lti1p3\Helpers;
class Helpers
{
public static function filterOutNulls(array $array): array
{
return array_filter($array, fn ($value) => !is_null($value));
}
public static function buildUrlWithQueryParams(string $url, array $params = []): string
{
if (empty($params)) {
return $url;
}
if (parse_url($url, PHP_URL_QUERY)) {
$separator = '&';
} else {
$separator = '?';
}
return $url.$separator.http_build_query($params, '');
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace Packback\Lti1p3\Interfaces;
interface ICache
{
public function getLaunchData(string $key): ?array;
public function cacheLaunchData(string $key, array $jwtBody): void;
public function cacheNonce(string $nonce, string $state): void;
public function checkNonceIsValid(string $nonce, string $state): bool;
public function cacheAccessToken(string $key, string $accessToken): void;
public function getAccessToken(string $key): ?string;
public function clearAccessToken(string $key): void;
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Packback\Lti1p3\Interfaces;
interface ICookie
{
public function getCookie(string $name): ?string;
public function setCookie(string $name, string $value, int $exp = 3600, array $options = []): void;
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Packback\Lti1p3\Interfaces;
interface IDatabase
{
public function findRegistrationByIssuer(string $iss, ?string $clientId = null): ?ILtiRegistration;
public function findDeployment(string $iss, string $deploymentId, ?string $clientId = null): ?ILtiDeployment;
}
@@ -0,0 +1,11 @@
<?php
namespace Packback\Lti1p3\Interfaces;
/** @internal */
interface ILtiDeployment
{
public function getDeploymentId();
public function setDeploymentId($deployment_id): ILtiDeployment;
}
@@ -0,0 +1,39 @@
<?php
namespace Packback\Lti1p3\Interfaces;
/** @internal */
interface ILtiRegistration
{
public function getIssuer();
public function setIssuer(string $issuer): ILtiRegistration;
public function getClientId();
public function setClientId(string $clientId): ILtiRegistration;
public function getKeySetUrl(): ?string;
public function setKeySetUrl(string $keySetUrl): ILtiRegistration;
public function getAuthTokenUrl(): ?string;
public function setAuthTokenUrl(?string $authTokenUrl): ILtiRegistration;
public function getAuthLoginUrl(): ?string;
public function setAuthLoginUrl(string $authLoginUrl): ILtiRegistration;
public function getAuthServer(): ?string;
public function setAuthServer(string $authServer): ILtiRegistration;
public function getToolPrivateKey();
public function setToolPrivateKey(string $toolPrivateKey): ILtiRegistration;
public function getKid();
public function setKid(string $kid): ILtiRegistration;
}
@@ -0,0 +1,33 @@
<?php
namespace Packback\Lti1p3\Interfaces;
use Psr\Http\Message\ResponseInterface;
/** @internal */
interface ILtiServiceConnector
{
public function getAccessToken(ILtiRegistration $registration, array $scopes): string;
public function makeRequest(IServiceRequest $request): ResponseInterface;
public function getResponseBody(ResponseInterface $response): ?array;
public function getResponseHeaders(ResponseInterface $response): ?array;
public function makeServiceRequest(
ILtiRegistration $registration,
array $scopes,
IServiceRequest $request,
bool $shouldRetry = true
): array;
public function getAll(
ILtiRegistration $registration,
array $scopes,
IServiceRequest $request,
?string $key
): array;
public function setDebuggingMode(bool $enable): ILtiServiceConnector;
}
@@ -0,0 +1,13 @@
<?php
namespace Packback\Lti1p3\Interfaces;
/** @internal */
interface IMessageValidator
{
public static function getMessageType(): string;
public static function canValidate(array $jwtBody): bool;
public static function validate(array $jwtBody): void;
}
@@ -0,0 +1,34 @@
<?php
namespace Packback\Lti1p3\Interfaces;
use Packback\Lti1p3\LtiMessageLaunch;
/**
* This is an optional interface if an LTI 1.3 tool supports migrations
* from LTI 1.1 compatible installations.
*
* To use this, just have whatever class you create that implements IDatabase
* also implement this interface.
*/
interface IMigrationDatabase extends IDatabase
{
/**
* Using the LtiMessageLaunch return an array of matching LTI 1.1 keys
*
* @return array<\Packback\Lti1p3\Lti1p1Key>
*/
public function findLti1p1Keys(LtiMessageLaunch $launch): array;
/**
* Given an LtiMessageLaunch, return true if this tool should migrate from 1.1 to 1.3
*/
public function shouldMigrate(LtiMessageLaunch $launch): bool;
/**
* This method should create a 1.3 deployment in your DB based on the LtiMessageLaunch.
* Previous to this, we validated the oauth_consumer_key_sign to ensure this migration
* can safely occur.
*/
public function migrateFromLti1p1(LtiMessageLaunch $launch): ?ILtiDeployment;
}
@@ -0,0 +1,31 @@
<?php
namespace Packback\Lti1p3\Interfaces;
/** @internal */
interface IServiceRequest
{
public function getMethod(): string;
public function getUrl(): string;
public function getPayload(): array;
public function setUrl(string $url): IServiceRequest;
public function setAccessToken(string $accessToken): IServiceRequest;
public function setBody(string $body): IServiceRequest;
public function setPayload(array $payload): IServiceRequest;
public function setAccept(string $accept): IServiceRequest;
public function setContentType(string $contentType): IServiceRequest;
public function getErrorPrefix(): string;
public function getMaskResponseLogs(): bool;
public function setMaskResponseLogs(bool $maskResponseLogs): self;
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace Packback\Lti1p3;
use Firebase\JWT\JWT;
use Packback\Lti1p3\Interfaces\IDatabase;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
class JwksEndpoint
{
public function __construct(private array $keys)
{
}
public static function new(array $keys): self
{
return new JwksEndpoint($keys);
}
public static function fromIssuer(IDatabase $database, string $issuer): self
{
$registration = $database->findRegistrationByIssuer($issuer);
return new JwksEndpoint([$registration->getKid() => $registration->getToolPrivateKey()]);
}
public static function fromRegistration(ILtiRegistration $registration): self
{
return new JwksEndpoint([$registration->getKid() => $registration->getToolPrivateKey()]);
}
public function getPublicJwks(): array
{
$jwks = [];
foreach ($this->keys as $kid => $private_key) {
$key_res = openssl_pkey_get_private($private_key);
$key_details = openssl_pkey_get_details($key_res);
$components = [
'kty' => 'RSA',
'alg' => 'RS256',
'use' => 'sig',
'e' => JWT::urlsafeB64Encode($key_details['rsa']['e']),
'n' => JWT::urlsafeB64Encode($key_details['rsa']['n']),
'kid' => $kid,
];
$jwks[] = $components;
}
return ['keys' => $jwks];
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace Packback\Lti1p3;
/**
* Used for migrations from LTI 1.1 to LTI 1.3
*
* @see IMigrationDatabase
*/
class Lti1p1Key
{
private ?string $key;
private ?string $secret;
public function __construct(?array $key = null)
{
$this->key = $key['key'] ?? null;
$this->secret = $key['secret'] ?? null;
}
public function getKey(): ?string
{
return $this->key;
}
public function setKey(string $key): self
{
$this->key = $key;
return $this;
}
public function getSecret(): ?string
{
return $this->secret;
}
public function setSecret(string $secret): self
{
$this->secret = $secret;
return $this;
}
/**
* Create a signature using the key and secret
*
* @see https://www.imsglobal.org/spec/lti/v1p3/migr#oauth_consumer_key_sign
*/
public function sign(string $deploymentId, string $iss, string $clientId, string $exp, string $nonce): string
{
$signatureComponents = [
$this->getKey(),
$deploymentId,
$iss,
$clientId,
$exp,
$nonce,
];
$baseString = implode('&', $signatureComponents);
$utf8String = mb_convert_encoding($baseString, 'utf8', mb_detect_encoding($baseString));
$hash = hash_hmac('sha256', $utf8String, $this->getSecret(), true);
return base64_encode($hash);
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
use Packback\Lti1p3\Interfaces\ILtiServiceConnector;
use Packback\Lti1p3\Interfaces\IServiceRequest;
abstract class LtiAbstractService
{
public function __construct(
private ILtiServiceConnector $serviceConnector,
private ILtiRegistration $registration,
private array $serviceData
) {
}
public function getServiceData(): array
{
return $this->serviceData;
}
public function setServiceData(array $serviceData): self
{
$this->serviceData = $serviceData;
return $this;
}
abstract public function getScope(): array;
protected function validateScopes(array $scopes): void
{
if (empty(array_intersect($scopes, $this->getScope()))) {
throw new LtiException('Missing required scope');
}
}
protected function makeServiceRequest(IServiceRequest $request): array
{
return $this->serviceConnector->makeServiceRequest(
$this->registration,
$this->getScope(),
$request,
);
}
protected function getAll(IServiceRequest $request, ?string $key = null): array
{
return $this->serviceConnector->getAll(
$this->registration,
$this->getScope(),
$request,
$key
);
}
}
@@ -0,0 +1,206 @@
<?php
namespace Packback\Lti1p3;
class LtiAssignmentsGradesService extends LtiAbstractService
{
public const CONTENTTYPE_SCORE = 'application/vnd.ims.lis.v1.score+json';
public const CONTENTTYPE_LINEITEM = 'application/vnd.ims.lis.v2.lineitem+json';
public const CONTENTTYPE_LINEITEMCONTAINER = 'application/vnd.ims.lis.v2.lineitemcontainer+json';
public const CONTENTTYPE_RESULTCONTAINER = 'application/vnd.ims.lis.v2.resultcontainer+json';
public function getScope(): array
{
return $this->getServiceData()['scope'];
}
// https://www.imsglobal.org/spec/lti-ags/v2p0#assignment-and-grade-service-claim
// When an LTI message is launching a resource associated to one and only one lineitem,
// the claim must include the endpoint URL for accessing the associated line item;
// in all other cases, this property must be either blank or not included in the claim.
public function getResourceLaunchLineItem(): ?LtiLineitem
{
$serviceData = $this->getServiceData();
if (empty($serviceData['lineitem'])) {
return null;
}
return LtiLineitem::new()->setId($serviceData['lineitem']);
}
public function putGrade(LtiGrade $grade, ?LtiLineitem $lineitem = null)
{
$this->validateScopes([LtiConstants::AGS_SCOPE_SCORE]);
$lineitem = $this->ensureLineItemExists($lineitem);
$scoreUrl = $this->appendLineItemPath($lineitem, '/scores');
$request = new ServiceRequest(
ServiceRequest::METHOD_POST,
$scoreUrl,
ServiceRequest::TYPE_SYNC_GRADE
);
$request->setBody($grade);
$request->setContentType(static::CONTENTTYPE_SCORE);
return $this->makeServiceRequest($request);
}
public function findLineItem(LtiLineitem $newLineItem): ?LtiLineitem
{
$lineitems = $this->getLineItems();
foreach ($lineitems as $lineitem) {
if ($this->isMatchingLineitem($lineitem, $newLineItem)) {
return new LtiLineitem($lineitem);
}
}
return null;
}
public function updateLineitem(LtiLineitem $lineitemToUpdate): LtiLineitem
{
$request = new ServiceRequest(
ServiceRequest::METHOD_PUT,
$lineitemToUpdate->getId(),
ServiceRequest::TYPE_UPDATE_LINEITEM
);
$request->setBody($lineitemToUpdate)
->setContentType(static::CONTENTTYPE_LINEITEM)
->setAccept(static::CONTENTTYPE_LINEITEM);
$updatedLineitem = $this->makeServiceRequest($request);
return new LtiLineitem($updatedLineitem['body']);
}
public function createLineitem(LtiLineitem $newLineItem): LtiLineitem
{
$request = new ServiceRequest(
ServiceRequest::METHOD_POST,
$this->getServiceData()['lineitems'],
ServiceRequest::TYPE_CREATE_LINEITEM
);
$request->setBody($newLineItem)
->setContentType(static::CONTENTTYPE_LINEITEM)
->setAccept(static::CONTENTTYPE_LINEITEM);
$createdLineItem = $this->makeServiceRequest($request);
return new LtiLineitem($createdLineItem['body']);
}
public function deleteLineitem(): array
{
$request = new ServiceRequest(
ServiceRequest::METHOD_DELETE,
$this->getServiceData()['lineitem'],
ServiceRequest::TYPE_DELETE_LINEITEM
);
return $this->makeServiceRequest($request);
}
public function findOrCreateLineitem(LtiLineitem $newLineItem): LtiLineitem
{
return $this->findLineItem($newLineItem) ?? $this->createLineitem($newLineItem);
}
public function getGrades(?LtiLineitem $lineitem = null)
{
$lineitem = $this->ensureLineItemExists($lineitem);
$resultsUrl = $this->appendLineItemPath($lineitem, '/results');
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$resultsUrl,
ServiceRequest::TYPE_GET_GRADES
);
$request->setAccept(static::CONTENTTYPE_RESULTCONTAINER);
return $this->getAll($request);
}
public function getLineItems(): array
{
$this->validateScopes([LtiConstants::AGS_SCOPE_LINEITEM, LtiConstants::AGS_SCOPE_LINEITEM_READONLY]);
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$this->getServiceData()['lineitems'],
ServiceRequest::TYPE_GET_LINEITEMS
);
$request->setAccept(static::CONTENTTYPE_LINEITEMCONTAINER);
$lineitems = $this->getAll($request);
// If there is only one item, then wrap it in an array so the foreach works
if (isset($lineitems['body']['id'])) {
$lineitems['body'] = [$lineitems['body']];
}
return $lineitems;
}
public function getLineItem(string $url): LtiLineitem
{
$this->validateScopes([LtiConstants::AGS_SCOPE_LINEITEM, LtiConstants::AGS_SCOPE_LINEITEM_READONLY]);
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$url,
ServiceRequest::TYPE_GET_LINEITEM
);
$request->setAccept(static::CONTENTTYPE_LINEITEM);
$response = $this->makeServiceRequest($request)['body'];
return new LtiLineitem($response);
}
private function ensureLineItemExists(?LtiLineitem $lineitem = null): LtiLineitem
{
// If no line item is passed in, attempt to use the one associated with
// this launch.
if (!isset($lineitem)) {
$lineitem = $this->getResourceLaunchLineItem();
}
// If none exists still, create a default line item.
if (!isset($lineitem)) {
$defaultLineitem = LtiLineitem::new()
->setLabel('default')
->setScoreMaximum(100);
$lineitem = $this->createLineitem($defaultLineitem);
}
// If the line item does not contain an ID, find or create it.
if (empty($lineitem->getId())) {
$lineitem = $this->findOrCreateLineitem($lineitem);
}
return $lineitem;
}
private function isMatchingLineitem(array $lineitem, LtiLineitem $newLineItem): bool
{
return $newLineItem->getTag() == ($lineitem['tag'] ?? null) &&
$newLineItem->getResourceId() == ($lineitem['resourceId'] ?? null) &&
$newLineItem->getResourceLinkId() == ($lineitem['resourceLinkId'] ?? null);
}
private function appendLineItemPath(LtiLineitem $lineItem, string $suffix): string
{
$url = $lineItem->getId();
$pos = strpos($url, '?');
if ($pos === false) {
$url = $url.$suffix;
} else {
$url = substr_replace($url, $suffix, $pos, 0);
}
return $url;
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace Packback\Lti1p3;
class LtiConstants
{
public const V1_3 = '1.3.0';
// Required message claims
public const MESSAGE_TYPE = 'https://purl.imsglobal.org/spec/lti/claim/message_type';
public const VERSION = 'https://purl.imsglobal.org/spec/lti/claim/version';
public const DEPLOYMENT_ID = 'https://purl.imsglobal.org/spec/lti/claim/deployment_id';
public const TARGET_LINK_URI = 'https://purl.imsglobal.org/spec/lti/claim/target_link_uri';
public const RESOURCE_LINK = 'https://purl.imsglobal.org/spec/lti/claim/resource_link';
public const ROLES = 'https://purl.imsglobal.org/spec/lti/claim/roles';
public const FOR_USER = 'https://purl.imsglobal.org/spec/lti/claim/for_user';
// Optional message claims
public const CONTEXT = 'https://purl.imsglobal.org/spec/lti/claim/context';
public const CUSTOM = 'https://purl.imsglobal.org/spec/lti/claim/custom';
public const LAUNCH_PRESENTATION = 'https://purl.imsglobal.org/spec/lti/claim/launch_presentation';
public const LIS = 'https://purl.imsglobal.org/spec/lti/claim/lis';
public const LTI1P1 = 'https://purl.imsglobal.org/spec/lti/claim/lti1p1';
public const ROLE_SCOPE_MENTOR = 'https://purlimsglobal.org/spec/lti/claim/role_scope_mentor';
public const TOOL_PLATFORM = 'https://purl.imsglobal.org/spec/lti/claim/tool_platform';
// LTI DL
public const DL_CONTENT_ITEMS = 'https://purl.imsglobal.org/spec/lti-dl/claim/content_items';
public const DL_DATA = 'https://purl.imsglobal.org/spec/lti-dl/claim/data';
public const DL_DEEP_LINK_SETTINGS = 'https://purl.imsglobal.org/spec/lti-dl/claim/deep_linking_settings';
public const DL_RESOURCE_LINK_TYPE = 'ltiResourceLink';
// LTI NRPS
public const NRPS_CLAIM_SERVICE = 'https://purl.imsglobal.org/spec/lti-nrps/claim/namesroleservice';
public const NRPS_SCOPE_MEMBERSHIP_READONLY = 'https://purl.imsglobal.org/spec/lti-nrps/scope/contextmembership.readonly';
// LTI AGS
public const AGS_CLAIM_ENDPOINT = 'https://purl.imsglobal.org/spec/lti-ags/claim/endpoint';
public const AGS_SCOPE_LINEITEM = 'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem';
public const AGS_SCOPE_LINEITEM_READONLY = 'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem.readonly';
public const AGS_SCOPE_RESULT_READONLY = 'https://purl.imsglobal.org/spec/lti-ags/scope/result.readonly';
public const AGS_SCOPE_SCORE = 'https://purl.imsglobal.org/spec/lti-ags/scope/score';
// LTI GS
public const GS_CLAIM_SERVICE = 'https://purl.imsglobal.org/spec/lti-gs/claim/groupsservice';
// User Vocab
public const SYSTEM_ADMINISTRATOR = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#Administrator';
public const SYSTEM_NONE = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#None';
public const SYSTEM_ACCOUNTADMIN = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#AccountAdmin';
public const SYSTEM_CREATOR = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#Creator';
public const SYSTEM_SYSADMIN = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#SysAdmin';
public const SYSTEM_SYSSUPPORT = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#SysSupport';
public const SYSTEM_USER = 'http://purl.imsglobal.org/vocab/lis/v2/system/person#User';
public const INSTITUTION_ADMINISTRATOR = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Administrator';
public const INSTITUTION_FACULTY = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Faculty';
public const INSTITUTION_GUEST = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Guest';
public const INSTITUTION_NONE = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#None';
public const INSTITUTION_OTHER = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Other';
public const INSTITUTION_STAFF = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Staff';
public const INSTITUTION_STUDENT = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Student';
public const INSTITUTION_ALUMNI = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Alumni';
public const INSTITUTION_INSTRUCTOR = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Instructor';
public const INSTITUTION_LEARNER = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Learner';
public const INSTITUTION_MEMBER = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Member';
public const INSTITUTION_MENTOR = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Mentor';
public const INSTITUTION_OBSERVER = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#Observer';
public const INSTITUTION_PROSPECTIVESTUDENT = 'http://purl.imsglobal.org/vocab/lis/v2/institution/person#ProspectiveStudent';
public const MEMBERSHIP_ADMINISTRATOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Administrator';
public const MEMBERSHIP_CONTENTDEVELOPER = 'http://purl.imsglobal.org/vocab/lis/v2/membership#ContentDeveloper';
public const MEMBERSHIP_INSTRUCTOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Instructor';
public const MEMBERSHIP_LEARNER = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Learner';
public const MEMBERSHIP_MENTOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Mentor';
public const MEMBERSHIP_MANAGER = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Manager';
public const MEMBERSHIP_MEMBER = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Member';
public const MEMBERSHIP_OFFICER = 'http://purl.imsglobal.org/vocab/lis/v2/membership#Officer';
// Context sub-roles
public const MEMBERSHIP_EXTERNALINSTRUCTOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#ExternalInstructor';
public const MEMBERSHIP_GRADER = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#Grader';
public const MEMBERSHIP_GUESTINSTRUCTOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#GuestInstructor';
public const MEMBERSHIP_LECTURER = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#Lecturer';
public const MEMBERSHIP_PRIMARYINSTRUCTOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#PrimaryInstructor';
public const MEMBERSHIP_SECONDARYINSTRUCTOR = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#SecondaryInstructor';
public const MEMBERSHIP_TA = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#TeachingAssistant';
public const MEMBERSHIP_TAGROUP = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#TeachingAssistantGroup';
public const MEMBERSHIP_TAOFFERING = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#TeachingAssistantOffering';
public const MEMBERSHIP_TASECTION = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#TeachingAssistantSection';
public const MEMBERSHIP_TASECTIONASSOCIATION = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#TeachingAssistantSectionAssociation';
public const MEMBERSHIP_TATEMPLATE = 'http://purl.imsglobal.org/vocab/lis/v2/membership/Instructor#TeachingAssistantTemplate';
// Context Vocab
public const COURSE_TEMPLATE = 'http://purl.imsglobal.org/vocab/lis/v2/course#CourseTemplate';
public const COURSE_OFFERING = 'http://purl.imsglobal.org/vocab/lis/v2/course#CourseOffering';
public const COURSE_SECTION = 'http://purl.imsglobal.org/vocab/lis/v2/course#CourseSection';
public const COURSE_GROUP = 'http://purl.imsglobal.org/vocab/lis/v2/course#Group';
// Message Types
public const MESSAGE_TYPE_DEEPLINK = 'LtiDeepLinkingRequest';
public const MESSAGE_TYPE_DEEPLINK_RESPONSE = 'LtiDeepLinkingResponse';
public const MESSAGE_TYPE_RESOURCE = 'LtiResourceLinkRequest';
public const MESSAGE_TYPE_SUBMISSIONREVIEW = 'LtiSubmissionReviewRequest';
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace Packback\Lti1p3;
class LtiCourseGroupsService extends LtiAbstractService
{
public const CONTENTTYPE_CONTEXTGROUPCONTAINER = 'application/vnd.ims.lti-gs.v1.contextgroupcontainer+json';
public function getScope(): array
{
return $this->getServiceData()['scope'];
}
public function getGroups(): array
{
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$this->getServiceData()['context_groups_url'],
ServiceRequest::TYPE_GET_GROUPS
);
$request->setAccept(static::CONTENTTYPE_CONTEXTGROUPCONTAINER);
return $this->getAll($request, 'groups');
}
public function getSets(): array
{
// Sets are optional.
if (!isset($this->getServiceData()['context_group_sets_url'])) {
return [];
}
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$this->getServiceData()['context_group_sets_url'],
ServiceRequest::TYPE_GET_SETS
);
$request->setAccept(static::CONTENTTYPE_CONTEXTGROUPCONTAINER);
return $this->getAll($request, 'sets');
}
public function getGroupsBySet(): array
{
$groups = $this->getGroups();
$sets = $this->getSets();
$groupsBySet = [];
$unsetted = [];
foreach ($sets as $key => $set) {
$groupsBySet[$set['id']] = $set;
$groupsBySet[$set['id']]['groups'] = [];
}
foreach ($groups as $key => $group) {
if (isset($group['set_id']) && isset($groupsBySet[$group['set_id']])) {
$groupsBySet[$group['set_id']]['groups'][$group['id']] = $group;
} else {
$unsetted[$group['id']] = $group;
}
}
if (!empty($unsetted)) {
$groupsBySet['none'] = [
'name' => 'None',
'id' => 'none',
'groups' => $unsetted,
];
}
return $groupsBySet;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace Packback\Lti1p3;
use Firebase\JWT\JWT;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
class LtiDeepLink
{
public function __construct(
private ILtiRegistration $registration,
private string $deployment_id,
private array $deep_link_settings
) {
}
public function getResponseJwt(array $resources): string
{
$message_jwt = [
'iss' => $this->registration->getClientId(),
'aud' => [$this->registration->getIssuer()],
'exp' => time() + 600,
'iat' => time(),
'nonce' => LtiOidcLogin::secureRandomString('nonce-'),
LtiConstants::DEPLOYMENT_ID => $this->deployment_id,
LtiConstants::MESSAGE_TYPE => LtiConstants::MESSAGE_TYPE_DEEPLINK_RESPONSE,
LtiConstants::VERSION => LtiConstants::V1_3,
LtiConstants::DL_CONTENT_ITEMS => array_map(function ($resource) {
return $resource->toArray();
}, $resources),
];
// https://www.imsglobal.org/spec/lti-dl/v2p0/#deep-linking-request-message
// 'data' is an optional property which, if it exists, must be returned by the tool
if (isset($this->deep_link_settings['data'])) {
$message_jwt[LtiConstants::DL_DATA] = $this->deep_link_settings['data'];
}
return JWT::encode($message_jwt, $this->registration->getToolPrivateKey(), 'RS256', $this->registration->getKid());
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Interfaces\ILtiDeployment;
class LtiDeployment implements ILtiDeployment
{
public function __construct(
private $deployment_id
) {
}
public static function new($deployment_id): self
{
return new LtiDeployment($deployment_id);
}
public function getDeploymentId()
{
return $this->deployment_id;
}
public function setDeploymentId($deployment_id): self
{
$this->deployment_id = $deployment_id;
return $this;
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace Packback\Lti1p3;
use Exception;
class LtiException extends Exception
{
}
+172
View File
@@ -0,0 +1,172 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Concerns\JsonStringable;
class LtiGrade
{
use JsonStringable;
private $score_given;
private $score_maximum;
private $comment;
private $activity_progress;
private $grading_progress;
private $timestamp;
private $user_id;
private $submission_review;
private $canvas_extension;
public function __construct(?array $grade = null)
{
$this->score_given = $grade['scoreGiven'] ?? null;
$this->score_maximum = $grade['scoreMaximum'] ?? null;
$this->comment = $grade['comment'] ?? null;
$this->activity_progress = $grade['activityProgress'] ?? null;
$this->grading_progress = $grade['gradingProgress'] ?? null;
$this->timestamp = $grade['timestamp'] ?? null;
$this->user_id = $grade['userId'] ?? null;
$this->submission_review = $grade['submissionReview'] ?? null;
$this->canvas_extension = $grade['https://canvas.instructure.com/lti/submission'] ?? null;
}
public function getArray(): array
{
return [
'scoreGiven' => $this->score_given,
'scoreMaximum' => $this->score_maximum,
'comment' => $this->comment,
'activityProgress' => $this->activity_progress,
'gradingProgress' => $this->grading_progress,
'timestamp' => $this->timestamp,
'userId' => $this->user_id,
'submissionReview' => $this->submission_review,
'https://canvas.instructure.com/lti/submission' => $this->canvas_extension,
];
}
/**
* Static function to allow for method chaining without having to assign to a variable first.
*/
public static function new(): self
{
return new LtiGrade();
}
public function getScoreGiven()
{
return $this->score_given;
}
public function setScoreGiven($value): self
{
$this->score_given = $value;
return $this;
}
public function getScoreMaximum()
{
return $this->score_maximum;
}
public function setScoreMaximum($value): self
{
$this->score_maximum = $value;
return $this;
}
public function getComment()
{
return $this->comment;
}
public function setComment($comment): self
{
$this->comment = $comment;
return $this;
}
public function getActivityProgress()
{
return $this->activity_progress;
}
public function setActivityProgress($value): self
{
$this->activity_progress = $value;
return $this;
}
public function getGradingProgress()
{
return $this->grading_progress;
}
public function setGradingProgress($value): self
{
$this->grading_progress = $value;
return $this;
}
public function getTimestamp()
{
return $this->timestamp;
}
public function setTimestamp($value): self
{
$this->timestamp = $value;
return $this;
}
public function getUserId()
{
return $this->user_id;
}
public function setUserId($value): self
{
$this->user_id = $value;
return $this;
}
public function getSubmissionReview()
{
return $this->submission_review;
}
public function setSubmissionReview($value): self
{
$this->submission_review = $value;
return $this;
}
public function getCanvasExtension()
{
return $this->canvas_extension;
}
/**
* Add custom extensions for Canvas.
*
* Disclaimer: You should only set this if your LMS is Canvas.
* Some LMS (e.g. Schoology) include validation logic that will throw if there
* is unexpected data. And, the type of LMS cannot simply be inferred by their URL.
*
* @see https://documentation.instructure.com/doc/api/score.html
*/
public function setCanvasExtension($value): self
{
$this->canvas_extension = $value;
return $this;
}
}
@@ -0,0 +1,88 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Concerns\JsonStringable;
class LtiGradeSubmissionReview
{
use JsonStringable;
private $reviewable_status;
private $label;
private $url;
private $custom;
public function __construct(?array $gradeSubmission = null)
{
$this->reviewable_status = $gradeSubmission['reviewableStatus'] ?? null;
$this->label = $gradeSubmission['label'] ?? null;
$this->url = $gradeSubmission['url'] ?? null;
$this->custom = $gradeSubmission['custom'] ?? null;
}
public function getArray(): array
{
return [
'reviewableStatus' => $this->reviewable_status,
'label' => $this->label,
'url' => $this->url,
'custom' => $this->custom,
];
}
/**
* Static function to allow for method chaining without having to assign to a variable first.
*/
public static function new(): self
{
return new LtiGradeSubmissionReview();
}
public function getReviewableStatus()
{
return $this->reviewable_status;
}
public function setReviewableStatus($value): self
{
$this->reviewable_status = $value;
return $this;
}
public function getLabel()
{
return $this->label;
}
public function setLabel($value): self
{
$this->label = $value;
return $this;
}
public function getUrl()
{
return $this->url;
}
public function setUrl($url): self
{
$this->url = $url;
return $this;
}
public function getCustom()
{
return $this->custom;
}
public function setCustom($value): self
{
$this->custom = $value;
return $this;
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Concerns\JsonStringable;
class LtiLineitem
{
use JsonStringable;
private $id;
private $score_maximum;
private $label;
private $resource_id;
private $resource_link_id;
private $tag;
private $start_date_time;
private $end_date_time;
private ?bool $grades_released;
public function __construct(?array $lineitem = null)
{
$this->id = $lineitem['id'] ?? null;
$this->score_maximum = $lineitem['scoreMaximum'] ?? null;
$this->label = $lineitem['label'] ?? null;
$this->resource_id = $lineitem['resourceId'] ?? null;
$this->resource_link_id = $lineitem['resourceLinkId'] ?? null;
$this->tag = $lineitem['tag'] ?? null;
$this->start_date_time = $lineitem['startDateTime'] ?? null;
$this->end_date_time = $lineitem['endDateTime'] ?? null;
$this->grades_released = $lineitem['gradesReleased'] ?? null;
}
/**
* Static function to allow for method chaining without having to assign to a variable first.
*/
public static function new(?array $lineItem = null): self
{
return new LtiLineitem($lineItem);
}
public function getArray(): array
{
return [
'id' => $this->id,
'scoreMaximum' => $this->score_maximum,
'label' => $this->label,
'resourceId' => $this->resource_id,
'resourceLinkId' => $this->resource_link_id,
'tag' => $this->tag,
'startDateTime' => $this->start_date_time,
'endDateTime' => $this->end_date_time,
'gradesReleased' => $this->grades_released,
];
}
public function getId()
{
return $this->id;
}
public function setId($value): self
{
$this->id = $value;
return $this;
}
public function getLabel()
{
return $this->label;
}
public function setLabel($value): self
{
$this->label = $value;
return $this;
}
public function getScoreMaximum()
{
return $this->score_maximum;
}
public function setScoreMaximum($value): self
{
$this->score_maximum = $value;
return $this;
}
public function getResourceId()
{
return $this->resource_id;
}
public function setResourceId($value): self
{
$this->resource_id = $value;
return $this;
}
public function getResourceLinkId()
{
return $this->resource_link_id;
}
public function setResourceLinkId($value): self
{
$this->resource_link_id = $value;
return $this;
}
public function getTag()
{
return $this->tag;
}
public function setTag($value): self
{
$this->tag = $value;
return $this;
}
public function getStartDateTime()
{
return $this->start_date_time;
}
public function setStartDateTime($value): self
{
$this->start_date_time = $value;
return $this;
}
public function getEndDateTime()
{
return $this->end_date_time;
}
public function setEndDateTime($value): self
{
$this->end_date_time = $value;
return $this;
}
public function getGradesReleased(): ?bool
{
return $this->grades_released;
}
public function setGradesReleased(?bool $value): self
{
$this->grades_released = $value;
return $this;
}
}
+563
View File
@@ -0,0 +1,563 @@
<?php
namespace Packback\Lti1p3;
use Exception;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use GuzzleHttp\Exception\TransferException;
use Packback\Lti1p3\Interfaces\ICache;
use Packback\Lti1p3\Interfaces\ICookie;
use Packback\Lti1p3\Interfaces\IDatabase;
use Packback\Lti1p3\Interfaces\ILtiDeployment;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
use Packback\Lti1p3\Interfaces\ILtiServiceConnector;
use Packback\Lti1p3\Interfaces\IMigrationDatabase;
use Packback\Lti1p3\MessageValidators\DeepLinkMessageValidator;
use Packback\Lti1p3\MessageValidators\ResourceMessageValidator;
use Packback\Lti1p3\MessageValidators\SubmissionReviewMessageValidator;
class LtiMessageLaunch
{
public const TYPE_DEEPLINK = 'LtiDeepLinkingRequest';
public const TYPE_SUBMISSIONREVIEW = 'LtiSubmissionReviewRequest';
public const TYPE_RESOURCELINK = 'LtiResourceLinkRequest';
public const ERR_FETCH_PUBLIC_KEY = 'Failed to fetch public key.';
public const ERR_NO_PUBLIC_KEY = 'Unable to find public key.';
public const ERR_NO_MATCHING_PUBLIC_KEY = 'Unable to find a public key which matches your JWT.';
public const ERR_STATE_NOT_FOUND = 'Please make sure you have cookies enabled in this browser and that you are not in private or incognito mode';
public const ERR_MISSING_ID_TOKEN = 'Missing id_token.';
public const ERR_INVALID_ID_TOKEN = 'Invalid id_token, JWT must contain 3 parts';
public const ERR_MISSING_NONCE = 'Missing Nonce.';
public const ERR_INVALID_NONCE = 'Invalid Nonce.';
/**
* :issuerUrl and :clientId are used to substitute the queried issuerUrl
* and clientId. Do not change those substrings without changing how the
* error message is built.
*/
public const ERR_MISSING_REGISTRATION = 'LTI 1.3 Registration not found for Issuer :issuerUrl and Client ID :clientId. Please make sure the LMS has provided the right information, and that the LMS has been registered correctly in the tool.';
public const ERR_CLIENT_NOT_REGISTERED = 'Client id not registered for this issuer.';
public const ERR_NO_KID = 'No KID specified in the JWT Header.';
public const ERR_INVALID_SIGNATURE = 'Invalid signature on id_token';
public const ERR_MISSING_DEPLOYEMENT_ID = 'No deployment ID was specified';
public const ERR_NO_DEPLOYMENT = 'Unable to find deployment.';
public const ERR_INVALID_MESSAGE_TYPE = 'Invalid message type';
public const ERR_UNRECOGNIZED_MESSAGE_TYPE = 'Unrecognized message type.';
public const ERR_INVALID_MESSAGE = 'Message validation failed.';
public const ERR_INVALID_ALG = 'Invalid alg was specified in the JWT header.';
public const ERR_MISMATCHED_ALG_KEY = 'The alg specified in the JWT header is incompatible with the JWK key type.';
public const ERR_OAUTH_KEY_SIGN_NOT_VERIFIED = 'Unable to upgrade from LTI 1.1 to 1.3. No OAuth Consumer Key matched this signature.';
public const ERR_OAUTH_KEY_SIGN_MISSING = 'Unable to upgrade from LTI 1.1 to 1.3. The oauth_consumer_key_sign was not provided.';
private array $request;
private array $jwt;
private ?ILtiRegistration $registration;
private ?ILtiDeployment $deployment;
public string $launch_id;
// See https://www.imsglobal.org/spec/security/v1p1#approved-jwt-signing-algorithms.
private static $ltiSupportedAlgs = [
'RS256' => 'RSA',
'RS384' => 'RSA',
'RS512' => 'RSA',
'ES256' => 'EC',
'ES384' => 'EC',
'ES512' => 'EC',
];
public function __construct(
private IDatabase $db,
private ICache $cache,
private ICookie $cookie,
private ILtiServiceConnector $serviceConnector
) {
$this->launch_id = uniqid('lti1p3_launch_', true);
}
/**
* Static function to allow for method chaining without having to assign to a variable first.
*/
public static function new(
IDatabase $db,
ICache $cache,
ICookie $cookie,
ILtiServiceConnector $serviceConnector
): self {
return new LtiMessageLaunch($db, $cache, $cookie, $serviceConnector);
}
/**
* Load an LtiMessageLaunch from a Cache using a launch id.
*
* @throws LtiException Will throw an LtiException if validation fails or launch cannot be found
*/
public static function fromCache(
string $launch_id,
IDatabase $db,
ICache $cache,
ICookie $cookie,
ILtiServiceConnector $serviceConnector
): self {
$new = new LtiMessageLaunch($db, $cache, $cookie, $serviceConnector);
$new->launch_id = $launch_id;
$new->jwt = ['body' => $new->cache->getLaunchData($launch_id)];
return $new->validateRegistration();
}
public function setRequest(array $request): self
{
$this->request = $request;
return $this;
}
public function initialize(array $request): self
{
return $this->setRequest($request)
->validate()
->migrate()
->cacheLaunchData();
}
/**
* Validates all aspects of an incoming LTI message launch and caches the launch if successful.
*
* @throws LtiException Will throw an LtiException if validation fails
*/
public function validate(): self
{
return $this->validateState()
->validateJwtFormat()
->validateNonce()
->validateRegistration()
->validateJwtSignature()
->validateDeployment()
->validateMessage();
}
public function migrate(): self
{
if (!$this->shouldMigrate()) {
return $this->ensureDeploymentExists();
}
if (!isset($this->jwt['body'][LtiConstants::LTI1P1]['oauth_consumer_key_sign'])) {
throw new LtiException(static::ERR_OAUTH_KEY_SIGN_MISSING);
}
if (!$this->matchingLti1p1KeyExists()) {
throw new LtiException(static::ERR_OAUTH_KEY_SIGN_NOT_VERIFIED);
}
$this->deployment = $this->db->migrateFromLti1p1($this);
return $this->ensureDeploymentExists();
}
public function cacheLaunchData(): self
{
$this->cache->cacheLaunchData($this->launch_id, $this->jwt['body']);
return $this;
}
/**
* Returns whether or not the current launch can use the names and roles service.
*/
public function hasNrps(): bool
{
return isset($this->jwt['body'][LtiConstants::NRPS_CLAIM_SERVICE]['context_memberships_url']);
}
/**
* Fetches an instance of the names and roles service for the current launch.
*/
public function getNrps(): LtiNamesRolesProvisioningService
{
return new LtiNamesRolesProvisioningService(
$this->serviceConnector,
$this->registration,
$this->jwt['body'][LtiConstants::NRPS_CLAIM_SERVICE]
);
}
/**
* Returns whether or not the current launch can use the groups service.
*/
public function hasGs(): bool
{
return isset($this->jwt['body'][LtiConstants::GS_CLAIM_SERVICE]['context_groups_url']);
}
/**
* Fetches an instance of the groups service for the current launch.
*/
public function getGs(): LtiCourseGroupsService
{
return new LtiCourseGroupsService(
$this->serviceConnector,
$this->registration,
$this->jwt['body'][LtiConstants::GS_CLAIM_SERVICE]
);
}
/**
* Returns whether or not the current launch can use the assignments and grades service.
*/
public function hasAgs(): bool
{
return isset($this->jwt['body'][LtiConstants::AGS_CLAIM_ENDPOINT]);
}
/**
* Fetches an instance of the assignments and grades service for the current launch.
*/
public function getAgs(): LtiAssignmentsGradesService
{
return new LtiAssignmentsGradesService(
$this->serviceConnector,
$this->registration,
$this->jwt['body'][LtiConstants::AGS_CLAIM_ENDPOINT]
);
}
/**
* Returns whether or not the current launch is a deep linking launch.
*/
public function isDeepLinkLaunch(): bool
{
return $this->jwt['body'][LtiConstants::MESSAGE_TYPE] === static::TYPE_DEEPLINK;
}
/**
* Fetches a deep link that can be used to construct a deep linking response.
*/
public function getDeepLink(): LtiDeepLink
{
return new LtiDeepLink(
$this->registration,
$this->jwt['body'][LtiConstants::DEPLOYMENT_ID],
$this->jwt['body'][LtiConstants::DL_DEEP_LINK_SETTINGS]
);
}
/**
* Returns whether or not the current launch is a submission review launch.
*/
public function isSubmissionReviewLaunch(): bool
{
return $this->jwt['body'][LtiConstants::MESSAGE_TYPE] === static::TYPE_SUBMISSIONREVIEW;
}
/**
* Returns whether or not the current launch is a resource launch.
*/
public function isResourceLaunch(): bool
{
return $this->jwt['body'][LtiConstants::MESSAGE_TYPE] === static::TYPE_RESOURCELINK;
}
/**
* Fetches the decoded body of the JWT used in the current launch.
*/
public function getLaunchData(): array
{
return $this->jwt['body'];
}
/**
* Get the unique launch id for the current launch.
*/
public function getLaunchId(): string
{
return $this->launch_id;
}
public static function getMissingRegistrationErrorMsg(string $issuerUrl, ?string $clientId = null): string
{
// Guard against client ID being null
if (!isset($clientId)) {
$clientId = '(N/A)';
}
$search = [':issuerUrl', ':clientId'];
$replace = [$issuerUrl, $clientId];
return str_replace($search, $replace, static::ERR_MISSING_REGISTRATION);
}
/**
* @throws LtiException
*/
private function getPublicKey(): Key
{
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$this->registration->getKeySetUrl(),
ServiceRequest::TYPE_GET_KEYSET
);
// Download key set
try {
$response = $this->serviceConnector->makeRequest($request);
} catch (TransferException $e) {
throw new LtiException(static::ERR_NO_PUBLIC_KEY);
}
$publicKeySet = $this->serviceConnector->getResponseBody($response);
if (empty($publicKeySet)) {
// Failed to fetch public keyset from URL.
throw new LtiException(static::ERR_FETCH_PUBLIC_KEY);
}
// Find key used to sign the JWT (matches the KID in the header)
foreach ($publicKeySet['keys'] as $key) {
if ($key['kid'] == $this->jwt['header']['kid']) {
$key['alg'] = $this->getKeyAlgorithm($key);
try {
$keySet = JWK::parseKeySet([
'keys' => [$key],
]);
} catch (Exception $e) {
// Do nothing
}
if (isset($keySet[$key['kid']])) {
return $keySet[$key['kid']];
}
}
}
// Could not find public key with a matching kid and alg.
throw new LtiException(static::ERR_NO_MATCHING_PUBLIC_KEY);
}
/**
* If alg is omitted from the JWK, infer it from the JWT header alg.
* See https://datatracker.ietf.org/doc/html/rfc7517#section-4.4.
*/
private function getKeyAlgorithm(array $key): string
{
if (isset($key['alg'])) {
return $key['alg'];
}
// The header alg must match the key type (family) specified in the JWK's kty.
if ($this->jwtAlgMatchesJwkKty($key)) {
return $this->jwt['header']['alg'];
}
throw new LtiException(static::ERR_MISMATCHED_ALG_KEY);
}
private function jwtAlgMatchesJwkKty(array $key): bool
{
$jwtAlg = $this->jwt['header']['alg'];
return isset(self::$ltiSupportedAlgs[$jwtAlg]) &&
self::$ltiSupportedAlgs[$jwtAlg] === $key['kty'];
}
protected function validateState(): self
{
// Check State for OIDC.
if ($this->cookie->getCookie(LtiOidcLogin::COOKIE_PREFIX.$this->request['state']) !== $this->request['state']) {
// Error if state doesn't match
throw new LtiException(static::ERR_STATE_NOT_FOUND);
}
return $this;
}
protected function validateJwtFormat(): self
{
if (!isset($this->request['id_token'])) {
throw new LtiException(static::ERR_MISSING_ID_TOKEN);
}
// Get parts of JWT.
$jwt_parts = explode('.', $this->request['id_token']);
if (count($jwt_parts) !== 3) {
// Invalid number of parts in JWT.
throw new LtiException(static::ERR_INVALID_ID_TOKEN);
}
// Decode JWT headers.
$this->jwt['header'] = json_decode(JWT::urlsafeB64Decode($jwt_parts[0]), true);
// Decode JWT Body.
$this->jwt['body'] = json_decode(JWT::urlsafeB64Decode($jwt_parts[1]), true);
return $this;
}
protected function validateNonce(): self
{
if (!isset($this->jwt['body']['nonce'])) {
throw new LtiException(static::ERR_MISSING_NONCE);
}
if (!$this->cache->checkNonceIsValid($this->jwt['body']['nonce'], $this->request['state'])) {
throw new LtiException(static::ERR_INVALID_NONCE);
}
return $this;
}
protected function validateRegistration(): self
{
// Find registration.
$clientId = $this->getAud();
$issuerUrl = $this->jwt['body']['iss'];
$this->registration = $this->db->findRegistrationByIssuer($issuerUrl, $clientId);
if (!isset($this->registration)) {
throw new LtiException($this->getMissingRegistrationErrorMsg($issuerUrl, $clientId));
}
// Check client id.
if ($clientId !== $this->registration->getClientId()) {
// Client not registered.
throw new LtiException(static::ERR_CLIENT_NOT_REGISTERED);
}
return $this;
}
protected function validateJwtSignature(): self
{
if (!isset($this->jwt['header']['kid'])) {
throw new LtiException(static::ERR_NO_KID);
}
// Fetch public key.
$public_key = $this->getPublicKey();
// Validate JWT signature
try {
$headers = new \stdClass();
JWT::decode($this->request['id_token'], $public_key, $headers);
} catch (ExpiredException $e) {
// Error validating signature.
throw new LtiException(static::ERR_INVALID_SIGNATURE);
}
return $this;
}
protected function validateDeployment(): self
{
if (!isset($this->jwt['body'][LtiConstants::DEPLOYMENT_ID])) {
throw new LtiException(static::ERR_MISSING_DEPLOYEMENT_ID);
}
// Find deployment.
$client_id = $this->getAud();
$this->deployment = $this->db->findDeployment($this->jwt['body']['iss'], $this->jwt['body'][LtiConstants::DEPLOYMENT_ID], $client_id);
if (!$this->canMigrate()) {
return $this->ensureDeploymentExists();
}
return $this;
}
protected function validateMessage(): self
{
if (!isset($this->jwt['body'][LtiConstants::MESSAGE_TYPE])) {
// Unable to identify message type.
throw new LtiException(static::ERR_INVALID_MESSAGE_TYPE);
}
$validator = $this->getMessageValidator($this->jwt['body']);
if (!isset($validator)) {
throw new LtiException(static::ERR_UNRECOGNIZED_MESSAGE_TYPE);
}
$validator::validate($this->jwt['body']);
return $this;
}
private function getMessageValidator(array $jwtBody): ?string
{
$availableValidators = [
DeepLinkMessageValidator::class,
ResourceMessageValidator::class,
SubmissionReviewMessageValidator::class,
];
// Filter out validators that cannot validate the message
$applicableValidators = array_filter($availableValidators, function ($validator) use ($jwtBody) {
return $validator::canValidate($jwtBody);
});
// There should be 0-1 validators. This will either return the validator, or null if none apply.
return array_shift($applicableValidators);
}
private function getAud(): string
{
if (is_array($this->jwt['body']['aud'])) {
return $this->jwt['body']['aud'][0];
} else {
return $this->jwt['body']['aud'];
}
}
/**
* @throws LtiException
*/
private function ensureDeploymentExists(): self
{
if (!isset($this->deployment)) {
throw new LtiException(static::ERR_NO_DEPLOYMENT);
}
return $this;
}
public function canMigrate(): bool
{
return $this->db instanceof IMigrationDatabase;
}
private function shouldMigrate(): bool
{
return $this->canMigrate()
&& $this->db->shouldMigrate($this);
}
private function matchingLti1p1KeyExists(): bool
{
$keys = $this->db->findLti1p1Keys($this);
foreach ($keys as $key) {
if ($this->oauthConsumerKeySignMatches($key)) {
return true;
}
}
return false;
}
private function oauthConsumerKeySignMatches(Lti1p1Key $key): bool
{
return $this->jwt['body'][LtiConstants::LTI1P1]['oauth_consumer_key_sign'] === $this->getOauthSignature($key);
}
private function getOauthSignature(Lti1p1Key $key): string
{
return $key->sign(
$this->jwt['body'][LtiConstants::DEPLOYMENT_ID],
$this->jwt['body']['iss'],
$this->getAud(),
$this->jwt['body']['exp'],
$this->jwt['body']['nonce']
);
}
}
@@ -0,0 +1,32 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Helpers\Helpers;
class LtiNamesRolesProvisioningService extends LtiAbstractService
{
public const CONTENTTYPE_MEMBERSHIPCONTAINER = 'application/vnd.ims.lti-nrps.v2.membershipcontainer+json';
public function getScope(): array
{
return [LtiConstants::NRPS_SCOPE_MEMBERSHIP_READONLY];
}
/**
* @param array $options An array of options that can be passed with the context_membership_url such as rlid, since, etc.
*/
public function getMembers(array $options = []): array
{
$url = Helpers::buildUrlWithQueryParams($this->getServiceData()['context_memberships_url'], $options);
$request = new ServiceRequest(
ServiceRequest::METHOD_GET,
$url,
ServiceRequest::TYPE_GET_MEMBERSHIPS
);
$request->setAccept(static::CONTENTTYPE_MEMBERSHIPCONTAINER);
return $this->getAll($request, 'members');
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Helpers\Helpers;
use Packback\Lti1p3\Interfaces\ICache;
use Packback\Lti1p3\Interfaces\ICookie;
use Packback\Lti1p3\Interfaces\IDatabase;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
class LtiOidcLogin
{
public const COOKIE_PREFIX = 'lti1p3_';
public const ERROR_MSG_LAUNCH_URL = 'No launch URL configured';
public const ERROR_MSG_ISSUER = 'Could not find issuer';
public const ERROR_MSG_LOGIN_HINT = 'Could not find login hint';
public function __construct(
public IDatabase $db,
public ICache $cache,
public ICookie $cookie
) {
}
/**
* Static function to allow for method chaining without having to assign to a variable first.
*/
public static function new(IDatabase $db, ICache $cache, ICookie $cookie): self
{
return new LtiOidcLogin($db, $cache, $cookie);
}
/**
* Calculate the redirect location to return to based on an OIDC third party initiated login request.
*/
public function getRedirectUrl(string $launchUrl, array $request): string
{
// Validate request data.
$registration = $this->validateOidcLogin($request);
// Build OIDC Auth response.
$authParams = $this->getAuthParams($launchUrl, $registration->getClientId(), $request);
return Helpers::buildUrlWithQueryParams($registration->getAuthLoginUrl(), $authParams);
}
public function validateOidcLogin(array $request): ILtiRegistration
{
if (!isset($request['iss'])) {
throw new OidcException(static::ERROR_MSG_ISSUER);
}
if (!isset($request['login_hint'])) {
throw new OidcException(static::ERROR_MSG_LOGIN_HINT);
}
// Fetch registration
$clientId = $request['client_id'] ?? null;
$registration = $this->db->findRegistrationByIssuer($request['iss'], $clientId);
if (!isset($registration)) {
$errorMsg = LtiMessageLaunch::getMissingRegistrationErrorMsg($request['iss'], $clientId);
throw new OidcException($errorMsg);
}
return $registration;
}
public function getAuthParams(string $launchUrl, string $clientId, array $request): array
{
// Set cookie (short lived)
$state = static::secureRandomString('state-');
$this->cookie->setCookie(static::COOKIE_PREFIX.$state, $state, 60);
$nonce = static::secureRandomString('nonce-');
$this->cache->cacheNonce($nonce, $state);
$authParams = [
'scope' => 'openid', // OIDC Scope.
'response_type' => 'id_token', // OIDC response is always an id token.
'response_mode' => 'form_post', // OIDC response is always a form post.
'prompt' => 'none', // Don't prompt user on redirect.
'client_id' => $clientId, // Registered client id.
'redirect_uri' => $launchUrl, // URL to return to after login.
'state' => $state, // State to identify browser session.
'nonce' => $nonce, // Prevent replay attacks.
'login_hint' => $request['login_hint'], // Login hint to identify platform session.
];
if (isset($request['lti_message_hint'])) {
// LTI message hint to identify LTI context within the platform.
$authParams['lti_message_hint'] = $request['lti_message_hint'];
}
return $authParams;
}
public static function secureRandomString(string $prefix = ''): string
{
return $prefix.hash('sha256', random_bytes(64));
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
class LtiRegistration implements ILtiRegistration
{
private ?string $issuer;
private ?string $clientId;
private ?string $keySetUrl;
private ?string $authTokenUrl;
private ?string $authLoginUrl;
private ?string $authServer;
private ?string $toolPrivateKey;
private ?string $kid;
public function __construct(?array $registration = null)
{
$this->issuer = $registration['issuer'] ?? null;
$this->clientId = $registration['clientId'] ?? null;
$this->keySetUrl = $registration['keySetUrl'] ?? null;
$this->authTokenUrl = $registration['authTokenUrl'] ?? null;
$this->authLoginUrl = $registration['authLoginUrl'] ?? null;
$this->authServer = $registration['authServer'] ?? null;
$this->toolPrivateKey = $registration['toolPrivateKey'] ?? null;
$this->kid = $registration['kid'] ?? null;
}
public static function new(?array $registration = null): self
{
return new LtiRegistration($registration);
}
public function getIssuer()
{
return $this->issuer;
}
public function setIssuer(string $issuer): self
{
$this->issuer = $issuer;
return $this;
}
public function getClientId()
{
return $this->clientId;
}
public function setClientId(string $clientId): self
{
$this->clientId = $clientId;
return $this;
}
public function getKeySetUrl(): ?string
{
return $this->keySetUrl;
}
public function setKeySetUrl(?string $keySetUrl): self
{
$this->keySetUrl = $keySetUrl;
return $this;
}
public function getAuthTokenUrl(): ?string
{
return $this->authTokenUrl;
}
public function setAuthTokenUrl(?string $authTokenUrl): self
{
$this->authTokenUrl = $authTokenUrl;
return $this;
}
public function getAuthLoginUrl(): ?string
{
return $this->authLoginUrl;
}
public function setAuthLoginUrl(?string $authLoginUrl): self
{
$this->authLoginUrl = $authLoginUrl;
return $this;
}
public function getAuthServer(): ?string
{
return $this->authServer ?? $this->authTokenUrl;
}
public function setAuthServer(?string $authServer): self
{
$this->authServer = $authServer;
return $this;
}
public function getToolPrivateKey()
{
return $this->toolPrivateKey;
}
public function setToolPrivateKey(string $toolPrivateKey): self
{
$this->toolPrivateKey = $toolPrivateKey;
return $this;
}
public function getKid()
{
return $this->kid ?? hash('sha256', trim($this->issuer.$this->clientId));
}
public function setKid(string $kid): self
{
$this->kid = $kid;
return $this;
}
}
+251
View File
@@ -0,0 +1,251 @@
<?php
namespace Packback\Lti1p3;
use Exception;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Packback\Lti1p3\Interfaces\ICache;
use Packback\Lti1p3\Interfaces\ILtiRegistration;
use Packback\Lti1p3\Interfaces\ILtiServiceConnector;
use Packback\Lti1p3\Interfaces\IServiceRequest;
use Psr\Http\Message\ResponseInterface;
class LtiServiceConnector implements ILtiServiceConnector
{
public const NEXT_PAGE_REGEX = '/<([^>]*)>; ?rel="next"/i';
private bool $debuggingMode = false;
public function __construct(
private ICache $cache,
private Client $client
) {
}
public function setDebuggingMode(bool $enable): self
{
$this->debuggingMode = $enable;
return $this;
}
public function getAccessToken(ILtiRegistration $registration, array $scopes): string
{
// Get a unique cache key for the access token
$accessTokenKey = $this->getAccessTokenCacheKey($registration, $scopes);
// Get access token from cache if it exists
$accessToken = $this->cache->getAccessToken($accessTokenKey);
if (isset($accessToken)) {
return $accessToken;
}
// Build up JWT to exchange for an auth token
$clientId = $registration->getClientId();
$jwtClaim = [
'iss' => $clientId,
'sub' => $clientId,
'aud' => $registration->getAuthServer(),
'iat' => time() - 5,
'exp' => time() + 60,
'jti' => 'lti-service-token'.hash('sha256', random_bytes(64)),
];
// Sign the JWT with our private key (given by the platform on registration)
$jwt = JWT::encode($jwtClaim, $registration->getToolPrivateKey(), 'RS256', $registration->getKid());
// Build auth token request headers
$authRequest = [
'grant_type' => 'client_credentials',
'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion' => $jwt,
'scope' => implode(' ', $scopes),
];
// Get Access
$request = new ServiceRequest(
ServiceRequest::METHOD_POST,
$registration->getAuthTokenUrl(),
ServiceRequest::TYPE_AUTH
);
$request->setPayload(['form_params' => $authRequest])
->setMaskResponseLogs(true);
$response = $this->makeRequest($request);
$tokenData = $this->getResponseBody($response);
// Cache access token
$this->cache->cacheAccessToken($accessTokenKey, $tokenData['access_token']);
return $tokenData['access_token'];
}
public function makeRequest(IServiceRequest $request): ResponseInterface
{
$response = $this->client->request(
$request->getMethod(),
$request->getUrl(),
$request->getPayload()
);
if ($this->debuggingMode) {
$this->logRequest(
$request,
$this->getResponseHeaders($response),
$this->getResponseBody($response)
);
}
return $response;
}
public function getResponseHeaders(ResponseInterface $response): ?array
{
$responseHeaders = $response->getHeaders();
array_walk($responseHeaders, function (&$value) {
$value = $value[0];
});
return $responseHeaders;
}
public function getResponseBody(ResponseInterface $response): ?array
{
$responseBody = (string) $response->getBody();
return json_decode($responseBody, true);
}
public function makeServiceRequest(
ILtiRegistration $registration,
array $scopes,
IServiceRequest $request,
bool $shouldRetry = true
): array {
$request->setAccessToken($this->getAccessToken($registration, $scopes));
try {
$response = $this->makeRequest($request);
} catch (ClientException $e) {
$status = $e->getResponse()->getStatusCode();
// If the error was due to invalid authentication and the request
// should be retried, clear the access token and retry it.
if ($status === 401 && $shouldRetry) {
$key = $this->getAccessTokenCacheKey($registration, $scopes);
$this->cache->clearAccessToken($key);
return $this->makeServiceRequest($registration, $scopes, $request, false);
}
throw $e;
}
return [
'headers' => $this->getResponseHeaders($response),
'body' => $this->getResponseBody($response),
'status' => $response->getStatusCode(),
];
}
public function getAll(
ILtiRegistration $registration,
array $scopes,
IServiceRequest $request,
?string $key = null
): array {
if ($request->getMethod() !== ServiceRequest::METHOD_GET) {
throw new Exception('An invalid method was specified by an LTI service requesting all items.');
}
$results = [];
$nextUrl = $request->getUrl();
while ($nextUrl) {
$request->setUrl($nextUrl);
$response = $this->makeServiceRequest($registration, $scopes, $request);
$pageResults = $this->getResultsFromResponse($response, $key);
$results = array_merge($results, $pageResults);
$nextUrl = $this->getNextUrl($response['headers']);
}
return $results;
}
public static function getLogMessage(
IServiceRequest $request,
array $responseHeaders,
?array $responseBody
): string {
if ($request->getMaskResponseLogs()) {
$responseHeaders = self::maskValues($responseHeaders);
$responseBody = self::maskValues($responseBody);
}
$contextArray = [
'request_method' => $request->getMethod(),
'request_url' => $request->getUrl(),
'response_headers' => $responseHeaders,
'response_body' => $responseBody,
];
$requestBody = $request->getPayload()['body'] ?? null;
if (isset($requestBody)) {
$contextArray['request_body'] = $requestBody;
}
return implode(' ', array_filter([
$request->getErrorPrefix(),
json_decode($requestBody)->userId ?? null,
json_encode($contextArray),
]));
}
private function logRequest(
IServiceRequest $request,
array $responseHeaders,
?array $responseBody
): void {
error_log(self::getLogMessage($request, $responseHeaders, $responseBody));
}
private static function maskValues(?array $payload): ?array
{
if (!isset($payload) || empty($payload)) {
return $payload;
}
foreach ($payload as $key => $value) {
$payload[$key] = '***';
}
return $payload;
}
private function getAccessTokenCacheKey(ILtiRegistration $registration, array $scopes): string
{
sort($scopes);
$scopeKey = md5(implode('|', $scopes));
return $registration->getIssuer().$registration->getClientId().$scopeKey;
}
private function getResultsFromResponse(array $response, ?string $key = null): array
{
if (isset($key)) {
return $response['body'][$key] ?? [];
}
return $response['body'] ?? [];
}
private function getNextUrl(array $headers): ?string
{
$subject = $headers['Link'] ?? $headers['link'] ?? '';
preg_match(static::NEXT_PAGE_REGEX, $subject, $matches);
return $matches[1] ?? null;
}
}
@@ -0,0 +1,38 @@
<?php
namespace Packback\Lti1p3\MessageValidators;
use Packback\Lti1p3\Interfaces\IMessageValidator;
use Packback\Lti1p3\LtiConstants;
use Packback\Lti1p3\LtiException;
abstract class AbstractMessageValidator implements IMessageValidator
{
abstract public static function getMessageType(): string;
public static function canValidate(array $jwtBody): bool
{
return $jwtBody[LtiConstants::MESSAGE_TYPE] === static::getMessageType();
}
abstract public static function validate(array $jwtBody): void;
/**
* @throws LtiException
*/
public static function validateGenericMessage(array $jwtBody): void
{
if (empty($jwtBody['sub'])) {
throw new LtiException('Must have a user (sub)');
}
if (!isset($jwtBody[LtiConstants::VERSION])) {
throw new LtiException('Missing LTI Version');
}
if ($jwtBody[LtiConstants::VERSION] !== LtiConstants::V1_3) {
throw new LtiException('Incorrect version, expected 1.3.0');
}
if (!isset($jwtBody[LtiConstants::ROLES])) {
throw new LtiException('Missing Roles Claim');
}
}
}
@@ -0,0 +1,36 @@
<?php
namespace Packback\Lti1p3\MessageValidators;
use Packback\Lti1p3\LtiConstants;
use Packback\Lti1p3\LtiException;
class DeepLinkMessageValidator extends AbstractMessageValidator
{
public static function getMessageType(): string
{
return LtiConstants::MESSAGE_TYPE_DEEPLINK;
}
/**
* @throws LtiException
*/
public static function validate(array $jwtBody): void
{
static::validateGenericMessage($jwtBody);
if (empty($jwtBody[LtiConstants::DL_DEEP_LINK_SETTINGS])) {
throw new LtiException('Missing Deep Linking Settings');
}
$deep_link_settings = $jwtBody[LtiConstants::DL_DEEP_LINK_SETTINGS];
if (empty($deep_link_settings['deep_link_return_url'])) {
throw new LtiException('Missing Deep Linking Return URL');
}
if (empty($deep_link_settings['accept_types']) || !in_array('ltiResourceLink', $deep_link_settings['accept_types'])) {
throw new LtiException('Must support resource link placement types');
}
if (empty($deep_link_settings['accept_presentation_document_targets'])) {
throw new LtiException('Must support a presentation type');
}
}
}
@@ -0,0 +1,26 @@
<?php
namespace Packback\Lti1p3\MessageValidators;
use Packback\Lti1p3\LtiConstants;
use Packback\Lti1p3\LtiException;
class ResourceMessageValidator extends AbstractMessageValidator
{
public static function getMessageType(): string
{
return LtiConstants::MESSAGE_TYPE_RESOURCE;
}
/**
* @throws LtiException
*/
public static function validate(array $jwtBody): void
{
static::validateGenericMessage($jwtBody);
if (empty($jwtBody[LtiConstants::RESOURCE_LINK]['id'])) {
throw new LtiException('Missing Resource Link Id');
}
}
}
@@ -0,0 +1,29 @@
<?php
namespace Packback\Lti1p3\MessageValidators;
use Packback\Lti1p3\LtiConstants;
use Packback\Lti1p3\LtiException;
class SubmissionReviewMessageValidator extends AbstractMessageValidator
{
public static function getMessageType(): string
{
return LtiConstants::MESSAGE_TYPE_SUBMISSIONREVIEW;
}
/**
* @throws LtiException
*/
public static function validate(array $jwtBody): void
{
static::validateGenericMessage($jwtBody);
if (empty($jwtBody[LtiConstants::RESOURCE_LINK]['id'])) {
throw new LtiException('Missing Resource Link Id');
}
if (empty($jwtBody[LtiConstants::FOR_USER])) {
throw new LtiException('Missing For User');
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace Packback\Lti1p3;
use Exception;
class OidcException extends Exception
{
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace Packback\Lti1p3;
use Packback\Lti1p3\Interfaces\IServiceRequest;
class ServiceRequest implements IServiceRequest
{
// Request methods
public const METHOD_DELETE = 'DELETE';
public const METHOD_GET = 'GET';
public const METHOD_POST = 'POST';
public const METHOD_PUT = 'PUT';
// Request types
public const TYPE_UNSUPPORTED = 'unsupported';
public const TYPE_AUTH = 'auth';
// MessageLaunch
public const TYPE_GET_KEYSET = 'get_keyset';
// AGS
public const TYPE_GET_GRADES = 'get_grades';
public const TYPE_SYNC_GRADE = 'sync_grades';
public const TYPE_CREATE_LINEITEM = 'create_lineitem';
public const TYPE_DELETE_LINEITEM = 'delete_lineitem';
public const TYPE_GET_LINEITEMS = 'get_lineitems';
public const TYPE_GET_LINEITEM = 'get_lineitem';
public const TYPE_UPDATE_LINEITEM = 'update_lineitem';
// CGS
public const TYPE_GET_GROUPS = 'get_groups';
public const TYPE_GET_SETS = 'get_sets';
// NRPS
public const TYPE_GET_MEMBERSHIPS = 'get_memberships';
private $body;
private $payload;
private $accessToken;
private $contentType = 'application/json';
private $accept = 'application/json';
// Other
private $maskResponseLogs = false;
public function __construct(
private string $method,
private string $url,
private string $type = self::TYPE_UNSUPPORTED
) {
}
public function getMethod(): string
{
return strtoupper($this->method);
}
public function getUrl(): string
{
return $this->url;
}
public function getPayload(): array
{
if (isset($this->payload)) {
return $this->payload;
}
$payload = [
'headers' => $this->getHeaders(),
];
$body = $this->getBody();
if ($body) {
$payload['body'] = $body;
}
return $payload;
}
public function setUrl(string $url): IServiceRequest
{
$this->url = $url;
return $this;
}
public function setAccessToken(string $accessToken): IServiceRequest
{
$this->accessToken = 'Bearer '.$accessToken;
return $this;
}
public function setBody(string $body): IServiceRequest
{
$this->body = $body;
return $this;
}
public function setPayload(array $payload): IServiceRequest
{
$this->payload = $payload;
return $this;
}
public function setAccept(string $accept): IServiceRequest
{
$this->accept = $accept;
return $this;
}
public function setContentType(string $contentType): IServiceRequest
{
$this->contentType = $contentType;
return $this;
}
public function getMaskResponseLogs(): bool
{
return $this->maskResponseLogs;
}
public function setMaskResponseLogs(bool $shouldMask): IServiceRequest
{
$this->maskResponseLogs = $shouldMask;
return $this;
}
public function getErrorPrefix(): string
{
$defaultMessage = 'Logging request data:';
$errorMessages = [
static::TYPE_UNSUPPORTED => $defaultMessage,
static::TYPE_AUTH => 'Authenticating:',
static::TYPE_GET_KEYSET => 'Getting key set:',
static::TYPE_GET_GRADES => 'Getting grades:',
static::TYPE_SYNC_GRADE => 'Syncing grade for this lti_user_id:',
static::TYPE_CREATE_LINEITEM => 'Creating lineitem:',
static::TYPE_DELETE_LINEITEM => 'Deleting lineitem:',
static::TYPE_GET_LINEITEMS => 'Getting lineitems:',
static::TYPE_GET_LINEITEM => 'Getting a lineitem:',
static::TYPE_UPDATE_LINEITEM => 'Updating lineitem:',
static::TYPE_GET_GROUPS => 'Getting groups:',
static::TYPE_GET_SETS => 'Getting sets:',
static::TYPE_GET_MEMBERSHIPS => 'Getting memberships:',
];
return $errorMessages[$this->type] ?? $defaultMessage;
}
private function getHeaders(): array
{
$headers = [
'Accept' => $this->accept,
];
if (isset($this->accessToken)) {
$headers['Authorization'] = $this->accessToken;
}
// Include Content-Type for POST and PUT requests
if (in_array($this->getMethod(), [ServiceRequest::METHOD_POST, ServiceRequest::METHOD_PUT])) {
$headers['Content-Type'] = $this->contentType;
}
return $headers;
}
private function getBody(): ?string
{
return $this->body;
}
}