Version in base suite: 5.0.7+dfsg-4+deb13u3 Base version: request-tracker5_5.0.7+dfsg-4+deb13u3 Target version: request-tracker5_5.0.7+dfsg-4+deb13u4 Base file: /srv/ftp-master.debian.org/ftp/pool/main/r/request-tracker5/request-tracker5_5.0.7+dfsg-4+deb13u3.dsc Target file: /srv/ftp-master.debian.org/policy/pool/main/r/request-tracker5/request-tracker5_5.0.7+dfsg-4+deb13u4.dsc .git-dpm | 4 changelog | 174 control | 2 patches/debianize_UPGRADING-4.4.diff | 2 patches/debianize_UPGRADING-5.0.diff | 2 patches/downgrade_Crypt::URandom.diff | 25 patches/series | 9 patches/upstream_5.0.7_cve:_patchset_2025-04-08-RT_Config.diff | 2 patches/upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff | 27 patches/upstream_5.0.7_cve:_patchset_2025-10-07.diff | 2 patches/upstream_5.0.7_cve:_patchset_2026-05-05-RT_Config.diff | 2 patches/upstream_5.0.7_cve:_patchset_2026-05-05.diff | 2 patches/upstream_5.0.7_cve:_patchset_2026-10-15.diff | 4639 ++++++++++ patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff | 344 patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff | 40 patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff | 29 patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff | 29 patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff | 55 patches/upstream_5.0.8_test_web:_patchset_2025-04-08.diff | 27 19 files changed, 5380 insertions(+), 36 deletions(-) dpkg-source: warning: cannot verify inline signature for /srv/release.debian.org/tmp/tmp8r3w03id/request-tracker5_5.0.7+dfsg-4+deb13u3.dsc: no acceptable signature found dpkg-source: warning: cannot verify inline signature for /srv/release.debian.org/tmp/tmp8r3w03id/request-tracker5_5.0.7+dfsg-4+deb13u4.dsc: no acceptable signature found diff -Nru request-tracker5-5.0.7+dfsg/debian/.git-dpm request-tracker5-5.0.7+dfsg/debian/.git-dpm --- request-tracker5-5.0.7+dfsg/debian/.git-dpm 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/.git-dpm 2026-11-22 08:53:30.000000000 +0000 @@ -1,6 +1,6 @@ # see git-dpm(1) from git-dpm package -7303c128c840cc9046320ec0591aaaeca953155c -7303c128c840cc9046320ec0591aaaeca953155c +51a927ca36a03968ebef468c57de35d40c8e02d0 +51a927ca36a03968ebef468c57de35d40c8e02d0 7ffdc76a3d7dde5bc3954f1c874ec200bdc3310a 7ffdc76a3d7dde5bc3954f1c874ec200bdc3310a request-tracker5_5.0.7+dfsg.orig.tar.gz diff -Nru request-tracker5-5.0.7+dfsg/debian/changelog request-tracker5-5.0.7+dfsg/debian/changelog --- request-tracker5-5.0.7+dfsg/debian/changelog 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/changelog 2026-11-24 10:26:02.000000000 +0000 @@ -1,3 +1,177 @@ +request-tracker5 (5.0.7+dfsg-4+deb13u4) trixie-security; urgency=high + + * Apply upstream patch which fixes several security vulnerabilities: + - [CVE-2026-108351] Remote code execution via an ExecuteCode right bypass + in template administration. A user granted ModifyTemplate but not + ShowTemplate (ShowGlobalTemplates for global templates) can alter the + body of an existing Perl template without holding ExecuteCode. RT's + standard scrips then run that code during ordinary ticket activity as the + operating-system user the web server runs as. The bypass also defeats + $DisallowExecuteCode. + - [CVE-2026-108353] Privilege escalation via the REST group and group + membership endpoints. A user with SeeGroup and AdminGroup on a single + user-defined group can convert it, through REST 2.0, into a role group of + another object (for example, the AdminCc role of an arbitrary queue) and + inherit that role's rights. Separately, a user holding only + ModifyOwnMembership can use the REST interfaces to add themselves to + queue or ticket role groups, or to RT's internal Privileged group. + - [CVE-2026-108279] Privilege escalation via a Cross-Site Request Forgery + (CSRF) protection bypass in the URL shortener. RT decided whether a + request needed CSRF confirmation before it expanded a short link, so the + arguments the link carried were never checked. Any authenticated user + with global ShowTicket can create a short link that, when followed by an + administrator holding ModifyACL or SuperUser, silently performs a rights + change such as granting the attacker SuperUser. + - [CVE-2026-108275] Cross-queue ticket modification and disclosure via + CreateTickets scrip action templates. A user holding the queue-level + ModifyTemplate and ModifyScrips rights on one queue can write a plain + (non-Perl) template that creates or updates tickets in other queues, + which RT carries out as the system user. This allows modifying tickets in + queues the user has no rights on, and reading them by moving them into a + queue the user can see. + - [CVE-2026-108270] Authorization bypass and information disclosure in + ticket forwarding. A user holding ForwardMessage on any single ticket can + cause RT to email the content and attachments of any transaction in the + instance to an address of their choosing, including correspondence on + tickets they cannot see. Separately, a user with ForwardMessage but not + ShowTicket on a ticket can forward that ticket's correspondence to + themselves. + - [CVE-2026-108274] Insecure direct object reference in custom field + values. A custom field value can be addressed by its id without checking + that it belongs to an object the user may access. A user who can see a + custom field can download that field's values from tickets they cannot + see, through the web interface or REST 2.0, and a user who can modify a + custom field can create, overwrite or delete its values on any object in + the instance. At least one write path is reachable from a self-service + preferences page. + - [CVE-2026-108278] Information disclosure via RSS feed URLs. The + authentication string in an RSS feed URL is not bound to the search the + URL was issued for, so anyone who obtains a feed URL can substitute their + own search and have it run with the feed owner's rights. This can expose + the subject and first message of every ticket the feed owner can read. + iCal feeds are not affected. + - [CVE-2026-108271] Incorrect authorization of the destination in several + operations. RT checked the user's rights on the record being changed but + not on the place it was being moved to, in dashboard editing, the search + builder's saved-search panel, article editing (web interface and REST + 2.0), the REST 2.0 custom field value endpoint, and REST 2.0 ticket + creation. An authenticated user can publish a dashboard or saved search + system-wide or to a group they cannot publish to, move an article into a + class they cannot create articles in, or attach history to a ticket they + have no rights on. The REST 2.0 custom field value endpoint also + disclosed custom field value definitions by id. + - [CVE-2026-108273] Ticket recipient disclosure on the ticket People and + Update pages. A user granted ReplyToTicket but not ShowTicket on a ticket + can read the ticket's requestor, owner, Cc and AdminCc email addresses, + and the member of a single-value custom role. + - [CVE-2026-108276] Information disclosure via the REST 1.0 group endpoint. + Any privileged (staff) user can retrieve a group's name, description, + membership (including members' names and email addresses) and custom + field values without SeeGroup. Because any group id is accepted, this + also exposes the watchers of queues, tickets and assets the user cannot + see. + - [CVE-2026-108280] Missing object-level authorization on queue, catalog, + custom field and article class administration pages. A user with + ShowConfigTab can read and change default values for any queue, asset + catalog and custom field, and the settings of any article class, without + AdminQueue, AdminCatalog, AdminCustomField or AdminClass on that object. + - [CVE-2026-108281] Missing authorization on scrip and custom field + ordering. A user with ShowConfigTab can reorder scrips, change the + processing stage of global scrips, and reorder global custom fields + without ModifyScrips or AssignCustomFields. Reordering or restaging + scrips can change the outcome of RT's automated actions. + - [CVE-2026-108352] Missing authorization in the custom field and custom + role editing pages. A user with only ShowConfigTab can change the object + type a custom field or custom role applies to. RT removes the field's or + role's existing applications before it denies the request, so the field + or role disappears from the objects it was used on. + - [CVE-2026-108347] Information disclosure via ticket relationship graphs. + A user viewing a ticket's relationship graph sees the owner and custom + field values of every linked ticket, even tickets they cannot see. A user + with ModifyTicket on any ticket can link it to an arbitrary ticket to + read that information. Ticket subjects are not exposed. + - [CVE-2026-108346] Disclosure of hidden ticket time fields. On systems + that enable $HideTimeFieldsFromUnprivilegedUsers (off by default), + unprivileged users can still read time worked, estimated and left, and + per-transaction time details, on tickets they can see, through the Self + Service export and REST 2.0, and can infer them through search. + - [CVE-2026-108282] Insecure direct object reference in saved search + handling. The search builder, saved chart search page, article search + page and the saved-search dashboard portlet accept a saved-setting id + without confirming it belongs to the owner named in the request. An + authenticated user can read another user's private saved searches, take + over another user's private dashboard, change another user's dashboard + subscription, and delete a queue's stored encryption setting, which turns + off outgoing encryption for that queue. + - [CVE-2026-108371] CSRF on the search chart page. The saved-search + controls on the chart page were not covered by RT's CSRF protection, so a + malicious web page can create, overwrite or delete a logged-in user's + saved chart searches, including those shared with groups or the whole + system. + - [CVE-2026-108365] CSRF in the Rights Inspector. The Rights Inspector's + revoke action was not covered by RT's CSRF protection, so a malicious web + page can make a logged-in user holding ModifyACL revoke a rights grant. + - [CVE-2026-108277] CSRF via cookie-authenticated REST 2.0 requests. + State-changing REST 2.0 requests authenticated with the web session + cookie are not covered by RT's CSRF protection. With RT's default + SameSite=Lax cookie policy, exploitation requires content served from a + same-site origin, such as a sibling subdomain or another port on the RT + host. REST 2.0 clients that authenticate with an Authorization header are + not affected. + - [CVE-2026-108344] Login CSRF on the password login form. On systems that + enable $RestrictLoginReferrer (off by default), the referrer check runs + after the session is created, so an attacker with any valid account can + log a user's browser into the attacker's account. Work the user then + submits is recorded in, and readable from, that account. + - [CVE-2026-108342] Multiple stored and reflected XSS vulnerabilities + from insufficient HTML escaping. Affected areas include the meeting + invitation display in ticket history, HTML ticket content, group and user + display names, administrator-managed object names, Wikitext custom field + values, table-style chart labels, ticket relationship graphs, the article + chooser, dashboard subscription and dashboard component pages, + saved-search and search result format handling, transaction and history + views, and file downloads with attacker-controlled content types. Some of + these require no RT account: on a queue that accepts mail from the + public, an outside sender can store a payload that runs when staff view + the ticket. + - [CVE-2026-105454] Stored XSS via crafted URLs in HTML ticket content. + RT's automatic link creation for URLs in HTML ticket content does not + escape the URL, so a crafted URL can add script that runs when the ticket + history is displayed, with no click needed. An outside sender of HTML + email to a public queue can plant it. + - [CVE-2026-108363] Reflected XSS in the advanced lifecycle editor. Request + content is written back into the editor without escaping. Exploitation + requires an administrator with ShowConfigTab and SuperUser to follow a + crafted link and click through RT's CSRF confirmation page. + - [CVE-2026-108343] Stored XSS via custom field link URLs. Custom fields + configured to render their own value as a link (IncludeContentForValue or + LinkValueTo pointing at the field's value) do not reliably reject + executable URL schemes. RT ships no custom fields configured this way. + - [CVE-2026-108272] Forged cryptographic signature status in incoming GnuPG + and S/MIME mail. On systems that decrypt or verify incoming mail, any + sender can craft an encrypted message that makes RT record and display a + signature status of their choosing, including a forged "signed by" + identity. This affects only the status shown in ticket history, not RT's + access control or outgoing encryption decisions. + - [CVE-2026-108350] Signature trust check bypass in incoming S/MIME mail. + On systems that process incoming S/MIME mail (not enabled by default), RT + skips its certificate trust check for certain signing certificates and + reports the message as validly signed. It also accepts the message when + RT is configured to reject mail that fails verification. + - [CVE-2026-108349] Unauthenticated denial of service via unbounded CSS + cache growth. RT's combined stylesheet handler can be reached without + logging in, and it caches each requested variant without limit. Anyone + who can send requests to the RT web server can grow every web process's + memory until the system runs out. + - [CVE-2026-108348] Security tokens and password salts generated with a + non-cryptographic random number generator. REST 2.0 authentication + tokens, RSS and iCal feed tokens, CSRF tokens and password salts were + generated with Perl's rand(). An authenticated user could attempt to + predict another user's tokens, though at substantial cost and under + conditions the attacker does not control. + + -- Andrew Ruthven Tue, 24 Nov 2026 23:26:02 +1300 + request-tracker5 (5.0.7+dfsg-4+deb13u3) trixie-security; urgency=high * Include missing default configuration items for security vulnerability diff -Nru request-tracker5-5.0.7+dfsg/debian/control request-tracker5-5.0.7+dfsg/debian/control --- request-tracker5-5.0.7+dfsg/debian/control 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/control 2026-11-22 08:53:30.000000000 +0000 @@ -19,6 +19,7 @@ libconvert-color-perl, libcpanel-json-xs-perl, libcrypt-eksblowfish-perl, + libcrypt-urandom-perl, libcrypt-x509-perl, libcss-squish-perl, libdata-guid-perl, @@ -159,6 +160,7 @@ libconvert-color-perl, libcpanel-json-xs-perl, libcrypt-eksblowfish-perl, + libcrypt-urandom-perl, libcrypt-x509-perl, libcss-minifier-xs-perl, libcss-squish-perl, diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-4.4.diff request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-4.4.diff --- request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-4.4.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-4.4.diff 2026-11-22 08:53:30.000000000 +0000 @@ -1,4 +1,4 @@ -From dd4e7d0f705ba5173a61c7a674b3184a063b9c61 Mon Sep 17 00:00:00 2001 +From 75e762734753a7d691c453504ebf929bb49d8a10 Mon Sep 17 00:00:00 2001 From: Andrew Ruthven Date: Wed, 21 May 2025 20:38:16 +1200 Subject: Debianize UPGRADING-4.4 diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-5.0.diff request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-5.0.diff --- request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-5.0.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/debianize_UPGRADING-5.0.diff 2026-11-22 08:53:30.000000000 +0000 @@ -1,4 +1,4 @@ -From f5de3aebd09b261a65e913c94db557dc565a2745 Mon Sep 17 00:00:00 2001 +From 4f5b20c6679ee29fc49713f0bee7231aaa5d44c3 Mon Sep 17 00:00:00 2001 From: Andrew Ruthven Date: Wed, 21 May 2025 20:29:22 +1200 Subject: Debianize UPGRADING-5.0 diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/downgrade_Crypt::URandom.diff request-tracker5-5.0.7+dfsg/debian/patches/downgrade_Crypt::URandom.diff --- request-tracker5-5.0.7+dfsg/debian/patches/downgrade_Crypt::URandom.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/downgrade_Crypt::URandom.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,25 @@ +From cf40059b2bf011517f3d173c236b5d70b84cb97f Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 18 Oct 2026 14:11:02 +1300 +Subject: Crypt::URandom 0.54 in Debian contains the security fix in 0.55 + +Patch-Name: downgrade_Crypt::URandom.diff +Author: Andrew Ruthven +Forwarded: not-needed +--- + etc/cpanfile | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/etc/cpanfile b/etc/cpanfile +index 65658ca4..f09ff54d 100644 +--- a/etc/cpanfile ++++ b/etc/cpanfile +@@ -11,7 +11,7 @@ requires 'Class::Accessor::Fast'; + requires 'Clone'; + requires 'Convert::Color'; + requires 'Crypt::Eksblowfish'; +-requires 'Crypt::URandom', '>= 0.55'; ++requires 'Crypt::URandom', '>= 0.54'; + requires 'CSS::Minifier::XS'; + requires 'CSS::Squish', '>= 0.06'; + requires 'Data::GUID'; diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/series request-tracker5-5.0.7+dfsg/debian/patches/series --- request-tracker5-5.0.7+dfsg/debian/patches/series 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/series 2026-11-22 08:53:30.000000000 +0000 @@ -27,10 +27,17 @@ use-io-socket-inet-in-tests.diff upstream_5.0.7_cve:_patchset_2025-04-08.diff upstream_5.0.7_cve:_patchset_2025-04-11.diff -upstream_5.0.8_test_web:_patchset_2025-04-08.diff +upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff debianize_UPGRADING-5.0.diff debianize_UPGRADING-4.4.diff upstream_5.0.7_cve:_patchset_2025-10-07.diff upstream_5.0.7_cve:_patchset_2026-05-05.diff upstream_5.0.7_cve:_patchset_2026-05-05-RT_Config.diff upstream_5.0.7_cve:_patchset_2025-04-08-RT_Config.diff +upstream_5.0.7_cve:_patchset_2026-10-15.diff +downgrade_Crypt::URandom.diff +upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff +upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff +upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff +upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff +upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08-RT_Config.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08-RT_Config.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08-RT_Config.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08-RT_Config.diff 2026-11-22 08:53:30.000000000 +0000 @@ -1,4 +1,4 @@ -From 7303c128c840cc9046320ec0591aaaeca953155c Mon Sep 17 00:00:00 2001 +From 2ae9faa3238692c63c85feed205412ef595780b2 Mon Sep 17 00:00:00 2001 From: Andrew Ruthven Date: Wed, 27 May 2026 20:47:49 +1200 Subject: Config settings for RestrictLinkDomains, and Cipher in SMIME. diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,27 @@ +From 20ebb9c9f8567bc9433c4e46d7fe194997770e22 Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 4 May 2025 17:25:39 +1200 +Subject: Fix test for 2025-04-08 CVE patchset + +Patch-Name: upstream_5.0.7_cve:_patchset_2025-04-08_test_fixes.diff +Author: Best Practical +Forwarded: not-needed +Applied: 5.0.8, commit:cb67ffa28333418178cb2f7be3562cb8d1817c63 +--- + t/web/helpers-http-cache-headers.t | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/t/web/helpers-http-cache-headers.t b/t/web/helpers-http-cache-headers.t +index c946daf4..4c4fdcfd 100644 +--- a/t/web/helpers-http-cache-headers.t ++++ b/t/web/helpers-http-cache-headers.t +@@ -97,6 +97,9 @@ foreach my $endpoint ( @endpoints ) { + if ( $endpoint =~ m{/Helpers/AssetUpdate} ) { + $m->get_ok( $endpoint . "?id=${asset_id}&Status=allocated" ); + } ++ elsif ( $endpoint =~ m{/Helpers/Permalink} ) { ++ $m->get_ok( $endpoint . "?URL=/" ); ++ } + else { + $m->get_ok( $endpoint . "?id=${ticket_id}&Status=open&Requestor=root" ); + } diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-10-07.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-10-07.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-10-07.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2025-10-07.diff 2026-11-22 08:53:30.000000000 +0000 @@ -1,4 +1,4 @@ -From 72d03f2d58a19d24c22aaf30fe8a2290fa26fc29 Mon Sep 17 00:00:00 2001 +From a7eb7717b3772e6ab97e00ec86fce6e9a5014f84 Mon Sep 17 00:00:00 2001 From: Andrew Ruthven Date: Wed, 8 Oct 2025 21:16:17 +1300 Subject: Fix for CVE-2025-61873 and CVE-2025-9158 diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05-RT_Config.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05-RT_Config.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05-RT_Config.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05-RT_Config.diff 2026-11-22 08:53:30.000000000 +0000 @@ -1,4 +1,4 @@ -From d5e631243d71f068cdce29a727fd84660fbfce42 Mon Sep 17 00:00:00 2001 +From 594af48ad973f075f9d855c479b36048c2d1cf64 Mon Sep 17 00:00:00 2001 From: Andrew Ruthven Date: Wed, 27 May 2026 20:37:45 +1200 Subject: Config settings for EnableRSS and EnableICal diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-05-05.diff 2026-11-22 08:53:30.000000000 +0000 @@ -1,4 +1,4 @@ -From ff22da9bbe33543f8dfd46a2c3de153a81abfc24 Mon Sep 17 00:00:00 2001 +From fe710572aaf51e36ddf0f86328d7b205dec19d94 Mon Sep 17 00:00:00 2001 From: Andrew Ruthven Date: Fri, 22 May 2026 22:14:01 +1200 Subject: Fix seven security issues in RT. diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,4639 @@ +From 5939050f85b91d8ecf1e1bba9ab1df2e27b3443d Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 18 Oct 2026 13:29:54 +1300 +Subject: Fix 28 security issues in RT. + +Resolve vulnerabilities that allow code execution and privilege escalation: + +- [CVE-2026-108351] Remote code execution via an ExecuteCode right bypass in + template administration. A user granted ModifyTemplate but not ShowTemplate + (ShowGlobalTemplates for global templates) can alter the body of an existing + Perl template without holding ExecuteCode. RT's standard scrips then run that + code during ordinary ticket activity as the operating-system user the web + server runs as. The bypass also defeats $DisallowExecuteCode. +- [CVE-2026-108353] Privilege escalation via the REST group and group + membership endpoints. A user with SeeGroup and AdminGroup on a single + user-defined group can convert it, through REST 2.0, into a role group of + another object (for example, the AdminCc role of an arbitrary queue) and + inherit that role's rights. Separately, a user holding only + ModifyOwnMembership can use the REST interfaces to add themselves to queue or + ticket role groups, or to RT's internal Privileged group. +- [CVE-2026-108279] Privilege escalation via a Cross-Site Request Forgery + (CSRF) protection bypass in the URL shortener. RT decided whether a request + needed CSRF confirmation before it expanded a short link, so the arguments + the link carried were never checked. Any authenticated user with global + ShowTicket can create a short link that, when followed by an administrator + holding ModifyACL or SuperUser, silently performs a rights change such as + granting the attacker SuperUser. +- [CVE-2026-108275] Cross-queue ticket modification and disclosure via + CreateTickets scrip action templates. A user holding the queue-level + ModifyTemplate and ModifyScrips rights on one queue can write a plain + (non-Perl) template that creates or updates tickets in other queues, which + RT carries out as the system user. This allows modifying tickets in queues + the user has no rights on, and reading them by moving them into a queue the + user can see. + +Resolve vulnerabilities that allow authorization bypass and information +disclosure: + +- [CVE-2026-108270] Authorization bypass and information disclosure in ticket + forwarding. A user holding ForwardMessage on any single ticket can cause RT + to email the content and attachments of any transaction in the instance to an + address of their choosing, including correspondence on tickets they cannot + see. Separately, a user with ForwardMessage but not ShowTicket on a ticket + can forward that ticket's correspondence to themselves. +- [CVE-2026-108274] Insecure direct object reference in custom field values. A + custom field value can be addressed by its id without checking that it + belongs to an object the user may access. A user who can see a custom field + can download that field's values from tickets they cannot see, through the + web interface or REST 2.0, and a user who can modify a custom field can + create, overwrite or delete its values on any object in the instance. At + least one write path is reachable from a self-service preferences page. +- [CVE-2026-108278] Information disclosure via RSS feed URLs. The + authentication string in an RSS feed URL is not bound to the search the URL + was issued for, so anyone who obtains a feed URL can substitute their own + search and have it run with the feed owner's rights. This can expose the + subject and first message of every ticket the feed owner can read. iCal feeds + are not affected. +- [CVE-2026-108271] Incorrect authorization of the destination in several + operations. RT checked the user's rights on the record being changed but not + on the place it was being moved to, in dashboard editing, the search + builder's saved-search panel, article editing (web interface and REST 2.0), + the REST 2.0 custom field value endpoint, and REST 2.0 ticket creation. An + authenticated user can publish a dashboard or saved search system-wide or to + a group they cannot publish to, move an article into a class they cannot + create articles in, or attach history to a ticket they have no rights on. The + REST 2.0 custom field value endpoint also disclosed custom field value + definitions by id. +- [CVE-2026-108273] Ticket recipient disclosure on the ticket People and Update + pages. A user granted ReplyToTicket but not ShowTicket on a ticket can read + the ticket's requestor, owner, Cc and AdminCc email addresses, and the member + of a single-value custom role. +- [CVE-2026-108276] Information disclosure via the REST 1.0 group endpoint. Any + privileged (staff) user can retrieve a group's name, description, membership + (including members' names and email addresses) and custom field values + without SeeGroup. Because any group id is accepted, this also exposes the + watchers of queues, tickets and assets the user cannot see. +- [CVE-2026-108280] Missing object-level authorization on queue, catalog, + custom field and article class administration pages. A user with + ShowConfigTab can read and change default values for any queue, asset catalog + and custom field, and the settings of any article class, without AdminQueue, + AdminCatalog, AdminCustomField or AdminClass on that object. +- [CVE-2026-108281] Missing authorization on scrip and custom field ordering. + A user with ShowConfigTab can reorder scrips, change the processing stage of + global scrips, and reorder global custom fields without ModifyScrips or + AssignCustomFields. Reordering or restaging scrips can change the outcome of + RT's automated actions. +- [CVE-2026-108352] Missing authorization in the custom field and custom role + editing pages. A user with only ShowConfigTab can change the object type a + custom field or custom role applies to. RT removes the field's or role's + existing applications before it denies the request, so the field or role + disappears from the objects it was used on. +- [CVE-2026-108347] Information disclosure via ticket relationship graphs. A + user viewing a ticket's relationship graph sees the owner and custom field + values of every linked ticket, even tickets they cannot see. A user with + ModifyTicket on any ticket can link it to an arbitrary ticket to read that + information. Ticket subjects are not exposed. +- [CVE-2026-108346] Disclosure of hidden ticket time fields. On systems that + enable $HideTimeFieldsFromUnprivilegedUsers (off by default), unprivileged + users can still read time worked, estimated and left, and per-transaction + time details, on tickets they can see, through the Self Service export and + REST 2.0, and can infer them through search. +- [CVE-2026-108282] Insecure direct object reference in saved search handling. + The search builder, saved chart search page, article search page and the + saved-search dashboard portlet accept a saved-setting id without confirming + it belongs to the owner named in the request. An authenticated user can read + another user's private saved searches, take over another user's private + dashboard, change another user's dashboard subscription, and delete a queue's + stored encryption setting, which turns off outgoing encryption for that + queue. + +Resolve vulnerabilities that allow Cross-Site Request Forgery (CSRF): + +- [CVE-2026-108371] CSRF on the search chart page. The saved-search controls + on the chart page were not covered by RT's CSRF protection, so a malicious + web page can create, overwrite or delete a logged-in user's saved chart + searches, including those shared with groups or the whole system. +- [CVE-2026-108365] CSRF in the Rights Inspector. The Rights Inspector's revoke + action was not covered by RT's CSRF protection, so a malicious web page can + make a logged-in user holding ModifyACL revoke a rights grant. +- [CVE-2026-108277] CSRF via cookie-authenticated REST 2.0 requests. + State-changing REST 2.0 requests authenticated with the web session cookie + are not covered by RT's CSRF protection. With RT's default SameSite=Lax + cookie policy, exploitation requires content served from a same-site origin, + such as a sibling subdomain or another port on the RT host. REST 2.0 clients + that authenticate with an Authorization header are not affected. +- [CVE-2026-108344] Login CSRF on the password login form. On systems that + enable $RestrictLoginReferrer (off by default), the referrer check runs after + the session is created, so an attacker with any valid account can log a + user's browser into the attacker's account. Work the user then submits is + recorded in, and readable from, that account. + +Resolve vulnerabilities that allow Cross-Site Scripting (XSS): + +- [CVE-2026-108342] Multiple stored and reflected XSS vulnerabilities from + insufficient HTML escaping. Affected areas include the meeting invitation + display in ticket history, HTML ticket content, group and user display names, + administrator-managed object names, Wikitext custom field values, table-style + chart labels, ticket relationship graphs, the article chooser, dashboard + subscription and dashboard component pages, saved-search and search result + format handling, transaction and history views, and file downloads with + attacker-controlled content types. Some of these require no RT account: on a + queue that accepts mail from the public, an outside sender can store a + payload that runs when staff view the ticket. +- [CVE-2026-105454] Stored XSS via crafted URLs in HTML ticket content. RT's + automatic link creation for URLs in HTML ticket content does not escape the + URL, so a crafted URL can add script that runs when the ticket history is + displayed, with no click needed. An outside sender of HTML email to a public + queue can plant it. +- [CVE-2026-108363] Reflected XSS in the advanced lifecycle editor. Request + content is written back into the editor without escaping. Exploitation + requires an administrator with ShowConfigTab and SuperUser to follow a + crafted link and click through RT's CSRF confirmation page. +- [CVE-2026-108343] Stored XSS via custom field link URLs. Custom fields + configured to render their own value as a link (IncludeContentForValue or + LinkValueTo pointing at the field's value) do not reliably reject executable + URL schemes. RT ships no custom fields configured this way. +- [CVE-2026-108272] Forged cryptographic signature status in incoming GnuPG and + S/MIME mail. On systems that decrypt or verify incoming mail, any sender can + craft an encrypted message that makes RT record and display a signature + status of their choosing, including a forged "signed by" identity. This + affects only the status shown in ticket history, not RT's access control or + outgoing encryption decisions. +- [CVE-2026-108350] Signature trust check bypass in incoming S/MIME mail. On + systems that process incoming S/MIME mail (not enabled by default), RT skips + its certificate trust check for certain signing certificates and reports the + message as validly signed. It also accepts the message when RT is configured + to reject mail that fails verification. + +Resolve vulnerabilities for other issues: + +- [CVE-2026-108349] Unauthenticated denial of service via unbounded CSS cache + growth. RT's combined stylesheet handler can be reached without logging in, + and it caches each requested variant without limit. Anyone who can send + requests to the RT web server can grow every web process's memory until the + system runs out. +- [CVE-2026-108348] Security tokens and password salts generated with a + non-cryptographic random number generator. REST 2.0 authentication tokens, + RSS and iCal feed tokens, CSRF tokens and password salts were generated with + Perl's rand(). An authenticated user could attempt to predict another user's + tokens, though at substantial cost and under conditions the attacker does not + control. + +Patch-Name: upstream_5.0.7_cve:_patchset_2026-10-15.diff +Author: Best Practical +Forwarded: not-needed +Applied: 5.0.11 +--- + etc/RT_Config.pm | 7 + + etc/cpanfile | 1 + + lib/RT/Action/CreateTickets.pm | 144 +++++++++---- + lib/RT/Action/SendForward.pm | 25 ++- + lib/RT/Article.pm | 13 ++ + lib/RT/Attribute.pm | 18 ++ + lib/RT/AuthToken.pm | 30 +-- + lib/RT/Config.pm | 25 +-- + lib/RT/Crypt.pm | 41 +++- + lib/RT/Crypt/SMIME.pm | 68 +++--- + lib/RT/CustomField.pm | 51 ++++- + lib/RT/CustomRole.pm | 5 + + lib/RT/Graph/Tickets.pm | 18 +- + lib/RT/Interface/Email/Crypt.pm | 19 ++ + lib/RT/Interface/Web.pm | 203 ++++++++++++++++-- + lib/RT/Interface/Web/MenuBuilder.pm | 32 ++- + lib/RT/ObjectCustomFieldValue.pm | 61 ++++-- + lib/RT/REST2/Middleware/Auth.pm | 45 ++++ + lib/RT/REST2/Resource.pm | 4 + + lib/RT/REST2/Resource/CustomFieldValue.pm | 34 ++- + lib/RT/REST2/Resource/Group.pm | 28 ++- + lib/RT/REST2/Resource/GroupMembers.pm | 25 ++- + lib/RT/REST2/Resource/Groups.pm | 12 ++ + .../REST2/Resource/ObjectCustomFieldValue.pm | 10 +- + lib/RT/REST2/Resource/Record/Writable.pm | 20 ++ + lib/RT/REST2/Resource/Ticket.pm | 26 ++- + lib/RT/REST2/Resource/Transactions.pm | 6 +- + lib/RT/REST2/Resource/UserGroups.pm | 8 +- + lib/RT/Record.pm | 8 + + lib/RT/Report.pm | 48 +++-- + lib/RT/Report/Entry.pm | 15 +- + lib/RT/SavedSearch.pm | 46 ++++ + lib/RT/SharedSetting.pm | 64 ++++-- + lib/RT/Template.pm | 155 ++++++++++++- + lib/RT/Ticket.pm | 48 ++++- + lib/RT/Tickets.pm | 21 ++ + lib/RT/Transaction.pm | 54 +++++ + lib/RT/Transactions.pm | 35 +++ + lib/RT/URI/attribute.pm | 10 + + lib/RT/URI/base.pm | 11 + + lib/RT/User.pm | 69 ++++-- + lib/RT/Util.pm | 101 ++++++++- + share/html/Admin/Articles/Classes/Modify.html | 23 +- + .../Admin/Assets/Catalogs/DefaultValues.html | 3 + + share/html/Admin/CustomFields/Modify.html | 15 +- + share/html/Admin/Elements/EditCustomFields | 2 +- + share/html/Admin/Global/Scrips.html | 5 + + share/html/Admin/Lifecycles/Advanced.html | 4 +- + share/html/Admin/Queues/DefaultValues.html | 3 + + share/html/Admin/Queues/Modify.html | 10 +- + share/html/Admin/Queues/Scrips.html | 5 + + share/html/Admin/Scrips/Objects.html | 9 +- + share/html/Articles/Article/Edit.html | 124 +++++------ + share/html/Articles/Elements/BeforeMessageBox | 3 +- + share/html/Dashboards/Subscription.html | 4 +- + share/html/Download/CustomFieldValue/dhandler | 6 +- + share/html/Elements/CollectionAsTable/Header | 2 +- + share/html/Elements/DoAuth | 4 + + share/html/Elements/Lifecycle/Graph | 9 +- + share/html/Elements/MakeClicky | 7 +- + share/html/Elements/SelectCustomFieldValue | 2 +- + share/html/Elements/SelectOwnerDropdown | 2 +- + share/html/Elements/SelectSLA | 2 +- + share/html/Elements/ShowCustomFieldWikitext | 3 +- + share/html/Elements/ShowCustomFields | 9 +- + share/html/Elements/ShowPrincipal | 3 +- + share/html/Elements/ShowTransaction | 17 ++ + .../html/Elements/ShowTransactionAttachments | 18 +- + share/html/Helpers/PreviewScrips | 6 + + share/html/Helpers/ShowSimplifiedRecipients | 5 + + share/html/NoAuth/css/dhandler | 2 + + share/html/NoAuth/rss/dhandler | 38 ++-- + share/html/REST/1.0/Forms/group/customfields | 4 +- + share/html/REST/1.0/Forms/group/default | 8 +- + share/html/REST/1.0/Forms/group/ns | 6 +- + share/html/REST/1.0/Forms/queue/ns | 5 +- + share/html/REST/1.0/search/dhandler | 1 + + share/html/Search/Elements/ConditionRow | 11 +- + share/html/Search/Elements/EditSearches | 47 ++-- + share/html/Search/Results.html | 5 +- + share/html/Ticket/Attachment/dhandler | 4 +- + share/html/Ticket/Display.html | 10 +- + share/html/Ticket/Forward.html | 6 +- + share/html/Ticket/Graphs/index.html | 2 + + share/html/Ticket/History.html | 5 +- + share/html/Ticket/Modify.html | 10 +- + share/html/Ticket/ModifyAll.html | 10 +- + share/html/Ticket/ModifyDates.html | 8 + + share/html/Ticket/ModifyLinks.html | 8 + + share/html/Ticket/ModifyPeople.html | 8 + + share/html/Ticket/Reminders.html | 8 + + share/html/Ticket/Update.html | 9 + + share/html/Widgets/SavedSearch | 5 +- + share/html/m/ticket/reply | 9 + + share/html/m/ticket/show | 19 +- + share/static/js/bootstrap-combobox.js | 18 +- + 96 files changed, 1828 insertions(+), 407 deletions(-) + +diff --git a/etc/RT_Config.pm b/etc/RT_Config.pm +index c5fb38f7..9a9bc52a 100644 +--- a/etc/RT_Config.pm ++++ b/etc/RT_Config.pm +@@ -1201,6 +1201,11 @@ checked to ensure that requests come from RT's own domain. As RT allows + for GET requests to alter state, disabling this opens RT up to + cross-site request forgery (CSRF) attacks. + ++This also governs REST 2.0, where the C header is checked in ++preference to C on requests that are authenticated by a session ++cookie and change state. Requests that supply credentials explicitly, ++with an C header, are not subject to this check. ++ + =cut + + Set($RestrictReferrer, 1); +@@ -1213,6 +1218,8 @@ it to 1 forces all logins to come from the login box, so the + user is aware that they are being logged in. The default is off, for + backwards compatability. + ++Requires C<$RestrictReferrer> to also be enabled for full coverage. ++ + =cut + + Set($RestrictLoginReferrer, 0); +diff --git a/etc/cpanfile b/etc/cpanfile +index d0cb7d27..65658ca4 100644 +--- a/etc/cpanfile ++++ b/etc/cpanfile +@@ -11,6 +11,7 @@ requires 'Class::Accessor::Fast'; + requires 'Clone'; + requires 'Convert::Color'; + requires 'Crypt::Eksblowfish'; ++requires 'Crypt::URandom', '>= 0.55'; + requires 'CSS::Minifier::XS'; + requires 'CSS::Squish', '>= 0.06'; + requires 'Data::GUID'; +diff --git a/lib/RT/Action/CreateTickets.pm b/lib/RT/Action/CreateTickets.pm +index ae058042..51641a6b 100644 +--- a/lib/RT/Action/CreateTickets.pm ++++ b/lib/RT/Action/CreateTickets.pm +@@ -261,6 +261,32 @@ When parsed, field names are converted to lowercase and have hyphens stripped. + C, C, C, C and C will + all be treated as the same thing. + ++=head2 Rights ++ ++There are several rights that manage who can create and modify templates ++that can be used with CreateTickets. ++ ++It is possible to give a user C and C at the ++queue level, allowing them to manage their own queue. This configuration is ++most commonly used to allow queue-level admins to create and modify templates ++used for email, but it can allow them to create templates for CreateTickets ++also. ++ ++With these queue-level rights, and access to Simple type templates only, ++queue-level admins can configure templates that create and update tickets ++only in that same queue. They also cannot add code as shown in the examples ++above, just static values. This is unlikely to be very useful for most ++scenarios where CreateTickets is used, like automatically creating a ticket ++in another queue based on some event. To get the most out of CreateTickets, ++a user with more rights will typically need to set them up. ++ ++A C or a user with the C right is able to use Perl ++templates and add Perl code directly to the template sections, as shown ++in the examples above. Note that granting C is a powerful right ++that allows users to run any code on the server, including writing code to ++run in scrip conditions and actions. As such, setting up CreateTickets ++actions is usually done by admins with these privileges. ++ + =head1 METHODS + + =cut +@@ -663,52 +689,9 @@ sub ParseLines { + + my $TicketObj ||= RT::Ticket->new( $self->CurrentUser ); + +- my %args; +- my %original_tags; +- my @lines = ( split( /\n/, $content ) ); +- while ( defined( my $line = shift @lines ) ) { +- if ( $line =~ /^(.*?):(?:\s+)(.*?)(?:\s*)$/ ) { +- my $value = $2; +- my $original_tag = $1; +- my $tag = lc($original_tag); +- $tag =~ s/-//g; +- $tag =~ s/^(requestor|cc|admincc)s?$/$1/i; +- +- $original_tags{$tag} = $original_tag; +- +- if ( ref( $args{$tag} ) ) +- { #If it's an array, we want to push the value +- push @{ $args{$tag} }, $value; +- } elsif ( defined( $args{$tag} ) ) +- { #if we're about to get a second value, make it an array +- $args{$tag} = [ $args{$tag}, $value ]; +- } else { #if there's nothing there, just set the value +- $args{$tag} = $value; +- } +- +- if ( $tag =~ /^content$/i ) { #just build up the content +- # convert it to an array +- $args{$tag} = defined($value) ? [ $value . "\n" ] : []; +- while ( defined( my $l = shift @lines ) ) { +- last if ( $l =~ /^ENDOFCONTENT\s*$/ ); +- push @{ $args{'content'} }, $l . "\n"; +- } +- } else { +- # if it's not content, strip leading and trailing spaces +- if ( $args{$tag} ) { +- $args{$tag} =~ s/^\s+//g; +- $args{$tag} =~ s/\s+$//g; +- } +- if ( +- ($tag =~ /^(requestor|cc|admincc)(group)?$/i +- or grep {lc $_ eq $tag} keys %RT::Link::TYPEMAP) +- and $args{$tag} =~ /,/ +- ) { +- $args{$tag} = [ split /,\s*/, $args{$tag} ]; +- } +- } +- } +- } ++ my ( $args, $original_tags ) = $self->ParseFields($content); ++ my %args = %$args; ++ my %original_tags = %$original_tags; + + foreach my $date (qw(due starts started resolved)) { + my $dateobj = RT::Date->new( $self->CurrentUser ); +@@ -814,6 +797,75 @@ sub ParseLines { + } + + ++=head2 ParseFields CONTENT ++ ++Parses the C lines of a single template block, as produced by ++L, into the fields the directive will act on. ++ ++Field names are lowercased and have hyphens stripped, so C, C ++and C are all the C field. A field named more than once becomes ++an arrayref. A C field takes every following line up to ++C, so lines in a ticket's body are not fields. ++ ++Returns two hashrefs: the fields, and the original name each was written with. ++ ++=cut ++ ++sub ParseFields { ++ my $self = shift; ++ my $content = shift; ++ ++ my %args; ++ my %original_tags; ++ my @lines = ( split( /\n/, $content ) ); ++ while ( defined( my $line = shift @lines ) ) { ++ if ( $line =~ /^(.*?):(?:\s+)(.*?)(?:\s*)$/ ) { ++ my $value = $2; ++ my $original_tag = $1; ++ my $tag = lc($original_tag); ++ $tag =~ s/-//g; ++ $tag =~ s/^(requestor|cc|admincc)s?$/$1/i; ++ ++ $original_tags{$tag} = $original_tag; ++ ++ if ( ref( $args{$tag} ) ) ++ { #If it's an array, we want to push the value ++ push @{ $args{$tag} }, $value; ++ } elsif ( defined( $args{$tag} ) ) ++ { #if we're about to get a second value, make it an array ++ $args{$tag} = [ $args{$tag}, $value ]; ++ } else { #if there's nothing there, just set the value ++ $args{$tag} = $value; ++ } ++ ++ if ( $tag =~ /^content$/i ) { #just build up the content ++ # convert it to an array ++ $args{$tag} = defined($value) ? [ $value . "\n" ] : []; ++ while ( defined( my $l = shift @lines ) ) { ++ last if ( $l =~ /^ENDOFCONTENT\s*$/ ); ++ push @{ $args{'content'} }, $l . "\n"; ++ } ++ } else { ++ # if it's not content, strip leading and trailing spaces ++ if ( $args{$tag} ) { ++ $args{$tag} =~ s/^\s+//g; ++ $args{$tag} =~ s/\s+$//g; ++ } ++ if ( ++ ($tag =~ /^(requestor|cc|admincc)(group)?$/i ++ or $tag =~ /^(customrole|cr)-?(.+)$/i ++ or grep {lc $_ eq $tag} keys %RT::Link::TYPEMAP) ++ and $args{$tag} =~ /,/ ++ ) { ++ $args{$tag} = [ split /,\s*/, $args{$tag} ]; ++ } ++ } ++ } ++ } ++ ++ return ( \%args, \%original_tags ); ++} ++ + =head2 _ParseXSVTemplate + + Parses a tab or comma delimited template. Should only ever be called by +diff --git a/lib/RT/Action/SendForward.pm b/lib/RT/Action/SendForward.pm +index 28e5ae42..e567924f 100644 +--- a/lib/RT/Action/SendForward.pm ++++ b/lib/RT/Action/SendForward.pm +@@ -65,10 +65,22 @@ sub Prepare { + + my $txn = $self->TransactionObj; + ++ my $forwarded; ++ my $creator = RT::CurrentUser->new( $txn->Creator ); + if ( $txn->Type eq 'Forward Transaction' ) { +- my $forwarded_txn = RT::Transaction->new( $self->CurrentUser ); +- $forwarded_txn->Load( $txn->Field ); +- $self->{ForwardedTransactionObj} = $forwarded_txn; ++ $forwarded = RT::Transaction->new($creator); ++ $forwarded->Load( $txn->Field ); ++ $self->{ForwardedTransactionObj} = $forwarded; ++ } ++ else { ++ $forwarded = RT::Ticket->new($creator); ++ $forwarded->Load( $self->TicketObj->id ); ++ $self->{ForwardedTicketObj} = $forwarded; ++ } ++ ++ unless ( $creator->id && $forwarded->id && $forwarded->CurrentUserCanSee ) { ++ RT->Logger->error( "Not forwarding transaction " . $txn->id . ": not visible to its creator" ); ++ return undef; + } + + my ( $result, $message ) = $self->TemplateObj->Parse( +@@ -90,7 +102,7 @@ sub Prepare { + $entity = $self->ForwardedTransactionObj->ContentAsMIME; + } + else { +- my $txns = $self->TicketObj->Transactions; ++ my $txns = $self->ForwardedTicketObj->Transactions; + $txns->Limit( + FIELD => 'Type', + OPERATOR => 'IN', +@@ -133,6 +145,11 @@ sub ForwardedTransactionObj { + return $self->{'ForwardedTransactionObj'}; + } + ++sub ForwardedTicketObj { ++ my $self = shift; ++ return $self->{'ForwardedTicketObj'}; ++} ++ + RT::Base->_ImportOverlays(); + + 1; +diff --git a/lib/RT/Article.pm b/lib/RT/Article.pm +index 3b8449db..932a237c 100644 +--- a/lib/RT/Article.pm ++++ b/lib/RT/Article.pm +@@ -524,6 +524,19 @@ sub SetClass { + return ( 0, $self->loc("Permission Denied") ); + } + ++ # An article must always belong to a valid class. Reject empty/undef/0 ++ # or any value that doesn't load a class, mirroring Create. ++ my $class = RT::Class->new( $self->CurrentUser ); ++ $class->Load($value) if defined $value && length $value; ++ unless ( $class->Id ) { ++ return ( 0, $self->loc('Invalid Class') ); ++ } ++ $value = $class->Id; # normalize a class name to its id ++ ++ if ( $value != $self->__Value('Class') ) { ++ return ( 0, $self->loc("Permission Denied") ) unless $class->CurrentUserHasRight('CreateArticle'); ++ } ++ + # Confirm the name isn't already used in the destination class + if ( $self->ValidateName( $self->Name, $value ) ) { + return ( $self->_Set( Field => 'Class', Value => $value ) ); +diff --git a/lib/RT/Attribute.pm b/lib/RT/Attribute.pm +index fd8d1221..3cddf703 100644 +--- a/lib/RT/Attribute.pm ++++ b/lib/RT/Attribute.pm +@@ -89,6 +89,13 @@ our $PERSONAL_ACL_MAP = { + + }; + ++our $SYSTEM_ACL_MAP = { ++ SavedSearch => { create => 'SuperUser', ++ update => 'SuperUser', ++ delete => 'SuperUser' }, ++ ++}; ++ + =head2 LookupObjectRight { ObjectType => undef, ObjectId => undef, Name => undef, Right => { create, update, delete, display } } + + Returns the right that the user needs to have on this attribute's object to perform the related attribute operation. Returns "allow" if the right is otherwise unspecified. +@@ -103,6 +110,17 @@ sub LookupObjectRight { + Name => undef, + @_); + ++ # if it's an attribute on the whole instance, check the system acl map first ++ if ( $args{'ObjectType'} eq 'RT::System' ) { ++ my $right = $SYSTEM_ACL_MAP->{ $args{'Name'} // '' }{ $args{'Right'} // '' }; ++ return $right if $right; ++ } ++ ++ # RT's built-in searches: shown to everyone, shared by everyone ++ if ( ( $args{'Name'} // '' ) =~ /^Search - / ) { ++ return ( $args{'Right'} // '' ) eq 'display' ? 'allow' : 'SuperUser'; ++ } ++ + # if it's an attribute on oneself, check the personal acl map + if (($args{'ObjectType'} eq 'RT::User') && ($args{'ObjectId'} eq $self->CurrentUser->Id)) { + return('allow') unless ($PERSONAL_ACL_MAP->{$args{'Name'}}); +diff --git a/lib/RT/AuthToken.pm b/lib/RT/AuthToken.pm +index 37502a2f..0e43819c 100644 +--- a/lib/RT/AuthToken.pm ++++ b/lib/RT/AuthToken.pm +@@ -55,7 +55,6 @@ use base 'RT::Record'; + + require RT::User; + require RT::Util; +-use Digest::SHA 'sha512_hex'; + + =head1 NAME + +@@ -113,12 +112,22 @@ sub Create { + || $self->CurrentUserHasRight('AdminUsers'); + + my $token = $self->_GenerateToken; ++ unless ( defined $token ) { ++ RT->Logger->error("Couldn't generate an auth token for user $args{Owner}"); ++ return (0, $self->loc("Could not generate a secure token")); ++ } ++ ++ my $crypted = $self->_CryptToken($token); ++ unless ( defined $crypted ) { ++ RT->Logger->error("Couldn't hash an auth token for user $args{Owner}"); ++ return (0, $self->loc("Could not generate a secure token")); ++ } + + # delete Expires arg if it is empty + delete $args{Expires} unless $args{Expires}; + + my ( $id, $msg ) = $self->SUPER::Create( +- Token => $self->_CryptToken($token), ++ Token => $crypted, + map { $_ => $args{$_} } grep {exists $args{$_}} + qw(Owner Description Expires), + ); +@@ -273,7 +282,11 @@ sub IsToken { + + # We got here by validating successfully, but with a legacy + # password form. Update to the most recent form. +- $self->_Set(Field => 'Token', Value => $self->_CryptToken($value)); ++ # The token was valid; if it cannot be rehashed right now, leave it in its ++ # old form rather than replacing a working token with nothing. ++ if ( defined( my $rehashed = $self->_CryptToken($value) ) ) { ++ $self->_Set( Field => 'Token', Value => $rehashed ); ++ } + return 1; + } + +@@ -350,16 +363,7 @@ Generates an unpredictable auth token + + sub _GenerateToken { + my $class = shift; +- require Time::HiRes; +- +- my $input = join '', +- Time::HiRes::time(), # subsecond-precision time +- {}, # unpredictable memory address +- rand(); # RNG +- +- my $digest = sha512_hex($input); +- +- return substr($digest, 0, 32); ++ return RT::Util::random_hex(32); + } + + =head2 _BuildAuthString +diff --git a/lib/RT/Config.pm b/lib/RT/Config.pm +index 11c22a7e..a2f54c01 100644 +--- a/lib/RT/Config.pm ++++ b/lib/RT/Config.pm +@@ -54,7 +54,6 @@ use warnings; + use 5.010; + use File::Spec (); + use Symbol::Global::Name; +-use List::MoreUtils 'uniq'; + use Clone (); + + # Store log messages generated before RT::Logger is available +@@ -246,34 +245,14 @@ our %META; + WidgetArguments => { + Description => 'Theme', #loc + Callback => sub { +- state @stylesheets; +- unless (@stylesheets) { +- for my $static_path ( RT::Interface::Web->StaticRoots ) { +- my $css_path = +- File::Spec->catdir( $static_path, 'css' ); +- next unless -d $css_path; +- if ( opendir my $dh, $css_path ) { +- push @stylesheets, grep { +- -e File::Spec->catfile( $css_path, $_, 'main.css' ) +- } readdir $dh; +- } +- else { +- RT->Logger->error("Can't read $css_path: $!"); +- } +- } +- @stylesheets = sort { lc $a cmp lc $b } uniq @stylesheets; +- } +- return { Values => \@stylesheets }; ++ return { Values => [ RT::Interface::Web->Themes ] }; + }, + }, + PostLoadCheck => sub { + my $self = shift; + my $value = $self->Get('WebDefaultStylesheet'); + +- my @roots = RT::Interface::Web->StaticRoots; +- for my $root (@roots) { +- return if -d "$root/css/$value"; +- } ++ return if grep { $_ eq $value } RT::Interface::Web->Themes; + + $RT::Logger->warning( + "The default stylesheet ($value) does not exist in this instance of RT. " +diff --git a/lib/RT/Crypt.pm b/lib/RT/Crypt.pm +index a82d8b2c..74144946 100644 +--- a/lib/RT/Crypt.pm ++++ b/lib/RT/Crypt.pm +@@ -572,13 +572,11 @@ sub VerifyDecrypt { + %args, Protocol => $protected->{'Protocol'}, Info => $protected + ); + +- # Let the header be modified so continuations are handled +- my $modify = $res{status_on}->head->modify; +- $res{status_on}->head->modify(1); +- $res{status_on}->head->add( +- "X-RT-" . $protected->{'Protocol'} . "-Status" => Encode::encode( "UTF-8", $res{'status'} ) ++ $self->AddStatusHeader( ++ Entity => $res{status_on}, ++ Protocol => $protected->{'Protocol'}, ++ Status => $res{'status'}, + ); +- $res{status_on}->head->modify($modify); + + push @res, \%res; + } +@@ -589,6 +587,37 @@ sub VerifyDecrypt { + return @res; + } + ++=head2 AddStatusHeader Entity => ENTITY, Protocol => NAME, Status => STATUS ++ ++Records the C a crypt backend reported for protocol C on the ++L C, as an C-Status> header. Existing ++headers of that name are kept, since a single entity can be the subject of ++more than one operation. ++ ++=cut ++ ++sub AddStatusHeader { ++ my $self = shift; ++ my %args = ( ++ Entity => undef, ++ Protocol => undef, ++ Status => undef, ++ @_ ++ ); ++ ++ my $head = $args{'Entity'}->head; ++ ++ # Let the header be modified so continuations are handled ++ my $modify = $head->modify; ++ $head->modify(1); ++ $head->add( ++ "X-RT-" . $args{'Protocol'} . "-Status" => Encode::encode( "UTF-8", $args{'Status'} ) ++ ); ++ $head->modify($modify); ++ ++ return; ++} ++ + =head2 DecryptContent Protocol => NAME, Content => STRINGREF, [Passphrase => undef] + + Decrypts the content in the string reference in-place. All other +diff --git a/lib/RT/Crypt/SMIME.pm b/lib/RT/Crypt/SMIME.pm +index 778105e4..7b4e4218 100644 +--- a/lib/RT/Crypt/SMIME.pm ++++ b/lib/RT/Crypt/SMIME.pm +@@ -531,28 +531,45 @@ sub Verify { + return %res; + } + +- my $signer; +- if ( my $key = do { $keyfh->seek(0, 0); local $/; readline $keyfh } ) {{ +- my %info = $self->GetCertificateInfo( Certificate => $key ); ++ my $key = do { $keyfh->seek(0, 0); local $/; readline $keyfh }; ++ my %info = $key ? $self->GetCertificateInfo( Certificate => $key ) : (); ++ my $signer = $info{info}[0]; ++ ++ # openssl was run with -noverify above, so it checked the signature but ++ # not the certificate chain; the trust decision is made here instead. ++ # Every path from here to a success status must pass through it, so keep ++ # it out of the block below, which uses last to skip the optional work of ++ # recording the certificate on a user. ++ ++ unless ( $signer ) { ++ $res{exit_code} = 1; ++ $res{'message'} = "Validation failed"; ++ $res{'status'} = $self->FormatStatus({ ++ Operation => "Verify", Status => "BAD", ++ Message => "No signer certificate was found", ++ Trust => "NONE", ++ }); ++ return %res; ++ } + +- $signer = $info{info}[0]; +- last unless $signer and $signer->{User}[0]{String}; ++ unless ( $signer->{TrustLevel} > 0 or $opts->{AcceptUntrustedCAs} ) { ++ # We don't trust it, mark validation as failed ++ $res{exit_code} = 1; ++ $res{'message'} = "Validation failed"; ++ $res{'status'} = $self->FormatStatus({ ++ Operation => "Verify", Status => "BAD", ++ Message => "The signing CA was not trusted", ++ Serial => $signer->{'Serial Number'} || 'unknown', ++ UserString => $signer->{User}[0]{String} || 'unknown', ++ ExpireTimestamp => $signer->{Expire}->Unix(), ++ CreatedTimestamp => $signer->{Created}->Unix(), ++ Trust => "NONE", ++ }); ++ return %res; ++ } + +- unless ( $info{info}[0]{TrustLevel} > 0 or $opts->{AcceptUntrustedCAs}) { +- # We don't trust it; give it the finger +- $res{exit_code} = 1; +- $res{'message'} = "Validation failed"; +- $res{'status'} = $self->FormatStatus({ +- Operation => "Verify", Status => "BAD", +- Message => "The signing CA was not trusted", +- Serial => $signer->{'Serial Number'} || 'unknown', +- UserString => $signer->{User}[0]{String}, +- ExpireTimestamp => $signer->{Expire}->Unix(), +- CreatedTimestamp => $signer->{Created}->Unix(), +- Trust => "NONE", +- }); +- return %res; +- } ++ { ++ last unless length( $signer->{User}[0]{String} // '' ); + + my ($address) = Email::Address->parse($signer->{User}[0]{String}); + last unless $address; +@@ -571,7 +588,7 @@ sub Verify { + my ($status, $msg) = $user->SetSMIMECertificate( $key ); + $RT::Logger->error("Couldn't set SMIME certificate for user #". $user->id .": $msg") + unless $status; +- }} ++ } + + my $res_entity = _extract_msg_from_buf( \$buf ); + unless ( $res_entity ) { +@@ -596,11 +613,11 @@ sub Verify { + + $res{'status'} = $self->FormatStatus({ + Operation => "Verify", Status => "DONE", +- Message => "The signature is good, signed by ".$signer->{User}[0]{String}.", assured by " . $signer->{Issuer}[0]{String} . ", trust is ".$signer->{TrustTerse}, ++ Message => "The signature is good, signed by ". ( $signer->{User}[0]{String} || 'unknown' ) .", assured by " . ( $signer->{Issuer}[0]{String} || 'unknown' ) . ", trust is ".$signer->{TrustTerse}, + Serial => $signer->{'Serial Number'} || 'unknown', +- UserString => $signer->{User}[0]{String}, ++ UserString => $signer->{User}[0]{String} // '', + Trust => uc($signer->{TrustTerse}), +- Issuer => $signer->{Issuer}[0]{String}, ++ Issuer => $signer->{Issuer}[0]{String} || 'unknown', + ExpireTimestamp => $signer->{Expire}->Unix(), + CreatedTimestamp => $signer->{Created}->Unix(), + }); +@@ -1155,7 +1172,8 @@ sub RunOpenSSLVerify + $res->{info}[0]{TrustTerse} = "unknown"; + $res->{info}[0]{TrustLevel} = 0; + } +- $res->{info}[0]{Formatted} = $res->{info}[0]{User}[0]{String} . " (issued by $res->{info}[0]{Issuer}[0]{String})"; ++ $res->{info}[0]{Formatted} = ( $res->{info}[0]{User}[0]{String} || 'unknown' ) ++ . " (issued by " . ( $res->{info}[0]{Issuer}[0]{String} || 'unknown' ) . ")"; + } + + # Extract the subject email address from an S/MIME certificate. +diff --git a/lib/RT/CustomField.pm b/lib/RT/CustomField.pm +index 3c88f371..e1b26bf3 100644 +--- a/lib/RT/CustomField.pm ++++ b/lib/RT/CustomField.pm +@@ -1422,6 +1422,11 @@ Autrijus: care to doc how LookupTypes work? + sub SetLookupType { + my $self = shift; + my $lookup = shift; ++ ++ unless ( $self->CurrentUserHasRight('AdminCustomField') ) { ++ return ( 0, $self->loc('Permission Denied') ); ++ } ++ + if ( $lookup ne $self->LookupType ) { + # Okay... We need to invalidate our existing relationships + RT::ObjectCustomField->new($self->CurrentUser)->DeleteAll( CustomField => $self ); +@@ -1682,6 +1687,32 @@ sub RemoveFromObject { + } + + ++=head2 CurrentUserCanSeeObject OBJECT ++ ++Returns true if the current user can see OBJECT, the record a value of this ++custom field would be attached to, otherwise false. ++ ++=cut ++ ++sub CurrentUserCanSeeObject { ++ my $self = shift; ++ my $object = shift; ++ ++ return 0 unless $object && $object->id; ++ return 1 if $self->CurrentUser->Id == RT->SystemUser->Id; ++ return 1 if $object->isa('RT::User'); ++ return 1 unless $object->can('CurrentUserCanSee'); ++ ++ # Transaction custom fields are updated right after the transaction is ++ # created, when its author can not necessarily see it yet. ++ if ( $object->isa('RT::Transaction') ) { ++ return 1 if ( $object->__Value('Creator') // 0 ) == $self->CurrentUser->Id; ++ } ++ ++ return $object->CurrentUserCanSee ? 1 : 0; ++} ++ ++ + =head2 AddValueForObject HASH + + Adds a custom field value for a record object of some kind. +@@ -1718,6 +1749,10 @@ sub AddValueForObject { + return ( 0, $self->loc('Permission Denied') ); + } + ++ unless ( $args{'ForCreation'} || $self->CurrentUserCanSeeObject($obj) ) { ++ return ( 0, $self->loc('Permission Denied') ); ++ } ++ + unless ( $self->MatchPattern($args{'Content'}) ) { + return ( 0, $self->FriendlyPattern ); + } +@@ -1989,8 +2024,9 @@ sub DeleteValueForObject { + Id => undef, + @_ ); + ++ my $obj = $args{'Object'} or return ( 0, $self->loc('Invalid object') ); + +- unless ($self->CurrentUserHasRight('ModifyCustomField')) { ++ unless ($self->CurrentUserHasRight('ModifyCustomField') && $self->CurrentUserCanSeeObject($obj)) { + return (0, $self->loc('Permission Denied')); + } + +@@ -1998,11 +2034,20 @@ sub DeleteValueForObject { + + if (my $id = $args{'Id'}) { + $oldval->Load($id); ++ ++ if ( $oldval->id ++ && !( $oldval->__Value('CustomField') == $self->Id ++ && $oldval->__Value('ObjectType') eq ref($obj) ++ && $oldval->__Value('ObjectId') == $obj->Id ) ) ++ { ++ return ( 0, ++ $self->loc( "Custom field value [_1] could not be found for custom field [_2]", $id, $self->Name ) ); ++ } + } + unless ($oldval->id) { + $oldval->LoadByObjectContentAndCustomField( +- Object => $args{'Object'}, +- Content => $args{'Content'}, ++ Object => $obj, ++ Content => $args{'Content'}, + CustomField => $self->Id, + ); + } +diff --git a/lib/RT/CustomRole.pm b/lib/RT/CustomRole.pm +index 8763acb3..43bf298a 100644 +--- a/lib/RT/CustomRole.pm ++++ b/lib/RT/CustomRole.pm +@@ -642,6 +642,11 @@ Returns (1, 'Status message') on success and (0, 'Error Message') on failure. + sub SetLookupType { + my $self = shift; + my $lookup = shift; ++ ++ unless ( $self->CurrentUser->HasRight( Object => RT->System, Right => 'AdminCustomRoles' ) ) { ++ return ( 0, $self->loc('Permission Denied') ); ++ } ++ + if ( $lookup ne $self->LookupType ) { + # Okay... We need to invalidate our existing relationships + RT::ObjectCustomRole->new($self->CurrentUser)->DeleteAll( CustomRole => $self ); +diff --git a/lib/RT/Graph/Tickets.pm b/lib/RT/Graph/Tickets.pm +index 933bab2f..ab6ff3b9 100644 +--- a/lib/RT/Graph/Tickets.pm ++++ b/lib/RT/Graph/Tickets.pm +@@ -77,6 +77,11 @@ our %link_style = ( + RefersTo => { style => 'dotted' }, + ); + ++# The values dot accepts for the rankdir graph attribute. GraphViz2 quotes ++# attribute values but does not escape quotes embedded in them, so anything ++# reaching rankdir has to be constrained to this set rather than escaped. ++our %RANKDIR_VALUES = map { $_ => 1 } qw(TB LR BT RL); ++ + # We don't use qw() because perl complains about "possible attempt to put comments in qw() list" + our @fill_colors = split ' ',<CurrentUserCanSee ) { ++ return $args{'Graph'}->add_node( ++ name => $args{'Ticket'}->id, ++ style => 'filled,rounded', ++ ); ++ } ++ + my %node_style = ( + style => 'filled,rounded', + %{ $ticket_status_style{ $args{'Ticket'}->Status } || {} }, +@@ -312,11 +324,15 @@ sub TicketLinks { + $args{ShowLinks} = [ grep { $valid_links{$_} } @{$args{ShowLinks}} ]; + $args{LeadingLink} = 'Members' unless $valid_links{ $args{LeadingLink} }; + ++ # Validate the graph direction. Normalized here so the recursive calls ++ # and AddTicket below all see the checked value. ++ $args{Direction} = 'TB' unless defined $args{Direction} && $RANKDIR_VALUES{ $args{Direction} }; ++ + unless ( $args{'Graph'} ) { + $args{'Graph'} = GraphViz2->new( + name => 'ticket_links_'. $args{'Ticket'}->id, + bgcolor => "transparent", +- graph => { rankdir => ($args{'Direction'} || "TB") }, ++ graph => { rankdir => $args{'Direction'} }, + node => { shape => 'box', style => 'filled,rounded', fillcolor => 'white' }, + global => {directed => 1}, + ); +diff --git a/lib/RT/Interface/Email/Crypt.pm b/lib/RT/Interface/Email/Crypt.pm +index 42253de9..178d9a59 100644 +--- a/lib/RT/Interface/Email/Crypt.pm ++++ b/lib/RT/Interface/Email/Crypt.pm +@@ -89,6 +89,25 @@ sub VerifyDecrypt { + %args, + Entity => $args{'Message'}, + ); ++ ++ # Verifying and decrypting replaces protected parts with their plaintext, ++ # so parts built from the message body enter the entity object only now. ++ # Whatever headers the sender included are added, including the ++ # ones cleaned previously. Clean the whole entity a second time and then write ++ # back only what the crypt backends themselves reported, so the status ++ # below is derived from the backend results alone. ++ ++ foreach my $p ( $args{'Message'}->parts_DFS ) { ++ $p->head->delete($_) for @headers; ++ } ++ foreach my $res ( @res ) { ++ RT::Crypt->AddStatusHeader( ++ Entity => $res->{'status_on'}, ++ Protocol => $res->{'Protocol'}, ++ Status => $res->{'status'}, ++ ); ++ } ++ + if ( !@res ) { + $args{'Message'}->head->replace( + 'X-RT-Incoming-Encryption' => 'Not encrypted' +diff --git a/lib/RT/Interface/Web.pm b/lib/RT/Interface/Web.pm +index 4c961e93..997c71fc 100644 +--- a/lib/RT/Interface/Web.pm ++++ b/lib/RT/Interface/Web.pm +@@ -91,6 +91,14 @@ our @SHORTENER_SEARCH_FIELDS + = qw/Class ObjectType BaseQuery Query Format RowsPerPage Order OrderBy ExtraQueryParams ResultPage/; + our @SHORTENER_CHART_FIELDS = qw/Width Height ChartStyle GroupBy ChartFunction StackedGroupBy ChartOrderBy ChartOrder ChartLimit ChartLimitType/; + ++# Arguments ExpandShortenerCode can set: the search and chart fields come from ++# the shortener content, the rest from the saved search that content names ++our @SHORTENER_ARGS = ( ++ @SHORTENER_SEARCH_FIELDS, ++ @SHORTENER_CHART_FIELDS, ++ qw/SavedSearchId SavedChartSearchId SavedSearchLoad SearchType SearchFields/, ++); ++ + =head2 SquishedCSS $style + + =cut +@@ -430,6 +438,8 @@ sub HandleRequest { + } + } + ++ ExpandShortenerCode($ARGS); ++ + MaybeShowInterstitialCSRFPage($ARGS); + + # now it applies not only to home page, but any dashboard that can be used as a workspace +@@ -730,8 +740,6 @@ sub ShowRequestedPage { + # session-id has been modified in any way + SendSessionCookie(); + +- ExpandShortenerCode($ARGS); +- + # precache all system level rights for the current user + $HTML::Mason::Commands::session{CurrentUser}->PrincipalObj->HasRights( Object => RT->System ); + +@@ -886,6 +894,16 @@ sub AttemptPasswordAuthentication { + my $ARGS = shift; + return unless defined $ARGS->{user} && defined $ARGS->{pass}; + ++ # Check RestrictLoginReferrer before authentication happens, so that a ++ # login which is not allowed never creates a session. /Elements/DoAuth ++ # does the same for the passwords external auth validates itself. ++ ++ if ( RT->Config->Get('RestrictLoginReferrer') and not IsLoginPageReferer() ) { ++ RT->Logger->error( "REJECTED LOGIN for @{[$ARGS->{user}]} from @{[RequestENV('REMOTE_ADDR')]}: " ++ . "not from RT's login page (Referrer: @{[RequestENV('HTTP_REFERER') || 'none']})" ); ++ return (0, HTML::Mason::Commands::loc("Use RT's login page to log in")); ++ } ++ + my $user_obj = RT::CurrentUser->new(); + $user_obj->Load( $ARGS->{user} ); + +@@ -1165,6 +1183,41 @@ sub ComponentPathIsSafe { + return($path !~ m{(?:^|/)\.} and $path !~ m{\0}); + } + ++=head2 LinkPathIsSafe PATH ++ ++Takes C, a link target handed to a component to build its links from, ++and returns a boolean indicating whether it is an internal path that is safe ++to render into an C or C attribute. ++ ++Safe means the path is internal: it carries no URI scheme, is not protocol ++relative, and holds nothing that could end the attribute it lands in. An ++undefined or empty path is safe, since components give those their own ++meaning. ++ ++Components that take such a path from their arguments must run it through ++this and discard whatever fails. ++ ++=cut ++ ++sub LinkPathIsSafe { ++ my $self = shift; ++ my $path = shift; ++ ++ return 1 unless defined $path and length $path; ++ ++ # A scheme of any kind makes this someone else's URL rather than ours ++ return 0 if $path =~ m{^[a-z][a-z0-9.+-]*:}i; ++ ++ # Protocol relative, including the backslash form browsers accept ++ return 0 if $path =~ m{^[/\\]{2}}; ++ ++ # Anything that could end the attribute we land in, and anything a ++ # browser might strip before it looks for a scheme ++ return 0 if $path =~ m{['"<>\s]|[^[:print:]]}; ++ ++ return 1; ++} ++ + =head2 PathIsSafe + + Takes a C<< Path => path >> and returns a boolean indicating that +@@ -1521,6 +1574,40 @@ sub StaticRoots { + return grep { $_ and -d $_ } @static; + } + ++=head2 Themes ++ ++Returns the names of the themes this instance of RT provides, i.e. the ++directories with a F under F in any of the L. ++C<$WebDefaultStylesheet> and the per-user theme preference name one of these. ++ ++The list is cached for the life of the process, so a theme added on disk is ++not offered until RT is restarted. ++ ++=cut ++ ++sub Themes { ++ my $self = shift; ++ ++ state @themes; ++ return @themes if @themes; ++ ++ my %seen; ++ for my $root ( $self->StaticRoots ) { ++ my $path = "$root/css"; ++ next unless -d $path; ++ ++ if ( opendir my $dh, $path ) { ++ push @themes, grep { !/^\./ && -e "$path/$_/main.css" && !$seen{$_}++ } readdir $dh; ++ closedir $dh; ++ } ++ else { ++ RT->Logger->error("Can't read $path: $!"); ++ } ++ } ++ @themes = sort { lc $a cmp lc $b } @themes; ++ return @themes; ++} ++ + our %IS_WHITELISTED_COMPONENT = ( + # The RSS feed embeds an auth token in the path, but query + # information for the search. Because it's a straight-up read, in +@@ -1530,11 +1617,10 @@ our %IS_WHITELISTED_COMPONENT = ( + # While these can be used for denial-of-service against RT + # (construct a very inefficient query and trick lots of users into + # running them against RT) it's incredibly useful to be able to link +- # to a search result (or chart) or bookmark a result page. ++ # to a search result or bookmark a result page. + '/Search/Results.html' => 1, + '/Search/Simple.html' => 1, + '/m/tickets/search' => 1, +- '/Search/Chart.html' => 1, + '/User/Search.html' => 1, + + # This page takes Attachment and Transaction argument to figure +@@ -1567,13 +1653,17 @@ our @GLOBAL_WHITELISTED_ARGS = ( + + # The Shortener code + 'sc', ++ ++ # Pagination, which only says which page of results to show ++ 'Page', ++ ++ # Search and chart arguments, which only say what to show and how ++ @SHORTENER_ARGS, + ); + + our %WHITELISTED_COMPONENT_ARGS = ( +- # SavedSearchLoad - This happens when you middle-(or ⌘ )-click "Edit" for a saved search on +- # the homepage. It's not going to do any damage + # NewQuery - This is simply to clear the search query +- '/Search/Build.html' => ['SavedSearchLoad','NewQuery'], ++ '/Search/Build.html' => ['NewQuery'], + # Happens if you try and reply to a message in the ticket history or click a number + # of options on a tickets Action menu + '/Ticket/Update.html' => ['QuoteTransaction', 'Action', 'DefaultStatus'], +@@ -1591,6 +1681,9 @@ our %WHITELISTED_COMPONENT_ARGS = ( + our %IS_BLACKLISTED_COMPONENT = ( + # Takes only id and toggles bookmark state + '/Helpers/Toggle/TicketBookmark' => 1, ++ ++ # Takes only id and revokes the named right ++ '/Helpers/RightsInspector/Revoke' => 1, + ); + + sub IsCompCSRFWhitelisted { +@@ -1679,6 +1772,45 @@ sub IsRefererCSRFWhitelisted { + return (0,$referer,$configs); + } + ++=head3 IsLoginPageReferer ++ ++Returns true if the current request came from RT's login page. ++ ++A request qualifies if it supplies a Referrer header, and that Referrer is one of ++the URLs where RT serves the login form, which is the login page itself, or the index ++page, which renders the form inline for a logged-out user. ++ ++REST endpoints are exempt. Their clients are not browsers and send no ++Referrer, and with C<$RestrictReferrer> enabled L confines a ++session created by a REST request to REST endpoints, so such a session cannot ++be used to browse RT. ++ ++=cut ++ ++sub IsLoginPageReferer { ++ return 1 if $HTML::Mason::Commands::r->path_info =~ m{^/+REST/\d+\.\d+(/|$)}; ++ ++ my $referer = RequestENV('HTTP_REFERER') or return 0; ++ my $uri = URI->new($referer); ++ ++ # A Referrer with no host and port is never a page RT served. ++ # @ReferrerWhitelist can accept one anyway: android-app://com.slack/ ++ # matches on authority, and its path of / would read as the index page. ++ return 0 unless $uri->can('host_port'); ++ ++ # The login form is served by RT itself, so the Referrer has to be a host ++ # RT answers to. ++ my ($host_ok) = IsRefererCSRFWhitelisted($referer); ++ return 0 unless $host_ok; ++ ++ my $path = $uri->path // ''; ++ my $webpath = RT->Config->Get('WebPath') || ''; ++ return 0 unless $path =~ s{^\Q$webpath\E}{}; ++ $path = '/' unless length $path; ++ ++ return $path =~ m{^(?:/(?:index\.html)?|/m/?(?:index\.html)?|/NoAuth/Login\.html)$} ? 1 : 0; ++} ++ + =head3 _NormalizeHost + + Takes a URI and creates a URI object that's been normalized +@@ -1780,10 +1912,21 @@ sub ExpandCSRFToken { + sub StoreRequestToken { + my $ARGS = shift; + +- my $token = Digest::MD5::md5_hex(time . {} . $$ . rand(1024)); ++ my $token = RT::Util::random_hex(32); ++ unless ( defined $token ) { ++ RT->Logger->error("Couldn't generate a request token"); ++ return; ++ } ++ + my $user = $HTML::Mason::Commands::session{'CurrentUser'}->UserObj; ++ my $auth = $user->GenerateAuthString( $token ); ++ unless ( defined $auth ) { ++ RT->Logger->error("Couldn't sign a request token for user " . $user->id); ++ return; ++ } ++ + my $data = { +- auth => $user->GenerateAuthString( $token ), ++ auth => $auth, + path => $HTML::Mason::Commands::r->path_info, + args => $ARGS, + }; +@@ -1821,6 +1964,16 @@ sub MaybeShowInterstitialCSRFPage { + $RT::Logger->notice("Possible CSRF: ".RT::CurrentUser->new->loc($msg, @loc)); + + my $token = StoreRequestToken($ARGS); ++ unless ( defined $token ) { ++ # The interstitial is what lets the user confirm this request, and it ++ # needs a token. Without one, refuse rather than wave the request ++ # through the check the interstitial exists to perform. ++ HTML::Mason::Commands::Abort( ++ HTML::Mason::Commands::loc("Your request could not be verified. Please try again, and contact your administrator if the problem persists."), ++ Code => HTTP::Status::HTTP_INTERNAL_SERVER_ERROR, ++ ); ++ } ++ + $HTML::Mason::Commands::m->comp( + '/Elements/CSRF', + OriginalURL => RT->Config->Get('WebBaseURL') . RT->Config->Get('WebPath') . $HTML::Mason::Commands::r->path_info, +@@ -2362,7 +2515,8 @@ sub MaybeRedirectToApproval { + my $ticket = RT::Ticket->new( $session{'CurrentUser'} ); + $ticket->Load($id); + +- if ($ticket and $ticket->id and lc($ticket->Type) eq 'approval') { ++ # Type is undef for a ticket the current user cannot see ++ if ($ticket and $ticket->id and lc($ticket->Type // '') eq 'approval') { + MaybeRedirectForResults( + Path => "/Approvals/Display.html", + Force => 1, +@@ -3464,7 +3618,9 @@ sub ProcessObjectCustomFieldUpdates { + foreach my $id ( keys %{ $custom_fields_to_mod{$class} } ) { + my $Object = $args{'Object'}; + $Object = $class->new( $session{'CurrentUser'} ) +- unless $Object && ref $Object eq $class; ++ unless $Object ++ && ref $Object eq $class ++ && ( !$id || ( $Object->id || 0 ) == $id ); + + # skip if we have no object to update + next unless $id || $Object->id; +@@ -4882,7 +5038,7 @@ Instantiate container object for saving searches. + + sub _load_container_object { + my ( $obj_type, $obj_id ) = @_; +- return RT::SavedSearch->new( $session{'CurrentUser'} )->_load_privacy_object( $obj_type, $obj_id ); ++ return RT::SavedSearch->new( $session{'CurrentUser'} )->_GetObject("$obj_type-$obj_id"); + } + + =head2 _parse_saved_search ( $arg ); +@@ -4902,7 +5058,28 @@ sub _parse_saved_search { + my $obj_id = $2; + my $search_id = $3; + +- return ( _load_container_object( $obj_type, $obj_id ), $search_id ); ++ my $container = _load_container_object( $obj_type, $obj_id ); ++ return unless $container && $container->Id; ++ ++ my $search = RT::Attribute->new( RT->SystemUser ); ++ $search->LoadByCols( ++ id => $search_id, ++ ObjectType => ref($container), ++ ObjectId => $container->Id, ++ ); ++ ++ unless ( $search->Id ) { ++ RT->Logger->debug("Attribute $search_id is not stored on $obj_type-$obj_id"); ++ return; ++ } ++ ++ my $name = $search->Name // ''; ++ unless ( $name eq 'SavedSearch' || $name =~ /^Search - / ) { ++ RT->Logger->debug("Attribute $search_id is not a saved search"); ++ return; ++ } ++ ++ return ( $container, $search_id ); + } + + =head2 ScrubHTML Content => CONTENT, Permissive => 1|0, Restrictive => 1|0, SkipStructureCheck => 1|0 +diff --git a/lib/RT/Interface/Web/MenuBuilder.pm b/lib/RT/Interface/Web/MenuBuilder.pm +index 2e6917d0..933f2837 100644 +--- a/lib/RT/Interface/Web/MenuBuilder.pm ++++ b/lib/RT/Interface/Web/MenuBuilder.pm +@@ -782,20 +782,34 @@ sub BuildMainNav { + OrderBy => $rss_data{OrderBy} + ) + ); +- my $RSSPath = join '/', map $HTML::Mason::Commands::m->interp->apply_escapes( $_, 'u' ), +- $current_user->UserObj->Name, +- $current_user->UserObj->GenerateAuthString( $short_query{sc} ++ # The feed URL carries its own signature, so with no auth ++ # string there is no link to offer. Leave the item out ++ # rather than produce one that cannot authenticate. ++ my $rss_auth = $current_user->UserObj->GenerateAuthString( $short_query{sc} + || ( $rss_data{Query} . $rss_data{Order} . $rss_data{OrderBy} ) ); ++ if ( defined $rss_auth ) { ++ my $RSSPath = join '/', map $HTML::Mason::Commands::m->interp->apply_escapes( $_, 'u' ), ++ $current_user->UserObj->Name, $rss_auth; + +- $more->child( rss => title => loc('RSS'), path => "/NoAuth/rss/$RSSPath/$RSSQueryString" ); ++ $more->child( rss => title => loc('RSS'), path => "/NoAuth/rss/$RSSPath/$RSSQueryString" ); ++ } ++ else { ++ RT->Logger->error("Couldn't sign an RSS feed URL; omitting the RSS link"); ++ } + } + + if ( RT->Config->Get('EnableICal') ) { +- my $ical_path = join '/', map $HTML::Mason::Commands::m->interp->apply_escapes( $_, 'u' ), +- $current_user->UserObj->Name, +- $current_user->UserObj->GenerateAuthString( $rss_data{Query} ), +- $short_query{sc} ? "sc-$short_query{sc}" : $rss_data{Query}; +- $more->child( ical => title => loc('iCal'), path => '/NoAuth/iCal/' . $ical_path ); ++ my $ical_auth = $current_user->UserObj->GenerateAuthString( $rss_data{Query} ); ++ if ( defined $ical_auth ) { ++ my $ical_path = join '/', map $HTML::Mason::Commands::m->interp->apply_escapes( $_, 'u' ), ++ $current_user->UserObj->Name, ++ $ical_auth, ++ $short_query{sc} ? "sc-$short_query{sc}" : $rss_data{Query}; ++ $more->child( ical => title => loc('iCal'), path => '/NoAuth/iCal/' . $ical_path ); ++ } ++ else { ++ RT->Logger->error("Couldn't sign an iCal feed URL; omitting the iCal link"); ++ } + } + + #XXX TODO better abstraction of SuperUser right check +diff --git a/lib/RT/ObjectCustomFieldValue.pm b/lib/RT/ObjectCustomFieldValue.pm +index 8d4e24a7..0ad7ae40 100644 +--- a/lib/RT/ObjectCustomFieldValue.pm ++++ b/lib/RT/ObjectCustomFieldValue.pm +@@ -54,6 +54,7 @@ use warnings; + use base 'RT::Record'; + + use RT::Interface::Web; ++use RT::Util 'CanonicalizeContentType'; + use Regexp::Common qw(RE_net_IPv4); + use Regexp::IPv6 qw($IPv6_re); + use Regexp::Common::net::CIDR; +@@ -83,6 +84,8 @@ sub Create { + @_, + ); + ++ $args{'ContentType'} = CanonicalizeContentType( $args{'ContentType'} ); ++ + my $cf = RT::CustomField->new( $self->CurrentUser ); + $cf->Load( $args{CustomField} ); + +@@ -375,18 +378,10 @@ sub _FillInTemplateURL { + return undef unless defined $url && length $url; + + # special case, whole value should be an URL +- if ( $url =~ /^__CustomField__/ ) { ++ my $value_is_url = $url =~ /^__CustomField__/ ? 1 : 0; ++ if ( $value_is_url ) { + my $value = $self->Content; + $value //= ''; +- # protect from potentially malicious URLs +- if ( $value =~ /^\s*(?:javascript|data):/i ) { +- my $object = $self->Object; +- $RT::Logger->error( +- "Potentially dangerous URL type in custom field '". $self->CustomFieldObj->Name ."'" +- ." on ". ref($object) ." #". $object->id +- ); +- return undef; +- } + $url =~ s/^__CustomField__/$value/; + } + +@@ -400,9 +395,37 @@ sub _FillInTemplateURL { + }gxe; + } + ++ # protect from potentially malicious URLs ++ if ( $value_is_url && $self->_IsDangerousURL($url) ) { ++ my $object = $self->Object; ++ $RT::Logger->error( ++ "Potentially dangerous URL type in custom field '". $self->CustomFieldObj->Name ."'" ++ ." on ". ref($object) ." #". $object->id ++ ); ++ return undef; ++ } ++ + return $url; + } } + ++=head2 _IsDangerousURL URL ++ ++Returns true if the given URL uses a scheme that browsers can execute as ++code. Characters that browsers ignore when they parse the scheme are removed ++before the check. ++ ++=cut ++ ++sub _IsDangerousURL { ++ my $self = shift; ++ my $url = shift; ++ ++ $url =~ s/[\x09\x0a\x0d]//g; ++ $url =~ s/^[\x00-\x20]+//; ++ ++ return $url =~ /^(?:javascript|data):/i ? 1 : 0; ++} ++ + + =head2 ValueLinkURL + +@@ -816,15 +839,24 @@ sub ExternalStoreDigest { + + =head2 CurrentUserCanSee + +-Returns true if user has "SeeCustomField" on the associated CustomField +-object, otherwise false. ++Returns true if the user has "SeeCustomField" on the associated CustomField ++object and can see the object the value is attached to, otherwise false. + + =cut + + sub CurrentUserCanSee { + my $self = shift; + return undef unless $self->Id; +- return $self->CustomFieldObj->CurrentUserHasRight('SeeCustomField'); ++ ++ return 1 if $self->CurrentUser->Id == RT->SystemUser->Id; ++ ++ return 0 unless $self->CustomFieldObj->CurrentUserHasRight('SeeCustomField'); ++ ++ my $object = $self->Object; ++ return 0 unless $object && $object->id; ++ return 1 if $object->isa('RT::User'); ++ return 1 unless $object->can('CurrentUserCanSee'); ++ return $object->CurrentUserCanSee ? 1 : 0; + } + + sub _Value { +@@ -834,7 +866,8 @@ sub _Value { + unless ( $self->CurrentUserCanSee ) { + $RT::Logger->debug( + "Permission denied. User #". $self->CurrentUser->id +- ." has no SeeCustomField right on CF #". $self->__Value('CustomField') ++ ." can not see value #". $self->id ." of CF #". $self->__Value('CustomField') ++ ." on ". $self->__Value('ObjectType') ." #". $self->__Value('ObjectId') + ); + return undef; + } +diff --git a/lib/RT/REST2/Middleware/Auth.pm b/lib/RT/REST2/Middleware/Auth.pm +index ff3357cc..9e2eb6ac 100644 +--- a/lib/RT/REST2/Middleware/Auth.pm ++++ b/lib/RT/REST2/Middleware/Auth.pm +@@ -53,12 +53,16 @@ use warnings; + + use base 'Plack::Middleware'; + ++use JSON (); ++ + our @auth_priority = qw( + login_from_cookie + login_from_authtoken + login_from_basicauth + ); + ++our %SAFE_METHODS = map { $_ => 1 } qw(GET HEAD OPTIONS); ++ + sub call { + my ($self, $env) = @_; + +@@ -70,6 +74,9 @@ sub call { + if ($env->{'rt.current_user'}) { + return $self->app->($env); + } ++ elsif ($env->{'rt.csrf'}) { ++ return $self->forbidden($env); ++ } + else { + return $self->unauthorized($env); + } +@@ -81,6 +88,11 @@ sub login_from_cookie { + # allow reusing authentication from the ordinary web UI so that + # among other things our JS can use REST2 + if ($env->{HTTP_COOKIE}) { ++ unless ($self->request_origin_allowed($env)) { ++ $env->{'rt.csrf'} = 1; ++ return; ++ } ++ + no warnings 'redefine'; + + # this is foul but LoadSessionFromCookie doesn't have a hook for +@@ -153,6 +165,39 @@ sub login_from_basicauth { + return; + } + ++sub request_origin_allowed { ++ my $self = shift; ++ my $env = shift; ++ ++ return 1 if $SAFE_METHODS{ $env->{REQUEST_METHOD} || '' }; ++ return 1 unless RT->Config->Get('RestrictReferrer'); ++ ++ my $origin = $env->{HTTP_ORIGIN} || $env->{HTTP_REFERER}; ++ return 0 unless $origin and $origin ne 'null'; ++ ++ my ($allowed) = RT::Interface::Web::IsRefererCSRFWhitelisted($origin); ++ return $allowed ? 1 : 0; ++} ++ ++sub forbidden { ++ my $self = shift; ++ my $env = shift; ++ ++ RT->Logger->notice( ++ "Possible CSRF: REST2 " . ($env->{REQUEST_METHOD} || '') . " request from origin " ++ . ($env->{HTTP_ORIGIN} || $env->{HTTP_REFERER} || '(none supplied)') ++ . " is not allowed by RT's configured hostname or whitelisted hosts" ++ ); ++ ++ my $body = JSON::to_json( { message => 'Cross-site request forgery protection refused this request' } ); ++ return [ ++ 403, ++ [ 'Content-Type' => 'application/json; charset=utf-8', ++ 'Content-Length' => length $body ], ++ [ $body ], ++ ]; ++} ++ + sub _looks_like_browser { + my $self = shift; + my $env = shift; +diff --git a/lib/RT/REST2/Resource.pm b/lib/RT/REST2/Resource.pm +index 4ed8057b..845dcabc 100644 +--- a/lib/RT/REST2/Resource.pm ++++ b/lib/RT/REST2/Resource.pm +@@ -77,6 +77,10 @@ sub expand_field { + my $field = shift; + my $param_prefix = shift || 'fields'; + ++ # Selecting a field reads the accessor directly rather than going through ++ # Serialize, so the time fields have to be filtered out here as well. ++ return if $item->can('IsTimeField') && $item->IsTimeField($field) && !$item->CurrentUserCanSeeTime; ++ + my $result; + if ($field eq 'CustomFields') { + if (my $cfs = custom_fields_for($item)) { +diff --git a/lib/RT/REST2/Resource/CustomFieldValue.pm b/lib/RT/REST2/Resource/CustomFieldValue.pm +index 9eb6e66f..9543a75c 100644 +--- a/lib/RT/REST2/Resource/CustomFieldValue.pm ++++ b/lib/RT/REST2/Resource/CustomFieldValue.pm +@@ -58,7 +58,23 @@ extends 'RT::REST2::Resource::Record'; + with 'RT::REST2::Resource::Record::Readable', + 'RT::REST2::Resource::Record::Hypermedia', + 'RT::REST2::Resource::Record::Deletable', +- 'RT::REST2::Resource::Record::Writable'; ++ 'RT::REST2::Resource::Record::Writable' ++ => { -alias => { immutable_fields => '_default_immutable_fields' } }; ++ ++=head2 immutable_fields ++ ++Adds C. A value belongs to one custom field for its whole life, ++and the request path already names it, so there is nothing for the request ++body to say. forbidden checks rights on the custom field from the path too, ++which a value the body pointed elsewhere would sidestep. ++ ++=cut ++ ++sub immutable_fields { ++ my $self = shift; ++ ++ return ( $self->_default_immutable_fields(@_), 'CustomField' ); ++} + + has 'customfield' => ( + is => 'ro', +@@ -88,6 +104,20 @@ sub dispatch_rules { + ) + } + ++=head2 resource_exists ++ ++A value is only a resource under the custom field that owns it. ++ ++=cut ++ ++sub resource_exists { ++ my $self = shift; ++ ++ my $record = $self->record; ++ return 0 unless $record->id && $self->customfield->id; ++ return $record->CustomField == $self->customfield->id; ++} ++ + sub forbidden { + my $self = shift; + my $method = $self->request->method; +@@ -102,6 +132,8 @@ sub create_record { + my $self = shift; + my $data = shift; + ++ delete @{$data}{ $self->immutable_fields('create') }; ++ + my ($ok, $msg) = $self->customfield->AddValue(%$data); + $self->record->Load($ok) if $ok; + return ($ok, $msg); +diff --git a/lib/RT/REST2/Resource/Group.pm b/lib/RT/REST2/Resource/Group.pm +index 7882d795..68fafeb7 100644 +--- a/lib/RT/REST2/Resource/Group.pm ++++ b/lib/RT/REST2/Resource/Group.pm +@@ -58,10 +58,25 @@ extends 'RT::REST2::Resource::Record'; + with 'RT::REST2::Resource::Record::Readable' + => { -alias => { serialize => '_default_serialize' } }, + 'RT::REST2::Resource::Record::DeletableByDisabling', +- 'RT::REST2::Resource::Record::Writable', ++ 'RT::REST2::Resource::Record::Writable' ++ => { -alias => { immutable_fields => '_default_immutable_fields' } }, + 'RT::REST2::Resource::Record::Hypermedia' + => { -alias => { hypermedia_links => '_default_hypermedia_links' } }; + ++=head2 immutable_fields ++ ++Adds C and C. With C, they are how RT locates a role ++group, so they describe where a group sits in RT rather than anything a ++client states. C stays writable, so groups can still be renamed. ++ ++=cut ++ ++sub immutable_fields { ++ my $self = shift; ++ ++ return ( $self->_default_immutable_fields(@_), qw(Domain Instance) ); ++} ++ + sub dispatch_rules { + Path::Dispatcher::Rule::Regex->new( + regex => qr{^/group/?$}, +@@ -69,7 +84,16 @@ sub dispatch_rules { + ), + Path::Dispatcher::Rule::Regex->new( + regex => qr{^/group/(\d+)/?$}, +- block => sub { { record_class => 'RT::Group', record_id => shift->pos(1) } }, ++ block => sub { ++ my ($match, $req) = @_; ++ my $group = RT::Group->new( $req->env->{"rt.current_user"} ); ++ $group->LoadUserDefinedGroup( $match->pos(1) ); ++ return { ++ record_class => 'RT::Group', ++ record_id => $match->pos(1), ++ record => $group, ++ }; ++ }, + ) + } + +diff --git a/lib/RT/REST2/Resource/GroupMembers.pm b/lib/RT/REST2/Resource/GroupMembers.pm +index b67e38ce..69d524e6 100644 +--- a/lib/RT/REST2/Resource/GroupMembers.pm ++++ b/lib/RT/REST2/Resource/GroupMembers.pm +@@ -52,6 +52,7 @@ use warnings; + + use Moose; + use namespace::autoclean; ++use RT::REST2::Util qw(error_as_json); + + extends 'RT::REST2::Resource::Collection'; + with 'RT::REST2::Resource::Role::RequestBodyIsJSON' => +@@ -68,7 +69,7 @@ sub dispatch_rules { + my ($match, $req) = @_; + my $group_id = $match->pos(1); + my $group = RT::Group->new($req->env->{"rt.current_user"}); +- $group->Load($group_id); ++ $group->LoadUserDefinedGroup($group_id); + my $collection; + + my $recursively = $req->parameters->{recursively} // 0; +@@ -104,7 +105,7 @@ sub dispatch_rules { + my $group_id = $match->pos(1); + my $member_id = $match->pos(2) || ''; + my $group = RT::Group->new($req->env->{"rt.current_user"}); +- $group->Load($group_id); ++ $group->LoadUserDefinedGroup($group_id); + my $collection = $group->MembersObj; + $collection->Limit(FIELD => 'MemberId', VALUE => $member_id); + return {group => $group, collection => $collection}; +@@ -112,6 +113,11 @@ sub dispatch_rules { + ), + } + ++sub resource_exists { ++ my $self = shift; ++ return $self->group->id; ++} ++ + sub forbidden { + my $self = shift; + return !$self->group->CurrentUserHasRight('AdminGroupMembership'); +@@ -174,6 +180,11 @@ sub delete_resource { + + sub from_json { + my $self = shift; ++ ++ # Web::Machine sends PUT to a missing resource down its create path, so ++ # resource_exists must be checked here too, as Record::Writable does. ++ return error_as_json( $self->response, \404, "Not Found" ) unless $self->resource_exists; ++ + my $params = JSON::decode_json($self->request->content); + my $group = $self->group; + +@@ -182,6 +193,16 @@ sub from_json { + if ($method eq 'PUT') { + for my $param (@$params) { + if ($param =~ /^\d+$/) { ++ my $principal = RT::Principal->new( $self->current_user ); ++ $principal->Load($param); ++ if ( $principal->id ++ && $principal->IsGroup ++ && ( $principal->Object->Domain // '' ) ne 'UserDefined' ) ++ { ++ push @results, $self->current_user->loc( "Group [_1] not found", $param ); ++ next; ++ } ++ + my ($ret, $msg) = $group->AddMember($param); + push @results, $msg; + } else { +diff --git a/lib/RT/REST2/Resource/Groups.pm b/lib/RT/REST2/Resource/Groups.pm +index 897245b9..adde24bf 100644 +--- a/lib/RT/REST2/Resource/Groups.pm ++++ b/lib/RT/REST2/Resource/Groups.pm +@@ -63,6 +63,18 @@ sub dispatch_rules { + ), + } + ++after 'limit_collection' => sub { ++ my $self = shift; ++ $self->collection->LimitToUserDefinedGroups(); ++ return 1; ++}; ++ ++sub searchable_fields { ++ my $self = shift; ++ my %excluded = map { ; $_ => 1 } qw(Domain Instance); ++ return grep { !$excluded{$_} } $self->collection->RecordClass->ReadableAttributes; ++} ++ + __PACKAGE__->meta->make_immutable; + + 1; +diff --git a/lib/RT/REST2/Resource/ObjectCustomFieldValue.pm b/lib/RT/REST2/Resource/ObjectCustomFieldValue.pm +index 51b7efc6..9d3253b3 100644 +--- a/lib/RT/REST2/Resource/ObjectCustomFieldValue.pm ++++ b/lib/RT/REST2/Resource/ObjectCustomFieldValue.pm +@@ -53,6 +53,7 @@ use warnings; + use Moose; + use namespace::autoclean; + use RT::REST2::Util qw( error_as_json ); ++use RT::Util 'CanonicalizeContentType'; + + extends 'RT::REST2::Resource::Record'; + with 'RT::REST2::Resource::Record::WithETag'; +@@ -68,7 +69,12 @@ sub allowed_methods { ['GET', 'HEAD'] } + + sub content_types_provided { + my $self = shift; +- { [ {$self->record->ContentType || 'text/plain; charset=utf-8' => 'to_binary'} ] }; ++ { [ { $self->_ContentType => 'to_binary' } ] }; ++} ++ ++sub _ContentType { ++ my $self = shift; ++ return CanonicalizeContentType( $self->record->ContentType ) || 'text/plain; charset=utf-8'; + } + + sub to_binary { +@@ -79,7 +85,7 @@ sub to_binary { + \400, "Only Image and Binary CustomFields can be downloaded"); + } + +- my $content_type = $self->record->ContentType || 'text/plain; charset=utf-8'; ++ my $content_type = $self->_ContentType; + if (RT->Config->Get('AlwaysDownloadAttachments') || $content_type =~ m{^(image/svg\+xml|application/pdf)}i) { + $self->response->header('Content-Disposition' => 'attachment'); + } +diff --git a/lib/RT/REST2/Resource/Record/Writable.pm b/lib/RT/REST2/Resource/Record/Writable.pm +index c5159c79..e4084c47 100644 +--- a/lib/RT/REST2/Resource/Record/Writable.pm ++++ b/lib/RT/REST2/Resource/Record/Writable.pm +@@ -62,6 +62,22 @@ with 'RT::REST2::Resource::Role::RequestBodyIsJSON' + requires 'record'; + requires 'record_class'; + ++=head2 immutable_fields ++ ++Returns the fields to drop from the request body, given C or ++C for the operation in progress. The fields listed here are dropped ++for both, so this ignores the argument; resource classes override it to ++append their own, and may vary those by operation. Fields are dropped ++silently rather than rejected. ++ ++=cut ++ ++sub immutable_fields { ++ my $self = shift; ++ ++ return qw(id Creator Created LastUpdated LastUpdatedBy); ++} ++ + sub post_is_create { 1 } + sub allow_missing_post { 1 } + sub create_path_after_handler { 1 } +@@ -152,6 +168,8 @@ sub update_record { + my $self = shift; + my $data = shift; + ++ delete @{$data}{ $self->immutable_fields('update') }; ++ + # update_role_members wants custom role IDs (like RT::CustomRole-ID) + # rather than role names. + if ( $data->{CustomRoles} ) { +@@ -297,6 +315,8 @@ sub create_record { + my $self = shift; + my $data = shift; + ++ delete @{$data}{ $self->immutable_fields('create') }; ++ + my $record = $self->record; + my %args = %$data; + +diff --git a/lib/RT/REST2/Resource/Ticket.pm b/lib/RT/REST2/Resource/Ticket.pm +index ebbb78d8..6edc359b 100644 +--- a/lib/RT/REST2/Resource/Ticket.pm ++++ b/lib/RT/REST2/Resource/Ticket.pm +@@ -61,9 +61,33 @@ with ( + => { -alias => { hypermedia_links => '_default_hypermedia_links' } }, + 'RT::REST2::Resource::Record::Deletable', + 'RT::REST2::Resource::Record::Writable' +- => { -alias => { create_record => '_create_record', update_record => '_update_record' } }, ++ => { -alias => { create_record => '_create_record', update_record => '_update_record', ++ immutable_fields => '_default_immutable_fields' } }, + ); + ++=head2 immutable_fields ++ ++Adds C and C, plus C on update. Merging via ++REST2 goes through the C field of an update, which is ++rights-checked. ++ ++C stays settable on create, as that is the only way REST2 clients have ++to make a reminder. Setting it afterwards is another matter: searches match ++C, so re-typing an existing ticket would drop it out of ++every result. ++ ++=cut ++ ++sub immutable_fields { ++ my $self = shift; ++ my $action = shift // ''; ++ ++ my @fields = ( $self->_default_immutable_fields($action), qw(EffectiveId IsMerged) ); ++ push @fields, 'Type' unless $action eq 'create'; ++ ++ return @fields; ++} ++ + has 'action' => ( + is => 'ro', + isa => 'Str', +diff --git a/lib/RT/REST2/Resource/Transactions.pm b/lib/RT/REST2/Resource/Transactions.pm +index 770de89c..622d00af 100644 +--- a/lib/RT/REST2/Resource/Transactions.pm ++++ b/lib/RT/REST2/Resource/Transactions.pm +@@ -71,7 +71,11 @@ sub dispatch_rules { + my $package = 'RT::' . ucfirst $class; + my $record = $package->new( $req->env->{"rt.current_user"} ); + +- $record->Load($id); ++ if ( $class eq 'group' ) { ++ $record->LoadUserDefinedGroup($id); ++ } else { ++ $record->Load($id); ++ } + return { collection => $record->Transactions }; + }, + ), +diff --git a/lib/RT/REST2/Resource/UserGroups.pm b/lib/RT/REST2/Resource/UserGroups.pm +index aa5d7b51..2317d314 100644 +--- a/lib/RT/REST2/Resource/UserGroups.pm ++++ b/lib/RT/REST2/Resource/UserGroups.pm +@@ -152,8 +152,12 @@ sub from_json { + for my $param (@$params) { + if ($param =~ /^\d+$/) { + my $group = RT::Group->new($self->request->env->{"rt.current_user"}); +- $group->Load($param); +- push @results, $group->AddMember($user->id); ++ $group->LoadUserDefinedGroup($param); ++ if ( $group->id ) { ++ push @results, $group->AddMember($user->id); ++ } else { ++ push @results, 0, $self->current_user->loc( "Group [_1] not found", $param ); ++ } + } else { + push @results, [0, 'You should provide group id for each group user should be added']; + } +diff --git a/lib/RT/Record.pm b/lib/RT/Record.pm +index dafbaa0c..45ee7fb8 100644 +--- a/lib/RT/Record.pm ++++ b/lib/RT/Record.pm +@@ -1322,6 +1322,10 @@ If Silent is true then no transactions will be recorded. You can individually + control transactions on both base and target and with SilentBase and + SilentTarget respectively. By default both transactions are created. + ++Schemes whose resolver reports L are refused, ++since they name records RT keeps for its own bookkeeping rather than records a ++caller links to. Pass AllowInternal to create such a link anyway. ++ + If the link destination is a local object and does the + L role, this method ensures object Status is not + "deleted". Linking to deleted objects is forbidden. +@@ -1347,6 +1351,7 @@ sub _AddLink { + Silent => undef, + SilentBase => undef, + SilentTarget => undef, ++ AllowInternal => 0, + @_ + ); + +@@ -1374,6 +1379,9 @@ sub _AddLink { + + my $remote_uri = RT::URI->new( $self->CurrentUser ); + if ($remote_uri->FromURI( $remote_link )) { ++ return ( 0, $self->loc( "Can't link to '[_1]'", $remote_link ) ) ++ if $remote_uri->Resolver->IsInternalOnly && !$args{'AllowInternal'}; ++ + my $remote_obj = $remote_uri->IsLocal ? $remote_uri->Object : undef; + if ($remote_obj and $remote_obj->id) { + # Enforce the remote end of StrictLinkACL +diff --git a/lib/RT/Report.pm b/lib/RT/Report.pm +index c15200ef..ec92e5a3 100644 +--- a/lib/RT/Report.pm ++++ b/lib/RT/Report.pm +@@ -92,7 +92,7 @@ our %GROUPINGS_META = ( + + my $queue = RT::Queue->new( $self->CurrentUser ); + $queue->Load( $args{'VALUE'} ); +- return $queue->Name; ++ return _DisplayValue( $queue->Name, $args{FORMAT} ); + }, + Localize => 1, + Distinct => 1, +@@ -104,7 +104,7 @@ our %GROUPINGS_META = ( + + my $catalog = RT::Catalog->new( $self->CurrentUser ); + $catalog->Load( $args{'VALUE'} ); +- return $catalog->Name; ++ return _DisplayValue( $catalog->Name, $args{FORMAT} ); + }, + Localize => 1, + Distinct => 1, +@@ -174,11 +174,12 @@ our %GROUPINGS_META = ( + if ( $args{FIELD} eq 'id' && ($args{'VALUE'} // '') !~ /\D/ ) { + my $princ = RT::Principal->new( $self->CurrentUser ); + $princ->Load( $args{'VALUE'} ) if $args{'VALUE'}; +- return $self->loc('(no value)') unless $princ->Id; +- return $princ->IsGroup ? $self->loc( 'Group: [_1]', $princ->Object->Name ) : $princ->Object->Name; ++ return _DisplayValue( $self->loc('(no value)'), $args{FORMAT} ) unless $princ->Id; ++ my $name = _DisplayValue( $princ->Object->Name, $args{FORMAT} ); ++ return $princ->IsGroup ? $self->loc( 'Group: [_1]', $name ) : $name; + } + else { +- return $args{VALUE}; ++ return _DisplayValue( $args{VALUE}, $args{FORMAT} ); + } + }, + Distinct => sub { +@@ -238,7 +239,7 @@ our %GROUPINGS_META = ( + elsif ( $args{'SUBKEY'} eq 'Month' ) { + return $self->loc($RT::Date::MONTHS[ int($raw) - 1 ]); + } +- return $raw; ++ return _DisplayValue( $raw, $args{FORMAT} ); + }, + Sort => 'raw', + Distinct => 1, +@@ -465,6 +466,14 @@ our %STATISTICS_META = ( + }, + ); + ++sub _DisplayValue { ++ my $value = shift; ++ my $format = shift || 'text'; ++ ++ RT::Interface::Web::EscapeHTML( \$value ) if $format eq 'html'; ++ return $value; ++} ++ + sub Groupings { + my $self = shift; + my %args = (@_); +@@ -1166,15 +1175,29 @@ sub Deserialize { + } + + ++=head2 FormatTable Groups => ARRAYREF, Functions => ARRAYREF, Format => 'html' ++ ++Returns the report as C, C and C lists of rows of cells. ++C is what the cells are built for, C by default, where labels and ++values are escaped as they can contain names and custom field values entered by ++other users. Pass C to get them as they are stored. ++ ++=cut ++ + sub FormatTable { + my $self = shift; + my %columns = @_; ++ my $format = delete $columns{'Format'} || 'html'; ++ ++ my $escape = $format eq 'html' ++ ? sub { my $value = shift; RT::Interface::Web::EscapeHTML( \$value ); return $value } ++ : sub { return shift }; + + my (@head, @body, @footer); + + @head = ({ cells => []}); + foreach my $column ( @{ $columns{'Groups'} } ) { +- push @{ $head[0]{'cells'} }, { type => 'head', value => $self->Label( $column ) }; ++ push @{ $head[0]{'cells'} }, { type => 'head', value => $escape->( $self->Label( $column ) ) }; + } + + my $i = 0; +@@ -1189,7 +1212,7 @@ sub FormatTable { + $i = 0; + my $last; + while ( my $entry = $self->Next ) { +- my $value = $entry->LabelValue( $column, 'html' ); ++ my $value = $entry->LabelValue( $column, $format ); + if ( !$last || $last->{'value'} ne $value ) { + push @{ $body[ $i++ ]{'cells'} }, $last = { type => 'label', value => $value }; + $last->{even} = $g++ % 2 +@@ -1236,7 +1259,7 @@ sub FormatTable { + unless $info->{'META'}{'NoHideEmpty'}; + } + +- my $label = $self->Label( $column ); ++ my $label = $escape->( $self->Label( $column ) ); + + unless (@subs) { + while ( my $entry = $self->Next ) { +@@ -1269,13 +1292,14 @@ sub FormatTable { + }; + } else { + push @{ $head[0]{'cells'} }, { type => 'head', value => $label, colspan => scalar @subs }; +- push @{ $head[1]{'cells'} }, { type => 'head', value => $_, color => $pick_color->(++$function_count) } ++ push @{ $head[1]{'cells'} }, ++ { type => 'head', value => $escape->($_), color => $pick_color->( ++$function_count ) } + foreach @subs; + } + + while ( my $entry = $self->Next ) { + my $query = $entry->Query; +- my $value = $entry->LabelValue( $column, 'html' ) || {}; ++ my $value = $entry->LabelValue( $column, $format ) || {}; + $value = { '' => $value } unless ref $value; + foreach my $e ( @subs ) { + push @{ $body[ $i ]{'cells'} }, { +@@ -1292,7 +1316,7 @@ sub FormatTable { + my $total_code = $self->LabelValueCode( $column ); + foreach my $e ( @subs ) { + my $total = $total{ $e }; +- $total = $total_code->( $self, %$info, VALUE => $total, FORMAT => 'html' ) ++ $total = $total_code->( $self, %$info, VALUE => $total, FORMAT => $format ) + if $total_code; + push @{ $footer[0]{'cells'} }, { type => 'value', value => $total }; + } +diff --git a/lib/RT/Report/Entry.pm b/lib/RT/Report/Entry.pm +index 8508bde5..618d299f 100644 +--- a/lib/RT/Report/Entry.pm ++++ b/lib/RT/Report/Entry.pm +@@ -91,14 +91,20 @@ sub LabelValue { + my $raw = $self->RawValue( $name, @_ ); + if ( my $code = $self->Report->LabelValueCode( $name ) ) { + $raw = $code->( $self, %{ $self->Report->ColumnInfo( $name ) }, VALUE => $raw, FORMAT => $format ); +- return $self->loc('(no value)') unless defined $raw && length $raw; ++ unless ( defined $raw && length $raw ) { ++ $raw = $self->loc('(no value)'); ++ RT::Interface::Web::EscapeHTML( \$raw ) if $format eq 'html'; ++ } + return $raw; + } + + unless ( ref $raw ) { +- return $self->loc('(no value)') unless defined $raw && length $raw; +- return $self->loc($raw) if $self->Report->ColumnInfo( $name )->{'META'}{'Localize'}; +- return $raw; ++ my $value ++ = !( defined $raw && length $raw ) ? $self->loc('(no value)') ++ : $self->Report->ColumnInfo( $name )->{'META'}{'Localize'} ? $self->loc($raw) ++ : $raw; ++ RT::Interface::Web::EscapeHTML( \$value ) if $format eq 'html'; ++ return $value; + } else { + my $loc = $self->Report->ColumnInfo( $name )->{'META'}{'Localize'}; + my %res = %$raw; +@@ -107,6 +113,7 @@ sub LabelValue { + $_ = $self->loc($_) foreach values %res; + } + $_ = $self->loc('(no value)') foreach grep !defined || !length, values %res; ++ RT::Interface::Web::EscapeHTML( \$_ ) foreach $format eq 'html' ? values %res : (); + return \%res; + } + } +diff --git a/lib/RT/SavedSearch.pm b/lib/RT/SavedSearch.pm +index 440f1bfa..5958b9be 100644 +--- a/lib/RT/SavedSearch.pm ++++ b/lib/RT/SavedSearch.pm +@@ -84,6 +84,21 @@ sub PostLoad { + $self->{'Type'} = $self->{'Attribute'}->SubValue('SearchType'); + } + ++=head2 PostLoadValidate ++ ++Ensure that the ID corresponds to an actual saved search, since it's all ++attributes under the hood. RT's built-in searches are named C> ++rather than C, so they count too. ++ ++=cut ++ ++sub PostLoadValidate { ++ my $self = shift; ++ my $name = $self->{'Attribute'}->__Value('Name') // ''; ++ return ( 0, "Invalid object type" ) unless $name eq 'SavedSearch' || $name =~ /^Search - /; ++ return 1; ++} ++ + sub SaveAttribute { + my $self = shift; + my $object = shift; +@@ -115,6 +130,37 @@ sub UpdateAttribute { + return ($status, $msg); + } + ++=head2 CurrentUserCanCreate [PRIVACY] ++ ++Returns true if the current user may save a search under PRIVACY, which defaults ++to this search's own privacy, asking L so that ++the answer is the one L would give. ++ ++The other C methods are still L's, which ++leave the question to L. This one is here because a caller that ++wants to move a search has to ask about a container it has not reached yet. ++ ++=cut ++ ++sub CurrentUserCanCreate { ++ my $self = shift; ++ my $privacy = shift || $self->Privacy; ++ ++ my $object = $self->_GetObject($privacy); ++ return 0 unless $object; ++ ++ my $right = RT::Attribute->new( $self->CurrentUser )->LookupObjectRight( ++ ObjectType => ref($object), ++ ObjectId => $object->Id, ++ Name => 'SavedSearch', ++ Right => 'create', ++ ); ++ ++ return 1 if $right eq 'allow'; ++ return 0 if $right eq 'deny'; ++ return $self->CurrentUser->HasRight( Right => $right, Object => $object ) ? 1 : 0; ++} ++ + =head2 RT::SavedSearch->EscapeDescription STRING + + This is a class method because system-level saved searches aren't true +diff --git a/lib/RT/SharedSetting.pm b/lib/RT/SharedSetting.pm +index 9bcc090a..3e9986aa 100644 +--- a/lib/RT/SharedSetting.pm ++++ b/lib/RT/SharedSetting.pm +@@ -102,19 +102,32 @@ sub Load { + my ($privacy, $id) = @_; + my $object = $self->_GetObject($privacy); + +- if ($object) { +- $self->{'Attribute'} = RT::Attribute->new($self->CurrentUser); +- $self->{'Attribute'}->Load( $id ); +- if ($self->{'Attribute'}->Id) { +- $self->{'Id'} = $self->{'Attribute'}->Id; +- $self->{'Privacy'} = $privacy; +- $self->PostLoad(); ++ if ( $object && $object->Id ) { ++ my $attribute = RT::Attribute->new( $self->CurrentUser ); ++ $attribute->Load($id); ++ if ( $attribute->Id ) { ++ unless ( ( $attribute->__Value('ObjectType') // '' ) eq ref($object) ++ && ( $attribute->__Value('ObjectId') // 0 ) == $object->Id ) ++ { ++ RT->Logger->warning("Attribute $id is not stored on object $privacy"); ++ return wantarray ? ( 0, $self->loc("Permission Denied") ) : 0; ++ } ++ ++ $self->{'Attribute'} = $attribute; ++ $self->{'Id'} = $attribute->Id; ++ $self->{'Privacy'} = $self->_build_privacy($object); ++ ++ # The checks need the attribute in place, so on failure put it back ++ # out of reach of callers that ignore us ++ my ( $ok, $msg ) = $self->CurrentUserCanSee ? $self->PostLoadValidate : ( 0, 'Permission Denied' ); ++ ++ if ( !$ok ) { ++ delete $self->{$_} for qw/Attribute Privacy/; ++ $self->{'Id'} = 0; ++ return wantarray ? ( $ok, $self->loc($msg) ) : $ok; ++ } + +- return wantarray ? (0, $self->loc("Permission Denied")) : 0 +- unless $self->CurrentUserCanSee; +- +- my ($ok, $msg) = $self->PostLoadValidate; +- return wantarray ? ($ok, $msg) : $ok if !$ok; ++ $self->PostLoad(); + + return wantarray ? (1, $self->loc("Loaded [_1] [_2]", $self->ObjectName, $self->Name)) : 1; + } else { +@@ -200,7 +213,9 @@ sub Save { + my $object = $self->_GetObject($privacy); + + return (0, $self->loc("Failed to load object for [_1]", $privacy)) +- unless $object; ++ unless $object && $object->Id; ++ ++ $privacy = $self->_build_privacy($object); + + return (0, $self->loc("Permission Denied")) + unless $self->CurrentUserCanCreate($privacy); +@@ -234,6 +249,10 @@ Updates the parameters of an existing shared setting. Any arguments are passed + to the L method. Returns a tuple of status and message, where + status is true on success. + ++A C that names a different container moves the setting there, which ++takes the rights to create it there as well as the rights to modify it where it ++is now. ++ + =cut + + sub Update { +@@ -247,6 +266,12 @@ sub Update { + return (0, $self->loc("Permission Denied")) + unless $self->CurrentUserCanModify; + ++ if ( defined $args{'Privacy'} && $args{'Privacy'} ne ( $self->Privacy // '' ) ) { ++ return ( 0, $self->loc("Permission Denied") ) ++ unless $self->_GetObject( $args{'Privacy'} ) ++ && $self->CurrentUserCanCreate( $args{'Privacy'} ); ++ } ++ + my ($status, $msg) = $self->UpdateAttribute(\%args); + + return (1, $self->loc("[_1] update: Nothing changed", ucfirst($self->ObjectName))) +@@ -276,6 +301,8 @@ where status is true upon success. + + sub Delete { + my $self = shift; ++ return ( 0, $self->loc( "No [_1] loaded", $self->ObjectName ) ) unless $self->Id; ++ + return (0, $self->loc("Permission Denied")) + unless $self->CurrentUserCanDelete; + +@@ -417,8 +444,17 @@ sub _GetObject { + + my $object = $self->_load_privacy_object($obj_type, $obj_id); + ++ # _load_privacy_object has already said why it declined ++ return undef unless $object; ++ + unless (ref($object) eq $obj_type) { +- $RT::Logger->error("Could not load object of type $obj_type with ID $obj_id, got object of type " . (ref($object) || 'undef')); ++ RT->Logger->error( ++ "Could not load object of type $obj_type with ID $obj_id, got object of type " . ref($object) ); ++ return undef; ++ } ++ ++ unless ( $object->Id ) { ++ RT->Logger->debug("Could not load object of type $obj_type with ID $obj_id"); + return undef; + } + +diff --git a/lib/RT/Template.pm b/lib/RT/Template.pm +index 4ccb791a..7a025117 100644 +--- a/lib/RT/Template.pm ++++ b/lib/RT/Template.pm +@@ -147,6 +147,26 @@ sub _Value { + + } + ++# Takes an optional type, and defaults to this template's stored type. Returns ++# true if content of that type is Perl, which allows code. ++# ++# This wrapper can always access the stored Type value, even if CurrentUser ++# doesn't have ShowTemplate, so it will always see what is in the DB. ++# ++# An undetermined type counts as Perl as has been true historically. ++# ++# The rights checks that gate code use this. _ParseContent dispatches on Type ++# directly, because it has already passed a read check and reads the stored ++# value anyway, and an undetermined type renders there without running code. ++ ++sub _TypeIsPerl { ++ my $self = shift; ++ my $type = @_ ? shift : $self->__Value('Type'); ++ ++ return 1 unless defined $type; ++ return $type eq 'Perl'; ++} ++ + =head2 Load + + Load a template, either by number or by name. +@@ -259,7 +279,8 @@ sub Create { + @_ + ); + +- if ( $args{Type} eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System) ) { ++ if ( $self->_TypeIsPerl( $args{Type} ) ++ && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System) ) { + return ( undef, $self->loc('Permission Denied') ); + } + +@@ -289,6 +310,15 @@ sub Create { + if $tmp->id; + } + ++ { ++ my ( $ok, $msg ) = $self->CheckCreateTicketsQueue( ++ Queue => $args{'Queue'}, ++ Type => $args{'Type'}, ++ Content => $args{'Content'}, ++ ); ++ return ( undef, $msg ) unless $ok; ++ } ++ + my ( $result, $msg ) = $self->SUPER::Create( + Content => $args{'Content'}, + Queue => $args{'Queue'}, +@@ -763,7 +793,7 @@ sub SetType { + my $self = shift; + my $NewType = shift; + +- if ($NewType eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) { ++ if ($self->_TypeIsPerl($NewType) && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) { + return ( undef, $self->loc('Permission Denied') ); + } + +@@ -780,13 +810,126 @@ sub SetContent { + my $self = shift; + my $NewContent = shift; + +- if ($self->Type eq 'Perl' && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) { ++ if ($self->_TypeIsPerl && !$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) { + return ( undef, $self->loc('Permission Denied') ); + } + ++ # __Value, not Queue and Type, because a user with ModifyTemplate but not ++ # ShowTemplate reads undef from both, which would skip the check entirely. ++ # CurrentUserHasQueueRight below reads the queue the same way. ++ my ( $ok, $msg ) = $self->CheckCreateTicketsQueue( ++ Queue => $self->__Value('Queue'), ++ Type => $self->__Value('Type'), ++ Content => $NewContent, ++ ); ++ return ( undef, $msg ) unless $ok; ++ + return $self->_Set( Field => 'Content', Value => $NewContent ); + } + ++=head2 CheckCreateTicketsQueue Queue => ID, Type => TYPE, Content => CONTENT ++ ++Confines the C<===Create-Ticket:> and C<===Update-Ticket:> directives of a ++queue-specific template to that template's own queue. ++ ++L runs as the system user, so a directive naming ++another queue, or a ticket by id in another queue, would otherwise act outside ++the queue whose C right allowed the template to be written. ++ ++C granted globally is already permission to act on every queue, so ++a user who holds it is exempt, as are global templates, which require it to ++write. C templates are exempt because if a user has C, they ++can modify any other objects in Perl code. ++ ++The check therefore applies only to a user whose C is limited to ++particular queues and is using Simple type templates. ++ ++Returns a status, and a message when the check fails. ++ ++=cut ++ ++sub CheckCreateTicketsQueue { ++ my $self = shift; ++ my %args = ( ++ Queue => undef, ++ Type => undef, ++ Content => undef, ++ @_ ++ ); ++ ++ # A global template has a Queue of 0, and is not confined to any queue. ++ # Callers must read Queue in a way that doesn't depend on the current user's ++ # rights, or a user who can't read the template skips the check entirely. ++ return (1) unless $args{'Queue'}; ++ return (1) if ( $args{'Type'} // '' ) eq 'Perl'; ++ return (1) ++ if $self->CurrentUser->HasRight( Object => RT->System, Right => 'ModifyTemplate' ); ++ ++ my $content = $args{'Content'}; ++ return (1) unless defined $content && length $content; ++ ++ # Hand RT::Action::CreateTickets->Parse only what it can parse. Anything ++ # else makes it log an error for every ordinary template that is saved. ++ return (1) ++ unless substr( $content, 0, 3 ) eq '===' ++ or $content =~ /(?:\t|,)/; ++ ++ my $queue = RT::Queue->new( RT->SystemUser ); ++ $queue->Load( $args{'Queue'} ); ++ return ( 0, $self->loc('Invalid queue') ) unless $queue->id; ++ ++ RT::StaticUtil::RequireModule('RT::Action::CreateTickets') ++ or return ( 0, $self->loc('Could not load the CreateTickets action') ); ++ ++ # Parse with the action itself, and read the fields of each directive with ++ # the same method the action reads them with when it runs, so this check and ++ # the directives it is checking cannot drift apart. A non-Perl template is ++ # parsed without interpolation, so every value here is the literal value ++ # that will be used. ++ my $action = RT::Action::CreateTickets->new( CurrentUser => $self->CurrentUser ); ++ $action->Parse( Content => $content ); ++ ++ my $denied = $self->loc( ++ "A template in the [_1] queue can only create or update tickets in that queue. Contact your RT admin for additional rights.", ++ $queue->Name ); ++ ++ my @targets = ( @{ $action->{'create_tickets'} || [] }, ++ @{ $action->{'update_tickets'} || [] } ); ++ ++ for my $target (@targets) { ++ my $directives = $action->{'templates'}->{$target}; ++ next unless defined $directives; ++ ++ my ($fields) = $action->ParseFields($directives); ++ my $value = $fields->{'queue'}; ++ next unless defined $value; ++ ++ # Naming a field twice yields every value it was given. ++ for my $name ( ref $value eq 'ARRAY' ? @$value : $value ) { ++ # An empty Queue sets nothing, and creating without one fails. ++ next unless defined $name && length $name; ++ ++ my $target_queue = RT::Queue->new( RT->SystemUser ); ++ $target_queue->Load($name); ++ return ( 0, $denied ) ++ unless $target_queue->id and $target_queue->id == $queue->id; ++ } ++ } ++ ++ # An update names its target by id, which has to be in this queue too. ++ for my $target ( @{ $action->{'update_tickets'} || [] } ) { ++ my ($id) = $target =~ /^update-(\d+)/; ++ next unless $id; ++ ++ my $ticket = RT::Ticket->new( RT->SystemUser ); ++ $ticket->LoadById($id); ++ return ( 0, $denied ) ++ unless $ticket->id and $ticket->Queue == $queue->id; ++ } ++ ++ return (1); ++} ++ + sub _UpdateAttributes { + my $self = shift; + my %args = ( +@@ -794,10 +937,10 @@ sub _UpdateAttributes { + @_, + ); + +- my $type = $args{NewValues}{Type} || $self->Type; ++ my $type = $args{NewValues}{Type} || $self->__Value('Type'); + + # forbid updating content when the (possibly new) value of Type is Perl +- if ($type eq 'Perl' && exists $args{NewValues}{Content}) { ++ if ($self->_TypeIsPerl($type) && exists $args{NewValues}{Content}) { + if (!$self->CurrentUser->HasRight(Right => 'ExecuteCode', Object => $RT::System)) { + return $self->loc('Permission Denied'); + } +@@ -820,7 +963,7 @@ sub CompileCheck { + my $self = shift; + + return (1, $self->loc("Template does not include Perl code")) +- unless $self->Type eq 'Perl'; ++ unless $self->_TypeIsPerl; + + my $content = $self->Content; + $content = '' if !defined($content); +diff --git a/lib/RT/Ticket.pm b/lib/RT/Ticket.pm +index 0da1e33b..07066df1 100644 +--- a/lib/RT/Ticket.pm ++++ b/lib/RT/Ticket.pm +@@ -1483,6 +1483,9 @@ Returns the amount of time worked on this ticket and all child tickets + sub TotalTimeWorked { + my $self = shift; + my $seen = shift || {}; ++ ++ return 0 unless $self->CurrentUserCanSeeTime; ++ + my $time = $self->TimeWorked; + my $links = $self->Members; + LINK: while (my $link = $links->Next) { +@@ -1518,6 +1521,8 @@ sub TimeWorkedPerUser { + my $self = shift; + my %time_worked; + ++ return \%time_worked unless $self->CurrentUserCanSeeTime; ++ + my $transactions = $self->Transactions; + $transactions->Limit( + FIELD => 'TimeTaken', +@@ -1819,10 +1824,11 @@ sub Atomic { + } + + if (%granted) { ++ my $atomic_id = $self->id; + *CurrentUserHasRight = sub { + my $self = shift; + my $right = shift; +- return 1 if $granted{$right}; ++ return 1 if $granted{$right} && ( $self->id // 0 ) == ( $atomic_id // 0 ); + return $orig_current_user_has_right->( $self, $right, @_ ); + }; + } +@@ -2930,6 +2936,9 @@ sub _Value { + unless ( $self->CurrentUserHasRight('ShowTicket') ) { + return (undef); + } ++ ++ return undef if $self->IsTimeField($field) && !$self->CurrentUserCanSeeTime; ++ + return ( $self->SUPER::_Value($field) ); + + } +@@ -3240,10 +3249,25 @@ sub Forward { + @_ + ); + +- unless ( $self->CurrentUserHasRight('ForwardMessage') ) { ++ unless ( $self->CurrentUserCanSee && $self->CurrentUserHasRight('ForwardMessage') ) { + return ( 0, $self->loc("Permission Denied") ); + } + ++ if ( $args{Transaction} ) { ++ my $txn = RT::Transaction->new( $self->CurrentUser ); ++ $txn->Load( $args{Transaction}->id ); ++ ++ unless ($txn->id ++ && $txn->CurrentUserCanSee ++ && $txn->ObjectType eq 'RT::Ticket' ++ && $txn->Object->id == $self->id ) ++ { ++ return ( 0, $self->loc("Permission Denied") ); ++ } ++ ++ $args{Transaction} = $txn; ++ } ++ + $args{$_} = join ", ", map { $_->format } RT::EmailParser->ParseEmailAddress( $args{$_} || '' ) for qw(To Cc Bcc); + + return (0, $self->loc("Can't forward: no valid email addresses specified") ) +@@ -3301,8 +3325,24 @@ Returns true if the current user can see time worked, estimated, left + sub CurrentUserCanSeeTime { + my $self = shift; + +- return $self->CurrentUser->Privileged || +- !RT->Config->Get('HideTimeFieldsFromUnprivilegedUsers'); ++ return 1 unless RT->Config->Get('HideTimeFieldsFromUnprivilegedUsers'); ++ return 1 if $self->CurrentUser->Id == RT->SystemUser->Id; ++ return $self->CurrentUser->Privileged ? 1 : 0; ++} ++ ++=head2 IsTimeField FIELD ++ ++Returns true if FIELD is one of the ticket time columns governed by ++C<$HideTimeFieldsFromUnprivilegedUsers>. Callable as a class method. ++ ++=cut ++ ++sub IsTimeField { ++ my $self = shift; ++ my $field = shift; ++ ++ return 0 unless defined $field; ++ return $field =~ /^Time(?:Worked|Estimated|Left)$/i ? 1 : 0; + } + + sub _DateForCustomDateRangeField { +diff --git a/lib/RT/Tickets.pm b/lib/RT/Tickets.pm +index 1034ef84..eb41e154 100644 +--- a/lib/RT/Tickets.pm ++++ b/lib/RT/Tickets.pm +@@ -414,6 +414,24 @@ sub _EnumLimit { + ); + } + ++=head2 IsHiddenTimeField FIELD ++ ++Returns true if FIELD is one of the time columns and the current user may not ++see it, per L. ++ ++=cut ++ ++sub IsHiddenTimeField { ++ my $self = shift; ++ my $field = shift; ++ ++ return 0 unless defined $field; ++ return 0 unless RT::Ticket->IsTimeField($field); ++ ++ my $ticket = RT::Ticket->new( $self->CurrentUser ); ++ return $ticket->CurrentUserCanSeeTime ? 0 : 1; ++} ++ + =head2 _IntLimit + + Handle fields where the values are limited to integers. (For example, +@@ -427,6 +445,8 @@ Meta Data: + sub _IntLimit { + my ( $sb, $field, $op, $value, @rest ) = @_; + ++ return if $sb->IsHiddenTimeField($field); ++ + my $is_a_like = $op =~ /MATCHES|ENDSWITH|STARTSWITH|LIKE/i; + + # We want to support for ticket autocomplete, +@@ -1622,6 +1642,7 @@ sub OrderByCols { + push @res, $row; + next; + } ++ next if $self->IsHiddenTimeField( $row->{FIELD} ); + if ( $row->{FIELD} !~ /\./ ) { + my $meta = $FIELD_METADATA{ $row->{FIELD} }; + unless ( $meta ) { +diff --git a/lib/RT/Transaction.pm b/lib/RT/Transaction.pm +index 5d58e7c6..ab433d2e 100644 +--- a/lib/RT/Transaction.pm ++++ b/lib/RT/Transaction.pm +@@ -1624,6 +1624,8 @@ sub _Value { + return undef; + } + ++ return undef if $self->IsTimeField($field) && !$self->CurrentUserCanSeeTime; ++ + return $self->SUPER::_Value( $field ); + } + +@@ -1654,6 +1656,9 @@ sub CurrentUserCanSee { + return 0 unless $cf->CurrentUserCanSee; + } + ++ # A transaction that only records a change to a hidden time field has nothing else to show ++ return 0 if $self->IsHiddenTimeFieldChange; ++ + # Transactions that might have changed the ->Object's visibility to + # the current user are marked readable + return 1 if $self->{ _object_is_readable }; +@@ -1662,6 +1667,53 @@ sub CurrentUserCanSee { + return $self->Object->CurrentUserCanSee("Transaction", $self); + } + ++=head2 CurrentUserCanSeeTime ++ ++Returns true if the current user can see the time values recorded on this ++transaction, deferring to L for ticket ++transactions. ++ ++=cut ++ ++sub CurrentUserCanSeeTime { ++ my $self = shift; ++ ++ return 1 unless RT->Config->Get('HideTimeFieldsFromUnprivilegedUsers'); ++ ++ my $object = $self->Object; ++ return 1 unless $object && $object->can('CurrentUserCanSeeTime'); ++ return $object->CurrentUserCanSeeTime; ++} ++ ++=head2 IsTimeField FIELD ++ ++Returns true if FIELD is one of the transaction time columns governed by ++C<$HideTimeFieldsFromUnprivilegedUsers>. Callable as a class method. ++ ++=cut ++ ++sub IsTimeField { ++ my $self = shift; ++ my $field = shift; ++ ++ return 0 unless defined $field; ++ return $field eq 'TimeTaken' ? 1 : 0; ++} ++ ++=head2 IsHiddenTimeFieldChange ++ ++Returns true if this transaction records a change to one of the time fields ++the current user is not allowed to see. ++ ++=cut ++ ++sub IsHiddenTimeFieldChange { ++ my $self = shift; ++ ++ return 0 unless RT::Ticket->IsTimeField( $self->__Value('Field') ); ++ return $self->CurrentUserCanSeeTime ? 0 : 1; ++} ++ + + sub Ticket { + my $self = shift; +@@ -2371,6 +2423,8 @@ sub Serialize { + $store{NewValue} = \( join '-', 'RT::Ticket', $RT::Organization, $store{NewValue} ); + } + ++ delete $store{TimeTaken} unless $self->CurrentUserCanSeeTime; ++ + return %store; + } + +diff --git a/lib/RT/Transactions.pm b/lib/RT/Transactions.pm +index 784fe84d..4c9835f9 100644 +--- a/lib/RT/Transactions.pm ++++ b/lib/RT/Transactions.pm +@@ -141,6 +141,12 @@ sub LimitToTicket { + sub AddRecord { + my $self = shift; + my ($record) = @_; ++ ++ # CurrentUserCanSee says no for these, but the checks below are skipped ++ # for most types when UseSQLForACLChecks is on, and no SQL limit expresses ++ # this. Grouped report rows are not transactions and have nothing to hide. ++ return if $record->isa('RT::Transaction') && $record->IsHiddenTimeFieldChange; ++ + return $self->SUPER::AddRecord($record) if $self->{_current_user_can_see_all}; + + if ( $self->{_is_ticket_only_search} && RT->Config->Get('UseSQLForACLChecks') ) { +@@ -339,6 +345,31 @@ sub _EnumLimit { + ); + } + ++=head2 IsHiddenTimeField FIELD ++ ++Returns true if FIELD is one of the time columns and the current user may not ++see it, per L. ++ ++=cut ++ ++sub IsHiddenTimeField { ++ my $self = shift; ++ my $field = shift; ++ ++ return 0 unless defined $field; ++ ++ # TimeTaken is ours; _TicketLimit drops the Ticket prefix before it asks about the ticket's own columns ++ return 0 unless RT::Transaction->IsTimeField($field) || RT::Ticket->IsTimeField($field); ++ ++ my $ticket = RT::Ticket->new( $self->CurrentUser ); ++ return $ticket->CurrentUserCanSeeTime ? 0 : 1; ++} ++ ++sub OrderByCols { ++ my $self = shift; ++ return $self->SUPER::OrderByCols( grep { !$self->IsHiddenTimeField( $_->{FIELD} ) } @_ ); ++} ++ + =head2 _IntLimit + + Handle fields where the values are limited to integers. (id) +@@ -351,6 +382,8 @@ Meta Data: + sub _IntLimit { + my ( $sb, $field, $op, $value, @rest ) = @_; + ++ return if $sb->IsHiddenTimeField($field); ++ + my $is_a_like = $op =~ /MATCHES|ENDSWITH|STARTSWITH|LIKE/i; + + # We want to support , but we need to explicitly typecast +@@ -842,6 +875,8 @@ sub _TicketLimit { + my ( $self, $field, $op, $value, %rest ) = @_; + $field =~ s!^Ticket!!; + ++ return if $self->IsHiddenTimeField($field); ++ + if ( $field eq 'Queue' && $value =~ /\D/ ) { + if ( ref $value eq 'ARRAY' ) { + my @values; +diff --git a/lib/RT/URI/attribute.pm b/lib/RT/URI/attribute.pm +index 8d3c5f00..c05a6d32 100644 +--- a/lib/RT/URI/attribute.pm ++++ b/lib/RT/URI/attribute.pm +@@ -93,6 +93,16 @@ sub LocalURIPrefix { + return $self->Scheme . "://" . RT->Config->Get('Organization'); + } + ++=head2 IsInternalOnly ++ ++Returns true. Attributes are RT's own storage, not records a user links to; ++the C links RT keeps between dashboards and the searches they ++include are created by L. ++ ++=cut ++ ++sub IsInternalOnly {1} ++ + =head2 IsLocal + + Returns a true value, the attribute ID, if this object represents a local attribute, +diff --git a/lib/RT/URI/base.pm b/lib/RT/URI/base.pm +index 6dafe392..e7f23f48 100644 +--- a/lib/RT/URI/base.pm ++++ b/lib/RT/URI/base.pm +@@ -127,6 +127,17 @@ sub IsLocal { + return undef; + } + ++=head2 IsInternalOnly ++ ++Returns false, meaning this scheme may be used in caller-supplied links. ++ ++Resolvers for schemes RT maintains for its own bookkeeping should override this ++and return true. See L. ++ ++=cut ++ ++sub IsInternalOnly {0} ++ + =head2 AsString + + Return a "pretty" string representing the URI object. +diff --git a/lib/RT/User.pm b/lib/RT/User.pm +index f4fbd273..0041ca00 100644 +--- a/lib/RT/User.pm ++++ b/lib/RT/User.pm +@@ -176,6 +176,10 @@ sub Create { + return ($ok, $msg) if !$ok; + + $args{'Password'} = $self->_GeneratePassword($args{'Password'}); ++ unless ( defined $args{'Password'} ) { ++ RT->Logger->error("Couldn't hash a password for new user $args{'Name'}"); ++ return ( 0, $self->loc("Could not set password") ); ++ } + } + + #TODO Specify some sensible defaults. +@@ -1156,6 +1160,10 @@ sub SetPassword { + + my $new = !$self->HasPassword; + $password = $self->_GeneratePassword($password); ++ unless ( defined $password ) { ++ RT->Logger->error("Couldn't hash a password for user " . $self->id); ++ return ( 0, $self->loc("Could not set password") ); ++ } + + ( $val, $msg ) = $self->_Set(Field => 'Password', Value => $password); + if ($val) { +@@ -1184,9 +1192,12 @@ sub _GeneratePassword_bcrypt { + } else { + $rounds = RT->Config->Get('BcryptCost'); + +- # Generate a random 16-octet base64 salt +- $salt = ""; +- $salt .= pack("C", int rand(256)) for 1..16; ++ # Generate a random 16-octet salt ++ $salt = RT::Util::random_bytes(16); ++ unless ( defined $salt ) { ++ RT->Logger->error("Couldn't generate a bcrypt salt"); ++ return; ++ } + } + + my $hash = Crypt::Eksblowfish::Bcrypt::bcrypt_hash({ +@@ -1205,11 +1216,18 @@ sub _GeneratePassword_sha512 { + my $self = shift; + my ($password, $salt) = @_; + +- # Generate a 16-character base64 salt ++ # Generate a 16-character base64 salt. The alphabet is 64 characters, a ++ # power of two, so masking each random octet down to six bits picks from ++ # it without bias. + unless ($salt) { +- $salt = ""; +- $salt .= ("a".."z", "A".."Z","0".."9", "+", "/")[rand 64] +- for 1..16; ++ my $bytes = RT::Util::random_bytes(16); ++ unless ( defined $bytes ) { ++ RT->Logger->error("Couldn't generate a sha512 salt"); ++ return; ++ } ++ ++ my @alphabet = ("a".."z", "A".."Z", "0".."9", "+", "/"); ++ $salt = join '', map { $alphabet[ $_ & 0x3f ] } unpack( 'C*', $bytes ); + } + + my $sha = Digest::SHA->new(512); +@@ -1228,6 +1246,8 @@ By default, the method is currently C. + + =cut + ++# Returns undef if the salt cannot be generated. Callers storing the result ++# MUST check it: an undef here means no password. + sub _GeneratePassword { + my $self = shift; + return $self->_GeneratePassword_bcrypt(@_); +@@ -1268,7 +1288,9 @@ sub IsPassword { + + if ( $self->PrincipalObj->Disabled ) { + # Run the bcrypt generator to avoid timing side-channel attacks +- RT::Util::constant_time_eq($self->_GeneratePassword_bcrypt($value), '0' x 64); ++ if ( defined( my $hash = $self->_GeneratePassword_bcrypt($value) ) ) { ++ RT::Util::constant_time_eq( $hash, '0' x 64 ); ++ } + $RT::Logger->info( + "Disabled user " . $self->Name . " tried to log in" ); + return (undef); +@@ -1276,7 +1298,9 @@ sub IsPassword { + + unless ($self->HasPassword) { + # Run the bcrypt generator to avoid timing side-channel attacks +- RT::Util::constant_time_eq($self->_GeneratePassword_bcrypt($value), '0' x 64); ++ if ( defined( my $hash = $self->_GeneratePassword_bcrypt($value) ) ) { ++ RT::Util::constant_time_eq( $hash, '0' x 64 ); ++ } + return undef; + } + my $stored = $self->__Value('Password'); +@@ -1333,8 +1357,12 @@ sub IsPassword { + + # We got here by validating successfully, but with a legacy + # password form. Update to the most recent form. ++ # The password was valid; if it cannot be rehashed right now, leave it in ++ # its old form rather than failing a login that should have succeeded. + my $obj = $self->isa("RT::CurrentUser") ? $self->UserObj : $self; +- $obj->_Set(Field => 'Password', Value => $self->_GeneratePassword($value) ); ++ if ( defined( my $rehashed = $self->_GeneratePassword($value) ) ) { ++ $obj->_Set(Field => 'Password', Value => $rehashed ); ++ } + return 1; + } + +@@ -1373,7 +1401,11 @@ Generate a random authentication string for the user. + + sub GenerateAuthToken { + my $self = shift; +- my $token = substr(Digest::MD5::md5_hex(time . {} . rand()),0,16); ++ my $token = RT::Util::random_hex(16); ++ unless ( defined $token ) { ++ RT->Logger->error("Couldn't generate an auth token for user " . $self->id); ++ return ( 0, $self->loc("Could not generate a secure token") ); ++ } + return $self->SetAuthToken( $token ); + } + +@@ -1393,7 +1425,11 @@ sub GenerateAuthString { + # Mint on demand via SystemUser: signing RSS/iCal/CSRF URLs is a + # system action, but ModifySelf isn't granted to Privileged users + # by default, so SetAuthToken under the current user would fail. +- $token = substr(Digest::MD5::md5_hex(time . {} . rand()), 0, 16); ++ $token = RT::Util::random_hex(16); ++ unless ( defined $token ) { ++ RT->Logger->error("Couldn't generate an auth token for user " . $self->id); ++ return; ++ } + my $writer = RT::User->new( RT->SystemUser ); + $writer->Load( $self->id ); + my ($ok, $msg) = $writer->SetAuthToken($token); +@@ -1788,14 +1824,7 @@ sub Stylesheet { + my $self = shift; + + my $style = RT->Config->Get('WebDefaultStylesheet', $self); +- +- if (RT::Interface::Web->ComponentPathIsSafe($style)) { +- for my $root (RT::Interface::Web->StaticRoots) { +- if (-d "$root/css/$style") { +- return $style +- } +- } +- } ++ return $style if grep { $_ eq $style } RT::Interface::Web->Themes; + + # Fall back to the system stylesheet. + return RT->Config->Get('WebDefaultStylesheet'); +diff --git a/lib/RT/Util.pm b/lib/RT/Util.pm +index 13d25bec..1c79e140 100644 +--- a/lib/RT/Util.pm ++++ b/lib/RT/Util.pm +@@ -52,10 +52,13 @@ use warnings; + + + use base 'Exporter'; +-our @EXPORT = qw/safe_run_child mime_recommended_filename EntityLooksLikeEmailMessage EmailContentTypes/; ++our @EXPORT ++ = qw/safe_run_child mime_recommended_filename EntityLooksLikeEmailMessage EmailContentTypes CanonicalizeContentType/; + + use Scalar::Util qw/weaken/; + use Encode qw/encode/; ++use Crypt::URandom (); ++use HTTP::Headers::Util qw/split_header_words join_header_words/; + + sub safe_run_child (&) { + my $our_pid = $$; +@@ -136,6 +139,42 @@ sub mime_recommended_filename { + return; + } + ++=head2 CanonicalizeContentType( TYPE ) ++ ++Parses TYPE and returns it re-serialized in a form with a single possible ++interpretation, so that matching it against known content types gives the ++same answer as parsing the C header built from it. ++ ++Returns the empty string unless TYPE holds exactly one content type of the ++form C, followed by parameters that all have a value as ++RFC 2045 section 5.1 requires. Callers are expected to fall back to a type ++of their own choosing on an empty return. ++ ++=cut ++ ++sub CanonicalizeContentType { ++ my $type = shift; ++ return '' unless defined $type; ++ ++ $type =~ s/[^\x20-\x7e]+//g; ++ ++ my @words = split_header_words($type); ++ return '' unless @words == 1; ++ ++ my $word = $words[0]; ++ ++ # restricted-name from RFC 6838 section 4.2 ++ return '' unless $word->[0] =~ m{^[a-z0-9][a-z0-9!\#\$&^_.+-]*/[a-z0-9][a-z0-9!\#\$&^_.+-]*$}; ++ ++ # [ type/subtype, undef, name, value, ... ], so parameters start at 2. ++ # RFC 2045 section 5.1 requires a value: reject "text/plain; charset". ++ for ( my $i = 2; $i < @$word; $i += 2 ) { ++ return '' unless defined $word->[ $i + 1 ]; ++ } ++ ++ return join_header_words(@words); ++} ++ + sub assert_bytes { + my $string = shift; + return unless utf8::is_utf8($string); +@@ -216,6 +255,66 @@ sub constant_time_eq { + return 0 + not $result; + } + ++=head2 C ++ ++Returns C<$count> random octets. ++ ++Returns undef, having logged the reason, if the platform cannot supply ++random data or supplies less than was asked for. ++ ++=cut ++ ++sub random_bytes { ++ my $count = shift; ++ ++ # Count must be a positive integer. ++ unless ( defined $count && $count =~ /\A[0-9]+\z/ && $count > 0 ) { ++ RT->Logger->error('random_bytes requires a positive integer count'); ++ return; ++ } ++ ++ # Crypt::URandom reports failure by croaking; convert that to RT's ++ # convention here so callers only ever have to check for undef. ++ my $bytes = eval { Crypt::URandom::urandom($count) }; ++ unless ( defined $bytes ) { ++ RT->Logger->error("Could not read $count octets from the system CSPRNG: $@"); ++ return; ++ } ++ ++ unless ( length($bytes) == $count ) { ++ RT->Logger->error( ++ "Asked the system CSPRNG for $count octets and got " . length($bytes) ); ++ return; ++ } ++ ++ return $bytes; ++} ++ ++=head2 C ++ ++Returns a string of C<$count> lowercase hexadecimal digits drawn from ++L, so C<$count> characters carry C<$count * 4> bits of ++entropy. Convenient where a random value has to survive as text, in a ++URL or an ascii database column. ++ ++Returns undef under the same conditions as L. ++ ++=cut ++ ++sub random_hex { ++ my $count = shift; ++ ++ unless ( defined $count && $count =~ /\A[0-9]+\z/ && $count > 0 ) { ++ RT->Logger->error('random_hex requires a positive integer count'); ++ return; ++ } ++ ++ my $bytes = random_bytes( int( ( $count + 1 ) / 2 ) ); ++ return unless defined $bytes; ++ ++ return substr( unpack( 'H*', $bytes ), 0, $count ); ++} ++ + =head2 EntityLooksLikeEmailMessage( MIME::Entity ) + + Check MIME type headers for entities that look like email. +diff --git a/share/html/Admin/Articles/Classes/Modify.html b/share/html/Admin/Articles/Classes/Modify.html +index 60a237a9..a93aab69 100644 +--- a/share/html/Admin/Articles/Classes/Modify.html ++++ b/share/html/Admin/Articles/Classes/Modify.html +@@ -268,18 +268,23 @@ if ( $ClassObj->Id && not $skip_update ) { + } + + if ( $ClassObj->id && $Submitted && not $skip_update ) { +- if ( $Disabled != $ClassObj->Disabled) { +- my ($code, $msg) = $ClassObj->SetDisabled($Disabled); +- push @results, loc('Enabled status [_1]', loc_fuzzy($msg)); +- } ++ if ( $ClassObj->CurrentUserHasRight('AdminClass') ) { ++ if ( $Disabled != $ClassObj->Disabled) { ++ my ($code, $msg) = $ClassObj->SetDisabled($Disabled); ++ push @results, loc('Enabled status [_1]', loc_fuzzy($msg)); ++ } + +- for (keys %include) { +- if ($ARGS{"Include-$_"}) { +- $ClassObj->DeleteAttribute("Skip-$_"); +- } else { +- $ClassObj->SetAttribute(Name => "Skip-$_", Content => 1); ++ for (keys %include) { ++ if ($ARGS{"Include-$_"}) { ++ $ClassObj->DeleteAttribute("Skip-$_"); ++ } else { ++ $ClassObj->SetAttribute(Name => "Skip-$_", Content => 1); ++ } + } + } ++ else { ++ push @results, loc('Permission Denied'); ++ } + } + + # This code does automatic redirection if any updates happen. +diff --git a/share/html/Admin/Assets/Catalogs/DefaultValues.html b/share/html/Admin/Assets/Catalogs/DefaultValues.html +index db74b278..e4df81b0 100644 +--- a/share/html/Admin/Assets/Catalogs/DefaultValues.html ++++ b/share/html/Admin/Assets/Catalogs/DefaultValues.html +@@ -77,6 +77,9 @@ + my $catalog = RT::Catalog->new( $session{CurrentUser} ); + $catalog->Load($id) || Abort( loc( "Couldn't load asset [_1]", $id ) ); + ++Abort( loc("Permission Denied"), Code => HTTP::Status::HTTP_FORBIDDEN ) ++ unless $catalog->CurrentUserHasRight('AdminCatalog'); ++ + my $title = loc( 'Default Values for catalog [_1]', $catalog->Name ); + + my @results; +diff --git a/share/html/Admin/CustomFields/Modify.html b/share/html/Admin/CustomFields/Modify.html +index 6f6be579..a9c11369 100644 +--- a/share/html/Admin/CustomFields/Modify.html ++++ b/share/html/Admin/CustomFields/Modify.html +@@ -425,11 +425,16 @@ if ( $ARGS{'Update'} && $id ne 'new' ) { + } + + if ( $CustomFieldObj->SupportDefaultValues ) { +- my ($ret, $msg) = $CustomFieldObj->SetDefaultValues( +- Object => RT->System, +- Values => $ARGS{'Default-' . $CustomFieldObj->id . '-Value'} // $ARGS{'Default-' . $CustomFieldObj->id . '-Values'}, +- ); +- push @results, $msg; ++ if ( $CustomFieldObj->CurrentUserHasRight('AdminCustomField') ) { ++ my ($ret, $msg) = $CustomFieldObj->SetDefaultValues( ++ Object => RT->System, ++ Values => $ARGS{'Default-' . $CustomFieldObj->id . '-Value'} // $ARGS{'Default-' . $CustomFieldObj->id . '-Values'}, ++ ); ++ push @results, $msg; ++ } ++ else { ++ push @results, loc('Permission Denied'); ++ } + } + + my $paramtag = "CustomField-". $CustomFieldObj->Id ."-Value"; +diff --git a/share/html/Admin/Elements/EditCustomFields b/share/html/Admin/Elements/EditCustomFields +index f1846a45..82415b25 100644 +--- a/share/html/Admin/Elements/EditCustomFields ++++ b/share/html/Admin/Elements/EditCustomFields +@@ -95,7 +95,7 @@ + + <%INIT> + my $id = $Object->Id || 0; +-if ($id and !$Object->CurrentUserHasRight('AssignCustomFields')) { ++if (!$Object->CurrentUserHasRight('AssignCustomFields')) { + $m->out('

