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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion app/config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,13 @@
'defaults' => 'php',
// Switch cookie name to avoid conflict with older versions of Registry
// Note this name must match the name used in webroot/auth/*/*
'cookie' => 'REGISTRYPECAKEPHP'
'cookie' => 'REGISTRYPECAKEPHP',
// Prevent PHP's session handling from forcing no-cache headers onto every
// response, so actions like MostlyStaticResourcesController::deliver()
// can set their own explicit HTTP caching headers (since v5.3.0).
'ini' => [
'session.cache_limiter' => '',
],
],

/**
Expand Down
19 changes: 19 additions & 0 deletions app/config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ function (RouteBuilder $builder) {
// Main application routes
$routes->scope('/', function (RouteBuilder $builder) {
// Register scoped middleware for in scopes.
$builder->registerMiddleware('postMaxSizeCheck', new \App\Middleware\PostMaxSizeCheckMiddleware());

Comment on lines +170 to +171
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not specific to this PR, but it looks like these registerMiddleware statements are supposed to be defined outside of any scope?

$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httponly' => true,
]));
Expand Down Expand Up @@ -237,6 +239,23 @@ function (RouteBuilder $builder) {
$builder->fallbacks();
});

/**
* Mostly Static Resources need a postMaxSizeCheck when uploading files (add/edit).
* Check for post_max_size overage first: PHP wipes the POST data when the threshold is crossed
* and will cause a CSRF failure if not caught (because the crsf token will be missing from the POST).
*/
$routes->scope('/mostly-static-resources', function (RouteBuilder $builder) {
$builder->applyMiddleware('postMaxSizeCheck', 'csrf');
$builder->connect(
'/add',
['controller' => 'MostlyStaticResources', 'action' => 'add']);
$builder->connect(
'/edit/{id}',
['controller' => 'MostlyStaticResources', 'action' => 'edit'],
['id' => '\d+', 'pass' => ['id']]
);
Comment on lines +249 to +256
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we inherit this from the default routes? ie, why do we need these and not delete?

});

/*
* If you need a different set of middleware or none at all,
* open new scope and define routes there.
Expand Down
11 changes: 10 additions & 1 deletion app/resources/locales/en_US/error.po
Original file line number Diff line number Diff line change
Expand Up @@ -493,8 +493,17 @@ msgstr "Unknown value \"{0}\""
msgid "unknown.identifier"
msgstr "Unknown Identifier \"{0}\""

msgid "upload.failed"
msgstr "File upload failed"

msgid "upload.maxsize"
msgstr "File size {0} exceeds maximum permitted {1}"
msgstr "File size {0} exceeds maximum permitted by CO Settings: {1}"

msgid "upload.php.uploadmaxfilesize"
msgstr "File size exceeds maximum permitted by PHP settings (maximum upload size is {0})"

msgid "upload.php.postmaxsize"
msgstr "The file size you attempted to upload is too large for this server to accept (maximum POST size is {0})."

msgid "Verifications.already"
msgstr "Email Address is already verified"
Expand Down
11 changes: 10 additions & 1 deletion app/resources/locales/en_US/field.po
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,9 @@ msgstr "Metadata"
msgid "middle"
msgstr "Middle"

msgid "mime_type"
msgstr "Mime Type"

msgid "modifiable"
msgstr "Modifiable"

Expand Down Expand Up @@ -931,11 +934,17 @@ msgstr "This Petition is complete and has been finalized. Please contact your ad
msgid "MostlyStaticResources.file_content"
msgstr "File to Upload"

msgid "MostlyStaticResources.image"
msgstr "Resource Image"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there are reason not just to use "Image"? (Similarly for "Resource URL".)


msgid "MostlyStaticResources.name"
msgstr "Slug"

msgid "MostlyStaticResources.name.desc"
msgstr "The URL fragment for this Resource, which must be unique and use only lowercase alphanumeric characters and dashes (-)"
msgstr "The URL fragment for this Resource, which must be unique and use only lowercase alphanumeric characters, dashes (-), underscores (_), and periods (.)"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See discussion in MostlyStaticResourcesTable, below.


msgid "MostlyStaticResources.url"
msgstr "Resource URL"

msgid "Notifications.actor_person_id"
msgstr "Actor"
Expand Down
10 changes: 9 additions & 1 deletion app/src/Controller/AppController.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@ public function beforeFilter(\Cake\Event\EventInterface $event) {

$this->getAppPrefs();

// Authenticated pages are not cached. Placing this here allows us to override
// caching in other contexts, such as for Mostly Static Resources. Cache-control
// was once a static header in the element/httpHeaders.php template file.
// This replaces that approach as of v5.3.0.
$this->response = $this->response->withDisabledCache();

parent::beforeFilter($event);
}

Expand Down Expand Up @@ -706,8 +712,10 @@ protected function getTheme() {
if(isset($theme)) {
$htmlSanitizer = new HtmlSanitizer(
// Allow all elements from the W3C Sanitizer API. This is more permissive than "allowSafeElements()".
// Also allow relative references, such as image src attributes to Mostly Static Resources.
// Also allow relative links, such as server-relative links to a specific CO Dashboard.
// See: https://github.com/symfony/symfony/blob/7.2/src/Symfony/Component/HtmlSanitizer/Reference/W3CReference.php
(new HtmlSanitizerConfig())->allowStaticElements()
(new HtmlSanitizerConfig())->allowStaticElements()->allowRelativeMedias()->allowRelativeLinks()
);

$theme->patch([
Expand Down
32 changes: 28 additions & 4 deletions app/src/Controller/PagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,14 @@ public function initialize(): void
* @since COmanage Registry v5.3.0
* @param string $coid CO ID
* @param string $name MSR Name (slug)
* @return \Cake\Http\Response|null
*/

