Merge remote-tracking branch 'remotes/origin/develop' into ostatus-controller-no-auth-check-on-non-federating-instances

# Conflicts:
#	lib/pleroma/web/feed/user_controller.ex
#	lib/pleroma/web/o_status/o_status_controller.ex
#	lib/pleroma/web/router.ex
#	lib/pleroma/web/static_fe/static_fe_controller.ex
This commit is contained in:
Ivan Tashkinov 2020-10-17 13:12:39 +03:00
commit 049ece1ef3
677 changed files with 1669 additions and 800 deletions

View file

@ -25,7 +25,7 @@
# #
# If you create your own checks, you must specify the source files for # If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis. # them here, so they can be loaded by Credo before running the analysis.
requires: [], requires: ["./test/credo/check/consistency/file_location.ex"],
# #
# Credo automatically checks for updates, like e.g. Hex does. # Credo automatically checks for updates, like e.g. Hex does.
# You can disable this behaviour below: # You can disable this behaviour below:
@ -71,7 +71,6 @@
# set this value to 0 (zero). # set this value to 0 (zero).
{Credo.Check.Design.TagTODO, exit_status: 0}, {Credo.Check.Design.TagTODO, exit_status: 0},
{Credo.Check.Design.TagFIXME, exit_status: 0}, {Credo.Check.Design.TagFIXME, exit_status: 0},
{Credo.Check.Readability.FunctionNames}, {Credo.Check.Readability.FunctionNames},
{Credo.Check.Readability.LargeNumbers}, {Credo.Check.Readability.LargeNumbers},
{Credo.Check.Readability.MaxLineLength, priority: :low, max_length: 100}, {Credo.Check.Readability.MaxLineLength, priority: :low, max_length: 100},
@ -91,7 +90,6 @@
{Credo.Check.Readability.VariableNames}, {Credo.Check.Readability.VariableNames},
{Credo.Check.Readability.Semicolons}, {Credo.Check.Readability.Semicolons},
{Credo.Check.Readability.SpaceAfterCommas}, {Credo.Check.Readability.SpaceAfterCommas},
{Credo.Check.Refactor.DoubleBooleanNegation}, {Credo.Check.Refactor.DoubleBooleanNegation},
{Credo.Check.Refactor.CondStatements}, {Credo.Check.Refactor.CondStatements},
{Credo.Check.Refactor.CyclomaticComplexity}, {Credo.Check.Refactor.CyclomaticComplexity},
@ -102,7 +100,6 @@
{Credo.Check.Refactor.Nesting}, {Credo.Check.Refactor.Nesting},
{Credo.Check.Refactor.PipeChainStart}, {Credo.Check.Refactor.PipeChainStart},
{Credo.Check.Refactor.UnlessWithElse}, {Credo.Check.Refactor.UnlessWithElse},
{Credo.Check.Warning.BoolOperationOnSameValues}, {Credo.Check.Warning.BoolOperationOnSameValues},
{Credo.Check.Warning.IExPry}, {Credo.Check.Warning.IExPry},
{Credo.Check.Warning.IoInspect}, {Credo.Check.Warning.IoInspect},
@ -131,6 +128,7 @@
# Custom checks can be created using `mix credo.gen.check`. # Custom checks can be created using `mix credo.gen.check`.
# #
{Credo.Check.Consistency.FileLocation}
] ]
} }
] ]

2
.gitignore vendored
View file

