diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 88a5c98..0a50fcc 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,37 +1,14 @@ { - "name": "Photos.network Core", - "context": "..", - "dockerFile": "../Dockerfile.dev", - "forwardPorts": [3000], - "postCreateCommand": "mkdir -p config && pip3 install -e .", - "runArgs": ["-e", "GIT_EDITOR=code --wait"], - "extensions": [ - "ms-python.vscode-pylance", - "visualstudioexptteam.vscodeintellicode", - "ms-azure-devops.azure-pipelines", - "redhat.vscode-yaml", - "esbenp.prettier-vscode" - ], - "settings": { - "python.pythonPath": "/usr/local/bin/python", - "python.linting.pylintEnabled": true, - "python.linting.enabled": true, - "python.formatting.provider": "black", - "python.testing.pytestArgs": ["--no-cov"], - "python.testing.pytestEnabled": true, - "editor.formatOnPaste": false, - "editor.formatOnSave": true, - "editor.formatOnType": true, - "files.trimTrailingWhitespace": true, - "terminal.integrated.shell.linux": "/bin/bash", - "yaml.customTags": [ - "!input scalar", - "!secret scalar", - "!include_dir_named scalar", - "!include_dir_list scalar", - "!include_dir_merge_list scalar", - "!include_dir_merge_named scalar" - ] - } - } - \ No newline at end of file + "name": "Photos.network core", + "image": "mcr.microsoft.com/devcontainers/rust:0-1-bullseye", + "appPort": [ + "7777:7777" + ], + "extensions": [ + "rust-lang.rust-analyzer", + "swellaby.vscode-rust-test-adapter", + "ms-vscode.test-adapter-converter" + ], + "postCreateCommand": "rustc --version", + "remoteUser": "vscode" +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3edb0b5 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,34 @@ +# Include any files or directories that you don't want to be copied to your +# container here (e.g., local build artifacts, temporary files, etc.). +# +# For more help, visit the .dockerignore file reference guide at +# https://docs.docker.com/engine/reference/builder/#dockerignore-file + +**/.DS_Store +**/__pycache__ +**/.venv +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/bin +**/charts +**/docker-compose* +**/compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a0010e4..240e595 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,7 +3,4 @@ # https://github.blog/2017-07-06-introducing-code-owners/ # Add a fallback to default owners -* @thebino - -# setup can be reviewed by the core team -setup.py @photos.network/core +* @photos-network/core-team diff --git a/.github/actions-rs/grcov.yml b/.github/actions-rs/grcov.yml new file mode 100644 index 0000000..2ef4c15 --- /dev/null +++ b/.github/actions-rs/grcov.yml @@ -0,0 +1,2 @@ +output-type: lcov +output-file: ./lcov.info diff --git a/.github/codecov.yml b/.github/codecov.yml new file mode 100644 index 0000000..ff4f571 --- /dev/null +++ b/.github/codecov.yml @@ -0,0 +1,21 @@ +# ref: https://docs.codecov.com/docs/codecovyml-reference +coverage: + # Hold ourselves to a high bar + range: 85..100 + round: down + precision: 1 + status: + # ref: https://docs.codecov.com/docs/commit-status + project: + default: + # Avoid false negatives + threshold: 1% + +# Test files aren't important for coverage +ignore: + - "tests" + +# Make comments less noisy +comment: + layout: "files" + require_changes: yes diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..05e9ab9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + - package-ecosystem: cargo + directory: / + schedule: + interval: weekly + ignore: + - dependency-name: "*" + # patch and minor updates don't matter for libraries + # remove this ignore rule if your package has binaries + update-types: + - "version-update:semver-patch" + - "version-update:semver-minor" diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 0000000..527486c --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,24 @@ +# Configuration file for [stale](https://github.com/apps/stale) + +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 + +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 + +# Issues with these labels will never be considered stale +exemptLabels: + - pinned + - security + +# Label to use when marking an issue as stale +staleLabel: wontfix + +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. + +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/.github/workflows/check.yaml b/.github/workflows/check.yaml new file mode 100644 index 0000000..93bf98a --- /dev/null +++ b/.github/workflows/check.yaml @@ -0,0 +1,87 @@ +name: check code quality + +on: [push] + +jobs: + check: + name: Check + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v3 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + + - name: Run cargo check + uses: actions-rs/cargo@v1 + with: + command: check + + test: + name: Tests + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v3 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + + - name: Run cargo test + uses: actions-rs/cargo@v1 + with: + command: test + args: --workspace --all-targets + # env: + # CARGO_INCREMENTAL: '0' + # RUSTFLAGS: '-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off -Cpanic=abort -Zpanic_abort_tests' + # RUSTDOCFLAGS: '-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off -Cpanic=abort -Zpanic_abort_tests' + + # - name: rust-grcov + # # You may pin to the exact commit or the version. + # # uses: actions-rs/grcov@bb47b1ed7883a1502fa6875d562727ace2511248 + # uses: actions-rs/grcov@v0.1 + + # - name: Upload coverage reports to Codecov + # uses: codecov/codecov-action@v3 + # env: + # CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + # with: + # verbose: true + # fail_ci_if_error: false + + lints: + name: Lint checks + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v3 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + components: rustfmt, clippy + + - name: Run cargo fmt + uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + - name: Run cargo clippy + uses: actions-rs/cargo@v1 + with: + command: clippy + args: -- -D warnings diff --git a/.gitignore b/.gitignore index 2d36077..a097bec 100644 --- a/.gitignore +++ b/.gitignore @@ -1,62 +1,22 @@ -# pytest -.pytest_cache -.cache +### Rust ### +debug/ +target/ -# GITHUB Proposed Python stuff: -*.py[cod] +# These are backup files generated by rustfmt +**/*.rs.bk -# C extensions -*.so +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb -# Packages -*.egg -*.egg-info -dist -build -eggs -.eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg -lib -lib64 -pip-wheel-metadata -# Logs -*.log -pip-log.txt +### IntelliJ ### +.idea/ -# Unit test / coverage reports -.coverage -.tox -coverage.xml -nosetests.xml -htmlcov/ -test-reports/ -test-results.xml -test-output.xml +# data directory +/data -# Translations -*.mo +# config directory +/config -# venv stuff -pyvenv.cfg -pip-selfcheck.json -venv -.venv -Pipfile* -share/* -/Scripts/ - -# Visual Studio Code -.vscode/* -!.vscode/cSpell.json -!.vscode/extensions.json -!.vscode/tasks.json -.env - -# Built docs -docs/build +# logs directory +/logs diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 9511341..b1f59e6 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,3 +1,12 @@ { - "recommendations": ["esbenp.prettier-vscode", "ms-python.python"] + "recommendations": [ + "rust-lang.rust-analyzer", + "tamasfe.even-better-toml", + "serayuzgur.crates", + "rangav.vscode-thunder-client", + "usernamehw.errorlens", + "dracula-theme.theme-dracula", + "vadimcn.vscode-lldb", + "ms-vscode.cpptools", + ], } diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..b1136c7 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Photos.network (OSX)", + "type": "lldb", + "request": "launch", + "program": "${workspaceRoot}/target/debug/core", + "args": [], + "cwd": "${workspaceRoot}" + }, + { + "name": "Photos.network (Windows)", + "type": "cppvsdbg", + "request": "launch", + "program": "${workspaceRoot}/target/debug/core.exe", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceRoot}", + "environment": [], + "externalConsole": true + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..7cb48bb --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,21 @@ +{ + "terminal.integrated.defaultProfile.osx": "zsh", + "editor.semanticTokenColorCustomizations": { + "rules": { + "*.mutable": { + "fontStyle": "", // set to empty string to disable underline, which is the default + }, + } + }, + "rust-analyzer.linkedProjects": [ + "./crates/accounts/Cargo.toml", + "./crates/activity_pub/Cargo.toml", + "./crates/common/Cargo.toml", + "./crates/media/Cargo.toml", + "./crates/oauth_authentication/Cargo.toml", + "./crates/oauth_authorization_server/Cargo.toml" + ], + "rust-analyzer.showUnlinkedFileNotification": false, + "debug.allowBreakpointsEverywhere": true, + "rest-client.followredirect": false +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index dbd7bcb..65e9c5e 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,77 +1,28 @@ { "version": "2.0.0", - "tasks": [ - { - "label": "Pytest", - "type": "shell", - "command": "pytest --timeout=10 tests", - "dependsOn": ["Install all Test Requirements"], - "group": { - "kind": "test", - "isDefault": true - }, - "presentation": { - "reveal": "always", - "panel": "new" - }, - "problemMatcher": [] - }, - { - "label": "Flake8", - "type": "shell", - "command": "pre-commit run flake8 --all-files", - "group": { - "kind": "test", - "isDefault": true - }, - "presentation": { - "reveal": "always", - "panel": "new" - }, - "problemMatcher": [] - }, - { - "label": "Pylint", - "type": "shell", - "command": "pylint photos", - "dependsOn": ["Install all Requirements"], - "group": { - "kind": "test", - "isDefault": true - }, - "presentation": { - "reveal": "always", - "panel": "new" - }, - "problemMatcher": [] - }, -{ - "label": "Install all Requirements", - "type": "shell", - "command": "pip3 install -r requirements_all.txt", - "group": { - "kind": "build", - "isDefault": true - }, - "presentation": { - "reveal": "always", - "panel": "new" - }, - "problemMatcher": [] - }, - { - "label": "Install all Test Requirements", - "type": "shell", - "command": "pip3 install -r requirements_test_all.txt", - "group": { - "kind": "build", - "isDefault": true - }, - "presentation": { - "reveal": "always", - "panel": "new" - }, - "problemMatcher": [] + "tasks": [{ + "label": "cargo build", + "type": "shell", + "command": "cargo build", + "args": [], + "group": { + "kind": "build", + "isDefault": true + } + }, + { + "label": "cargo run", + "type": "shell", + "command": "cargo", + "args": [ + "run" + // "--release", + // "--", + // "arg1" + ], + "group": { + "kind": "build", + "isDefault": true } - ] + }] } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c87c607 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,61 @@ +## [Unreleased] +### Changed +- Rust rewrite +- License changed to AGPL + + +## [0.5.1] - 2022-07-07 +### Removed +- unused client_secret from oauth calls + + +## [0.5.0] - 2022-07-07 +### Added +- generate random client credentials to fallback configuration + +### Changed +- renamed configuration file to `core_configuration.json` + + +## [0.4.0] - 2021-12-11 +### Added +- system port to image response + +### Changed +- return with `HTTPUnauthorized` instead of `HTTPForbidden` + + +## [0.3.0] - 2021-10-03 +### Added +- Enrich photo list metadata + +### Changed +- changed request url to `api` instead of `v1` + + +## [0.2.1] - 2020-05-09 +### Changed +- trim and lowercase username on oauth login + + +## [0.2.0] - 2020-05-06 +### Added +- dynamic client loading from `configuration.json` +- simplified user management + + +## [0.0.1] - 2021-03-11 +### Added +- integrated oauth authorization server +- dynamic addon loading with dedicated setup step +- async file logging + + +[unreleased]: https://github.com/photos-network/core/compare/Release/v0.5.1...HEAD +[0.5.1]: https://github.com/photos-network/core/compare/Release/v0.5.0...Release/v0.5.1 +[0.5.0]: https://github.com/photos-network/core/compare/Release/v0.4.0...Release/v0.5.0 +[0.4.0]: https://github.com/photos-network/core/compare/Release/v0.3.0...Release/v0.4.0 +[0.3.0]: https://github.com/photos-network/core/compare/Release/v0.2.1...Release/v0.3.0 +[0.2.1]: https://github.com/photos-network/core/compare/Release/v0.2.0...Release/v0.2.1 +[0.2.0]: https://github.com/photos-network/core/compare/Release/v0.0.1...Release/v0.2.0 +[0.0.1]: https://github.com/photos-network/core/releases/tag/Release/v0.0.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..7d98688 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,102 @@ +# Welcome to Photos.network + +This is a **FOSS** (free and open-source software) and lives from contributions of the community. + +There are many ways to contribute: + + * ๐Ÿ“ฃ Spread the project or its apps to the world + * โœ๏ธ Writing tutorials and blog posts + * ๐Ÿ“ Create or update the documentation + * ๐Ÿ› Submit bug reports + * ๐Ÿ’ก Adding ideas and feature requests to Discussions + * ๐Ÿ‘ฉโ€๐ŸŽจ Create designs or UX flows + * ๐Ÿง‘โ€๐Ÿ’ป Contribute code or review PRs + + + +## ๐Ÿ“œ Ground Rules + +A community like this should be **open**, **considerate** and **respectful**. + +Behaviours that reinforce these values contribute to a positive environment, and include: + + * **Being open**. Members of the community are open to collaboration, whether it's on PEPs, patches, problems, or otherwise. + * **Focusing on what is best for the community**. We're respectful of the processes set forth in the community, and we work within them. + * **Acknowledging time and effort**. We're respectful of the volunteer efforts that permeate the Python community. We're thoughtful when addressing the efforts of others, keeping in mind that often times the labor was completed simply for the good of the community. + * **Being respectful of differing viewpoints and experiences**. We're receptive to constructive comments and criticism, as the experiences and skill sets of other members contribute to the whole of our efforts. + * **Showing empathy towards other community members**. We're attentive in our communications, whether in person or online, and we're tactful when approaching differing views. + * **Being considerate**. Members of the community are considerate of their peers -- other Python users. + * **Being respectful**. We're respectful of others, their positions, their skills, their commitments, and their efforts. + * **Gracefully accepting constructive criticism**. When we disagree, we are courteous in raising our issues. + * **Using welcoming and inclusive language**. We're accepting of all who wish to take part in our activities, fostering an environment where anyone can participate and everyone can make a difference. + + + +## ๐Ÿง‘โ€๐Ÿ’ป Code Contribution + +To contribute code to the repository, you don't need any permissions. +First start by forking the repository, clone and checkout your clone and start coding. +When you're happy with your changes, create Atomic commits on a **new feature branch** and push it to ***your*** fork. + +Atomic commits will make it easier to track down regressions. Also, it enables the ability to cherry-pick or revert a change if needed. + +1. Fork it (https://github.com/photos-network/core/fork) +2. Create a new feature branch (`git checkout -b feature/fooBar`) +3. Commit your changes (`git commit -am 'Add some fooBar'`) +4. Push to the branch (`git push origin feature/fooBar`) +5. Create a new Pull Request + + + +## ๐Ÿ› How to report a bug + +> If you find a security vulnerability, do NOT open an issue. Email [security@photos.network](mailto:security@photos.network) instead. See [SECURITY.md](./SECURITY.md) for details. + +1. Open the [issues tab](https://github.com/photos-network/core/issues) on github +2. Click on [New issue](https://github.com/photos-network/core/issues/new/choose) +3. Choose the bug report ๐Ÿ› template and fill out all required fields + + + +## ๐Ÿ’ก How to suggest a feature or enhancement + +Check [open issues](https://github.com/photos-network/core/issues) for a list of proposed features. + +If your suggestion can not be found already, see if it is already covered by our [Roadmap](https://github.com/photos-network/core/#roadmap). + + + +## ๐Ÿ“Ÿ Communication + +To get in touch with the community join our [Discord](https://img.shields.io/discord/793235453871390720) or write use on Mastodon: [@photos@mastodon.cloud](https://mastodon.cloud/@photos). + + + +## ๐Ÿ’พ Technology + +The project is written in [Rust](https://rust-lang.org/) + +Underneath it is using these frameworks: + +* [tokio](https://github.com/tokio-rs/tokio) - an asynchronous runtime +* [tower](https://github.com/tower-rs/tower) - for networking +* [axum](https://github.com/tokio-rs/axum) - as web framework +* [abi_stable](https://github.com/rodrimati1992/abi_stable_crates) - FFI for dynamic library loading + + + +## ๐Ÿ’ป Build & Run + +To build and run the core + +```shell +$ cargo run +``` + +### ๐Ÿ”ฌ Verifications + +To run tests + +```shell +$ cargo test +``` diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0107434 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4002 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "abi_stable" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "467388fe07f5a809f4df42226142cadd5a7706810b76a0896fd68d156b1ea886" +dependencies = [ + "abi_stable_derive", + "abi_stable_shared", + "const_panic", + "core_extensions", + "crossbeam-channel", + "generational-arena", + "libloading", + "lock_api", + "parking_lot", + "paste", + "repr_offset", + "rustc_version", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "abi_stable_derive" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aecd3efa5a5294f5c67913d45f985ccb382b3c93327581529610eeecdf4821a" +dependencies = [ + "abi_stable_shared", + "as_derive_utils", + "core_extensions", + "proc-macro2", + "quote", + "rustc_version", + "syn 1.0.109", + "typed-arena", +] + +[[package]] +name = "abi_stable_shared" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b5df7688c123e63f4d4d649cba63f2967ba7f7861b1664fca3f77d3dad2b63" +dependencies = [ + "core_extensions", +] + +[[package]] +name = "accounts" +version = "0.6.0" +dependencies = [ + "axum", + "common", + "database", + "mockall", + "rstest", + "serde", + "tower-http", +] + +[[package]] +name = "activity_pub" +version = "0.6.0" +dependencies = [ + "activitypub_federation", + "common", +] + +[[package]] +name = "activitypub_federation" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e6e7fefba6602240fcf612931b70640ad1e249dff833551ebc218f1c96a4193" +dependencies = [ + "activitystreams-kinds", + "actix-web", + "anyhow", + "async-trait", + "axum", + "base64 0.21.2", + "bytes", + "chrono", + "derive_builder", + "dyn-clone", + "enum_delegate", + "futures-core", + "http", + "http-signature-normalization", + "http-signature-normalization-reqwest", + "httpdate", + "hyper", + "itertools", + "once_cell", + "openssl", + "pin-project-lite", + "regex", + "reqwest", + "reqwest-middleware", + "serde", + "serde_json", + "sha2", + "thiserror", + "tokio", + "tower", + "tracing", + "url", +] + +[[package]] +name = "activitystreams-kinds" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e97dfe76efd8c0b113cc3580a6b5f4acba47662e3cfbbfcce081c9ac89798990" +dependencies = [ + "serde", + "url", +] + +[[package]] +name = "actix-codec" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617a8268e3537fe1d8c9ead925fca49ef6400927ee7bc26750e90ecee14ce4b8" +dependencies = [ + "bitflags 1.3.2", + "bytes", + "futures-core", + "futures-sink", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-http" +version = "3.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2079246596c18b4a33e274ae10c0e50613f4d32a4198e09c7b93771013fed74" +dependencies = [ + "actix-codec", + "actix-rt", + "actix-service", + "actix-utils", + "ahash 0.8.3", + "base64 0.21.2", + "bitflags 1.3.2", + "bytes", + "bytestring", + "derive_more", + "encoding_rs", + "futures-core", + "h2", + "http", + "httparse", + "httpdate", + "itoa", + "language-tags", + "local-channel", + "mime", + "percent-encoding", + "pin-project-lite", + "rand", + "sha1", + "smallvec", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-router" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66ff4d247d2b160861fa2866457e85706833527840e4133f8f49aa423a38799" +dependencies = [ + "bytestring", + "http", + "regex", + "serde", + "tracing", +] + +[[package]] +name = "actix-rt" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15265b6b8e2347670eb363c47fc8c75208b4a4994b27192f345fcbe707804f3e" +dependencies = [ + "futures-core", + "tokio", +] + +[[package]] +name = "actix-server" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e8613a75dd50cc45f473cee3c34d59ed677c0f7b44480ce3b8247d7dc519327" +dependencies = [ + "actix-rt", + "actix-service", + "actix-utils", + "futures-core", + "futures-util", + "mio", + "num_cpus", + "socket2 0.4.9", + "tokio", + "tracing", +] + +[[package]] +name = "actix-service" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a" +dependencies = [ + "futures-core", + "paste", + "pin-project-lite", +] + +[[package]] +name = "actix-utils" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8" +dependencies = [ + "local-waker", + "pin-project-lite", +] + +[[package]] +name = "actix-web" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd3cb42f9566ab176e1ef0b8b3a896529062b4efc6be0123046095914c4c1c96" +dependencies = [ + "actix-codec", + "actix-http", + "actix-router", + "actix-rt", + "actix-server", + "actix-service", + "actix-utils", + "ahash 0.7.6", + "bytes", + "bytestring", + "cfg-if", + "derive_more", + "encoding_rs", + "futures-core", + "futures-util", + "http", + "itoa", + "language-tags", + "log", + "mime", + "once_cell", + "pin-project-lite", + "regex", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "socket2 0.4.9", + "time 0.3.27", + "url", +] + +[[package]] +name = "addr2line" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "ahash" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +dependencies = [ + "getrandom", + "once_cell", + "version_check", +] + +[[package]] +name = "ahash" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b13c32d80ecc7ab747b80c3784bce54ee8a7a0cc4fbda9bf4cda2cf6fe90854" + +[[package]] +name = "as_derive_utils" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff3c96645900a44cf11941c111bd08a6573b0e2f9f69bc9264b179d8fae753c4" +dependencies = [ + "core_extensions", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "async-trait" +version = "0.1.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "auto-future" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c1e7e457ea78e524f48639f551fd79703ac3f2237f5ecccdf4708f8a75ad373" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "axum" +version = "0.6.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" +dependencies = [ + "async-trait", + "axum-core", + "base64 0.21.2", + "bitflags 1.3.2", + "bytes", + "futures-util", + "headers", + "http", + "http-body", + "hyper", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "mime", + "rustversion", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-test" +version = "12.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e990c7052d8cb6a5a4351f325513c3f0347c15811c4a4e00a30e548576c5088f" +dependencies = [ + "anyhow", + "auto-future", + "axum", + "bytes", + "cookie", + "http", + "hyper", + "lazy_static", + "portpicker", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "tokio", + "url", +] + +[[package]] +name = "backtrace" +version = "0.3.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" + +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" +dependencies = [ + "serde", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "bytes" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" + +[[package]] +name = "bytestring" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238e4886760d98c4f899360c834fa93e62cf7f721ac3c2da375cbdf4b8679aae" +dependencies = [ + "bytes", +] + +[[package]] +name = "camino" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cfa25e60aea747ec7e1124f238816749faa93759c6ff5b31f1ccdda137f4479" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4acbb09d9ee8e23699b9634375c72795d095bf268439da88562cf9b501f181fa" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", +] + +[[package]] +name = "cc" +version = "1.0.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "305fe645edc1442a0fa8b6726ba61d422798d37a52e12eaecf4b022ebbb88f01" +dependencies = [ + "libc", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "time 0.1.45", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "common" +version = "0.6.0" +dependencies = [ + "async-trait", + "axum", + "http", + "photos_network_plugin", + "serde", + "serde_json", + "serde_with", + "testdir", + "time 0.3.27", + "tracing", + "uuid", +] + +[[package]] +name = "const-oid" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" + +[[package]] +name = "const_panic" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6051f239ecec86fde3410901ab7860d458d160371533842974fc61f96d15879b" + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "cookie" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7efb37c3e1ccb1ff97164ad95ac1606e8ccd35b3fa0a7d99a304c7f4a428cc24" +dependencies = [ + "time 0.3.27", + "version_check", +] + +[[package]] +name = "core" +version = "0.6.0" +dependencies = [ + "abi_stable", + "accounts", + "activity_pub", + "anyhow", + "axum", + "common", + "core_extensions", + "database", + "media", + "oauth_authentication", + "oauth_authorization_server", + "photos_network_plugin", + "pretty_assertions", + "reqwest", + "serde", + "serde_json", + "serde_urlencoded", + "sqlx", + "tokio", + "tokio-stream", + "tokio-util", + "tower-http", + "tracing", + "tracing-appender", + "tracing-subscriber", +] + +[[package]] +name = "core-foundation" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" + +[[package]] +name = "core_extensions" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92c71dc07c9721607e7a16108336048ee978c3a8b129294534272e8bac96c0ee" +dependencies = [ + "core_extensions_proc_macros", +] + +[[package]] +name = "core_extensions_proc_macros" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f3b219d28b6e3b4ac87bc1fc522e0803ab22e055da177bff0068c4150c61a6" + +[[package]] +name = "cpufeatures" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484" + +[[package]] +name = "crossbeam-channel" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4c2f4e1afd912bc40bfd6fed5d9dc1f288e0ba01bfcc835cc5bc3eb13efe15" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +dependencies = [ + "darling_core 0.14.4", + "darling_macro 0.14.4", +] + +[[package]] +name = "darling" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" +dependencies = [ + "darling_core 0.20.3", + "darling_macro 0.20.3", +] + +[[package]] +name = "darling_core" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.28", +] + +[[package]] +name = "darling_macro" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +dependencies = [ + "darling_core 0.14.4", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" +dependencies = [ + "darling_core 0.20.3", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "data-encoding" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" + +[[package]] +name = "database" +version = "0.6.0" +dependencies = [ + "async-trait", + "common", + "pretty_assertions", + "sqlx", + "testdir", + "time 0.3.27", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "der" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7684a49fb1af197853ef7b2ee694bc1f5b4179556f1e5710e1760c5db6f5e929" +dependencies = [ + "serde", +] + +[[package]] +name = "derive_builder" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d67778784b508018359cbc8696edb3db78160bab2c2a28ba7f56ef6932997f8" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c11bdc11a0c47bc7d37d582b5285da6849c96681023680b906673c5707af7b0f" +dependencies = [ + "darling 0.14.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_macro" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebcda35c7a396850a55ffeac740804b40ffec779b98fffbb1738f4033f0ee79e" +dependencies = [ + "derive_builder_core", + "syn 1.0.109", +] + +[[package]] +name = "derive_more" +version = "0.99.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 1.0.109", +] + +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "downcast" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" + +[[package]] +name = "dyn-clone" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "304e6508efa593091e97a9abbc10f90aa7ca635b6d2784feff3c89d41dd12272" + +[[package]] +name = "ecdsa" +version = "0.16.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "either" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" +dependencies = [ + "serde", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "968405c8fdc9b3bf4df0a6638858cc0b52462836ab6b1c87377785dd09cf1c0b" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "encoding_rs" +version = "0.8.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "enum_delegate" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8ea75f31022cba043afe037940d73684327e915f88f62478e778c3de914cd0a" +dependencies = [ + "enum_delegate_lib", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "enum_delegate_lib" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e1f6c3800b304a6be0012039e2a45a322a093539c45ab818d9e6895a39c90fe" +dependencies = [ + "proc-macro2", + "quote", + "rand", + "syn 1.0.109", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b30f669a7961ef1631673d2766cc92f52d64f7ef354d4fe0ddfd30ed52f0f4f" +dependencies = [ + "errno-dragonfly", + "libc", + "windows-sys", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "fastrand" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" + +[[package]] +name = "ff" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +dependencies = [ + "num-traits", +] + +[[package]] +name = "flume" +version = "0.10.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1657b4441c3403d9f7b3409e47575237dac27b1b5726df654a6ecbf92f0f7577" +dependencies = [ + "futures-core", + "futures-sink", + "pin-project", + "spin 0.9.8", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fragile" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" + +[[package]] +name = "futures" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" + +[[package]] +name = "futures-executor" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" + +[[package]] +name = "futures-macro" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "futures-sink" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" + +[[package]] +name = "futures-task" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" + +[[package]] +name = "futures-timer" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" + +[[package]] +name = "futures-util" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generational-arena" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877e94aff08e743b651baaea359664321055749b398adff8740a7399af7796e7" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "h2" +version = "0.3.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap 1.9.3", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +dependencies = [ + "ahash 0.7.6", +] + +[[package]] +name = "hashbrown" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" +dependencies = [ + "ahash 0.8.3", + "allocator-api2", +] + +[[package]] +name = "hashlink" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312f66718a2d7789ffef4f4b7b213138ed9f1eb3aa1d0d82fc99f88fb3ffd26f" +dependencies = [ + "hashbrown 0.14.0", +] + +[[package]] +name = "headers" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3e372db8e5c0d213e0cd0b9be18be2aca3d44cf2fe30a9d46a65581cd454584" +dependencies = [ + "base64 0.13.1", + "bitflags 1.3.2", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", +] + +[[package]] +name = "headers-core" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" +dependencies = [ + "http", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "hermit-abi" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "http" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "http-range-header" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" + +[[package]] +name = "http-signature-normalization" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b95e3149194de5f3f9d5225bcc6a8677979f8ff8ce39c85654730ad4824f101e" +dependencies = [ + "httpdate", +] + +[[package]] +name = "http-signature-normalization-reqwest" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c382c69a07b21accae86298d520579403af6479b1cd1c389e3ee11f01d48627" +dependencies = [ + "base64 0.13.1", + "http-signature-normalization", + "httpdate", + "reqwest", + "reqwest-middleware", + "sha2", + "thiserror", + "tokio", +] + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "hyper" +version = "0.14.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2 0.4.9", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d78e1e73ec14cf7375674f74d7dde185c8206fd9dea6fb6295e8a98098aaa97" +dependencies = [ + "futures-util", + "http", + "hyper", + "rustls", + "tokio", + "tokio-rustls", +] + +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +dependencies = [ + "equivalent", + "hashbrown 0.14.0", + "serde", +] + +[[package]] +name = "ipnet" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" + +[[package]] +name = "js-sys" +version = "0.3.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "language-tags" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +dependencies = [ + "spin 0.5.2", +] + +[[package]] +name = "libc" +version = "0.2.147" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libm" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" + +[[package]] +name = "libsqlite3-sys" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503" + +[[package]] +name = "local-channel" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f303ec0e94c6c54447f84f3b0ef7af769858a9c4ef56ef2a986d3dcd4c3fc9c" +dependencies = [ + "futures-core", + "futures-sink", + "futures-util", + "local-waker", +] + +[[package]] +name = "local-waker" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34f76eb3611940e0e7d53a9aaa4e6a3151f69541a282fd0dad5571420c53ff1" + +[[package]] +name = "lock_api" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" + +[[package]] +name = "matchit" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed1202b2a6f884ae56f04cff409ab315c5ce26b5e58d7412e484f01fd52f52ef" + +[[package]] +name = "md-5" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca" +dependencies = [ + "digest", +] + +[[package]] +name = "media" +version = "0.6.0" +dependencies = [ + "axum", + "common", + "database", + "hyper", + "mime", + "mockall", + "rand", + "rstest", + "serde", + "serde_json", + "sqlx", + "tempfile", + "testdir", + "time 0.3.27", + "tokio", + "tower", + "tower-http", + "tracing", + "uuid", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +dependencies = [ + "libc", + "log", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys", +] + +[[package]] +name = "mockall" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c84490118f2ee2d74570d114f3d0493cbf02790df303d2707606c3e14e07c96" +dependencies = [ + "cfg-if", + "downcast", + "fragile", + "lazy_static", + "mockall_derive", + "predicates", + "predicates-tree", +] + +[[package]] +name = "mockall_derive" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" +dependencies = [ + "cfg-if", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "multer" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01acbdc23469fd8fe07ab135923371d5f5a422fbf9c522158677c8eb15bc51c2" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "log", + "memchr", + "mime", + "spin 0.9.8", + "version_check", +] + +[[package]] +name = "native-tls" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "ntapi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" +dependencies = [ + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151" +dependencies = [ + "byteorder", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "oauth2" +version = "4.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09a6e2a2b13a56ebeabba9142f911745be6456163fd6c3d361274ebcd891a80c" +dependencies = [ + "base64 0.13.1", + "chrono", + "getrandom", + "http", + "rand", + "reqwest", + "serde", + "serde_json", + "serde_path_to_error", + "sha2", + "thiserror", + "url", +] + +[[package]] +name = "oauth_authentication" +version = "0.6.0" +dependencies = [ + "anyhow", + "axum", + "axum-test", + "openidconnect", + "rand", + "serde_json", + "testdir", + "thiserror", + "tokio", + "tower-http", + "tracing", + "tracing-subscriber", + "url", +] + +[[package]] +name = "oauth_authorization_server" +version = "0.6.0" +dependencies = [ + "axum", + "axum-test", + "chrono", + "openidconnect", + "rand", + "rsa", + "serde", + "serde_json", + "testdir", + "thiserror", + "tokio", + "tower-http", + "tracing", + "tracing-subscriber", + "url", + "uuid", +] + +[[package]] +name = "object" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" + +[[package]] +name = "openidconnect" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03335ade401352b354b017e7597ddb40040091da445b031bf659e597e032b1fc" +dependencies = [ + "base64 0.13.1", + "chrono", + "dyn-clone", + "hmac", + "http", + "itertools", + "log", + "oauth2", + "p256", + "p384", + "rand", + "rsa", + "serde", + "serde-value", + "serde_derive", + "serde_json", + "serde_path_to_error", + "serde_plain", + "serde_with", + "sha2", + "subtle", + "thiserror", + "url", +] + +[[package]] +name = "openssl" +version = "0.10.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "729b745ad4a5575dd06a3e1af1414bd330ee561c01b3899eb584baeaa8def17e" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "866b5f16f90776b9bb8dc1e1802ac6f0513de3a7a7465867bfbc563dc737faac" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "ordered-float" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7940cf2ca942593318d07fcf2596cdca60a85c9e7fab408a5e21a4f9dcd40d87" +dependencies = [ + "num-traits", +] + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70786f51bcc69f6a4c0360e063a4cac5419ef7c5cd5b3c99ad70f3be5ba79209" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets", +] + +[[package]] +name = "paste" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" + +[[package]] +name = "photos_network_plugin" +version = "0.2.0" +dependencies = [ + "abi_stable", + "core_extensions", +] + +[[package]] +name = "pin-project" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cc1b0bf1727a77a54b6654e7b5f1af8604923edc8b81885f8ec92f9e3f0a05" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" + +[[package]] +name = "portpicker" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be97d76faf1bfab666e1375477b23fde79eccf0276e9b63b92a39d676a889ba9" +dependencies = [ + "rand", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "predicates" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59230a63c37f3e18569bdb90e4a89cbf5bf8b06fea0b84e65ea10cc4df47addd" +dependencies = [ + "difflib", + "float-cmp", + "itertools", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b794032607612e7abeb4db69adb4e33590fa6cf1149e95fd7cb00e634b92f174" + +[[package]] +name = "predicates-tree" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368ba315fb8c5052ab692e68a0eefec6ec57b23a36959c14496f0b0df2c0cecf" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "pretty_assertions" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66" +dependencies = [ + "diff", + "yansi", +] + +[[package]] +name = "primeorder" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c2fcef82c0ec6eefcc179b978446c399b3cdf73c392c35604e399eee6df1ee3" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "regex" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bc1d4caf89fac26a70747fe603c130093b53c773888797a6329091246d651a" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2" + +[[package]] +name = "relative-path" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bf2521270932c3c7bed1a59151222bd7643c79310f2916f01925e1e16255698" + +[[package]] +name = "repr_offset" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb1070755bd29dffc19d0971cab794e607839ba2ef4b69a9e6fbc8733c1b72ea" +dependencies = [ + "tstr", +] + +[[package]] +name = "reqwest" +version = "0.11.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" +dependencies = [ + "base64 0.21.2", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "hyper", + "hyper-rustls", + "hyper-tls", + "ipnet", + "js-sys", + "log", + "mime", + "mime_guess", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-native-tls", + "tokio-rustls", + "tokio-util", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", + "winreg", +] + +[[package]] +name = "reqwest-middleware" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff44108c7925d082f2861e683a88618b68235ad9cdc60d64d9d1188efc951cdb" +dependencies = [ + "anyhow", + "async-trait", + "http", + "reqwest", + "serde", + "task-local-extensions", + "thiserror", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin 0.5.2", + "untrusted", + "web-sys", + "winapi", +] + +[[package]] +name = "rsa" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ab43bb47d23c1a631b4b680199a45255dce26fa9ab2fa902581f624ff13e6a8" +dependencies = [ + "byteorder", + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-iter", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rstest" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97eeab2f3c0a199bc4be135c36c924b6590b88c377d416494288c14f2db30199" +dependencies = [ + "futures", + "futures-timer", + "rstest_macros", + "rustc_version", +] + +[[package]] +name = "rstest_macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d428f8247852f894ee1be110b375111b586d4fa431f6c46e64ba5a0dcccbe605" +dependencies = [ + "cfg-if", + "glob", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.28", + "unicode-ident", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "172891ebdceb05aa0005f533a6cbfca599ddd7d966f6f5d4d9b2e70478e70399" +dependencies = [ + "bitflags 2.3.3", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustls" +version = "0.21.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1feddffcfcc0b33f5c6ce9a29e341e4cd59c3f78e7ee45f4a40c038b1d6cbb" +dependencies = [ + "log", + "ring", + "rustls-webpki", + "sct", +] + +[[package]] +name = "rustls-pemfile" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" +dependencies = [ + "base64 0.21.2", +] + +[[package]] +name = "rustls-webpki" +version = "0.101.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261e9e0888cba427c3316e6322805653c9425240b6fd96cee7cb671ab70ab8d0" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" + +[[package]] +name = "ryu" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" + +[[package]] +name = "schannel" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sct" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "security-framework" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" +dependencies = [ + "serde", +] + +[[package]] +name = "serde" +version = "1.0.187" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7fe14252655bd1e578af19f5fa00fe02fd0013b100ca6b49fde31c41bae4c" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.187" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e46b2a6ca578b3f1d4501b12f78ed4692006d79d82a1a7c561c12dbc3d625eb8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "serde_json" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076066c5f1078eac5b722a31827a8832fe108bed65dfa75e233c89f8206e976c" +dependencies = [ + "indexmap 2.0.0", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335" +dependencies = [ + "itoa", + "serde", +] + +[[package]] +name = "serde_plain" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6018081315db179d0ce57b1fe4b62a12a0028c9cf9bbef868c9cf477b3c34ae" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237" +dependencies = [ + "base64 0.21.2", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.0.0", + "serde", + "serde_json", + "serde_with_macros", + "time 0.3.27", +] + +[[package]] +name = "serde_with_macros" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6be15c453eb305019bfa438b1593c731f36a289a7853f7707ee29e870b3b3c" +dependencies = [ + "darling 0.20.3", + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "sha1" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] + +[[package]] +name = "signature" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "slab" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" + +[[package]] +name = "socket2" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "socket2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2538b18701741680e0322a2302176d3253a35388e2e62f172f64f4f16605f877" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1e996ef02c474957d681f1b05213dfb0abab947b446a62d37770b23500184a" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlformat" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c12bc9199d1db8234678b7051747c07f517cdcf019262d1847b94ec8b1aee3e" +dependencies = [ + "itertools", + "nom", + "unicode_categories", +] + +[[package]] +name = "sqlx" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e58421b6bc416714d5115a2ca953718f6c621a51b68e4f4922aea5a4391a721" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd4cef4251aabbae751a3710927945901ee1d97ee96d757f6880ebb9a79bfd53" +dependencies = [ + "ahash 0.8.3", + "atoi", + "byteorder", + "bytes", + "crc", + "crossbeam-queue", + "dotenvy", + "either", + "event-listener", + "futures-channel", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashlink", + "hex", + "indexmap 2.0.0", + "log", + "memchr", + "native-tls", + "once_cell", + "paste", + "percent-encoding", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlformat", + "thiserror", + "time 0.3.27", + "tokio", + "tokio-stream", + "tracing", + "url", +] + +[[package]] +name = "sqlx-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "208e3165167afd7f3881b16c1ef3f2af69fa75980897aac8874a0696516d12c2" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 1.0.109", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a4a8336d278c62231d87f24e8a7a74898156e34c1c18942857be2acb29c7dfc" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 1.0.109", + "tempfile", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca69bf415b93b60b80dc8fda3cb4ef52b2336614d8da2de5456cc942a110482" +dependencies = [ + "atoi", + "base64 0.21.2", + "bitflags 2.3.3", + "byteorder", + "bytes", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "time 0.3.27", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0db2df1b8731c3651e204629dd55e52adbae0462fa1bdcbed56a2302c18181e" +dependencies = [ + "atoi", + "base64 0.21.2", + "bitflags 2.3.3", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "time 0.3.27", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4c21bf34c7cae5b283efb3ac1bcc7670df7561124dc2f8bdc0b59be40f79a2" +dependencies = [ + "atoi", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "sqlx-core", + "time 0.3.27", + "tracing", + "url", +] + +[[package]] +name = "stringprep" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3737bde7edce97102e0e2b15365bf7a20bfdb5f60f4f9e8d7004258a51a8da" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "subtle" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + +[[package]] +name = "sysinfo" +version = "0.26.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c18a6156d1f27a9592ee18c1a846ca8dd5c258b7179fc193ae87c74ebb666f5" +dependencies = [ + "cfg-if", + "core-foundation-sys", + "libc", + "ntapi", + "once_cell", + "winapi", +] + +[[package]] +name = "task-local-extensions" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba323866e5d033818e3240feeb9f7db2c4296674e4d9e16b97b7bf8f490434e8" +dependencies = [ + "pin-utils", +] + +[[package]] +name = "tempfile" +version = "3.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" +dependencies = [ + "cfg-if", + "fastrand", + "redox_syscall", + "rustix", + "windows-sys", +] + +[[package]] +name = "termtree" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" + +[[package]] +name = "testdir" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48b7965698cfb3d1ac1e6e54b4b45f5caa9e89bda223c8cf723d9cf53d7cefa7" +dependencies = [ + "anyhow", + "backtrace", + "cargo_metadata", + "once_cell", + "sysinfo", + "whoami", +] + +[[package]] +name = "thiserror" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "611040a08a0439f8248d1990b111c95baa9c704c805fa1f62104b39655fd7f90" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "090198534930841fab3a5d1bb637cde49e339654e606195f8d9c76eeb081dc96" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "thread_local" +version = "1.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "time" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", +] + +[[package]] +name = "time" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb39ee79a6d8de55f48f2293a830e040392f1c5f16e336bdd1788cd0aadce07" +dependencies = [ + "deranged", + "itoa", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" + +[[package]] +name = "time-macros" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "733d258752e9303d392b94b75230d07b0b9c489350c69b851fc6c065fde3e8f9" +dependencies = [ + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d3ce25f50619af8b0aec2eb23deebe84249e19e2ddd393a6e16e3300a6dadfd" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "num_cpus", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.5.3", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2dbec703c26b00d74844519606ef15d09a7d6857860f84ad223dec002ddea2" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "futures-util", + "hashbrown 0.12.3", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "pin-project", + "pin-project-lite", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ae70283aba8d2a8b411c695c437fe25b8b5e44e23e780662002fc72fb47a82" +dependencies = [ + "bitflags 2.3.3", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" + +[[package]] +name = "tower-service" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" + +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" +dependencies = [ + "crossbeam-channel", + "time 0.3.27", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", +] + +[[package]] +name = "tracing-core" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +dependencies = [ + "lazy_static", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a651bc37f915e81f087d86e62a18eec5f79550c7faff886f7090b4ea757c77" +dependencies = [ + "nu-ansi-term", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "try-lock" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" + +[[package]] +name = "tstr" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca3264971090dec0feef3b455a3c178f02762f7550cf4592991ac64b3be2d7e" +dependencies = [ + "tstr_proc_macros", +] + +[[package]] +name = "tstr_proc_macros" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78122066b0cb818b8afd08f7ed22f7fdbc3e90815035726f0840d0d26c0747a" + +[[package]] +name = "tungstenite" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e862a1c4128df0112ab625f55cd5c934bcb4312ba80b39ae4b4835a3fd58e649" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "sha1", + "thiserror", + "url", + "utf-8", +] + +[[package]] +name = "typed-arena" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" + +[[package]] +name = "typenum" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" + +[[package]] +name = "unicode-ident" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" + +[[package]] +name = "unicode-normalization" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "url" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "uuid" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" +dependencies = [ + "getrandom", + "serde", +] + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.28", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.28", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" + +[[package]] +name = "wasm-streams" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bbae3363c08332cadccd13b67db371814cd214c2524020932f0804b8cf7c078" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "webpki-roots" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87" +dependencies = [ + "webpki", +] + +[[package]] +name = "whoami" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22fc3756b8a9133049b26c7f61ab35416c130e8c09b660f5b3958b446f52cc50" +dependencies = [ + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" + +[[package]] +name = "zeroize" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1e8e1e3 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,150 @@ +# define keys that can be inherited by members of the workspace +[workspace.package] +authors = ["Photos network developers "] +description = "A privacy first **photo storage and sharing service** in the fediverse." +version = "0.6.0" +homepage = "https://photos.network/" +documentation = "https://developers.photos.network/" +repository = "https://github.com/photos-network/core" +readme = "README.md" +license = "AGPL-3.0" +edition = "2021" + +[package] +name = "core" +version.workspace = true +edition.workspace = true +description.workspace = true +license.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +include = ["src/**/*", "LICENSE.md", "README.md", "CHANGELOG.md"] + + +[workspace] +members = [ + "crates/accounts", + "crates/activity_pub", + "crates/common", + "crates/database", + "crates/media", + "crates/oauth_authentication", + "crates/oauth_authorization_server", + "crates/plugin_interface" +] + +# define dependencies to be inherited by members of the workspace +[workspace.dependencies] +# local crates +accounts = { path = "./crates/accounts" } +activity_pub = { path = "./crates/activity_pub" } +common = { path = "./crates/common" } +database = { path = "./crates/database" } +media = { path = "./crates/media" } +oauth_authentication = { path = "./crates/oauth_authentication" } +oauth_authorization_server = { path = "./crates/oauth_authorization_server" } + +# 3rd party dependencies +abi_stable = "0.11.1" +activitypub_federation = "0.4.6" +async-trait = "0.1.73" +axum = { version = "0.6.20", features = ["ws", "headers"] } +axum-test = "12.1.0" +anyhow = "1.0.72" + +core_extensions = { version = "1.5.2", default_features = false, features = ["std"] } +chrono = { version = "0.4.26", features = ["serde"] } + +futures = "0.3.25" +futures-channel = "0.3.25" +futures-util = "0.3.25" + +http = "0.2.9" +hyper = { version = "0.14.27", features = ["full"] } + +log = "0.4.19" +mime = "0.3" +mockall = "0.11.4" + +openidconnect = { version = "3.2.0", features = ["accept-rfc3339-timestamps", "accept-string-booleans"] } + +pretty_assertions = "1.3.0" + +rand = "0.8.5" +rstest = "0.18.2" +rumqttc = "0.23.0" +rsa = "0.9.2" +reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "stream", "multipart"] } + +serde = "1.0.183" +serde_json = { version = "1.0.104", features = ["raw_value"] } +serde_with = "3.3.0" +serde_urlencoded = "0.7.1" +smallvec = "1.8.0" +sqlx = "0.7.1" + +testdir = "0.8.0" +tempfile = "3.8.0" +thiserror = "1.0.40" +time = "0.3.27" +tokio = { version = "1.30.0", features = ["full"] } +tokio-stream = { version = "0.1.11", features = ["net"] } +tokio-util = { version = "0.7.4", features = ["rt"] } +tower = { version = "0.4.13", features = ["util"] } +tower-http = { version = "0.4.3", features = ["fs", "tracing", "trace", "cors"] } +tracing = "0.1.37" +tracing-subscriber = { version = "0.3.17", features = ["registry", "fmt", "std", "json"] } +tracing-appender = "0.2.2" + +url = { version = "2.4.0", features = ["serde"] } +uuid = { version = "1.4.1", features = ["serde", "v4"] } + +[dependencies.photos_network_plugin] +version = "0.2.0" +path = "./crates/plugin_interface" + + + +[dependencies] +# local crates +accounts.workspace = true +activity_pub.workspace = true +common.workspace = true +database.workspace = true +media.workspace = true +oauth_authentication.workspace = true +oauth_authorization_server.workspace = true + + +# Plugin +abi_stable.workspace = true +core_extensions.workspace = true + +# de/serialization +serde.workspace = true +serde_json.workspace = true + +# error handling +anyhow.workspace = true + +# http +axum.workspace = true +tokio.workspace = true +tower-http.workspace = true +tokio-stream.workspace = true +tokio-util.workspace = true + +# logging +tracing.workspace = true +tracing-subscriber.workspace = true +tracing-appender.workspace = true + +# database +sqlx.workspace = true + + +[dev-dependencies] +pretty_assertions.workspace = true +serde_urlencoded.workspace = true +reqwest.workspace = true diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..0584ce4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +FROM rust:latest AS builder +LABEL "description"="Photos.network core system" +LABEL "version"="0.6.0" +LABEL "maintainer"="github.com/photos-network" + +RUN rustup target add x86_64-unknown-linux-musl +RUN apt update && apt install -y musl-tools musl-dev +RUN update-ca-certificates + +ENV USER=core +ENV UID=10001 + +RUN adduser \ + --disabled-password \ + --gecos "" \ + --home "/nonexistent" \ + --shell "/sbin/nologin" \ + --no-create-home \ + --uid "${UID}" \ + "${USER}" + +WORKDIR /core + +COPY ./ . + +RUN cargo build --target x86_64-unknown-linux-musl --release + +#################################################################################################### +## Final image +#################################################################################################### +FROM scratch + +# Import from builder. +COPY --from=builder /etc/passwd /etc/passwd +COPY --from=builder /etc/group /etc/group + +WORKDIR /core + +# Copy our build +COPY --from=builder /core/target/x86_64-unknown-linux-musl/release/core ./ + +# Use an unprivileged user. +USER core:core + +CMD ["/app/core"] diff --git a/Dockerfile.dev b/Dockerfile.dev deleted file mode 100644 index 7b02d8e..0000000 --- a/Dockerfile.dev +++ /dev/null @@ -1,35 +0,0 @@ -FROM mcr.microsoft.com/vscode/devcontainers/python:0-3.8 - -RUN \ - apt-get update && apt-get install -y --no-install-recommends \ - libudev-dev \ - libavformat-dev \ - libavcodec-dev \ - libavdevice-dev \ - libavutil-dev \ - libswscale-dev \ - libswresample-dev \ - libavfilter-dev \ - git \ - && apt-get clean \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /photosnetwork - -COPY requirements*.txt ./ - -RUN pip3 install --upgrade pip - -# Install Python dependencies from requirements -RUN pip3 install -r requirements_test.txt - -COPY . . - -RUN python3 setup.py install - -RUN core - -# Set the default shell to bash instead of sh -# ENV SHELL /bin/bash - -# ENTRYPOINT ./entrypoint.sh diff --git a/LICENSE.md b/LICENSE.md index e69de29..c796e17 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Photos.network ยท A privacy first, self-hosted photo storage and sharing service for fediverse. + Copyright 2020 Photos network developers + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 2fdecae..d90780d 100644 --- a/README.md +++ b/README.md @@ -1,75 +1,118 @@ # Photos.network -[![License](https://img.shields.io/github/license/photos.network/core)](./LICENSE.md) -[![GitHub contributors](https://img.shields.io/github/contributors/photos.network/core)](https://github.com/photos.network/core/graphs/contributors) +[![License](https://img.shields.io/github/license/photos-network/core?style=for-the-badge)](./LICENSE.md) +[![GitHub contributors](https://img.shields.io/github/contributors/photos-network/core?color=success&style=for-the-badge)](https://github.com/photos-network/core/graphs/contributors) +[![Discord](https://img.shields.io/discord/793235453871390720?style=for-the-badge)](https://discord.gg/dGFDpmWp46) +![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/photos-network/core/check.yaml?style=for-the-badge) + + +[Photos.network](https://photos.network) is a free and open source, privacy first, self-hosted photo storage and sharing service for fediverse. -[Photos.network](https://photos.network) is an open source project for self hosted photo management. Its core features are: - - Share photos with friends, family or public - - Filter / Search photos by attributes like location or date - - Group photos by objects like people of objects -## Core -This repository contains the core system of the project. +- Share photos with friends, family or public +- Filter / Search photos by attributes like location or date +- Group photos by their content like people or objects +- Upload photos and videos without resolution or quality constraints + + + +## ๐Ÿง  Core + +This repository contains the **core** system of the project. It is responsible for main tasks e.g.: - - **Authentication** (validate the identity of users) - - **Authorization** (handle access privileges of resources like photos or albums) - - **Add-on Handling** (managing add-ons) - - **Persistency** (read / write data) - - **Task Processing** (keep track of running tasks) - -### Add-ons -The core system can be extended by add-ons to attune user needs. - -Each addon is encapsulated in a separate directory wich have to contain at least: -- `addon.json` with detailed informations and requirements -- `__init__.py` with an async setup function - -```json -{ - "domain": "api", - "name": "REST api", - "requirements": [], - "core": "0.1.0" -} -``` -```python -async def async_setup(core: ApplicationCore, config: dict) -> bool: - return True -``` +- **Authentication** (validate the identity of users) +- **Authorization** (handle access privileges of resources like photos or albums) +- **Plugin Handling** (extend the feature-set by plugins) +- **Persistency** (read / write data) +- **Task Processing** (keep track of running tasks) + - - Sync photos (reading & writing) - - server <=> server - - nextcloud, gdrive, icloud - - client <=> server - - browser, native app - - File processing - - Metadata parsing - - Image processing - - Object detection - - Face detection +## ๐Ÿงฉ Contribution +This is a free and open project and lives from contributions of the community. +See our [Contribution Guide](CONTRIBUTING.md) -## Development -Always use [PEP 484: Type Hints](https://www.python.org/dev/peps/pep-0484/) in your syntax. -#### Prepare setup -Prepare an environment by running: + +## ๐Ÿงช Development + +The core is written in ๐Ÿฆ€ [Rust](https://rust-lang.org/) and highly customizably by using a Plugin-system. + + + +#### ๐Ÿ“„ Documentation + +With the nightly version of `cargo doc` an additional index-page will be created. ```shell -python3 -m venv venv -source ./venv/bin/activate -pip3 install -r requirements_dev.txt +$ RUSTDOCFLAGS="--enable-index-page -Zunstable-options" cargo +nightly doc --all --no-deps --document-private-items --all-features ``` -After the environment is build, install the core: + + +#### ๐Ÿ”ฌ Testing + +An continuous check on all files is done in the background and will trigger `cargo test` on each file change. + ```shell -python3 setup.py install +$ cargo watch --exec test ``` -#### Run +To run tests for all crates in this workspace, run: ```shell -python3 ./venv/bin/core +$ cargo test --workspace --all-targets +``` + +### Visual Studio Code + +The fastest start into development can be archived by using [Visual Studio Code](https://code.visualstudio.com/) and [Docker](https://www.docker.com/get-started). + +1. Install [Docker](https://www.docker.com/get-started) +2. Install [Visual Studio Code](https://code.visualstudio.com/) +3. Install [Visual Studio Code Remote - Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) +4. Clone and Open this repository in Visual Studio Code +5. Click the "Reopen in Container" Dialog +6. Launch **Photos.network** from the `RUN` window. + +![VS Code with devcontainers](vscode.gif) + + + +## ๐Ÿ“œ Roadmap (MvP) + + - Authenticate via openID + - Create a new media item + - Upload one or multiple photos + - Download a list of owned media items + - Download the original photo from a specific media item + - *Metadata (size, resolution) + - *EXIF (orientation, image taken timestamp, last modified, camera) + - *RAW (image support for RAW-images) + - *Resize (create low-resolutions / thumbnails) + - *Deep learning (image recognition, Reinforcement learning) + - *Plugin System (extract features into plugins) + + + +## ๐Ÿ›๏ธ License + +``` +Photos.network ยท A privacy first photo storage and sharing service for fediverse +Copyright (C) 2020 Photos network developers + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . ``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c57d41a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,22 @@ +# Security + +We take the security of this software seriously. + +If you believe you have found a security vulnerability in any of our repositories, please report it to us as described below. + + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, send email at [security@photos.network](mailto:security@photos.network). +If possible, encrypt your message with our PGP key; +- **Fingerprint**: C320ย 7E30ย 54CDย AA7Bย E197ย ย DFF4ย 1B42ย 5A06ย 30A6ย ABD0 +- **Public key**: https://keys.openpgp.org/search?q=security@photos.network + + +It is also possible to report it via the [Github security page](https://github.com/photos-network/core/security) + +Please do not make vulnerabilities public without notifying us and giving us at least 4 weeks to respond. + +If you are going to write about Photos.networkโ€™s security, please get in touch, so we can make sure that all claims are correct. diff --git a/config/configuration.json b/config/configuration.json deleted file mode 100644 index 2a6fd4e..0000000 --- a/config/configuration.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "internal_url": "192.168.0.1", - "external_url": "external.url.com", - "data_dir": "data", - "addons": [ - { - "name": "api", - "config": { - "cors": false - } - }, - { - "name": "metadata" - }, - { - "name": "nextcloud" - } - ] -} diff --git a/core/__init__.py b/core/__init__.py deleted file mode 100644 index 00d293a..0000000 --- a/core/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""init""" diff --git a/core/__main__.py b/core/__main__.py deleted file mode 100644 index 4449032..0000000 --- a/core/__main__.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Entry point of Photos.network""" - -import asyncio -import logging -import os -from typing import Optional, TYPE_CHECKING - -import sys - -from core.configs import RuntimeConfig -from core.const import REQUIRED_PYTHON_VER -from core.core import ApplicationCore - -_LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.DEBUG) - - -def validate_python() -> None: - """Validate that the right Python version is running.""" - if sys.version_info[:3] < REQUIRED_PYTHON_VER: - print( - "Photos.network requires at least Python " - f"{REQUIRED_PYTHON_VER[0]}.{REQUIRED_PYTHON_VER[1]}.{REQUIRED_PYTHON_VER[2]}" - ) - sys.exit(1) - - -async def async_setup( - runtime_config: RuntimeConfig, -) -> Optional[ApplicationCore]: - """Set up Photos.""" - application = ApplicationCore() - _LOGGER.debug("main::async_setup()") - application.config.config_dir = runtime_config.config_dir - application.config.data_dir = runtime_config.data_dir - - _LOGGER.info(f"Config directory: {runtime_config.config_dir}", ) - - return application - - -async def setup_and_run(runtime_config: RuntimeConfig) -> int: - """Set up and run the system.""" - core = await async_setup(runtime_config) - - if core is None: - return 1 - - return await core.async_run() - - -def get_or_create_directory(directory: str, is_relative: bool = True) -> str: - if is_relative: - directory_path = os.path.abspath(os.path.join(os.getcwd(), directory)) - else: - directory_path = os.path.abspath(directory) - - if not os.path.exists(directory_path): - _LOGGER.warning("config_dir does not exist") - os.mkdir(directory_path) - - return directory_path - - -def main() -> int: - """Start Photos.network""" - validate_python() - - _LOGGER.debug("Now run the core system...") - - config_dir = get_or_create_directory(directory='config') - data_dir = get_or_create_directory(directory='data', is_relative=False) - - runtime_conf = RuntimeConfig( - config_dir=config_dir, - data_dir=data_dir, - safe_mode=False, - debug=True, - verbose=True - ) - - exit_code = asyncio.run(setup_and_run(runtime_conf)) - - return exit_code - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/core/addon.py b/core/addon.py deleted file mode 100644 index f71eb72..0000000 --- a/core/addon.py +++ /dev/null @@ -1,250 +0,0 @@ -"""Loading addons from regarding directory.""" -import asyncio -import importlib -import json -import logging -import os -import pathlib -import time -from subprocess import Popen, PIPE -from typing import Optional, cast, Dict, Any, List, TYPE_CHECKING - -import sys - -# Typing imports that create a circular dependency -if TYPE_CHECKING: - from core.core import ApplicationCore - -SLOW_SETUP_MAX_WAIT = 300 - -_LOGGER = logging.getLogger(__name__) -_LOGGER.setLevel(logging.DEBUG) - - -class Addon: - """Base representation of addons.""" - - @classmethod - def resolve_from_root( - cls, - core: "ApplicationCore", - addon_name: str, - addon_config: dict = None - ) -> "Optional[Addon]": - """Resolve an addon from a root module.""" - addon_path = pathlib.Path(core.config.addon_dir) / addon_name / "addon.json" - - if not addon_path.is_file(): - return None - - try: - manifest = json.loads(addon_path.read_text()) - except ValueError as err: - _LOGGER.error(f"Error parsing manifest.json file at {addon_path}: {err}") - return None - - return cls( - core, - f"{addon_path}", - addon_path.parent, - manifest, - addon_config - ) - - def __init__( - self, - core: "ApplicationCore", - pkg_path: str, - file_path: pathlib.Path, - manifest: Dict[str, Any], - addon_config: Dict[str, Any] = None - ): - """Initialize an integration.""" - self.core = core - self.pkg_path = pkg_path - self.file_path = file_path - self.manifest = manifest - self.addon_config = addon_config - - _LOGGER.info(f"Initialize '{self.domain}' ({pkg_path})") - - @property - def name(self) -> str: - """Return name.""" - return cast(str, self.manifest["name"]) - - @property - def disabled(self) -> Optional[str]: - """Return reason integration is disabled.""" - return cast(Optional[str], self.manifest.get("disabled")) - - @property - def domain(self) -> str: - """Return domain.""" - return cast(str, self.manifest["domain"]) - - @property - def dependencies(self) -> List[str]: - """Return dependencies.""" - return cast(List[str], self.manifest.get("dependencies", [])) - - @property - def requirements(self) -> List[str]: - """Return requirements.""" - return cast(List[str], self.manifest.get("requirements", [])) - - @property - def config_flow(self) -> bool: - """Return config_flow.""" - return cast(bool, self.manifest.get("config_flow", False)) - - @property - def documentation(self) -> Optional[str]: - """Return documentation.""" - return cast(str, self.manifest.get("documentation")) - - def __repr__(self) -> str: - """Text representation of class.""" - return f"" - - def install_requirements(self) -> bool: - """install requirements for addon. return True if all requrements fulfilled""" - all_requirements_resolved = True - for requirement in self.requirements: - _LOGGER.info(f"Install requirement {requirement} for {self.domain}") - try: - installed = self.install_package(package=requirement) - if not installed: - all_requirements_resolved = False - except: - _LOGGER.error(f"could not fulfill requirement: {requirement}") - all_requirements_resolved = False - - return all_requirements_resolved - - def install_package( - self, - package: str, - upgrade: bool = True, - target: Optional[str] = None, - constraints: Optional[str] = None, - find_links: Optional[str] = None, - no_cache_dir: Optional[bool] = False, - ) -> bool: - """Install a package on PyPi. Accepts pip compatible package strings. - - Return boolean if install successful. - """ - # Not using 'import pip; pip.main([])' because it breaks the logger - _LOGGER.info("Attempting install of %s", package) - env = os.environ.copy() - args = [sys.executable, "-m", "pip", "install", "--quiet", package] - if no_cache_dir: - args.append("--no-cache-dir") - if upgrade: - args.append("--upgrade") - if constraints is not None: - args += ["--constraint", constraints] - if find_links is not None: - args += ["--find-links", find_links, "--prefer-binary"] - process = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, env=env) - _, stderr = process.communicate() - if process.returncode != 0: - _LOGGER.error( - "Unable to install package %s: %s", - package, - stderr.decode("utf-8").lstrip().strip(), - ) - return False - - return True - - async def async_setup_addon( - self, - ) -> bool: - """run custom setup for addon.""" - processed_config = self.addon_config - - start = time.perf_counter() - _LOGGER.info(f"Start setup for '{self.domain}'") - - # Some integrations fail on import because they call functions incorrectly. - # So we do it before validating config to catch these errors. - try: - component = importlib.import_module(f"core.addons.{self.domain}") - except ImportError as err: - _LOGGER.error(f"Unable to import addon '{self.domain}': {err}") - return False - except Exception: # pylint: disable=broad-except - _LOGGER.exception(f"Setup failed for {self.domain}: unknown error") - return False - - try: - if hasattr(component, "async_setup"): - task = component.async_setup(self.core, processed_config) # type: ignore - elif hasattr(component, "setup"): - # This should not be replaced with core.async_add_executor_job because - # we don't want to track this task in case it blocks startup. - task = self.core.loop.run_in_executor( - None, component.setup, self.core, processed_config # type: ignore - ) - else: - _LOGGER.error("!! ==> No setup function defined.") - return False - - async with self.core.timeout.async_timeout(SLOW_SETUP_MAX_WAIT, self.domain): - result = await task - except asyncio.TimeoutError: - _LOGGER.error( - "Setup of %s is taking longer than %s seconds." - " Startup will proceed without waiting any longer", - self.domain, - SLOW_SETUP_MAX_WAIT, - ) - return False - except Exception: # pylint: disable=broad-except - _LOGGER.exception("Error during setup of component %s", self.domain) - return False - finally: - end = time.perf_counter() - _LOGGER.info(f"Setup of '{self.domain}' took {end - start:#.2f} seconds") - - if result is False: - _LOGGER.error("Integration failed to initialize.") - return False - if result is not True: - _LOGGER.error( - f"Integration {self.domain!r} did not return boolean if setup was " - "successful. Disabling component." - ) - return False - - # Flush out async_setup calling create_task. Fragile but covered by test. - await asyncio.sleep(0) - - self.core.config.addons.add(self.domain) - - return True - - -class AddonSetupFlow: - """Base class for the setup flow. See PEP 487 for details""" - # _core: Optional[ApplicationCore] = None - _registry = [] - - @classmethod - def __init_subclass__(cls, **kwargs): - super().__init_subclass__(**kwargs) - cls._registry.append(cls) - - def get_registry(cls): - return cls._registry - - async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - """Handle a flow initiated by the user.""" - return self.async_abort(reason="not_implemented") - - def async_abort(self, *, reason: str, description_placeholders: Optional[Dict] = None) -> Dict[str, Any]: - """Abort the config flow.""" - - return dict() diff --git a/core/addons/__init__.py b/core/addons/__init__.py deleted file mode 100644 index 460a044..0000000 --- a/core/addons/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Place addons in subdirectories here.""" diff --git a/core/addons/api/__init__.py b/core/addons/api/__init__.py deleted file mode 100644 index f1a880f..0000000 --- a/core/addons/api/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -"""REST API implementation.""" -import json -import logging -from json import JSONEncoder - -from aiohttp import web - -from core.addons.api.auth import APIAuthView -from core.webserver import status -from core.core import ApplicationCore, callback -from core.webserver.request import Request -from core.webserver.type import APPLICATION_JSON - -_LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.DEBUG) - - -async def async_setup(core: ApplicationCore, config: dict) -> bool: - """setup addon to core application.""" - is_cors_enabled = config["cors"] - _LOGGER.info(f"enable cors: {is_cors_enabled}") - core.http.register_request(APIStatusView) - core.http.register_request(APIAuthView) - - return True - - -class APIStatusView(Request): - """View to handle Status requests.""" - - requires_auth = False - url = "/" - name = "api:status" - - async def get(self): - """Retrieve if API is running.""" - msg = json.dumps("API is running", cls=JSONEncoder, allow_nan=False).encode("UTF-8") - - response = web.Response( - body=msg, - content_type=APPLICATION_JSON, - status=status.HTTP_OK, - ) - response.enable_compression() - return response diff --git a/core/addons/api/addon.json b/core/addons/api/addon.json deleted file mode 100644 index a17e424..0000000 --- a/core/addons/api/addon.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "domain": "api", - "name": "REST api", - "requirements": [], - "core": "0.1.0" -} diff --git a/core/addons/api/auth.py b/core/addons/api/auth.py deleted file mode 100644 index 2f1b8ad..0000000 --- a/core/addons/api/auth.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Authentication flow implementation.""" -import json -from json import JSONEncoder - -from aiohttp import web -from core.webserver import status - -from core.webserver.request import Request -from core.webserver.type import APPLICATION_JSON - - -class APIAuthView(Request): - """View to handle auth requests.""" - - requires_auth = False - url = "/auth" - name = "api:auth" - - async def post(self): - # TODO: handle data for authentication - msg = json.dumps("Authentication not implemented yet!", cls=JSONEncoder, allow_nan=False).encode("UTF-8") - - response = web.Response( - body=msg, - content_type=APPLICATION_JSON, - status=status.HTTP_UNPROCESSABLE_ENTITY, - ) - response.enable_compression() - return response diff --git a/core/addons/metadata/__init__.py b/core/addons/metadata/__init__.py deleted file mode 100644 index d846aac..0000000 --- a/core/addons/metadata/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Metadata integration to parse image metadata like exif informations""" -import logging - -from exif import Image -from core.core import ApplicationCore - -_LOGGER = logging.getLogger(__name__) -_LOGGER.setLevel(logging.DEBUG) - - -async def async_setup(core: ApplicationCore, config: dict) -> bool: - """setup triggered by the ApplicationCore for each config entry.""" - _LOGGER.info(f"addon config: {config}") - - # Return boolean to indicate that initialization was successful. - return True - - -async def async_update(core: ApplicationCore, config: dict): - # TODO: iterate through images for authenticated user - # TODO: read exif data - with open('grand_canyon.jpg', 'rb') as image_file: - my_image = Image(image_file) - has_exif = my_image.has_exif - _LOGGER.error(f"metadata::async_update() has_exif: {has_exif}") diff --git a/core/addons/metadata/addon.json b/core/addons/metadata/addon.json deleted file mode 100644 index f31ca5b..0000000 --- a/core/addons/metadata/addon.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "domain": "metadata", - "name": "File metadata parsing", - "requirements": [ - "exif==1.0.4" - ], - "core": "0.1.0" -} diff --git a/core/addons/metadata/setup.py b/core/addons/metadata/setup.py deleted file mode 100644 index a4b7f35..0000000 --- a/core/addons/metadata/setup.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Userfacing setup process""" -import logging -from typing import Optional, Dict, Any - -from core.addons import AddonSetupFlow - -_LOGGER = logging.getLogger(__name__) - - -class MetadataSetup(AddonSetupFlow): - async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - """Invoke when a user initiates a flow via the user interface.""" diff --git a/core/addons/nextcloud/__init__.py b/core/addons/nextcloud/__init__.py deleted file mode 100644 index e982cb7..0000000 --- a/core/addons/nextcloud/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Next cloud integration to sync photos in a directory""" -import logging - -from core.core import ApplicationCore - -_LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.DEBUG) - - -async def async_setup(core: ApplicationCore, config: dict) -> bool: - """setup triggered by the ApplicationCore for each config entry.""" - _LOGGER.info(f"addon config: {config}") - - # TODO: instantiation should be done per each user instead - # for entry in config: - # _LOGGER.debug(f'config: {entry}') - # server = entry.get("server") - # port = entry.get("port") - # username = entry.get("username") - # password = entry.get("password") - - # Return boolean to indicate that initialization was successful. - return True diff --git a/core/addons/nextcloud/addon.json b/core/addons/nextcloud/addon.json deleted file mode 100644 index 9fcf404..0000000 --- a/core/addons/nextcloud/addon.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "domain": "nextcloud", - "name": "Next cloud sync", - "requirements": [], - "core": "0.1.0" -} diff --git a/core/addons/places365/__init__.py b/core/addons/places365/__init__.py deleted file mode 100644 index c1d45b3..0000000 --- a/core/addons/places365/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Next cloud integration to sync photos in a directory""" -import logging - - -from core.core import ApplicationCore -from core.addons.places365.places365 import inference_places365 - -_LOGGER = logging.getLogger(__name__) -_LOGGER.setLevel(logging.DEBUG) - - -async def async_setup(core: ApplicationCore, config: dict) -> bool: - """setup triggered by the ApplicationCore for each config entry.""" - - # Return boolean to indicate that initialization was successful. - return True - - -async def update(image_path: str) -> dict: - captions = {} - - try: - res_places365 = inference_places365(image_path) - captions['places365'] = res_places365 - # self.captions_json = captions - # if self.search_captions: - # self.search_captions = self.search_captions + ' , ' + \ - # ' , '.join(res_places365['attributes'] + res_places365['categories'] + [res_places365['environment']]) - # else: - # self.search_captions = ' , '.join( - # res_places365['attributes'] + res_places365['categories'] + - # [res_places365['environment']]) - # - # self.save() - _LOGGER.info(f"generated places365 captions for image {image_path}.") - except: - _LOGGER.warning(f"could not generate places365 captions for image {image_path}") - - return captions diff --git a/core/addons/places365/addon.json b/core/addons/places365/addon.json deleted file mode 100644 index 814ce76..0000000 --- a/core/addons/places365/addon.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "domain": "places365", - "name": "Tag various places based on convolutional neural networks (CNN)", - "requirements": [ - "torchvision==0.2.1", - "Pillow==5.1.0" - ], - "core": "0.1.0" -} diff --git a/core/addons/places365/places365.py b/core/addons/places365/places365.py deleted file mode 100644 index bb6a2bb..0000000 --- a/core/addons/places365/places365.py +++ /dev/null @@ -1,142 +0,0 @@ -# PlacesCNN to predict the scene category, attribute, and class activation map in a single pass -# by Bolei Zhou, sep 2, 2017 -# last modified date: Dec. 27, 2017, migrating everything to python36 and latest pytorch and torchvision -import logging -import os - -import numpy as np -import torch -import wideresnet -from PIL import Image -from torch.autograd import Variable as V -from torch.nn import functional as F -from torchvision import transforms as trn - -_LOGGER = logging.getLogger(__name__) -_LOGGER.setLevel(logging.DEBUG) - -torch.nn.Module.dump_patches = True - -dir_places365_model = os.path.join(os.path.dirname(__file__), 'model') - - -def load_labels(): - # prepare all the labels - # scene category relevant - file_path_category = os.path.join(dir_places365_model, 'categories_places365.txt') - classes = list() - with open(file_path_category) as class_file: - for line in class_file: - classes.append(line.strip().split(' ')[0][3:]) - classes = tuple(classes) - - # indoor and outdoor relevant - file_path_IO = os.path.join(dir_places365_model, 'IO_places365.txt') - with open(file_path_IO) as f: - lines = f.readlines() - labels_IO = [] - for line in lines: - items = line.rstrip().split() - labels_IO.append(int(items[-1]) - 1) # 0 is indoor, 1 is outdoor - labels_IO = np.array(labels_IO) - - # scene attribute relevant - file_path_attribute = os.path.join(dir_places365_model, 'labels_sunattribute.txt') - with open(file_path_attribute) as f: - lines = f.readlines() - labels_attribute = [item.rstrip() for item in lines] - - file_path_W = os.path.join(dir_places365_model, 'W_sceneattribute_wideresnet18.npy') - W_attribute = np.load(file_path_W) - - return classes, labels_IO, labels_attribute, W_attribute - - -def returnTF(): - # load the image transformer - tf = trn.Compose([ - trn.Resize((224, 224)), - trn.ToTensor(), - trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) - ]) - return tf - - -def remove_nonspace_separators(text): - return ' '.join(' '.join(' '.join(text.split('_')).split('/')).split('-')) - - -# load the labels -classes, labels_IO, labels_attribute, W_attribute = load_labels() - - -# img_root = '/home/hooram/ownphotos_media/photos/' - -# img_paths = [f for f in os.listdir(img_root) if f.endswith('.jpg')] - -def inference_places365(img_path) -> dict: - features_blobs = [] - - def hook_feature(module, input, output): - features_blobs.append(np.squeeze(output.data.cpu().numpy())) - - def load_model(): - # this model has a last conv feature map as 14x14 - # model_file = os.path.join(dir_places365_model,'whole_wideresnet18_places365_python36.pth.tar') - model_file = os.path.join(dir_places365_model, 'wideresnet18_places365.pth.tar') - - model = wideresnet.resnet18(num_classes=365) - checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage) - state_dict = {str.replace(k, 'module.', ''): v for k, v in checkpoint['state_dict'].items()} - model.load_state_dict(state_dict) - model.eval() - # hook the feature extractor - features_names = ['layer4', 'avgpool'] # this is the last conv layer of the resnet - for name in features_names: - model._modules.get(name).register_forward_hook(hook_feature) - return model - - # load the model - model = load_model() - - # load the transformer - tf = returnTF() # image transformer - - # get the softmax weight - params = list(model.parameters()) - weight_softmax = params[-2].data.numpy() - weight_softmax[weight_softmax < 0] = 0 - - # load the test image - # img_url = 'http://places2.csail.mit.edu/imgs/12.jpg' - # os.system('wget %s -q -O test.jpg' % img_url) - img = Image.open(img_path) - input_img = V(tf(img).unsqueeze(0)) - - # forward pass - logit = model.forward(input_img) - h_x = F.softmax(logit, 1).data.squeeze() - probs, idx = h_x.sort(0, True) - probs = probs.numpy() - idx = idx.numpy() - - res = {} - - # output the IO prediction - io_image = np.mean(labels_IO[idx[:10]]) # vote for the indoor or outdoor - if io_image < 0.5: - res['environment'] = 'indoor' - else: - res['environment'] = 'outdoor' - - # output the prediction of scene category - res['categories'] = [] - for i in range(0, 5): - res['categories'].append(remove_nonspace_separators(classes[idx[i]])) - - # output the scene attributes - responses_attribute = W_attribute.dot(features_blobs[1]) - idx_a = np.argsort(responses_attribute) - res['attributes'] = [remove_nonspace_separators(labels_attribute[idx_a[i]]) for i in range(-1, -10, -1)] - - return res diff --git a/core/addons/places365/wideresnet.py b/core/addons/places365/wideresnet.py deleted file mode 100644 index 1899959..0000000 --- a/core/addons/places365/wideresnet.py +++ /dev/null @@ -1,211 +0,0 @@ -import math -import torch.nn as nn -import torch.utils.model_zoo as model_zoo - -__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', - 'resnet152'] - -model_urls = { - 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', - 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', - 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', - 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', - 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', -} - - -def conv3x3(in_planes, out_planes, stride=1): - "3x3 convolution with padding" - return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, - padding=1, bias=False) - - -class BasicBlock(nn.Module): - expansion = 1 - - def __init__(self, inplanes, planes, stride=1, downsample=None): - super(BasicBlock, self).__init__() - self.conv1 = conv3x3(inplanes, planes, stride) - self.bn1 = nn.BatchNorm2d(planes) - self.relu = nn.ReLU(inplace=True) - self.conv2 = conv3x3(planes, planes) - self.bn2 = nn.BatchNorm2d(planes) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - residual = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.bn2(out) - - if self.downsample is not None: - residual = self.downsample(x) - - out += residual - out = self.relu(out) - - return out - - -class Bottleneck(nn.Module): - expansion = 4 - - def __init__(self, inplanes, planes, stride=1, downsample=None): - super(Bottleneck, self).__init__() - self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) - self.bn1 = nn.BatchNorm2d(planes) - self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, - padding=1, bias=False) - self.bn2 = nn.BatchNorm2d(planes) - self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) - self.bn3 = nn.BatchNorm2d(planes * 4) - self.relu = nn.ReLU(inplace=True) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - residual = x - - out = self.conv1(x) - out = self.bn1(out) - out = self.relu(out) - - out = self.conv2(out) - out = self.bn2(out) - out = self.relu(out) - - out = self.conv3(out) - out = self.bn3(out) - - if self.downsample is not None: - residual = self.downsample(x) - - out += residual - out = self.relu(out) - - return out - - -class ResNet(nn.Module): - - def __init__(self, block, layers, num_classes=1000): - self.inplanes = 64 - super(ResNet, self).__init__() - self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, - bias=False) - self.bn1 = nn.BatchNorm2d(64) - self.relu = nn.ReLU(inplace=True) - # self.maxpool = nn.MaxPool2d(kernel_size=3, stride=1, padding=1) # previous stride is 2 - self.layer1 = self._make_layer(block, 64, layers[0]) - self.layer2 = self._make_layer(block, 128, layers[1], stride=2) - self.layer3 = self._make_layer(block, 256, layers[2], stride=2) - self.layer4 = self._make_layer(block, 512, layers[3], stride=2) - self.avgpool = nn.AvgPool2d(14) - self.fc = nn.Linear(512 * block.expansion, num_classes) - - for m in self.modules(): - if isinstance(m, nn.Conv2d): - n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels - m.weight.data.normal_(0, math.sqrt(2. / n)) - elif isinstance(m, nn.BatchNorm2d): - m.weight.data.fill_(1) - m.bias.data.zero_() - - def _make_layer(self, block, planes, blocks, stride=1): - downsample = None - if stride != 1 or self.inplanes != planes * block.expansion: - downsample = nn.Sequential( - nn.Conv2d(self.inplanes, planes * block.expansion, - kernel_size=1, stride=stride, bias=False), - nn.BatchNorm2d(planes * block.expansion), - ) - - layers = [] - layers.append(block(self.inplanes, planes, stride, downsample)) - self.inplanes = planes * block.expansion - for i in range(1, blocks): - layers.append(block(self.inplanes, planes)) - - return nn.Sequential(*layers) - - def forward(self, x): - x = self.conv1(x) - x = self.bn1(x) - x = self.relu(x) - # x = self.maxpool(x) - - x = self.layer1(x) - x = self.layer2(x) - x = self.layer3(x) - x = self.layer4(x) - - x = self.avgpool(x) - x = x.view(x.size(0), -1) - x = self.fc(x) - - return x - - -def resnet18(pretrained=False, **kwargs): - """Constructs a ResNet-18 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) - return model - - -def resnet34(pretrained=False, **kwargs): - """Constructs a ResNet-34 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) - return model - - -def resnet50(pretrained=False, **kwargs): - """Constructs a ResNet-50 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) - return model - - -def resnet101(pretrained=False, **kwargs): - """Constructs a ResNet-101 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) - return model - - -def resnet152(pretrained=False, **kwargs): - """Constructs a ResNet-152 model. - - Args: - pretrained (bool): If True, returns a model pre-trained on ImageNet - """ - model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) - if pretrained: - model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) - return model diff --git a/core/authentication/user.py b/core/authentication/user.py deleted file mode 100644 index a45bd7d..0000000 --- a/core/authentication/user.py +++ /dev/null @@ -1,24 +0,0 @@ -"""User representation.""" -import datetime -from typing import Optional - - -class User: - def __init__( - self, - user_id: str, - username: str, - name: Optional[str], - email: Optional[str], - password_hash: str, - is_admin: bool = False, - is_active: bool = True, - last_login: datetime = datetime.datetime, - date_joined: datetime = datetime.datetime - ): - self.username = username - self.name = name - self.email = email - self.password_hash = password_hash - self.is_admin = is_admin - self.is_active = is_active diff --git a/core/authorization/__init__.py b/core/authorization/__init__.py deleted file mode 100644 index a7ea85d..0000000 --- a/core/authorization/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""authorization handles permissions / rights""" diff --git a/core/configs.py b/core/configs.py deleted file mode 100644 index a344a30..0000000 --- a/core/configs.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Configurations for runtime and application instance.""" -import dataclasses -import datetime -import logging -import os -from typing import Dict, Optional, Set, TYPE_CHECKING - -import pytz - -# Typing imports that create a circular dependency -if TYPE_CHECKING: - from core.core import ApplicationCore - -_LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.DEBUG) - - -class Config: - """Representation class of configurations.""" - - def __init__(self, core: "ApplicationCore") -> None: - """Initialize a new config object.""" - self.core = core - - self.internal_url: Optional[str] = None - self.external_url: Optional[str] = None - - self.time_zone: datetime.tzinfo = pytz.utc.zone - - # List of loaded addons - self.addons: Set[str] = set() - - # Directory that holds addons - self.addon_dir: Optional[str] = 'core/addons' - - # Directory that holds configuration data - self.config_dir: Optional[str] = None - - # Directory that holds application data - self.data_dir: Optional[str] = None - - def path(self, *path: str) -> str: - """Generate path to the file within the configuration directory. - - Async friendly. - """ - if self.config_dir is None: - raise RuntimeError("config_dir is not set") - return os.path.join(self.config_dir, *path) - - def as_dict(self) -> Dict: - """Create a dictionary representation of the configuration. - - Async friendly. - """ - time_zone = pytz.utc.UTC.zone - if self.time_zone and getattr(self.time_zone, "zone"): - time_zone = getattr(self.time_zone, "zone") - - return { - "internal_url": self.internal_url, - "external_url": self.external_url, - "time_zone": time_zone, - "addons": self.addons, - "config_dir": self.config_dir, - "data_dir": self.data_dir, - } - - -@dataclasses.dataclass -class RuntimeConfig: - """Class to hold the information for running ApplicationCore.""" - - # directory holding configurations - config_dir: str - - # directory holding application data - data_dir: str - - # disable addons if enabled - safe_mode: bool = False - - # add debug log states - debug: bool = False - - # add verbose log states - verbose: bool = True diff --git a/core/const.py b/core/const.py deleted file mode 100644 index 7d5c689..0000000 --- a/core/const.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Constants used by Photos.network.""" -MAJOR_VERSION = 0 -MINOR_VERSION = 1 -PATCH_VERSION = 0 -__short_version__ = f"{MAJOR_VERSION}.{MINOR_VERSION}" -__version__ = f"{__short_version__}.{PATCH_VERSION}" -REQUIRED_PYTHON_VER = (3, 7, 1) - -# The exit code to send to request a restart -RESTART_EXIT_CODE = 100 - -DEVICE_DEFAULT_NAME = "Unnamed Device" - -URL_API = "/api/" - -CONF_ACCESS_TOKEN = "access_token" -CONF_ADDRESS = "address" -CONF_CLIENT_ID = "client_id" -CONF_CLIENT_SECRET = "client_secret" -CORE_VERSION = __version__ diff --git a/core/context.py b/core/context.py deleted file mode 100644 index f1e0510..0000000 --- a/core/context.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Constants use by the Application instance""" -import attr - -from typing import Optional -from core.utils.uuid import random_uuid_hex - - -@attr.s(slots=True, frozen=True) -class Context: - """The context that triggered something.""" - - user_id: str = attr.ib(default=None) - parent_id: Optional[str] = attr.ib(default=None) - id: str = attr.ib(factory=random_uuid_hex) - - def as_dict(self) -> dict: - """Return a dictionary representation of the context.""" - return {"id": self.id, "parent_id": self.parent_id, "user_id": self.user_id} diff --git a/core/core.py b/core/core.py deleted file mode 100644 index ec36287..0000000 --- a/core/core.py +++ /dev/null @@ -1,286 +0,0 @@ -"""Core application component.""" -import asyncio -import enum -import json -import logging -import os -from typing import Optional, Iterable, Awaitable, Any, Set, TypeVar, Callable -from time import monotonic - -import sys -from colorlog import ColoredFormatter - -from core import loader -from core.addon import Addon -from core.configs import Config -from core.utils.timeout import TimeoutManager -from core.webserver import Webserver - -ERROR_LOG_FILENAME = "core.log" - -# core.data key for logging information. -DATA_LOGGING = "logging" - -# How long to wait to log tasks that are blocking -BLOCK_LOG_TIMEOUT = 60 # seconds - -_LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.DEBUG) - -CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable) - - -def callback(func: CALLABLE_T) -> CALLABLE_T: - """Annotation to mark method as safe to call from within the event loop.""" - setattr(func, "_callback", True) - return func - - -def is_callback(func: Callable[..., Any]) -> bool: - """Check if function is safe to be called in the event loop.""" - return getattr(func, "_callback", False) is True - - -class ApplicationCore: - """ApplicationCore root object.""" - http: "Webserver" = None # type: ignore - - def __init__(self) -> None: - """Initialize new ApplicationCore.""" - - _LOGGER.debug("ApplicationCore::init...") - - self.loop = asyncio.get_running_loop() - self._pending_tasks: list = [] - self._track_task = True - self.banned_ips: list = [] - self.failed_logins: dict = {} - self.config = Config(self) - self.addons = loader.Components(self) - - # This is a dictionary that any addon can store any data on. - self.data: dict = {} - self.state: CoreState = CoreState.not_running - self.exit_code: int = 0 - - # If not None, use to signal end-of-loop - self._stopped: Optional[asyncio.Event] = None - - # Timeout handler for Core/Helper namespace - self.timeout: TimeoutManager = TimeoutManager() - - @property - def is_running(self) -> bool: - """Return if Photos Core is running.""" - return self.state in (CoreState.starting, CoreState.running) - - @property - def is_stopping(self) -> bool: - """Return if Photos Core is stopping.""" - return self.state in (CoreState.stopping, CoreState.final_write) - - def async_enable_logging(self, verbose: bool = False) -> None: - """Setup logging for application core""" - fmt = "%(asctime)s %(levelname)s (%(threadName)s) [%(name)s] %(message)s" - datefmt = "%Y-%m-%d %H:%M:%S" - logging.basicConfig(level=logging.INFO) - - colorfmt = f"%(log_color)s{fmt}%(reset)s" - logging.getLogger().handlers[0].setFormatter( - ColoredFormatter( - colorfmt, - datefmt=datefmt, - reset=True, - log_colors={ - "DEBUG": "cyan", - "INFO": "green", - "WARNING": "yellow", - "ERROR": "red", - "CRITICAL": "red", - }, - ) - ) - - logging.basicConfig(format=fmt, datefmt=datefmt, level=logging.INFO) - - logging.getLogger("requests").setLevel(logging.WARNING) - logging.getLogger("urllib3").setLevel(logging.WARNING) - logging.getLogger("aiohttp.access").setLevel(logging.WARNING) - - sys.excepthook = lambda *args: logging.getLogger("").exception( - "Uncaught exception", exc_info=args # type: ignore - ) - log_rotate_days = 14 - err_log_path = self.config.path(ERROR_LOG_FILENAME) - err_path_exists = os.path.isfile(err_log_path) - err_dir = os.path.dirname(err_log_path) - if not err_dir or not err_path_exists: - os.mkdir(err_log_path) - err_handler: logging.FileHandler = ( - logging.handlers.TimedRotatingFileHandler( - err_log_path, when="midnight", backupCount=log_rotate_days - ) - ) - err_handler.setLevel(logging.INFO if verbose else logging.WARNING) - err_handler.setFormatter(logging.Formatter(fmt, datefmt=datefmt)) - - logger = logging.getLogger("") - logger.addHandler(err_handler) - logger.setLevel(logging.INFO if verbose else logging.WARNING) - - def start(self) -> int: - """Start Photos Core. - Note: This function is only used for testing. - For regular use, use "await photos.run()". - """ - _LOGGER.debug("start core loop") - self.loop.run_forever() - return self.exit_code - - async def async_run(self, *, attach_signals: bool = True) -> int: - """Main entry point.""" - _LOGGER.debug("ApplicationCore::async_run") - - if self.state != CoreState.not_running: - raise RuntimeError("Core is already running") - - # _async_stop will set this instead of stopping the loop - self._stopped = asyncio.Event() - - await self.async_start() - - await self._stopped.wait() - return self.exit_code - - async def async_start(self) -> None: - """Finalize startup from inside the event loop. - This method is a coroutine. - """ - _LOGGER.debug("ApplicationCore::async_start()") - # setattr(self.loop, "_thread_ident", threading.get_ident()) - - self.state = CoreState.starting - - try: - await self.async_block_till_done() - except asyncio.TimeoutError: - _LOGGER.warning( - "Something is blocking core from wrapping up the " - "start up phase. We're going to continue anyway." - ) - - # Wait for all startup triggers before changing state - await asyncio.sleep(0) - - if self.state != CoreState.starting: - _LOGGER.warning( - "Photos.network startup has been interrupted. " - "Its state may be inconsistent" - ) - return - - self.state = CoreState.running - - async def async_set_up_addons(self) -> None: - """setup addons by checking and installing their dependencies and - run their 'async_setup' method.""" - conf_dict = await self._load_config() - addon_dict = await self._load_addons(conf_dict) - - for addon in addon_dict.values(): - # _LOGGER.info(f"setup addon '{addon.domain}'") - - all_requirements_fulfilled = addon.install_requirements() - if not all_requirements_fulfilled: - _LOGGER.error(f"setup addon '{addon.domain}' failed. Not all requirements installed!") - - if all_requirements_fulfilled: - await addon.async_setup_addon() - - async def _load_addons(self, conf_dict) -> dict[Addon]: - """load addons from files""" - addons = {} - for item in conf_dict.get("addons"): - addon_name = item.get("name") - addon_config = item.get("config") - addons[addon_name] = Addon.resolve_from_root(self, addon_name, addon_config) - - return addons - - async def _load_config(self) -> dict: - """load configuration from file and return as dict""" - config_file = os.path.join(self.config.config_dir, 'configuration.json') - _LOGGER.info(f"config_file {config_file}") - with open(config_file, encoding="utf-8") as file: - conf_dict = json.load(file) - - if not isinstance(conf_dict, dict): - msg = ( - f"The configuration file {os.path.basename(self.config.config_dir)} " - "does not contain a dictionary" - ) - _LOGGER.error(msg) - raise RuntimeError(msg) - return conf_dict - - async def async_block_till_done(self) -> None: - """Block until all pending work is done.""" - # To flush out any call_soon_threadsafe - await asyncio.sleep(0) - start_time: Optional[float] = None - - self.http = Webserver(self) - - # setup addons from config entries - await self.async_set_up_addons() - - await self.http.start() - _LOGGER.info("Webserver should be up and running...") - - while self._pending_tasks: - pending = [task for task in self._pending_tasks if not task.done()] - self._pending_tasks.clear() - if pending: - await self._await_and_log_pending(pending) - - if start_time is None: - # Avoid calling monotonic() until we know - # we may need to start logging blocked tasks. - start_time = 0 - elif start_time == 0: - # If we have waited twice then we set the start time - start_time = monotonic() - elif monotonic() - start_time > BLOCK_LOG_TIMEOUT: - # We have waited at least three loops and new tasks - # continue to block. At this point we start - # logging all waiting tasks. - for task in pending: - _LOGGER.debug("Waiting for task: %s", task) - else: - await asyncio.sleep(0) - - async def _await_and_log_pending(self, pending: Iterable[Awaitable[Any]]) -> None: - """Await and log tasks that take a long time.""" - wait_time = 0 - while pending: - _, pending = await asyncio.wait(pending, timeout=BLOCK_LOG_TIMEOUT) - if not pending: - return - wait_time += BLOCK_LOG_TIMEOUT - for task in pending: - _LOGGER.debug("Waited %s seconds for task: %s", wait_time, task) - - -class CoreState(enum.Enum): - """Represent the current state of Photos.network""" - - not_running = "NOT_RUNNING" - starting = "STARTING" - running = "RUNNING" - stopping = "STOPPING" - final_write = "FINAL_WRITE" - stopped = "STOPPED" - - def __str__(self) -> str: # pylint: disable=invalid-str-returned - """Return the event.""" - return self.value # type: ignore diff --git a/core/loader.py b/core/loader.py deleted file mode 100644 index 3967ec5..0000000 --- a/core/loader.py +++ /dev/null @@ -1,119 +0,0 @@ -"""The methods for loading integrations.""" -import asyncio -import functools as ft -import importlib -import json -import logging -import pathlib -from typing import Optional, List - -import sys -from types import ModuleType - -from core.addon import Addon -_LOGGER = logging.getLogger(__name__) -logging.basicConfig(level=logging.DEBUG) - -DATA_ADDONS = "addons" - - -class ModuleWrapper: - """Class to wrap a Python module and auto fill in application core as argument.""" - - def __init__(self, - core: "ApplicationCore", - module: ModuleType - ) -> None: - """Initialize the module wrapper.""" - self._core = core - self._module = module - _LOGGER.error(f"ModuleWrapper init {module}") - - -class Components: - """Helper to load components.""" - - def __init__( - self, - core: "ApplicationCore" - ) -> None: - """Initialize the Components class.""" - self._core = core - - def __getattr__(self, comp_name: str) -> ModuleWrapper: - """Fetch a component.""" - # Test integration cache - integration = self._core.data.get(DATA_ADDONS, {}).get(comp_name) - _LOGGER.error(f"Components.getattr integration {integration}") - - if isinstance(integration, Addon): - component: Optional[ModuleType] = integration.get_component() - else: - # Fallback to importing old-school - component = _load_file(self._core, comp_name, _lookup_path(self._core)) - - if component is None: - raise ImportError(f"Unable to load {comp_name}") - - wrapped = ModuleWrapper(self._core, component) - setattr(self, comp_name, wrapped) - return wrapped - - def _load_file( - self, - comp_or_platform: str, - base_paths: List[str] - ) -> Optional[ModuleType]: - """Try to load specified file. - - Looks in config dir first, then built-in components. - Only returns it if also found to be valid. - Async friendly. - """ - try: - return self._core.data[DATA_ADDONS][comp_or_platform] # type: ignore - except KeyError: - pass - - cache = self._core.data.get(DATA_ADDONS) - if cache is None: - cache = self._core.data[DATA_ADDONS] = {} - - for path in (f"{base}.{comp_or_platform}" for base in base_paths): - try: - module = importlib.import_module(path) - - # In Python 3 you can import files from directories that do not - # contain the file __init__.py. A directory is a valid module if - # it contains a file with the .py extension. In this case Python - # will succeed in importing the directory as a module and call it - # a namespace. We do not care about namespaces. - # This prevents that when only - # custom_components/switch/some_platform.py exists, - # the import custom_components.switch would succeed. - # __file__ was unset for namespaces before Python 3.7 - if getattr(module, "__file__", None) is None: - continue - - cache[comp_or_platform] = module - - if module.__name__.startswith(PACKAGE_CUSTOM_COMPONENTS): - _LOGGER.warning(CUSTOM_WARNING, comp_or_platform) - - return module - - except ImportError as err: - # This error happens if for example custom_components/switch - # exists and we try to load switch.demo. - # Ignore errors for custom_components, custom_components.switch - # and custom_components.switch.demo. - white_listed_errors = [] - parts = [] - for part in path.split("."): - parts.append(part) - white_listed_errors.append(f"No module named '{'.'.join(parts)}'") - - if str(err) not in white_listed_errors: - _LOGGER.exception(f"Error loading {path}. Make sure all dependencies are installed") - - return None diff --git a/core/persistency/__init__.py b/core/persistency/__init__.py deleted file mode 100644 index 3adfc12..0000000 --- a/core/persistency/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""persistency implementation to read/write data.""" diff --git a/core/utils/__init__.py b/core/utils/__init__.py deleted file mode 100644 index 6171434..0000000 --- a/core/utils/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""utils and helpers""" diff --git a/core/utils/timeout.py b/core/utils/timeout.py deleted file mode 100644 index cf09bfb..0000000 --- a/core/utils/timeout.py +++ /dev/null @@ -1,507 +0,0 @@ -"""Advanced timeout handling. - -Set of helper classes to handle timeouts of tasks with advanced options -like zones and freezing of timeouts. -""" -from __future__ import annotations - -import asyncio -import enum -from types import TracebackType -from typing import Any, Dict, List, Optional, Type, Union - - -ZONE_GLOBAL = "global" - - -class _State(str, enum.Enum): - """States of a task.""" - - INIT = "INIT" - ACTIVE = "ACTIVE" - TIMEOUT = "TIMEOUT" - EXIT = "EXIT" - - -class _GlobalFreezeContext: - """Context manager that freezes the global timeout.""" - - def __init__(self, manager: TimeoutManager) -> None: - """Initialize internal timeout context manager.""" - self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - self._manager: TimeoutManager = manager - - async def __aenter__(self) -> _GlobalFreezeContext: - self._enter() - return self - - async def __aexit__( - self, - exc_type: Type[BaseException], - exc_val: BaseException, - exc_tb: TracebackType, - ) -> Optional[bool]: - self._exit() - return None - - def __enter__(self) -> _GlobalFreezeContext: - self._loop.call_soon_threadsafe(self._enter) - return self - - def __exit__( - self, - exc_type: Type[BaseException], - exc_val: BaseException, - exc_tb: TracebackType, - ) -> Optional[bool]: - self._loop.call_soon_threadsafe(self._exit) - return True - - def _enter(self) -> None: - """Run freeze.""" - if not self._manager.freezes_done: - return - - # Global reset - for task in self._manager.global_tasks: - task.pause() - - # Zones reset - for zone in self._manager.zones.values(): - if not zone.freezes_done: - continue - zone.pause() - - self._manager.global_freezes.append(self) - - def _exit(self) -> None: - """Finish freeze.""" - self._manager.global_freezes.remove(self) - if not self._manager.freezes_done: - return - - # Global reset - for task in self._manager.global_tasks: - task.reset() - - # Zones reset - for zone in self._manager.zones.values(): - if not zone.freezes_done: - continue - zone.reset() - - -class _ZoneFreezeContext: - """Context manager that freezes a zone timeout.""" - - def __init__(self, zone: _ZoneTimeoutManager) -> None: - """Initialize internal timeout context manager.""" - self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - self._zone: _ZoneTimeoutManager = zone - - async def __aenter__(self) -> _ZoneFreezeContext: - self._enter() - return self - - async def __aexit__( - self, - exc_type: Type[BaseException], - exc_val: BaseException, - exc_tb: TracebackType, - ) -> Optional[bool]: - self._exit() - return None - - def __enter__(self) -> _ZoneFreezeContext: - self._loop.call_soon_threadsafe(self._enter) - return self - - def __exit__( - self, - exc_type: Type[BaseException], - exc_val: BaseException, - exc_tb: TracebackType, - ) -> Optional[bool]: - self._loop.call_soon_threadsafe(self._exit) - return True - - def _enter(self) -> None: - """Run freeze.""" - if self._zone.freezes_done: - self._zone.pause() - self._zone.enter_freeze(self) - - def _exit(self) -> None: - """Finish freeze.""" - self._zone.exit_freeze(self) - if not self._zone.freezes_done: - return - self._zone.reset() - - -class _GlobalTaskContext: - """Context manager that tracks a global task.""" - - def __init__( - self, - manager: TimeoutManager, - task: asyncio.Task[Any], - timeout: float, - cool_down: float, - ) -> None: - """Initialize internal timeout context manager.""" - self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - self._manager: TimeoutManager = manager - self._task: asyncio.Task[Any] = task - self._time_left: float = timeout - self._expiration_time: Optional[float] = None - self._timeout_handler: Optional[asyncio.Handle] = None - self._wait_zone: asyncio.Event = asyncio.Event() - self._state: _State = _State.INIT - self._cool_down: float = cool_down - - async def __aenter__(self) -> _GlobalTaskContext: - self._manager.global_tasks.append(self) - self._start_timer() - self._state = _State.ACTIVE - return self - - async def __aexit__( - self, - exc_type: Type[BaseException], - exc_val: BaseException, - exc_tb: TracebackType, - ) -> Optional[bool]: - self._stop_timer() - self._manager.global_tasks.remove(self) - - # Timeout on exit - if exc_type is asyncio.CancelledError and self.state == _State.TIMEOUT: - raise asyncio.TimeoutError - - self._state = _State.EXIT - self._wait_zone.set() - return None - - @property - def state(self) -> _State: - """Return state of the Global task.""" - return self._state - - def zones_done_signal(self) -> None: - """Signal that all zones are done.""" - self._wait_zone.set() - - def _start_timer(self) -> None: - """Start timeout handler.""" - if self._timeout_handler: - return - - self._expiration_time = self._loop.time() + self._time_left - self._timeout_handler = self._loop.call_at( - self._expiration_time, self._on_timeout - ) - - def _stop_timer(self) -> None: - """Stop zone timer.""" - if self._timeout_handler is None: - return - - self._timeout_handler.cancel() - self._timeout_handler = None - # Calculate new timeout - assert self._expiration_time - self._time_left = self._expiration_time - self._loop.time() - - def _on_timeout(self) -> None: - """Process timeout.""" - self._state = _State.TIMEOUT - self._timeout_handler = None - - # Reset timer if zones are running - if not self._manager.zones_done: - asyncio.create_task(self._on_wait()) - else: - self._cancel_task() - - def _cancel_task(self) -> None: - """Cancel own task.""" - if self._task.done(): - return - self._task.cancel() - - def pause(self) -> None: - """Pause timers while it freeze.""" - self._stop_timer() - - def reset(self) -> None: - """Reset timer after freeze.""" - self._start_timer() - - async def _on_wait(self) -> None: - """Wait until zones are done.""" - await self._wait_zone.wait() - await asyncio.sleep(self._cool_down) # Allow context switch - if not self.state == _State.TIMEOUT: - return - self._cancel_task() - - -class _ZoneTaskContext: - """Context manager that tracks an active task for a zone.""" - - def __init__( - self, - zone: _ZoneTimeoutManager, - task: asyncio.Task[Any], - timeout: float, - ) -> None: - """Initialize internal timeout context manager.""" - self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - self._zone: _ZoneTimeoutManager = zone - self._task: asyncio.Task[Any] = task - self._state: _State = _State.INIT - self._time_left: float = timeout - self._expiration_time: Optional[float] = None - self._timeout_handler: Optional[asyncio.Handle] = None - - @property - def state(self) -> _State: - """Return state of the Zone task.""" - return self._state - - async def __aenter__(self) -> _ZoneTaskContext: - self._zone.enter_task(self) - self._state = _State.ACTIVE - - # Zone is on freeze - if self._zone.freezes_done: - self._start_timer() - - return self - - async def __aexit__( - self, - exc_type: Type[BaseException], - exc_val: BaseException, - exc_tb: TracebackType, - ) -> Optional[bool]: - self._zone.exit_task(self) - self._stop_timer() - - # Timeout on exit - if exc_type is asyncio.CancelledError and self.state == _State.TIMEOUT: - raise asyncio.TimeoutError - - self._state = _State.EXIT - return None - - def _start_timer(self) -> None: - """Start timeout handler.""" - if self._timeout_handler: - return - - self._expiration_time = self._loop.time() + self._time_left - self._timeout_handler = self._loop.call_at( - self._expiration_time, self._on_timeout - ) - - def _stop_timer(self) -> None: - """Stop zone timer.""" - if self._timeout_handler is None: - return - - self._timeout_handler.cancel() - self._timeout_handler = None - # Calculate new timeout - assert self._expiration_time - self._time_left = self._expiration_time - self._loop.time() - - def _on_timeout(self) -> None: - """Process timeout.""" - self._state = _State.TIMEOUT - self._timeout_handler = None - - # Timeout - if self._task.done(): - return - self._task.cancel() - - def pause(self) -> None: - """Pause timers while it freeze.""" - self._stop_timer() - - def reset(self) -> None: - """Reset timer after freeze.""" - self._start_timer() - - -class _ZoneTimeoutManager: - """Manage the timeouts for a zone.""" - - def __init__(self, manager: TimeoutManager, zone: str) -> None: - """Initialize internal timeout context manager.""" - self._manager: TimeoutManager = manager - self._zone: str = zone - self._tasks: List[_ZoneTaskContext] = [] - self._freezes: List[_ZoneFreezeContext] = [] - - @property - def name(self) -> str: - """Return Zone name.""" - return self._zone - - @property - def active(self) -> bool: - """Return True if zone is active.""" - return len(self._tasks) > 0 or len(self._freezes) > 0 - - @property - def freezes_done(self) -> bool: - """Return True if all freeze are done.""" - return len(self._freezes) == 0 and self._manager.freezes_done - - def enter_task(self, task: _ZoneTaskContext) -> None: - """Start into new Task.""" - self._tasks.append(task) - - def exit_task(self, task: _ZoneTaskContext) -> None: - """Exit a running Task.""" - self._tasks.remove(task) - - # On latest listener - if not self.active: - self._manager.drop_zone(self.name) - - def enter_freeze(self, freeze: _ZoneFreezeContext) -> None: - """Start into new freeze.""" - self._freezes.append(freeze) - - def exit_freeze(self, freeze: _ZoneFreezeContext) -> None: - """Exit a running Freeze.""" - self._freezes.remove(freeze) - - # On latest listener - if not self.active: - self._manager.drop_zone(self.name) - - def pause(self) -> None: - """Stop timers while it freeze.""" - if not self.active: - return - - # Forward pause - for task in self._tasks: - task.pause() - - def reset(self) -> None: - """Reset timer after freeze.""" - if not self.active: - return - - # Forward reset - for task in self._tasks: - task.reset() - - -class TimeoutManager: - """Class to manage timeouts over different zones. - - Manages both global and zone based timeouts. - """ - - def __init__(self) -> None: - """Initialize TimeoutManager.""" - self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - self._zones: Dict[str, _ZoneTimeoutManager] = {} - self._globals: List[_GlobalTaskContext] = [] - self._freezes: List[_GlobalFreezeContext] = [] - - @property - def zones_done(self) -> bool: - """Return True if all zones are finished.""" - return not bool(self._zones) - - @property - def freezes_done(self) -> bool: - """Return True if all freezes are finished.""" - return not self._freezes - - @property - def zones(self) -> Dict[str, _ZoneTimeoutManager]: - """Return all Zones.""" - return self._zones - - @property - def global_tasks(self) -> List[_GlobalTaskContext]: - """Return all global Tasks.""" - return self._globals - - @property - def global_freezes(self) -> List[_GlobalFreezeContext]: - """Return all global Freezes.""" - return self._freezes - - def drop_zone(self, zone_name: str) -> None: - """Drop a zone out of scope.""" - self._zones.pop(zone_name, None) - if self._zones: - return - - # Signal Global task, all zones are done - for task in self._globals: - task.zones_done_signal() - - def async_timeout( - self, timeout: float, zone_name: str = ZONE_GLOBAL, cool_down: float = 0 - ) -> Union[_ZoneTaskContext, _GlobalTaskContext]: - """Timeout based on a zone. - - For using as Async Context Manager. - """ - current_task: Optional[asyncio.Task[Any]] = asyncio.current_task() - assert current_task - - # Global Zone - if zone_name == ZONE_GLOBAL: - task = _GlobalTaskContext(self, current_task, timeout, cool_down) - return task - - # Zone Handling - if zone_name in self.zones: - zone: _ZoneTimeoutManager = self.zones[zone_name] - else: - self.zones[zone_name] = zone = _ZoneTimeoutManager(self, zone_name) - - # Create Task - return _ZoneTaskContext(zone, current_task, timeout) - - def async_freeze( - self, zone_name: str = ZONE_GLOBAL - ) -> Union[_ZoneFreezeContext, _GlobalFreezeContext]: - """Freeze all timer until job is done. - - For using as Async Context Manager. - """ - # Global Freeze - if zone_name == ZONE_GLOBAL: - return _GlobalFreezeContext(self) - - # Zone Freeze - if zone_name in self.zones: - zone: _ZoneTimeoutManager = self.zones[zone_name] - else: - self.zones[zone_name] = zone = _ZoneTimeoutManager(self, zone_name) - - return _ZoneFreezeContext(zone) - - def freeze( - self, zone_name: str = ZONE_GLOBAL - ) -> Union[_ZoneFreezeContext, _GlobalFreezeContext]: - """Freeze all timer until job is done. - - For using as Context Manager. - """ - return run_callback_threadsafe( - self._loop, self.async_freeze, zone_name - ).result() diff --git a/core/utils/uuid.py b/core/utils/uuid.py deleted file mode 100644 index f781168..0000000 --- a/core/utils/uuid.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Helpers to generate uuids.""" - -from random import getrandbits - - -def random_uuid_hex() -> str: - """Generate a random UUID hex. - This uuid should not be used for cryptographically secure - operations. - """ - return "%032x" % getrandbits(32 * 4) diff --git a/core/webserver/__init__.py b/core/webserver/__init__.py deleted file mode 100644 index 65f9f8e..0000000 --- a/core/webserver/__init__.py +++ /dev/null @@ -1,122 +0,0 @@ -"""HTTP server implementation.""" -from ipaddress import ip_address -from typing import TYPE_CHECKING, TypeVar, Type - -from aiohttp import web, hdrs -import logging - -from aiohttp.web_exceptions import HTTPForbidden, HTTPUnauthorized -from aiohttp.web_middlewares import middleware - -if TYPE_CHECKING: - from core.webserver.request import Request - from core.core import ApplicationCore - -_LOGGER = logging.getLogger(__name__) -MAX_CLIENT_SIZE: int = 1024 ** 2 * 16 -LOGIN_ATTEMPT_THRESHOLD = 3 -KEY_AUTHENTICATED = "authenticated" - - -class Webserver: - """Webserver implementation""" - - def __init__(self, core: "ApplicationCore"): - self.core = core - self.app = web.Application( - middlewares=[], - client_max_size=MAX_CLIENT_SIZE) - self.runner = web.AppRunner(self.app) - - self.app.middlewares.append(self.ban_middleware) - self.app.middlewares.append(self.auth_middleware) - # TODO: add cors middleware - # self.app.middlewares.append(self.cors_middleware) - - def register_request(self, view: Type["Request"]): - """Register a request, wich must inherit from Request""" - if not hasattr(view, "url"): - class_name = view.__class__.__name__ - raise AttributeError(f'{class_name} missing required attribute "url"') - - if not hasattr(view, "name"): - class_name = view.__class__.__name__ - raise AttributeError(f'{class_name} missing required attribute "name"') - - view.register(view, self.app, self.app.router) - - async def start(self): - await self.runner.setup() - - site = web.TCPSite( - runner=self.runner, - host='localhost', - port=8080) - await site.start() - - async def stop(self): - await self.runner.cleanup() - - @middleware - async def ban_middleware(self, request: web.Request, handler): - """Block IP if threshold of failed login attempts exceeds.""" - remote_ip = ip_address(request.remote) - is_banned = remote_ip in self.core.banned_ips - - # return with Forbidden if already banned - if is_banned: - raise HTTPForbidden() - - try: - return await handler(request) - except HTTPUnauthorized: - remote_addr = ip_address(request.remote) - remote_host = request.remote - - msg = f"Login attempt or request with invalid authentication from {remote_host} ({remote_addr})" - - user_agent = request.headers.get("user-agent") - if user_agent: - msg = f"{msg} ({user_agent})" - - _LOGGER.warning(msg) - - # track failed login attempt - if remote_addr in self.core.failed_logins: - # check login attempt count - if self.core.failed_logins[remote_addr] >= LOGIN_ATTEMPT_THRESHOLD: - _LOGGER.warning(f"Banned IP {remote_addr} for too many login attempts") - self.core.banned_ips.append(remote_addr) - else: - old_count = self.core.banned_ips[remote_addr] - self.core.banned_ips[remote_addr] = old_count + 1 - else: - self.core.failed_logins[remote_addr] = 1 - - raise - - @middleware - async def auth_middleware(self, request: web.Request, handler): - """Check authentication for requests.""" - authenticated = False - - if hdrs.AUTHORIZATION in request.headers: - try: - auth_type, auth_val = request.headers.get(hdrs.AUTHORIZATION).split(" ", 1) - except ValueError: - # If no space in authorization header - return False - - if auth_type != "Bearer": - return False - - _LOGGER.error(f"validate auth_val: {auth_val}") - - authenticated = True - auth_type = "bearer token" - - if authenticated: - _LOGGER.debug(f"Authenticated {request.remote} for {request.path} using {auth_type}") - request[KEY_AUTHENTICATED] = authenticated - - return await handler(request) diff --git a/core/webserver/exceptions.py b/core/webserver/exceptions.py deleted file mode 100644 index a2312b0..0000000 --- a/core/webserver/exceptions.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Exceptions used by webserver.""" - - -class WebserverError(Exception): - """General exception occurred.""" - - -class Unauthorized(WebserverError): - """When an action is unauthorized""" - - -class ServiceNotFound(WebserverError): - """Raised when an error occured.""" diff --git a/core/webserver/request.py b/core/webserver/request.py deleted file mode 100644 index 213be57..0000000 --- a/core/webserver/request.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python3 -import asyncio -import json -import logging -from typing import Any, Optional, List, Callable - -import voluptuous -from aiohttp import web -from aiohttp.typedefs import LooseHeaders, JSONEncoder -from aiohttp.web_exceptions import ( - HTTPInternalServerError, HTTPBadRequest, HTTPUnauthorized, -) - -from core.context import Context -from core.core import is_callback -from core.webserver import exceptions, KEY_AUTHENTICATED -from core.webserver.status import HTTP_OK -from core.webserver.type import APPLICATION_JSON -_LOGGER = logging.getLogger(__name__) - - -class Request: - url: Optional[str] = None - extra_urls: List[str] = [] - - requires_auth = True - - @staticmethod - def context(request: web.Request) -> Context: - """Generate a context from a request.""" - user = request.get("core_user") - if user is None: - return Context() - - return Context(user_id=user.id) - - @staticmethod - def json( - result: Any, - status_code: int = HTTP_OK, - headers: Optional[LooseHeaders] = None, - ) -> web.Response: - """Return a JSON response.""" - try: - msg = json.dumps(result, cls=JSONEncoder, allow_nan=False).encode("UTF-8") - except (ValueError, TypeError) as err: - _LOGGER.error(f"Unable to serialize to JSON: {err}\n{result}") - raise HTTPInternalServerError from err - response = web.Response( - body=msg, - content_type=APPLICATION_JSON, - status=status_code, - headers=headers, - ) - response.enable_compression() - return response - - @staticmethod - def json_message( - message: str, - status_code: int = HTTP_OK, - message_code: Optional[str] = None, - headers: Optional[LooseHeaders] = None, - ) -> web.Response: - """Return a JSON message response.""" - data = {"message": message} - if message_code is not None: - data["code"] = message_code - return Request.json(data, status_code, headers=headers) - - def register(self, app: web.Application, router: web.UrlDispatcher) -> None: - """Register the view with a router.""" - assert self.url is not None, "No url set for view" - urls = [self.url] + self.extra_urls - routes = [] - - for method in ("get", "post", "delete", "put", "patch", "head", "options"): - handler = getattr(self, method, None) - - if not handler: - continue - - handler = request_handler_factory(self, handler) - - for url in urls: - routes.append(router.add_route(method, url, handler)) - - -def request_handler_factory(view: Request, handler: Callable) -> Callable: - """Wrap the handler classes.""" - assert asyncio.iscoroutinefunction(handler) or is_callback( - handler - ), "Handler should be a coroutine or a callback." - - async def handle(request: web.Request) -> web.StreamResponse: - """Handle incoming request.""" - authenticated = request.get(KEY_AUTHENTICATED, False) - - if view.requires_auth and not authenticated: - raise HTTPUnauthorized() - - _LOGGER.debug(f"Serving {request.path} to {request.remote} (auth: {authenticated})") - - try: - result = handler(request, **request.match_info) - - if asyncio.iscoroutine(result): - result = await result - except voluptuous.Invalid as err: - raise HTTPBadRequest() from err - except exceptions.ServiceNotFound as err: - raise HTTPInternalServerError() from err - except exceptions.Unauthorized as err: - raise HTTPUnauthorized() from err - - if isinstance(result, web.StreamResponse): - # The method handler returned a ready-made Response, how nice of it - return result - - status_code = HTTP_OK - - if isinstance(result, tuple): - result, status_code = result - - if isinstance(result, bytes): - bresult = result - elif isinstance(result, str): - bresult = result.encode("utf-8") - elif result is None: - bresult = b"" - else: - assert ( - False - ), f"Result should be None, string, bytes or Response. Got: {result}" - - return web.Response(body=bresult, status=status_code) - - return handle diff --git a/core/webserver/status.py b/core/webserver/status.py deleted file mode 100644 index 65779da..0000000 --- a/core/webserver/status.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python3 - -HTTP_OK = 200 -HTTP_CREATED = 201 -HTTP_ACCEPTED = 202 -HTTP_MOVED_PERMANENTLY = 301 -HTTP_BAD_REQUEST = 400 -HTTP_UNAUTHORIZED = 401 -HTTP_FORBIDDEN = 403 -HTTP_NOT_FOUND = 404 -HTTP_METHOD_NOT_ALLOWED = 405 -HTTP_UNPROCESSABLE_ENTITY = 422 -HTTP_TOO_MANY_REQUESTS = 429 -HTTP_INTERNAL_SERVER_ERROR = 500 -HTTP_BAD_GATEWAY = 502 -HTTP_SERVICE_UNAVAILABLE = 503 diff --git a/core/webserver/type.py b/core/webserver/type.py deleted file mode 100644 index d1c8d94..0000000 --- a/core/webserver/type.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python3 - -APPLICATION_JSON = "application/json" -APPLICATION_X_WWW_FORM_URL_ENCODED = "application/x-www-form-urlencoded" -IMAGE_JPEG = "image/jpeg" -IMAGE_PNG = "image/png" -IMAGE_GIF = "image/gif" -TEXT_HTML = "text/html" -TEXT_PLAIN = "text/plain" -MULTIPART_FORM_DATA = "multipart/form-data; boundary=$boundary" diff --git a/crates/accounts/Cargo.toml b/crates/accounts/Cargo.toml new file mode 100644 index 0000000..df14706 --- /dev/null +++ b/crates/accounts/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "accounts" +description = "Manages all accounts in the database." +version.workspace = true +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "accounts" +path = "src/lib.rs" +doctest = false + +[dependencies] +common = { path = "../common" } +database = { path = "../database" } + +# serialization +serde = { workspace = true, features = ["derive"] } + +# Router +axum = { workspace = true } +tower-http.workspace = true + +# testing +mockall = { workspace = true } +rstest = { workspace = true } diff --git a/crates/accounts/src/api/mod.rs b/crates/accounts/src/api/mod.rs new file mode 100644 index 0000000..e62bb99 --- /dev/null +++ b/crates/accounts/src/api/mod.rs @@ -0,0 +1,2 @@ +pub mod router; +pub(crate) mod routes; diff --git a/crates/accounts/src/api/router.rs b/crates/accounts/src/api/router.rs new file mode 100644 index 0000000..5fe2a60 --- /dev/null +++ b/crates/accounts/src/api/router.rs @@ -0,0 +1,57 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::routing::{get, patch}; +use axum::Router; + +use super::routes::get_user_id_profile::get_user_id_profile; + +pub struct AccountsApi {} + +impl AccountsApi { + pub fn routes() -> Router + where + S: Send + Sync + 'static + Clone, + { + Router::new() + // Returns information about a single account by ID + // 200 OK + // 401 Unauthorized - Requesting user is unauthenticated + // 404 Not Found - The requested resource does not exist. + .route("/users/:user_id/profile", get(get_user_id_profile)) + // Update a single account when `admin.users:write` scope is present + // 200 - OK + // 400 Bad Request - The request body was malformed or a field violated its constraints. + // 401 Unauthorized - You are unauthenticated + // 403 Forbidden - You are authenticated but have no permission to manage the target user. + // 404 Not Found - The requested resource does not exist. + .route("/users/:user_id/profile", patch(get_user_id_profile)) + // Disable a single account by ID when `admin.users:write` scope is present + // 204 No Content - Account was disabled successful + // 401 Unauthorized - You are unauthenticated + // 403 Forbidden - You are authenticated but have no permission to manage the target user. + // 404 Not Found - The requested resource does not exist. + .route("/users/:user_id/disable", patch(get_user_id_profile)) + // Enable a single account by ID when `admin.users:write` scope is present + // 204 No Content - Account was enabled successful + // 401 Unauthorized - You are unauthenticated + // 403 Forbidden - You are authenticated but have no permission to manage the target user. + // 404 Not Found - The requested resource does not exist. + .route("/users/:user_id/enabled", patch(get_user_id_profile)) + .layer(tower_http::trace::TraceLayer::new_for_http()) + } +} diff --git a/crates/accounts/src/api/routes/get_user_id_profile.rs b/crates/accounts/src/api/routes/get_user_id_profile.rs new file mode 100644 index 0000000..6ff98bd --- /dev/null +++ b/crates/accounts/src/api/routes/get_user_id_profile.rs @@ -0,0 +1,22 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::http::StatusCode; + +pub(crate) async fn get_user_id_profile() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/accounts/src/api/routes/mod.rs b/crates/accounts/src/api/routes/mod.rs new file mode 100644 index 0000000..c02637b --- /dev/null +++ b/crates/accounts/src/api/routes/mod.rs @@ -0,0 +1 @@ +pub(crate) mod get_user_id_profile; diff --git a/crates/accounts/src/lib.rs b/crates/accounts/src/lib.rs new file mode 100644 index 0000000..8aaf638 --- /dev/null +++ b/crates/accounts/src/lib.rs @@ -0,0 +1,20 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate handles all account related tasks in [Photos.network](https://photos.network) core application. +//! +pub mod api; diff --git a/crates/activity_pub/Cargo.toml b/crates/activity_pub/Cargo.toml new file mode 100644 index 0000000..61cda90 --- /dev/null +++ b/crates/activity_pub/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "activity_pub" +description = "ActivityPub protocol implementation to join the Fediverse." +version.workspace = true +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "activity_pub" +path = "src/lib.rs" +doctest = false + +[dependencies] +common = { workspace = true } +activitypub_federation = { workspace = true } diff --git a/crates/activity_pub/README.md b/crates/activity_pub/README.md new file mode 100644 index 0000000..6e73731 --- /dev/null +++ b/crates/activity_pub/README.md @@ -0,0 +1,4 @@ +# activity_pub + +This crate provides the [ActivityPub](https://www.w3.org/TR/activitypub/) implementation for [Photos.network](https://photos.network). + diff --git a/crates/activity_pub/src/lib.rs b/crates/activity_pub/src/lib.rs new file mode 100644 index 0000000..b821bf8 --- /dev/null +++ b/crates/activity_pub/src/lib.rs @@ -0,0 +1,18 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +//! This crate provides the [ActivityPub](https://www.w3.org/TR/activitypub/) implementation for [Photos.network](https://photos.network). +//! diff --git a/crates/activity_pub/src/model/person.rs b/crates/activity_pub/src/model/person.rs new file mode 100644 index 0000000..3f414c2 --- /dev/null +++ b/crates/activity_pub/src/model/person.rs @@ -0,0 +1,30 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Person { + id: ObjectId, + #[serde(rename = "type")] + kind: PersonType, + preferred_username: String, + name: String, + inbox: Url, + outbox: Url, + public_key: PublicKey, +} diff --git a/crates/activity_pub/src/routes/webfinger.rs b/crates/activity_pub/src/routes/webfinger.rs new file mode 100644 index 0000000..7bdcc9d --- /dev/null +++ b/crates/activity_pub/src/routes/webfinger.rs @@ -0,0 +1,34 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + + +use axum::{ + routing::{ get, post }, + Router, +}; + +pub fn routes() -> Router + where + S: Send + Sync + 'static + Clone, + { + Router::new() + .route("/authorize", get(authorization_endpoint_get)) + + .route("/token", post( || async { "Access token request" } )) + .route("/refresh", post( || async { "Access token request" } )) + .route("/", post( || async { "Access token request" } )) + } diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml new file mode 100644 index 0000000..2316765 --- /dev/null +++ b/crates/common/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "common" +version.workspace = true +authors.workspace = true +description.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "common" +path = "src/lib.rs" +doctest = false + +[dependencies] +async-trait.workspace = true +axum.workspace = true +http.workspace = true +photos_network_plugin = { path = "../plugin_interface" } + +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +serde_with.workspace = true +time.workspace = true +tracing.workspace = true +uuid = { workspace = true, features = ["serde"] } + +[dev-dependencies] +testdir.workspace = true diff --git a/crates/common/README.md b/crates/common/README.md new file mode 100644 index 0000000..e28b9de --- /dev/null +++ b/crates/common/README.md @@ -0,0 +1,3 @@ +# common + +This crate provides shared data types used within [Photos.network](https://photos.network). diff --git a/crates/common/src/auth/login.rs b/crates/common/src/auth/login.rs new file mode 100644 index 0000000..979da2f --- /dev/null +++ b/crates/common/src/auth/login.rs @@ -0,0 +1,44 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Login request +//! +//! Provides an abstraction over a vlue for sensitive data like passwords. +//! It is not printing its value to logs or tracing +//! +use serde::{Deserialize, Serialize}; + +use crate::model::sensitive::Sensitive; + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +pub struct Login { + pub username_or_email: Sensitive, + pub password: Sensitive, + pub totp_2fa_token: Option, +} + +// Login response +// +// * `jwt` - None if email verification is enabled. +// * `verify_email_sent` - Indicates if an email verification is needed. +// +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct LoginResponse { + pub jwt: Option>, + pub registration_created: bool, + pub verify_email_sent: bool, +} diff --git a/crates/common/src/auth/mod.rs b/crates/common/src/auth/mod.rs new file mode 100644 index 0000000..063e88f --- /dev/null +++ b/crates/common/src/auth/mod.rs @@ -0,0 +1,2 @@ +pub mod login; +pub mod user; diff --git a/crates/common/src/auth/user.rs b/crates/common/src/auth/user.rs new file mode 100644 index 0000000..ca3d5c7 --- /dev/null +++ b/crates/common/src/auth/user.rs @@ -0,0 +1,61 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use std::fmt; +use time::OffsetDateTime; +use uuid::Uuid; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct User { + pub uuid: String, //Uuid, + pub email: String, + pub password: Option, + pub lastname: Option, + pub firstname: Option, + pub is_locked: bool, + pub created_at: OffsetDateTime, + pub updated_at: Option, + pub last_login: Option, +} + +impl fmt::Display for User { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} ({}), locked:{})", + self.email, self.uuid, self.is_locked + ) + } +} + +impl User { + pub(crate) fn new(email: String) -> User { + User { + uuid: Uuid::parse_str("808c78e4-34bc-486a-902f-929e8b146d20") + .unwrap() + .to_string(), + email, + password: Option::None, + lastname: Option::None, + firstname: Option::None, + is_locked: false, + created_at: OffsetDateTime::now_utc(), + updated_at: Option::None, + last_login: Option::None, + } + } +} diff --git a/crates/common/src/config/client.rs b/crates/common/src/config/client.rs new file mode 100644 index 0000000..715adbf --- /dev/null +++ b/crates/common/src/config/client.rs @@ -0,0 +1,88 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This represents an oauth client configuration +use std::fmt; + +use serde::{Deserialize, Serialize}; + +#[derive(PartialEq, Debug, Deserialize, Serialize, Clone)] +pub struct OAuthClientConfig { + pub name: String, + pub client_id: String, + pub client_secret: String, + pub redirect_uris: Vec, +} + +impl fmt::Display for OAuthClientConfig { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}, redirects: {:?}", self.name, self.redirect_uris) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_full_deserialization() { + // given + let json = r#"{ + "name": "Client", + "client_id": "clientId", + "client_secret": "clientSecret", + "redirect_uris": [ + "https://demo.photos.network/callback", + "http://127.0.0.1:7777/callback", + "photosapp://authenticate" + ] + }"#; + + let data = OAuthClientConfig { + name: "Client".into(), + client_id: "clientId".into(), + client_secret: "clientSecret".into(), + redirect_uris: vec![ + "https://demo.photos.network/callback".into(), + "http://127.0.0.1:7777/callback".into(), + "photosapp://authenticate".into(), + ], + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } + + #[test] + fn test_minimal_deserialization() { + // given + let json = r#"{ + "name": "Client", + "client_id": "clientId", + "client_secret": "clientSecret", + "redirect_uris": [] + }"#; + + let data = OAuthClientConfig { + name: "Client".into(), + client_id: "clientId".into(), + client_secret: "clientSecret".into(), + redirect_uris: vec![], + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } +} diff --git a/crates/common/src/config/configuration.rs b/crates/common/src/config/configuration.rs new file mode 100644 index 0000000..45d5dbb --- /dev/null +++ b/crates/common/src/config/configuration.rs @@ -0,0 +1,173 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This defines the app configuration +use std::{fmt, fs}; + +use serde::Deserialize; +use tracing::info; + +use super::{client::OAuthClientConfig, database_config::DatabaseConfig, plugin::Plugin}; + +#[derive(Debug, PartialEq, Deserialize, Clone)] +pub struct Configuration { + pub internal_url: String, + pub external_url: String, + pub database: Option, + // pub auth_provider: Vec, + pub clients: Vec, + pub plugins: Vec, +} + +impl Configuration { + pub fn new(path: &str) -> Option { + info!("Load configuration file {}", path); + let data = fs::read_to_string(path).expect("Unable to read configuration file!"); + let config: Configuration = + serde_json::from_str(&data).expect("Configuration file could not be parsed as JSON!"); + + Some(config) + } + + /// Use this for tests + pub fn empty() -> Self { + Configuration { + internal_url: "".into(), + external_url: "".into(), + database: None, + clients: vec![], + plugins: vec![], + } + } +} + +impl fmt::Display for Configuration { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let clients = &self.clients; + let plugins = &self.plugins; + + write!(f, "{{")?; + write!(f, "\n\tinternal: {}", self.internal_url)?; + write!(f, "\n\texternal: {}", self.external_url)?; + + // clients + write!(f, "\n\tclients: [ ")?; + for (count, v) in clients.iter().enumerate() { + if count != 0 { + write!(f, ", ")?; + } + write!(f, "\n\t\t{}", v)?; + } + write!(f, "\n\t] ")?; + + // plugins + write!(f, "\n\tplugins: [ ")?; + for (count, v) in plugins.iter().enumerate() { + if count != 0 { + write!(f, ", ")?; + } + write!(f, "\n\t\t{}", v)?; + } + write!(f, "\n\t]")?; + write!(f, "\n}}") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Map; + + #[test] + fn test_minimal_deserialization() { + // given + let json = r#"{ + "internal_url": "192.168.0.1", + "external_url": "demo.photos.network", + "clients": [], + "plugins": [] + }"#; + + let data = Configuration { + internal_url: "192.168.0.1".into(), + external_url: "demo.photos.network".into(), + database: None, + clients: vec![], + plugins: vec![], + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } + + #[test] + fn test_full_deserialization() { + // given + let json = r#"{ + "internal_url": "192.168.0.1", + "external_url": "demo.photos.network", + "clients": [ + { + "name": "Client", + "client_id": "clientId", + "client_secret": "clientSecret", + "redirect_uris": [] + } + ], + "plugins": [ + { + "name": "Plugin", + "config": { + "property1": null, + "property2": true, + "property3": "aBc", + "property4": 42 + } + } + ] + }"#; + + let mut config = Map::new(); + config.insert("property1".to_string(), serde_json::Value::Null); + config.insert("property2".to_string(), serde_json::Value::Bool(true)); + config.insert( + "property3".to_string(), + serde_json::Value::String("aBc".into()), + ); + config.insert( + "property4".to_string(), + serde_json::Value::Number(42.into()), + ); + + let data = Configuration { + internal_url: "192.168.0.1".into(), + external_url: "demo.photos.network".into(), + database: None, + clients: vec![OAuthClientConfig { + name: "Client".into(), + client_id: "clientId".into(), + client_secret: "clientSecret".into(), + redirect_uris: vec![], + }], + plugins: vec![Plugin { + name: "Plugin".into(), + config: Some(config), + }], + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } +} diff --git a/crates/common/src/config/database_config.rs b/crates/common/src/config/database_config.rs new file mode 100644 index 0000000..5dcfa36 --- /dev/null +++ b/crates/common/src/config/database_config.rs @@ -0,0 +1,93 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This represents a database configuration +use std::fmt; + +use serde::{Deserialize, Serialize}; + +#[derive(PartialEq, Debug, Deserialize, Serialize, Clone)] +pub struct DatabaseConfig { + pub driver: DatabaseDriver, + pub url: String, +} + +#[derive(PartialEq, Debug, Deserialize, Serialize, Clone)] +pub enum DatabaseDriver { + MySQL, + PostgresSQL, + SQLite, +} + +impl fmt::Display for DatabaseConfig { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?} database; URL: {}", self.driver, self.url) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_mysql_deserialization() { + // given + let json = r#"{ + "driver": "MySQL", + "url": "protocol://username:password@host/database" + }"#; + + let data = DatabaseConfig { + driver: DatabaseDriver::MySQL, + url: "protocol://username:password@host/database".into(), + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } + + #[test] + fn test_postgres_deserialization() { + // given + let json = r#"{ + "driver": "MySQL", + "url": "protocol://username:password@host/database" + }"#; + + let data = DatabaseConfig { + driver: DatabaseDriver::MySQL, + url: "protocol://username:password@host/database".into(), + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } + + #[test] + fn test_sqlite_deserialization() { + // given + let json = r#"{ + "driver": "SQLite", + "url": "protocol://username:password@host/database" + }"#; + + let data = DatabaseConfig { + driver: DatabaseDriver::SQLite, + url: "protocol://username:password@host/database".into(), + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } +} diff --git a/crates/common/src/config/mod.rs b/crates/common/src/config/mod.rs new file mode 100644 index 0000000..54e729f --- /dev/null +++ b/crates/common/src/config/mod.rs @@ -0,0 +1,24 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! The Configuration to customize the behaviour of the Photos.network core +//! +//! +pub mod client; +pub mod configuration; +pub mod database_config; +pub mod plugin; diff --git a/crates/common/src/config/plugin.rs b/crates/common/src/config/plugin.rs new file mode 100644 index 0000000..3ad93ed --- /dev/null +++ b/crates/common/src/config/plugin.rs @@ -0,0 +1,87 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This describes a plugin with a key-value pair configuration +use std::fmt; + +use serde::Deserialize; +use serde_json::Map; + +#[derive(Debug, PartialEq, Deserialize, Clone)] +pub struct Plugin { + pub name: String, + pub config: Option>, +} + +impl fmt::Display for Plugin { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.name) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_full_deserialization() { + // given + let json = r#"{ + "name": "Plugin", + "config": { + "property1": null, + "property2": true, + "property3": "aBc", + "property4": 42 + } + }"#; + + let mut config = Map::new(); + config.insert("property1".to_string(), serde_json::Value::Null); + config.insert("property2".to_string(), serde_json::Value::Bool(true)); + config.insert( + "property3".to_string(), + serde_json::Value::String("aBc".into()), + ); + config.insert( + "property4".to_string(), + serde_json::Value::Number(42.into()), + ); + + let data = Plugin { + name: "Plugin".into(), + config: Some(config), + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } + + #[test] + fn test_minimal_deserialization() { + // given + let json = r#"{ + "name": "Plugin" + }"#; + + let data = Plugin { + name: "Plugin".into(), + config: None, + }; + + assert_eq!(data, serde_json::from_str(json).unwrap()); + } +} diff --git a/crates/common/src/database/details.rs b/crates/common/src/database/details.rs new file mode 100644 index 0000000..a7b713e --- /dev/null +++ b/crates/common/src/database/details.rs @@ -0,0 +1,45 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use uuid::Uuid; + +pub struct Details { + pub uuid: &'static Uuid, + pub camera_manufacturer: &'static str, + pub camera_model: &'static str, + pub camera_serial: &'static str, + pub lens_model: &'static str, + pub lens_serial: &'static str, + pub orientation: &'static str, + pub compression: &'static str, + pub resolution_x: &'static str, + pub resolution_y: &'static str, + pub resolution_unit: &'static str, + pub exposure_time: &'static str, + pub exposure_mode: &'static str, + pub exposure_program: &'static str, + pub exposure_bias: &'static str, + pub aperture: &'static f32, + pub iso: &'static i32, + pub color_space: &'static str, + pub pixel_x: &'static i64, + pub pixel_y: &'static i64, + pub user_comment: &'static str, + pub white_balance: &'static str, + pub flash: bool, + pub exif_version: &'static f32, +} diff --git a/crates/common/src/database/location.rs b/crates/common/src/database/location.rs new file mode 100644 index 0000000..bb928cc --- /dev/null +++ b/crates/common/src/database/location.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use uuid::Uuid; + +pub struct Location { + pub uuid: &'static Uuid, + pub latitude: &'static f64, + pub longitude: &'static f64, + pub altitude: &'static Option, +} diff --git a/crates/common/src/database/media_item.rs b/crates/common/src/database/media_item.rs new file mode 100644 index 0000000..8c2db07 --- /dev/null +++ b/crates/common/src/database/media_item.rs @@ -0,0 +1,31 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use std::time::Instant; + +use super::{details::Details, location::Location, reference::Reference, tag::Tag}; + +pub struct MediaItem { + pub uuid: &'static str, + pub name: &'static str, + pub added_at: Instant, + pub taken_at: Option, + pub details: Option
, + pub tags: Option>, + pub location: Option, + pub references: Option>, +} diff --git a/crates/common/src/database/mod.rs b/crates/common/src/database/mod.rs new file mode 100644 index 0000000..321db81 --- /dev/null +++ b/crates/common/src/database/mod.rs @@ -0,0 +1,86 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use async_trait::async_trait; +use std::error::Error; +use time::OffsetDateTime; + +use crate::auth::user::User; + +use self::{media_item::MediaItem, reference::Reference}; + +pub mod details; +pub mod location; +pub mod media_item; +pub mod reference; +pub mod tag; +pub mod user; + +#[async_trait] +pub trait Database { + /// Initialize the database and run required migrations + async fn setup(&mut self) -> Result<(), Box>; + + /// List registered user accounts + async fn get_users(&self) -> Result, Box>; + + /// Create a new user account + async fn create_user(&self, user: &User) -> Result<(), Box>; + + /// Get user by user_id + async fn get_user(&self, user_id: &str) -> Result>; + + /// Partial update a single user account + async fn update_email(&self, email: &str, user_id: &str) -> Result<(), Box>; + async fn update_nickname(&self, nickname: &str) -> Result<(), Box>; + async fn update_names( + &self, + firstname: &str, + lastname: &str, + user_id: &str, + ) -> Result<(), Box>; + + async fn disable_user(&self, user_id: &str) -> Result<(), Box>; + async fn enable_user(&self, user_id: &str) -> Result<(), Box>; + + async fn get_media_items(&self, user_id: &str) -> Result, Box>; + async fn create_media_item( + &self, + user_id: &str, + name: &str, + date_taken: OffsetDateTime, + ) -> Result>; + async fn get_media_item(&self, media_id: &str) -> Result>; + async fn add_reference( + &self, + user_id: &str, + media_id: &str, + reference: &Reference, + ) -> Result>; + + async fn update_reference( + &self, + reference_id: &str, + reference: &Reference, + ) -> Result<(), Box>; + + async fn remove_reference( + &self, + media_id: &str, + reference_id: &str, + ) -> Result<(), Box>; +} diff --git a/crates/common/src/database/reference.rs b/crates/common/src/database/reference.rs new file mode 100644 index 0000000..988dac3 --- /dev/null +++ b/crates/common/src/database/reference.rs @@ -0,0 +1,28 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use time::OffsetDateTime; + +pub struct Reference { + pub uuid: String, + pub filepath: String, + pub filename: String, + pub size: u64, + pub description: &'static str, + pub last_modified: OffsetDateTime, + pub is_missing: bool, +} diff --git a/crates/common/src/database/tag.rs b/crates/common/src/database/tag.rs new file mode 100644 index 0000000..6f9605b --- /dev/null +++ b/crates/common/src/database/tag.rs @@ -0,0 +1,24 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use uuid::Uuid; + +pub struct Tag { + pub uuid: &'static Uuid, + pub tag: &'static str, + pub origin: &'static str, +} diff --git a/crates/common/src/database/user.rs b/crates/common/src/database/user.rs new file mode 100644 index 0000000..8c2db07 --- /dev/null +++ b/crates/common/src/database/user.rs @@ -0,0 +1,31 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use std::time::Instant; + +use super::{details::Details, location::Location, reference::Reference, tag::Tag}; + +pub struct MediaItem { + pub uuid: &'static str, + pub name: &'static str, + pub added_at: Instant, + pub taken_at: Option, + pub details: Option
, + pub tags: Option>, + pub location: Option, + pub references: Option>, +} diff --git a/crates/common/src/http/extractors/mod.rs b/crates/common/src/http/extractors/mod.rs new file mode 100644 index 0000000..e2ef6fc --- /dev/null +++ b/crates/common/src/http/extractors/mod.rs @@ -0,0 +1,18 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +pub mod optuser; +pub mod user; diff --git a/crates/common/src/http/extractors/optuser.rs b/crates/common/src/http/extractors/optuser.rs new file mode 100644 index 0000000..64a75c1 --- /dev/null +++ b/crates/common/src/http/extractors/optuser.rs @@ -0,0 +1,48 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This extractor checks if an `Authorization` is header and contains a valid JWT token. +//! Otherwise it will respond `Some(None)` to indicate an unauthorized user or a visiter without an account at all. +//! +use crate::auth::user::User; +use async_trait::async_trait; +use axum::extract::FromRequestParts; +use http::request::Parts; + +pub struct OptionalUser(pub Option); + +#[async_trait] +impl FromRequestParts for OptionalUser +where + S: Send + Sync, +{ + type Rejection = String; + + #[allow(clippy::bind_instead_of_map)] + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { + parts + .headers + .get("Authorization") + .and_then(|header| { + let _auth_token = header.to_str().ok(); + + // TODO: verify auth token + Some(Self(Some(User::new("info@photos.network".to_string())))) + }) + .ok_or("".to_string()) + } +} diff --git a/crates/common/src/http/extractors/user.rs b/crates/common/src/http/extractors/user.rs new file mode 100644 index 0000000..2803b6f --- /dev/null +++ b/crates/common/src/http/extractors/user.rs @@ -0,0 +1,50 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This extractor requires an `Authorization` header present with a valid JWT token. +//! Otherwise it will respond with `StatusCode::UNAUTHORIZED` +//! +use async_trait::async_trait; +use axum::extract::FromRequestParts; +use axum::http::StatusCode; +use http::request::Parts; + +use crate::auth::user::User; + +#[async_trait] +impl FromRequestParts for User +where + S: Send + Sync, +{ + type Rejection = (StatusCode, &'static str); + + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { + let _auth_token = parts + .headers + .get("Authorization") + .and_then(|header| header.to_str().ok()) + .ok_or((StatusCode::UNAUTHORIZED, "Unauthorized"))?; + + // TODO: get user for Authtoken + Ok(User::new("info@photos.network".to_string())) + // TODO: verify Token + // verify_auth_token(auth_header) + // .await + // .map_err(|_| (StatusCode::UNAUTHORIZED, "Unauthorized")) + //Err((StatusCode::UNAUTHORIZED, "Unauthorized")) + } +} diff --git a/crates/common/src/http/mod.rs b/crates/common/src/http/mod.rs new file mode 100644 index 0000000..c343108 --- /dev/null +++ b/crates/common/src/http/mod.rs @@ -0,0 +1,17 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +pub mod extractors; diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs new file mode 100644 index 0000000..74b59d3 --- /dev/null +++ b/crates/common/src/lib.rs @@ -0,0 +1,57 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate offers shared data models for [Photos.network](https://photos.network) core application. +//! + +use std::collections::HashMap; + +use axum::Router; +use config::configuration::Configuration; +use database::Database; +use photos_network_plugin::{PluginFactoryRef, PluginId}; + +pub mod auth; +pub mod config; +pub mod database; +pub mod http; +pub mod model { + pub mod sensitive; +} + +/// Aggregates the applications configuration, its loaded plugins and the router for all REST APIs +#[derive(Clone)] +pub struct ApplicationState { + pub config: Configuration, + pub plugins: HashMap, + pub router: Option, + pub database: D, +} + +impl ApplicationState +where + D: Database, +{ + pub fn new(config: Configuration, database: D) -> Self { + Self { + config, + plugins: HashMap::new(), + router: None, + database, + } + } +} diff --git a/crates/common/src/model/sensitive.rs b/crates/common/src/model/sensitive.rs new file mode 100644 index 0000000..5500b3b --- /dev/null +++ b/crates/common/src/model/sensitive.rs @@ -0,0 +1,158 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Sensitive. +//! +//! Provides an abstraction over a vlue for sensitive data like passwords. +//! It is not printing its value to logs or tracing +//! +use serde::{Deserialize, Serialize}; +use std::{ + borrow::Borrow, + ops::{Deref, DerefMut}, +}; +#[cfg(feature = "full")] +use ts_rs::TS; + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Default)] +#[serde(transparent)] +pub struct Sensitive(T); + +impl Sensitive { + pub fn new(item: T) -> Self { + Sensitive(item) + } + pub fn into_inner(self) -> T { + self.0 + } +} + +// overrides the standard debug programmer-facing representation to prevent the value from leaking. +impl std::fmt::Debug for Sensitive { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("[********]").finish() + } +} + +impl AsRef for Sensitive { + fn as_ref(&self) -> &T { + &self.0 + } +} + +impl AsRef for Sensitive { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl AsRef<[u8]> for Sensitive { + fn as_ref(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl AsRef<[u8]> for Sensitive> { + fn as_ref(&self) -> &[u8] { + self.0.as_ref() + } +} + +impl AsMut for Sensitive { + fn as_mut(&mut self) -> &mut T { + &mut self.0 + } +} + +impl AsMut for Sensitive { + fn as_mut(&mut self) -> &mut str { + &mut self.0 + } +} + +impl Deref for Sensitive { + type Target = str; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Sensitive { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl From for Sensitive { + fn from(t: T) -> Self { + Sensitive(t) + } +} + +impl From<&str> for Sensitive { + fn from(s: &str) -> Self { + Sensitive(s.into()) + } +} + +impl Borrow for Sensitive { + fn borrow(&self) -> &T { + &self.0 + } +} + +impl Borrow for Sensitive { + fn borrow(&self) -> &str { + &self.0 + } +} + +#[cfg(feature = "full")] +impl TS for Sensitive { + fn name() -> String { + "string".to_string() + } + fn name_with_type_args(_args: Vec) -> String { + "string".to_string() + } + fn dependencies() -> Vec { + Vec::new() + } + fn transparent() -> bool { + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_representation_should_replace_value() { + let sensitive_secret: Sensitive = "secret".into(); + + assert_eq!("[********]", format!("{:?}", sensitive_secret)) + } + + #[test] + fn convert_string_into_should_succeed() { + let sensitive_secret: Sensitive = "secret".into(); + + assert_eq!("secret", sensitive_secret.0) + } +} diff --git a/crates/database/.env b/crates/database/.env new file mode 100644 index 0000000..a148121 --- /dev/null +++ b/crates/database/.env @@ -0,0 +1 @@ +DATABASE_URL=sqlite://data/core.sqlite3 diff --git a/crates/database/Cargo.toml b/crates/database/Cargo.toml new file mode 100644 index 0000000..b38d323 --- /dev/null +++ b/crates/database/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "database" +version.workspace = true +authors.workspace = true +description.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "database" +path = "src/lib.rs" +doctest = false + +[dependencies] +common.workspace = true +async-trait.workspace = true +tracing.workspace = true +uuid.workspace = true +tokio.workspace = true +sqlx = { workspace = true, features = ["runtime-tokio", "tls-native-tls", "postgres", "mysql", "sqlite", "any", "macros", "migrate", "time" ] } + +[dev-dependencies] +pretty_assertions.workspace = true +testdir.workspace = true +time.workspace = true diff --git a/crates/database/README.md b/crates/database/README.md new file mode 100644 index 0000000..979d716 --- /dev/null +++ b/crates/database/README.md @@ -0,0 +1,11 @@ +# database + +This crate provides an database abstraction used within [Photos.network](https://photos.network). + + +We're using polymorphism via trait objects so users can choose between differen database implementations like `PostgreSQL`, `MySQL` or `SQLite`. +The [trait object](lib.rs) defines shared behaviour and is implemented multiple times for each database type. + +Another solution would be to use a generic type, since we only need a single instance for now, it would be totally sufficient. +It might be possible that a user wants to migrate from a `SQLite` to a `PostgreSQL` in the future, than it would be a hard limitation to use only +a single generic database. diff --git a/crates/database/migrations/0001_initial.sql b/crates/database/migrations/0001_initial.sql new file mode 100644 index 0000000..e489500 --- /dev/null +++ b/crates/database/migrations/0001_initial.sql @@ -0,0 +1,130 @@ +CREATE TABLE IF NOT EXISTS users ( + --auto generated + uuid VARCHAR NOT NULL, + email VARCHAR UNIQUE, + password VARCHAR, + lastname VARCHAR, + firstname VARCHAR, + displayname VARCHAR, + --indicates if user is not able to login + is_locked BOOLEAN DEFAULT FALSE, + created_at TIMESTAMPTZ DEFAULT NULL, + updated_at TIMESTAMPTZ DEFAULT NULL, + last_login_at TIMESTAMPTZ DEFAULT NULL, + PRIMARY KEY (uuid) +); + +CREATE TABLE IF NOT EXISTS media ( + uuid VARCHAR NOT NULL, + -- reference to `users` + owner VARCHAR NOT NULL, + name VARCHAR, + -- show/hide by default regarding user settings + is_sensitive BOOLEAN DEFAULT FALSE, + -- added to photos.network + added_at TIMESTAMPTZ DEFAULT NULL, + -- captured timestamp + taken_at TIMESTAMPTZ DEFAULT NULL, + PRIMARY KEY (uuid), + FOREIGN KEY(owner) REFERENCES users (uuid) +); + +CREATE TABLE IF NOT EXISTS reference ( + uuid VARCHAR NOT NULL, + -- reference to `media` + media VARCHAR NOT NULL, + -- reference to `users` + owner VARCHAR NOT NULL, + -- ./data/files/[media.owner.uuid]/[media.date_taken.year]/[filename] + filepath VARCHAR NOT NULL, + -- original filename e.g. DSC1234.NEF + filename VARCHAR NOT NULL, + -- file size in bytes + size INTEGER NOT NULL, + description VARCHAR DEFAULT NULL, + -- xmp, metadata + last_modified TIMESTAMPTZ DEFAULT NULL, + PRIMARY KEY (uuid), + FOREIGN KEY(media) REFERENCES media (uuid) + FOREIGN KEY(owner) REFERENCES users (uuid) +); +CREATE TABLE IF NOT EXISTS details ( + uuid VARCHAR NOT NULL, + -- reference to `reference` + reference VARCHAR DEFAULT NULL, + -- NIKON + camera_manufacturer VARCHAR DEFAULT NULL, + -- Z7 + camera_model VARCHAR DEFAULT NULL, + -- 6014533 + camera_serial VARCHAR DEFAULT NULL, + -- NIKKOR Z 35mm f/1.8 S + lens_model VARCHAR DEFAULT NULL, + -- 20028476 + lens_serial VARCHAR DEFAULT NULL, + -- https://jdhao.github.io/2019/07/31/image_rotation_exif_info/ + orientation VARCHAR DEFAULT NULL, + -- JPEG compression + compression VARCHAR DEFAULT NULL, + -- 72.0 + resolution_x FLOAT DEFAULT NULL, + -- 72.0 + resolution_y FLOAT DEFAULT NULL, + -- Inch + resolution_unit VARCHAR DEFAULT NULL, + -- 1/400 s + exposure_time FLOAT DEFAULT NULL, + -- Auto exposure + exposure_mode VARCHAR DEFAULT NULL, + -- Aperture priority + exposure_program VARCHAR DEFAULT NULL, + -- 0 EV + exposure_bias VARCHAR DEFAULT NULL, + -- 1.8 + aperture FLOAT DEFAULT NULL, + focal_length VARCHAR DEFAULT NULL, + iso INTEGER NOT NULL, + -- sRGB + color_space VARCHAR DEFAULT NULL, + -- 8.256 pixel + pixel_x INTEGER NOT NULL, + -- 5.504 pixel + pixel_y INTEGER NOT NULL, + -- copyright info + user_comment VARCHAR DEFAULT NULL, + -- Auto white balance + white_balance VARCHAR DEFAULT NULL, + -- 0 = no flash + flash BOOL DEFAULT NULL, + -- Exif version 2.1 + exif_version FLOAT DEFAULT NULL, + FOREIGN KEY(reference) REFERENCES reference (uuid) +); + +CREATE TABLE IF NOT EXISTS tags ( + uuid VARCHAR NOT NULL, + -- language unaware string like "landscape" + tag VARCHAR NOT NULL, + -- reference to `media` + media VARCHAR NOT NULL, + -- plugin name or `USER` where the tag comes from + origin VARCHAR DEFAULT NULL, + PRIMARY KEY (uuid), + FOREIGN KEY(media) REFERENCES media (uuid) +); + +CREATE TABLE IF NOT EXISTS locations ( + uuid VARCHAR NOT NULL, + -- reference to `media` + media VARCHAR NOT NULL, + -- float gives a precision of ~1,7m + -- see https://stackoverflow.com/questions/159255/what-is-the-ideal-data-type-to-use-when-storing-latitude-longitude-in-a-mysql + -- 48.13750 + latitude FLOAT NOT NULL, + -- 11.57586 + longitude FLOAT NOT NULL, + -- 520 m + altitude FLOAT DEFAULT NULL, + PRIMARY KEY (uuid), + FOREIGN KEY(media) REFERENCES media (uuid) +); diff --git a/crates/database/src/lib.rs b/crates/database/src/lib.rs new file mode 100644 index 0000000..fc3f629 --- /dev/null +++ b/crates/database/src/lib.rs @@ -0,0 +1,3 @@ +//pub mod postgres; +pub mod postgres; +pub mod sqlite; diff --git a/crates/database/src/postgres.rs b/crates/database/src/postgres.rs new file mode 100644 index 0000000..c127a7f --- /dev/null +++ b/crates/database/src/postgres.rs @@ -0,0 +1,194 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate offers a database abstraction for [Photos.network](https://photos.network) core application. +//! +use async_trait::async_trait; +use common::auth::user::User; +use common::database::media_item::MediaItem; +use common::database::reference::Reference; +use common::database::Database; +use sqlx::types::time::OffsetDateTime; +use sqlx::PgPool; +use sqlx::Row; +use std::error::Error; +use tracing::info; +use uuid::Uuid; + +#[derive(Clone)] +pub struct PostgresDatabase { + pub pool: PgPool, +} + +impl PostgresDatabase { + pub async fn new(db_url: &str) -> Self { + let pool = PgPool::connect(db_url).await.unwrap(); + + PostgresDatabase { pool } + } +} + +#[async_trait] +impl Database for PostgresDatabase { + async fn setup(&mut self) -> Result<(), Box> { + // run migrations from `migrations` directory + sqlx::migrate!("./migrations").run(&self.pool).await?; + + Ok(()) + } + + async fn get_users(&self) -> Result, Box> { + let query = "SELECT uuid, email, password, lastname, firstname FROM users"; + + let res = sqlx::query(query); + + let rows = res.fetch_all(&self.pool).await?; + + let users = rows + .iter() + .map(|row| User { + uuid: row.get("uuid"), + email: row.get("email"), + password: row.get("password"), + lastname: row.get("lastname"), + firstname: row.get("firstname"), + is_locked: false, + created_at: OffsetDateTime::now_utc(), + updated_at: None, + last_login: None, + }) + .collect(); + + Ok(users) + } + + async fn create_user(&self, user: &User) -> Result<(), Box> { + let query = "INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)"; + let id = Uuid::new_v4().hyphenated().to_string(); + info!("create new user with id `{}`.", id); + sqlx::query(query) + .bind(id) + .bind(&user.email) + .bind(&user.password) + .bind(&user.lastname) + .bind(&user.firstname) + .execute(&self.pool) + .await?; + + Ok(()) + } + + async fn get_user(&self, _user_id: &str) -> Result> { + Err("Not implemented".into()) + } + + async fn update_email(&self, email: &str, user_id: &str) -> Result<(), Box> { + let query = "UPDATE users SET email = $1 WHERE uuid = $2"; + + sqlx::query(query) + .bind(email) + .bind(user_id) + .execute(&self.pool) + .await?; + + Ok(()) + } + + async fn update_nickname(&self, _nickname: &str) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn update_names( + &self, + _firstname: &str, + _lastname: &str, + _user_id: &str, + ) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn disable_user(&self, _user_id: &str) -> Result<(), Box> { + Err("Not implemented".into()) + } + async fn enable_user(&self, _user_id: &str) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn get_media_items(&self, _user_id: &str) -> Result, Box> { + Err("Not implemented".into()) + } + + /// Creates a new media item if it doesn't exist and returns the media_id + async fn create_media_item( + &self, + user_id: &str, + name: &str, + date_taken: OffsetDateTime, + ) -> Result> { + let query = "SELECT COUNT(*) FROM media WHERE owner is $1 and taken_at like $2"; + let res = sqlx::query(query).bind(user_id).bind(date_taken); + let rows = res.fetch_all(&self.pool).await?; + + if rows.len() > 1 { + // TODO: return media item id for existing item + // rows.first() + } else { + let query = "INSERT INTO media (uuid, owner, name, is_sensitive, added_at, taken_at) VALUES ($1, $2, $3, $4, $5, $6)"; + let id = Uuid::new_v4().hyphenated().to_string(); + info!("create new media item with id `{}`.", id); + + sqlx::query(query) + .bind(id.clone()) + .bind(&user_id) + .bind(&name) + .bind(false) + .bind(OffsetDateTime::now_utc()) + .bind(date_taken) + .execute(&self.pool) + .await?; + } + + Ok("".to_string()) + } + async fn get_media_item(&self, _media_id: &str) -> Result> { + Err("Not implemented".into()) + } + async fn add_reference( + &self, + _user_id: &str, + _media_id: &str, + _reference: &Reference, + ) -> Result> { + Err("Not implemented".into()) + } + + async fn update_reference( + &self, + _reference_id: &str, + _reference: &Reference, + ) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn remove_reference( + &self, + _media_id: &str, + _reference_id: &str, + ) -> Result<(), Box> { + Err("Not implemented".into()) + } +} diff --git a/crates/database/src/sqlite.rs b/crates/database/src/sqlite.rs new file mode 100644 index 0000000..78975c6 --- /dev/null +++ b/crates/database/src/sqlite.rs @@ -0,0 +1,551 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate offers a database abstraction for [Photos.network](https://photos.network) core application. +//! +use async_trait::async_trait; +use common::auth::user::User; +use common::database::media_item::MediaItem; +use common::database::reference::Reference; +use common::database::Database; +use sqlx::sqlite::SqliteQueryResult; +use sqlx::types::time::OffsetDateTime; +use sqlx::Row; +use sqlx::SqlitePool; +use std::error::Error; +use std::i64; +use tracing::error; +use tracing::info; +use uuid::Uuid; + +#[derive(Clone)] +pub struct SqliteDatabase { + pub pool: SqlitePool, +} + +impl SqliteDatabase { + pub async fn new(db_url: &str) -> Self { + let pool = SqlitePool::connect(db_url).await.unwrap(); + + SqliteDatabase { pool } + } +} + +#[async_trait] +impl Database for SqliteDatabase { + async fn setup(&mut self) -> Result<(), Box> { + // run migrations from `migrations` directory + sqlx::migrate!("./migrations").run(&self.pool).await?; + + Ok(()) + } + + async fn get_users(&self) -> Result, Box> { + let query = "SELECT uuid, email, password, lastname, firstname FROM users"; + + let res = sqlx::query(query); + + let rows = res.fetch_all(&self.pool).await?; + + let users = rows + .iter() + .map(|row| User { + uuid: row.get("uuid"), + email: row.get("email"), + password: row.get("password"), + lastname: row.get("lastname"), + firstname: row.get("firstname"), + is_locked: false, + created_at: OffsetDateTime::now_utc(), + updated_at: None, + last_login: None, + }) + .collect(); + + Ok(users) + } + + async fn create_user(&self, user: &User) -> Result<(), Box> { + let query = "INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)"; + let id = Uuid::new_v4().hyphenated().to_string(); + info!("create new user with id `{}`.", id); + sqlx::query(query) + .bind(id) + .bind(&user.email) + .bind(&user.password) + .bind(&user.lastname) + .bind(&user.firstname) + .execute(&self.pool) + .await?; + + Ok(()) + } + + async fn get_user(&self, _user_id: &str) -> Result> { + Err("Not implemented".into()) + } + + async fn update_email(&self, email: &str, user_id: &str) -> Result<(), Box> { + let query = "UPDATE users SET email = $1 WHERE uuid = $2"; + + sqlx::query(query) + .bind(email) + .bind(user_id) + .execute(&self.pool) + .await?; + + Ok(()) + } + + async fn update_nickname(&self, _nickname: &str) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn update_names( + &self, + _firstname: &str, + _lastname: &str, + _user_id: &str, + ) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn disable_user(&self, _user_id: &str) -> Result<(), Box> { + Err("Not implemented".into()) + } + async fn enable_user(&self, _user_id: &str) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn get_media_items(&self, _user_id: &str) -> Result, Box> { + Err("Not implemented".into()) + } + async fn create_media_item( + &self, + user_id: &str, + name: &str, + date_taken: OffsetDateTime, + ) -> Result> { + struct Item { + uuid: String, + } + + let rows: Option = sqlx::query_as!( + Item, + "SELECT uuid FROM media WHERE owner is $1 AND name is $2 AND taken_at is $3", + user_id, + name, + date_taken, + ) + .fetch_optional(&self.pool) + .await?; + + return match rows { + Some(r) => { + info!("Found media item with same 'name' and 'taken_at' for owner."); + + Ok(r.uuid) + } + _ => { + let query = "INSERT INTO media (uuid, owner, name, is_sensitive, added_at, taken_at) VALUES ($1, $2, $3, $4, $5, $6)"; + let id = Uuid::new_v4().hyphenated().to_string(); + + let db_result = sqlx::query(query) + .bind(id.clone()) + .bind(&user_id.to_string()) + .bind(&name.to_string()) + .bind(false) + .bind(OffsetDateTime::now_utc()) + .bind(date_taken) + .execute(&self.pool) + .await; + + match db_result { + Ok(_) => { + info!("New media item created with id {}.", id) + } + Err(e) => { + error!("Could not create new media item in database! {}", e); + } + } + + Ok(id) + } + }; + } + + async fn get_media_item(&self, _media_id: &str) -> Result> { + Err("Not implemented".into()) + } + + async fn add_reference( + &self, + user_id: &str, + media_id: &str, + reference: &Reference, + ) -> Result> { + let query = "INSERT INTO reference (uuid, media, owner, filepath, filename, size) VALUES ($1, $2, $3, $4, $5, $6)"; + let id = Uuid::new_v4().hyphenated().to_string(); + let _res: SqliteQueryResult = sqlx::query(query) + .bind(id.clone()) + .bind(&media_id) + .bind(&user_id) + .bind(&reference.filepath) + .bind(&reference.filename) + .bind(i64::try_from(reference.size).unwrap()) + .execute(&self.pool) + .await?; + + Ok(id) + } + + async fn update_reference( + &self, + _reference_id: &str, + _reference: &Reference, + ) -> Result<(), Box> { + Err("Not implemented".into()) + } + + async fn remove_reference( + &self, + _media_id: &str, + _reference_id: &str, + ) -> Result<(), Box> { + Err("Not implemented".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + use testdir::testdir; + use time::format_description::well_known::Rfc3339; + + #[sqlx::test] + async fn create_user_should_succeed(pool: SqlitePool) -> sqlx::Result<()> { + // given + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/create_user_should_succeed.sqlite", + ) + .await; + + // when + for i in 0..3 { + let user = User { + uuid: Uuid::new_v4().hyphenated().to_string(), + email: format!("test_{}@photos.network", i), + password: Some("unsecure".into()), + lastname: Some("Stuermer".into()), + firstname: Some("Benjamin".into()), + is_locked: false, + created_at: OffsetDateTime::now_utc(), + updated_at: None, + last_login: None, + }; + + // when + let _ = db.create_user(&user).await; + } + + // then + let count = sqlx::query("SELECT COUNT(*) AS 'count!' FROM users") + .fetch_one(&pool) + .await?; + assert_eq!(count.get::("count!"), 3); + + Ok(()) + } + + #[sqlx::test] + async fn create_already_existing_user_should_fail(pool: SqlitePool) -> sqlx::Result<()> { + // given + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/create_already_existing_user_should_fail.sqlite", + ) + .await; + + // when + let uuid = uuid::Uuid::new_v4().hyphenated().to_string(); + let user = User { + uuid, + email: "info@photos.network".into(), + password: Some("unsecure".into()), + lastname: Some("Stuermer".into()), + firstname: Some("Benjamin".into()), + is_locked: false, + created_at: OffsetDateTime::now_utc(), + updated_at: None, + last_login: None, + }; + + // then + let result1 = db.create_user(&user.clone()).await; + assert!(result1.is_ok()); + + let result2 = db.create_user(&user.clone()).await; + assert!(result2.is_err()); + + let count = sqlx::query("SELECT COUNT(*) AS 'count!' FROM users") + .fetch_one(&pool) + .await?; + assert_eq!(count.get::("count!"), 1); + + Ok(()) + } + + #[sqlx::test] + async fn update_email_should_succeed(pool: SqlitePool) -> sqlx::Result<()> { + // given + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind("570DC079-664A-4496-BAA3-668C445A447") + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/update_email_should_succeed.sqlite", + ) + .await; + + // when + let result = db + .update_email( + "security@photos.network".into(), + "570DC079-664A-4496-BAA3-668C445A447".into(), + ) + .await; + + // then + assert!(result.is_ok()); + let count = sqlx::query("SELECT email FROM users LIMIT 1") + .fetch_one(&pool) + .await?; + assert_eq!(count.get::("email"), "security@photos.network"); + + Ok(()) + } + + #[sqlx::test] + async fn update_email_to_existing_should_fail(pool: SqlitePool) -> sqlx::Result<()> { + // given + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind("570DC079-664A-4496-BAA3-668C445A447") + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind("0D341AD3-D38F-455F-8411-E25186665FC5") + .bind("security@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/update_email_to_existing_should_fail.sqlite", + ) + .await; + + // when + let result = db + .update_email( + "security@photos.network".into(), + "570DC079-664A-4496-BAA3-668C445A447".into(), + ) + .await; + + // then + assert!(result.is_err()); + + let rows = sqlx::query("SELECT email FROM users") + .fetch_all(&pool) + .await?; + assert_eq!(rows[0].get::("email"), "info@photos.network"); + assert_eq!(rows[1].get::("email"), "security@photos.network"); + + Ok(()) + } + + #[sqlx::test] + async fn get_users_should_succeed(pool: SqlitePool) -> sqlx::Result<()> { + // given + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind("570DC079-664A-4496-BAA3-668C445A447") + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/get_users_should_succeed.sqlite", + ) + .await; + + // when + let users = db.get_users().await.unwrap(); + + // then + assert_eq!(users.clone().len(), 1); + assert_eq!( + users.get(0).unwrap().uuid, + "570DC079-664A-4496-BAA3-668C445A447" + ); + + Ok(()) + } + + //noinspection DuplicatedCode + #[sqlx::test] + async fn create_media_item_should_succeed(pool: SqlitePool) -> sqlx::Result<()> { + // given + let user_id = "570DC079-664A-4496-BAA3-668C445A447"; + // create fake user - used as FOREIGN KEY in media + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind(user_id.clone()) + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/create_media_item_should_succeed.sqlite", + ) + .await; + + let name = "DSC_1234"; + let date_taken = OffsetDateTime::now_utc(); + + // when + let media_item_result = db + .create_media_item(user_id.clone(), name, date_taken) + .await; + + // then + assert!(media_item_result.is_ok()); + + Ok(()) + } + + //noinspection DuplicatedCode + #[sqlx::test] + async fn create_media_item_should_return_existing_uuid(pool: SqlitePool) -> sqlx::Result<()> { + // given + + let user_id = "570DC079-664A-4496-BAA3-668C445A447"; + let media_id = "ef9ac799-02f3-4b3f-9d96-7576be0434e6"; + let added_at = OffsetDateTime::parse("2023-02-03T13:37:01.234567Z", &Rfc3339).unwrap(); + let taken_at = OffsetDateTime::parse("2023-01-01T13:37:01.234567Z", &Rfc3339).unwrap(); + let name = "DSC_1234"; + + // create fake user - used as FOREIGN KEY in media + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind(user_id.clone()) + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + + sqlx::query("INSERT INTO media (uuid, owner, name, is_sensitive, added_at, taken_at) VALUES ($1, $2, $3, $4, $5, $6)") + .bind(media_id.clone()) + .bind(user_id.clone()) + .bind("DSC_1234") + .bind(false) + .bind(added_at) + .bind(taken_at) + .execute(&pool).await?; + + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/create_media_item_should_return_existing_uuid.sqlite", + ) + .await; + + // when + let media_item_result = db.create_media_item(user_id.clone(), name, taken_at).await; + + // then + assert!(media_item_result.is_ok()); + assert_eq!(media_item_result.ok().unwrap(), media_id.to_string()); + + Ok(()) + } + + //noinspection DuplicatedCode + #[sqlx::test] + async fn add_reference_should_succeed(pool: SqlitePool) -> sqlx::Result<()> { + // given + let user_id = "570DC079-664A-4496-BAA3-668C445A447"; + let media_id = "ef9ac799-02f3-4b3f-9d96-7576be0434e6"; + let reference_id = "ef9ac799-02f3-4b3f-9d96-7576be0434e6"; + let added_at = OffsetDateTime::parse("2023-02-03T13:37:01.234567Z", &Rfc3339).unwrap(); + let taken_at = OffsetDateTime::parse("2023-01-01T13:37:01.234567Z", &Rfc3339).unwrap(); + // create fake user - used as FOREIGN KEY in reference + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind(user_id.clone()) + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + // create fake media item - used as FOREIGN KEY in reference + sqlx::query("INSERT INTO media (uuid, owner, name, is_sensitive, added_at, taken_at) VALUES ($1, $2, $3, $4, $5, $6)") + .bind(media_id.clone()) + .bind(user_id.clone()) + .bind("DSC_1234") + .bind(false) + .bind(added_at) + .bind(taken_at) + .execute(&pool).await?; + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/database/sqlite/tests/add_reference_should_succeed.sqlite", + ) + .await; + + let filename = "DSC_1234.jpg"; + let dir: PathBuf = testdir!(); + let path = dir.join(filename); + let filepath = path.clone().to_str().unwrap().to_string(); + std::fs::write(&path, "fake image data").ok(); + let metadata = std::fs::metadata(path.clone()).unwrap(); + + let reference = Reference { + uuid: reference_id.to_string(), + filepath, + filename: filename.to_string(), + size: metadata.len(), + description: "", + last_modified: OffsetDateTime::parse("2023-02-03T13:37:01.234567Z", &Rfc3339).unwrap(), + is_missing: false, + }; + + // when + let add_reference_result = db + .add_reference(user_id.clone(), media_id.clone(), &reference) + .await; + + // then + assert!(add_reference_result.is_ok()); + + Ok(()) + } +} diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml new file mode 100644 index 0000000..55b58aa --- /dev/null +++ b/crates/media/Cargo.toml @@ -0,0 +1,50 @@ +[package] +name = "media" +description = "Manages all media items in the database and on filesystem." +version.workspace = true +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "media" +path = "src/lib.rs" +doctest = false + +[dependencies] +common.workspace = true +database.workspace = true +# database = { path = "../database" } + +time.workspace = true + +tracing.workspace = true +tokio = { workspace = true, features = ["full"] } + +# serialization +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true + +# Router +axum = { workspace = true, features = ["multipart"] } +hyper = { workspace = true, features = ["full"] } +tower-http.workspace = true +mime.workspace = true + +# persistency +uuid = { workspace = true, features = ["serde"] } +sqlx.workspace = true +rand.workspace = true +tempfile.workspace = true + + +[dev-dependencies] +# testing +mockall.workspace = true +rstest.workspace = true +tower = { workspace = true, features = ["util"] } +testdir.workspace = true diff --git a/crates/media/README.md b/crates/media/README.md new file mode 100644 index 0000000..34cd85b --- /dev/null +++ b/crates/media/README.md @@ -0,0 +1,6 @@ +# media + +This crate handles all media items like photos or albums for [Photos.network](https://photos.network). + +Persisting the metadata in a database with [SQLx](https://crates.io/crates/sqlx) and accessing the files via [filesystem](https://crates.io/crates/filesystem). + diff --git a/crates/media/src/api/mod.rs b/crates/media/src/api/mod.rs new file mode 100644 index 0000000..e62bb99 --- /dev/null +++ b/crates/media/src/api/mod.rs @@ -0,0 +1,2 @@ +pub mod router; +pub(crate) mod routes; diff --git a/crates/media/src/api/router.rs b/crates/media/src/api/router.rs new file mode 100644 index 0000000..fa53a32 --- /dev/null +++ b/crates/media/src/api/router.rs @@ -0,0 +1,248 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use super::routes::delete_media_id::delete_media_id; +use super::routes::get_albums::get_albums; +use super::routes::get_albums_id::get_albums_id; +use super::routes::get_media::get_media; +use super::routes::get_media_id::get_media_id; +use super::routes::patch_albums_id::patch_albums_id; +use super::routes::patch_albums_id_share::patch_albums_id_share; +use super::routes::patch_albums_id_unshare::patch_albums_id_unshare; +use super::routes::patch_media_id::patch_media_id; +use super::routes::post_albums::post_albums; +use super::routes::post_media::post_media; +use super::routes::post_media_id::post_media_id; +use crate::repository::{MediaRepository, MediaRepositoryState}; +use axum::routing::{delete, get, patch, post}; +use axum::Router; +use common::ApplicationState; +use database::sqlite::SqliteDatabase; +use std::sync::Arc; + +pub struct MediaApi {} + +impl MediaApi { + pub async fn routes(state: ApplicationState) -> Router + where + S: Send + Sync + Clone, + { + let media_repository: MediaRepository = + MediaRepository::new(state.database.clone(), state.config.clone()).await; + let repository_state: MediaRepositoryState = Arc::new(media_repository); + + Router::new() + // Returns a list of owned media items for current user + // 200 Ok + // 401 Unauthorized - Requesting user is unauthenticated + // 403 Forbidden + // 500 Internal Server Error + .route("/media", get(get_media)) + // Creates a new media item to aggregate related files for current user + // 201 - Created + // 400 Bad Request - The request body was malformed or a field violated its constraints. + // 401 Unauthorized - You are unauthenticated + // 403 Forbidden - You are authenticated but have no permission to manage the target user. + // 500 Internal Server Error + .route("/media", post(post_media)) + // Returns a specific owned or shared media item for current user + // 200 - Ok + // 400 Bad Request - The request body was malformed or a field violated its constraints. + // 401 Unauthorized - You are unauthenticated + // 403 Forbidden - You are authenticated but have no permission to manage the target user. + // 500 Internal Server Error + .route("/media/:media_id", get(get_media_id)) + // Add files for a specific media item + .route("/media/:media_id", post(post_media_id)) + // Updates fields from a specific media item for current user + .route("/media/:media_id", patch(patch_media_id)) + // Deletes the given item owned by the user + .route("/media/:media_id", delete(delete_media_id)) + // list owned and shared albums + .route("/albums", get(get_albums)) + // create new album + .route("/albums", post(post_albums)) + // get metadata of a specific owned or shared album + .route("/albums/:entity_id", get(get_albums_id)) + // updates the given album owned by the user + .route("/albums/:entity_id", patch(patch_albums_id)) + // shares the given album + .route("/albums/:entity_id/share", patch(patch_albums_id_share)) + // unshares the given album + .route("/albums/:entity_id/unshare", patch(patch_albums_id_unshare)) + .layer(tower_http::trace::TraceLayer::new_for_http()) + .with_state(repository_state) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use super::*; + use axum::{ + body::Body, + http::{self, Request, StatusCode}, + }; + use common::config::configuration::Configuration; + use serde_json::json; + use sqlx::SqlitePool; + use tower::ServiceExt; + + #[sqlx::test] + async fn get_media_with_query_success(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + let app = Router::new().nest("/", MediaApi::routes(state).await); + + // when + let response = app + .oneshot( + Request::builder() + .uri("/media?limit=100000&offset=1") + .method("GET") + .header("Authorization", "FakeAuth") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::OK); + + let body = hyper::body::to_bytes(response.into_body()).await.unwrap(); + let body: String = serde_json::from_slice(&body).unwrap(); + + assert_eq!(body, "list media items. limit=100000, offset=1"); + } + + #[sqlx::test] + async fn get_media_without_query_success(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + let app = Router::new().nest("/", MediaApi::routes(state).await); + + // when + let response = app + .oneshot( + Request::builder() + .uri("/media") + .method("GET") + .header("Authorization", "FakeAuth") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::OK); + + let body = hyper::body::to_bytes(response.into_body()).await.unwrap(); + let body: String = serde_json::from_slice(&body).unwrap(); + + assert_eq!(body, "list media items. limit=1000, offset=0"); + } + + #[sqlx::test] + async fn post_media_without_user_fail(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + let app = Router::new().nest("/", MediaApi::routes(state).await); + + // when + let response = app + .oneshot( + Request::builder() + .uri("/media") + .method("POST") + .header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) + .header( + "Content-Disposition", + "attachment; filename=\"DSC_1234.NEF\"", + ) + //.body(Body::from(bytes)) + //.body(Body::empty()) + // TODO: add multipart file to body + .body(Body::from( + serde_json::to_vec(&json!([1, 2, 3, 4])).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } + + // TODO: test is failing due to missing multi-part body + //#[sqlx::test] + #[allow(dead_code)] + async fn post_media_success(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + let app = Router::new().nest("/", MediaApi::routes(state).await); + + // when + let response = app + .oneshot( + Request::builder() + .uri("/media") + .method("POST") + .header("Authorization", "FakeAuth") + .header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) + .header( + "Content-Disposition", + "attachment; filename=\"DSC_1234.NEF\"", + ) + //.body(Body::from(bytes)) + //.body(Body::empty()) + // TODO: add multipart file to body + .body(Body::from( + serde_json::to_vec(&json!([1, 2, 3, 4])).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED); + } +} diff --git a/crates/media/src/api/routes/delete_media_id.rs b/crates/media/src/api/routes/delete_media_id.rs new file mode 100644 index 0000000..f3a2654 --- /dev/null +++ b/crates/media/src/api/routes/delete_media_id.rs @@ -0,0 +1,24 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Deletes the given item owned by the user +//! +use axum::http::StatusCode; + +pub(crate) async fn delete_media_id() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/get_albums.rs b/crates/media/src/api/routes/get_albums.rs new file mode 100644 index 0000000..a415e99 --- /dev/null +++ b/crates/media/src/api/routes/get_albums.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Returns the binary of a given entity +//! + +use axum::http::StatusCode; + +pub(crate) async fn get_albums() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/get_albums_id.rs b/crates/media/src/api/routes/get_albums_id.rs new file mode 100644 index 0000000..efdda53 --- /dev/null +++ b/crates/media/src/api/routes/get_albums_id.rs @@ -0,0 +1,22 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::http::StatusCode; + +pub(crate) async fn get_albums_id() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/get_media.rs b/crates/media/src/api/routes/get_media.rs new file mode 100644 index 0000000..9060981 --- /dev/null +++ b/crates/media/src/api/routes/get_media.rs @@ -0,0 +1,108 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Returns a list of owned media items for current user +//! +use axum::extract::State; +use axum::{extract::Query, http::StatusCode, Json}; +use common::auth::user::User; +use serde::{Deserialize, Serialize}; +use std::result::Result; +use tracing::error; +use uuid::Uuid; + +use crate::data::error::DataAccessError; +use crate::data::media_item::MediaItem; +use crate::repository::MediaRepositoryState; + +#[derive(Serialize, Deserialize)] +pub(crate) struct MediaListQuery { + offset: Option, + limit: Option, +} + +pub(crate) async fn get_media( + State(repo): State, + user: User, + Query(query): Query, +) -> Result, StatusCode> { + let items: Result, DataAccessError> = repo + .get_media_items_for_user(Uuid::parse_str(user.uuid.as_str()).unwrap()) + .await; + match items { + Ok(i) => { + error!("Found {} items for user.", i.len()); + } + Err(_) => { + error!("Failed to get media items!"); + } + } + // TODO: read list from persistency + // TODO: return list + Ok(Json( + format!( + "list media items. limit={}, offset={}", + query.limit.unwrap_or(1000), + query.offset.unwrap_or(0) + ) + .to_owned(), + )) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use axum::Router; + use common::{config::configuration::Configuration, ApplicationState}; + use database::sqlite::SqliteDatabase; + use hyper::{Body, Request}; + use sqlx::SqlitePool; + use tower::ServiceExt; + + use crate::api::router::MediaApi; + + use super::*; + + #[sqlx::test] + async fn get_media_unauthorized_should_not_fail(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + + let app = Router::new().nest("/", MediaApi::routes(state).await); + + // when + let response = app + .oneshot( + Request::builder() + .method("GET") + .uri("/media") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } +} diff --git a/crates/media/src/api/routes/get_media_id.rs b/crates/media/src/api/routes/get_media_id.rs new file mode 100644 index 0000000..4b618b9 --- /dev/null +++ b/crates/media/src/api/routes/get_media_id.rs @@ -0,0 +1,31 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Returns a specific owned or shared media item for current user +//! + +use axum::http::StatusCode; + +pub(crate) async fn get_media_id() -> std::result::Result { + // TODO: parse params max-with / max-height =wmax-width-hmax-height (=w2048-h1024) + // -wmax-width (preserving the aspect ratio) + // -hmax-height (preserving the aspect ratio) + // -c crop images to max-width / max-height + // -d remove exif data + + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/mod.rs b/crates/media/src/api/routes/mod.rs new file mode 100644 index 0000000..b6c1d6d --- /dev/null +++ b/crates/media/src/api/routes/mod.rs @@ -0,0 +1,14 @@ +pub(crate) mod delete_media_id; +pub(crate) mod get_albums; +pub(crate) mod get_albums_id; +pub(crate) mod get_media; +pub(crate) mod get_media_id; +pub(crate) mod patch_albums_id; +pub(crate) mod patch_albums_id_share; +pub(crate) mod patch_albums_id_unshare; +pub(crate) mod patch_media_id; +pub(crate) mod post_albums; +pub(crate) mod post_media; +pub(crate) mod post_media_id; + +pub(crate) mod photo_details; diff --git a/crates/media/src/api/routes/patch_albums_id.rs b/crates/media/src/api/routes/patch_albums_id.rs new file mode 100644 index 0000000..796d652 --- /dev/null +++ b/crates/media/src/api/routes/patch_albums_id.rs @@ -0,0 +1,22 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::http::StatusCode; + +pub(crate) async fn patch_albums_id() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/patch_albums_id_share.rs b/crates/media/src/api/routes/patch_albums_id_share.rs new file mode 100644 index 0000000..549c4f2 --- /dev/null +++ b/crates/media/src/api/routes/patch_albums_id_share.rs @@ -0,0 +1,22 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::http::StatusCode; + +pub(crate) async fn patch_albums_id_share() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/patch_albums_id_unshare.rs b/crates/media/src/api/routes/patch_albums_id_unshare.rs new file mode 100644 index 0000000..6ab4fe2 --- /dev/null +++ b/crates/media/src/api/routes/patch_albums_id_unshare.rs @@ -0,0 +1,22 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::http::StatusCode; + +pub(crate) async fn patch_albums_id_unshare() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/patch_media_id.rs b/crates/media/src/api/routes/patch_media_id.rs new file mode 100644 index 0000000..da24821 --- /dev/null +++ b/crates/media/src/api/routes/patch_media_id.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Updates fields from a specific media item for current user +//! + +use axum::http::StatusCode; + +pub(crate) async fn patch_media_id() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/photo_details.rs b/crates/media/src/api/routes/photo_details.rs new file mode 100644 index 0000000..9720588 --- /dev/null +++ b/crates/media/src/api/routes/photo_details.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Returns the details of a given media item +//! +use axum::http::StatusCode; + +#[allow(dead_code)] +pub(crate) async fn photo_details() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/post_albums.rs b/crates/media/src/api/routes/post_albums.rs new file mode 100644 index 0000000..93bd775 --- /dev/null +++ b/crates/media/src/api/routes/post_albums.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Returns the binary of a given entity +//! + +use axum::http::StatusCode; + +pub(crate) async fn post_albums() -> std::result::Result { + Err(StatusCode::NOT_IMPLEMENTED) +} diff --git a/crates/media/src/api/routes/post_media.rs b/crates/media/src/api/routes/post_media.rs new file mode 100644 index 0000000..f7e0c8c --- /dev/null +++ b/crates/media/src/api/routes/post_media.rs @@ -0,0 +1,243 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Creates a new media item to aggregate related files for current user +//! +use axum::{ + extract::{Multipart, State}, + http::StatusCode, + Json, +}; +use common::auth::user::User; +use hyper::header::LOCATION; +use hyper::HeaderMap; +use serde::{Deserialize, Serialize}; +use time::format_description::well_known::Rfc3339; +use time::OffsetDateTime; +use tracing::debug; +use uuid::Uuid; + +use crate::{data::error::DataAccessError, repository::MediaRepositoryState}; + +#[derive(Serialize, Deserialize)] +pub struct ResponseId { + pub id: String, +} + +pub(crate) async fn post_media( + State(repo): State, + user: User, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), StatusCode> { + let mut name = None; + let mut date_taken = None; + let mut headers = HeaderMap::new(); + + while let Some(field) = multipart.next_field().await.unwrap() { + if let Some(field_name) = field.name() { + match field_name { + "name" => name = Some(field.text().await.unwrap()), + "date_taken" => date_taken = Some(field.text().await.unwrap()), + _ => continue, + } + } + } + + if name.is_none() || date_taken.is_none() { + return Err(StatusCode::BAD_REQUEST); + } + + let date = OffsetDateTime::parse(date_taken.unwrap().as_str(), &Rfc3339); + if date.is_err() { + return Err(StatusCode::BAD_REQUEST); + } + + let result = repo + .create_media_item_for_user( + Uuid::parse_str(user.uuid.as_str()).unwrap(), + name.clone().unwrap(), + date.unwrap(), + ) + .await; + + match result { + Ok(uuid) => { + debug!( + "name={}, taken={} => id={}", + name.unwrap(), + date.unwrap(), + uuid.clone().hyphenated().to_string() + ); + + Ok(( + StatusCode::OK, + Json(ResponseId { + id: uuid.hyphenated().to_string(), + }), + )) + } + Err(error) => { + match error { + DataAccessError::AlreadyExist(id) => { + // TODO: use Redirect::permanent to add a Location header to the already existing item + let location = format!("/media/{}", id); + headers.insert(LOCATION, location.parse().unwrap()); + + return Err(StatusCode::SEE_OTHER); + } + _ => { + return Err(StatusCode::INTERNAL_SERVER_ERROR); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::io; + + use axum::Router; + use common::{config::configuration::Configuration, ApplicationState}; + use database::sqlite::SqliteDatabase; + use hyper::{Body, Request}; + use mime::BOUNDARY; + use sqlx::SqlitePool; + use tokio::fs::File; + use tower::ServiceExt; + + use crate::api::router::MediaApi; + use axum::http::header::CONTENT_TYPE; + use hyper::header::CONNECTION; + use std::io::Write; + use std::path::PathBuf; + use testdir::testdir; + use tokio::io::AsyncReadExt; + + use super::*; + + #[sqlx::test] + async fn post_media_unauthorized_should_fail(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + + let app = Router::new().nest("/", MediaApi::routes(state).await); + + // when + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/media") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } + + #[sqlx::test] + async fn post_media_authorized_without_name_field(pool: SqlitePool) { + // given + let state: ApplicationState = ApplicationState { + config: Configuration::empty(), + plugins: HashMap::new(), + router: None, + database: SqliteDatabase { pool }, + }; + let app = Router::new().nest("/", MediaApi::routes(state).await); + let data = media_item_form_data().await.unwrap(); + + // when + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/media") + .header("Authorization", "FakeAuth") + .header(CONNECTION, "Keep-Alive") + .header( + CONTENT_TYPE, + format!("multipart/form-data; boundary={}", BOUNDARY), + ) + // .header(CONTENT_TYPE, &*format!("multipart/form-data; boundary={}", BOUNDARY)) + .body(data.into()) + .unwrap(), + ) + .await + .unwrap(); + + // then + assert_eq!(response.status(), StatusCode::OK); + } + + async fn media_item_form_data() -> io::Result> { + let mut data: Vec = Vec::new(); + + write!(data, "--{}\r\n", BOUNDARY)?; + write!(data, "Content-Disposition: form-data; name=\"name\";\r\n")?; + write!(data, "\r\n")?; + write!(data, "DSC_1234")?; + write!(data, "\r\n")?; + + write!(data, "--{}\r\n", BOUNDARY)?; + write!( + data, + "Content-Disposition: form-data; name=\"date_taken\";\r\n" + )?; + write!(data, "\r\n")?; + write!(data, "1985-04-12T23:20:50.52Z")?; + write!(data, "\r\n")?; + + write!(data, "--{}--\r\n", BOUNDARY)?; + + Ok(data) + } + + #[allow(dead_code)] + async fn image_data() -> io::Result> { + let dir: PathBuf = testdir!(); + let path = dir.join("11.jpg"); + std::fs::write(&path, "fake image data").ok(); + + let mut data: Vec = Vec::new(); + write!(data, "--{}\r\n", BOUNDARY)?; + write!( + data, + "Content-Disposition: form-data; name=\"DSC_1234\"; filename=\"11.jpg\"\r\n" + )?; + write!(data, "Content-Type: image/jpeg\r\n")?; + write!(data, "\r\n")?; + + let mut f = File::open(path).await?; + f.read_to_end(&mut data).await?; + + write!(data, "\r\n")?; // The key thing you are missing + write!(data, "--{}--\r\n", BOUNDARY)?; + + Ok(data) + } +} diff --git a/crates/media/src/api/routes/post_media_id.rs b/crates/media/src/api/routes/post_media_id.rs new file mode 100644 index 0000000..75342f0 --- /dev/null +++ b/crates/media/src/api/routes/post_media_id.rs @@ -0,0 +1,110 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Add files for a specific media item +//! + +use axum::extract::{Multipart, Path, State}; +use axum::http::StatusCode; +use common::auth::user::User; +use hyper::header::LOCATION; +use hyper::HeaderMap; +use tempfile::tempfile; +use tokio::fs::File; +use tracing::{debug, error}; +use uuid::Uuid; + +use std::io::SeekFrom; +use tokio::io::{AsyncSeekExt, AsyncWriteExt}; + +use crate::data::error::DataAccessError; +use crate::repository::MediaRepositoryState; + +pub(crate) async fn post_media_id( + State(repo): State, + Path(media_id): Path, + user: User, + mut multipart: Multipart, +) -> Result { + error!("POST /media/{} user={}", media_id, user); + let mut headers = HeaderMap::new(); + let tempfile = tempfile().unwrap(); + let mut tempfile = File::from_std(tempfile); + let mut name: String = "".to_string(); + while let Some(mut field) = multipart.next_field().await.unwrap() { + if let Some(field_name) = field.name() { + match field_name { + "name" => { + name = field.text().await.unwrap(); + debug!("name={}", name.clone()); + } + "file" => { + while let Some(chunk) = field + .chunk() + .await + .expect("Could not read file from multipart upload!") + { + tempfile + .write_all(&chunk) + .await + .expect("Could not write reference file to tmp!") + } + tempfile.seek(SeekFrom::Start(0)).await.unwrap(); + + // TODO: wrap bytes and write to persistence + debug!("filesize={}", field.chunk().await.unwrap().unwrap().len()); + } + _ => continue, + } + } + } + + let result = repo + .add_reference_for_media_item( + Uuid::parse_str(user.uuid.as_str()).unwrap(), + media_id, + name, + tempfile, + ) + .await; + + match result { + Ok(uuid) => { + debug!( + "reference added. uuid={}", + uuid.clone().hyphenated().to_string() + ); + + Ok(uuid.hyphenated().to_string()) + } + Err(error) => { + match error { + DataAccessError::AlreadyExist(id) => { + // TODO: use Redirect::permanent to add a Location header to the already existing item + + let location = format!("/media/{}", id); + headers.insert(LOCATION, location.parse().unwrap()); + + return Err(StatusCode::SEE_OTHER); + } + _ => { + return Err(StatusCode::INTERNAL_SERVER_ERROR); + } + } + } + } +} diff --git a/crates/media/src/data/error.rs b/crates/media/src/data/error.rs new file mode 100644 index 0000000..6108cc7 --- /dev/null +++ b/crates/media/src/data/error.rs @@ -0,0 +1,27 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#[allow(dead_code)] +pub enum DataAccessError { + NotFound, + #[allow(dead_code)] + InvalidDateFormat, + AlreadyExist(String), + TechnicalError, + #[allow(dead_code)] + OtherError, +} diff --git a/crates/media/src/data/exif_info.rs b/crates/media/src/data/exif_info.rs new file mode 100644 index 0000000..d2c6007 --- /dev/null +++ b/crates/media/src/data/exif_info.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +pub struct ExifInformation { + pub camera: &'static str, + pub lens: &'static str, + pub focal_length: &'static str, + pub iso: &'static str, + pub shutter_speed: &'static str, + pub aperture: &'static str, +} diff --git a/crates/media/src/data/file.rs b/crates/media/src/data/file.rs new file mode 100644 index 0000000..97bacab --- /dev/null +++ b/crates/media/src/data/file.rs @@ -0,0 +1,26 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use std::time::Instant; + +pub struct File { + pub uuid: &'static str, + pub filename: &'static str, + pub filesize: f64, + pub last_modified: Option, + pub is_missing: bool, +} diff --git a/crates/media/src/data/location.rs b/crates/media/src/data/location.rs new file mode 100644 index 0000000..e6dd24e --- /dev/null +++ b/crates/media/src/data/location.rs @@ -0,0 +1,21 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +pub struct Location { + pub latitude: f64, + pub longitude: f64, +} diff --git a/crates/media/src/data/media_item.rs b/crates/media/src/data/media_item.rs new file mode 100644 index 0000000..44df9d5 --- /dev/null +++ b/crates/media/src/data/media_item.rs @@ -0,0 +1,49 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use std::time::Instant; + +use super::exif_info::ExifInformation; +use super::file::File; +use super::location::Location; + +pub struct MediaItem { + pub uuid: &'static str, + pub name: &'static str, + pub date_added: Instant, + pub date_taken: Option, + pub details: Option, + pub tags: Option>, + pub location: Option, + pub references: Option>, +} + +impl MediaItem { + #[allow(dead_code)] + fn new(name: &'static str) -> Self { + MediaItem { + uuid: "", + name, + date_added: Instant::now(), + date_taken: None, + location: None, + details: None, + tags: None, + references: None, + } + } +} diff --git a/crates/media/src/data/mod.rs b/crates/media/src/data/mod.rs new file mode 100644 index 0000000..5529475 --- /dev/null +++ b/crates/media/src/data/mod.rs @@ -0,0 +1,5 @@ +pub mod error; +pub mod exif_info; +pub mod file; +pub mod location; +pub mod media_item; diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs new file mode 100644 index 0000000..c06c16c --- /dev/null +++ b/crates/media/src/lib.rs @@ -0,0 +1,29 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate handles all media item related tasks in [Photos.network](https://photos.network) core application. +//! +//! * Providing an REST API to list, add or update items +//! * Reading and Writing files to the filesystem +//! * Persisting additional metadata in a database +//! + +pub mod api; + +pub mod data; + +pub mod repository; diff --git a/crates/media/src/repository.rs b/crates/media/src/repository.rs new file mode 100644 index 0000000..410c1df --- /dev/null +++ b/crates/media/src/repository.rs @@ -0,0 +1,213 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use crate::data::error::DataAccessError; +use crate::data::media_item::MediaItem; +use axum::async_trait; +use common::config::configuration::Configuration; +use common::database::reference::Reference; +use common::database::Database; +use database::sqlite::SqliteDatabase; +use std::path::Path; +use std::sync::Arc; +use time::OffsetDateTime; +use tokio::fs::File; +use tracing::info; +use uuid::Uuid; + +#[allow(dead_code)] +pub struct MediaRepository { + pub(crate) database: SqliteDatabase, + pub(crate) config: Configuration, +} + +pub type MediaRepositoryState = Arc; + +/// MockPhotosRepositoryTrait is created by automock macro +#[cfg_attr(test, mockall::automock)] +#[async_trait] +pub trait MediaRepositoryTrait { + // Gets a list of media items from the DB filtered by user_id + async fn get_media_items_for_user( + &self, + user_id: Uuid, + ) -> Result, DataAccessError>; + + /// Create a new media item for the given user + async fn create_media_item_for_user( + &self, + user_id: Uuid, + name: String, + date_taken: OffsetDateTime, + ) -> Result; + + async fn add_reference_for_media_item( + &self, + user_id: Uuid, + media_id: String, + name: String, + file: File, + ) -> Result; +} + +impl MediaRepository { + pub async fn new(database: SqliteDatabase, config: Configuration) -> Self { + Self { database, config } + } +} + +#[async_trait] +impl MediaRepositoryTrait for MediaRepository { + async fn get_media_items_for_user( + &self, + user_id: Uuid, + ) -> Result, DataAccessError> { + info!("get items for user {}", user_id); + + let items_result = &self + .database + .get_media_items(user_id.hyphenated().to_string().as_str()) + .await; + return match items_result { + Ok(items) => { + Ok(items + .into_iter() + .map(|d| MediaItem { + // TODO: fill in missing info like references, details, tags + // TODO: check references on filesystem + uuid: d.uuid, + name: d.name, + date_added: d.added_at, + date_taken: d.taken_at, + details: None, + tags: None, + location: None, + references: None, + }) + .collect()) + } + Err(_) => Err(DataAccessError::OtherError), + }; + } + + async fn create_media_item_for_user( + &self, + user_id: Uuid, + name: String, + date_taken: OffsetDateTime, + ) -> Result { + let db_result = &self + .database + .create_media_item( + user_id.hyphenated().to_string().as_str(), + name.as_str(), + date_taken, + ) + .await; + + match db_result { + Ok(id) => Ok(Uuid::parse_str(id.as_str()).unwrap()), + Err(_) => Err(DataAccessError::OtherError), + } + } + + async fn add_reference_for_media_item( + &self, + user_id: Uuid, + media_id: String, + name: String, + mut tmp_file: File, + ) -> Result { + let path = Path::new("data/files/") + .join(user_id.clone().hyphenated().to_string()) + .join(media_id.clone()) + .join(name.clone()); + + let mut dest_file = File::create(path.clone()).await.unwrap(); + + let num_bytes = tokio::io::copy(&mut tmp_file, &mut dest_file) + .await + .expect("Coudl not copy tmp file to path!"); + println!( + "{} bytes copied to path {}", + num_bytes, + path.clone().to_string_lossy() + ); + + let reference = Reference { + uuid: Uuid::new_v4().hyphenated().to_string(), + filepath: path.to_str().unwrap().to_string(), + filename: name.to_string(), + size: 0u64, + description: "", + last_modified: OffsetDateTime::now_utc(), + is_missing: false, + }; + let _ = &self + .database + .add_reference(media_id.as_str(), name.as_str(), &reference) + .await; + Err(DataAccessError::OtherError) + } +} + +#[allow(unused_imports)] +mod tests { + use database::sqlite::SqliteDatabase; + use sqlx::SqlitePool; + + use super::*; + + //noinspection DuplicatedCode + #[sqlx::test(migrations = "../database/migrations")] + async fn get_media_items_should_succeed(pool: SqlitePool) -> sqlx::Result<()> { + // given + let user_id = "605EE8BE-BAF2-4499-B8D4-BA8C74E8B242"; + sqlx::query("INSERT INTO users (uuid, email, password, lastname, firstname) VALUES ($1, $2, $3, $4, $5)") + .bind(user_id.clone()) + .bind("info@photos.network") + .bind("unsecure") + .bind("Stuermer") + .bind("Benjamin") + .execute(&pool).await?; + + sqlx::query("INSERT INTO media (uuid, name, owner) VALUES ($1, $2, $3)") + .bind("6A92460C-53FB-4B42-AC1B-E6760A34E169") + .bind("DSC_1234") + .bind(user_id.clone()) + .execute(&pool) + .await?; + + let db = SqliteDatabase::new( + "target/sqlx/test-dbs/media/repository/tests/get_media_items_should_succeed.sqlite", + ) + .await; + let repository = MediaRepository::new(db, Configuration::empty()).await; + + // when + let result = repository + .get_media_items_for_user(Uuid::parse_str(user_id).unwrap()) + .await; + + // then + // TODO fix assertion + assert!(result.is_err()); + //assert_eq!(result.ok().unwrap().len(), 1); + + Ok(()) + } +} diff --git a/crates/oauth_authentication/Cargo.toml b/crates/oauth_authentication/Cargo.toml new file mode 100644 index 0000000..909c0fd --- /dev/null +++ b/crates/oauth_authentication/Cargo.toml @@ -0,0 +1,61 @@ +[package] +name = "oauth_authentication" +description = "OAuth 2.0 authentication" +version.workspace = true +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "oauth_authentication" +path = "src/lib.rs" +doctest = false + +[dependencies] +# OIDC interfaces +openidconnect.workspace = true + +anyhow.workspace = true + +# error handling +thiserror.workspace = true + +# URL parsing +url.workspace = true + + + +# OIDC Router +axum.workspace = true +tower-http.workspace = true + + +# json payload +# serde = { workspace = true, features = ["derive"] } + +# time related data in models +# chrono.workspace = true +# uuid.workspace = true + +# key signing and cryptographics +# rsa = { version = "0.9.2" } + +# Rendering login form +# dioxus = "0.3.2" +# dioxus-ssr = "0.3.0" + +# tower-http.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true + + +[dev-dependencies] +testdir.workspace = true +rand.workspace = true +tokio.workspace = true +serde_json.workspace = true +axum-test.workspace = true diff --git a/crates/oauth_authentication/README.md b/crates/oauth_authentication/README.md new file mode 100644 index 0000000..6d98b17 --- /dev/null +++ b/crates/oauth_authentication/README.md @@ -0,0 +1,56 @@ +# OAuth 2.0 Authentication + +This crate offers an **Authorization code flow with PKCE** for [Photos.network](https://photos.network). + +To identify users and granting them access to the applications content, the Open Authorization (OAuth) standard is used so users can login without sharing credentials theirselfs. +Since public clients (e.g. native mobile applications and single-page applications) cannot securely store client secrets. +This application is using [PKCE](https://datatracker.ietf.org/doc/html/rfc7636) so it creates a pair of secrets (Code Verifier & Code Challenge) and send it to the **authorization server** over HTTPS. This way a malicious attacker can only intercept the Authorization Code but can't exchange it for a token without knowing the Code Verifier. + +### Native apps +Decompiling the app will reveal the Client Secret, which is bound to the app and is the same for all users and devices. Also they make use of a custom URL scheme to capture redirects (e.g., photosapp://) potentially allowing malicious applications to receive an Authorization Code from your Authorization Server. + +### Single-page application +Cannot securely store a Client Secret because their entire source is available to the browser. + + +## Authorization code flow with PKCE +```mermaid +sequenceDiagram; + participant U as Users + participant A as App + participant AM as Authorization Server + participant R as Resource Server + + U->>A: User clicks login + A->>AM: GET http://127.0.0.1/.well-known/openid-configuration + + AM->>A: JSON meta-data document + Note right of A: { "authorization_endpoint":"http://localhost:7777/oidc/authorize",
"token_endpoint":"http://localhost:7777/oidc/token" ... + + A->>A: Generate Code Verifier & Challenge + + A->>AM: GET http://localhost:7777/oidc/authorize?[...] + Note right of A: GET /oidc/authorize parameters:
response_type=id_token%20token
client_id=mobile-app (identifier)
redirect_uri=photosapp://authenticate
state=xxxx (CRFS protection)
nonce=xyz (server-side replay protection)
scope=openid email profile library:read
code_challenge=elU6u5zyqQT2f92GRQUq6PautAeNDf4DQPayy
code_challenge_method=S256 + + AM->>U: show login prompt + U->>AM: perform login and grant consent + AM->>A: 302 Redirect to http://127.0.0.1/callback?[...] (redirect_uri) + Note right of A: GET /callback
state=xxx
code=xxx + + A->>AM: GET http://localhost:7777/oidc/token + Note right of A: GET /oidc/token parameters:
client_id=xxx (identifier)
redirect_uri=http://127.0.0.1/callback
code_verifier=xxxx (generated verifier)
code=xyz (authorization_code)
grant_type=authorization_code + AM->>AM: Validate code verifier and challenge + AM->>A: ID Token and Access token + Note right of A: {
"token_type": "Bearer",
"expires_in": 3600,
"access_token": "eyJraWQiOiI3bFV0aGJyR2hWVmx...",
"id_token": "eyJraWQiOiI3bFV0aGJyR2hWVmx...",
"scope": "profile openid email"
} + + %% R->>A: return user attributes + %% U->>O: GET http://127.0.0.1/callback?[...] + %% O->>A: POST http://127.0.0.1:7777/oidc/token + %% Note right of O: POST /oidc/token
client_id=xxx
grant_type=authorization_code
code=xxx
state=xxx + %% A->>O: JSON { "base64(id_token)", access_token" } + %% O->>O: verify id_token signature is valid and signed + %% O->>U: GET 302 Redirect to http://127.0.0.1 + Note over A: User is authenticate to http://127.0.0.1 + A->>R: Request user data with Access Token + R->>A: responds with requested data +``` diff --git a/crates/oauth_authentication/src/lib.rs b/crates/oauth_authentication/src/lib.rs new file mode 100644 index 0000000..9e58400 --- /dev/null +++ b/crates/oauth_authentication/src/lib.rs @@ -0,0 +1,286 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate offers an **Authorization code flow with PKCE** in a [Photos.network](https://photos.network) core application. +//! +//! To identify users and granting them access to the applications content, the Open Authorization (OAuth) standard is used so users can login without sharing credentials theirselfs. +//! +use anyhow::{anyhow, Ok}; +use axum::Router; +use openidconnect::core::{ + CoreAuthenticationFlow, CoreClient, CoreProviderMetadata, CoreResponseType, CoreUserInfoClaims, +}; +use openidconnect::{ + AccessTokenHash, AuthorizationCode, ClientId, ClientSecret, CsrfToken, + EmptyAdditionalProviderMetadata, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, + ProviderMetadata, RedirectUrl, Scope, +}; + +use anyhow::Result; +use openidconnect::reqwest::http_client; +use thiserror::Error; + +// Use OpenID Connect Discovery to fetch the provider metadata. +use openidconnect::{OAuth2TokenResponse, TokenResponse}; + +pub struct AuthenticationManager { + #[allow(clippy::type_complexity)] + pub client: openidconnect::Client< + openidconnect::EmptyAdditionalClaims, + openidconnect::core::CoreAuthDisplay, + openidconnect::core::CoreGenderClaim, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + openidconnect::core::CoreJsonWebKeyUse, + openidconnect::core::CoreJsonWebKey, + openidconnect::core::CoreAuthPrompt, + openidconnect::StandardErrorResponse, + openidconnect::StandardTokenResponse< + openidconnect::IdTokenFields< + openidconnect::EmptyAdditionalClaims, + openidconnect::EmptyExtraTokenFields, + openidconnect::core::CoreGenderClaim, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + >, + openidconnect::core::CoreTokenType, + >, + openidconnect::core::CoreTokenType, + openidconnect::StandardTokenIntrospectionResponse< + openidconnect::EmptyExtraTokenFields, + openidconnect::core::CoreTokenType, + >, + openidconnect::core::CoreRevocableToken, + openidconnect::StandardErrorResponse, + >, + #[allow(clippy::type_complexity)] + pub provider_metadata: ProviderMetadata< + EmptyAdditionalProviderMetadata, + openidconnect::core::CoreAuthDisplay, + openidconnect::core::CoreClientAuthMethod, + openidconnect::core::CoreClaimName, + openidconnect::core::CoreClaimType, + openidconnect::core::CoreGrantType, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJweKeyManagementAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + openidconnect::core::CoreJsonWebKeyUse, + openidconnect::core::CoreJsonWebKey, + openidconnect::core::CoreResponseMode, + CoreResponseType, + openidconnect::core::CoreSubjectIdentifierType, + >, + pub pkce_challenge: PkceCodeChallenge, + pub pkce_verifier: PkceCodeVerifier, +} + +impl AuthenticationManager { + pub fn routes() -> Router + where + S: Send + Sync + 'static + Clone, + { + Router::new().layer(tower_http::trace::TraceLayer::new_for_http()) + } +} + +#[derive(Debug, Error)] +enum AuthError {} + +impl AuthenticationManager { + pub fn new() -> Result { + tracing::error!("run setup"); + + let provider_metadata = CoreProviderMetadata::discover( + &IssuerUrl::new("https://accounts.google.com".to_string())?, + http_client, + )?; + + // Generate a PKCE challenge. + let (pkce_challenge, pkce_verifier): (PkceCodeChallenge, openidconnect::PkceCodeVerifier) = + PkceCodeChallenge::new_random_sha256(); + + Ok(Self { + provider_metadata: provider_metadata.clone(), + client: CoreClient::from_provider_metadata( + provider_metadata, + ClientId::new( + "953760225864-77il4losuech1dtsea36tmma2e8bko3h.apps.googleusercontent.com" + .to_string(), + ), + Some(ClientSecret::new( + "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".to_string(), + )), + ) + // Set the URL the user will be redirected to after the authorization process. + .set_redirect_uri(RedirectUrl::new("http://127.0.0.1/callback".to_string())?), + pkce_challenge, + pkce_verifier, + }) + } + + #[allow(clippy::type_complexity)] + pub fn create_authorization_url( + client: openidconnect::Client< + openidconnect::EmptyAdditionalClaims, + openidconnect::core::CoreAuthDisplay, + openidconnect::core::CoreGenderClaim, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + openidconnect::core::CoreJsonWebKeyUse, + openidconnect::core::CoreJsonWebKey, + openidconnect::core::CoreAuthPrompt, + openidconnect::StandardErrorResponse, + openidconnect::StandardTokenResponse< + openidconnect::IdTokenFields< + openidconnect::EmptyAdditionalClaims, + openidconnect::EmptyExtraTokenFields, + openidconnect::core::CoreGenderClaim, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + >, + openidconnect::core::CoreTokenType, + >, + openidconnect::core::CoreTokenType, + openidconnect::StandardTokenIntrospectionResponse< + openidconnect::EmptyExtraTokenFields, + openidconnect::core::CoreTokenType, + >, + openidconnect::core::CoreRevocableToken, + openidconnect::StandardErrorResponse, + >, + pkce_challenge: PkceCodeChallenge, + ) -> Result { + let nonce = Nonce::new_random; + // Generate the full authorization URL. + let (auth_url, _csrf_token, nonce) = client + .authorize_url( + CoreAuthenticationFlow::AuthorizationCode, + CsrfToken::new_random, + nonce, + ) + // Set the desired scopes. + .add_scope(Scope::new("email".to_string())) + .add_scope(Scope::new("profile".to_string())) + // Set the PKCE code challenge. + .set_pkce_challenge(pkce_challenge) + .url(); + + // This is the URL you should redirect the user to, in order to trigger the authorization + // process. + println!("Browse to: {}", auth_url); + + Ok(nonce) + } + + #[allow(clippy::type_complexity)] + pub fn exchange_code( + client: openidconnect::Client< + openidconnect::EmptyAdditionalClaims, + openidconnect::core::CoreAuthDisplay, + openidconnect::core::CoreGenderClaim, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + openidconnect::core::CoreJsonWebKeyUse, + openidconnect::core::CoreJsonWebKey, + openidconnect::core::CoreAuthPrompt, + openidconnect::StandardErrorResponse, + openidconnect::StandardTokenResponse< + openidconnect::IdTokenFields< + openidconnect::EmptyAdditionalClaims, + openidconnect::EmptyExtraTokenFields, + openidconnect::core::CoreGenderClaim, + openidconnect::core::CoreJweContentEncryptionAlgorithm, + openidconnect::core::CoreJwsSigningAlgorithm, + openidconnect::core::CoreJsonWebKeyType, + >, + openidconnect::core::CoreTokenType, + >, + openidconnect::core::CoreTokenType, + openidconnect::StandardTokenIntrospectionResponse< + openidconnect::EmptyExtraTokenFields, + openidconnect::core::CoreTokenType, + >, + openidconnect::core::CoreRevocableToken, + openidconnect::StandardErrorResponse, + >, + pkce_verifier: PkceCodeVerifier, + authorization_code: String, + nonce: Nonce, + ) -> Result<()> { + // Once the user has been redirected to the redirect URL, you'll have access to the + // authorization code. For security reasons, your code should verify that the `state` + // parameter returned by the server matches `csrf_state`. + + // Now you can exchange it for an access token and ID token. + let token_response = client + .exchange_code(AuthorizationCode::new(authorization_code)) + // Set the PKCE code verifier. + .set_pkce_verifier(pkce_verifier) + .request(http_client)?; + + // Extract the ID token claims after verifying its authenticity and nonce. + let id_token = token_response + .id_token() + .ok_or_else(|| anyhow!("Server did not return an ID token"))?; + let claims = id_token.claims(&client.id_token_verifier(), &nonce)?; + + // Verify the access token hash to ensure that the access token hasn't been substituted for + // another user's. + if let Some(expected_access_token_hash) = claims.access_token_hash() { + let actual_access_token_hash = AccessTokenHash::from_token( + token_response.access_token(), + &id_token.signing_alg()?, + )?; + if actual_access_token_hash != *expected_access_token_hash { + return Err(anyhow!("Invalid access token")); + } + } + + // The authenticated user's identity is now available. See the IdTokenClaims struct for a + // complete listing of the available claims. + println!( + "User {} with e-mail address {} has authenticated successfully", + claims.subject().as_str(), + claims + .email() + .map(|email| email.as_str()) + .unwrap_or(""), + ); + + // If available, we can use the UserInfo endpoint to request additional information. + + // The user_info request uses the AccessToken returned in the token response. To parse custom + // claims, use UserInfoClaims directly (with the desired type parameters) rather than using the + // CoreUserInfoClaims type alias. + let _userinfo: CoreUserInfoClaims = client + .user_info(token_response.access_token().to_owned(), None) + .map_err(|err| anyhow!("No user info endpoint: {:?}", err))? + .request(http_client) + .map_err(|err| anyhow!("Failed requesting user info: {:?}", err))?; + + // See the OAuth2TokenResponse trait for a listing of other available fields such as + // access_token() and refresh_token(). + + Ok(()) + } +} diff --git a/crates/oauth_authorization_server/Cargo.toml b/crates/oauth_authorization_server/Cargo.toml new file mode 100644 index 0000000..b58b26d --- /dev/null +++ b/crates/oauth_authorization_server/Cargo.toml @@ -0,0 +1,55 @@ +[package] +name = "oauth_authorization_server" +description = "OAuth Authorization Server for privacy and offline support to replace third-party oauth servers like Okta, Google or Microsoft" +version.workspace = true +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +repository.workspace = true +readme.workspace = true +license.workspace = true +edition.workspace = true + +[lib] +name = "oauth_authorization_server" +path = "src/lib.rs" +doctest = false + +[dependencies] +# OIDC interfaces +openidconnect.workspace = true + +# OIDC Router +axum.workspace = true + +# json payload +serde.workspace = true + +# time related data in models +chrono.workspace = true +uuid.workspace = true + +# key signing and cryptographics +rsa.workspace = true + +# error handling +thiserror.workspace = true + +# URL parsing +url.workspace = true + +# Rendering login form +# dioxus = "0.3.2" +# dioxus-ssr = "0.3.0" + +tower-http.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true + + +[dev-dependencies] +testdir.workspace = true +rand.workspace = true +tokio.workspace = true +serde_json.workspace = true +axum-test.workspace = true diff --git a/crates/oauth_authorization_server/README.md b/crates/oauth_authorization_server/README.md new file mode 100644 index 0000000..3e166d2 --- /dev/null +++ b/crates/oauth_authorization_server/README.md @@ -0,0 +1,5 @@ +# OAuth Authorization Server + +This crate offers an **OAuth Authorization Server** for [Photos.network](https://photos.network). + +Especially for data privacy or offline support, this can interact as its own authorization server to handle user accounts locally without using any third-party authorization like Google, Okta or Microsoft. diff --git a/crates/oauth_authorization_server/src/client.rs b/crates/oauth_authorization_server/src/client.rs new file mode 100644 index 0000000..02bbb38 --- /dev/null +++ b/crates/oauth_authorization_server/src/client.rs @@ -0,0 +1,25 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Client { + pub id: String, + pub secret: Option, + pub redirect_uri: String, +} diff --git a/crates/oauth_authorization_server/src/config.rs b/crates/oauth_authorization_server/src/config.rs new file mode 100644 index 0000000..267f755 --- /dev/null +++ b/crates/oauth_authorization_server/src/config.rs @@ -0,0 +1,50 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use serde::{Deserialize, Serialize}; + +use std::path::{Path, PathBuf}; + +use crate::client::Client; + +#[derive(Debug, Deserialize, Serialize)] +pub struct ServerConfig { + pub listen_addr: String, + pub domain: String, + pub use_ssl: bool, + pub realm_keys_base_path: PathBuf, + pub realms: Vec, +} + +impl Default for ServerConfig { + fn default() -> Self { + Self { + listen_addr: String::from("127.0.0.1:7777"), + domain: String::from("localhost:7777"), + use_ssl: false, + realm_keys_base_path: Path::new("keys").to_path_buf(), + realms: vec![], + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct ConfigRealm { + pub name: String, + pub domain: Option, + pub clients: Vec, +} diff --git a/crates/oauth_authorization_server/src/error.rs b/crates/oauth_authorization_server/src/error.rs new file mode 100644 index 0000000..84c3bb1 --- /dev/null +++ b/crates/oauth_authorization_server/src/error.rs @@ -0,0 +1,45 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error(transparent)] + OpenIDUrlParseError(#[from] openidconnect::url::ParseError), + + #[error(transparent)] + AddrParseError(#[from] std::net::AddrParseError), + + #[error("{0}")] + HyperError(String), + + #[error("{0}")] + MappedError(String), + + #[error(transparent)] + IOError(#[from] std::io::Error), + + #[error(transparent)] + RSAError(#[from] rsa::Error), + + #[error(transparent)] + Pkcs1Error(#[from] rsa::pkcs1::Error), + + #[error("could not open key of realm {0}")] + CouldNotOpenRealmKey(String), +} diff --git a/crates/oauth_authorization_server/src/handler/authorize.rs b/crates/oauth_authorization_server/src/handler/authorize.rs new file mode 100644 index 0000000..0f855fd --- /dev/null +++ b/crates/oauth_authorization_server/src/handler/authorize.rs @@ -0,0 +1,64 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Validate the request to ensure that all required parameters are present and valid. +//! +//! See Section 4.1.1: https://tools.ietf.org/html/rfc6749#section-4.1.1 +//! +use axum::extract::{Query, State}; +use axum::http::StatusCode; +use axum::response::Redirect; +use std::sync::{Arc, RwLock}; + +use crate::query::AuthorizeQuery; +use crate::request::AuthRequest; +use crate::state::ServerState; + +pub(crate) type SharedState = Arc>; + +pub(crate) async fn authorization_handler( + Query(query): Query, + State(state): State, +) -> std::result::Result { + let req = AuthRequest { + id: uuid::Uuid::new_v4(), + code_challenge: query.code_challenge, + code: None, + created_at: chrono::Utc::now().naive_utc(), + state: query.state, + nonce: query.nonce, + }; + for realm in state.write().unwrap().realms.iter_mut() { + for client in realm.clients.iter() { + if client.id == query.client_id { + realm.requests.push(req); + let realm_login_url = format!("/{}/login", &realm.name); + return Ok(Redirect::to(&realm_login_url)); + } + } + } + + for client in state.read().unwrap().master_realm.clients.iter() { + if client.id == query.client_id { + state.write().unwrap().master_realm.requests.push(req); + let realm_login_url = format!("/{}/login", &state.read().unwrap().master_realm.name); + return Ok(Redirect::to(&realm_login_url)); + } + } + + Err(StatusCode::UNAUTHORIZED) +} diff --git a/crates/oauth_authorization_server/src/handler/discovery.rs b/crates/oauth_authorization_server/src/handler/discovery.rs new file mode 100644 index 0000000..7189171 --- /dev/null +++ b/crates/oauth_authorization_server/src/handler/discovery.rs @@ -0,0 +1,36 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::extract::State; +use axum::Json; +use axum::{headers::Host, TypedHeader}; +use openidconnect::core::CoreProviderMetadata; + +use super::authorize::SharedState; + +pub(crate) async fn openid_discover_handler( + State(state): State, + TypedHeader(host): TypedHeader, +) -> Json { + for realm in state.read().unwrap().realms.iter() { + if realm.domain == host.hostname() { + return Json(realm.provider_metadata.clone()); + } + } + + Json(state.read().unwrap().master_realm.provider_metadata.clone()) +} diff --git a/crates/oauth_authorization_server/src/handler/jwks.rs b/crates/oauth_authorization_server/src/handler/jwks.rs new file mode 100644 index 0000000..d5a0bfc --- /dev/null +++ b/crates/oauth_authorization_server/src/handler/jwks.rs @@ -0,0 +1,36 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::extract::State; +use axum::Json; +use axum::{headers::Host, TypedHeader}; +use openidconnect::core::CoreJsonWebKeySet; + +use super::authorize::SharedState; + +pub(crate) async fn openid_jwks_handler( + State(state): State, + TypedHeader(host): TypedHeader, +) -> Json { + for realm in state.read().unwrap().realms.iter() { + if realm.domain == host.hostname() { + return Json(realm.jwks.clone()); + } + } + + Json(state.read().unwrap().master_realm.jwks.clone()) +} diff --git a/crates/oauth_authorization_server/src/handler/login.rs b/crates/oauth_authorization_server/src/handler/login.rs new file mode 100644 index 0000000..d845b49 --- /dev/null +++ b/crates/oauth_authorization_server/src/handler/login.rs @@ -0,0 +1,62 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use axum::response::Html; +use axum::Form; + +use serde::Deserialize; + +pub(crate) async fn get_realm_login_form( + axum::extract::Path(_realm): axum::extract::Path, + // Query(query): Query, +) -> Html { + // create a VirtualDom with the app component + // rebuild the VirtualDom before rendering + + // tracing::debug!( + // "Rendering form for request_id={} and realm={}", + // query.request_id, + // realm + // ); + + // render the VirtualDom to HTML + // Html(dioxus_ssr::render(&app)) + Html("Login".to_string()) +} + +pub(crate) async fn post_realm_login(Form(login_form): Form) -> Html { + tracing::debug!( + "username: {}, password: {}", + login_form.username, + login_form.password + ); + + // TODO: validate credentials + + Html(String::from("
Success
")) +} + +#[derive(Debug, Deserialize)] +pub(crate) struct LoginQuery { + _request_id: String, +} + +#[derive(Debug, Deserialize)] +pub(crate) struct LoginFormData { + username: String, + password: String, +} diff --git a/crates/oauth_authorization_server/src/lib.rs b/crates/oauth_authorization_server/src/lib.rs new file mode 100644 index 0000000..26fcd1d --- /dev/null +++ b/crates/oauth_authorization_server/src/lib.rs @@ -0,0 +1,66 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This crate offers an **OAuth Authorization Server** for [Photos.network](https://photos.network) core application. +//! +use axum::routing::get; +use axum::Router; +use handler::{ + authorize::authorization_handler, + discovery::openid_discover_handler, + jwks::openid_jwks_handler, + login::{get_realm_login_form, post_realm_login}, +}; +use state::ServerState; +use std::sync::{Arc, RwLock}; + +pub mod client; +pub mod config; +pub mod error; +pub mod query; +pub mod realm; +pub mod request; +pub mod state; +pub mod handler { + pub mod authorize; + pub mod discovery; + pub mod jwks; + pub mod login; +} + +pub struct AuthorizationServerManager {} + +impl AuthorizationServerManager { + pub fn routes(server: ServerState) -> Router + where + S: Send + Sync + 'static + Clone, + { + Router::new() + .route( + "/.well-known/openid-configuration", + get(openid_discover_handler), + ) + .route("/oidc/authorize", get(authorization_handler)) + .route("/jwk", get(openid_jwks_handler)) + .route( + "/:realm/login", + get(get_realm_login_form).post(post_realm_login), + ) + .layer(tower_http::trace::TraceLayer::new_for_http()) + .with_state(Arc::new(RwLock::new(server))) + } +} diff --git a/crates/oauth_authorization_server/src/query.rs b/crates/oauth_authorization_server/src/query.rs new file mode 100644 index 0000000..a895044 --- /dev/null +++ b/crates/oauth_authorization_server/src/query.rs @@ -0,0 +1,32 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use serde::Deserialize; +use url::Url; + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +pub(crate) struct AuthorizeQuery { + pub(crate) response_type: String, + pub(crate) client_id: String, + pub(crate) state: String, + pub(crate) code_challenge: String, + pub(crate) code_challenge_method: String, + pub(crate) redirect_uri: Url, + pub(crate) scope: String, + pub(crate) nonce: String, +} diff --git a/crates/oauth_authorization_server/src/realm.rs b/crates/oauth_authorization_server/src/realm.rs new file mode 100644 index 0000000..cbf619f --- /dev/null +++ b/crates/oauth_authorization_server/src/realm.rs @@ -0,0 +1,155 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use openidconnect::core::{ + CoreClaimName, CoreJsonWebKeySet, CoreJwsSigningAlgorithm, CoreProviderMetadata, + CoreResponseType, CoreRsaPrivateSigningKey, CoreSubjectIdentifierType, +}; +use openidconnect::{ + AuthUrl, EmptyAdditionalProviderMetadata, IssuerUrl, JsonWebKeyId, JsonWebKeySetUrl, + PrivateSigningKey, ResponseTypes, TokenUrl, UserInfoUrl, +}; + +use std::fs::File; +use std::io::Read; +use std::path::Path; + +use crate::client::Client; +use crate::error::Error; +use crate::request::AuthRequest; + +#[derive(Debug, Clone)] +pub struct Realm { + #[allow(dead_code)] + pub(crate) name: String, + pub(crate) clients: Vec, + pub(crate) domain: String, + pub(crate) provider_metadata: CoreProviderMetadata, + pub(crate) jwks: CoreJsonWebKeySet, + pub(crate) requests: Vec, +} + +impl Realm { + pub fn new>( + name: &str, + domain: &str, + scheme: &str, + clients: Vec, + realm_keys_base_path: P, + ) -> Result { + let mut realm_key_file = File::open( + realm_keys_base_path + .as_ref() + .join(name) + .with_extension("pem"), + ) + .unwrap_or_else(|_| { + panic!( + "key ({}) not found in directory ({})!", + name, + realm_keys_base_path.as_ref().display() + ) + }); + let mut realm_key_str = String::new(); + realm_key_file + .read_to_string(&mut realm_key_str) + .map_err(|_| Error::CouldNotOpenRealmKey(name.to_owned()))?; + + Ok(Self { + name: name.to_owned(), + domain: domain.to_owned(), + clients, + requests: vec![], + provider_metadata: CoreProviderMetadata::new( + // Parameters required by the OpenID Connect Discovery spec. + IssuerUrl::new(format!("{}://{}", scheme, domain))?, + AuthUrl::new(format!("{}://{}/oidc/authorize", scheme, domain))?, + // Use the JsonWebKeySet struct to serve the JWK Set at this URL. + JsonWebKeySetUrl::new(format!("{}://{}/oidc/jwk", scheme, domain))?, + // Supported response types (flows). + vec![ + // Recommended: support the code flow. + ResponseTypes::new(vec![CoreResponseType::Code]), + ], + // For user privacy, the Pairwise subject identifier type is preferred. This prevents + // distinct relying parties (clients) from knowing whether their users represent the same + // real identities. This identifier type is only useful for relying parties that don't + // receive the 'email', 'profile' or other personally-identifying scopes. + // The Public subject identifier type is also supported. + vec![CoreSubjectIdentifierType::Pairwise], + // Support the RS256 signature algorithm. + vec![CoreJwsSigningAlgorithm::RsaSsaPssSha256], + // OpenID Connect Providers may supply custom metadata by providing a struct that + // implements the AdditionalProviderMetadata trait. This requires manually using the + // generic ProviderMetadata struct rather than the CoreProviderMetadata type alias, + // however. + EmptyAdditionalProviderMetadata {}, + ) + // Specify the token endpoint (required for the code flow). + .set_token_endpoint(Some(TokenUrl::new(format!( + "{}://{}/oidc/token", + scheme, domain + ))?)) + // Recommended: support the UserInfo endpoint. + .set_userinfo_endpoint(Some(UserInfoUrl::new(format!( + "{}://{}/oidc/userinfo", + scheme, domain + ))?)) + // Recommended: specify the supported scopes. + .set_scopes_supported(Some(vec![ + openidconnect::Scope::new("openid".to_string()), + openidconnect::Scope::new("email".to_string()), + openidconnect::Scope::new("profile".to_string()), + openidconnect::Scope::new("library.read".to_string()), + openidconnect::Scope::new("library.append".to_string()), + openidconnect::Scope::new("library.edit".to_string()), + openidconnect::Scope::new("library.write".to_string()), + openidconnect::Scope::new("library.share".to_string()), + openidconnect::Scope::new("admin.users:read".to_string()), + openidconnect::Scope::new("admin.users:invite".to_string()), + openidconnect::Scope::new("admin.users:write".to_string()), + ])) + // Recommended: specify the supported ID token claims. + .set_claims_supported(Some(vec![ + // Providers may also define an enum instead of using CoreClaimName. + CoreClaimName::new("sub".to_string()), + CoreClaimName::new("aud".to_string()), + CoreClaimName::new("email".to_string()), + CoreClaimName::new("email_verified".to_string()), + CoreClaimName::new("exp".to_string()), + CoreClaimName::new("iat".to_string()), + CoreClaimName::new("iss".to_string()), + CoreClaimName::new("name".to_string()), + CoreClaimName::new("given_name".to_string()), + CoreClaimName::new("family_name".to_string()), + CoreClaimName::new("picture".to_string()), + CoreClaimName::new("locale".to_string()), + ])), + jwks: CoreJsonWebKeySet::new(vec![ + // RSA keys may also be constructed directly using CoreJsonWebKey::new_rsa(). Providers + // aiming to support other key types may provide their own implementation of the + // JsonWebKey trait or submit a PR to add the desired support to this crate. + CoreRsaPrivateSigningKey::from_pem( + &realm_key_str, + Some(JsonWebKeyId::new(format!("{}_key", name))), + ) + .expect("Invalid RSA private key") + .as_verification_key(), + ]), + }) + } +} diff --git a/crates/oauth_authorization_server/src/request.rs b/crates/oauth_authorization_server/src/request.rs new file mode 100644 index 0000000..de79fd2 --- /dev/null +++ b/crates/oauth_authorization_server/src/request.rs @@ -0,0 +1,27 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub(crate) struct AuthRequest { + pub(crate) id: uuid::Uuid, + pub(crate) code: Option, + pub(crate) created_at: chrono::NaiveDateTime, + pub(crate) state: String, + pub(crate) code_challenge: String, + pub(crate) nonce: String, +} diff --git a/crates/oauth_authorization_server/src/state.rs b/crates/oauth_authorization_server/src/state.rs new file mode 100644 index 0000000..ac989cc --- /dev/null +++ b/crates/oauth_authorization_server/src/state.rs @@ -0,0 +1,70 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use crate::client::Client; +use crate::config::ServerConfig; +use crate::error::Error; +use crate::realm::Realm; + +#[derive(Debug, Clone)] +pub struct ServerState { + pub addr: String, + pub realms: Vec, + pub master_realm: Realm, +} + +impl ServerState { + pub fn new(config: ServerConfig) -> Result { + let realms = config + .realms + .iter() + .filter_map(|r| { + Realm::new( + &r.name, + &r.domain.clone().unwrap_or(config.domain.clone()), + helper_get_scheme_from_config(config.use_ssl), + r.clients.clone(), + config.realm_keys_base_path.clone(), + ) + .ok() + }) + .collect::>(); + Ok(Self { + addr: config.listen_addr, + realms, + master_realm: Realm::new( + "master", + &config.domain, + helper_get_scheme_from_config(config.use_ssl), + vec![Client { + id: String::from("master_client"), + secret: None, + redirect_uri: String::from("photosapp://authenticate"), + }], + config.realm_keys_base_path.clone(), + )?, + }) + } +} + +fn helper_get_scheme_from_config(use_ssl: bool) -> &'static str { + if use_ssl { + "https" + } else { + "http" + } +} diff --git a/crates/oauth_authorization_server/tests/authorization_flow.rs b/crates/oauth_authorization_server/tests/authorization_flow.rs new file mode 100644 index 0000000..46ddf0e --- /dev/null +++ b/crates/oauth_authorization_server/tests/authorization_flow.rs @@ -0,0 +1,74 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Thest the OIDC authorization code flow with PKCE +//! +//! 1st - [OpenID Connect Discovery](https://server.com/.well-known/openid-configuration) +//! 2nd - [Authorization](https://server.com/oidc/authorize?) +//! 3rd - [Token](https://server.com/oidc/token) +//! 4th - [User info](https://server.com/oidc/userinfo) +//! 5th - [End session](https://server.com/oidc/logout) +//! 6th - [Revokation](https://server.com/oidc/revoke) +//! +use ::axum_test::TestServer; + +mod common; + +#[cfg(test)] +mod tests { + use super::*; + + // Test if OIDC discovery responds with 200 OK and contains mandatory fields + // e.g. issuer, authorization_endpoint and token_endpoint + #[tokio::test] + async fn oidc_discovery_succesful() { + // given + let router = common::create_router(); + let server = TestServer::new(router.into_make_service()).unwrap(); + + // when + let response = server.get(".well-known/openid-configuration").await; + + // then + assert_eq!( + response.status_code().as_u16(), + 200, + "HTTP 200 OK success status response code expected" + ); + + // TODO: verify body + } + + #[tokio::test] + async fn oidc_authorization_code_flow_with_pkce_succesful() { + // given + let router = common::create_router(); + let server = TestServer::new(router.into_make_service()).unwrap(); + + // when + let response = server.get(".well-known/openid-configuration").await; + + // then + assert_eq!( + response.status_code().as_u16(), + 200, + "HTTP 200 OK success status response code expected" + ); + + // TODO: verify Location header + } +} diff --git a/crates/oauth_authorization_server/tests/common/mod.rs b/crates/oauth_authorization_server/tests/common/mod.rs new file mode 100644 index 0000000..cd25f45 --- /dev/null +++ b/crates/oauth_authorization_server/tests/common/mod.rs @@ -0,0 +1,68 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Create a private key file to use for OIDC. +//! +use axum::Router; +use oauth_authorization_server::{ + config::ServerConfig, state::ServerState, AuthorizationServerManager, +}; +use rand::rngs::OsRng; +use rsa::pkcs1::EncodeRsaPrivateKey; +use rsa::pkcs8::LineEnding; +use rsa::RsaPrivateKey; +use std::fs; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; +use testdir::testdir; + +pub fn create_fake_pem(filename: &'static str) -> PathBuf { + let path: PathBuf = testdir!(); + let keys_base_path = path.join("keys"); + // create keys directory + fs::create_dir(&keys_base_path).unwrap(); + + // create a fake private key + let mut rng = OsRng; + let bits = 2048; + let key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate private key"); + let pem = key.to_pkcs1_pem(LineEnding::LF).unwrap(); + + // write private key into file + let mut file: File = File::create(keys_base_path.join(filename)).expect("no file"); + file.write_all(pem.as_bytes()).expect("write failed"); + + keys_base_path +} + +pub fn create_router() -> Router { + let private_key: PathBuf = create_fake_pem("master.pem"); + + // create server config with fake key + let server_config = ServerConfig { + listen_addr: String::from("127.0.0.1:7777"), + domain: String::from("localhost:7777"), + use_ssl: false, + realm_keys_base_path: private_key, + realms: vec![], + }; + let server_state = ServerState::new(server_config).expect("no server config!"); + let router = AuthorizationServerManager::routes(server_state); + + router +} diff --git a/crates/plugin_interface/Cargo.lock b/crates/plugin_interface/Cargo.lock new file mode 100644 index 0000000..e00697b --- /dev/null +++ b/crates/plugin_interface/Cargo.lock @@ -0,0 +1,442 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "abi_stable" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f69d9465d88d24382d43fa68335a92fe9d3c53a918549c693403ed9a85eff50" +dependencies = [ + "abi_stable_derive", + "abi_stable_shared", + "const_panic", + "core_extensions", + "crossbeam-channel", + "generational-arena", + "libloading", + "lock_api", + "parking_lot", + "paste", + "repr_offset", + "rustc_version", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "abi_stable_derive" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aecd3efa5a5294f5c67913d45f985ccb382b3c93327581529610eeecdf4821a" +dependencies = [ + "abi_stable_shared", + "as_derive_utils", + "core_extensions", + "proc-macro2", + "quote", + "rustc_version", + "syn 1.0.109", + "typed-arena", +] + +[[package]] +name = "abi_stable_shared" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b5df7688c123e63f4d4d649cba63f2967ba7f7861b1664fca3f77d3dad2b63" +dependencies = [ + "core_extensions", +] + +[[package]] +name = "as_derive_utils" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff3c96645900a44cf11941c111bd08a6573b0e2f9f69bc9264b179d8fae753c4" +dependencies = [ + "core_extensions", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "const_panic" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58baae561b85ca19b3122a9ddd35c8ec40c3bcd14fe89921824eae73f7baffbf" + +[[package]] +name = "core_extensions" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92c71dc07c9721607e7a16108336048ee978c3a8b129294534272e8bac96c0ee" +dependencies = [ + "core_extensions_proc_macros", +] + +[[package]] +name = "core_extensions_proc_macros" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f3b219d28b6e3b4ac87bc1fc522e0803ab22e055da177bff0068c4150c61a6" + +[[package]] +name = "crossbeam-channel" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf2b3e8478797446514c91ef04bafcb59faba183e621ad488df88983cc14128c" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" +dependencies = [ + "cfg-if 1.0.0", +] + +[[package]] +name = "generational-arena" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d3b771574f62d0548cee0ad9057857e9fc25d7a3335f140c84f6acd0bf601" +dependencies = [ + "cfg-if 0.1.10", +] + +[[package]] +name = "itoa" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" + +[[package]] +name = "libc" +version = "0.2.140" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99227334921fae1a979cf0bfdfcc6b3e5ce376ef57e16fb6fb3ea2ed6095f80c" + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if 1.0.0", + "winapi", +] + +[[package]] +name = "lock_api" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "redox_syscall", + "smallvec", + "windows-sys", +] + +[[package]] +name = "paste" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79" + +[[package]] +name = "photos_network_plugin" +version = "0.2.0" +dependencies = [ + "abi_stable", + "core_extensions", +] + +[[package]] +name = "proc-macro2" +version = "1.0.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e472a104799c74b514a57226160104aa483546de37e839ec50e3c2e41dd87534" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags", +] + +[[package]] +name = "repr_offset" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb1070755bd29dffc19d0971cab794e607839ba2ef4b69a9e6fbc8733c1b72ea" +dependencies = [ + "tstr", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "ryu" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "semver" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" + +[[package]] +name = "serde" +version = "1.0.158" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "771d4d9c4163ee138805e12c710dd365e4f44be8be0503cb1bb9eb989425d9c9" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.158" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e801c1712f48475582b7696ac71e0ca34ebb30e09338425384269d9717c62cad" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c533a59c9d8a93a09c6ab31f0fd5e5f4dd1b8fc9434804029839884765d04ea" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "smallvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aad1363ed6d37b84299588d62d3a7d95b5a5c2d9aad5c85609fda12afaa1f40" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tstr" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca3264971090dec0feef3b455a3c178f02762f7550cf4592991ac64b3be2d7e" +dependencies = [ + "tstr_proc_macros", +] + +[[package]] +name = "tstr_proc_macros" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78122066b0cb818b8afd08f7ed22f7fdbc3e90815035726f0840d0d26c0747a" + +[[package]] +name = "typed-arena" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" + +[[package]] +name = "unicode-ident" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" diff --git a/crates/plugin_interface/Cargo.toml b/crates/plugin_interface/Cargo.toml new file mode 100644 index 0000000..55bd41d --- /dev/null +++ b/crates/plugin_interface/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "photos_network_plugin" +version = "0.2.0" +authors = ["Photos network developers "] + +repository = "https://github.com/photos-network/plugin" +description = "The plugin interface for photos.network an free and open-source project (FOSS) for a self-hosted photo management." +documentation = "https://developers.photos.network/" +readme = "README.md" +keywords = ["Photos.network", "Photos network", "plugin", "abi_stable_crates"] +license = "GNU Affero General Public License (AGPL)" +edition = "2021" + +[dependencies] +abi_stable = "0.11.1" +core_extensions = { version = "1.5.3", default_features = false, features = ["std"] } diff --git a/crates/plugin_interface/src/lib.rs b/crates/plugin_interface/src/lib.rs new file mode 100644 index 0000000..27bdf73 --- /dev/null +++ b/crates/plugin_interface/src/lib.rs @@ -0,0 +1,82 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! This is the plugin interface definition for Photos.network +//! +//! The Photos.network core will look for available plugins during start up and +//! enable and load them when the plugin identifier is present in the configuration file. +//! +//! Plugins can not be unloaded during runtime! +//! + +use abi_stable::{ + declare_root_module_statics, + external_types::crossbeam_channel::RSender, + library::RootModule, + package_version_strings, sabi_trait, + sabi_types::VersionStrings, + std_types::{RBox, RResult, RString}, + StableAbi, +}; + +pub type PluginType = Plugin_TO<'static, RBox<()>>; +pub type PluginId = RString; + +#[repr(C)] +#[derive(Debug, Clone, PartialEq, StableAbi)] +pub struct PluginCommand { + pub from: RString, + pub to: RString, + pub command: RString, +} + +/// Interface definition of the plugin +#[sabi_trait] +pub trait Plugin { + fn on_core_init(&self) -> RResult; + fn on_core_started(&self) -> RResult; +} + +/// Factory to load the plugin at runtime +/// +#[repr(C)] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = PluginFactoryRef)))] +#[sabi(missing_field(panic))] +pub struct PluginFactory { + /// Constructs the plugin. + #[sabi(last_prefix_field)] + pub new: extern "C" fn(RSender, PluginId) -> RResult, +} + +impl RootModule for PluginFactoryRef { + declare_root_module_statics! {PluginFactoryRef} + const BASE_NAME: &'static str = "plugin"; + const NAME: &'static str = "plugin"; + const VERSION_STRINGS: VersionStrings = package_version_strings!(); +} + +#[repr(u8)] +#[derive(Debug, StableAbi)] +pub enum Error { + /// A deserialization error produced when trying to deserialize json + /// as a particular command type. + UnsupportedCommand(RBox), + /// A deserialization error produced when trying to deserialize json + /// as a particular return value type. + UnsupportedReturnValue(RBox), +} diff --git a/crates/plugin_interface/src/model/command.rs b/crates/plugin_interface/src/model/command.rs new file mode 100644 index 0000000..dcb4760 --- /dev/null +++ b/crates/plugin_interface/src/model/command.rs @@ -0,0 +1,24 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#[repr(C)] +#[derive(Debug, Clone, PartialEq, StableAbi)] +pub struct PluginCommand { + pub from: PluginId, + pub to: PluginId, + pub command: RString, +} diff --git a/crates/plugin_interface/src/model/response.rs b/crates/plugin_interface/src/model/response.rs new file mode 100644 index 0000000..f78b232 --- /dev/null +++ b/crates/plugin_interface/src/model/response.rs @@ -0,0 +1,24 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#[repr(C)] +#[derive(Debug, Clone, PartialEq, Eq, StableAbi)] +pub struct PluginResponse { + pub from: PluginId, + pub to: PluginId, + pub response: RString, +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..75f3ea7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,32 @@ +version: '3.3' + +services: + core: + image: 'rust:1.66.1-slim' + volumes: + - ./target/debug:/usr/src/app:rw + environment: + - USER=core + ports: + - 7777:7777 + depends_on: + - database + restart: 'no' + working_dir: /usr/src/app + + command: bash -c "/usr/src/app/core" + + database: + image: postgres:latest + volumes: + - ./data/database:/var/lib/postgres/data + environment: + - POSTGRES_PASSWORD=unsecure + ports: + - 5432:5432 + healthcheck: + test: psql -U postgres -q -d postgres -c "SELECT 'ready';" + interval: 10s + timeout: 5s + retries: 5 + start_period: 5s diff --git a/documentation/http/get_media.hurl b/documentation/http/get_media.hurl new file mode 100644 index 0000000..5abaa98 --- /dev/null +++ b/documentation/http/get_media.hurl @@ -0,0 +1,5 @@ +GET http://127.0.0.1:7777/media +Authorization: FakeToken + +HTTP 200 + diff --git a/documentation/http/post_media.hurl b/documentation/http/post_media.hurl new file mode 100644 index 0000000..087391b --- /dev/null +++ b/documentation/http/post_media.hurl @@ -0,0 +1,12 @@ +POST http://127.0.0.1:7777/media +Authorization: FakeToken +Connection: Keep-Alive + +[MultipartFormData] +name: DSC_1234 +date_taken: 1985-04-12T23:20:50.52Z + +HTTP 200 + +[Asserts] +jsonpath "$.id" != null diff --git a/documentation/oidc.http b/documentation/oidc.http new file mode 100644 index 0000000..1d88aaa --- /dev/null +++ b/documentation/oidc.http @@ -0,0 +1,54 @@ +@host = 127.0.0.1 +@port = 7777 + +### +GET http://{{host}}:{{port}} + +### + +GET http://{{host}}:{{port}}/.well-known/openid-configuration HTTP/1.1 + +### + +GET http://{{host}}:{{port}}/oidc/authorize?response_type=id_token token&client_id=mobile-app&state=12345&code_challenge=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU&code_challenge_method=S256&redirect_uri=photosapp://authenticate&scope=profile&nonce=ABCDE + +### +GET http://{{host}}:{{port}}/master/login + +### +POST http://{{host}}:{{port}}/master/login +content-type: application/x-www-form-urlencoded + +username=user +&password=pass + +### + +@jwt = "" + +// Login User +POST http://{{host}}:{{port}}/api/v1/users/login +Content-Type: application/json + +{ + "username": "admin", + "password": "P@ssw0rd" +} + +//Response body +//{ +// "id": "1", +// "token": "1234567890" +//} + +// script part +@{ +const pattern = /"token": "(.*)"/; +jwt = $response.body.match(pattern, $1); +} + +// Twitter Seciton + +// GET list of Twitter Users, use jwt parsed from previous call +GET http://{{host}}:{{port}}/api/v1/twitterusers +Authorization: {{jwt}} \ No newline at end of file diff --git a/documentation/oidc.hurl b/documentation/oidc.hurl new file mode 100644 index 0000000..b5a2891 --- /dev/null +++ b/documentation/oidc.hurl @@ -0,0 +1,49 @@ +# Chain HTTP requests with curl and capture and verify the results. + +# API up and running +GET http://127.0.0.1:7777 + +HTTP 200 +[Asserts] +jsonpath "$.message" == "API running" + + +# OIDC discovery +GET http://127.0.0.1:7777/.well-known/openid-configuration + +HTTP 200 +[Asserts] +jsonpath "$.issuer" == "http://localhost:7777" +jsonpath "$.authorization_endpoint" == "http://localhost:7777/oidc/authorize" +jsonpath "$.token_endpoint" == "http://localhost:7777/oidc/token" +jsonpath "$.userinfo_endpoint" == "http://localhost:7777/oidc/userinfo" +jsonpath "$.jwks_uri" == "http://localhost:7777/oidc/jwk" +jsonpath "$.scopes_supported" count == 11 +jsonpath "$.scopes_supported" includes "email" +jsonpath "$.scopes_supported" includes "library.read" +jsonpath "$.scopes_supported" includes "library.append" +jsonpath "$.scopes_supported" includes "library.edit" +jsonpath "$.scopes_supported" includes "library.write" +jsonpath "$.scopes_supported" includes "library.share" + +# OIDC authorization flow with PKCE +GET http://127.0.0.1:7777/oidc/authorize?response_type=id_token%20token&client_id=mobile-app&state=12345&code_challenge=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU&code_challenge_method=S256&redirect_uri=photosapp://authenticate&scope=openid%20profile%20email%20phone%20library:read&nonce=ABCDE + +HTTP 303 +[Asserts] +header "Location" exists +header "Location" contains "login" +header "Location" == "/master/login" + + +GET http://localhost:7777/master/login +HTTP 200 + + + +POST http://localhost:7777/master/login +[FormParams] +username: toto +password: 12345678 + +HTTP 200 diff --git a/plugins/libphotos_network_plugin.d b/plugins/libphotos_network_plugin.d new file mode 100644 index 0000000..89b8d11 --- /dev/null +++ b/plugins/libphotos_network_plugin.d @@ -0,0 +1 @@ +/Users/stuermer/workspace/github/photos-network/plugin_interface/target/debug/libphotos_network_plugin.rlib: /Users/stuermer/workspace/github/photos-network/plugin_interface/src/lib.rs diff --git a/plugins/libphotos_network_plugin.rlib b/plugins/libphotos_network_plugin.rlib new file mode 100644 index 0000000..67cbf5d Binary files /dev/null and b/plugins/libphotos_network_plugin.rlib differ diff --git a/plugins/libplugin_metadata.d b/plugins/libplugin_metadata.d new file mode 100644 index 0000000..b302a68 --- /dev/null +++ b/plugins/libplugin_metadata.d @@ -0,0 +1 @@ +/Users/stuermer/workspace/github/photos-network/plugin_metadata/target/debug/libplugin_metadata.dylib: /Users/stuermer/workspace/github/photos-network/plugin_interface/src/lib.rs /Users/stuermer/workspace/github/photos-network/plugin_metadata/src/lib.rs diff --git a/plugins/libplugin_metadata.dylib b/plugins/libplugin_metadata.dylib new file mode 100755 index 0000000..ccb8587 Binary files /dev/null and b/plugins/libplugin_metadata.dylib differ diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 20932df..0000000 --- a/requirements.txt +++ /dev/null @@ -1,30 +0,0 @@ -aiohttp==3.7.1 -aiohttp_cors==0.7.0 -astral==1.10.1 -async_timeout==3.0.1 -attrs==19.3.0 -bcrypt==3.1.7 -certifi>=2020.6.20 -ciso8601==2.1.3 -httpx==0.16.1 -importlib-metadata==1.6.0;python_version<'3.8' -jinja2>=2.11.2 -PyJWT==1.7.1 -cryptography==3.2 -pip>=8.0.3 -python-slugify==4.0.1 -pytz>=2020.1 -pyyaml==5.3.1 -requests==2.25.0 -ruamel.yaml==0.15.100 -sqlalchemy==1.3.20 -voluptuous==0.12.0 -voluptuous-serialize==2.4.0 -yarl==1.4.2 -colorlog>=4.0.0 - -# Constrain urllib3 to ensure we deal with CVE-2019-11236 & CVE-2019-11324 -urllib3>=1.24.3 - -# Constrain httplib2 to protect against CVE-2020-11078 -httplib2>=0.18.0 diff --git a/requirements_test.txt b/requirements_test.txt deleted file mode 100644 index 612e69c..0000000 --- a/requirements_test.txt +++ /dev/null @@ -1,9 +0,0 @@ --r requirements.txt - -pytest-aiohttp==0.3.0 -pytest-cov==2.10.1 -pytest-test-groups==1.0.3 -pytest-sugar==0.9.4 -pytest-timeout==1.4.2 -pytest-xdist==2.1.0 -pytest==6.1.2 diff --git a/run_tests b/run_tests new file mode 100755 index 0000000..3b6f2e5 --- /dev/null +++ b/run_tests @@ -0,0 +1,5 @@ +#!/bin/bash + +cargo test --workspace --all-targets +cargo fmt --all -- --check +cargo clippy -- -D warnings diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 7cf470c..0000000 --- a/setup.cfg +++ /dev/null @@ -1,39 +0,0 @@ -[metadata] -DEBUG=True - -license = Apache License 2.0 -license_file = LICENSE.md -platforms = any -description = Open-source platform for photo management running on Python 3. -long_description = file: README.md -keywords = photos, self-hosted, google-photos, apple-photos, object-detection, face-recognition, face-detection -classifier = - Development Status :: 1 - Planning - Intended Audience :: End Users/Desktop - Intended Audience :: Developers - License :: OSI Approved :: Apache Software License - Operating System :: OS Independent - Programming Language :: Python :: 3.7 - Topic :: Communications :: File Sharing - -[flake8] -exclude = .venv,.git,.venv,build -doctests = True -# To work with Black -# E501: line too long -# W503: Line break occurred before a binary operator -# W504 line break after binary operator -ignore = - E501, - W503, - W504 - -[mypy] -python_version = 3.7 -show_error_codes = true -ignore_errors = true -follow_imports = silent -ignore_missing_imports = true -warn_incomplete_stub = true -warn_redundant_casts = true -warn_unused_configs = true diff --git a/setup.py b/setup.py deleted file mode 100644 index 9448be4..0000000 --- a/setup.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Photos.network setup script""" -from setuptools import setup - -from core import const - -import sys - -if sys.version_info < (3, 0): - print("{PROJECT_NAME} requires python version >= 3.0") - sys.exit(1) - -setup( - name="core", - version=const.CORE_VERSION, - description="The core system for photos.network", - long_description="The core system for photos.network to manage components.", - author="The Photos Network Authors", - author_email="devs@photos.network", - url="https://dev.photos.network/core", - license="Apache License 2.0", - classifiers=[ - "Intended Audience :: End Users/Desktop", - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Operating System :: OS Independent", - "Topic :: Software Development :: Libraries :: Python Modules", - "Topic :: Scientific/Engineering :: Atmospheric Science", - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Programming Language :: Python :: 3.8", - ], - keywords=["docker", "photos-network", "api"], - zip_safe=False, - platforms="any", - packages=[ - "core", - "core.addons", - "core.authentication", - "core.authorization", - "core.utils", - "core.webserver", - ], - entry_points={"console_scripts": ["core = core.__main__:main"]}, - include_package_data=True, - package_data={ - "core": ["addons/**/*.py"], - } -) diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..3a9a7af --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,273 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Photos.network ยท A privacy first photo storage and sharing service. +//! +//! The core application is responsible for main tasks like: +//! * Authentication (validate the identity of users) +//! * Authorization (handle access privileges of resources like photos or albums) +//! * Plugins (manage and trigger plugins) +//! * Persistency (read / write data) +//! * Task Processing (keep track of running tasks) +//! +//! See also the following crates +//! * [Authentication](../oauth_authentication/index.html) + +use std::fs::{self, OpenOptions}; +use std::net::SocketAddr; + +use abi_stable::external_types::crossbeam_channel; +use abi_stable::std_types::RResult::{RErr, ROk}; +use accounts::api::router::AccountsApi; +use anyhow::Result; +use axum::extract::DefaultBodyLimit; +use axum::routing::{get, head}; +use axum::{Json, Router}; +use common::auth::user::User; +use common::database::Database; +use common::ApplicationState; +use database::sqlite::SqliteDatabase; +use media::api::router::MediaApi; +use oauth_authentication::AuthenticationManager; +use oauth_authorization_server::client::Client; +use oauth_authorization_server::config::ConfigRealm; +use oauth_authorization_server::config::ServerConfig; +use oauth_authorization_server::state::ServerState; +use oauth_authorization_server::AuthorizationServerManager; +use serde::{Deserialize, Serialize}; +use sqlx::types::time::OffsetDateTime; +use std::path::Path; +use tower_http::cors::CorsLayer; +use tower_http::services::ServeDir; +use tower_http::trace::TraceLayer; +use tracing::{debug, error, info}; +use tracing_subscriber::{fmt, layer::SubscriberExt}; + +use common::config::configuration::Configuration; +use plugin::plugin_manager::PluginManager; + +pub mod plugin; + +const CONFIG_PATH: &str = "./config/core.json"; +const DATA_PATH: &str = "./data"; +const PLUGIN_PATH: &str = "./plugins"; +const LOGGING_PATH: &str = "./logs"; + +/// starts the core applications server, reading the user configuration, connecting to databases and spinning up the REST API. +pub async fn start_server() -> Result<()> { + // enable logging + let file_appender = tracing_appender::rolling::daily(LOGGING_PATH, "core"); + let (file_writer, _guard) = tracing_appender::non_blocking(file_appender); + tracing::subscriber::set_global_default( + fmt::Subscriber::builder() + // subscriber configuration + .with_max_level(tracing::Level::TRACE) + .with_target(false) + .finish() + // add additional writers + .with( + fmt::Layer::default() + .with_ansi(false) + .with_writer(file_writer), + ), + ) + .expect("Unable to set global tracing subscriber"); + + info!("Photos.network core is starting..."); + + // create mandatory application directories if necessary + fs::create_dir_all("data")?; + fs::create_dir_all("config")?; + fs::create_dir_all("plugins")?; + + // read config file + let configuration = Configuration::new(CONFIG_PATH).expect("Could not parse configuration!"); + debug!("Configuration: {}", configuration); + + // init database + //let db = PostgresDatabase::new("postgres://postgres:unsecure@localhost:5432/postgres").await; + + let _file = OpenOptions::new() + .write(true) + .create_new(true) + .open("data/core.sqlite3"); + + let mut db = SqliteDatabase::new("data/core.sqlite3").await; + + { + let _ = db.setup().await; + } + + let users = db.get_users().await; + if users.unwrap().is_empty() { + info!("No user found, create a default admin user. Please check `data/credentials.txt` for details."); + let default_user = "photo@photos.network"; + let default_pass = "unsecure"; + let path = Path::new(DATA_PATH).join("credentials.txt"); + let _ = fs::write(path, format!("{}\n{}", default_user, default_pass)); + // let mut output = File::create(path)?; + // let line = "hello"; + // write!(output, "{}\n{}", default_user, default_pass); + + let user = User { + uuid: "".to_string(), + email: default_user.to_string(), + password: Some(default_pass.to_string()), + lastname: Some("Admin".to_string()), + firstname: Some("".to_string()), + is_locked: false, + created_at: OffsetDateTime::now_utc(), + updated_at: None, + last_login: None, + }; + let _ = db.clone().create_user(&user).await; + } + + // init application state + //let mut app_state = ApplicationState::::new(configuration.clone(), db); + let mut app_state = ApplicationState::::new(configuration.clone(), db); + + let cfg = ServerConfig { + listen_addr: configuration.internal_url.to_owned(), + domain: configuration.external_url.to_owned(), + use_ssl: true, + realm_keys_base_path: Path::new("config").to_path_buf(), + realms: vec![ConfigRealm { + name: String::from("master"), + domain: Some(configuration.external_url.to_owned()), + clients: vec![Client { + id: String::from("mobile-app"), + secret: None, + redirect_uri: String::from("photosapp://authenticate"), + }], + }], + }; + let server = ServerState::new(cfg)?; + + // TODO: check if `data/credentials.txt` still exists and stop immediately! + let mut router = Router::new() + // favicon + .nest_service("/assets", ServeDir::new("src/api/static")) + + // health check + .route("/", get(status)) + .route("/", head(status)) + + // Media items + .nest("/", MediaApi::routes(app_state.clone()).await) + + // OAuth 2.0 Authentication + .nest("/", AuthenticationManager::routes()) + + // OAuth Authorization Server + .nest("/", AuthorizationServerManager::routes(server)) + + // Account management + .nest("/", AccountsApi::routes()) + .layer(TraceLayer::new_for_http()) + // grant all CORS OPTIONS requests + .layer(CorsLayer::very_permissive()) + + // allow to receive bodies larger than the default limit of 2MB + .layer(DefaultBodyLimit::disable()) + + // add database connection pool + //.with_state(pool) + + + // TODO: share app state with routes + // .with_state(Arc::new(app_state)) + ; + app_state.router = Some(router); + + // initialize plugin manager + let mut plugin_manager = PluginManager::new( + configuration.clone(), + PLUGIN_PATH.to_string(), + &mut app_state, + )?; + + match plugin_manager.init().await { + Ok(_) => info!("PluginManager: initialization succed."), + Err(e) => error!("PluginManager: initialization failed! {}", e), + } + plugin_manager.trigger_on_init().await; + + // trigger `on_core_init` on all loaded plugins + for (plugin_id, factory) in app_state.plugins { + info!("Plugin '{}' found in AppState.", plugin_id); + + let plugin_constructor = factory.new(); + + let (sender, _receiver) = crossbeam_channel::unbounded(); + + let plugin = match plugin_constructor(sender.clone(), plugin_id.clone()) { + ROk(x) => x, + RErr(_) => { + // TODO: handle error + error!( + "Not able to trigger plugin constructor for '{}'!", + plugin_id + ); + //plugin_new_errs.push((plugin_id.clone(), e)); + continue; + } + }; + + plugin.on_core_init(); + } + + // TODO: add routes lazy (e.g. from plugin) + router = app_state + .router + .unwrap() + .route("/test", get(|| async { "" })); + + // task::spawn_blocking(move || { + // tracing::debug!("setup Authentication Manager..."); + // let manager = AuthenticationManager::new(); + // let nonce = AuthenticationManager::create_authorization_url( + // manager::client, + // manager::pkce_challenge, + // ); + // }).await?; + + // start server with all routes + let addr: SocketAddr = SocketAddr::from(([0, 0, 0, 0], 7777)); + tracing::debug!("listening on {}", addr); + axum::Server::bind(&addr) + .serve(router.into_make_service()) + .await + .unwrap(); + + Ok(()) +} + +async fn status() -> Json { + // TODO: get app state + + // TODO: print loaded plugins from appState + let status = Status { + message: String::from("API running"), + }; + Json(status) +} + +#[derive(Debug, Serialize, Deserialize)] +struct Status { + message: String, +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..d3c7813 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,29 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use core::start_server; +use std::process; + +/// the `#[tokio::main]` macro initializes a runtime instance and executes the main in it. +/// See: https://tokio.rs/tokio/tutorial/hello-tokio#async-main-function +#[tokio::main] +async fn main() { + if let Err(e) = start_server().await { + eprintln!("error: {:#}", e); + process::exit(1); + } +} diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs new file mode 100644 index 0000000..e7201b2 --- /dev/null +++ b/src/plugin/mod.rs @@ -0,0 +1,21 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! The PluginManager will setup & initialize configured and available plugins. +//! +//! +pub mod plugin_manager; diff --git a/src/plugin/plugin_manager.rs b/src/plugin/plugin_manager.rs new file mode 100644 index 0000000..4bb7cfe --- /dev/null +++ b/src/plugin/plugin_manager.rs @@ -0,0 +1,103 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +use std::path::PathBuf; + +use abi_stable::library::{lib_header_from_path, LibrarySuffix, RawLibrary}; + +use anyhow::Result; +use common::{config::configuration::Configuration, ApplicationState}; + +use core_extensions::SelfOps; +use database::sqlite::SqliteDatabase; +use photos_network_plugin::{PluginFactoryRef, PluginId}; +use tracing::{debug, error, info}; + +pub struct PluginManager<'a> { + config: Configuration, + path: String, + state: &'a mut ApplicationState, +} + +impl<'a> PluginManager<'a> { + pub fn new( + config: Configuration, + path: String, + state: &'a mut ApplicationState, + ) -> Result { + Ok(Self { + config, + path, + state, + }) + } + + pub async fn init<'b>(&mut self) -> Result<()> { + info!( + "Found {} plugin(s) in the configuration.", + self.config.plugins.len() + ); + + for configured_plugin in &self.config.plugins { + info!( + "Plugin '{}' found in the configuration file.", + configured_plugin.name + ); + + let mut base_name = String::from("plugin_").to_owned(); + let plugin_name = configured_plugin.name.to_lowercase().to_owned(); + base_name.push_str(&plugin_name); + let plugin_dir: PathBuf = self.path.clone().into_::(); + + let plugin_path: PathBuf = + RawLibrary::path_in_directory(&plugin_dir, &base_name, LibrarySuffix::NoSuffix); + + if plugin_path.exists() { + debug!( + "Plugin '{}' also found in the `plugins` directory", + plugin_name + ); + + debug!("Try to load plugin '{}'...", plugin_name); + let header = lib_header_from_path(&plugin_path)?; + let res = header.init_root_module::(); + + let root_module = match res { + Ok(x) => x, + Err(e) => { + error!("Could not init plugin! {}", e); + continue; + } + }; + + let mut _loaded_libraries = vec![PluginId::from(plugin_name.clone())]; + + // TODO: insert loaded plugin instead? + self.state + .plugins + .insert(PluginId::from(plugin_name), root_module); + } + } + + Ok(()) + } + + pub async fn trigger_on_init(&mut self) { + // self.state.router.as_mut().unwrap().route("/foo", get( || async { "It's working!" } )); + // ERROR: move occurs because value has type `Router`, which does not implement the `Copy` trait + } +} diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index 5882ef5..0000000 --- a/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests for Photos.network""" \ No newline at end of file diff --git a/tests/addons/api/__init__.py b/tests/addons/api/__init__.py deleted file mode 100644 index 6e7d4fc..0000000 --- a/tests/addons/api/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Tests for the api addon.""" diff --git a/tests/addons/api/test_init.py b/tests/addons/api/test_init.py deleted file mode 100644 index 16088b5..0000000 --- a/tests/addons/api/test_init.py +++ /dev/null @@ -1,30 +0,0 @@ -"""Test the default api implementation.""" -import asyncio -import os - -import pytest - -from core.core import ApplicationCore, CoreState -from core.webserver import status - - -@pytest.fixture -def mock_api_client(): - """Start the HTTP component and return admin API client.""" - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - core = ApplicationCore() - core.config.internal_url = "" - core.config.external_url = "" - core.config.data_dir = os.path.join(os.path.dirname(__file__), "resources", "data") - core.state = CoreState.running - core.start() - - return loop.run_until_complete(core) - - -async def test_api_get_non_existing_state(mock_api_client): - """Test if the debug interface allows us to get a state.""" - resp = await mock_api_client.get("/api/states/does_not_exist") - assert resp.status == status.HTTP_NOT_FOUND diff --git a/tests/api/authentication/signin.rs b/tests/api/authentication/signin.rs new file mode 100644 index 0000000..733866c --- /dev/null +++ b/tests/api/authentication/signin.rs @@ -0,0 +1,56 @@ +/* Photos.network ยท A privacy first photo storage and sharing service for fediverse. + * Copyright (C) 2020 Photos network developers + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +//! Test authentication behaviour like invalid user or password +//! + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + let a = 3; + let b = 1 + 1; + + assert_eq!(a, b, "we are testing addition with {} and {}", a, b); + } + + #[tokio::test] + async fn authenticate_without_user() { + // given + let test_state = spawn_app().await; + let client = test_state.api_client; + let input = serde_json::json!({"password": "secret"}); + + // when + let response = client + .post(&format!("{}/oauth/authorize", &test_state.app_address)) + .form(&input) + .send() + .await + .expect("authorization request failed!"); + + // then + assert_eq!( + response.status().as_u16(), + 422, + "{} returns client error status", + "no username" + ); + } +} diff --git a/tests/test_config.py b/tests/test_config.py deleted file mode 100644 index 6b20896..0000000 --- a/tests/test_config.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Test config utils.""" -import os -from unittest import mock - -import pytest - - -# async def test_create_default_config(): -# """Test creation of default config.""" -# await config_util.async_create_default_config() -# -# assert os.path.isfile(YAML_PATH) -# assert os.path.isfile(SECRET_PATH) -# assert os.path.isfile(VERSION_PATH) -# assert os.path.isfile(GROUP_PATH) -# assert os.path.isfile(AUTOMATIONS_PATH) diff --git a/tests/test_webserver.py b/tests/test_webserver.py deleted file mode 100644 index bc3d233..0000000 --- a/tests/test_webserver.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Test webserver implementation.""" -from aiohttp import web - - -async def hello(request): - return web.Response(text='Hello, world') - - -async def test_hello(aiohttp_client, loop): - app = web.Application() - app.router.add_get('/', hello) - client = await aiohttp_client(app) - resp = await client.get('/') - assert resp.status == 200 - text = await resp.text() - assert 'Hello, world' in text diff --git a/vscode.gif b/vscode.gif new file mode 100644 index 0000000..e27e86d Binary files /dev/null and b/vscode.gif differ