public function deliver(string $coid, string $name) {
// We use PagesController rather than MostlyStaticResourcesController to avoid complexities
// with PrimaryLink lookups. We render here rather than redirecting into the MSRController to
// reduce URL bar thrashing.

// MSRs are only enabled if file uploads are enabled
$CoSettings = TableRegistry::getTableLocator()->get("CoSettings");

Expand All @@ -74,24 +75,47 @@ public function deliver(string $coid, string $name) {
}

$MSRTable = TableRegistry::getTableLocator()->get("MostlyStaticResources");


// Begin by pulling only the necessary data to determine if the resource was changed.
$msr = $MSRTable->find()
->select(['id','mime_type','modified'])
->where([
'co_id' => (int)$coid,
'name' => $name,
'status' => SuspendableStatusEnum::Active
])
->first();

// Return an error if not found.
if(empty($msr)) {
$this->Flash->error(__d('error', 'notfound', $name));

return $this->redirect(StringUtilities::pagesUrl($coid, "error-landing"));
}

// Generate an etag based on the id and modified date.
$etag = $msr->id . '-' . $msr->modified->getTimestamp();

$response = $this->response
->withType($msr->mime_type)
->withEtag($etag, true)
->withCache($msr->modified->getTimestamp(), '+1 year');

// If there are no modifications, just return the response without pulling the file content.
if ($response->isNotModified($this->request)) {
return $response->withNotModified();
}

// There are modifications - get the content.
$msrContent = $MSRTable->find()
->select(['file_content'])
->where(['id' => $msr->id])
->first();

$fileContent = stream_get_contents($msr->file_content);
$fileContent = stream_get_contents($msrContent->file_content);
fclose($msrContent->file_content);

return $this->response->withType($msr->mime_type)->withStringBody($fileContent);
return $response->withStringBody($fileContent);
}

/**
Expand Down
27 changes: 24 additions & 3 deletions app/src/Controller/StandardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use App\Lib\Traits\IndexQueryTrait;
use Cake\Database\Schema\TableSchemaInterface;
use Cake\Datasource\ConnectionManager;
use Cake\I18n\Number;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
Expand Down Expand Up @@ -838,13 +839,33 @@ protected function processFileUpload(TableSchemaInterface $schema, array &$data)
if($CoSettings->uploadsEnabled()) {
$upload = $data['file_content'];

if(!empty($upload) && $upload->getSize() > 0) {
// First verify size is within the configured limit
if(!empty($upload) && $upload->getError() !== UPLOAD_ERR_NO_FILE) {
// First ensure that the file upload didn't produce a PHP error, starting with upload_max_filesize.
if($upload->getError() === UPLOAD_ERR_INI_SIZE || $upload->getError() === UPLOAD_ERR_FORM_SIZE) {
throw new \InvalidArgumentException(
__d('error', 'upload.php.uploadmaxfilesize', [
ini_get('upload_max_filesize')
])
);
}

// Any other PHP failure? partial upload, etc.
if($upload->getError() !== UPLOAD_ERR_OK) {
throw new \InvalidArgumentException(
__d('error', 'upload.failed')
);
}

// Now verify that the file size is within the CO Settings configured limit
$size = $upload->getSize();

if($size > $CoSettings->getUploadMaxSize()) {
throw new \InvalidArgumentException(__d('error', 'upload.maxsize', [$size, $CoSettings->getMsrMaxSize()]));
throw new \InvalidArgumentException(
__d('error', 'upload.maxsize', [
Number::toReadableSize($size),
Number::toReadableSize($CoSettings->getUploadMaxSize())
])
);
}

// Next parse the mime-type. We can't rely on the client provided value,
Expand Down
88 changes: 88 additions & 0 deletions app/src/Middleware/PostMaxSizeCheckMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php
/**
* COmanage post_max_size Check for File Uploads
*
* Portions licensed to the University Corporation for Advanced Internet
* Development, Inc. ("UCAID") under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* UCAID licenses this file to you 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.
*
* @link https://www.internet2.edu/comanage COmanage Project
* @package registry
* @since COmanage Registry v5.3.0
* @license Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
*/

declare(strict_types=1);

namespace App\Middleware;

