Commit Graph

112 Commits

Author SHA1 Message Date
David Taylor 1cec333f48 REFACTOR: Introduce RouteMatcher class
This consolidates logic used to match routes in ApiKey, UserApiKey and DefaultCurrentUserProvider. This reduces duplicated logic, and will allow UserApiKeysScope to easily re-use the parameter matching logic from ApiKeyScope
2020-10-19 10:40:55 +01:00
David Taylor 1ba9b34b03
DEV: Move UserApiKey scopes to dedicated table (#10704)
This has no functional impact yet, but it is the first step in adding more granular scopes to UserApiKeys
2020-09-29 10:57:48 +01:00
Sam Saffron 44fba9463b
FEATURE: Add support for not persistent sessions
In some cases Discourse admins may opt for sessions not to persist when a
browser is closed.

This is particularly useful in healthcare and education settings where
computers are shared among multiple workers.

By default `persistent_sessions` site setting is enabled, to opt out you
must disable the site setting.
2020-09-11 15:11:24 +10:00
David Taylor 629ee5494d
FEATURE: Allow plugins to register parameter-based API routes (#10505)
Example usage:

```
add_api_parameter_route(
  method: :get,
  route: "users#bookmarks",
  format: :ics
)
```
2020-08-24 10:24:52 +01:00
Guo Xiang Tan 94fced2133
FIX: Handle PG readonly mode in `Auth::DefaultCurrentUserProvider`.
Avoid writing to the DB when PG is in readonly mode.
2020-07-21 13:44:05 +08:00
Roman Rizzi f13ec11c64
FEATURE: Add scopes to API keys (#9844)
* Added scopes UI

* Create scopes when creating a new API key

* Show scopes on the API key show route

* Apply scopes on API requests

* Extend scopes from plugins

* Add missing scopes. A mapping can be associated with multiple controller actions

* Only send scopes if the use global key option is disabled. Use the discourse plugin registry to add new scopes

* Add not null validations and index for api_key_id

* Annotate model

* DEV: Move default mappings to ApiKeyScope

* Remove unused attribute and improve UI for existing keys

* Support multiple parameters separated by a comma
2020-07-16 15:51:24 -03:00
Guo Xiang Tan d3c972c30c FIX: Rescue from readonly errors when looking up auth tokens.
Since this is rare, we don't want to check for
`Discourse.pg_readonly_mode?` on every request since we have to reach
for Redis. Instead, just rescue the error here.
2020-06-04 09:12:49 +08:00
David Taylor ff331e845a
DEV: Prevent 'previous definition' warnings for PARAMETER_API_PATTERNS 2020-05-13 12:54:28 +01:00
David Taylor 0344ad14c1
FIX: Add missing rss routes to parameter api whitelist 2020-05-12 16:08:35 +01:00
David Taylor 6230f5c554
FEATURE: Allow parameter authentication for UserApiKeys (#9742)
This refactors default_current_user_provider in a few ways:
- Introduce a generic `api_parameter_allowed?` method which checks for whitelisted routes/formats
- Only read the api_key parameter on allowed routes. It is now completely ignored on other routes (previously it would raise a 403)
- Start reading user_api_key parameter on allowed routes
- Refactor tests as end-end integration tests

A plugin API for PARAMETER_API_PATTERNS will be added soon
2020-05-12 13:35:36 +01:00
Martin Brennan fa572d3a7a
DEV: Remove all code referencing at_desktop bookmark reminders (#9650)
We have found no need for these reminder types, so we are removing the code for them.
2020-05-06 15:22:43 +10:00
Jeff Wong e3590d4ead
FEATURE: add user_session_refreshed trigger (#9412)
Trigger an event for plugins to consume when a user session is refreshed.

This allows external auth to be notified about account activity, and be
able to take action such as use oauth refresh tokens to keep oauth
tokens valid.
2020-04-14 09:32:24 -07:00
Dan Ungureanu 0653750fbf
FEATURE: Hash user API keys in the database (#9344)
The 'key' column will be dropped in a future commit.
2020-04-07 16:42:52 +03:00
Blake Erickson d04ba4b3b2
DEPRECATION: Remove support for api creds in query params (#9106)
* DEPRECATION: Remove support for api creds in query params

This commit removes support for api credentials in query params except
for a few whitelisted routes like rss/json feeds and the handle_mail
route.

Several tests were written to valid these changes, but the bulk of the
spec changes are just switching them over to use header based auth so
that they will pass without changing what they were actually testing.

Original commit that notified admins this change was coming was created
over 3 months ago: 2db2003187

* fix tests

* Also allow iCalendar feeds

Co-authored-by: Rafael dos Santos Silva <xfalcox@gmail.com>
2020-04-06 16:55:44 -06:00
Sam Saffron 25f1f23288
FEATURE: Stricter rules for user presence
Previously we would consider a user "present" and "last seen" if the
browser window was visible.

This has many edge cases, you could be considered present and around for
days just by having a window open and no screensaver on.

Instead we now also check that you either clicked, transitioned around app
or scrolled the page in the last minute in combination with window
visibility

This will lead to more reliable notifications via email and reduce load of
message bus for cases where a user walks away from the terminal
2020-03-26 17:36:52 +11:00
Jarek Radosz e950471c0f
DEV: Replace User.unstage and User#unstage API with User#unstage! (#8906)
* DEV: Replace User.unstage and User#unstage API with User#unstage!

Quoting @SamSaffron:

> User.unstage mixes concerns of both unstaging users and updating params which is fragile/surprising.
> u.unstage destroys notifications and raises a user_unstaged event prior to the user becoming unstaged and the user object being saved.

User#unstage! no longer updates user attributes and saves the object before triggering the `user_unstaged` event.

* Update one more spec

* Assign attributes after unstaging
2020-03-17 16:48:24 +01:00
Blake Erickson 269ec70ba8 DEV: Only show deprecation message for non-whitelisted requests
As another step toward fully dreprecating query parameter authentication
in API requests this change prevents an admin dashboard message from
showing up if using a whitelisted route like rss feeds or the
mail-receiver route.
2020-03-16 12:05:24 -06:00
Martin Brennan 793f39139a
FEATURE: Send notifications for time-based and At Desktop bookmark reminders (#9071)
* This PR implements the scheduling and notification system for bookmark reminders. Every 5 minutes a schedule runs to check any reminders that need to be sent before now, limited to **300** reminders at a time. Any leftover reminders will be sent in the next run. This is to avoid having to deal with fickle sidekiq and reminders in the far-flung future, which would necessitate having a background job anyway to clean up any missing `enqueue_at` reminders.

* If a reminder is sent its `reminder_at` time is cleared and the `reminder_last_sent_at` time is filled in. Notifications are only user-level notifications for now.

* All JavaScript and frontend code related to displaying the bookmark reminder notification is contained here. The reminder functionality is now re-enabled in the bookmark modal as well.

* This PR also implements the "Remind me next time I am at my desktop" bookmark reminder functionality. When the user is on a mobile device they are able to select this option. When they choose this option we set a key in Redis saying they have a pending at desktop reminder. The next time they change devices we check if the new device is desktop, and if it is we send reminders using a DistributedMutex. There is also a job to ensure consistency of these reminders in Redis (in case Redis drops the ball) and the at desktop reminders expire after 20 days.

* Also in this PR is a fix to delete all Bookmarks for a user via `UserDestroyer`
2020-03-12 10:16:00 +10:00
Sam Saffron 1f34f653bf
FIX: last ip address could point at wrong ip
Due to unicorn env object recycling request.ip could point at the wrong
ip address by the time defer block is called. This usually would happen
under load.

This also avoids keeping the entire request object as referenced by the
closure.
2020-03-11 17:42:56 +11:00
David Taylor 4c9ca24ccf
FEATURE: Hash API keys in the database (#8438)
API keys are now only visible when first created. After that, only the first four characters are stored in the database for identification, along with an sha256 hash of the full key. This makes key usage easier to audit, and ensures attackers would not have access to the live site in the event of a database leak.

This makes the merge lower risk, because we have some time to revert if needed. Once the change is confirmed to be working, we will add a second commit to drop the `key` column.
2019-12-12 11:45:00 +00:00
Joffrey JAFFEUX 0d3d2c43a0
DEV: s/\$redis/Discourse\.redis (#8431)
This commit also adds a rubocop rule to prevent global variables.
2019-12-03 10:05:53 +01:00
David Taylor a227083c1c
FEATURE: Limit the number of active sessions for a user (#8411)
If a user has more than 60 active sessions, the oldest sessions will be terminated automatically. This protects performance when logging in and when loading the list of recently used devices.
2019-11-27 12:39:31 +00:00
Blake Erickson 15f6f57cdc DEV: Add update message for an outdated mail-receiver
Previous versions of the mail-receiver used query based api credentials,
if we detect this we will show a message in the admin panel to update
the mail receiver.
2019-11-08 17:32:22 -07:00
Blake Erickson 2db2003187 DEV: Add deprecation warning of non-header based API auth
This change adds a message to the admin panel if it detects an api
requests that doesn't use the new header based authentication method.

The message is to warn people to switch to header based auth and links
to the api documention topic on meta for more info.
2019-11-07 17:06:13 -07:00
David Taylor 52c5cf33f8
FEATURE: Overhaul of admin API key system (#8284)
- Allow revoking keys without deleting them
- Auto-revoke keys after a period of no use (default 6 months)
- Allow multiple keys per user
- Allow attaching a description to each key, for easier auditing
- Log changes to keys in the staff action log
- Move all key management to one place, and improve the UI
2019-11-05 14:10:23 +00:00
Krzysztof Kotlarek 427d54b2b0 DEV: Upgrading Discourse to Zeitwerk (#8098)
Zeitwerk simplifies working with dependencies in dev and makes it easier reloading class chains. 

We no longer need to use Rails "require_dependency" anywhere and instead can just use standard 
Ruby patterns to require files.

This is a far reaching change and we expect some followups here.
2019-10-02 14:01:53 +10:00
Sam Saffron dc9110cc43 FEATURE: track date api key was last used
Start tracking the date an api key was last used. This has already been
the case for user_api_keys.

This information can provide us with the ability to automatically expire
unused api keys after N days.
2019-09-03 18:11:30 +10:00
David Taylor af86cf46dc FEATURE: Allow API requests to specify the `DISCOURSE_VISIBLE` header
This allows API consumers to automatically update the user's last_seen time. The default behaviour is unchanged.
2019-04-15 17:34:34 +01:00
Leo McArdle b084750953 FIX: don't redirect incorrectly after full screen login (#7170)
Fixes two issues:
1. Redirecting to an external origin's path after login did not work
2. User would be erroneously redirected to the external origin after logout

https://meta.discourse.org/t/109755
2019-03-19 12:39:13 +00:00
Blake Erickson 7ac394f51f FIX: prevent mixed api auth headers & query params
When using the api and you provide an http header based api key any other
auth based information (username, external_id, or user_id) passed in as
query params will not be used and vice versa.

Followup to f03b293e6a
2019-03-12 17:33:21 -06:00
Blake Erickson f03b293e6a
FEATURE: Header based auth for API requests (#7129)
Now you can also make authenticated API requests by passing the
`api_key` and `api_username` in the HTTP header instead of query params.

The new header values are: `Api-key` and `Api-Username`.

Here is an example in cURL:

``` text
curl -i -sS -X POST "http://127.0.0.1:3000/categories" \
  -H "Content-Type: multipart/form-data;" \
  -H "Api-Key: 7aa202bec1ff70563bc0a3d102feac0a7dd2af96b5b772a9feaf27485f9d31a2" \
  -H "Api-Username: system" \
  -F "name=7c1c0ed93583cba7124b745d1bd56b32" \
  -F "color=49d9e9" \
  -F "text_color=f0fcfd"
```

There is also support for `Api-User-Id` and `Api-User-External-Id`
instead of specifying the username along with the key.
2019-03-08 09:13:31 -07:00
Guo Xiang Tan d32900292d FIX: Don't update `User#last_seen_at` when PG is in readonly take 3. 2019-01-22 18:07:48 +08:00
Guo Xiang Tan 3c6a8a2bb1 Partially revert 4466fcf1bc. 2019-01-21 15:41:01 +08:00
Guo Xiang Tan 4466fcf1bc FIX: Don't update `User#last_seen_at` when PG is readonly take 2. 2019-01-21 13:49:08 +08:00
Guo Xiang Tan c732ae9ca9 FIX: Don't update `User#last_seen_at` when PG is in readonly. 2019-01-21 13:29:29 +08:00
Régis Hanol 182b34243d
FIX: opts is a hash in 'log_on_user'
cc @nbianca
2018-11-12 16:00:12 +01:00
Bianca Nenciu 5af9a69a3b FIX: Do not check for suspicious login when impersonating. (#6534)
* FIX: Do not check for suspicious login when impersonating.

* DEV: Add 'impersonate' parameter to log_on_user.
2018-11-12 15:34:12 +01:00
Régis Hanol d17c8df926 Only check for suspicious login for staff members 2018-10-26 00:29:28 +02:00
David Taylor 56e0f47bcd FIX: Do not update `last_seen` for API access
This regressed in 2dc3a50. I have now added tests for the behavior.
2018-10-25 13:38:57 +01:00
Guo Xiang Tan d1af89e3b3 DEV: Extract global admin api rate limiting into a dedicated method.
* We have a use case for overriding the rate limiting logic in a
  plugin.
2018-09-04 16:37:54 +08:00
Guo Xiang Tan 3b337bfc6b Revert "FIX: Don't rate limit admin and staff constraints when matching routes."
This reverts commit 651b50b1a1.
2018-09-04 14:27:21 +08:00
Guo Xiang Tan 651b50b1a1 FIX: Don't rate limit admin and staff constraints when matching routes.
* When an error is raised when checking route constraints, we
  can only return true/false which either lets the request
  through or return a 404 error. Therefore, we just skip
  rate limiting here and let the controller handle the
  rate limiting.
2018-09-04 13:52:58 +08:00
Sam 272de95175 FIX: client duplicate registration should be cleaned up
If for any reason we are unable to correct client id on a user api key
invalidate old keys for client/user
2018-08-22 12:56:49 +10:00
Bianca Nenciu 860c1c3dcd FEATURE: Automatically expire keys if not used for a configurable amount of time. (#6264) 2018-08-20 17:36:14 +02:00
David Taylor 2dc3a50dac FIX: Do not update `last seen` time for suspended users 2018-07-18 16:04:57 +01:00
Régis Hanol 2cf6fb7359 FIX: always unstage users when they log in 2018-05-13 17:00:02 +02:00
Sam 3d6dc764be needed to remove legacy from a few more spots 2018-05-04 11:12:01 +10:00
Robin Ward c75fd34328 Allow Discourse installs to name the token cookie 2018-03-13 16:48:40 -04:00
Sam 0134e41286 FEATURE: detect when client thinks user is logged on but is not
This cleans up an error condition where UI thinks a user is logged on
but the user is not. If this happens user will be prompted to refresh.
2018-03-06 16:49:31 +11:00
Sam a3c7ee09b6 FIX: ruby bench not working properly
- Remove thin which is no longer supported
- Bypass admin api rate limiting in profile environment
- Admin password was too short
- Run by default in concurrency 1 mode
- A skip bundle assets flag to speed up local testing
2018-02-19 11:37:16 +11:00