@ -27,6 +27,8 @@ erl_crash.dump
# variables. # variables.
/config/*.secret.exs /config/*.secret.exs
/config/generated_config.exs /config/generated_config.exs
/config/*.env
# Database setup file, some may forget to delete it # Database setup file, some may forget to delete it
/config/setup_db.psql /config/setup_db.psql

View file

@ -25,6 +25,8 @@ before_script:
- apt-get update && apt-get install -y cmake - apt-get update && apt-get install -y cmake
- mix local.hex --force - mix local.hex --force
- mix local.rebar --force - mix local.rebar --force
- apt-get -qq update
- apt-get install -y libmagic-dev
build: build:
stage: build stage: build

View file

@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Changed ### Changed
- **Breaking** Requires `libmagic` (or `file`) to guess file types.
- **Breaking:** Pleroma Admin API: emoji packs and files routes changed. - **Breaking:** Pleroma Admin API: emoji packs and files routes changed.
- **Breaking:** Sensitive/NSFW statuses no longer disable link previews. - **Breaking:** Sensitive/NSFW statuses no longer disable link previews.
- Search: Users are now findable by their urls. - Search: Users are now findable by their urls.

View file

@ -677,7 +677,7 @@
config :pleroma, Pleroma.Workers.PurgeExpiredActivity, enabled: true, min_lifetime: 600 config :pleroma, Pleroma.Workers.PurgeExpiredActivity, enabled: true, min_lifetime: 600
config :pleroma, Pleroma.Plugs.RemoteIp, config :pleroma, Pleroma.Web.Plugs.RemoteIp,
enabled: true, enabled: true,
headers: ["x-forwarded-for"], headers: ["x-forwarded-for"],
proxies: [], proxies: [],
@ -802,6 +802,8 @@
timeout: 300_000 timeout: 300_000
] ]
config :pleroma, :majic_pool, size: 2
private_instance? = :if_instance_is_private private_instance? = :if_instance_is_private
config :pleroma, :restrict_unauthenticated, config :pleroma, :restrict_unauthenticated,

View file

@ -3250,10 +3250,10 @@
}, },
%{ %{
group: :pleroma, group: :pleroma,
key: Pleroma.Plugs.RemoteIp, key: Pleroma.Web.Plugs.RemoteIp,
type: :group, type: :group,
description: """ description: """
`Pleroma.Plugs.RemoteIp` is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration. `Pleroma.Web.Plugs.RemoteIp` is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration.
**If your instance is not behind at least one reverse proxy, you should not enable this plug.** **If your instance is not behind at least one reverse proxy, you should not enable this plug.**
""", """,
children: [ children: [
@ -3708,5 +3708,19 @@
] ]
} }
] ]
},
%{
group: :pleroma,
key: :majic_pool,
type: :group,
description: "Majic/libmagic configuration",
children: [
%{
key: :size,
type: :integer,
description: "Number of majic workers to start.",
suggestions: [2]
}
]
} }
] ]

View file

@ -113,7 +113,7 @@
config :pleroma, Pleroma.Emails.NewUsersDigestEmail, enabled: true config :pleroma, Pleroma.Emails.NewUsersDigestEmail, enabled: true
config :pleroma, Pleroma.Plugs.RemoteIp, enabled: false config :pleroma, Pleroma.Web.Plugs.RemoteIp, enabled: false
config :pleroma, Pleroma.Web.ApiSpec.CastAndValidate, strict: true config :pleroma, Pleroma.Web.ApiSpec.CastAndValidate, strict: true

View file

@ -1,6 +1,7 @@
{ {
"skip_files": [ "skip_files": [
"test/support", "test/support",
"lib/mix/tasks/pleroma/benchmark.ex" "lib/mix/tasks/pleroma/benchmark.ex",
"lib/credo/check/consistency/file_location.ex"
] ]
} }

View file

@ -37,3 +37,8 @@ If any of the options are left unspecified, you will be prompted interactively.
- `--static-dir <path>` - the directory custom public files should be read from (custom emojis, frontend bundle overrides, robots.txt, etc.) - `--static-dir <path>` - the directory custom public files should be read from (custom emojis, frontend bundle overrides, robots.txt, etc.)
- `--listen-ip <ip>` - the ip the app should listen to, defaults to 127.0.0.1 - `--listen-ip <ip>` - the ip the app should listen to, defaults to 127.0.0.1
- `--listen-port <port>` - the port the app should listen to, defaults to 4000 - `--listen-port <port>` - the port the app should listen to, defaults to 4000
- `--strip-uploads <Y|N>` - use ExifTool to strip uploads of sensitive location data
- `--anonymize-uploads <Y|N>` - randomize uploaded filenames
- `--dedupe-uploads <Y|N>` - store files based on their hash to reduce data storage requirements if duplicates are uploaded with different filenames
- `--skip-release-env` - skip generation the release environment file
- `--release-env-file` - release environment file path

View file

@ -0,0 +1,9 @@
# Generate release environment file
```sh tab="OTP"
./bin/pleroma_ctl release_env gen
```
```sh tab="From Source"
mix pleroma.release_env gen
```

View file

@ -14,7 +14,7 @@
2. Stop the Pleroma service. 2. Stop the Pleroma service.
3. Go to the working directory of Pleroma (default is `/opt/pleroma`) 3. Go to the working directory of Pleroma (default is `/opt/pleroma`)
4. Copy the above mentioned files back to their original position. 4. Copy the above mentioned files back to their original position.
5. Drop the existing database if restoring in-place. `sudo -Hu postgres psql -c 'DROP DATABASE <pleroma_db>;'` 5. Drop the existing database and user if restoring in-place. `sudo -Hu postgres psql -c 'DROP DATABASE <pleroma_db>;';` `sudo -Hu postgres psql -c 'DROP USER <pleroma_db>;'`
6. Restore the database schema and pleroma postgres role the with the original `setup_db.psql` if you have it: `sudo -Hu postgres psql -f config/setup_db.psql`. 6. Restore the database schema and pleroma postgres role the with the original `setup_db.psql` if you have it: `sudo -Hu postgres psql -f config/setup_db.psql`.
Alternatively, run the `mix pleroma.instance gen` task again. You can ignore most of the questions, but make the database user, name, and password the same as found in your backup of `config/prod.secret.exs`. Then run the restoration of the pleroma role and schema with of the generated `config/setup_db.psql` as instructed above. You may delete the `config/generated_config.exs` file as it is not needed. Alternatively, run the `mix pleroma.instance gen` task again. You can ignore most of the questions, but make the database user, name, and password the same as found in your backup of `config/prod.secret.exs`. Then run the restoration of the pleroma role and schema with of the generated `config/setup_db.psql` as instructed above. You may delete the `config/generated_config.exs` file as it is not needed.
@ -23,6 +23,7 @@
8. If you installed a newer Pleroma version, you should run `mix ecto.migrate`[^1]. This task performs database migrations, if there were any. 8. If you installed a newer Pleroma version, you should run `mix ecto.migrate`[^1]. This task performs database migrations, if there were any.
9. Restart the Pleroma service. 9. Restart the Pleroma service.
10. Run `sudo -Hu postgres vacuumdb --all --analyze-in-stages`. This will quickly generate the statistics so that postgres can properly plan queries. 10. Run `sudo -Hu postgres vacuumdb --all --analyze-in-stages`. This will quickly generate the statistics so that postgres can properly plan queries.
11. If setting up on a new server configure Nginx by using the `installation/pleroma.nginx` config sample or reference the Pleroma installation guide for your OS which contains the Nginx configuration instructions.
[^1]: Prefix with `MIX_ENV=prod` to run it using the production config file. [^1]: Prefix with `MIX_ENV=prod` to run it using the production config file.
@ -35,6 +36,6 @@
3. Disable pleroma from systemd `systemctl disable pleroma` 3. Disable pleroma from systemd `systemctl disable pleroma`
4. Remove the files and folders you created during installation (see installation guide). This includes the pleroma, nginx and systemd files and folders. 4. Remove the files and folders you created during installation (see installation guide). This includes the pleroma, nginx and systemd files and folders.
5. Reload nginx now that the configuration is removed `systemctl reload nginx` 5. Reload nginx now that the configuration is removed `systemctl reload nginx`
6. Remove the database and database user `sudo -Hu postgres psql -c 'DROP DATABASE <pleroma_db>;';` `sudo -Hu postgres psql -c 'DROP USER <pleroma_db>;';` 6. Remove the database and database user `sudo -Hu postgres psql -c 'DROP DATABASE <pleroma_db>;';` `sudo -Hu postgres psql -c 'DROP USER <pleroma_db>;'`
7. Remove the system user `userdel pleroma` 7. Remove the system user `userdel pleroma`
8. Remove the dependencies that you don't need anymore (see installation guide). Make sure you don't remove packages that are still needed for other software that you have running! 8. Remove the dependencies that you don't need anymore (see installation guide). Make sure you don't remove packages that are still needed for other software that you have running!

View file

@ -71,7 +71,7 @@ Feel free to contact us to be added to this list!
### Indigenous ### Indigenous
- Homepage: <https://indigenous.realize.be/> - Homepage: <https://indigenous.realize.be/>
- Source Code: <https://github.com/swentel/indigenous-android/> - Source Code: <https://github.com/swentel/indigenous-android/>
- Contact: [@realize.be@realize.be](@realize.be@realize.be) - Contact: [@swentel@realize.be](https://realize.be)
- Platforms: Android - Platforms: Android
- Features: No Streaming - Features: No Streaming

View file

@ -113,7 +113,7 @@ To add configuration to your config file, you can copy it from the base config.
* `Pleroma.Web.ActivityPub.MRF.MentionPolicy`: Drops posts mentioning configurable users. (See [`:mrf_mention`](#mrf_mention)). * `Pleroma.Web.ActivityPub.MRF.MentionPolicy`: Drops posts mentioning configurable users. (See [`:mrf_mention`](#mrf_mention)).
* `Pleroma.Web.ActivityPub.MRF.VocabularyPolicy`: Restricts activities to a configured set of vocabulary. (See [`:mrf_vocabulary`](#mrf_vocabulary)). * `Pleroma.Web.ActivityPub.MRF.VocabularyPolicy`: Restricts activities to a configured set of vocabulary. (See [`:mrf_vocabulary`](#mrf_vocabulary)).
* `Pleroma.Web.ActivityPub.MRF.ObjectAgePolicy`: Rejects or delists posts based on their age when received. (See [`:mrf_object_age`](#mrf_object_age)). * `Pleroma.Web.ActivityPub.MRF.ObjectAgePolicy`: Rejects or delists posts based on their age when received. (See [`:mrf_object_age`](#mrf_object_age)).
* `Pleroma.Web.ActivityPub.MRF.ActivityExpirationPolicy`: Sets a default expiration on all posts made by users of the local instance. Requires `Pleroma.ActivityExpiration` to be enabled for processing the scheduled delections. * `Pleroma.Web.ActivityPub.MRF.ActivityExpirationPolicy`: Sets a default expiration on all posts made by users of the local instance. Requires `Pleroma.Workers.PurgeExpiredActivity` to be enabled for processing the scheduled delections.
* `Pleroma.Web.ActivityPub.MRF.ForceBotUnlistedPolicy`: Makes all bot posts to disappear from public timelines. * `Pleroma.Web.ActivityPub.MRF.ForceBotUnlistedPolicy`: Makes all bot posts to disappear from public timelines.
* `transparency`: Make the content of your Message Rewrite Facility settings public (via nodeinfo). * `transparency`: Make the content of your Message Rewrite Facility settings public (via nodeinfo).
* `transparency_exclusions`: Exclude specific instance names from MRF transparency. The use of the exclusions feature will be disclosed in nodeinfo as a boolean value. * `transparency_exclusions`: Exclude specific instance names from MRF transparency. The use of the exclusions feature will be disclosed in nodeinfo as a boolean value.
@ -219,12 +219,6 @@ config :pleroma, :mrf_user_allowlist, %{
* `total_user_limit`: the number of scheduled activities a user is allowed to create in total (Default: `300`) * `total_user_limit`: the number of scheduled activities a user is allowed to create in total (Default: `300`)
* `enabled`: whether scheduled activities are sent to the job queue to be executed * `enabled`: whether scheduled activities are sent to the job queue to be executed
## Pleroma.ActivityExpiration
Enables the worker which processes posts scheduled for deletion. Pinned posts are exempt from expiration.
* `enabled`: whether expired activities will be sent to the job queue to be deleted
## FedSockets ## FedSockets
FedSockets is an experimental feature allowing for Pleroma backends to federate using a persistant websocket connection as opposed to making each federation a seperate http connection. This feature is currently off by default. It is configurable throught he following options. FedSockets is an experimental feature allowing for Pleroma backends to federate using a persistant websocket connection as opposed to making each federation a seperate http connection. This feature is currently off by default. It is configurable throught he following options.
@ -416,12 +410,12 @@ This will make Pleroma listen on `127.0.0.1` port `8080` and generate urls start
* ``referrer_policy``: The referrer policy to use, either `"same-origin"` or `"no-referrer"`. * ``referrer_policy``: The referrer policy to use, either `"same-origin"` or `"no-referrer"`.
* ``report_uri``: Adds the specified url to `report-uri` and `report-to` group in CSP header. * ``report_uri``: Adds the specified url to `report-uri` and `report-to` group in CSP header.
### Pleroma.Plugs.RemoteIp ### Pleroma.Web.Plugs.RemoteIp
!!! warning !!! warning
If your instance is not behind at least one reverse proxy, you should not enable this plug. If your instance is not behind at least one reverse proxy, you should not enable this plug.
`Pleroma.Plugs.RemoteIp` is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration. `Pleroma.Web.Plugs.RemoteIp` is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration.
Available options: Available options:
@ -434,7 +428,7 @@ Available options:
### :rate_limit ### :rate_limit
!!! note !!! note
If your instance is behind a reverse proxy ensure [`Pleroma.Plugs.RemoteIp`](#pleroma-plugs-remoteip) is enabled (it is enabled by default). If your instance is behind a reverse proxy ensure [`Pleroma.Web.Plugs.RemoteIp`](#pleroma-plugs-remoteip) is enabled (it is enabled by default).
A keyword list of rate limiters where a key is a limiter name and value is the limiter configuration. The basic configuration is a tuple where: A keyword list of rate limiters where a key is a limiter name and value is the limiter configuration. The basic configuration is a tuple where:

View file

@ -6,7 +6,7 @@ This document contains notes and guidelines for Pleroma developers.
* Pleroma supports hierarchical OAuth scopes, just like Mastodon but with added granularity of admin scopes. For a reference, see [Mastodon OAuth scopes](https://docs.joinmastodon.org/api/oauth-scopes/). * Pleroma supports hierarchical OAuth scopes, just like Mastodon but with added granularity of admin scopes. For a reference, see [Mastodon OAuth scopes](https://docs.joinmastodon.org/api/oauth-scopes/).
* It is important to either define OAuth scope restrictions or explicitly mark OAuth scope check as skipped, for every controller action. To define scopes, call `plug(Pleroma.Plugs.OAuthScopesPlug, %{scopes: [...]})`. To explicitly set OAuth scopes check skipped, call `plug(:skip_plug, Pleroma.Plugs.OAuthScopesPlug <when ...>)`. * It is important to either define OAuth scope restrictions or explicitly mark OAuth scope check as skipped, for every controller action. To define scopes, call `plug(Pleroma.Web.Plugs.OAuthScopesPlug, %{scopes: [...]})`. To explicitly set OAuth scopes check skipped, call `plug(:skip_plug, Pleroma.Web.Plugs.OAuthScopesPlug <when ...>)`.
* In controllers, `use Pleroma.Web, :controller` will result in `action/2` (see `Pleroma.Web.controller/0` for definition) be called prior to actual controller action, and it'll perform security / privacy checks before passing control to actual controller action. * In controllers, `use Pleroma.Web, :controller` will result in `action/2` (see `Pleroma.Web.controller/0` for definition) be called prior to actual controller action, and it'll perform security / privacy checks before passing control to actual controller action.
@ -16,7 +16,7 @@ This document contains notes and guidelines for Pleroma developers.
## [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) ## [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization)
* With HTTP Basic Auth, OAuth scopes check is _not_ performed for any action (since password is provided during the auth, requester is able to obtain a token with full permissions anyways). `Pleroma.Plugs.AuthenticationPlug` and `Pleroma.Plugs.LegacyAuthenticationPlug` both call `Pleroma.Plugs.OAuthScopesPlug.skip_plug(conn)` when password is provided. * With HTTP Basic Auth, OAuth scopes check is _not_ performed for any action (since password is provided during the auth, requester is able to obtain a token with full permissions anyways). `Pleroma.Web.Plugs.AuthenticationPlug` and `Pleroma.Web.Plugs.LegacyAuthenticationPlug` both call `Pleroma.Web.Plugs.OAuthScopesPlug.skip_plug(conn)` when password is provided.
## Auth-related configuration, OAuth consumer mode etc. ## Auth-related configuration, OAuth consumer mode etc.

View file

@ -13,6 +13,7 @@ It assumes that you have administrative rights, either as root or a user with [s
* `erlang-parsetools` * `erlang-parsetools`
* `erlang-xmerl` * `erlang-xmerl`
* `git` * `git`
* `file-dev`
* Development Tools * Development Tools
* `cmake` * `cmake`
@ -42,7 +43,7 @@ sudo apk upgrade
* Install some tools, which are needed later: * Install some tools, which are needed later:
```shell ```shell
sudo apk add git build-base cmake sudo apk add git build-base cmake file-dev
``` ```
### Install Elixir and Erlang ### Install Elixir and Erlang

View file

@ -10,6 +10,7 @@ This guide will assume that you have administrative rights, either as root or a
* `git` * `git`
* `base-devel` * `base-devel`
* `cmake` * `cmake`
* `file`
#### Optional packages used in this guide #### Optional packages used in this guide
@ -30,7 +31,7 @@ sudo pacman -Syu
* Install some of the above mentioned programs: * Install some of the above mentioned programs:
```shell ```shell
sudo pacman -S git base-devel elixir cmake sudo pacman -S git base-devel elixir cmake file
``` ```
### Install PostgreSQL ### Install PostgreSQL

View file

@ -10,6 +10,7 @@ This guide will assume you are on Debian Stretch. This guide should also work wi
* `elixir` (1.8+, Follow the guide to install from the Erlang Solutions repo or use [asdf](https://github.com/asdf-vm/asdf) as the pleroma user) * `elixir` (1.8+, Follow the guide to install from the Erlang Solutions repo or use [asdf](https://github.com/asdf-vm/asdf) as the pleroma user)
* `erlang-dev` * `erlang-dev`
* `erlang-nox` * `erlang-nox`
* `libmagic-dev`
* `git` * `git`
* `build-essential` * `build-essential`
* `cmake` * `cmake`
@ -34,7 +35,7 @@ sudo apt full-upgrade
* Install some of the above mentioned programs: * Install some of the above mentioned programs:
```shell ```shell
sudo apt install git build-essential postgresql postgresql-contrib cmake sudo apt install git build-essential postgresql postgresql-contrib cmake libmagic-devel
``` ```
### Install Elixir and Erlang ### Install Elixir and Erlang
@ -100,6 +101,7 @@ sudo -Hu pleroma mix deps.get
mv config/{generated_config.exs,prod.secret.exs} mv config/{generated_config.exs,prod.secret.exs}
``` ```
* The previous command creates also the file `config/setup_db.psql`, with which you can create the database: * The previous command creates also the file `config/setup_db.psql`, with which you can create the database:
```shell ```shell
@ -180,6 +182,7 @@ sudo cp /opt/pleroma/installation/pleroma.service /etc/systemd/system/pleroma.se
``` ```
* Edit the service file and make sure that all paths fit your installation * Edit the service file and make sure that all paths fit your installation
* Check that `EnvironmentFile` contains the correct path to the env file. Or generate the env file: `sudo -Hu pleroma mix pleroma.release_env gen`
* Enable and start `pleroma.service`: * Enable and start `pleroma.service`:
```shell ```shell

View file

@ -17,6 +17,7 @@
- `git` - `git`
- `build-essential` - `build-essential`
- `cmake` - `cmake`
- `libmagic-dev`
#### このガイドで利用している追加パッケージ #### このガイドで利用している追加パッケージ
@ -36,7 +37,7 @@ sudo apt full-upgrade
* 上記に挙げたパッケージをインストールしておきます。 * 上記に挙げたパッケージをインストールしておきます。
``` ```
sudo apt install git build-essential postgresql postgresql-contrib cmake ffmpeg imagemagick sudo apt install git build-essential postgresql postgresql-contrib cmake ffmpeg imagemagick libmagic-dev
``` ```
### ElixirとErlangをインストールします ### ElixirとErlangをインストールします

View file

@ -29,6 +29,7 @@ Gentoo quite pointedly does not come with a cron daemon installed, and as such i
* `dev-lang/elixir` * `dev-lang/elixir`
* `dev-vcs/git` * `dev-vcs/git`
* `dev-util/cmake` * `dev-util/cmake`
* `sys-apps/file`
#### Optional ebuilds used in this guide #### Optional ebuilds used in this guide
@ -50,7 +51,7 @@ Gentoo quite pointedly does not come with a cron daemon installed, and as such i
* Emerge all required the required and suggested software in one go: * Emerge all required the required and suggested software in one go:
```shell ```shell
# emerge --ask dev-db/postgresql dev-lang/elixir dev-vcs/git www-servers/nginx app-crypt/certbot app-crypt/certbot-nginx dev-util/cmake # emerge --ask dev-db/postgresql dev-lang/elixir dev-vcs/git www-servers/nginx app-crypt/certbot app-crypt/certbot-nginx dev-util/cmake sys-apps/file
``` ```
If you would not like to install the optional packages, remove them from this line. If you would not like to install the optional packages, remove them from this line.

View file

@ -27,17 +27,18 @@ Other than things bundled in the OTP release Pleroma depends on:
* PostgreSQL (also utilizes extensions in postgresql-contrib) * PostgreSQL (also utilizes extensions in postgresql-contrib)
* nginx (could be swapped with another reverse proxy but this guide covers only it) * nginx (could be swapped with another reverse proxy but this guide covers only it)
* certbot (for Let's Encrypt certificates, could be swapped with another ACME client, but this guide covers only it) * certbot (for Let's Encrypt certificates, could be swapped with another ACME client, but this guide covers only it)
* libmagic/file
=== "Alpine" === "Alpine"
``` ```
echo "http://nl.alpinelinux.org/alpine/latest-stable/community" >> /etc/apk/repositories echo "http://nl.alpinelinux.org/alpine/latest-stable/community" >> /etc/apk/repositories
apk update apk update
apk add curl unzip ncurses postgresql postgresql-contrib nginx certbot apk add curl unzip ncurses postgresql postgresql-contrib nginx certbot file-dev
``` ```
=== "Debian/Ubuntu" === "Debian/Ubuntu"
``` ```
apt install curl unzip libncurses5 postgresql postgresql-contrib nginx certbot apt install curl unzip libncurses5 postgresql postgresql-contrib nginx certbot libmagic-dev
``` ```
### Installing optional packages ### Installing optional packages
@ -148,6 +149,9 @@ chown -R pleroma /etc/pleroma
# Run the config generator # Run the config generator
su pleroma -s $SHELL -lc "./bin/pleroma_ctl instance gen --output /etc/pleroma/config.exs --output-psql /tmp/setup_db.psql" su pleroma -s $SHELL -lc "./bin/pleroma_ctl instance gen --output /etc/pleroma/config.exs --output-psql /tmp/setup_db.psql"
# Run the environment file generator.
su pleroma -s $SHELL -lc "./bin/pleroma_ctl release_env gen"
# Create the postgres database # Create the postgres database
su postgres -s $SHELL -lc "psql -f /tmp/setup_db.psql" su postgres -s $SHELL -lc "psql -f /tmp/setup_db.psql"
@ -158,7 +162,7 @@ su pleroma -s $SHELL -lc "./bin/pleroma_ctl migrate"
# su pleroma -s $SHELL -lc "./bin/pleroma_ctl migrate --migrations-path priv/repo/optional_migrations/rum_indexing/" # su pleroma -s $SHELL -lc "./bin/pleroma_ctl migrate --migrations-path priv/repo/optional_migrations/rum_indexing/"
# Start the instance to verify that everything is working as expected # Start the instance to verify that everything is working as expected
su pleroma -s $SHELL -lc "./bin/pleroma daemon" su pleroma -s $SHELL -lc "export $(cat /opt/pleroma/config/pleroma.env); ./bin/pleroma daemon"
# Wait for about 20 seconds and query the instance endpoint, if it shows your uri, name and email correctly, you are configured correctly # Wait for about 20 seconds and query the instance endpoint, if it shows your uri, name and email correctly, you are configured correctly
sleep 20 && curl http://localhost:4000/api/v1/instance sleep 20 && curl http://localhost:4000/api/v1/instance
@ -310,4 +314,3 @@ This will create an account withe the username of 'joeuser' with the email addre
## Questions ## Questions
Questions about the installation or didnt it work as it should be, ask in [#pleroma:matrix.org](https://matrix.heldscal.la/#/room/#freenode_#pleroma:matrix.org) or IRC Channel **#pleroma** on **Freenode**. Questions about the installation or didnt it work as it should be, ask in [#pleroma:matrix.org](https://matrix.heldscal.la/#/room/#freenode_#pleroma:matrix.org) or IRC Channel **#pleroma** on **Freenode**.

View file

@ -8,6 +8,7 @@ pidfile="/var/run/pleroma.pid"
directory=/opt/pleroma directory=/opt/pleroma
healthcheck_delay=60 healthcheck_delay=60
healthcheck_timer=30 healthcheck_timer=30
export $(cat /opt/pleroma/config/pleroma.env)
: ${pleroma_port:-4000} : ${pleroma_port:-4000}

View file

@ -17,6 +17,8 @@ Environment="MIX_ENV=prod"
Environment="HOME=/var/lib/pleroma" Environment="HOME=/var/lib/pleroma"
; Path to the folder containing the Pleroma installation. ; Path to the folder containing the Pleroma installation.
WorkingDirectory=/opt/pleroma WorkingDirectory=/opt/pleroma
; Path to the environment file. the file contains RELEASE_COOKIE and etc
EnvironmentFile=/opt/pleroma/config/pleroma.env
; Path to the Mix binary. ; Path to the Mix binary.
ExecStart=/usr/bin/mix phx.server ExecStart=/usr/bin/mix phx.server

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.CountStatuses do defmodule Mix.Tasks.Pleroma.CountStatuses do
@shortdoc "Re-counts statuses for all users" @shortdoc "Re-counts statuses for all users"

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.Digest do defmodule Mix.Tasks.Pleroma.Digest do
use Mix.Task use Mix.Task
import Mix.Pleroma import Mix.Pleroma

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.Docs do defmodule Mix.Tasks.Pleroma.Docs do
use Mix.Task use Mix.Task
import Mix.Pleroma import Mix.Pleroma

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.Email do defmodule Mix.Tasks.Pleroma.Email do
use Mix.Task use Mix.Task
import Mix.Pleroma import Mix.Pleroma

View file

@ -33,7 +33,12 @@ def run(["gen" | rest]) do
uploads_dir: :string, uploads_dir: :string,
static_dir: :string, static_dir: :string,
listen_ip: :string, listen_ip: :string,
listen_port: :string listen_port: :string,
strip_uploads: :string,
anonymize_uploads: :string,
dedupe_uploads: :string,
skip_release_env: :boolean,
release_env_file: :string
], ],
aliases: [ aliases: [
o: :output, o: :output,
@ -158,6 +163,30 @@ def run(["gen" | rest]) do
) )
|> Path.expand() |> Path.expand()
strip_uploads =
get_option(
options,
:strip_uploads,
"Do you want to strip location (GPS) data from uploaded images? (y/n)",
"y"
) === "y"
anonymize_uploads =
get_option(
options,
:anonymize_uploads,
"Do you want to anonymize the filenames of uploads? (y/n)",
"n"
) === "y"
dedupe_uploads =
get_option(
options,
:dedupe_uploads,
"Do you want to deduplicate uploaded files? (y/n)",
"n"
) === "y"
Config.put([:instance, :static_dir], static_dir) Config.put([:instance, :static_dir], static_dir)
secret = :crypto.strong_rand_bytes(64) |> Base.encode64() |> binary_part(0, 64) secret = :crypto.strong_rand_bytes(64) |> Base.encode64() |> binary_part(0, 64)
@ -188,7 +217,13 @@ def run(["gen" | rest]) do
uploads_dir: uploads_dir, uploads_dir: uploads_dir,
rum_enabled: rum_enabled, rum_enabled: rum_enabled,
listen_ip: listen_ip, listen_ip: listen_ip,
listen_port: listen_port listen_port: listen_port,
upload_filters:
upload_filters(%{
strip: strip_uploads,
anonymize: anonymize_uploads,
dedupe: dedupe_uploads
})
) )
result_psql = result_psql =
@ -208,6 +243,24 @@ def run(["gen" | rest]) do
write_robots_txt(static_dir, indexable, template_dir) write_robots_txt(static_dir, indexable, template_dir)
if Keyword.get(options, :skip_release_env, false) do
shell_info("""
Release environment file is skip. Please generate the release env file before start.
`MIX_ENV=#{Mix.env()} mix pleroma.release_env gen`
""")
else
shell_info("Generation the environment file:")
release_env_args =
with path when not is_nil(path) <- Keyword.get(options, :release_env_file) do
["gen", "--path", path]
else
_ -> ["gen"]
end
Mix.Tasks.Pleroma.ReleaseEnv.run(release_env_args)
end
shell_info( shell_info(
"\n All files successfully written! Refer to the installation instructions for your platform for next steps." "\n All files successfully written! Refer to the installation instructions for your platform for next steps."
) )
@ -247,4 +300,31 @@ defp write_robots_txt(static_dir, indexable, template_dir) do
File.write(robots_txt_path, robots_txt) File.write(robots_txt_path, robots_txt)
shell_info("Writing #{robots_txt_path}.") shell_info("Writing #{robots_txt_path}.")
end end
defp upload_filters(filters) when is_map(filters) do
enabled_filters =
if filters.strip do
[Pleroma.Upload.Filter.ExifTool]
else
[]
end
enabled_filters =
if filters.anonymize do
enabled_filters ++ [Pleroma.Upload.Filter.AnonymizeFilename]
else
enabled_filters
end
enabled_filters =
if filters.dedupe do
enabled_filters ++ [Pleroma.Upload.Filter.Dedupe]
else
enabled_filters
end
enabled_filters
end
defp upload_filters(_), do: []
end end

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.NotificationSettings do defmodule Mix.Tasks.Pleroma.NotificationSettings do
@shortdoc "Enable&Disable privacy option for push notifications" @shortdoc "Enable&Disable privacy option for push notifications"
@moduledoc """ @moduledoc """

View file

@ -0,0 +1,76 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Mix.Tasks.Pleroma.ReleaseEnv do
use Mix.Task
import Mix.Pleroma
@shortdoc "Generate Pleroma environment file."
@moduledoc File.read!("docs/administration/CLI_tasks/release_environments.md")
def run(["gen" | rest]) do
{options, [], []} =
OptionParser.parse(
rest,
strict: [
force: :boolean,
path: :string
],
aliases: [
p: :path,
f: :force
]
)
file_path =
get_option(
options,
:path,
"Environment file path",
"./config/pleroma.env"
)
env_path = Path.expand(file_path)
proceed? =
if File.exists?(env_path) do
get_option(
options,
:force,
"Environment file already exists. Do you want to overwrite the #{env_path} file? (y/n)",
"n"
) === "y"
else
true
end
if proceed? do
case do_generate(env_path) do
{:error, reason} ->
shell_error(
File.Error.message(%{action: "write to file", reason: reason, path: env_path})
)
_ ->
shell_info("\nThe file generated: #{env_path}.\n")
shell_info("""
WARNING: before start pleroma app please make sure to make the file read-only and non-modifiable.
Example:
chmod 0444 #{file_path}
chattr +i #{file_path}
""")
end
else
shell_info("\nThe file is exist. #{env_path}.\n")
end
end
def do_generate(path) do
content = "RELEASE_COOKIE=#{Base.encode32(:crypto.strong_rand_bytes(32))}"
File.mkdir_p!(Path.dirname(path))
File.write(path, content)
end
end

View file

@ -419,7 +419,7 @@ def run(["list"]) do
|> Enum.each(fn user -> |> Enum.each(fn user ->
shell_info( shell_info(
"#{user.nickname} moderator: #{user.is_moderator}, admin: #{user.is_admin}, locked: #{ "#{user.nickname} moderator: #{user.is_moderator}, admin: #{user.is_admin}, locked: #{
user.locked user.is_locked
}, deactivated: #{user.deactivated}" }, deactivated: #{user.deactivated}"
) )
end) end)
@ -447,10 +447,10 @@ defp set_admin(user, value) do
defp set_locked(user, value) do defp set_locked(user, value) do
{:ok, user} = {:ok, user} =
user user
|> Changeset.change(%{locked: value}) |> Changeset.change(%{is_locked: value})
|> User.update_and_set_cache() |> User.update_and_set_cache()
shell_info("Locked status of #{user.nickname}: #{user.locked}") shell_info("Locked status of #{user.nickname}: #{user.is_locked}")
user user
end end

View file

@ -52,7 +52,7 @@ def start(_type, _args) do
Pleroma.HTML.compile_scrubbers() Pleroma.HTML.compile_scrubbers()
Pleroma.Config.Oban.warn() Pleroma.Config.Oban.warn()
Config.DeprecationWarnings.warn() Config.DeprecationWarnings.warn()
Pleroma.Plugs.HTTPSecurityPlug.warn_if_disabled() Pleroma.Web.Plugs.HTTPSecurityPlug.warn_if_disabled()
Pleroma.ApplicationRequirements.verify!() Pleroma.ApplicationRequirements.verify!()
setup_instrumenters() setup_instrumenters()
load_custom_modules() load_custom_modules()
@ -88,13 +88,14 @@ def start(_type, _args) do
Pleroma.Repo, Pleroma.Repo,
Config.TransferTask, Config.TransferTask,
Pleroma.Emoji, Pleroma.Emoji,
Pleroma.Plugs.RateLimiter.Supervisor Pleroma.Web.Plugs.RateLimiter.Supervisor
] ++ ] ++
cachex_children() ++ cachex_children() ++
http_children(adapter, @env) ++ http_children(adapter, @env) ++
[ [
Pleroma.Stats, Pleroma.Stats,
Pleroma.JobQueueMonitor, Pleroma.JobQueueMonitor,
{Majic.Pool, [name: Pleroma.MajicPool, pool_size: Config.get([:majic_pool, :size], 2)]},
{Oban, Config.get(Oban)} {Oban, Config.get(Oban)}
] ++ ] ++
task_children(@env) ++ task_children(@env) ++

View file

@ -4,8 +4,8 @@
defmodule Pleroma.BBS.Authenticator do defmodule Pleroma.BBS.Authenticator do
use Sshd.PasswordAuthenticator use Sshd.PasswordAuthenticator
alias Pleroma.Plugs.AuthenticationPlug
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.Plugs.AuthenticationPlug
def authenticate(username, password) do def authenticate(username, password) do
username = to_string(username) username = to_string(username)

View file

@ -39,7 +39,8 @@ def warn do
:ok <- check_media_proxy_whitelist_config(), :ok <- check_media_proxy_whitelist_config(),
:ok <- check_welcome_message_config(), :ok <- check_welcome_message_config(),
:ok <- check_gun_pool_options(), :ok <- check_gun_pool_options(),
:ok <- check_activity_expiration_config() do :ok <- check_activity_expiration_config(),
:ok <- check_remote_ip_plug_name() do
:ok :ok
else else
_ -> _ ->
@ -176,4 +177,20 @@ def check_activity_expiration_config do
warning_preface warning_preface
) )
end end
@spec check_remote_ip_plug_name() :: :ok | nil
def check_remote_ip_plug_name do
warning_preface = """
!!!DEPRECATION WARNING!!!
Your config is using old namespace for RemoteIp Plug. Setting should work for now, but you are advised to change to new namespace to prevent possible issues later:
"""
move_namespace_and_warn(
[
{Pleroma.Plugs.RemoteIp, Pleroma.Web.Plugs.RemoteIp,
"\n* `config :pleroma, Pleroma.Plugs.RemoteIp` is now `config :pleroma, Pleroma.Web.Plugs.RemoteIp`"}
],
warning_preface
)
end
end end

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Config.Oban do defmodule Pleroma.Config.Oban do
require Logger require Logger

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Docs.Generator do defmodule Pleroma.Docs.Generator do
@callback process(keyword()) :: {:ok, String.t()} @callback process(keyword()) :: {:ok, String.t()}

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Docs.JSON do defmodule Pleroma.Docs.JSON do
@behaviour Pleroma.Docs.Generator @behaviour Pleroma.Docs.Generator
@external_resource "config/description.exs" @external_resource "config/description.exs"

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Docs.Markdown do defmodule Pleroma.Docs.Markdown do
@behaviour Pleroma.Docs.Generator @behaviour Pleroma.Docs.Generator

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Emoji.Pack do defmodule Pleroma.Emoji.Pack do
@derive {Jason.Encoder, only: [:files, :pack, :files_count]} @derive {Jason.Encoder, only: [:files, :pack, :files_count]}
defstruct files: %{}, defstruct files: %{},

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Gun.ConnectionPool do defmodule Pleroma.Gun.ConnectionPool do
@registry __MODULE__ @registry __MODULE__

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Gun.ConnectionPool.Reclaimer do defmodule Pleroma.Gun.ConnectionPool.Reclaimer do
use GenServer, restart: :temporary use GenServer, restart: :temporary

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Gun.ConnectionPool.Worker do defmodule Pleroma.Gun.ConnectionPool.Worker do
alias Pleroma.Gun alias Pleroma.Gun
use GenServer, restart: :temporary use GenServer, restart: :temporary

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Gun.ConnectionPool.WorkerSupervisor do defmodule Pleroma.Gun.ConnectionPool.WorkerSupervisor do
@moduledoc "Supervisor for pool workers. Does not do anything except enforce max connection limit" @moduledoc "Supervisor for pool workers. Does not do anything except enforce max connection limit"

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.AdapterHelper.Default do defmodule Pleroma.HTTP.AdapterHelper.Default do
alias Pleroma.HTTP.AdapterHelper alias Pleroma.HTTP.AdapterHelper

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.HTTP.AdapterHelper.Hackney do defmodule Pleroma.HTTP.AdapterHelper.Hackney do
@behaviour Pleroma.HTTP.AdapterHelper @behaviour Pleroma.HTTP.AdapterHelper

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.JWT do defmodule Pleroma.JWT do
use Joken.Config use Joken.Config

View file

@ -1,120 +0,0 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.MIME do
@moduledoc """
Returns the mime-type of a binary and optionally a normalized file-name.
"""
@default "application/octet-stream"
@read_bytes 35
@spec file_mime_type(String.t(), String.t()) ::
{:ok, content_type :: String.t(), filename :: String.t()} | {:error, any()} | :error
def file_mime_type(path, filename) do
with {:ok, content_type} <- file_mime_type(path),
filename <- fix_extension(filename, content_type) do
{:ok, content_type, filename}
end
end
@spec file_mime_type(String.t()) :: {:ok, String.t()} | {:error, any()} | :error
def file_mime_type(filename) do
File.open(filename, [:read], fn f ->
check_mime_type(IO.binread(f, @read_bytes))
end)
end
def bin_mime_type(binary, filename) do
with {:ok, content_type} <- bin_mime_type(binary),
filename <- fix_extension(filename, content_type) do
{:ok, content_type, filename}
end
end
@spec bin_mime_type(binary()) :: {:ok, String.t()} | :error
def bin_mime_type(<<head::binary-size(@read_bytes), _::binary>>) do
{:ok, check_mime_type(head)}
end
def bin_mime_type(_), do: :error
def mime_type(<<_::binary>>), do: {:ok, @default}
defp fix_extension(filename, content_type) do
parts = String.split(filename, ".")
new_filename =
if length(parts) > 1 do
Enum.drop(parts, -1) |> Enum.join(".")
else
Enum.join(parts)
end
cond do
content_type == "application/octet-stream" ->
filename
ext = List.first(MIME.extensions(content_type)) ->
new_filename <> "." <> ext
true ->
Enum.join([new_filename, String.split(content_type, "/") |> List.last()], ".")
end
end
defp check_mime_type(<<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, _::binary>>) do
"image/png"
end
defp check_mime_type(<<0x47, 0x49, 0x46, 0x38, _, 0x61, _::binary>>) do
"image/gif"
end
defp check_mime_type(<<0xFF, 0xD8, 0xFF, _::binary>>) do
"image/jpeg"
end
defp check_mime_type(<<0x1A, 0x45, 0xDF, 0xA3, _::binary>>) do
"video/webm"
end
defp check_mime_type(<<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70, _::binary>>) do
"video/mp4"
end
defp check_mime_type(<<0x49, 0x44, 0x33, _::binary>>) do
"audio/mpeg"
end
defp check_mime_type(<<255, 251, _, 68, 0, 0, 0, 0, _::binary>>) do
"audio/mpeg"
end
defp check_mime_type(
<<0x4F, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00, _::size(160), 0x80, 0x74, 0x68, 0x65,
0x6F, 0x72, 0x61, _::binary>>
) do
"video/ogg"
end
defp check_mime_type(<<0x4F, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00, _::binary>>) do
"audio/ogg"
end
defp check_mime_type(<<"RIFF", _::binary-size(4), "WAVE", _::binary>>) do
"audio/wav"
end
defp check_mime_type(<<"RIFF", _::binary-size(4), "WEBP", _::binary>>) do
"image/webp"
end
defp check_mime_type(<<"RIFF", _::binary-size(4), "AVI.", _::binary>>) do
"video/avi"
end
defp check_mime_type(_) do
@default
end
end

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.ModerationLog do defmodule Pleroma.ModerationLog do
use Ecto.Schema use Ecto.Schema

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Telemetry.Logger do defmodule Pleroma.Telemetry.Logger do
@moduledoc "Transforms Pleroma telemetry events to logs" @moduledoc "Transforms Pleroma telemetry events to logs"

View file

@ -8,9 +8,9 @@ defmodule Pleroma.Tests.AuthTestController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Web.Plugs.OAuthScopesPlug
# Serves only with proper OAuth token (:api and :authenticated_api) # Serves only with proper OAuth token (:api and :authenticated_api)
# Skipping EnsurePublicOrAuthenticatedPlug has no effect in this case # Skipping EnsurePublicOrAuthenticatedPlug has no effect in this case

View file

@ -66,6 +66,7 @@ defp get_description(opts, upload) do
end end
@spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()} @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
@doc "Store a file. If using a `Plug.Upload{}` as the source, be sure to use `Majic.Plug` to ensure its content_type and filename is correct."
def store(upload, opts \\ []) do def store(upload, opts \\ []) do
opts = get_opts(opts) opts = get_opts(opts)
@ -139,14 +140,13 @@ defp get_opts(opts) do
end end
defp prepare_upload(%Plug.Upload{} = file, opts) do defp prepare_upload(%Plug.Upload{} = file, opts) do
with :ok <- check_file_size(file.path, opts.size_limit), with :ok <- check_file_size(file.path, opts.size_limit) do
{:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
{:ok, {:ok,
%__MODULE__{ %__MODULE__{
id: UUID.generate(), id: UUID.generate(),
name: name, name: file.filename,
tempfile: file.path, tempfile: file.path,
content_type: content_type content_type: file.content_type
}} }}
end end
end end
@ -154,16 +154,17 @@ defp prepare_upload(%Plug.Upload{} = file, opts) do
defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data) parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
data = Base.decode64!(parsed["data"], ignore: :whitespace) data = Base.decode64!(parsed["data"], ignore: :whitespace)
hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data))) hash = Base.encode16(:crypto.hash(:sha256, data), lower: true)
with :ok <- check_binary_size(data, opts.size_limit), with :ok <- check_binary_size(data, opts.size_limit),
tmp_path <- tempfile_for_image(data), tmp_path <- tempfile_for_image(data),
{:ok, content_type, name} <- {:ok, %{mime_type: content_type}} <-
Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
[ext | _] <- MIME.extensions(content_type) do
{:ok, {:ok,
%__MODULE__{ %__MODULE__{
id: UUID.generate(), id: UUID.generate(),
name: name, name: hash <> "." <> ext,
tempfile: tmp_path, tempfile: tmp_path,
content_type: content_type content_type: content_type
}} }}
@ -172,7 +173,7 @@ defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
# For Mix.Tasks.MigrateLocalUploads # For Mix.Tasks.MigrateLocalUploads
defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) do with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
{:ok, %__MODULE__{upload | content_type: content_type}} {:ok, %__MODULE__{upload | content_type: content_type}}
end end
end end

View file

@ -12,7 +12,7 @@ defmodule Pleroma.Uploaders.Uploader do
@doc """ @doc """
Instructs how to get the file from the backend. Instructs how to get the file from the backend.
Used by `Pleroma.Plugs.UploadedMedia`. Used by `Pleroma.Web.Plugs.UploadedMedia`.
""" """
@type get_method :: {:static_dir, directory :: String.t()} | {:url, url :: String.t()} @type get_method :: {:static_dir, directory :: String.t()} | {:url, url :: String.t()}
@callback get_file(file :: String.t()) :: {:ok, get_method()} @callback get_file(file :: String.t()) :: {:ok, get_method()}

View file

@ -107,7 +107,7 @@ defmodule Pleroma.User do
field(:note_count, :integer, default: 0) field(:note_count, :integer, default: 0)
field(:follower_count, :integer, default: 0) field(:follower_count, :integer, default: 0)
field(:following_count, :integer, default: 0) field(:following_count, :integer, default: 0)
field(:locked, :boolean, default: false) field(:is_locked, :boolean, default: false)
field(:confirmation_pending, :boolean, default: false) field(:confirmation_pending, :boolean, default: false)
field(:password_reset_pending, :boolean, default: false) field(:password_reset_pending, :boolean, default: false)
field(:approval_pending, :boolean, default: false) field(:approval_pending, :boolean, default: false)
@ -136,7 +136,7 @@ defmodule Pleroma.User do
field(:pleroma_settings_store, :map, default: %{}) field(:pleroma_settings_store, :map, default: %{})
field(:fields, {:array, :map}, default: []) field(:fields, {:array, :map}, default: [])
field(:raw_fields, {:array, :map}, default: []) field(:raw_fields, {:array, :map}, default: [])
field(:discoverable, :boolean, default: false) field(:is_discoverable, :boolean, default: false)
field(:invisible, :boolean, default: false) field(:invisible, :boolean, default: false)
field(:allow_following_move, :boolean, default: true) field(:allow_following_move, :boolean, default: true)
field(:skip_thread_containment, :boolean, default: false) field(:skip_thread_containment, :boolean, default: false)
@ -436,7 +436,7 @@ def remote_user_changeset(struct \\ %User{local: false}, params) do
:avatar, :avatar,
:ap_enabled, :ap_enabled,
:banner, :banner,
:locked, :is_locked,
:last_refreshed_at, :last_refreshed_at,
:uri, :uri,
:follower_address, :follower_address,
@ -448,7 +448,7 @@ def remote_user_changeset(struct \\ %User{local: false}, params) do
:follower_count, :follower_count,
:fields, :fields,
:following_count, :following_count,
:discoverable, :is_discoverable,
:invisible, :invisible,
:actor_type, :actor_type,
:also_known_as, :also_known_as,
@ -479,7 +479,7 @@ def update_changeset(struct, params \\ %{}) do
:public_key, :public_key,
:inbox, :inbox,
:shared_inbox, :shared_inbox,
:locked, :is_locked,
:no_rich_text, :no_rich_text,
:default_scope, :default_scope,
:banner, :banner,
@ -495,7 +495,7 @@ def update_changeset(struct, params \\ %{}) do
:fields, :fields,
:raw_fields, :raw_fields,
:pleroma_settings_store, :pleroma_settings_store,
:discoverable, :is_discoverable,
:actor_type, :actor_type,
:also_known_as, :also_known_as,
:accepts_chat_messages :accepts_chat_messages
@ -847,7 +847,7 @@ def needs_update?(_), do: true
@spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()} @spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
# "Locked" (self-locked) users demand explicit authorization of follow requests # "Locked" (self-locked) users demand explicit authorization of follow requests
def maybe_direct_follow(%User{} = follower, %User{local: true, locked: true} = followed) do def maybe_direct_follow(%User{} = follower, %User{local: true, is_locked: true} = followed) do
follow(follower, followed, :follow_pending) follow(follower, followed, :follow_pending)
end end
@ -954,7 +954,7 @@ def get_follow_state(
end end
def locked?(%User{} = user) do def locked?(%User{} = user) do
user.locked || false user.is_locked || false
end end
def get_by_id(id) do def get_by_id(id) do
@ -1601,7 +1601,7 @@ def purge_user_changeset(user) do
note_count: 0, note_count: 0,
follower_count: 0, follower_count: 0,
following_count: 0, following_count: 0,
locked: false, is_locked: false,
confirmation_pending: false, confirmation_pending: false,
password_reset_pending: false, password_reset_pending: false,
approval_pending: false, approval_pending: false,
@ -1618,7 +1618,7 @@ def purge_user_changeset(user) do
pleroma_settings_store: %{}, pleroma_settings_store: %{},
fields: [], fields: [],
raw_fields: [], raw_fields: [],
discoverable: false, is_discoverable: false,
also_known_as: [] also_known_as: []
}) })
end end

View file

@ -164,7 +164,7 @@ defp filter_invisible_users(query) do
end end
defp filter_discoverable_users(query) do defp filter_discoverable_users(query) do
from(q in query, where: q.discoverable == true) from(q in query, where: q.is_discoverable == true)
end end
defp filter_internal_users(query) do defp filter_internal_users(query) do

View file

@ -2,11 +2,6 @@
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Plug do
# Substitute for `call/2` which is defined with `use Pleroma.Web, :plug`
@callback perform(Plug.Conn.t(), Plug.opts()) :: Plug.Conn.t()
end
defmodule Pleroma.Web do defmodule Pleroma.Web do
@moduledoc """ @moduledoc """
A module that keeps using definitions for controllers, A module that keeps using definitions for controllers,
@ -25,12 +20,12 @@ defmodule Pleroma.Web do
below. below.
""" """
alias Pleroma.Plugs.EnsureAuthenticatedPlug alias Pleroma.Web.Plugs.EnsureAuthenticatedPlug
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.ExpectAuthenticatedCheckPlug alias Pleroma.Web.Plugs.ExpectAuthenticatedCheckPlug
alias Pleroma.Plugs.ExpectPublicOrAuthenticatedCheckPlug alias Pleroma.Web.Plugs.ExpectPublicOrAuthenticatedCheckPlug
alias Pleroma.Plugs.OAuthScopesPlug alias Pleroma.Web.Plugs.OAuthScopesPlug
alias Pleroma.Plugs.PlugHelper alias Pleroma.Web.Plugs.PlugHelper
def controller do def controller do
quote do quote do

View file

@ -1228,11 +1228,11 @@ defp object_to_user_data(data) do
{String.trim(name, ":"), url} {String.trim(name, ":"), url}
end) end)
locked = data["manuallyApprovesFollowers"] || false is_locked = data["manuallyApprovesFollowers"] || false
capabilities = data["capabilities"] || %{} capabilities = data["capabilities"] || %{}
accepts_chat_messages = capabilities["acceptsChatMessages"] accepts_chat_messages = capabilities["acceptsChatMessages"]
data = Transmogrifier.maybe_fix_user_object(data) data = Transmogrifier.maybe_fix_user_object(data)
discoverable = data["discoverable"] || false is_discoverable = data["discoverable"] || false
invisible = data["invisible"] || false invisible = data["invisible"] || false
actor_type = data["type"] || "Person" actor_type = data["type"] || "Person"
@ -1257,8 +1257,8 @@ defp object_to_user_data(data) do
banner: banner, banner: banner,
fields: fields, fields: fields,
emoji: emojis, emoji: emojis,
locked: locked, is_locked: is_locked,
discoverable: discoverable, is_discoverable: is_discoverable,
invisible: invisible, invisible: invisible,
avatar: avatar, avatar: avatar,
name: data["name"], name: data["name"],

View file

@ -9,7 +9,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
alias Pleroma.Delivery alias Pleroma.Delivery
alias Pleroma.Object alias Pleroma.Object
alias Pleroma.Object.Fetcher alias Pleroma.Object.Fetcher
alias Pleroma.Plugs.EnsureAuthenticatedPlug
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Builder alias Pleroma.Web.ActivityPub.Builder
@ -23,8 +22,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
alias Pleroma.Web.ActivityPub.Visibility alias Pleroma.Web.ActivityPub.Visibility
alias Pleroma.Web.ControllerHelper alias Pleroma.Web.ControllerHelper
alias Pleroma.Web.Endpoint alias Pleroma.Web.Endpoint
alias Pleroma.Web.FederatingPlug
alias Pleroma.Web.Federator alias Pleroma.Web.Federator
alias Pleroma.Web.Plugs.EnsureAuthenticatedPlug
alias Pleroma.Web.Plugs.FederatingPlug
require Logger require Logger
@ -45,8 +45,10 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubController do
when action in [:read_inbox, :update_outbox, :whoami, :upload_media] when action in [:read_inbox, :update_outbox, :whoami, :upload_media]
) )
plug(Majic.Plug, [pool: Pleroma.MajicPool] when action in [:upload_media])
plug( plug(
Pleroma.Plugs.Cache, Pleroma.Web.Plugs.Cache,
[query_params: false, tracking_fun: &__MODULE__.track_object_fetch/2] [query_params: false, tracking_fun: &__MODULE__.track_object_fetch/2]
when action in [:activity, :object] when action in [:activity, :object]
) )

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.Builder do defmodule Pleroma.Web.ActivityPub.Builder do
@moduledoc """ @moduledoc """
This module builds the objects. Meant to be used for creating local objects. This module builds the objects. Meant to be used for creating local objects.

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.SideEffects do defmodule Pleroma.Web.ActivityPub.SideEffects do
@moduledoc """ @moduledoc """
This module looks at an inserted object and executes the side effects that it This module looks at an inserted object and executes the side effects that it
@ -98,7 +102,7 @@ def handle(
%User{} = followed <- User.get_cached_by_ap_id(followed_user), %User{} = followed <- User.get_cached_by_ap_id(followed_user),
{_, {:ok, _}, _, _} <- {_, {:ok, _}, _, _} <-
{:following, User.follow(follower, followed, :follow_pending), follower, followed} do {:following, User.follow(follower, followed, :follow_pending), follower, followed} do
if followed.local && !followed.locked do if followed.local && !followed.is_locked do
{:ok, accept_data, _} = Builder.accept(followed, object) {:ok, accept_data, _} = Builder.accept(followed, object)
{:ok, _activity, _} = Pipeline.common_pipeline(accept_data, local: true) {:ok, _activity, _} = Pipeline.common_pipeline(accept_data, local: true)
end end

View file

@ -101,7 +101,7 @@ def render("user.json", %{user: user}) do
"name" => user.name, "name" => user.name,
"summary" => user.bio, "summary" => user.bio,
"url" => user.ap_id, "url" => user.ap_id,
"manuallyApprovesFollowers" => user.locked, "manuallyApprovesFollowers" => user.is_locked,
"publicKey" => %{ "publicKey" => %{
"id" => "#{user.ap_id}#main-key", "id" => "#{user.ap_id}#main-key",
"owner" => user.ap_id, "owner" => user.ap_id,
@ -110,7 +110,7 @@ def render("user.json", %{user: user}) do
"endpoints" => endpoints, "endpoints" => endpoints,
"attachment" => fields, "attachment" => fields,
"tag" => emoji_tags, "tag" => emoji_tags,
"discoverable" => user.discoverable, "discoverable" => user.is_discoverable,
"capabilities" => capabilities "capabilities" => capabilities
} }
|> Map.merge(maybe_make_image(&User.avatar_url/2, "icon", user)) |> Map.merge(maybe_make_image(&User.avatar_url/2, "icon", user))

View file

@ -10,7 +10,6 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
alias Pleroma.Config alias Pleroma.Config
alias Pleroma.MFA alias Pleroma.MFA
alias Pleroma.ModerationLog alias Pleroma.ModerationLog
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Stats alias Pleroma.Stats
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
@ -21,6 +20,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIController do
alias Pleroma.Web.AdminAPI.ModerationLogView alias Pleroma.Web.AdminAPI.ModerationLogView
alias Pleroma.Web.AdminAPI.Search alias Pleroma.Web.AdminAPI.Search
alias Pleroma.Web.Endpoint alias Pleroma.Web.Endpoint
alias Pleroma.Web.Plugs.OAuthScopesPlug
alias Pleroma.Web.Router alias Pleroma.Web.Router
@users_page_size 50 @users_page_size 50

View file

@ -10,10 +10,10 @@ defmodule Pleroma.Web.AdminAPI.ChatController do
alias Pleroma.Chat.MessageReference alias Pleroma.Chat.MessageReference
alias Pleroma.ModerationLog alias Pleroma.ModerationLog
alias Pleroma.Pagination alias Pleroma.Pagination
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Web.AdminAPI alias Pleroma.Web.AdminAPI
alias Pleroma.Web.CommonAPI alias Pleroma.Web.CommonAPI
alias Pleroma.Web.PleromaAPI.Chat.MessageReferenceView alias Pleroma.Web.PleromaAPI.Chat.MessageReferenceView
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger require Logger

View file

@ -7,7 +7,7 @@ defmodule Pleroma.Web.AdminAPI.ConfigController do
alias Pleroma.Config alias Pleroma.Config
alias Pleroma.ConfigDB alias Pleroma.ConfigDB
alias Pleroma.Plugs.OAuthScopesPlug alias Pleroma.Web.Plugs.OAuthScopesPlug
plug(Pleroma.Web.ApiSpec.CastAndValidate) plug(Pleroma.Web.ApiSpec.CastAndValidate)
plug(OAuthScopesPlug, %{scopes: ["write"], admin: true} when action == :update) plug(OAuthScopesPlug, %{scopes: ["write"], admin: true} when action == :update)

View file

@ -5,9 +5,9 @@
defmodule Pleroma.Web.AdminAPI.InstanceDocumentController do defmodule Pleroma.Web.AdminAPI.InstanceDocumentController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.Plugs.InstanceStatic
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Web.InstanceDocument alias Pleroma.Web.InstanceDocument
alias Pleroma.Web.Plugs.InstanceStatic
alias Pleroma.Web.Plugs.OAuthScopesPlug
plug(Pleroma.Web.ApiSpec.CastAndValidate) plug(Pleroma.Web.ApiSpec.CastAndValidate)

View file

@ -8,8 +8,8 @@ defmodule Pleroma.Web.AdminAPI.InviteController do
import Pleroma.Web.ControllerHelper, only: [json_response: 3] import Pleroma.Web.ControllerHelper, only: [json_response: 3]
alias Pleroma.Config alias Pleroma.Config
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.UserInviteToken alias Pleroma.UserInviteToken
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger require Logger

View file

@ -5,9 +5,9 @@
defmodule Pleroma.Web.AdminAPI.MediaProxyCacheController do defmodule Pleroma.Web.AdminAPI.MediaProxyCacheController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Web.ApiSpec.Admin, as: Spec alias Pleroma.Web.ApiSpec.Admin, as: Spec
alias Pleroma.Web.MediaProxy alias Pleroma.Web.MediaProxy
alias Pleroma.Web.Plugs.OAuthScopesPlug
plug(Pleroma.Web.ApiSpec.CastAndValidate) plug(Pleroma.Web.ApiSpec.CastAndValidate)

View file

@ -7,8 +7,8 @@ defmodule Pleroma.Web.AdminAPI.OAuthAppController do
import Pleroma.Web.ControllerHelper, only: [json_response: 3] import Pleroma.Web.ControllerHelper, only: [json_response: 3]
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Web.OAuth.App alias Pleroma.Web.OAuth.App
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger require Logger

View file

@ -6,8 +6,8 @@ defmodule Pleroma.Web.AdminAPI.RelayController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.ModerationLog alias Pleroma.ModerationLog
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Web.ActivityPub.Relay alias Pleroma.Web.ActivityPub.Relay
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger require Logger

View file

@ -9,12 +9,12 @@ defmodule Pleroma.Web.AdminAPI.ReportController do
alias Pleroma.Activity alias Pleroma.Activity
alias Pleroma.ModerationLog alias Pleroma.ModerationLog
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.ReportNote alias Pleroma.ReportNote
alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.AdminAPI alias Pleroma.Web.AdminAPI
alias Pleroma.Web.AdminAPI.Report alias Pleroma.Web.AdminAPI.Report
alias Pleroma.Web.CommonAPI alias Pleroma.Web.CommonAPI
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger require Logger

View file

@ -7,10 +7,10 @@ defmodule Pleroma.Web.AdminAPI.StatusController do
alias Pleroma.Activity alias Pleroma.Activity
alias Pleroma.ModerationLog alias Pleroma.ModerationLog
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.CommonAPI alias Pleroma.Web.CommonAPI
alias Pleroma.Web.MastodonAPI alias Pleroma.Web.MastodonAPI
alias Pleroma.Web.Plugs.OAuthScopesPlug
require Logger require Logger

View file

@ -39,7 +39,7 @@ def render("credentials.json", %{user: user, for: for_user}) do
:fields, :fields,
:name, :name,
:nickname, :nickname,
:locked, :is_locked,
:no_rich_text, :no_rich_text,
:default_scope, :default_scope,
:hide_follows, :hide_follows,

View file

@ -50,7 +50,7 @@ defmodule Pleroma.Web.ApiSpec.Schemas.Chat do
"fields" => [] "fields" => []
}, },
"statuses_count" => 1, "statuses_count" => 1,
"locked" => false, "is_locked" => false,
"created_at" => "2020-04-16T13:40:15.000Z", "created_at" => "2020-04-16T13:40:15.000Z",
"display_name" => "lain", "display_name" => "lain",
"fields" => [], "fields" => [],

View file

@ -252,7 +252,7 @@ defmodule Pleroma.Web.ApiSpec.Schemas.Status do
"header" => "http://localhost:4001/images/banner.png", "header" => "http://localhost:4001/images/banner.png",
"header_static" => "http://localhost:4001/images/banner.png", "header_static" => "http://localhost:4001/images/banner.png",
"id" => "9toJCsKN7SmSf3aj5c", "id" => "9toJCsKN7SmSf3aj5c",
"locked" => false, "is_locked" => false,
"note" => "Tester Number 6", "note" => "Tester Number 6",
"pleroma" => %{ "pleroma" => %{
"background_image" => nil, "background_image" => nil,

View file

@ -3,10 +3,10 @@
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Auth.PleromaAuthenticator do defmodule Pleroma.Web.Auth.PleromaAuthenticator do
alias Pleroma.Plugs.AuthenticationPlug
alias Pleroma.Registration alias Pleroma.Registration
alias Pleroma.Repo alias Pleroma.Repo
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.Plugs.AuthenticationPlug
import Pleroma.Web.Auth.Authenticator, import Pleroma.Web.Auth.Authenticator,
only: [fetch_credentials: 1, fetch_user: 1] only: [fetch_credentials: 1, fetch_user: 1]

View file

@ -5,8 +5,8 @@
defmodule Pleroma.Web.Auth.TOTPAuthenticator do defmodule Pleroma.Web.Auth.TOTPAuthenticator do
alias Pleroma.MFA alias Pleroma.MFA
alias Pleroma.MFA.TOTP alias Pleroma.MFA.TOTP
alias Pleroma.Plugs.AuthenticationPlug
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.Plugs.AuthenticationPlug
@doc "Verify code or check backup code." @doc "Verify code or check backup code."
@spec verify(String.t(), User.t()) :: @spec verify(String.t(), User.t()) ::

View file

@ -12,12 +12,12 @@ defmodule Pleroma.Web.CommonAPI.Utils do
alias Pleroma.Conversation.Participation alias Pleroma.Conversation.Participation
alias Pleroma.Formatter alias Pleroma.Formatter
alias Pleroma.Object alias Pleroma.Object
alias Pleroma.Plugs.AuthenticationPlug
alias Pleroma.Repo alias Pleroma.Repo
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.ActivityPub.Utils alias Pleroma.Web.ActivityPub.Utils
alias Pleroma.Web.ActivityPub.Visibility alias Pleroma.Web.ActivityPub.Visibility
alias Pleroma.Web.MediaProxy alias Pleroma.Web.MediaProxy
alias Pleroma.Web.Plugs.AuthenticationPlug
require Logger require Logger
require Pleroma.Constants require Pleroma.Constants

View file

@ -9,17 +9,17 @@ defmodule Pleroma.Web.Endpoint do
socket("/socket", Pleroma.Web.UserSocket) socket("/socket", Pleroma.Web.UserSocket)
plug(Pleroma.Plugs.SetLocalePlug) plug(Pleroma.Web.Plugs.SetLocalePlug)
plug(CORSPlug) plug(CORSPlug)
plug(Pleroma.Plugs.HTTPSecurityPlug) plug(Pleroma.Web.Plugs.HTTPSecurityPlug)
plug(Pleroma.Plugs.UploadedMedia) plug(Pleroma.Web.Plugs.UploadedMedia)
@static_cache_control "public, no-cache" @static_cache_control "public, no-cache"
# InstanceStatic needs to be before Plug.Static to be able to override shipped-static files # InstanceStatic needs to be before Plug.Static to be able to override shipped-static files
# If you're adding new paths to `only:` you'll need to configure them in InstanceStatic as well # If you're adding new paths to `only:` you'll need to configure them in InstanceStatic as well
# Cache-control headers are duplicated in case we turn off etags in the future # Cache-control headers are duplicated in case we turn off etags in the future
plug(Pleroma.Plugs.InstanceStatic, plug(Pleroma.Web.Plugs.InstanceStatic,
at: "/", at: "/",
gzip: true, gzip: true,
cache_control_for_etags: @static_cache_control, cache_control_for_etags: @static_cache_control,
@ -29,7 +29,7 @@ defmodule Pleroma.Web.Endpoint do
) )
# Careful! No `only` restriction here, as we don't know what frontends contain. # Careful! No `only` restriction here, as we don't know what frontends contain.
plug(Pleroma.Plugs.FrontendStatic, plug(Pleroma.Web.Plugs.FrontendStatic,
at: "/", at: "/",
frontend_type: :primary, frontend_type: :primary,
gzip: true, gzip: true,
@ -41,7 +41,7 @@ defmodule Pleroma.Web.Endpoint do
plug(Plug.Static.IndexHtml, at: "/pleroma/admin/") plug(Plug.Static.IndexHtml, at: "/pleroma/admin/")
plug(Pleroma.Plugs.FrontendStatic, plug(Pleroma.Web.Plugs.FrontendStatic,
at: "/pleroma/admin", at: "/pleroma/admin",
frontend_type: :admin, frontend_type: :admin,
gzip: true, gzip: true,
@ -79,7 +79,7 @@ defmodule Pleroma.Web.Endpoint do
plug(Phoenix.CodeReloader) plug(Phoenix.CodeReloader)
end end
plug(Pleroma.Plugs.TrailingFormatPlug) plug(Pleroma.Web.Plugs.TrailingFormatPlug)
plug(Plug.RequestId) plug(Plug.RequestId)
plug(Plug.Logger, log: :debug) plug(Plug.Logger, log: :debug)
@ -122,7 +122,7 @@ defmodule Pleroma.Web.Endpoint do
extra: extra extra: extra
) )
plug(Pleroma.Plugs.RemoteIp) plug(Pleroma.Web.Plugs.RemoteIp)
defmodule Instrumenter do defmodule Instrumenter do
use Prometheus.PhoenixInstrumenter use Prometheus.PhoenixInstrumenter

View file

@ -2,7 +2,7 @@
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
defmodule Fallback.RedirectController do defmodule Pleroma.Web.Fallback.RedirectController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
require Logger require Logger
@ -75,7 +75,7 @@ def empty(conn, _params) do
end end
defp index_file_path do defp index_file_path do
Pleroma.Plugs.InstanceStatic.file_path("index.html") Pleroma.Web.Plugs.InstanceStatic.file_path("index.html")
end end
defp build_tags(conn, params) do defp build_tags(conn, params) do

View file

@ -5,21 +5,18 @@
defmodule Pleroma.Web.Feed.UserController do defmodule Pleroma.Web.Feed.UserController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Fallback.RedirectController
alias Pleroma.Config
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.ActivityPubController alias Pleroma.Web.ActivityPub.ActivityPubController
alias Pleroma.Web.Feed.FeedView alias Pleroma.Web.Feed.FeedView
plug(Pleroma.Plugs.SetFormatPlug when action in [:feed_redirect]) plug(Pleroma.Web.Plugs.SetFormatPlug when action in [:feed_redirect])
action_fallback(:errors) action_fallback(:errors)
def feed_redirect(%{assigns: %{format: "html"}} = conn, %{"nickname" => nickname}) do def feed_redirect(%{assigns: %{format: "html"}} = conn, %{"nickname" => nickname}) do
with {_, %User{} = user} <- {:fetch_user, User.get_cached_by_nickname_or_id(nickname)} do with {_, %User{} = user} <- {:fetch_user, User.get_cached_by_nickname_or_id(nickname)} do
RedirectController.redirector_with_meta(conn, %{user: user}) Pleroma.Web.Fallback.RedirectController.redirector_with_meta(conn, %{user: user})
end end
end end

View file

@ -1,3 +1,7 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Mailer.SubscriptionController do defmodule Pleroma.Web.Mailer.SubscriptionController do
use Pleroma.Web, :controller use Pleroma.Web, :controller

View file

@ -5,9 +5,9 @@
defmodule Pleroma.Web.MastoFEController do defmodule Pleroma.Web.MastoFEController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Web.Plugs.OAuthScopesPlug
plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action == :put_settings) plug(OAuthScopesPlug, %{scopes: ["write:accounts"]} when action == :put_settings)

View file

@ -15,9 +15,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
] ]
alias Pleroma.Maps alias Pleroma.Maps
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Plugs.RateLimiter
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.ActivityPub.ActivityPub
alias Pleroma.Web.ActivityPub.Builder alias Pleroma.Web.ActivityPub.Builder
@ -29,6 +26,9 @@ defmodule Pleroma.Web.MastodonAPI.AccountController do
alias Pleroma.Web.MastodonAPI.StatusView alias Pleroma.Web.MastodonAPI.StatusView
alias Pleroma.Web.OAuth.OAuthController alias Pleroma.Web.OAuth.OAuthController
alias Pleroma.Web.OAuth.OAuthView alias Pleroma.Web.OAuth.OAuthView
alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Web.Plugs.OAuthScopesPlug
alias Pleroma.Web.Plugs.RateLimiter
alias Pleroma.Web.TwitterAPI.TwitterAPI alias Pleroma.Web.TwitterAPI.TwitterAPI
plug(Pleroma.Web.ApiSpec.CastAndValidate) plug(Pleroma.Web.ApiSpec.CastAndValidate)
@ -177,7 +177,6 @@ def update_credentials(%{assigns: %{user: user}, body_params: params} = conn, _p
user_params = user_params =
[ [
:no_rich_text, :no_rich_text,
:locked,
:hide_followers_count, :hide_followers_count,
:hide_follows_count, :hide_follows_count,
:hide_followers, :hide_followers,
@ -186,7 +185,6 @@ def update_credentials(%{assigns: %{user: user}, body_params: params} = conn, _p
:show_role, :show_role,
:skip_thread_containment, :skip_thread_containment,
:allow_following_move, :allow_following_move,
:discoverable,
:accepts_chat_messages :accepts_chat_messages
] ]
|> Enum.reduce(%{}, fn key, acc -> |> Enum.reduce(%{}, fn key, acc ->
@ -210,6 +208,8 @@ def update_credentials(%{assigns: %{user: user}, body_params: params} = conn, _p
if bot, do: {:ok, "Service"}, else: {:ok, "Person"} if bot, do: {:ok, "Service"}, else: {:ok, "Person"}
end) end)
|> Maps.put_if_present(:actor_type, params[:actor_type]) |> Maps.put_if_present(:actor_type, params[:actor_type])
|> Maps.put_if_present(:is_locked, params[:locked])
|> Maps.put_if_present(:is_discoverable, params[:discoverable])
# What happens here: # What happens here:
# #

View file

@ -5,12 +5,12 @@
defmodule Pleroma.Web.MastodonAPI.AppController do defmodule Pleroma.Web.MastodonAPI.AppController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Repo alias Pleroma.Repo
alias Pleroma.Web.OAuth.App alias Pleroma.Web.OAuth.App
alias Pleroma.Web.OAuth.Scopes alias Pleroma.Web.OAuth.Scopes
alias Pleroma.Web.OAuth.Token alias Pleroma.Web.OAuth.Token
alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug
alias Pleroma.Web.Plugs.OAuthScopesPlug
action_fallback(Pleroma.Web.MastodonAPI.FallbackController) action_fallback(Pleroma.Web.MastodonAPI.FallbackController)

View file

@ -15,7 +15,7 @@ defmodule Pleroma.Web.MastodonAPI.AuthController do
action_fallback(Pleroma.Web.MastodonAPI.FallbackController) action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
plug(Pleroma.Plugs.RateLimiter, [name: :password_reset] when action == :password_reset) plug(Pleroma.Web.Plugs.RateLimiter, [name: :password_reset] when action == :password_reset)
@local_mastodon_name "Mastodon-Local" @local_mastodon_name "Mastodon-Local"

View file

@ -8,8 +8,8 @@ defmodule Pleroma.Web.MastodonAPI.ConversationController do
import Pleroma.Web.ControllerHelper, only: [add_link_headers: 2] import Pleroma.Web.ControllerHelper, only: [add_link_headers: 2]
alias Pleroma.Conversation.Participation alias Pleroma.Conversation.Participation
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.Repo alias Pleroma.Repo
alias Pleroma.Web.Plugs.OAuthScopesPlug
action_fallback(Pleroma.Web.MastodonAPI.FallbackController) action_fallback(Pleroma.Web.MastodonAPI.FallbackController)

View file

@ -9,7 +9,7 @@ defmodule Pleroma.Web.MastodonAPI.CustomEmojiController do
plug( plug(
:skip_plug, :skip_plug,
[Pleroma.Plugs.OAuthScopesPlug, Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug] [Pleroma.Web.Plugs.OAuthScopesPlug, Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug]
when action == :index when action == :index
) )

View file

@ -5,8 +5,8 @@
defmodule Pleroma.Web.MastodonAPI.DomainBlockController do defmodule Pleroma.Web.MastodonAPI.DomainBlockController do
use Pleroma.Web, :controller use Pleroma.Web, :controller
alias Pleroma.Plugs.OAuthScopesPlug
alias Pleroma.User alias Pleroma.User
alias Pleroma.Web.Plugs.OAuthScopesPlug
plug(Pleroma.Web.ApiSpec.CastAndValidate) plug(Pleroma.Web.ApiSpec.CastAndValidate)
defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.DomainBlockOperation defdelegate open_api_operation(action), to: Pleroma.Web.ApiSpec.DomainBlockOperation

Some files were not shown because too many files have changed in this diff Show more