use Cake\Http\Exception\BadRequestException;
use Cake\Http\FlashMessage;
use Cake\Http\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class PostMaxSizeCheckMiddleware implements MiddlewareInterface {

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
if ($request->is('post')) {
$contentLength = (int)$request->getHeaderLine('Content-Length');
$postMaxBytes = $this->iniSizeToBytes(ini_get('post_max_size'));

if ($contentLength > 0 && $postMaxBytes > 0 && $contentLength > $postMaxBytes) {
// Route the user back to where they came from with an error message if possible.
$referer = $request->getHeaderLine('Referer');
$session = $request->getAttribute('session');

if(empty($referer) || empty($session)) {
// There's no referer to reference (and possibly no session), so just show the more abrupt white-screen error.
throw new BadRequestException(
__d('error', 'upload.php.postmaxsize', [ini_get('post_max_size')])
);
}

// We have a referer, so set the flash message and return.
$flash = new FlashMessage($session);
$flash->error(__d('error', 'upload.php.postmaxsize', [ini_get('post_max_size')]));
return (new Response())->withStatus(302)->withHeader('Location', $referer);
}
}

return $handler->handle($request);
}

protected function iniSizeToBytes(string $val): int {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe just use PHP's ini_parse_quantity function instead? This imposes a minimum PHP of 8.2.0, but I think we're there already.

$val = trim($val);
if ($val === '') {
return 0;
}

$unit = strtolower($val[strlen($val) - 1]);
$num = (int)$val;

// Convert the value to bytes by letting it fall through the switch statement starting at
// the correct unit. If we start with "g", the value will be multiplied by 1024 three times.
switch ($unit) {
case 'g': $num *= 1024;
case 'm': $num *= 1024;
case 'k': $num *= 1024;
}

return $num;
}
}
4 changes: 2 additions & 2 deletions app/src/Model/Table/CoSettingsTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,8 @@ public function addDefaults(int $coId): int {
'platform_env_mfa_enable_eg' => false,
'platform_upload_enable' => false,
// In general storing large files in the database is not performant, this number
// probably shouldn't be increased.
'platform_upload_max_size' => 10000000
// probably shouldn't be increased. This is 10MB in bytes.
'platform_upload_max_size' => 10485760
// XXX to add new settings, set a default here, then add a validation rule below
// also update data model documentation
// 'disable_expiration' => false,
Expand Down
4 changes: 2 additions & 2 deletions app/src/Model/Table/MostlyStaticResourcesTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,10 @@ public function validationDefault(Validator $validator): Validator {
$this->registerStringValidation($validator, $schema, 'name', true);

// AR-MostlyStaticResource-2 A Mostly Static Resource name may consist only of
// lowercase alphanumeric characters and dashes
// lowercase alphanumeric characters, dashes, underscores, and periods (for allowing extensions)
$validator->add('name', [
'slugfilter' => [
'rule' => ['custom', '/^[a-z0-9-]+$/'],
'rule' => ['custom', '/^[a-z0-9._\-]+$/'],
Comment on lines -128 to +131
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes me uncomfortable, though I'm not sure I have a good reason other than it's deviating from the out of the box pattern.

Cake 3+ uses dashes, not underscores, in URLs. I get that someone might upload a file with an underscore, but we don't need to preserve the filename exactly as uploaded.

Allowing periods for extensions also allows them for poorly constructed filenames. But maybe that's not a problem we should really be solving.

Copy link
Contributor Author

@arlen arlen Sep 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My goal here was to allow filenames to upload with minimal transformation - and dots and underscores are fairly common in image filenames (I much prefer dashes). I'm ok with skipping underscores or enforcing their change to dashes if we feel strongly about this.

On extensions: we may not require them for rendering, since Content-Type is set explicitly from the stored mime_type column. But keeping the name field recognizable/familiar to whoever's managing these resources through the UI feels like better UX even if just a convenience. I'm hesitant to strip the extensions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess I'd prefer to preserve these - but I can compromise on the underscore. I feel more strongly about the dot (for extensions). Thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, in the spirit of unnecessary compromise, let's convert underscores to dashes but leave the dots.

'message' => __d('error', 'MostlyStaticPages.slug.invalid')
]
]);
Expand Down
2 changes: 1 addition & 1 deletion app/templates/CoSettings/fields.inc
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ if($vv_obj->co->isCOmanageCO()) {
'platform_upload_enable',
// XXX maybe only show if platform_msr_enable=true?
'platform_upload_max_size' => [
'default' => 10000000
'default' => 10485760 // 10MB in bytes
]
]);
}
4 changes: 2 additions & 2 deletions app/templates/MostlyStaticPages/fields.inc
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ if($vv_action == 'edit') {
<script nonce="<?= $vv_js_nonce ?>">
function setPageUrl() {
var baseurl = "<?= $vv_base_url ?>";
var slug = document.getElementById('name').value;
var slug = $('#name').value;

var fullurl = "";

if(slug) {
fullurl = baseurl + slug;
}

document.getElementById('pageurl').value = fullurl;
$('#pageurl').value = fullurl;
}

$(function() {
Expand Down
4 changes: 4 additions & 0 deletions app/templates/MostlyStaticResources/columns.inc
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,9 @@ $indexColumns = [
'type' => 'enum',
'class' => 'SuspendableStatusEnum',
'sortable' => true
],
'mime_type' => [
'type' => 'echo',
'sortable' => true
]
];
Loading