', loc('(No custom fields)'), '

'); + return; + } +diff --git a/share/html/Admin/Global/Scrips.html b/share/html/Admin/Global/Scrips.html +index 100dd95e..5a43f91b 100644 +--- a/share/html/Admin/Global/Scrips.html ++++ b/share/html/Admin/Global/Scrips.html +@@ -52,6 +52,11 @@ + <%init> + my $title = loc("Modify scrips which apply to all queues"); + my (@actions); ++ ++if ( $ARGS{MoveScripUp} || $ARGS{MoveScripDown} ) { ++ Abort( loc("Permission Denied"), Code => HTTP::Status::HTTP_FORBIDDEN ) ++ unless $session{CurrentUser}->HasRight( Object => RT->System, Right => 'ModifyScrips' ); ++} + + <%ARGS> + $id => 0 +diff --git a/share/html/Admin/Lifecycles/Advanced.html b/share/html/Admin/Lifecycles/Advanced.html +index ca286021..a3aababe 100644 +--- a/share/html/Admin/Lifecycles/Advanced.html ++++ b/share/html/Admin/Lifecycles/Advanced.html +@@ -61,7 +61,7 @@ + <&| /Widgets/TitleBox, title => loc('Basics'), content_class => 'mx-auto width-sm' &> +
+ +- ++ + +
+ +@@ -96,7 +96,7 @@ + +
+ +- ++ + +
+ +diff --git a/share/html/Admin/Queues/DefaultValues.html b/share/html/Admin/Queues/DefaultValues.html +index a0128693..4d9380af 100644 +--- a/share/html/Admin/Queues/DefaultValues.html ++++ b/share/html/Admin/Queues/DefaultValues.html +@@ -150,6 +150,9 @@ + my $queue = RT::Queue->new( $session{CurrentUser} ); + $queue->Load($id) || Abort( loc( "Couldn't load object [_1]", $id ) ); + ++Abort( loc("Permission Denied"), Code => HTTP::Status::HTTP_FORBIDDEN ) ++ unless $queue->CurrentUserHasRight('AdminQueue'); ++ + my $title = loc( 'Default Values for queue [_1]', $queue->Name ); + my @groupings = (RT::CustomField->CustomGroupings('RT::Ticket', $queue->Name), ''); + +diff --git a/share/html/Admin/Queues/Modify.html b/share/html/Admin/Queues/Modify.html +index fbf556f5..de15ad40 100644 +--- a/share/html/Admin/Queues/Modify.html ++++ b/share/html/Admin/Queues/Modify.html +@@ -185,9 +185,9 @@ +
+
+ % if ( $Create ) { +- <& /Elements/Submit, Label => loc('Create') &> ++ <& /Elements/Submit, Label => loc('Create'), Name => 'Submit' &> + % } else { +- <& /Elements/Submit, Label => loc('Save Changes') &> ++ <& /Elements/Submit, Label => loc('Save Changes'), Name => 'Submit' &> + % } +
+
+@@ -234,7 +234,7 @@ unless ($status) { + $EnabledChecked = 'checked="checked"'; + + unless ($Create) { +- if ( defined $id && $id eq 'new' && not $skip_update ) { ++ if ( defined $id && $id eq 'new' && !$skip_update && $ARGS{Submit} ) { + my ($val, $msg) = $QueueObj->Create( Name => $Name ); + if (!$val) { + $Create = 1; # Create failed, so bring us back to step 1 +@@ -271,7 +271,7 @@ if ( $QueueObj->Id && not $skip_update ) { + AttributesRef => \@attribs, + Object => $QueueObj, + ARGSRef => \%ARGS +- ); ++ ) if $ARGS{Submit}; + + $Disabled = $ARGS{'Disabled'} = $Enabled? 0: 1; + +@@ -285,7 +285,7 @@ if ( $QueueObj->Id && not $skip_update ) { + CallbackName => 'ProcessLinks' + ); + push @results, @linkresults; +- push @results, ProcessObjectCustomFieldUpdates( ARGSRef => \%ARGS, Object => $QueueObj ); ++ push @results, ProcessObjectCustomFieldUpdates( ARGSRef => \%ARGS, Object => $QueueObj ) if $ARGS{Submit}; + if ( RT->Config->Get('RTAddressRegexp') ) { + foreach my $address ( $QueueObj->CorrespondAddress, $QueueObj->CommentAddress ) { + next unless defined $address && length $address; +diff --git a/share/html/Admin/Queues/Scrips.html b/share/html/Admin/Queues/Scrips.html +index fe098f6b..09baf779 100644 +--- a/share/html/Admin/Queues/Scrips.html ++++ b/share/html/Admin/Queues/Scrips.html +@@ -53,6 +53,11 @@ my $QueueObj = RT::Queue->new($session{'CurrentUser'}); + $QueueObj->Load($id); + Abort(loc("Queue [_1] not found",$id)) unless $QueueObj->id; + ++if ( $ARGS{MoveScripUp} || $ARGS{MoveScripDown} ) { ++ Abort( loc("Permission Denied"), Code => HTTP::Status::HTTP_FORBIDDEN ) ++ unless $QueueObj->CurrentUserHasRight('ModifyScrips'); ++} ++ + my $title = loc("Modify scrips for queue [_1]", $QueueObj->Name); + + +diff --git a/share/html/Admin/Scrips/Objects.html b/share/html/Admin/Scrips/Objects.html +index 5622075b..7de16ea3 100644 +--- a/share/html/Admin/Scrips/Objects.html ++++ b/share/html/Admin/Scrips/Objects.html +@@ -163,8 +163,13 @@ if ( $Update ) { + } + } + if ($global and $global->Stage ne $Stage) { +- my ($status, $msg) = $global->SetStage($Stage); +- push @results, $msg; ++ if ( $session{'CurrentUser'}->HasRight( Object => RT->System, Right => 'ModifyScrips' ) ) { ++ my ($status, $msg) = $global->SetStage($Stage); ++ push @results, $msg; ++ } ++ else { ++ push @results, loc('Permission Denied'); ++ } + } + MaybeRedirectForResults( + Actions => \@results, +diff --git a/share/html/Articles/Article/Edit.html b/share/html/Articles/Article/Edit.html +index 1b8e477c..44270192 100644 +--- a/share/html/Articles/Article/Edit.html ++++ b/share/html/Articles/Article/Edit.html +@@ -89,7 +89,7 @@ + +
+
+- <& /Elements/Submit, Label => ($id eq 'new' ? loc('Create') : loc('Save Changes')), color => "#993333" &> ++ <& /Elements/Submit, Label => ($id eq 'new' ? loc('Create') : loc('Save Changes')), color => "#993333", Name => 'Submit' &> +
+
+ +@@ -166,7 +166,7 @@ elsif ( $id eq 'new' ) { + } + + my %cfs; +- if ($sortorder_ok) { ++ if ( $sortorder_ok && $ARGS{Submit} ) { + %cfs = ProcessObjectCustomFieldUpdatesForCreate( + ARGSRef => \%ARGS, + ContextObject => $ClassObj, +@@ -214,79 +214,81 @@ else { + Why => loc("Unable to load article") ); + } + +- my @attribs = qw(Name Summary Class Disabled SortOrder); ++ if ( $ARGS{Submit} ) { ++ my @attribs = qw(Name Summary Class Disabled SortOrder); + +- if ($sortorder_ok) { +- @results = UpdateRecordObject( +- AttributesRef => \@attribs, +- Object => $ArticleObj, +- ARGSRef => \%ARGS +- ); +- } ++ if ($sortorder_ok) { ++ @results = UpdateRecordObject( ++ AttributesRef => \@attribs, ++ Object => $ArticleObj, ++ ARGSRef => \%ARGS ++ ); ++ } + +- my @cf_results = ProcessObjectCustomFieldUpdates( +- Object => $ArticleObj, +- ARGSRef => \%ARGS +- ); +- @results = ( @results, @cf_results ); +- +- # Delete links that are gone gone gone. +- foreach my $arg ( keys %ARGS ) { +- if ( $arg =~ /DeleteLink-(.*?)-(RefersTo|MemberOf|RefersTo)-(.*)$/ ) { +- my $base = $1; +- my $type = $2; +- my $target = $3; +- +- my ( $val, $msg ) = $ArticleObj->DeleteLink( +- Base => $base, +- Type => $type, +- Target => $target +- ); ++ my @cf_results = ProcessObjectCustomFieldUpdates( ++ Object => $ArticleObj, ++ ARGSRef => \%ARGS ++ ); ++ @results = ( @results, @cf_results ); + +- push @results, $msg; ++ # Delete links that are gone gone gone. ++ foreach my $arg ( keys %ARGS ) { ++ if ( $arg =~ /DeleteLink-(.*?)-(RefersTo|MemberOf|RefersTo)-(.*)$/ ) { ++ my $base = $1; ++ my $type = $2; ++ my $target = $3; + +- } ++ my ( $val, $msg ) = $ArticleObj->DeleteLink( ++ Base => $base, ++ Type => $type, ++ Target => $target ++ ); + +- } +- +- my @linktypes = qw(DependsOn MemberOf RefersTo ); ++ push @results, $msg; + +- foreach my $linktype (@linktypes) { ++ } + +- for my $luri ( split( / /, ( $ARGS{ $ArticleObj->Id . "-$linktype" } || '' )) ) { +- $luri =~ s/\s*$//; # Strip trailing whitespace +- my ( $val, $msg ) = +- $ArticleObj->AddLink( Target => $luri, Type => $linktype ); +- push @results, $msg; +- delete $ARGS{ $ArticleObj->Id . "-$linktype" } if $val; + } + +- for my $luri ( split( / /, ( $ARGS{ "$linktype-" . $ArticleObj->Id } || '' )) ) { +- my ( $val, $msg ) = +- $ArticleObj->AddLink( Base => $luri, Type => $linktype ); +- push @results, $msg; +- delete $ARGS{ "$linktype-" . $ArticleObj->Id } if $val; +- } ++ my @linktypes = qw(DependsOn MemberOf RefersTo ); + +- } ++ foreach my $linktype (@linktypes) { + +- my %topics; +- if ( $ARGS{'EditTopics'} ) { +- $topics{$_}++ for @{ $ARGS{'Topics'} }; +- my $objTopics = +- RT::ObjectTopics->new( $session{'CurrentUser'} ); +- $objTopics->LimitToObject($ArticleObj); +- while ( my $t = $objTopics->Next ) { +- $topics{ $t->Topic }--; +- } +- for my $id ( keys %topics ) { +- if ( $topics{$id} > 0 ) { +- my ( $val, $msg ) = $ArticleObj->AddTopic( Topic => $id ); ++ for my $luri ( split( / /, ( $ARGS{ $ArticleObj->Id . "-$linktype" } || '' )) ) { ++ $luri =~ s/\s*$//; # Strip trailing whitespace ++ my ( $val, $msg ) = ++ $ArticleObj->AddLink( Target => $luri, Type => $linktype ); + push @results, $msg; ++ delete $ARGS{ $ArticleObj->Id . "-$linktype" } if $val; + } +- elsif ( $topics{$id} < 0 ) { +- my ( $val, $msg ) = $ArticleObj->DeleteTopic( Topic => $id ); ++ ++ for my $luri ( split( / /, ( $ARGS{ "$linktype-" . $ArticleObj->Id } || '' )) ) { ++ my ( $val, $msg ) = ++ $ArticleObj->AddLink( Base => $luri, Type => $linktype ); + push @results, $msg; ++ delete $ARGS{ "$linktype-" . $ArticleObj->Id } if $val; ++ } ++ ++ } ++ ++ my %topics; ++ if ( $ARGS{'EditTopics'} ) { ++ $topics{$_}++ for @{ $ARGS{'Topics'} }; ++ my $objTopics = ++ RT::ObjectTopics->new( $session{'CurrentUser'} ); ++ $objTopics->LimitToObject($ArticleObj); ++ while ( my $t = $objTopics->Next ) { ++ $topics{ $t->Topic }--; ++ } ++ for my $id ( keys %topics ) { ++ if ( $topics{$id} > 0 ) { ++ my ( $val, $msg ) = $ArticleObj->AddTopic( Topic => $id ); ++ push @results, $msg; ++ } ++ elsif ( $topics{$id} < 0 ) { ++ my ( $val, $msg ) = $ArticleObj->DeleteTopic( Topic => $id ); ++ push @results, $msg; ++ } + } + } + } +diff --git a/share/html/Articles/Elements/BeforeMessageBox b/share/html/Articles/Elements/BeforeMessageBox +index 96472da8..57f66919 100644 +--- a/share/html/Articles/Elements/BeforeMessageBox ++++ b/share/html/Articles/Elements/BeforeMessageBox +@@ -65,8 +65,7 @@ + + +diff --git a/share/html/Dashboards/Subscription.html b/share/html/Dashboards/Subscription.html +index 1021c7c5..649d6deb 100644 +--- a/share/html/Dashboards/Subscription.html ++++ b/share/html/Dashboards/Subscription.html +@@ -284,8 +284,10 @@ + + +diff --git a/share/html/Download/CustomFieldValue/dhandler b/share/html/Download/CustomFieldValue/dhandler +index 743229c2..c42cf93f 100644 +--- a/share/html/Download/CustomFieldValue/dhandler ++++ b/share/html/Download/CustomFieldValue/dhandler +@@ -46,6 +46,8 @@ + %# + %# END BPS TAGGED BLOCK }}} + <%perl> ++use RT::Util 'CanonicalizeContentType'; ++ + my $id; + my $arg = $m->dhandler_arg; # get rest of path + if ($arg =~ /^(\d+)\//) { +@@ -63,8 +65,8 @@ unless ($OCFV->id) { + + Abort( loc('Permission Denied'), Code => HTTP::Status::HTTP_FORBIDDEN ) unless $OCFV->CurrentUserCanSee; + +-my $content_type = $OCFV->ContentType || 'text/plain; charset=utf-8'; +- ++my $content_type = CanonicalizeContentType( $OCFV->ContentType ) || 'text/plain; charset=utf-8'; ++ + if (RT->Config->Get('AlwaysDownloadAttachments') || $content_type =~ m{^(image/svg\+xml|application/pdf)}i) { + $r->headers_out->{'Content-Disposition'} = "attachment"; + } +diff --git a/share/html/Elements/CollectionAsTable/Header b/share/html/Elements/CollectionAsTable/Header +index 04f4732f..6c5eb615 100644 +--- a/share/html/Elements/CollectionAsTable/Header ++++ b/share/html/Elements/CollectionAsTable/Header +@@ -144,7 +144,7 @@ foreach my $col ( @Format ) { + ); + ProcessColumnMapValue( $tmp_columnmap, Arguments => [ $attr ] ); + }; +- $m->out(qq{ style="text-align: $align"}) if $align; ++ $m->out( ' style="text-align: ' . $m->interp->apply_escapes( $align => 'h' ) . '"' ) if $align; + $m->out('>'); + + my $loc_title; +diff --git a/share/html/Elements/DoAuth b/share/html/Elements/DoAuth +index f05ae25f..e01890ed 100644 +--- a/share/html/Elements/DoAuth ++++ b/share/html/Elements/DoAuth +@@ -49,6 +49,10 @@ + # return as quickly as possible if the user is logged in + return if $session{CurrentUser} && $session{'CurrentUser'}->id; + ++return if defined $user and defined $pass ++ and RT->Config->Get('RestrictLoginReferrer') ++ and not RT::Interface::Web::IsLoginPageReferer(); ++ + # It's important to nab the next page from the session before we + # potentially blow the session away below. + my $next = $session{'NextPage'}->{ $ARGS{'next'} || "" }; +diff --git a/share/html/Elements/Lifecycle/Graph b/share/html/Elements/Lifecycle/Graph +index b2a2c37f..4a75a8ff 100644 +--- a/share/html/Elements/Lifecycle/Graph ++++ b/share/html/Elements/Lifecycle/Graph +@@ -45,7 +45,7 @@ + %# those contributions and any derivatives thereof. + %# + %# END BPS TAGGED BLOCK }}} +-
++
+
+ + +@@ -76,7 +76,12 @@ + + +
+diff --git a/share/html/Elements/MakeClicky b/share/html/Elements/MakeClicky +index df8a86f5..48a3aff4 100644 +--- a/share/html/Elements/MakeClicky ++++ b/share/html/Elements/MakeClicky +@@ -47,6 +47,7 @@ + %# END BPS TAGGED BLOCK }}} + <%ONCE> + use Regexp::Common qw(URI); ++use HTML::Entities (); + + my $escaper = sub { + my $content = shift; +@@ -63,7 +64,8 @@ my %actions = ( + my %args = @_; + my $post = ""; + $post = ")" if $args{value} !~ /\(/ and $args{value} =~ s/\)$//; +- $args{value} = $escaper->($args{value}) unless $args{html}; ++ $args{value} = HTML::Entities::decode_entities($args{value}) if $args{html}; ++ $args{value} = $escaper->($args{value}); + my $result = qq{[}. loc('Open URL') .qq{]}; + return $args{value} . qq{ $result$post}; + }, +@@ -71,7 +73,8 @@ my %actions = ( + my %args = @_; + my $post = ""; + $post = ")" if $args{value} !~ /\(/ and $args{value} =~ s/\)$//; +- $args{value} = $escaper->($args{value}) unless $args{html}; ++ $args{value} = HTML::Entities::decode_entities($args{value}) if $args{html}; ++ $args{value} = $escaper->($args{value}); + my $result = qq{$args{value}}; + return qq{$result$post}; + }, +diff --git a/share/html/Elements/SelectCustomFieldValue b/share/html/Elements/SelectCustomFieldValue +index 49c9034c..b46e2139 100644 +--- a/share/html/Elements/SelectCustomFieldValue ++++ b/share/html/Elements/SelectCustomFieldValue +@@ -69,7 +69,7 @@ + % label => $value->Description ? $value->Name . ' (' . $value->Description . ')' : $value->Name, + % }; + % } +-jQuery('#'+'CF-' + <% $CustomField->id %>).autocomplete({ source: <% JSON::to_json(\@options) |n %> }); ++jQuery('#'+'CF-' + <% $CustomField->id %>).autocomplete({ source: <% JSON(\@options) |n %> }); + + % } else { + +diff --git a/share/html/Elements/SelectOwnerDropdown b/share/html/Elements/SelectOwnerDropdown +index 7e85b690..31b1eb72 100644 +--- a/share/html/Elements/SelectOwnerDropdown ++++ b/share/html/Elements/SelectOwnerDropdown +@@ -47,7 +47,7 @@ + %# END BPS TAGGED BLOCK }}} + + % if ($DefaultValue) { +- ++ + % } + % for my $sla ( sort keys %{RT->Config->Get('ServiceAgreements')->{'Levels'}} ) { + +diff --git a/share/html/Elements/ShowCustomFieldWikitext b/share/html/Elements/ShowCustomFieldWikitext +index fd0bfe56..ec085628 100644 +--- a/share/html/Elements/ShowCustomFieldWikitext ++++ b/share/html/Elements/ShowCustomFieldWikitext +@@ -48,7 +48,6 @@ + <%$wiki_content|n%> + <%init> + my $content = $Object->LargeContent || $Object->Content; +-$content = $m->comp('/Elements/ScrubHTML', Content => $content, Permissive => $Object->_ContentIsPermissive); + my $base = $Object->Object->WikiBase; + my %wiki_args = ( + extended => 1, +@@ -60,6 +59,8 @@ $m->callback( CallbackName => 'WikiFormatArgs', ARGSRef => \%ARGS, WikiArgsRef = + + use Text::WikiFormat; + my $wiki_content = Text::WikiFormat::format( $content."\n" , {}, { %wiki_args } ); ++$wiki_content = $m->comp('/Elements/ScrubHTML', Content => $wiki_content, ++ Permissive => $Object->_ContentIsPermissive); + + <%ARGS> + $Object +diff --git a/share/html/Elements/ShowCustomFields b/share/html/Elements/ShowCustomFields +index c9806fe5..e85620da 100644 +--- a/share/html/Elements/ShowCustomFields ++++ b/share/html/Elements/ShowCustomFields +@@ -151,15 +151,16 @@ my $print_value = sub { + + # This section automatically populates a div with the "IncludeContentForValue" for this custom + # field if it's been defined +- if ( $cf->IncludeContentForValue ) { ++ my $include = $value->IncludeContentForValue; ++ if ( defined $include && length $include ) { + my $vid = $value->id; + $m->out( '\n} ); + $m->out( qq{\n} ); + } + }; +diff --git a/share/html/Elements/ShowPrincipal b/share/html/Elements/ShowPrincipal +index 5a4a35fa..71824374 100644 +--- a/share/html/Elements/ShowPrincipal ++++ b/share/html/Elements/ShowPrincipal +@@ -62,7 +62,8 @@ if ($Object->isa("RT::Group")) { + + # Link to the group summary page + my $href = RT->Config->Get("WebPath") . "/Group/Summary.html?id="; +- push @ret, sort map { "id . "\">" . loc("Group:") . " " . $_->Name . "" } ++ push @ret, sort map { "id . "\">" . loc("Group:") . " " ++ . $m->interp->apply_escapes( $_->Name, 'h' ) . "" } + @{ $Object->GroupMembersObj( Recursively => 0)->ItemsArrayRef }; + + $m->out( join($Separator, @ret) ); +diff --git a/share/html/Elements/ShowTransaction b/share/html/Elements/ShowTransaction +index e604ae3d..7a97132a 100644 +--- a/share/html/Elements/ShowTransaction ++++ b/share/html/Elements/ShowTransaction +@@ -169,6 +169,23 @@ $EmailRecordPath => undef + + + <%INIT> ++my %link_paths = ( ++ AttachmentPath => \$AttachmentPath, ++ DisplayPath => \$DisplayPath, ++ EmailRecordPath => \$EmailRecordPath, ++ EncryptionPath => \$EncryptionPath, ++ ForwardPath => \$ForwardPath, ++ UpdatePath => \$UpdatePath, ++); ++ ++for my $name ( sort keys %link_paths ) { ++ my $path = $link_paths{$name}; ++ next if RT::Interface::Web->LinkPathIsSafe($$path); ++ RT->Logger->warning("Ignoring $name that is not an internal path: $$path"); ++ undef $$path; ++ delete $ARGS{$name}; ++} ++ + my $record_type = $Object->RecordType; + my $type_class = $Object->ClassifyTransaction( $Transaction ); + +diff --git a/share/html/Elements/ShowTransactionAttachments b/share/html/Elements/ShowTransactionAttachments +index 03f0d01d..190b38b8 100644 +--- a/share/html/Elements/ShowTransactionAttachments ++++ b/share/html/Elements/ShowTransactionAttachments +@@ -133,6 +133,9 @@ $WarnUnsigned => 0 + $displayed_inline => {} + + <%INIT> ++$AttachmentPath //= RT->Config->Get('WebPath') ++ . ( $HTML::Mason::Commands::r->path_info =~ m{^/SelfService/} ? '/SelfService/Attachment' : '/Ticket/Attachment' ); ++ + my @DisplayHeaders=qw(_all); + if ( $Transaction->Type =~ /EmailRecord$/ ) { + @DisplayHeaders = qw(To Cc Bcc); +@@ -167,18 +170,20 @@ my $render_attachment = sub { + + # provide a clear download link for meeting invitations + if ( $content_type eq 'text/calendar' ) { ++ my $escape = sub { $m->interp->apply_escapes( $_[0], 'h' ) }; ++ + # A named attachment will already have a download button + $m->out(''); + } +@@ -346,10 +351,11 @@ my $render_attachment = sub { + + my $url = RT->System->ExternalStorageURLFor($message) + || $AttachmentPath .'/'. $Transaction->Id .'/'. $message->Id .'/' +- . $m->interp->apply_escapes( $filename, 'u', 'h' ); ++ . $m->interp->apply_escapes( $filename, 'u' ); ++ my $eurl = $m->interp->apply_escapes( $url, 'h' ); + + $m->out( +- qq{$efilename} ++ qq{$efilename} + ); + } + elsif ( $message->ContentLength && $message->ContentLength > 0 ) { +diff --git a/share/html/Helpers/PreviewScrips b/share/html/Helpers/PreviewScrips +index 177c2ef7..ccad5d27 100644 +--- a/share/html/Helpers/PreviewScrips ++++ b/share/html/Helpers/PreviewScrips +@@ -51,6 +51,12 @@ $TicketObj->Load($ARGS{id}); + $m->abort unless $TicketObj->id && $ARGS{UpdateType}; + + $m->abort unless $TicketObj->CurrentUserHasRight('ShowOutgoingEmail'); ++ ++# Recipients are computed from scrips prepared as RT_System, so they are not ++# filtered by the requesting user's visibility. Render them only to a user who ++# is allowed to see the ticket. ++$m->abort unless $TicketObj->CurrentUserHasRight('ShowTicket'); ++ + if ( $ARGS{UpdateType} eq 'private' ) { + $m->abort + unless $TicketObj->CurrentUserHasRight( 'CommentOnTicket' ) || $TicketObj->CurrentUserHasRight( 'ModifyTicket' ); +diff --git a/share/html/Helpers/ShowSimplifiedRecipients b/share/html/Helpers/ShowSimplifiedRecipients +index e5374718..4abbe835 100644 +--- a/share/html/Helpers/ShowSimplifiedRecipients ++++ b/share/html/Helpers/ShowSimplifiedRecipients +@@ -52,6 +52,11 @@ my $TicketObj = RT::Ticket->new($session{CurrentUser}); + $TicketObj->Load($ARGS{id}); + $m->abort unless $TicketObj->id && $ARGS{UpdateType}; + ++# Recipients are computed from scrips prepared as RT_System, so they are not ++# filtered by the requesting user's visibility. Render them only to a user who ++# is allowed to see the ticket. ++$m->abort unless $TicketObj->CurrentUserHasRight('ShowTicket'); ++ + if ( $ARGS{UpdateType} eq 'private' ) { + $m->abort + unless $TicketObj->CurrentUserHasRight( 'CommentOnTicket' ) || $TicketObj->CurrentUserHasRight( 'ModifyTicket' ); +diff --git a/share/html/NoAuth/css/dhandler b/share/html/NoAuth/css/dhandler +index 35b35902..568559f4 100644 +--- a/share/html/NoAuth/css/dhandler ++++ b/share/html/NoAuth/css/dhandler +@@ -52,6 +52,8 @@ my $squisher; + my $arg = $m->dhandler_arg; + if ( $arg =~ m{(.*)/squished-[0-9a-f]{32}\.css$} ) { + my $style = $1; ++ $m->abort(404) unless grep { $_ eq $style } RT::Interface::Web->Themes; ++ + my $squished = RT::Interface::Web::SquishedCSS( $style ); + # Don't send Last-Modified since we don't handle If-Modified-Since + #$r->header_out( 'Last-Modified' => $squished->ModifiedTimeString ); +diff --git a/share/html/NoAuth/rss/dhandler b/share/html/NoAuth/rss/dhandler +index a6058969..acbaa171 100644 +--- a/share/html/NoAuth/rss/dhandler ++++ b/share/html/NoAuth/rss/dhandler +@@ -71,6 +71,23 @@ my $user = RT::User->new(RT->SystemUser); + $user->Load($name); + $notfound->("Invalid user: $user") unless $user->id; + ++my @search_args = qw(Query Order OrderBy); ++ ++# The auth string covers Query, Order and OrderBy as one concatenation, so it ++# does not pin down where each one ends. Whatever a caller trims off the Query ++# lands at the start of the next argument, so requiring that one to look like ++# a sort argument keeps the split where it was signed. ++my %sort_format = ( ++ Order => qr{^(?:ASC|DESC)?$}i, ++ OrderBy => qr{^[\w.]*(?:\{[^{}]*\}[\w.]*)*$}, ++); ++ ++for my $arg (qw(Order OrderBy)) { ++ next unless defined $ARGS{$arg} && length $ARGS{$arg}; ++ $notfound->("Invalid $arg: $ARGS{$arg}") if grep { !/$sort_format{$arg}/ } split /\|/, $ARGS{$arg}; ++ last; ++} ++ + $notfound->("Invalid authstring") + unless $user->ValidateAuthString( $auth, + $ARGS{sc} || ( $ARGS{Query} . $ARGS{Order} . $ARGS{OrderBy} ) ); +@@ -79,21 +96,18 @@ my $cu = RT::CurrentUser->new; + $cu->Load($user); + local $session{'CurrentUser'} = $cu; + ++my %search; + if ( my $sc = $ARGS{sc} ) { + my $shortener = RT::Shortener->new( $session{CurrentUser} ); + $shortener->LoadByCode($sc); +- if ( $shortener->Id ) { +- my $content = $shortener->DecodedContent; +- for my $key ( keys %$content ) { +- if ( !exists $ARGS{$key} ) { +- $ARGS{$key} = $content->{$key}; +- } +- } +- } +- else { +- RT->Logger->warning("Couldn't load shortener $sc"); +- } ++ $notfound->("Couldn't load shortener $sc") unless $shortener->Id; ++ ++ my $content = $shortener->DecodedContent; ++ %search = map { $_ => $content->{$_} // '' } @search_args; ++} ++else { ++ %search = map { $_ => $ARGS{$_} // '' } @search_args; + } + +-$m->comp("/Search/Elements/ResultsRSSView", %ARGS); ++$m->comp("/Search/Elements/ResultsRSSView", %search); + +diff --git a/share/html/REST/1.0/Forms/group/customfields b/share/html/REST/1.0/Forms/group/customfields +index 29edbb53..b543f0bc 100644 +--- a/share/html/REST/1.0/Forms/group/customfields ++++ b/share/html/REST/1.0/Forms/group/customfields +@@ -57,9 +57,11 @@ my @comments; + my ($c, $o, $k, $e) = ("", [], {}, 0); + my $group = RT::Group->new($session{CurrentUser}); + +-$group->Load($id); ++$group->LoadUserDefinedGroup($id); + if (!$group->Id) { + return [ "# Group $id does not exist.", [], {}, 1 ]; ++} elsif ( !$group->CurrentUserHasRight('SeeGroup') ) { ++ return [ "# You are not allowed to display group $id.", [], {}, 1 ]; + } + + if (%$changes) { +diff --git a/share/html/REST/1.0/Forms/group/default b/share/html/REST/1.0/Forms/group/default +index 10702901..df9d204d 100644 +--- a/share/html/REST/1.0/Forms/group/default ++++ b/share/html/REST/1.0/Forms/group/default +@@ -67,9 +67,15 @@ if ( $fields && %$fields ) { + my %fields = map { lc $_ => $_ } @fields; + + if ($id ne 'new') { +- $group->Load($id); ++ $group->LoadUserDefinedGroup($id); + if (!$group->Id) { + return [ "# Group $id does not exist.", [], {}, 1 ]; ++ } elsif (%data) { ++ if ( !$group->CurrentUserHasRight('AdminGroup') ) { ++ return [ "# You are not allowed to modify group $id.", [], {}, 1 ]; ++ } ++ } elsif ( !$group->CurrentUserHasRight('SeeGroup') ) { ++ return [ "# You are not allowed to display group $id.", [], {}, 1 ]; + } + } + else { +diff --git a/share/html/REST/1.0/Forms/group/ns b/share/html/REST/1.0/Forms/group/ns +index 61266c4b..def27639 100644 +--- a/share/html/REST/1.0/Forms/group/ns ++++ b/share/html/REST/1.0/Forms/group/ns +@@ -54,9 +54,11 @@ $id + use RT::Groups; + + my $groups = RT::Groups->new($session{CurrentUser}); ++$groups->LimitToUserDefinedGroups; + $groups->Limit(FIELD => 'Name', OPERATOR => '=', VALUE => $id, CASESENSITIVE => 0); +-if ($groups->Count == 0) { ++my $group = $groups->Next; ++if ( !$group ) { + return (0, "No group named $id exists."); + } +-return $groups->Next->Id; ++return $group->Id; + +diff --git a/share/html/REST/1.0/Forms/queue/ns b/share/html/REST/1.0/Forms/queue/ns +index bae9d3b1..97fd4d1c 100644 +--- a/share/html/REST/1.0/Forms/queue/ns ++++ b/share/html/REST/1.0/Forms/queue/ns +@@ -55,8 +55,9 @@ use RT::Queues; + + my $queues = RT::Queues->new($session{CurrentUser}); + $queues->Limit(FIELD => 'Name', OPERATOR => '=', VALUE => $id, CASESENSITIVE => 0 ); +-if ($queues->Count == 0) { ++my $queue = $queues->Next; ++if ( !$queue ) { + return (0, "No queue named $id exists."); + } +-return $queues->Next->Id; ++return $queue->Id; + +diff --git a/share/html/REST/1.0/search/dhandler b/share/html/REST/1.0/search/dhandler +index 27230436..0e042f7e 100644 +--- a/share/html/REST/1.0/search/dhandler ++++ b/share/html/REST/1.0/search/dhandler +@@ -284,6 +284,7 @@ my %search_whitelist = ( + group => { + disabled => 1, + map { lc $_ => 1 } ++ grep { !/^(?:Domain|Instance)$/ } + grep { $RT::Record::_TABLE_ATTR->{'RT::Group'}{$_}{read} } + keys %{ $RT::Record::_TABLE_ATTR->{'RT::Group'} } + } +diff --git a/share/html/Search/Elements/ConditionRow b/share/html/Search/Elements/ConditionRow +index ece5b8b9..f9b54a3c 100644 +--- a/share/html/Search/Elements/ConditionRow ++++ b/share/html/Search/Elements/ConditionRow +@@ -62,10 +62,12 @@ return unless $Condition && $Condition->{'Name'}; + $m->callback( Condition => \$Condition ); + return unless $Condition; + ++my $escape = sub { return $m->interp->apply_escapes( defined $_[0] ? $_[0] : '', 'h' ) }; ++ + my $handle_block = RT::Util::RecursiveSub(sub { + my $self_cb = shift; + my $box = shift; +- return $box unless ref $box; ++ return $escape->($box) unless ref $box; + + my $name = shift; + if ( UNIVERSAL::isa($box, 'ARRAY') ) { +@@ -89,13 +91,14 @@ my $handle_block = RT::Util::RecursiveSub(sub { + } + if ( $box->{'Type'} eq 'select' ) { + my $res = ''; +- my $id = $box->{Id} // $name; +- $res .= qq{}; + my @options = @{ $box->{'Options'} }; + while( defined( my $k = shift @options ) ) { + my $v = shift @options; + my $class = CSSClass($k); +- $res .= qq{}; ++ my ( $value, $label ) = ( $escape->($k), $escape->($v) ); ++ $res .= qq{}; + } + $res .= qq{}; + return $res; +diff --git a/share/html/Search/Elements/EditSearches b/share/html/Search/Elements/EditSearches +index d4688e08..5f64bce3 100644 +--- a/share/html/Search/Elements/EditSearches ++++ b/share/html/Search/Elements/EditSearches +@@ -334,6 +334,11 @@ elsif ( $ARGS{'SavedSearchDelete'} ) { + return @results; + } + } ++ else { ++ push @results, loc( 'Can not load saved search "[_1]"', $SavedSearch->{'Id'} ); ++ return @results; ++ } ++ + $SavedSearch->{'Id'} = 'new'; + $SavedSearch->{'Object'} = undef; + $SavedSearch->{'Description'} = undef; +@@ -341,6 +346,12 @@ elsif ( $ARGS{'SavedSearchDelete'} ) { + } + elsif ( $ARGS{'SavedSearchCopy'} ) { + my ($container, $id ) = _parse_saved_search( $ARGS{'SavedSearchId'} ); ++ ++ unless ( $container ) { ++ push @results, loc( 'Can not load saved search "[_1]"', $ARGS{'SavedSearchId'} ); ++ return @results; ++ } ++ + $SavedSearch->{'Object'} = RT::Attribute->new( $session{'CurrentUser'} ); + $SavedSearch->{'Object'}->Load( $id ); + if ( $ARGS{'SavedSearchDescription'} && $ARGS{'SavedSearchDescription'} ne $SavedSearch->{'Object'}->Description ) { +@@ -356,9 +367,12 @@ if ( $SavedSearch->{'Id'} && $SavedSearch->{'Id'} ne 'new' + && !$SavedSearch->{'Object'} ) + { + my ($container, $id ) = _parse_saved_search( $ARGS{'SavedSearchId'} ); +- $SavedSearch->{'Object'} = RT::Attribute->new( $session{'CurrentUser'} ); +- $SavedSearch->{'Object'}->Load( $id ); +- $SavedSearch->{'Description'} ||= $SavedSearch->{'Object'}->Description; ++ ++ if ( $id ) { ++ $SavedSearch->{'Object'} = RT::Attribute->new( $session{'CurrentUser'} ); ++ $SavedSearch->{'Object'}->Load( $id ); ++ $SavedSearch->{'Description'} ||= $SavedSearch->{'Object'}->Description; ++ } + } + + return @results; +@@ -410,7 +424,12 @@ if ( $obj && $obj->id ) { + # or it will fail the 2nd change if we use SetObjectType and + # SetObjectId sequentially + +- if ( $obj->CurrentUserHasRight('update') ) { ++ # __Set skips the ACL as well, so the destination has to be authorized ++ # here: landing the search there takes the rights to have saved it there ++ my $can_move = ( $new_obj_type eq $obj_type && $new_obj_id == $obj_id ) ++ || RT::SavedSearch->new( $session{'CurrentUser'} )->CurrentUserCanCreate("$new_obj_type-$new_obj_id"); ++ ++ if ( $can_move && $obj->CurrentUserHasRight('update') ) { + if ( $new_obj_type ne $obj_type ) { + ( $val, $msg ) = $obj->__Set( + Field => 'ObjectType', +@@ -429,6 +448,9 @@ if ( $obj && $obj->id ) { + } + # Reload to refresh $obj->Object + $obj->Load( $obj->Id ); ++ ++ my ( $type, $oid ) = ( $obj->__Value('ObjectType'), $obj->__Value('ObjectId') ); ++ $SavedSearch->{'Id'} = join '-', $type, $oid, 'SavedSearch', $obj->Id; + } + else { + # two loc are just for convenience so we don't need to +@@ -455,11 +477,7 @@ elsif ( $id eq 'new' and defined $desc and length $desc ) { + $SavedSearch->{'Object'} = RT::Attribute->new( $session{'CurrentUser'} ); + $SavedSearch->{'Object'}->Load( $saved_search->Id ); + # Build new SearchId +- $SavedSearch->{'Id'} = +- ref( $session{'CurrentUser'}->UserObj ) . '-' +- . $session{'CurrentUser'}->UserObj->Id +- . '-SavedSearch-' +- . $SavedSearch->{'Object'}->Id; ++ $SavedSearch->{'Id'} = join '-', $saved_search->Privacy, 'SavedSearch', $saved_search->Id; + } + else { + push @results, loc("Can't find a saved search to work with").': '.loc($msg); +@@ -482,16 +500,21 @@ return @results; + % my $links = $Object->DependedOnBy; + % $links->RowsPerPage(50); + % my $total = $links->CountAll; ++% my $dashboard = RT::Dashboard->new( $session{CurrentUser} ); +

+ <&|/l, $total &>This search is used in the following [quant,_1,dashboard,dashboards]: +

+
    + % while ( my $link = $links->Next ) { ++% my $resolver = $link->BaseURI->Resolver; ++% my $base = $resolver->Object; ++% next unless $base && $base->isa('RT::Attribute') && $base->Name eq 'Dashboard'; ++% my $privacy = $dashboard->_build_privacy( $base->ObjectType, $base->ObjectId ); +
  • +-% if ( $link->BaseObj->Name eq 'Dashboard' ) { +- <% $link->BaseURI->AsString %> ++% if ( $dashboard->CurrentUserCanSee($privacy) ) { ++ <% $resolver->AsString %> + % } else { +- <% $link->BaseObj->ObjectType %>: #<% $link->BaseObj->ObjectId %> ++ <% loc( 'Dashboard #[_1]', $base->id ) %> + % } +
  • + % } +diff --git a/share/html/Search/Results.html b/share/html/Search/Results.html +index 746af51b..9a414a79 100644 +--- a/share/html/Search/Results.html ++++ b/share/html/Search/Results.html +@@ -255,10 +255,13 @@ my $refresh = $session{$interval_name} || RT->Config->Get('SearchResultsRefreshI + + # Check $m->request_args, not $DECODED_ARGS, to avoid creating a new CSRF token on each refresh + if (RT->Config->Get('RestrictReferrer') and $refresh and not $m->request_args->{CSRF_Token}) { ++ # Auto-refresh needs a token to get back past the referrer check. If one ++ # cannot be minted the results still render; only the refresh is dropped. + my $token = RT::Interface::Web::StoreRequestToken( $session{$hash_name} ); + $m->notes->{RefreshURL} = RT->Config->Get('WebURL') + . "Search/Results.html?CSRF_Token=" +- . $token; ++ . $token ++ if defined $token; + } + + my %link_rel; +diff --git a/share/html/Ticket/Attachment/dhandler b/share/html/Ticket/Attachment/dhandler +index 14432f17..22d39a4c 100644 +--- a/share/html/Ticket/Attachment/dhandler ++++ b/share/html/Ticket/Attachment/dhandler +@@ -46,6 +46,8 @@ + %# + %# END BPS TAGGED BLOCK }}} + <%perl> ++use RT::Util 'CanonicalizeContentType'; ++ + my ( $ticket, $trans, $attach, $filename ); + my $arg = $m->dhandler_arg; # get rest of path + if ( $arg =~ m{^(\d+)/(\d+)} ) { +@@ -66,7 +68,7 @@ unless ( $AttachmentObj->TransactionId() == $trans ) { + } + + my $content = $AttachmentObj->OriginalContent; +-my $content_type = $AttachmentObj->ContentType || 'text/plain'; ++my $content_type = CanonicalizeContentType( $AttachmentObj->ContentType ) || 'text/plain'; + + my $attachment_regex = qr{^(image/svg\+xml|application/pdf)}i; + if ( RT->Config->Get('AlwaysDownloadAttachments') || ($content_type =~ $attachment_regex) ) { +diff --git a/share/html/Ticket/Display.html b/share/html/Ticket/Display.html +index 888b59e1..0a5fb5b0 100644 +--- a/share/html/Ticket/Display.html ++++ b/share/html/Ticket/Display.html +@@ -208,11 +208,11 @@ if ($ARGS{'id'} eq 'new') { + }); + if ( !$SkipProcessing ) { + unless ($TicketObj->CurrentUserHasRight('ShowTicket')) { +- if (@Actions) { +- Abort("A change was applied successfully, but you no longer have permissions to view the ticket", Actions => \@Actions, Code => HTTP::Status::HTTP_FORBIDDEN); +- } else { +- Abort("No permission to view ticket", Code => HTTP::Status::HTTP_FORBIDDEN); +- } ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@Actions, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); + } + if ( $ARGS{'MarkAsSeen'} ) { + $TicketObj->SetAttribute( +diff --git a/share/html/Ticket/Forward.html b/share/html/Ticket/Forward.html +index 9fd421ad..bf35520f 100644 +--- a/share/html/Ticket/Forward.html ++++ b/share/html/Ticket/Forward.html +@@ -134,7 +134,7 @@ $m->comp( '/Elements/Crypt/SignEncryptWidget:Process', + ); + + Abort( loc("Permission Denied") ) +- unless $TicketObj->CurrentUserHasRight('ForwardMessage'); ++ unless $TicketObj->CurrentUserCanSee && $TicketObj->CurrentUserHasRight('ForwardMessage'); + + my $txn; + if ( $QuoteTransaction ) { +@@ -142,6 +142,10 @@ if ( $QuoteTransaction ) { + $txn->Load( $QuoteTransaction ); + Abort( loc("Couldn't load transaction #[_1]", $QuoteTransaction) ) + unless $txn->id; ++ Abort( loc("Permission Denied") ) ++ unless $txn->CurrentUserCanSee ++ && $txn->ObjectType eq 'RT::Ticket' ++ && $txn->Object->id == $TicketObj->id; + } + + if ( $Forward || $ForwardAndReturn ) { +diff --git a/share/html/Ticket/Graphs/index.html b/share/html/Ticket/Graphs/index.html +index e16d23e9..a4a84549 100644 +--- a/share/html/Ticket/Graphs/index.html ++++ b/share/html/Ticket/Graphs/index.html +@@ -99,6 +99,8 @@ push @results, $m->comp( '/Search/Elements/EditSearches:Init', + Type => 'Graph', + ); + ++$ARGS{'Direction'} = 'TB' ++ unless defined $ARGS{'Direction'} && $RT::Graph::Tickets::RANKDIR_VALUES{ $ARGS{'Direction'} }; + $ARGS{'LeadingLink'} ||= 'Members'; + if ( $ARGS{'ShowLinks'} && !ref $ARGS{'ShowLinks'} ) { + $ARGS{'ShowLinks'} = [$ARGS{'ShowLinks'}]; +diff --git a/share/html/Ticket/History.html b/share/html/Ticket/History.html +index 1825b321..d33d0749 100644 +--- a/share/html/Ticket/History.html ++++ b/share/html/Ticket/History.html +@@ -70,7 +70,10 @@ $id => undef + my $Ticket = LoadTicket ($id); + + unless ($Ticket->CurrentUserHasRight('ShowTicket')) { +- Abort("No permission to view ticket"); ++ Abort( ++ loc("No permission to view ticket"), ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); + } + + $Ticket->CurrentUser->AddRecentlyViewedTicket($Ticket); +diff --git a/share/html/Ticket/Modify.html b/share/html/Ticket/Modify.html +index a46f513b..04070858 100644 +--- a/share/html/Ticket/Modify.html ++++ b/share/html/Ticket/Modify.html +@@ -120,11 +120,11 @@ unless ($skip_update) { + } + + unless ($TicketObj->CurrentUserHasRight('ShowTicket')) { +- if (@results) { +- Abort("A change was applied successfully, but you no longer have permissions to view the ticket", Actions => \@results); +- } else { +- Abort("No permission to view ticket"); +- } ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@results, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); + } + + $TicketObj->CurrentUser->AddRecentlyViewedTicket($TicketObj); +diff --git a/share/html/Ticket/ModifyAll.html b/share/html/Ticket/ModifyAll.html +index 3887c950..1d8aac95 100644 +--- a/share/html/Ticket/ModifyAll.html ++++ b/share/html/Ticket/ModifyAll.html +@@ -212,11 +212,11 @@ unless ($skip_update or $OnlySearchForPeople or $OnlySearchForGroup or $ARGS{'Ad + + # If they've gone and moved the ticket to somewhere they can't see, etc... + unless ($Ticket->CurrentUserHasRight('ShowTicket')) { +- if (@results) { +- Abort("A change was applied successfully, but you no longer have permissions to view the ticket", Actions => \@results); +- } else { +- Abort("No permission to view ticket"); +- } ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@results, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); + } + + $Ticket->CurrentUser->AddRecentlyViewedTicket($Ticket); +diff --git a/share/html/Ticket/ModifyDates.html b/share/html/Ticket/ModifyDates.html +index 33b0509e..03ba46ca 100644 +--- a/share/html/Ticket/ModifyDates.html ++++ b/share/html/Ticket/ModifyDates.html +@@ -76,6 +76,14 @@ $TicketObj->Atomic(sub{ + push @results, ProcessObjectCustomFieldUpdates(Object => $TicketObj, ARGSRef => \%ARGS); + }); + ++unless ( $TicketObj->CurrentUserHasRight('ShowTicket') ) { ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@results, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); ++} ++ + $TicketObj->CurrentUser->AddRecentlyViewedTicket($TicketObj); + + +diff --git a/share/html/Ticket/ModifyLinks.html b/share/html/Ticket/ModifyLinks.html +index b52c1220..d6fde14d 100644 +--- a/share/html/Ticket/ModifyLinks.html ++++ b/share/html/Ticket/ModifyLinks.html +@@ -89,6 +89,14 @@ MaybeRedirectForResults( + Arguments => { id => $id }, + ); + ++unless ( $Ticket->CurrentUserHasRight('ShowTicket') ) { ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@results, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); ++} ++ + $Ticket->CurrentUser->AddRecentlyViewedTicket($Ticket); + + +diff --git a/share/html/Ticket/ModifyPeople.html b/share/html/Ticket/ModifyPeople.html +index bd27c67a..e76e0fd0 100644 +--- a/share/html/Ticket/ModifyPeople.html ++++ b/share/html/Ticket/ModifyPeople.html +@@ -131,6 +131,14 @@ unless ($OnlySearchForPeople or $OnlySearchForGroup) { + }); + } + ++unless ( $Ticket->CurrentUserHasRight('ShowTicket') ) { ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@results, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); ++} ++ + # Use the ticket's scrips to figure out the new list of recipients. + my $notify_actor = RT->Config->Get( 'NotifyActor', $session{CurrentUser} ); + +diff --git a/share/html/Ticket/Reminders.html b/share/html/Ticket/Reminders.html +index fdb2fc2e..b18b170e 100644 +--- a/share/html/Ticket/Reminders.html ++++ b/share/html/Ticket/Reminders.html +@@ -75,6 +75,14 @@ my @actions = $Ticket->Atomic(sub{ + ProcessTicketReminders( TicketObj => $Ticket, ARGSRef => \%ARGS ); + }); + ++unless ( $Ticket->CurrentUserHasRight('ShowTicket') ) { ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@actions, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); ++} ++ + $Ticket->CurrentUser->AddRecentlyViewedTicket($Ticket); + + +diff --git a/share/html/Ticket/Update.html b/share/html/Ticket/Update.html +index 73e72389..c26a523b 100644 +--- a/share/html/Ticket/Update.html ++++ b/share/html/Ticket/Update.html +@@ -336,6 +336,15 @@ my $checks_failure = 0; + + my $TicketObj = LoadTicket($id); + ++# The update form renders ticket data that object rights do not filter, such ++# as single value custom role members, so require ShowTicket to display it. ++unless ( $TicketObj->CurrentUserHasRight('ShowTicket') ) { ++ Abort( ++ loc("No permission to view ticket"), ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); ++} ++ + my @results; + + # no support for muliple articles included at the same time +diff --git a/share/html/Widgets/SavedSearch b/share/html/Widgets/SavedSearch +index 51f8ef22..c8e9e03c 100644 +--- a/share/html/Widgets/SavedSearch ++++ b/share/html/Widgets/SavedSearch +@@ -135,9 +135,8 @@ if ( $args->{SavedSearchSave} || $args->{SavedSearchCopy} ) { + ); + if ($ok) { + $self->{CurrentSearch}{Object} = $saved_search->{Attribute}; +- $self->{SearchId} = $args->{SavedChartSearchId} = 'RT::User-' . +- $session{CurrentUser}->id . '-SavedSearch-' . +- $saved_search->Id; ++ $self->{SearchId} = $args->{SavedChartSearchId} ++ = join '-', $saved_search->Privacy, 'SavedSearch', $saved_search->Id; + push @actions, loc( '[_1] [_2] saved.', loc($self->{SearchType}), $args->{SavedSearchDescription} ); + } else { + push @actions, +diff --git a/share/html/m/ticket/reply b/share/html/m/ticket/reply +index 38269843..ab609116 100644 +--- a/share/html/m/ticket/reply ++++ b/share/html/m/ticket/reply +@@ -156,6 +156,15 @@ my $title; + + my $t = LoadTicket($id); + ++# The update form renders ticket data that object rights do not filter, such ++# as the current owner, so require ShowTicket to display it. ++unless ( $t->CurrentUserHasRight('ShowTicket') ) { ++ Abort( ++ loc("No permission to view ticket"), ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); ++} ++ + my @results; + + $m->callback( Ticket => $t, ARGSRef => \%ARGS, results => \@results, CallbackName => 'Initial' ); +diff --git a/share/html/m/ticket/show b/share/html/m/ticket/show +index d93b7772..a0708e57 100644 +--- a/share/html/m/ticket/show ++++ b/share/html/m/ticket/show +@@ -111,11 +111,11 @@ if ($ARGS{'id'} eq 'new') { + }); + + unless ($Ticket->CurrentUserHasRight('ShowTicket')) { +- if (@Actions) { +- Abort("A change was applied successfully, but you no longer have permissions to view the ticket", Actions => \@Actions); +- } else { +- Abort("No permission to view ticket"); +- } ++ Abort( ++ loc("No permission to view ticket"), ++ Actions => \@Actions, ++ Code => HTTP::Status::HTTP_FORBIDDEN, ++ ); + } + if ( $ARGS{'MarkAsSeen'} ) { + $Ticket->SetAttribute( +@@ -188,15 +188,16 @@ my $print_value = sub { + + # This section automatically populates a div with the "IncludeContentForValue" for this custom + # field if it's been defined +- if ( $cf->IncludeContentForValue ) { ++ my $include = $value->IncludeContentForValue; ++ if ( defined $include && length $include ) { + my $vid = $value->id; + $m->out( '\n} ); + $m->out( qq{\n} ); + } + }; +diff --git a/share/static/js/bootstrap-combobox.js b/share/static/js/bootstrap-combobox.js +index 24f75dfc..b0704948 100644 +--- a/share/static/js/bootstrap-combobox.js ++++ b/share/static/js/bootstrap-combobox.js +@@ -215,11 +215,23 @@ + return beginswith.concat(caseSensitive, caseInsensitive); + } + ++ , escape: function (text) { ++ return $('
    ').text(text == null ? '' : text).html(); ++ } ++ + , highlighter: function (item) { ++ var that = this ++ , text = item == null ? '' : String(item); ++ ++ if (!this.query.length) { ++ return this.escape(text); ++ } ++ + var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); +- return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { +- return '' + match + ''; +- }) ++ return text.split(new RegExp('(' + query + ')', 'i')).map(function (part, i) { ++ var escaped = that.escape(part); ++ return i % 2 ? '' + escaped + '' : escaped; ++ }).join(''); + } + + , render: function (items) { diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,344 @@ +From bf52ece637c219bf24ac506b2da92e902d3b5d53 Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sat, 21 Nov 2026 21:16:38 +1300 +Subject: Fix to test files for requiring submit button to update queues and + articles + +Changes to test files from this commit: + +Require the submit button to update queues and articles + +The Class and Lifecycle parameters are common search names that have been +whitelisted by the CSRF check (Lifecycle is specifically whitelisted by +RTIR). Therefore, we need to add this additional argument check to protect +these admin pages. + +Patch-Name: upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes1.diff +Author: sunnavy +Forwarded: not-needed +Applied: 5.0.11, commit:33f693dc161845e2f2f808468eeebfb296ed8e9c +--- + t/articles/interface.t | 5 +++-- + t/articles/queue-specific-class.t | 3 ++- + t/articles/upload-customfields.t | 1 + + t/mail/gnupg-bad.t | 2 +- + t/mail/gnupg-incoming.t | 2 +- + t/mail/gnupg-realmail.t | 2 +- + t/mail/gnupg-special.t | 1 + + t/sla/web.t | 2 +- + t/web/admin_queue_lifecycle.t | 8 ++++---- + t/web/cf_html.t | 4 ++++ + t/web/cf_onqueue.t | 1 + + t/web/crypt-gnupg.t | 6 +++--- + t/web/csrf.t | 2 +- + t/web/queue_create.t | 4 ++++ + t/web/smime/outgoing.t | 2 +- + t/web/ticket_create.t | 2 +- + 16 files changed, 30 insertions(+), 17 deletions(-) + +diff --git a/t/articles/interface.t b/t/articles/interface.t +index 5822fc75..0e6e86a2 100644 +--- a/t/articles/interface.t ++++ b/t/articles/interface.t +@@ -176,7 +176,8 @@ my $turi = "t:$ticket_id"; + my $a1uri = 'a:'.$article1->Id; + $m->submit_form(form_name => 'EditArticle', + fields => { $article3->Id.'-RefersTo' => $turi, +- 'RefersTo-'.$article3->Id => $a1uri } ++ 'RefersTo-'.$article3->Id => $a1uri }, ++ button => 'Submit', + ); + + $m->content_like(qr/Ticket.*$ticket_id/, "Ticket linkto was created"); +@@ -198,7 +199,7 @@ $m->form_number(3); + $m->set_visible([option => $answerCF->Name]); + $m->click(); + $m->title_like(qr/Create a new article/, "got edit page from extraction"); +-$m->submit_form(form_name => 'EditArticle', fields => { Name => 'more testing' }); ++$m->submit_form(form_name => 'EditArticle', fields => { Name => 'more testing' }, button => 'Submit'); + $m->title_like(qr/Modify article/); + $m->follow_link_ok( { text => 'Display' }, '-> Display' ); + $m->content_like(qr/Africa/, "Article content exist"); +diff --git a/t/articles/queue-specific-class.t b/t/articles/queue-specific-class.t +index 42e6e1e0..b3037513 100644 +--- a/t/articles/queue-specific-class.t ++++ b/t/articles/queue-specific-class.t +@@ -38,7 +38,8 @@ for my $name ( keys %class ) { + form_number => 3, + fields => { Name => "article $name", + 'Summary' => "$name summary", +- 'Object-RT::Article--CustomField-1-Values' => "$name content"} ++ 'Object-RT::Article--CustomField-1-Values' => "$name content"}, ++ button => 'Submit', + ); + + $m->content_like( qr/Article \d+ created/, "created article $name" ); +diff --git a/t/articles/upload-customfields.t b/t/articles/upload-customfields.t +index 20b8cef1..5260e71a 100644 +--- a/t/articles/upload-customfields.t ++++ b/t/articles/upload-customfields.t +@@ -78,6 +78,7 @@ $m->submit_form( + Name => 'Image Test '.$$, + Summary => 'testing img cf creation', + }, ++ button => 'Submit', + ); + + $m->content_like(qr/Article \d+ created/, "an article was created succesfully"); +diff --git a/t/mail/gnupg-bad.t b/t/mail/gnupg-bad.t +index ea90e3a4..b56ae2ba 100644 +--- a/t/mail/gnupg-bad.t ++++ b/t/mail/gnupg-bad.t +@@ -17,7 +17,7 @@ $m->login; + $m->get( $baseurl.'/Admin/Queues/'); + $m->follow_link_ok( {text => 'General'} ); + $m->submit_form( form_number => 3, +- fields => { CorrespondAddress => 'rt@example.com' } ); ++ fields => { CorrespondAddress => 'rt@example.com' }, button => 'Submit' ); + $m->content_like(qr/rt\@example.com.* - never/, 'has key info.'); + + ok(my $user = RT::User->new(RT->SystemUser)); +diff --git a/t/mail/gnupg-incoming.t b/t/mail/gnupg-incoming.t +index 1844a35e..979ed77c 100644 +--- a/t/mail/gnupg-incoming.t ++++ b/t/mail/gnupg-incoming.t +@@ -30,7 +30,7 @@ ok( $m->login, 'we did log in' ); + $m->get( $baseurl.'/Admin/Queues/'); + $m->follow_link_ok( {text => 'General'} ); + $m->submit_form( form_number => 3, +- fields => { CorrespondAddress => 'general@example.com' } ); ++ fields => { CorrespondAddress => 'general@example.com' }, button => 'Submit' ); + $m->content_like(qr/general\@example.com.* - never/, 'has key info.'); + + ok(my $user = RT::User->new(RT->SystemUser)); +diff --git a/t/mail/gnupg-realmail.t b/t/mail/gnupg-realmail.t +index 8c386358..64c341c9 100644 +--- a/t/mail/gnupg-realmail.t ++++ b/t/mail/gnupg-realmail.t +@@ -14,7 +14,7 @@ ok $m->login, 'we did log in'; + $m->get_ok( '/Admin/Queues/'); + $m->follow_link_ok( {text => 'General'} ); + $m->submit_form( form_number => 3, +- fields => { CorrespondAddress => 'rt-recipient@example.com' } ); ++ fields => { CorrespondAddress => 'rt-recipient@example.com' }, button => 'Submit' ); + $m->content_like(qr/rt-recipient\@example.com.* - never/, 'has key info.'); + + my $eid = 0; +diff --git a/t/mail/gnupg-special.t b/t/mail/gnupg-special.t +index c95e5bfd..4c2534ca 100644 +--- a/t/mail/gnupg-special.t ++++ b/t/mail/gnupg-special.t +@@ -19,6 +19,7 @@ ok( $m->login, 'we did log in' ); + $m->submit_form( + form_number => 3, + fields => { CorrespondAddress => 'rt-recipient@example.com' }, ++ button => 'Submit', + ); + $m->content_like(qr/rt-recipient\@example.com.* - never/, 'has key info.'); + } +diff --git a/t/sla/web.t b/t/sla/web.t +index 0eb0be8e..651c8842 100644 +--- a/t/sla/web.t ++++ b/t/sla/web.t +@@ -86,7 +86,7 @@ ok $m->login( 'user', 'password' ), 'logged in as user'; + $m->get_ok( $baseurl . '/Admin/Queues/Modify.html?id=' . $queue->id ); + my $form = $m->form_name( 'ModifyQueue' ); + $m->untick( 'SLAEnabled', 1 ); +- $m->submit; ++ $m->click('Submit'); + $m->text_contains( q{SLADisabled changed from (no value) to "1"} ); + } + +diff --git a/t/web/admin_queue_lifecycle.t b/t/web/admin_queue_lifecycle.t +index e5565b27..f3f9ff06 100644 +--- a/t/web/admin_queue_lifecycle.t ++++ b/t/web/admin_queue_lifecycle.t +@@ -34,14 +34,14 @@ $m->content_lacks( 'That is already the current value', + 'no message of "That is already the current value"' ); + + $form = $m->form_name('ModifyQueue'); +-$m->submit_form( fields => { Lifecycle => 'foo' }, ); ++$m->submit_form( fields => { Lifecycle => 'foo' }, button => 'Submit' ); + $m->content_contains( + 'Lifecycle changed from "default" to "foo"'); + $lifecycle_input = $form->find_input('Lifecycle'); + is( $lifecycle_input->value, 'foo', 'lifecycle is changed to foo' ); + + $form = $m->form_name('ModifyQueue'); +-$m->submit_form( fields => { Lifecycle => 'default' }, ); ++$m->submit_form( fields => { Lifecycle => 'default' }, button => 'Submit' ); + $m->content_contains( + 'Lifecycle changed from "foo" to "default"'); + $lifecycle_input = $form->find_input('Lifecycle'); +@@ -68,7 +68,7 @@ RT::Lifecycle->FillCache(); + ok( $m->login(), 'logged in' ); + $m->get_ok( $url . '/Admin/Queues/Modify.html?id=1' ); + $form = $m->form_name('ModifyQueue'); +-$m->submit_form( fields => { Lifecycle => 'bar' }, ); ++$m->submit_form( fields => { Lifecycle => 'bar' }, button => 'Submit' ); + $m->text_contains(q{Lifecycle changed from "default" to "bar"}); + $lifecycle_input = $form->find_input('Lifecycle'); + is( $lifecycle_input->value, 'bar', 'lifecycle is changed to bar' ); +@@ -84,7 +84,7 @@ ok( $m->login(), 'logged in' ); + $m->get_ok( $url . '/Admin/Queues/Modify.html?id=1' ); + $m->next_warning_like(qr/Unable to load lifecycle for bar/, 'warning of missing lifecycle bar'); + $form = $m->form_name('ModifyQueue'); +-$m->submit_form( fields => { Lifecycle => 'default' }, ); ++$m->submit_form( fields => { Lifecycle => 'default' }, button => 'Submit' ); + $m->text_contains(q{Lifecycle changed from "bar" to "default"}); + $lifecycle_input = $form->find_input('Lifecycle'); + is( $lifecycle_input->value, 'default', 'lifecycle is changed to default' ); +diff --git a/t/web/cf_html.t b/t/web/cf_html.t +index cd8b66a4..9cd208e3 100644 +--- a/t/web/cf_html.t ++++ b/t/web/cf_html.t +@@ -33,6 +33,7 @@ $m->submit_form_ok( + with_fields => { + $cf_input => $content, + }, ++ button => 'Submit', + }, + 'Set content' + ); +@@ -50,6 +51,7 @@ $m->submit_form_ok( + $cf_input => $new_content, + + }, ++ button => 'Submit', + }, + 'Update content' + ); +@@ -66,6 +68,7 @@ $m->submit_form_ok( + $cf_input => $newer_content, + + }, ++ button => 'Submit', + }, + 'Update content again' + ); +@@ -87,6 +90,7 @@ $m->submit_form_ok( + with_fields => { + $cf_input => '', + }, ++ button => 'Submit', + }, + 'Delete content' + ); +diff --git a/t/web/cf_onqueue.t b/t/web/cf_onqueue.t +index 74559330..7b031986 100644 +--- a/t/web/cf_onqueue.t ++++ b/t/web/cf_onqueue.t +@@ -52,6 +52,7 @@ diag "Edit the CF value for default queue"; + fields => { + 'Object-RT::Queue-1-CustomField-2-Value' => 'QueueCFTest content', + }, ++ button => 'Submit', + ); + $m->content_contains('QueueCFTest QueueCFTest content added', 'Content filed in CF QueueCFTest for default queue' ); + +diff --git a/t/web/crypt-gnupg.t b/t/web/crypt-gnupg.t +index 558f3856..e91bb706 100644 +--- a/t/web/crypt-gnupg.t ++++ b/t/web/crypt-gnupg.t +@@ -50,7 +50,7 @@ ok $m->login, 'logged in'; + $m->get_ok("/Admin/Queues/Modify.html?id=$qid"); + $m->form_with_fields('Sign', 'Encrypt'); + $m->field(Encrypt => 1); +-$m->submit; ++$m->click('Submit'); + + RT::Test->clean_caught_mails; + +@@ -119,7 +119,7 @@ $m->get("$baseurl/Admin/Queues/Modify.html?id=$qid"); + $m->form_with_fields('Sign', 'Encrypt'); + $m->field(Encrypt => undef); + $m->field(Sign => 1); +-$m->submit; ++$m->click('Submit'); + + RT::Test->clean_caught_mails; + +@@ -213,7 +213,7 @@ $m->get("$baseurl/Admin/Queues/Modify.html?id=$qid"); + $m->form_with_fields('Sign', 'Encrypt'); + $m->field(Encrypt => 1); + $m->field(Sign => 1); +-$m->submit; ++$m->click('Submit'); + + RT::Test->clean_caught_mails; + +diff --git a/t/web/csrf.t b/t/web/csrf.t +index 74855800..4f1fe5b3 100644 +--- a/t/web/csrf.t ++++ b/t/web/csrf.t +@@ -157,7 +157,7 @@ $m->content_contains("Possible cross-site request forgery"); + my ($token) = $m->content =~ m{CSRF_Token=(\w+)}; + + $m->add_header(Referer => undef); +-$m->get_ok("/Admin/Queues/Modify.html?id=new&Name=test&CSRF_Token=$token"); ++$m->get_ok("/Admin/Queues/Modify.html?id=new&Name=test&Submit=1&CSRF_Token=$token"); + $m->content_contains("Possible cross-site request forgery"); + $m->content_contains("If you really intended to visit $baseurl/Admin/Queues/Modify.html"); + $m->content_contains("your browser did not supply a Referrer header"); +diff --git a/t/web/queue_create.t b/t/web/queue_create.t +index 40f7b3b8..f59d1537 100644 +--- a/t/web/queue_create.t ++++ b/t/web/queue_create.t +@@ -21,6 +21,7 @@ diag "Create a queue"; + fields => { + Name => '', + }, ++ button => 'Submit', + ); + $m->text_contains('Queue name is required'); + $m->submit_form( +@@ -28,6 +29,7 @@ diag "Create a queue"; + fields => { + Name => '0', + }, ++ button => 'Submit', + ); + $m->text_contains("'0' is not a valid name"); + $m->submit_form( +@@ -35,6 +37,7 @@ diag "Create a queue"; + fields => { + Name => '1', + }, ++ button => 'Submit', + ); + $m->text_contains("'1' is not a valid name"); + $m->submit_form( +@@ -42,6 +45,7 @@ diag "Create a queue"; + fields => { + Name => $queue_name, + }, ++ button => 'Submit', + ); + $m->content_contains('Queue created', 'created queue sucessfully' ); + +diff --git a/t/web/smime/outgoing.t b/t/web/smime/outgoing.t +index 6d3a5304..0696dcf0 100644 +--- a/t/web/smime/outgoing.t ++++ b/t/web/smime/outgoing.t +@@ -357,7 +357,7 @@ sub t_set_queue_crypt_options { + $m->untick($opt => 1); + } + } +- $m->submit; ++ $m->click('Submit'); + } + + sub describe_options { +diff --git a/t/web/ticket_create.t b/t/web/ticket_create.t +index 4548f9da..38acbc71 100644 +--- a/t/web/ticket_create.t ++++ b/t/web/ticket_create.t +@@ -30,7 +30,7 @@ my ( $baseurl, $m ) = RT::Test->started_ok; + ok $m->login; + $m->get_ok( '/Admin/Queues/Modify.html?id=' . $queue1->id ); + $m->form_name('ModifyQueue'); +-$m->submit_form( fields => { Lifecycle => 'foo' } ); ++$m->submit_form( fields => { Lifecycle => 'foo' }, button => 'Submit' ); + + # set up custom field + my $cf = RT::Test->load_or_create_custom_field( Name => 'test_cf', Queue => $queue1->Name, Type => 'FreeformSingle' ); diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,40 @@ +From 44690f182aa3008e27a48580ea51aca395db639f Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 22 Nov 2026 11:59:04 +1300 +Subject: Fix to test file to escape labels and values rendered into chart + tables + +Change to test file from this commit: + +ChartTable writes every cell out with $m->out, which escapes nothing. Header +cells carry custom field and custom role names, and the grouping cells carry +the grouped value itself: a queue, catalog, user or group name, a custom +field value, etc. + +Considering ChartTable cells may hold markup on purpose like the business +hours that may carry a CSS class, here we escape at the source: FormatTable +escapes the labels it puts in cells, LabelValue escapes the value it returns +for the html format when no Display code handled it, and the Display codes +that return a name escape it. + +Patch-Name: upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes2.diff +Author: sunnavy +Forwarded: not-needed +Applied: 5.0.11, commit:2fdfdbf280aca538331df41d75ef33a884434da7 +--- + t/charts/group-by-cr.t | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/t/charts/group-by-cr.t b/t/charts/group-by-cr.t +index 7876888a..2fce109a 100644 +--- a/t/charts/group-by-cr.t ++++ b/t/charts/group-by-cr.t +@@ -45,7 +45,7 @@ use_ok 'RT::Report::Tickets'; + 'tbody' => [ + { 'cells' => [ + { 'type' => 'label', +- 'value' => '(no value)' ++ 'value' => '(no value)' + }, + { 'query' => '(CustomRole.{1}.Name IS NULL)', + 'type' => 'value', diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,29 @@ +From 84fdcb9f7ecd37e19d776d7f268574e01655890b Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 22 Nov 2026 12:00:52 +1300 +Subject: Grant ShowTicket in the REST2 image CF test + +Downloading a value needs rights on the record as well as on the +custom field. + +Patch-Name: upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes3.diff +Author: sunnavy +Forwarded: not-needed +Applied: 5.0.11, commit:dbb84d5507f4249963cbf398755b57cadf32f229 +--- + t/rest2/cf-image.t | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/t/rest2/cf-image.t b/t/rest2/cf-image.t +index 5025ddf2..942aaee3 100644 +--- a/t/rest2/cf-image.t ++++ b/t/rest2/cf-image.t +@@ -40,7 +40,7 @@ my $text_ocfv = $ticket->CustomFieldValues('Text CF')->First; + is($res->code, 403); + } + +-$user->PrincipalObj->GrantRight( Right => 'SeeCustomField' ); ++$user->PrincipalObj->GrantRight( Right => $_ ) for qw(SeeCustomField ShowTicket); + + # Try undef ObjectCustomFieldValue + { diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,29 @@ +From f4dd5985d03b691a831a7ae5e65b2ef59d539da0 Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 22 Nov 2026 12:02:10 +1300 +Subject: Expect & escaped as & in HTML MakeClicky URLs + +MakeClicky will escape URLs in HTML content with EscapeHTML, as it +does for text content, and EscapeHTML encodes & as &. + +Patch-Name: upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes4.diff +Author: Jim Brandt +Forwarded: not-needed +Applied: 5.0.11, commit:9a3b462975fbe88300f2a78497a90e7985b9457b +--- + t/web/make-clicky.t | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/t/web/make-clicky.t b/t/web/make-clicky.t +index 8a9446cd..2e43143b 100644 +--- a/t/web/make-clicky.t ++++ b/t/web/make-clicky.t +@@ -71,7 +71,7 @@ diag "Found in other attribute"; + diag "Do not double encode & test"; + { + my $url = 'http://bestpractical.com/search?q=me&irene;token=foo'; +- my $string = qq[http://bestpractical.com/search?q=me&irene;token=foo]; ++ my $string = qq[http://bestpractical.com/search?q=me&irene;token=foo]; + is_string( make_clicky($m,$url, 1), $string, "URL with & should not rencode" ); + + } diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff 1970-01-01 00:00:00.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff 2026-11-22 08:53:30.000000000 +0000 @@ -0,0 +1,55 @@ +From 51a927ca36a03968ebef468c57de35d40c8e02d0 Mon Sep 17 00:00:00 2001 +From: Andrew Ruthven +Date: Sun, 22 Nov 2026 12:03:56 +1300 +Subject: Fix to test for authorize the destination container before moving a + shared setting + +Changes to test file from this commit: + +This is consistent with moving tickets to a different queue. + +The saved search privacy dropdown has only ever offered RT::System to +SuperUsers, but the attribute rights asked for EditSavedSearches there. +Require SuperUser for RT::System as well, so the two agree. + +Patch-Name: upstream_5.0.7_cve:_patchset_2026-10-15_test_fixes5.diff +Author: sunnavy +Forwarded: not-needed +Applied: 5.0.11, commit:c843c131c8064ff63b732cac59f7fab63feb305d +--- + t/web/saved_search_permissions.t | 21 +++++++++++++++++++-- + 1 file changed, 19 insertions(+), 2 deletions(-) + +diff --git a/t/web/saved_search_permissions.t b/t/web/saved_search_permissions.t +index fc35cc48..faee8414 100644 +--- a/t/web/saved_search_permissions.t ++++ b/t/web/saved_search_permissions.t +@@ -71,9 +71,26 @@ $m->content_contains( $message, 'user foo can not delete RT System saved search' + + ok($user->PrincipalObj->GrantRight(Object => RT->System, Right =>'EditSavedSearches'), + 'Granted foo EditSavedSearches'); ++ ++diag('EditSavedSearches does not reach RT System saved searches'); ++ ++$m->get_ok( $url . '/Search/Build.html?Query=id<10&SavedSearchSave=1' ++ . '&SavedSearchOwner=RT::System-1&SavedSearchDescription=Less+than+10' ); ++$m->content_contains( 'Permission Denied', 'user foo can not save an RT System saved search' ); ++$m->content_lacks( 'RT::System-1-SavedSearch-', 'no RT System saved search was created' ); ++ ++$m->get_ok( $url . "/Search/Build.html?SavedSearchLoad=$id" ); ++$m->content_lacks('name="SavedSearchSave"', 'Update button still not shown to user foo' ); ++$m->content_lacks('name="SavedSearchDelete"', 'Delete button still not shown to user foo' ); ++ + $m->get_ok( $url . "/Search/Build.html?SavedSearchDelete=1&SavedSearchId=$id" ); +-$message = qq{Deleted saved search}; +-$m->content_contains( $message, 'user foo deleted RT saved search' ); ++$message = qq{No permission to delete search}; ++$m->content_contains( $message, 'user foo still can not delete RT System saved search' ); + ++ok($user->PrincipalObj->GrantRight(Object => RT->System, Right =>'SuperUser'), ++ 'Granted foo SuperUser'); ++$m->get_ok( $url . "/Search/Build.html?SavedSearchDelete=1&SavedSearchId=$id" ); ++$message = qq{Deleted saved search}; ++$m->content_contains( $message, 'user foo deleted RT System saved search' ); + + done_testing; diff -Nru request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.8_test_web:_patchset_2025-04-08.diff request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.8_test_web:_patchset_2025-04-08.diff --- request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.8_test_web:_patchset_2025-04-08.diff 2026-06-01 01:10:39.000000000 +0000 +++ request-tracker5-5.0.7+dfsg/debian/patches/upstream_5.0.8_test_web:_patchset_2025-04-08.diff 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -From 9ae6226d9cede5339c007fac69da5c7c516d09c9 Mon Sep 17 00:00:00 2001 -From: Andrew Ruthven -Date: Sun, 4 May 2025 17:25:39 +1200 -Subject: Fix test for 2025-04-08 CVE patchset - -Patch-Name: upstream_5.0.8_test_web:_patchset_2025-04-08.diff -Author: Best Practical -Forwarded: not-needed -Applied: 5.0.8, commit:cb67ffa28333418178cb2f7be3562cb8d1817c63 ---- - t/web/helpers-http-cache-headers.t | 3 +++ - 1 file changed, 3 insertions(+) - -diff --git a/t/web/helpers-http-cache-headers.t b/t/web/helpers-http-cache-headers.t -index c946daf4..4c4fdcfd 100644 ---- a/t/web/helpers-http-cache-headers.t -+++ b/t/web/helpers-http-cache-headers.t -@@ -97,6 +97,9 @@ foreach my $endpoint ( @endpoints ) { - if ( $endpoint =~ m{/Helpers/AssetUpdate} ) { - $m->get_ok( $endpoint . "?id=${asset_id}&Status=allocated" ); - } -+ elsif ( $endpoint =~ m{/Helpers/Permalink} ) { -+ $m->get_ok( $endpoint . "?URL=/" ); -+ } - else { - $m->get_ok( $endpoint . "?id=${ticket_id}&Status=open&Requestor=root" ); - }