Commit Graph

9379 Commits

Author SHA1 Message Date
Daniel Waterworth 8371c96b7e
PERF: Speed up tests (#15214) 2021-12-07 12:45:58 -06:00
Daniel Waterworth 95c75d3f4f
DEV: Set uploads_id_seq starting point before tests (#15215)
Some tests don't pass when this is elevated. They should be fixed,
since, at some point, we may create enough uploads during tests that
they fail naturally.
2021-12-07 12:26:35 -06:00
Loïc Guitaut d0888c190e FIX: Display pending posts in a moderated category
Currently we display pending posts in topics (both for author and staff
members) but the feature is only enabled when there’s an enabled global site
setting related to moderation.

This patch allows to have the same behavior for a site where there’s
nothing enabled globally but where a moderated category exists. So when
browsing a topic of a moderated category, the presence of pending posts
will be checked whereas nothing will happen in a normal category.
2021-12-07 10:14:45 +01:00
Alan Guo Xiang Tan 4e67297a7c FIX: Missing allowed urls when displaying granualar API key scopes.
Follow-up to 3791fbd919
2021-12-07 10:17:17 +08:00
Alan Guo Xiang Tan 44588255fc FEATURE: Introduce API scopes for badges. 2021-12-07 10:17:17 +08:00
Andrei Prigorshnev f3508065a3
FIX: auth incorrectly handles duplicate usernames (#15197) 2021-12-06 20:49:04 +04:00
Roman Rizzi 43903f8dfe
FIX: Updating a consolidated notification should bump it to the top. (#15199)
In the future, it would be better to have a consolidated_at timestamp instead of updating created_at.
2021-12-06 12:31:44 -03:00
Daniel Waterworth 3ebce550fe
DEV: Make add_api_parameter_route parameter deprecations errors (#15198)
Since we said we would remove support in 2.7, this is overdue.
2021-12-06 09:10:14 -06:00
Andrei Prigorshnev 10cc082560
FIX: when using external auth disallowed characters weren't removed from username (#15185) 2021-12-06 15:06:35 +04:00
Jarek Radosz 28bf9599f5
FEATURE: Pre-setting user locale via bulk invite (#15195) 2021-12-06 02:08:21 +01:00
Martin Brennan 3b13f1146b
FIX: Add random suffix to outbound Message-ID for email (#15179)
Currently the Message-IDs we send out for outbound email
are not unique; for a post they look like:

topic/TOPIC_ID/POST_ID@HOST

And for a topic they look like:

topic/TOPIC_ID@HOST

This commit changes the outbound Message-IDs to also have
a random suffix before the host, so the new format is
like this:

topic/TOPIC_ID/POST_ID.RANDOM_SUFFIX@HOST

Or:

topic/TOPIC_ID.RANDOM_SUFFIX@HOST

This should help with email deliverability. This change
is backwards-compatible, the old Message-ID format will
still be recognized in the mail receiver flow, so people
will still be able to reply using Message-IDs, In-Reply-To,
and References headers that have already been sent.

This commit also refactors Message-ID related logic
to a central location, and adds judicious amounts of
tests and documentation.
2021-12-06 10:34:39 +10:00
Daniel Waterworth 959923d3cf
FIX: Match for indeterminate depth in URL during upload tests (#15186)
Since the uploads id sequence counter isn't reset before test runs, the
URL might not be /1X/
2021-12-03 16:05:27 -06:00
Daniel Waterworth 63112f89a3
PERF: Shave off some test-suite time (#15183) 2021-12-03 14:54:07 -06:00
Blake Erickson 643f82d8d6
DEV: Update email responses in api docs (#15178)
Documenting the `/u/:username:/emails.json` endpoint.

Also removing some email fields from user api responses because they
aren't actually included in the response unless you are querying
yourself.
2021-12-03 08:03:58 -07:00
Michelle Bueno Saquetim Vendrame 9b5836aa1d
Add three reports (#14338)
* Add report top_users_by_received_likes

* Add report top_users_by_received_likes_from_inferior_trust_level

* Add report top_users_by_likes_received_from_a_variety_of_people

* Add test to report_top_users_by_received_likes

* add top_users_by_likes_received_from_a_variety_of_people report test

* add top_users_by_likes_received_from_inferior_trust_level report tests
2021-12-02 22:41:55 +05:30
Daniel Waterworth 2f04a9b9fb
DEV: Remove site_setting_saved event (#15164)
We said we would drop it from 2.4, so this is long overdue

Co-authored-by: Jarek Radosz <jradosz@gmail.com>
2021-12-02 09:33:03 -06:00
David Taylor cfb6199a95
FIX: Don't redirect XHR/JSON requests when login is required (#15093)
When redirecting to login, we store a destination_url cookie, which the user is then redirected to after login. We never want the user to be redirected to a JSON URL. Instead, we should return a 403 in these situations.

This should also be much less confusing for API consumers - a 403 is a better representation than a 302.
2021-12-02 15:12:25 +00:00
Andrei Prigorshnev 1c0022c195
FIX: extract and fix overriding of usernames by external auth (#14637) 2021-12-02 17:42:23 +04:00
Osama Sayegh 1d69261bc0
FIX: Set `auto_update` to false for non-git themes/components (#15157)
Related to: 20f736aa11.

`auto_update` is true by default at the database level, but it doesn't make sense for `auto_update` to be true on themes that are not imported from a Git repository.
2021-12-01 19:58:13 +03:00
David Taylor 1fa7a87f86
SECURITY: Remove ember-cli specific response from application routes (#15155)
Under some conditions, these varied responses could lead to cache poisoning, hence the 'security' label.

Previously the Rails application would serve JSON data in place of HTML whenever Ember CLI requested an `application.html.erb`-rendered page. This commit removes that logic, and instead parses the HTML out of the standard response. This means that Rails doesn't need to customize its response for Ember CLI.
2021-12-01 16:10:40 +00:00
Natalie Tay 0f598ca51e
SECURITY: Only show tags to users with permission (#15148) 2021-12-01 10:26:56 +08:00
Krzysztof Kotlarek 9cabd3721b
FEATURE: ability to add description to tags (#15125)
Ability to add description to tags, which will be displayed on hover.
2021-12-01 09:18:56 +11:00
Jarek Radosz 78723345c0
DEV: Fix a flaky bookmarks test (#15129)
* DEV: Specify bookmarks order

It's better to order by id than to have a semi-random order. Fixes a flaky test:

```
 1) TopicView with a few sample posts #bookmarks gets the first post bookmark reminder at for the user
59
     Failure/Error: expect(first[:post_id]).to eq(bookmark1.post_id)
60

61
       expected: 1901
62
            got: 1902
63

64
       (compared using ==)
65
     # ./spec/components/topic_view_spec.rb:420:in `block (4 levels) in <main>'
66
     # ./spec/rails_helper.rb:284:in `block (2 levels) in <top (required)>'
67
     # ./vendor/bundle/ruby/2.7.0/gems/webmock-3.14.0/lib/webmock/rspec.rb:37:in `block (2 levels) in <top (required)>'
68
```

* Change test

* Revert "DEV: Specify bookmarks order"

This reverts commit 1f50026231.
2021-12-01 08:56:00 +11:00
Roman Rizzi 1fc06520bd
REFACTOR: Improve support for consolidating notifications. (#14904)
* REFACTOR: Improve support for consolidating notifications.

Before this commit, we didn't have a single way of consolidating notifications. For notifications like group summaries, we manually removed old ones before creating a new one. On the other hand, we used an after_create callback for likes and group membership requests, which caused unnecessary work, as we need to delete the record we created to replace it with a consolidated one.

We now have all the consolidation rules centralized in a single place: the consolidation planner class. Other parts of the app looking to create a consolidable notification can do so by calling Notification#consolidate_or_save!, instead of the default Notification#create! method.

Finally, we added two more rules: one for re-using existing group summaries and another for deleting duplicated dashboard problems PMs notifications when the user is tracking the moderator's inbox. Setting the threshold to one forces the planner to apply this rule every time.

I plan to add plugin support for adding custom rules in another PR to keep this one relatively small.

* DEV: Introduces a plugin API for consolidating notifications.

This commit removes the `Notification#filter_by_consolidation_data` scope since plugins could have to define their criteria. The Plan class now receives two blocks, one to query for an already consolidated notification, which we'll try to update, and another to query for existing ones to consolidate.

It also receives a consolidation window, which accepts an ActiveSupport::Duration object, and filter notifications created since that value.
2021-11-30 13:36:14 -03:00
Andrei Prigorshnev 88f9bb3dc9
FIX: do not suggest "user1" as a username to invited users (#15031)
Recently, the wrong new behavior appeared – we started to suggest to invited users usernames like "user1".

To reproduce:
1. Create an invitation with default settings, do not restrict it to email
2. Copy an invitation link and follow it in incognito mode
See username already filled, with eg “user1”. See screenshot. Should be empty.

This bug was very likely introduced by my recent changes to UserNameSuggester.
2021-11-30 16:59:37 +04:00
Osama Sayegh 7bd3986b21
FEATURE: Replace `Crawl-delay` directive with proper rate limiting (#15131)
We have a couple of site setting, `slow_down_crawler_user_agents` and `slow_down_crawler_rate`, that are meant to allow site owners to signal to specific crawlers that they're crawling the site too aggressively and that they should slow down.

When a crawler is added to the `slow_down_crawler_user_agents` setting, Discourse currently adds a `Crawl-delay` directive for that crawler in `/robots.txt`. Unfortunately, many crawlers don't support the `Crawl-delay` directive in `/robots.txt` which leaves the site owners no options if a crawler is crawling the site too aggressively.

This PR replaces the `Crawl-delay` directive with proper rate limiting for crawlers added to the `slow_down_crawler_user_agents` list. On every request made by a non-logged in user, Discourse will check the User Agent string and if it contains one of the values of the `slow_down_crawler_user_agents` list, Discourse will only allow 1 request every N seconds for that User Agent (N is the value of the `slow_down_crawler_rate` setting) and the rest of requests made within the same interval will get a 429 response. 

The `slow_down_crawler_user_agents` setting becomes quite dangerous with this PR since it could rate limit lots if not all of anonymous traffic if the setting is not used appropriately. So to protect against this scenario, we've added a couple of new validations to the setting when it's changed:

1) each value added to setting must 3 characters or longer
2) each value cannot be a substring of tokens found in popular browser User Agent. The current list of prohibited values is: apple, windows, linux, ubuntu, gecko, firefox, chrome, safari, applewebkit, webkit, mozilla, macintosh, khtml, intel, osx, os x, iphone, ipad and mac.
2021-11-30 12:55:25 +03:00
Alan Guo Xiang Tan 0edacbd8f7
DEV: Load fabricators for plugins automatically. (#15106) 2021-11-30 15:55:45 +11:00
Loïc Guitaut a5fbb90df4 FEATURE: Display pending posts on user’s page
Currently when a user creates posts that are moderated (for whatever
reason), a popup is displayed saying the post needs approval and the
total number of the user’s pending posts. But then this piece of
information is kind of lost and there is nowhere for the user to know
what are their pending posts or how many there are.

This patch solves this issue by adding a new “Pending” section to the
user’s activity page when there are some pending posts to display. When
there are none, then the “Pending” section isn’t displayed at all.
2021-11-29 10:26:33 +01:00
Penar Musaraj d99deaf1ab
FEATURE: show recent searches in quick search panel (#15024) 2021-11-25 15:44:15 -05:00
Rafael dos Santos Silva 5647819de4
FEATURE: Send a 'noindex' header in non-canonical responses (#15026)
* FEATURE: Optionally send a 'noindex' header in non-canonical responses

This will be used in a SEO experiment.

Co-authored-by: David Taylor <david@taylorhq.com>
2021-11-25 16:58:39 -03:00
David Taylor 03998e0a29
FIX: Use CDN URL for internal onebox avatars (#15077)
This commit will also trigger a background rebake for all existing posts with internal oneboxes
2021-11-25 12:07:34 +00:00
Dan Ungureanu fa8cd629f1
DEV: Hash tokens stored from email_tokens (#14493)
This commit adds token_hash and scopes columns to email_tokens table.
token_hash is a replacement for the token column to avoid storing email
tokens in plaintext as it can pose a security risk. The new scope column
ensures that email tokens cannot be used to perform a different action
than the one intended.

To sum up, this commit:

* Adds token_hash and scope to email_tokens

* Reuses code that schedules critical_user_email

* Refactors EmailToken.confirm and EmailToken.atomic_confirm methods

* Periodically cleans old, unconfirmed or expired email tokens
2021-11-25 09:34:39 +02:00
Natalie Tay 4c46c7e334
DEV: Remove xlink hrefs (#15059) 2021-11-25 15:22:43 +11:00
janzenisaac 8c7cc426b7
FEATURE: Notify responders of post removal (#15049)
- Notify users whose posts were cascade deleted due to a flagged post
2021-11-24 09:28:20 -06:00
Bianca Nenciu 3ea8937157
FEATURE: Add email normalization rules setting (#14593)
When this setting is turned on, it will check that normalized emails
are unique. Normalized emails are emails without any dots or plus
aliases.

This setting can be used to block use of aliases of the same email
address.
2021-11-24 11:30:06 +02:00
Alan Guo Xiang Tan a6aff40e4b
DEV: Allow default scope to be configurable per topic. (#15018)
Not exposing this as a plugin API yet as we're testing it out with a
plugin.
2021-11-24 16:40:58 +08:00
Martin Brennan 44be79f095
FIX: Strip Auto-Submitted email header from group SMTP emails (#15057)
Remove Auto-Submitted header for group private message emails, it does
not make sense there and may hurt deliverability.

From https://www.iana.org/assignments/auto-submitted-keywords/auto-submitted-keywords.xhtml:

> Indicates that a message was generated by an automatic process, and is not a direct response to another message.
2021-11-24 10:54:01 +10:00
Bianca Nenciu 73760c77d9
FEATURE: Mention @here to notify users in topic (#14900)
Use @here to mention all users that were allowed to topic directly or
through group, who liked topics or read the topic. Only first 10 users
will be notified.
2021-11-23 22:25:54 +02:00
Dan Ungureanu ff7acc9828
FIX: Git should not prompt for credentials (#15062)
When cloning a public remote repository (no key), git should not prompt
for credentials.
2021-11-23 13:54:51 +02:00
Dan Ungureanu 948a1523ea
FIX: Keep existent tags when editing tag topics (#15050)
Allow current user to keep existent tags when adding or removing a tag.
For example, a user could not remove a tag from a topic if the topic
had another tag that was restricted to a different category.
2021-11-23 13:00:45 +02:00
Alan Guo Xiang Tan c0f278d358
DEV: Fix flaky specs due to 8226ab1099. (#15060)
The users all shared the same `User#last_seen_at` column so depending on
how the database returned the records, the user that we're interested in
may be excluded from the update query.

Follow-up to 8226ab1099
2021-11-23 15:26:55 +08:00
Alan Guo Xiang Tan 8226ab1099
PERF: Updating first unread PM for user not respecting limits. (#15056)
In b8c8909a9d, we introduced a regression
where users may have had their `UserStat.first_unread_pm_at` set
incorrectly. This commit introduces a migration to reset `UserStat.first_unread_pm_at` back to
`User#created_at`.

Follow-up to b8c8909a9d.
2021-11-23 12:51:54 +08:00
RogerBW fd66df5997
FEATURE: adds uploads scope for API keys (#14941)
* FEATURE: adds uploads scope for API keys

* Add basic test, change "image" to "file"
2021-11-22 10:49:08 -07:00
Rafael dos Santos Silva c891c44775
UX: Lower digest suppress period from a year to 6 months (#15023) 2021-11-22 14:37:32 -03:00
Jarek Radosz d91d67a442
FEATURE: Allow theme settings to request refresh (#15037)
Similar to site settings, adds support for `refresh` option to theme settings.

```yaml
super_feature_enabled:
  type: bool
  default: false
  refresh: true
```
2021-11-22 13:16:56 +01:00
Dan Ungureanu f43c433d50
FIX: Allow invites if must_approve_users is true (#15043)
This was implemented in 36e0e6a, but then regressed when the guardian
for invites was refactored in 76a7b75.
2021-11-22 14:04:35 +02:00
Martin Brennan 8a3ab1cc43
DEV: Fix spec (#15036)
Broken by 9f8ee8f137
2021-11-22 15:59:10 +11:00
Martin Brennan 9f8ee8f137
FIX: Don't publish notifications to MessageBus for inactive users (#15035)
We are pushing /notification-alert/#{user_id} and /notification/#{user_id}
messages to MessageBus from both PostAlerter and User#publish_notification_state.
This can cause memory issues on large sites with many users. This commit
stems the bleeding by only sending these alert messages if the user
in question has been seen in the last 30 days, which eliminates a large
chunk of users on some sites.
2021-11-22 14:38:49 +11:00
Martin Brennan fa6b87a1bf
SECURITY: Strip unrendered unicode bidirectional chars in code blocks (#15032)
When rendering the markdown code blocks we replace the
offending characters in the output string with spans highlighting a textual
representation of the character, along with a title attribute with
information about why the character was highlighted.

The list of characters stripped by this fix, which are the bidirectional
characters considered relevant, are:

U+202A
U+202B
U+202C
U+202D
U+202E
U+2066
U+2067
U+2068
U+2069
2021-11-22 10:43:03 +10:00
Vinoth Kannan fc1c76cfcc
FIX: exclude moderator_action post for reply count in user summary. (#14991)
Previously, incorrect reply counts are displayed in the "top categories" section of the user summary page since we included the `moderator_action` and `small_action` post types.

Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>
2021-11-18 13:42:03 +05:30
Penar Musaraj 20f5474be9
FEATURE: Log only topic/post search queries in search log (#14994) 2021-11-18 09:21:12 +08:00
Martin Brennan b96c10a903
DEV: Extract shared external upload routes into controller helper (#14984)
This commit refactors the direct external upload routes (get presigned
put, complete external, create/abort/complete multipart) into a
helper which is then included in both BackupController and the
UploadController. This is done so UploadController doesn't need
strange backup logic added to it, and so each controller implementing
this helper can do their own validation/error handling nicely.

This is a follow up to e4350bb966
2021-11-18 09:17:23 +10:00
Osama Sayegh b86127ad12
FEATURE: Apply rate limits per user instead of IP for trusted users (#14706)
Currently, Discourse rate limits all incoming requests by the IP address they
originate from regardless of the user making the request. This can be
frustrating if there are multiple users using Discourse simultaneously while
sharing the same IP address (e.g. employees in an office).

This commit implements a new feature to make Discourse apply rate limits by
user id rather than IP address for users at or higher than the configured trust
level (1 is the default).

For example, let's say a Discourse instance is configured to allow 200 requests
per minute per IP address, and we have 10 users at trust level 4 using
Discourse simultaneously from the same IP address. Before this feature, the 10
users could only make a total of 200 requests per minute before they got rate
limited. But with the new feature, each user is allowed to make 200 requests
per minute because the rate limits are applied on user id rather than the IP
address.

The minimum trust level for applying user-id-based rate limits can be
configured by the `skip_per_ip_rate_limit_trust_level` global setting. The
default is 1, but it can be changed by either adding the
`DISCOURSE_SKIP_PER_IP_RATE_LIMIT_TRUST_LEVEL` environment variable with the
desired value to your `app.yml`, or changing the setting's value in the
`discourse.conf` file.

Requests made with API keys are still rate limited by IP address and the
relevant global settings that control API keys rate limits.

Before this commit, Discourse's auth cookie (`_t`) was simply a 32 characters
string that Discourse used to lookup the current user from the database and the
cookie contained no additional information about the user. However, we had to
change the cookie content in this commit so we could identify the user from the
cookie without making a database query before the rate limits logic and avoid
introducing a bottleneck on busy sites.

Besides the 32 characters auth token, the cookie now includes the user id,
trust level and the cookie's generation date, and we encrypt/sign the cookie to
prevent tampering.

Internal ticket number: t54739.
2021-11-17 23:27:30 +03:00
Bianca Nenciu cc1b45f58b
FIX: Convert URLs embedded topics to absolute form (#14975)
Sometimes the expanded post contained broken relative URLs because they
were not converted to their absolute form.
2021-11-17 16:39:49 +11:00
Martin Brennan 515acb8fc4
FIX: Error when SMTP enabled in PostAlerter with no incoming email (#14981)
When 31035010af
was done it failed to take into account the case where the smtp_enabled
site setting was true, but the topic had no allowed groups / no
incoming email record, which caused errors for topics even with
nothing to do with group SMTP.
2021-11-17 09:24:17 +10:00
Martin Brennan e7a4742490
FIX: Clean up emoji name which is file name (#14980)
Uppy adds the file name as the "name" parameter in the
payload by default, which means that for things like the
emoji uploader which have a name param used by the controller,
that param will be passed as the file name. We already use
the existing file name if the name param is null, so this
commit just does further cleanup of the name param, removing
the extension if it is a filename so we don't end up with
emoji names like blah_png.
2021-11-17 09:20:44 +10:00
Akshay Birajdar 6b5e8be25a Support parsing array in #param_to_integer_list
Co-authored-by: Akshay Birajdar <akshay.birajdar@coupa.com>
2021-11-16 10:27:00 -05:00
Vinoth Kannan c47a526371
FIX: exclude topics from muted tag in category featured list. (#14925)
Topics from muted tags were visible in the categories page's featured topics section since we didn't filter it before.
2021-11-16 12:10:50 +05:30
Martin Brennan 31035010af
FIX: Use correct group out of multiple for SMTP sender (#14957)
When there are multiple groups on a topic, we were selecting
the first from the topic allowed groups to act as the sender
email address when sending group SMTP replies via PostAlerter.
However, this was not ordered, and since there is no created_at
column on TopicAllowedGroup we cannot order this nicely, which
caused just a random group to be used (based on whatever postgres
decided it felt like that morning).

This commit changes the group used for SMTP sending to be the
group using the email_username of the to address of the first
incoming email for the topic, if there are more than one allowed
groups on the topic. Otherwise it just uses the only SMTP enabled
group.
2021-11-16 10:21:49 +10:00
Martin Brennan eabe2df8d2
FIX: Drop malformed CC addresses in GroupSmtpEmail job (#14934)
Sometimes, a user may have a malformed email such as
`test@test.com<mailto:test@test.com` their email address,
and as a topic participant will be included as a CC email
when sending a GroupSmtpEmail. This causes the CC parsing to
fail and further down the line in Email::Sender the code
to check the CC addresses expects an array but gets a string
instead because of the parse failure.

Instead, we can just check if the CC addresses are valid
and drop them if they are not in the GroupSmtpEmail job.
2021-11-16 08:15:11 +10:00
David Taylor f45853676f
SECURITY: Ensure _forum_session cookies cannot be reused between sites (#14950)
This only affects multisite Discourse instances (where multiple forums are served from a single application server). The vast majority of self-hosted Discourse forums do not fall into this category.

On affected instances, this vulnerability could allow encrypted session cookies to be re-used between sites served by the same application instance.
2021-11-15 15:50:12 +00:00
Martin Brennan 08e625c446
FIX: Use previous chunk to check if local backup chunk upload complete (#14896)
Uppy and Resumable slice up their chunks differently, which causes a difference
in this algorithm. Let's take a 131.6MB file (137951695 bytes) with a 5MB (5242880 bytes)
chunk size. For resumable, there are 26 chunks, and uppy there are 27. This is
controlled by forceChunkSize in resumable which is false by default. The final
chunk size is 6879695 (chunk size + remainder) whereas in uppy it is 1636815 (just remainder).

This means that the current condition of uploaded_file_size + current_chunk_size >= total_size
is hit twice by uppy, because it uses a more correct number of chunks. This
can be solved for both uppy and resumable by checking the _previous_ chunk
number * chunk_size as the uploaded_file_size.

An example of what is happening before that change, using the current
chunk number to calculate uploaded_file_size.

chunk 26: resumable: uploaded_file_size (26 * 5242880) + current_chunk_size (6879695) = 143194575 >= total_size (137951695) ? YES
chunk 26: uppy: uploaded_file_size (26 * 5242880) + current_chunk_size (5242880) = 141557760 >= total_size (137951695) ? YES
chunk 27: uppy: uploaded_file_size (27 * 5242880) + current_chunk_size (1636815) = 143194575 >= total_size (137951695) ? YES

An example of what this looks like after the change, using the previous
chunk number to calculate uploaded_file_size:

chunk 26: resumable: uploaded_file_size (25 * 5242880) + current_chunk_size (6879695) = 137951695 >= total_size (137951695) ? YES
chunk 26: uppy: uploaded_file_size (25 * 5242880) + current_chunk_size (5242880) = 136314880 >= total_size (137951695) ? NO
chunk 27: uppy: uploaded_file_size (26 * 5242880) + current_chunk_size (1636815) = 137951695 >= total_size (137951695) ? YES
2021-11-15 15:08:21 +10:00
Jarek Radosz 043e0dcad7
DEV: Don't try to load admin locales in tests (#14917)
It always fails with:

```
Failed to load resource: the server responded with a status of 403 (Forbidden), url: http://localhost:60099/extra-locales/admin?v=[…]
```
2021-11-13 15:31:55 +01:00
Rafael dos Santos Silva 6645243a26
SECURITY: Disallow caching of MIME/Content-Type errors (#14907)
This will sign intermediary proxies and/or misconfigured CDNs to not
cache those error responses.
2021-11-12 15:52:25 -03:00
Martin Brennan e0be6ce1ee
DEV: Catch Mocha::ExpectationError in request specs (#14897)
Same issue as 28b00dc6fc, the
Mocha::ExpectationError inherits from Exception instead
of StandardError so RspecErrorTracker does not show the
actual failed expectation in request specs, the status of
the response is just 500 with no further detail.
2021-11-12 13:10:16 +10:00
David Taylor 13fdc979a8
DEV: Improve multisite testing (#14884)
This commit adds the RailsMultisite middleware in test mode when Rails.configuration.multisite is true. This allows for much more realistic integration testing. The `multisite_spec.rb` file is rewritten to avoid needing to simulate a middleware stack.
2021-11-11 16:44:58 +00:00
Roman Rizzi a3814b1e56
FIX: Display top posts from private categories if the user has access. (#14878)
Users viewing the top topics from the categories page should see those belonging to a private category if they have access to it.
2021-11-11 13:35:03 -03:00
Martin Brennan e4350bb966
FEATURE: Direct S3 multipart uploads for backups (#14736)
This PR introduces a new `enable_experimental_backup_uploads` site setting (default false and hidden), which when enabled alongside `enable_direct_s3_uploads` will allow for direct S3 multipart uploads of backup .tar.gz files.

To make multipart external uploads work with both the S3BackupStore and the S3Store, I've had to move several methods out of S3Store and into S3Helper, including:

* presigned_url
* create_multipart
* abort_multipart
* complete_multipart
* presign_multipart_part
* list_multipart_parts

Then, S3Store and S3BackupStore either delegate directly to S3Helper or have their own special methods to call S3Helper for these methods. FileStore.temporary_upload_path has also removed its dependence on upload_path, and can now be used interchangeably between the stores. A similar change was made in the frontend as well, moving the multipart related JS code out of ComposerUppyUpload and into a mixin of its own, so it can also be used by UppyUploadMixin.

Some changes to ExternalUploadManager had to be made here as well. The backup direct uploads do not need an Upload record made for them in the database, so they can be moved to their final S3 resting place when completing the multipart upload.

This changeset is not perfect; it introduces some special cases in UploadController to handle backups that was previously in BackupController, because UploadController is where the multipart routes are located. A subsequent pull request will pull these routes into a module or some other sharing pattern, along with hooks, so the backup controller and the upload controller (and any future controllers that may need them) can include these routes in a nicer way.
2021-11-11 08:25:31 +10:00
Bianca Nenciu 3791fbd919
FEATURE: Add read-only scope to API keys (#14856)
This commit adds a global read-only scope that can be used to create
new API keys.
2021-11-10 17:48:00 +02:00
Martin Brennan 6a68bd4825
DEV: Limit list multipart parts to 1 (#14853)
We are only using list_multipart_parts right now in the
uploads controller for multipart uploads to check if the
upload exists; thus we don't need up to 1000 parts.

Also adding a note for future explorers that list_multipart_parts
only gets 1000 parts max, and adding params for max parts
and starting parts.
2021-11-10 08:01:28 +10:00
David Taylor 65a389c3ac
FIX: Allow bulk invites to be used with DiscourseConnect (#14862)
Support for invites alongside DiscourseConnect was added in 355d51af. This commit fixes the guardian method so that the bulk invite button functionality also works.
2021-11-09 17:43:23 +00:00
David Taylor 5ac10e2e79
DEV: Update DiscourseConnect nonce errors to be more descriptive (#14858) 2021-11-09 17:39:05 +00:00
Dan Ungureanu ec3758b573
FIX: Make PostRevisor more consistent (#14841)
* FIX: Preserve field types when updating revision

When a post was edited quickly twice by the same user, the old post
revision was updated with the newest changes. To check if the change
was reverted (i.e. rename topic A to B and then back to A) a comparison
of the initial value and last value is performed. If the check passes
then the intermediary value is dismissed and only the initial value and
the last ones are preserved. Otherwise, the modification is dismissed
because the field returned to its initial value.

This used to work well for most fields, but failed for "tags" because
the field is an array and the values were transformed to strings to
perform the comparison.

* FIX: Reset last_editor_id if revision is reverted

If a post was revised and then the same revision was reverted,
last_editor_id was still set to the ID of the user who last edited the
post. This was a problem because the same person could then edit the
same post again and because it was the same user and same post, the
system attempted to update the last one (that did not exist anymore).
2021-11-09 16:29:37 +02:00
Bianca Nenciu b203e316ac
FEATURE: Add pagination to API keys page (#14777) 2021-11-09 12:18:23 +02:00
Dan Ungureanu 46fed1303f
FIX: Regression introduced in #14715 (#14842)
* FIX: Regression introduced in #14715

Wrong method names were used to get Redis keys.

* DEV: Remove more stubs
2021-11-09 17:20:09 +11:00
Martin Brennan fc98d1edfa
DEV: Improve s3:ensure_cors_rules logging (#14832) 2021-11-08 11:44:12 +10:00
Osama Sayegh e2afa1b799
FIX: Skip post validations for system revisions when author deletes post (#14824) 2021-11-08 09:33:41 +08:00
Martin Brennan 9a72a0945f
FIX: Ensure CORS rules exist for S3 using rake task (#14802)
This commit introduces a new s3:ensure_cors_rules rake task
that is run as a prerequisite to s3:upload_assets. This rake
task calls out to the S3CorsRulesets class to ensure that
the 3 relevant sets of CORS rules are applied, depending on
site settings:

* assets
* direct S3 backups
* direct S3 uploads

This works for both Global S3 settings and Database S3 settings
(the latter set directly via SiteSetting).

As it is, only one rule can be applied, which is generally
the assets rule as it is called first. This commit changes
the ensure_cors! method to be able to apply new rules as
well as the existing ones.

This commit also slightly changes the existing rules to cover
direct S3 uploads via uppy, especially multipart, which requires
some more headers.
2021-11-08 09:16:38 +10:00
Roman Rizzi 53abcd825d
FIX: Canonical URLs may be relative (#14825)
FinalDestination's follow_canonical mode used for embedded topics should work when canonical URLs are relative, as specified in [RFC 6596](https://datatracker.ietf.org/doc/html/rfc6596)
2021-11-05 14:20:14 -03:00
Blake Erickson 892e33fd93
Add `embed_url` to the api docs (#14813)
When creating a topic via the api you can pass in the `embed_url` param,
so adding this to the api docs.

See: https://github.com/discourse/discourse_api_docs/pull/26
2021-11-03 19:22:55 -06:00
Mark VanLandingham 67265a5045
DEV: Plugin instance method for push_notification_filters (#14787) 2021-11-03 12:21:33 -05:00
Joe 836c0f5ffe fix spec 2021-11-03 11:41:13 -04:00
Vinoth Kannan 53b7220638
FIX: exclude suppressed category topics in digest even if unmuted. (#14793)
Previously, suppressed category topics are included in the digest emails if the user visited that topic before and the `TopicUser` record is created with any notification level except 'muted'.
2021-11-03 12:47:09 +05:30
jbrw aec125b617
FIX: Display Instagram Oneboxes in an iframe (#14789)
We are no longer able to display the image returned by Instagram directly within a Discourse site (either in the composer, or within a cooked post within a topic), so:

- Display an image placeholder in the composer preview
- A cooked post should use an iframe to display the Instagram 'embed' content
2021-11-02 14:34:51 -04:00
Jean 8d73730c44
FEATURE: Add setting to disable notifications for topic tags edits (#14794) 2021-11-02 13:53:21 -04:00
Martin Brennan 28b00dc6fc
DEV: Output webmock errors in request specs (#14782)
* DEV: Output webmock errors in request specs

In request specs, if you had not properly mocked an external
HTTP call, you would end up with a 500 error with no further
information instead of your expected response code, with an
rspec output like this:

```
Failures:

  1) UploadsController#generate_presigned_put when the store is external generates a presigned URL and creates an external upload stub
     Failure/Error: expect(response.status).to eq(200)

       expected: 200
            got: 500

       (compared using ==)
     # ./spec/requests/uploads_controller_spec.rb:727:in `block (4 levels) in <top (required)>'
     # ./spec/rails_helper.rb:280:in `block (2 levels) in <top (required)>'
```

This is not helpful at all when you want to find what you actually
failed to mock, which is shown straight away in non-request specs.

This commit introduces a rescue_from block in the application
controller to log this error, so we have a much nicer output that
helps the developer find the issue:

```
Failures:

  1) UploadsController#generate_presigned_put when the store is external generates a presigned URL and creates an external upload stub
     Failure/Error: expect(response.status).to eq(200)

       expected: 200
            got: 500

       (compared using ==)
     # ./spec/requests/uploads_controller_spec.rb:727:in `block (4 levels) in <top (required)>'
     # ./spec/rails_helper.rb:280:in `block (2 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # WebMock::NetConnectNotAllowedError:
     #   Real HTTP connections are disabled. Unregistered request: GET https://s3-upload-bucket.s3.us-west-1.amazonaws.com/?cors with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'', 'Authorization'=>'AWS4-HMAC-SHA256 Credential=some key/20211101/us-west-1/s3/aws4_request, SignedHeaders=host;user-agent;x-amz-content-sha256;x-amz-date, Signature=test', 'Host'=>'s3-upload-bucket.s3.us-west-1.amazonaws.com', 'User-Agent'=>'aws-sdk-ruby3/3.121.2 ruby/2.7.1 x86_64-linux aws-sdk-s3/1.96.1', 'X-Amz-Content-Sha256'=>'test', 'X-Amz-Date'=>'20211101T035113Z'}
     #
     #   You can stub this request with the following snippet:
     #
     #   stub_request(:get, "https://s3-upload-bucket.s3.us-west-1.amazonaws.com/?cors").
     #     with(
     #       headers: {
     #   	  'Accept'=>'*/*',
     #   	  'Accept-Encoding'=>'',
     #   	  'Authorization'=>'AWS4-HMAC-SHA256 Credential=some key/20211101/us-west-1/s3/aws4_request, SignedHeaders=host;user-agent;x-amz-content-sha256;x-amz-date, Signature=test',
     #   	  'Host'=>'s3-upload-bucket.s3.us-west-1.amazonaws.com',
     #   	  'User-Agent'=>'aws-sdk-ruby3/3.121.2 ruby/2.7.1 x86_64-linux aws-sdk-s3/1.96.1',
     #   	  'X-Amz-Content-Sha256'=>'test',
     #   	  'X-Amz-Date'=>'20211101T035113Z'
     #       }).
     #     to_return(status: 200, body: "", headers: {})
     #
     #   registered request stubs:
     #
     #   stub_request(:head, "https://s3-upload-bucket.s3.us-west-1.amazonaws.com/")
     #
     #   ============================================================
```

* DEV: Require webmock in application controller if rails.env.test

* DEV: Rescue from StandardError and NetConnectNotAllowedError
2021-11-01 14:38:41 +08:00
Alan Guo Xiang Tan a03c48b720
FIX: Use the same mode for chinese search when indexing and querying. (#14780)
The `白名单` term becomes `名单 白名单` after it is processed by
cppjieba in :query mode. However, `白名单` is not tokenized as such by cppjieba when it
appears in a string of text. Therefore, this may lead to failed matches as
the search data generated while indexing may not contain all of the
terms generated by :query mode. We've decided to maintain parity for now
such that both indexing and querying uses the same :mix mode. This may
lead to less accurate search but our plan is to properly support CJK
search in the future.
2021-11-01 10:14:47 +08:00
Martin Brennan a059c7251f
DEV: Add tests to S3Helper.ensure_cors and move rules to class (#14767)
In preparation for adding automatic CORS rules creation
for direct S3 uploads, I am adding tests here and moving the
CORS rule definitions into a dedicated class so they are all
in the one place.

There is a problem with ensure_cors! as well -- if there is
already a CORS rule defined (presumably the asset one) then
we do nothing and do not apply the new rule. This means that
the S3BackupStore.ensure_cors method does nothing right now
if the assets rule is already defined, and it will mean the
same for any direct S3 upload rules I add for uppy. We need
to be able to add more rules, not just one.

This is not a problem on our hosting because we define the
rules at an infra level.
2021-11-01 08:23:13 +10:00
Jarek Radosz ab374fff72
DEV: Move imap_helper to spec/support directory (#14776) 2021-10-29 20:46:25 +02:00
Jarek Radosz d760c86031
DEV: Load rails_helper in pbkdf2_spec (#14775)
Fixes failing tests in CI, where this spec file was first in a batch.
2021-10-29 20:15:10 +02:00
jbrw cfc62dbace
FIX: allowed_theme_ids should not be persisted in GlobalSettings (#14756)
* FIX: allowed_theme_ids should not be persisted in GlobalSettings

It was observed that the memoized value of `GlobalSetting.allowed_theme_ids` would be persisted across requests, which could lead to unpredictable/undesired behaviours in a multisite environment.

This change moves that logic out of GlobalSettings so that the returned theme IDs are correct for the current site.

Uses get_set_cache, which ultimately uses DistributedCache, which will take care of multisite issues for us.
2021-10-29 11:46:52 -04:00
Bianca Nenciu 1c3c0f04d9
FEATURE: Pull hotlinked images in user bios (#14726) 2021-10-29 17:58:05 +03:00
Bianca Nenciu 19ef6995a8
FIX: Do not replace words in hashtags and mentions (#14760)
Watched words were replaced inside mentions and hashtags when watched
word regular expressions were enabled.
2021-10-29 17:53:09 +03:00
Bianca Nenciu cb0958fcea
FIX: Hide links to muted topics and in categories list (#14761)
* FIX: Hide links to muted topics

* FIX: Hide muted topics in categories list on mobile
2021-10-29 17:52:23 +03:00
Vinoth Kannan deee715a2c
FIX: update flair group of all members if primary group setting changed. (#14762)
Previously, if we enable the `primary_group` setting on a group then the `flair_group_id` of its' members are not affected.
2021-10-28 22:56:44 +05:30
Vinoth Kannan c62242c6b3
FIX: should not receive topic invites from ignored users. (#14746)
Previously, ignored users can send notifications by inviting the ignorer to topics or PMs.
2021-10-28 21:03:00 +05:30
Vinoth Kannan a2851b5d4c
FIX: include new tags in validation if user can create one. (#14744)
Previously, users who have enough trust level are unable to create topics with new tags if the selected category required a minimum number of tags.
2021-10-28 11:59:46 +05:30
Martin Brennan b659e94a8e
DEV: Delete vacate_legacy_prefix_backups code (#14735)
Introduced in 3037617327, we no
longer need this code, as all of the backups have been
migrated.
2021-10-28 07:53:21 +10:00
Jean 92f4cdd330
FEATURE: bypass topic bump when disable_category_edit_notifications is enabled (#14754) 2021-10-27 17:05:10 -04:00
Roman Rizzi df3eb93973
DEV: Sanitize HTML admin inputs (#14681)
* DEV: Sanitize HTML admin inputs

This PR adds on-save HTML sanitization for:

Client site settings
translation overrides
badges descriptions
user fields descriptions

I used Rails's SafeListSanitizer, which [accepts the following HTML tags and attributes](018cf54073/lib/rails/html/sanitizer.rb (L108))

* Make sure that the sanitization logic doesn't corrupt settings with special characters
2021-10-27 11:33:07 -03:00