Compare commits

..

4 Commits

47 changed files with 830 additions and 2423 deletions

View File

@ -1,4 +1,4 @@
**/target/
/target
tarpaulin-report.html
.env
cobertura.xml

View File

@ -1,82 +0,0 @@
pipeline:
backend:
image: rust
environment:
- DATABASE_URL=postgres://postgres:password@database:5432/postgres
commands:
- curl -fsSL https://deb.nodesource.com/setup_16.x | bash - &&\
- apt update && apt-get -y --no-install-recommends install nodejs tar gpg curl wget
- rustup component add rustfmt
- rustup component add clippy
# rewrite conducotr configuration
- sed -i 's%url = "http:\/\/localhost:5000"%url = "http:\/\/librepages-conductor:5000"%' config/default.toml
- make dev-env
- make migrate
- make lint
- make test
- make release
build_docker_img:
image: plugins/docker
when:
event: [pull_request]
settings:
dry_run: true
repo: realaravinth/librepages
tags: latest
build_and_publish_docker_img:
image: plugins/docker
when:
event: [push, tag, deployment]
settings:
username: realaravinth
password:
from_secret: DOCKER_TOKEN
repo: realaravinth/librepages
tags: latest
# build_publisher_docker_img:
# image: plugins/docker
# when:
# event: [push, tag, deployment]
# settings:
# dry_run: true
# dockerfile: scripts/publish-bins-docker
# purge: false
# repo: realaravinth/librepages-publisher
# tags: latest
#
publish_bins:
image: rust
when:
event: [push, tag, deployment]
commands:
- apt update
- apt-get -y --no-install-recommends install gpg tar curl wget
- echo -n "$RELEASE_BOT_GPG_SIGNING_KEY" | gpg --batch --import --pinentry-mode loopback
- scripts/bin-publish.sh publish master latest $DUMBSERVE_PASSWORD
secrets: [RELEASE_BOT_GPG_SIGNING_KEY, DUMBSERVE_PASSWORD, GPG_PASSWORD]
services:
database:
image: postgres
environment:
- POSTGRES_PASSWORD=password
librepages-conductor:
image: realaravinth/librepages-conductor
command: conductor serve
environment:
- LPCONDUCTOR_SERVER__PROXY_HAS_TLS=false
- LPCONDUCTOR_DEBUG=false
- LPCONDUCTOR_CONDUCTOR=dummy
- LPCONDUCTOR_SERVER_URL_PREFIX=""
- LPCONDUCTOR_SERVER_DOMAIN="librepages.test"
- LPCONDUCTOR_SERVER_IP=0.0.0.0
- LPCONDUCTOR_SERVER_PROXY_HAS_TLS=false
- LPCONDUCTOR_SERVER_PORT=7000
- LPCONDUCTOR_SOURCE_CODE=https://example.org
- LPCONDUCTOR_CREDS_USERNAME="librepages_api"
- LPCONDUCTOR_CREDS_PASSWORD="longrandomlygeneratedpassword"
- PORT=5000

183
Cargo.lock generated
View File

@ -42,7 +42,7 @@ dependencies = [
"actix-service",
"actix-utils",
"ahash",
"base64 0.13.1",
"base64",
"bitflags",
"brotli",
"bytes",
@ -339,9 +339,9 @@ checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"
[[package]]
name = "async-trait"
version = "0.1.60"
version = "0.1.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d1d8ab452a3936018a687b20e6f7cf5363d713b732b8884001317b0e48aa3"
checksum = "31e6e93155431f3931513b243d371981bb2770112b370c82745a1d19d2f99364"
dependencies = [
"proc-macro2",
"quote",
@ -380,12 +380,6 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ea22880d78093b0cbe17c89f64a7d457941e65759157ec6cb31a31d652b05e5"
[[package]]
name = "bitflags"
version = "1.3.2"
@ -486,9 +480,9 @@ dependencies = [
[[package]]
name = "cc"
version = "1.0.78"
version = "1.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d"
checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4"
dependencies = [
"jobserver",
]
@ -581,12 +575,12 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "cookie"
version = "0.16.2"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb"
checksum = "344adc371239ef32293cb1c4fe519592fcf21206c79c02854320afcdf3ab4917"
dependencies = [
"aes-gcm",
"base64 0.20.0",
"base64",
"hkdf",
"hmac",
"percent-encoding",
@ -1348,9 +1342,9 @@ dependencies = [
[[package]]
name = "itoa"
version = "1.0.5"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc"
[[package]]
name = "jobserver"
@ -1413,7 +1407,7 @@ dependencies = [
[[package]]
name = "libconfig"
version = "0.1.0"
source = "git+https://git.batsense.net/librepages/libconfig#f5c8c7a73744b844075a2af3fae88465e29a434f"
source = "git+https://git.batsense.net/librepages/libconfig#f54290c4bae26b51a4945e0bf812e2b99856963b"
dependencies = [
"serde",
]
@ -1432,52 +1426,6 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "librepages"
version = "0.1.0"
dependencies = [
"actix-auth-middleware",
"actix-http",
"actix-identity",
"actix-rt",
"actix-web",
"actix-web-codegen-const-routes",
"argon2-creds",
"cache-buster",
"clap",
"config",
"derive_more",
"futures",
"git2",
"hex",
"hmac",
"lazy_static",
"libconductor",
"libconfig",
"mime",
"mime_guess",
"mktemp",
"num_cpus",
"num_enum",
"pretty_env_logger",
"rand",
"reqwest",
"rust-embed",
"serde",
"serde_json",
"serde_yaml",
"sha2",
"sqlx",
"tera",
"tokio",
"toml",
"tracing",
"tracing-actix-web",
"url",
"urlencoding",
"uuid 1.2.2",
]
[[package]]
name = "libssh2-sys"
version = "0.2.23"
@ -1793,6 +1741,49 @@ version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee"
[[package]]
name = "pages"
version = "0.1.0"
dependencies = [
"actix-auth-middleware",
"actix-http",
"actix-identity",
"actix-rt",
"actix-web",
"actix-web-codegen-const-routes",
"argon2-creds",
"cache-buster",
"clap",
"config",
"derive_more",
"futures",
"git2",
"lazy_static",
"libconductor",
"libconfig",
"mime",
"mime_guess",
"mktemp",
"num_cpus",
"num_enum",
"pretty_env_logger",
"rand",
"reqwest",
"rust-embed",
"serde",
"serde_json",
"serde_yaml",
"sqlx",
"tera",
"tokio",
"toml",
"tracing",
"tracing-actix-web",
"url",
"urlencoding",
"uuid 1.2.2",
]
[[package]]
name = "parking_lot"
version = "0.11.2"
@ -1843,9 +1834,9 @@ dependencies = [
[[package]]
name = "paste"
version = "1.0.11"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d01a5bd0424d00070b0098dd17ebca6f961a959dead1dbcbbbc1d1cd8d3deeba"
checksum = "cf1c2c742266c2f1041c914ba65355a83ae8747b05f208319784083583494b4b"
[[package]]
name = "pathdiff"
@ -2050,9 +2041,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.49"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5"
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
dependencies = [
"unicode-ident",
]
@ -2065,9 +2056,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
version = "1.0.23"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
dependencies = [
"proc-macro2",
]
@ -2154,7 +2145,7 @@ version = "0.11.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68cc60575865c7831548863cc02356512e3f1dc2f3f82cb837d7fc4cc8f3c97c"
dependencies = [
"base64 0.13.1",
"base64",
"bytes",
"encoding_rs",
"futures-core",
@ -2206,7 +2197,7 @@ version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a"
dependencies = [
"base64 0.13.1",
"base64",
"bitflags",
"serde",
]
@ -2217,7 +2208,7 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b50162d19404029c1ceca6f6980fe40d45c8b369f6f44446fa14bb39573b5bb9"
dependencies = [
"base64 0.13.1",
"base64",
"blake2b_simd",
"constant_time_eq",
"crossbeam-utils",
@ -2294,14 +2285,14 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0864aeff53f8c05aa08d86e5ef839d3dfcf07aeba2db32f12db0ef716e87bd55"
dependencies = [
"base64 0.13.1",
"base64",
]
[[package]]
name = "ryu"
version = "1.0.12"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde"
checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09"
[[package]]
name = "same-file"
@ -2363,24 +2354,24 @@ dependencies = [
[[package]]
name = "semver"
version = "1.0.16"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a"
checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4"
[[package]]
name = "serde"
version = "1.0.151"
version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fed41fc1a24994d044e6db6935e69511a1153b52c15eb42493b26fa87feba0"
checksum = "e326c9ec8042f1b5da33252c8a37e9ffbd2c9bef0155215b6e6c80c790e05f91"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.151"
version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "255abe9a125a985c05190d687b320c12f9b1f0b99445e608c21ba0782c719ad8"
checksum = "42a3df25b0713732468deadad63ab9da1f1fd75a48a15024b50363f128db627e"
dependencies = [
"proc-macro2",
"quote",
@ -2389,9 +2380,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.91"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883"
checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db"
dependencies = [
"itoa",
"ryu",
@ -2412,9 +2403,9 @@ dependencies = [
[[package]]
name = "serde_yaml"
version = "0.9.16"
version = "0.9.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92b5b431e8907b50339b51223b97d102db8d987ced36f6e4d03621db9316c834"
checksum = "6d232d893b10de3eb7258ff01974d6ee20663d8e833263c99409d4b13a0209da"
dependencies = [
"indexmap",
"itoa",
@ -2520,7 +2511,7 @@ checksum = "dcbc16ddba161afc99e14d1713a453747a2b07fc097d2009f4c300ec99286105"
dependencies = [
"ahash",
"atoi",
"base64 0.13.1",
"base64",
"bitflags",
"byteorder",
"bytes",
@ -2650,9 +2641,9 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"
[[package]]
name = "syn"
version = "1.0.107"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5"
checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
dependencies = [
"proc-macro2",
"quote",
@ -2717,18 +2708,18 @@ checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
[[package]]
name = "thiserror"
version = "1.0.38"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"
checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.38"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"
checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
dependencies = [
"proc-macro2",
"quote",
@ -2996,9 +2987,9 @@ checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992"
[[package]]
name = "unicode-ident"
version = "1.0.6"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]]
name = "unicode-normalization"
@ -3033,9 +3024,9 @@ dependencies = [
[[package]]
name = "unsafe-libyaml"
version = "0.2.5"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc7ed8ba44ca06be78ea1ad2c3682a43349126c8818054231ee6f4748012aed2"
checksum = "c1e5fa573d8ac5f1a856f8d7be41d390ee973daf97c806b2c1a465e4e1406e68"
[[package]]
name = "untrusted"

View File

@ -1,12 +1,12 @@
[package]
name = "librepages"
name = "pages"
version = "0.1.0"
edition = "2021"
build = "build.rs"
homepage = "https://git.batsense.net/LibrePages/librepages"
repository = "https://git.batsense.net/LibrePages/librepages"
documentation = "https://git.batsense.net/LibrePages/librepages"
readme = "https://git.batsense.net/LibrePages/librepages/blob/master/README.md"
homepage = "https://github.com/realaravinth/pages"
repository = "https://github.com/realaravinth/pages"
documentation = "https://github.con/realaravinth/pages"
readme = "https://github.com/realaravinth/pages/blob/master/README.md"
license = "AGPLv3 or later version"
authors = ["realaravinth <realaravinth@batsense.net>"]
@ -19,7 +19,7 @@ actix-identity = "0.4.0"
actix-rt = "2"
actix-web-codegen-const-routes = { version = "0.1.0", tag = "0.1.0", git = "https://github.com/realaravinth/actix-web-codegen-const-routes" }
argon2-creds = { branch = "master", git = "https://github.com/realaravinth/argon2-creds"}
sqlx = { version = "0.6.2", features = ["runtime-actix-rustls", "postgres", "time", "offline", "json", "uuid"] }
sqlx = { version = "0.6.1", features = ["runtime-actix-rustls", "postgres", "time", "offline", "json", "uuid"] }
clap = { version = "3.2.20", features = ["derive"]}
libconfig = { version = "0.1.0", git = "https://git.batsense.net/librepages/libconfig" }
libconductor = { version = "0.1.0", git = "https://git.batsense.net/librepages/conductor/" }
@ -53,9 +53,6 @@ toml = "0.5.9"
serde_yaml = "0.9.14"
uuid = { version = "1.2.2", features = ["serde"] }
reqwest = { version = "0.11.13", features = ["json"] }
sha2 = "0.10.6"
hmac = "0.12.1"
hex= "0.4.3"
[dependencies.cache-buster]
git = "https://github.com/realaravinth/cache-buster"

View File

@ -19,11 +19,11 @@ RUN cd utils/cache-bust && cargo run
RUN cargo build --release
FROM debian:bullseye-slim
#RUN useradd -ms /bin/bash -u 1000 librepages
#RUN mkdir -p /var/www/librepages && chown librepages /var/www/librepages
#RUN useradd -ms /bin/bash -u 1000 pages
#RUN mkdir -p /var/www/pages && chown pages /var/www/pages
RUN apt-get update && apt-get install -y ca-certificates
COPY scripts/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
COPY --from=rust /src/target/release/librepages /usr/local/bin/
COPY --from=rust /src/target/release/pages /usr/local/bin/
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

View File

@ -24,20 +24,21 @@ coverage: ## Generate HTML code coverage
dev-env: ## Download development dependencies
npm install
cargo fetch
./scripts/conductor.sh
doc: ## Prepare documentation
cargo doc --no-deps --workspace --all-features
docker: ## Build docker images
docker build \
-t realaravinth/librepages:master \
-t realaravinth/librepages:latest \
-t realaravinth/librepages:0.1.0 .
-t realaravinth/pages:master \
-t realaravinth/pages:latest \
-t realaravinth/pages:0.1.0 .
docker-publish: docker ## Build and publish docker images
docker push realaravinth/librepages:master
docker push realaravinth/librepages:latest
docker push realaravinth/librepages:0.1.0
docker push realaravinth/pages:master
docker push realaravinth/pages:latest
docker push realaravinth/pages:0.1.0
lint: ## Lint codebase
cargo fmt -v --all -- --emit files
@ -46,7 +47,7 @@ lint: ## Lint codebase
migrate: ## run migrations
$(call cache_bust)
unset DATABASE_URL && cargo build
DATABASE_URL=${DATABASE_URL} cargo run -- migrate
cargo run -- migrate
release: ## Release build
$(call cache_bust)

View File

@ -5,8 +5,10 @@
**Auto-deploy static websites from git repositories**
</p>
[![status-badge](https://ci.batsense.net/api/badges/LibrePages/librepages/status.svg)](https://ci.batsense.net/LibrePages/librepages)
[![Build](https://github.com/realaravinth/pages/actions/workflows/linux.yml/badge.svg)](https://github.com/realaravinth/pages/actions/workflows/linux.yml)
[![dependency status](https://deps.rs/repo/github/realaravinth/pages/status.svg)](https://deps.rs/repo/github/realaravinth/pages)
[![codecov](https://codecov.io/gh/realaravinth/pages/branch/master/graph/badge.svg)](https://codecov.io/gh/realaravinth/pages)
</div>

View File

@ -1,7 +1,7 @@
debug = true
allow_registration = true
# source code of your copy of pages server.
source_code = "https://git.batsense.net/LibrePages/pages"
source_code = "https://github.com/realaravinth/pages"
support_email = "support@librepages.example.org"
conductors = [
{ username = "librepages_api", api_key = "longrandomlygeneratedpassword", url = "http://localhost:5000"}

View File

@ -3,10 +3,10 @@
The process is tedious, most of this will be automated with a script in
the future.
## 1. Create new user for running `librepages`:
## 1. Create new user for running `pages`:
```bash
sudo useradd -b /srv -m -s /usr/bin/zsh librepages
sudo useradd -b /srv -m -s /usr/bin/zsh pages
```
## 2. Install Runtime dependencies
@ -19,11 +19,11 @@ On Debian-based systems, run:
sudo apt install nginx
```
## 3. Build `librepages`
## 3. Build `Pages`
### i. Install Build Dependencies
To build `librepages`, you need the following dependencies:
To build `pages`, you need the following dependencies:
1. [Git](https://packages.debian.org/bullseye/git)
2. [pkg-config](https://packages.debian.org/bullseye/pkg-config)
@ -71,23 +71,23 @@ Install binary and copy demo configuration file into default configuration
lookup path(`/etc/static-pages/config.toml`)
```bash
sudo cp ./target/release/librepages /usr/local/bin/ && \
sudo cp ./target/release/pages /usr/local/bin/ && \
sudo mkdir /etc/static-pages && \
sudo cp config/default.toml /etc/static-pages/config.toml
```
## 4. Systemd service configuration:
### i. Copy the following to `/etc/systemd/system/librepages.service`:
### i. Copy the following to `/etc/systemd/system/pages.service`:
```systemd
[Unit]
Description=librepages: Auto-deploy static websites from git repositories
Description=pages: Auto-deploy static websites from git repositories
[Service]
Type=simple
User=librepages
ExecStart=/usr/local/bin/librepages
User=pages
ExecStart=/usr/local/bin/pages
Restart=on-failure
RestartSec=1
MemoryDenyWriteExecute=true
@ -107,13 +107,13 @@ WantedBy=multi-user.target
```bash
sudo systemctl daemon-reload && \
sudo systemctl enable librepages && \ # Auto startup during boot
sudo systemctl start librepages
sudo systemctl enable pages && \ # Auto startup during boot
sudo systemctl start pages
```
## 5. Optionally configure Nginx to reverse proxy requests to LibrePages
## 5. Optionally configure Nginx to reverse proxy requests to Pages
**NOTE: This sections includes instructions to reverse proxy requests to
LibrePages API, not the websites managed by librepages.**
Pages API, not the websites managed by Pages.**
See [here](../../config/librepages-nginx-config) for sample Nginx configuration.
See [here](../../config/pages-nginx-config) for sample Nginx configuration.

View File

@ -0,0 +1,6 @@
CREATE TABLE IF NOT EXISTS librepages_gitea_instances (
url VARCHAR(3000) NOT NULL UNIQUE,
client_id TEXT NOT NULL,
client_secret TEXT NOT NULL,
ID SERIAL PRIMARY KEY NOT NULL
);

View File

@ -0,0 +1,9 @@
-- Add migration script here
CREATE TABLE IF NOT EXISTS librepages_gitea_oidc_configuration (
gitea_instance INTEGER NOT NULL references librepages_gitea_instances(ID) ON DELETE CASCADE,
authorization_endpoint VARCHAR(3000) NOT NULL UNIQUE,
token_endpoint VARCHAR(3000) NOT NULL UNIQUE,
userinfo_endpoint VARCHAR(3000) NOT NULL UNIQUE,
introspection_endpoint VARCHAR(3000) NOT NULL UNIQUE,
ID SERIAL PRIMARY KEY NOT NULL
)

View File

@ -1,15 +0,0 @@
CREATE TABLE IF NOT EXISTS librepages_forgejo_webhooks (
forgejo_webhook_secret VARCHAR(40) NOT NULL UNIQUE,
forgejo_url VARCHAR(3000) NOT NULL,
auth_token VARCHAR(40) NOT NULL UNIQUE,
ID SERIAL PRIMARY KEY NOT NULL,
owned_by INTEGER NOT NULL references librepages_users(ID) ON DELETE CASCADE
);
CREATE UNIQUE INDEX librepages_forgejo_webhook_auth_token_index ON librepages_forgejo_webhooks(auth_token);
CREATE TABLE IF NOT EXISTS librepages_forgejo_webhook_site_mapping (
site_id INTEGER NOT NULL references librepages_sites(ID) ON DELETE CASCADE,
forgejo_webhook_id INTEGER NOT NULL references librepages_forgejo_webhooks(ID) ON DELETE CASCADE,
UNIQUE(site_id, forgejo_webhook_id)
);

View File

@ -33,15 +33,14 @@ FILENAME="$NAME-$2-linux-amd64"
TARBALL=$FILENAME.tar.gz
TARGET_DIR="$TMP_DIR/$FILENAME/"
mkdir -p $TARGET_DIR
DOCKER_IMG="realaravinth/librepages:$3"
DOCKER_IMG="realaravinth/pages:$3"
get_bin(){
echo "[*] Grabbing binary"
#container_id=$(docker create $DOCKER_IMG)
#docker cp $container_id:/usr/local/bin/pages $TARGET_DIR/
#docker rm -v $container_id
cp target/release/librepages $TARGET_DIR
container_id=$(docker create $DOCKER_IMG)
docker cp $container_id:/usr/local/bin/pages $TARGET_DIR/
docker rm -v $container_id
}
copy() {

View File

@ -15,4 +15,4 @@ else
useradd --uid $USER_ID -b /home -m -s /bin/bash $LIBREPAGES_USER
fi
su $LIBREPAGES_USER -c 'librepages'
su $LIBREPAGES_USER -c 'pages'

View File

@ -1,14 +0,0 @@
FROM realaravinth/librepages:latest as base
RUN echo foo
FROM debian:bullseye-slim
RUN apt update
RUN apt-get -y --no-install-recommends install gpg tar curl wget
WORKDIR /src
COPY --from=base /usr/local/bin/librepages .
COPY . .
ARG RELEASE_BOT_GPG_SIGNING_KEY
RUN echo -n "$RELEASE_BOT_GPG_SIGNING_KEY"
RUN echo -n "$RELEASE_BOT_GPG_SIGNING_KEY" | gpg --batch --import --pinentry-mode loopback
env GPG_PASSWORD=$GPG_PASSWORD
RUN /src/scripts/bin-publish.sh publish master latest $DUMBSERVE_PASSWORD

View File

@ -1,783 +1,3 @@
{
"db": "PostgreSQL",
"10d30dade86d79210203bdbce4b6db5d2aa446b0f88ca834771ecbbe11be51fb": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "UPDATE librepages_sites SET deleted = true\n WHERE hostname = ($1)\n AND owned_by = ( SELECT ID FROM librepages_users WHERE name = $2);\n "
},
"12391b10cf16a807322c49c9cc7e0a015f26b445beacf4cdd4e7714f36b4adf6": {
"describe": {
"columns": [
{
"name": "site_secret",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "repo_url",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "pub_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT site_secret, repo_url, branch, hostname, pub_id\n FROM librepages_sites\n WHERE deleted = false\n AND owned_by = (SELECT ID FROM librepages_users WHERE name = $1 );\n "
},
"14cdc724af64942e93994f97e9eafc8272d15605eff7aab9e5177d01f2bf6118": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Text",
"Timestamptz",
"Text",
"Uuid"
]
}
},
"query": "INSERT INTO librepages_site_deploy_events\n (event_type, time, site, pub_id) VALUES (\n (SELECT iD from librepages_deploy_event_type WHERE name = $1),\n $2,\n (SELECT ID from librepages_sites WHERE hostname = $3),\n $4\n );\n "
},
"1be33ea4fe0e6079c88768ff912b824f4b0250193f2d086046c1fd0da125ae0c": {
"describe": {
"columns": [
{
"name": "name",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "password",
"ordinal": 1,
"type_info": "Text"
}
],
"nullable": [
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT name, password FROM librepages_users WHERE name = ($1)"
},
"279b5ae27935279b06d2799eef2da6a316324a05d23ba7a729c608c70168c496": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar",
"Text"
]
}
},
"query": "UPDATE librepages_users set name = $1\n WHERE name = $2"
},
"39854fcbfb0247377c6c5ca70c2c0fa7804548848bf56f881eea2f8242e7a09d": {
"describe": {
"columns": [
{
"name": "name",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "time",
"ordinal": 1,
"type_info": "Timestamptz"
},
{
"name": "pub_id",
"ordinal": 2,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text",
"Uuid"
]
}
},
"query": "SELECT\n librepages_deploy_event_type.name,\n librepages_site_deploy_events.time,\n librepages_site_deploy_events.pub_id\n FROM\n librepages_site_deploy_events\n INNER JOIN librepages_deploy_event_type ON\n librepages_deploy_event_type.ID = librepages_site_deploy_events.event_type\n WHERE\n librepages_site_deploy_events.site = (\n SELECT ID FROM librepages_sites WHERE hostname = $1\n )\n AND\n librepages_site_deploy_events.pub_id = $2\n "
},
"3ecc3a4c89b1289368ef9d9c97204330f74138a0da614ef2174c59a687119595": {
"describe": {
"columns": [
{
"name": "forgejo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "auth_token",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "forgejo_webhook_secret",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "SELECT\n forgejo_url, auth_token, forgejo_webhook_secret\n FROM\n librepages_forgejo_webhooks\n WHERE\n auth_token = $1\n AND\n owned_by = (SELECT ID FROM librepages_users WHERE name = $2);\n "
},
"432fe829719ce8110f768b4a611724bb34191ac224d2143ff4c81548da75c103": {
"describe": {
"columns": [
{
"name": "repo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "owned_by",
"ordinal": 3,
"type_info": "Int4"
},
{
"name": "site_secret",
"ordinal": 4,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Uuid",
"Text"
]
}
},
"query": "SELECT repo_url, branch, hostname, owned_by, site_secret\n FROM librepages_sites\n WHERE pub_id = $1\n AND\n owned_by = (SELECT ID from librepages_users WHERE name = $2)\n AND\n deleted = false;\n "
},
"4445ff3226af3b5a24b255c5bb012c99b222cc7bd6dda80f232809ed273fc712": {
"describe": {
"columns": [
{
"name": "repo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "site_secret",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "owned_by",
"ordinal": 4,
"type_info": "Int4"
},
{
"name": "pub_id",
"ordinal": 5,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT repo_url, site_secret, branch, hostname, owned_by, pub_id\n FROM librepages_sites\n WHERE repo_url = $1\n AND deleted = false;\n "
},
"4cddf1049783251bfc79090055724e894a2be9451302f7691ce2f4240f1ee3ad": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Int4"
}
],
"nullable": [
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT ID FROM librepages_sites WHERE repo_url = $1"
},
"53f3c21c06c8d1c218537dfa9183fd0604aaf28200d8aa12e97db4ac317df39e": {
"describe": {
"columns": [
{
"name": "name",
"ordinal": 0,
"type_info": "Varchar"
}
],
"nullable": [
false
],
"parameters": {
"Left": [
"Int4"
]
}
},
"query": "SELECT name FROM librepages_users WHERE ID = $1"
},
"54f1ad328c83997d5e80686665d4cfef58d3529d24cb6caaa7ff301479e5d735": {
"describe": {
"columns": [
{
"name": "repo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 2,
"type_info": "Varchar"
},
{
"name": "owned_by",
"ordinal": 3,
"type_info": "Int4"
},
{
"name": "pub_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT repo_url, branch, hostname, owned_by, pub_id\n FROM librepages_sites\n WHERE site_secret = $1\n AND deleted = false;\n "
},
"5c5d774bde06c0ab83c3616a56a28f12dfd9c546cbaac9f246d3b350c587823e": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "DELETE FROM librepages_users WHERE name = ($1)"
},
"65f6181364cd8c6ed4eae3f62b5ae771a27e8da6e698c235ca77d4cec784d04b": {
"describe": {
"columns": [
{
"name": "site_secret",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "repo_url",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "branch",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "hostname",
"ordinal": 3,
"type_info": "Varchar"
},
{
"name": "pub_id",
"ordinal": 4,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false,
false,
false
],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "SELECT site_secret, repo_url, branch, hostname, pub_id\n FROM librepages_sites\n WHERE deleted = false\n AND owned_by = (SELECT ID FROM librepages_users WHERE name = $1 )\n AND hostname = $2;\n "
},
"6a557f851d4f47383b864085093beb0954e79779f21b655978f07e285281e0ac": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar",
"Text"
]
}
},
"query": "UPDATE librepages_users set email = $1\n WHERE name = $2"
},
"6db98c6ae90b8eb98ace1a5acfa3c8af2b6ed7d51c6debda12637f5d7b076c15": {
"describe": {
"columns": [
{
"name": "exists",
"ordinal": 0,
"type_info": "Bool"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT EXISTS (SELECT 1 from librepages_sites WHERE hostname = $1 AND deleted = false)"
},
"77612c85be99e6de2e4a6e3105ebaeb470d6cc57b2999b673a085da41c035f9e": {
"describe": {
"columns": [
{
"name": "time",
"ordinal": 0,
"type_info": "Timestamptz"
},
{
"name": "pub_id",
"ordinal": 1,
"type_info": "Uuid"
}
],
"nullable": [
false,
false
],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "SELECT\n time,\n pub_id\n FROM\n librepages_site_deploy_events\n WHERE\n site = (SELECT ID FROM librepages_sites WHERE hostname = $1)\n AND\n event_type = (SELECT ID FROM librepages_deploy_event_type WHERE name = $2)\n AND\n time = (\n SELECT MAX(time) \n FROM\n librepages_site_deploy_events\n WHERE\n site = (SELECT ID FROM librepages_sites WHERE hostname = $1)\n )\n "
},
"8735b654bc261571e6a5908d55a8217474c76bdff7f3cbcc71500a0fe13249db": {
"describe": {
"columns": [
{
"name": "exists",
"ordinal": 0,
"type_info": "Bool"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT EXISTS (SELECT 1 from librepages_users WHERE email = $1)"
},
"8bf4e01b8c38d035fe6bdbfbe8ad9cb35e3fc2fd11107bae92880d157ed11379": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Text"
]
}
},
"query": "INSERT INTO librepages_forgejo_webhooks\n (forgejo_url , auth_token, forgejo_webhook_secret, owned_by) VALUES ($1, $2, $3, \n (SELECT ID FROM librepages_users WHERE name = $4)\n )"
},
"90907d6cb4ca3b485f7b583584fb5821a950362679d061e490545c76634c211e": {
"describe": {
"columns": [
{
"name": "exists",
"ordinal": 0,
"type_info": "Bool"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT EXISTS (SELECT 1 from librepages_sites WHERE repo_url = $1)"
},
"924e756de5544cece865a10a7e136ecc6126e3a603947264cc7899387c18c819": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Text",
"Text"
]
}
},
"query": "UPDATE librepages_users set password = $1\n WHERE name = $2"
},
"9710a01bc4c5c5cda2db27d14baca3d7a6ceffa66c7d539da6fda7947c222e71": {
"describe": {
"columns": [
{
"name": "forgejo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "auth_token",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "forgejo_webhook_secret",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT\n forgejo_url, auth_token, forgejo_webhook_secret\n FROM\n librepages_forgejo_webhooks\n WHERE\n owned_by = (SELECT ID FROM librepages_users WHERE name = $1);\n "
},
"a6284ede1dbf340942dd97afb75865ba0a41009a145254117b03002bd9afa588": {
"describe": {
"columns": [
{
"name": "forgejo_url",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "auth_token",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "forgejo_webhook_secret",
"ordinal": 2,
"type_info": "Varchar"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT forgejo_url, auth_token, forgejo_webhook_secret\n FROM librepages_forgejo_webhooks\n WHERE auth_token = $1\n "
},
"b48c77db6e663d97df44bf9ec2ee92fd3e02f2dcbcdbd1d491e09fab2da68494": {
"describe": {
"columns": [
{
"name": "name",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "password",
"ordinal": 1,
"type_info": "Text"
}
],
"nullable": [
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT name, password FROM librepages_users WHERE email = ($1)"
},
"b7e51e976a4a80a78df8dbfed1f195af212023d00faee88ab2d09326896bd653": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Text",
"Int4",
"Text"
]
}
},
"query": "INSERT INTO librepages_forgejo_webhook_site_mapping\n (site_id, forgejo_webhook_id) VALUES (\n (SELECT ID FROM librepages_sites WHERE repo_url = $1 AND ID = $2),\n (SELECT ID FROM librepages_forgejo_webhooks WHERE auth_token = $3)\n ) ON CONFLICT (site_id, forgejo_webhook_id) DO NOTHING;"
},
"b8b1b3c5fa205b071f577b2ce9993ddfc7c99ada26aea48aa1c201c8c3c7fcf6": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Text",
"Varchar",
"Uuid",
"Text"
]
}
},
"query": "\n INSERT INTO librepages_sites\n (site_secret, repo_url, branch, hostname, pub_id, owned_by)\n VALUES ($1, $2, $3, $4, $5, ( SELECT ID FROM librepages_users WHERE name = $6 ));\n "
},
"bdd4d2a1b0b97ebf8ed61cfd120b40146fbf3ea9afb5cd0e03c9d29860b6a26b": {
"describe": {
"columns": [
{
"name": "exists",
"ordinal": 0,
"type_info": "Bool"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT EXISTS (SELECT 1 from librepages_users WHERE name = $1)"
},
"ced69a08729ffb906e8971dbdce6a8d4197bc9bb8ccd7c58b3a88eb7be73fc2e": {
"describe": {
"columns": [
{
"name": "email",
"ordinal": 0,
"type_info": "Varchar"
}
],
"nullable": [
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT email FROM librepages_users WHERE name = $1"
},
"d2327c1bcb40e18518c2112413a19a9b26eb0f54f83c53e968c9752d70c8dd4e": {
"describe": {
"columns": [
{
"name": "name",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "time",
"ordinal": 1,
"type_info": "Timestamptz"
},
{
"name": "pub_id",
"ordinal": 2,
"type_info": "Uuid"
}
],
"nullable": [
false,
false,
false
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT\n librepages_deploy_event_type.name,\n librepages_site_deploy_events.time,\n librepages_site_deploy_events.pub_id\n FROM\n librepages_site_deploy_events\n INNER JOIN librepages_deploy_event_type ON\n librepages_deploy_event_type.ID = librepages_site_deploy_events.event_type\n WHERE\n librepages_site_deploy_events.site = (\n SELECT ID FROM librepages_sites WHERE hostname = $1\n );\n "
},
"e4adf1bc9175eeb9d61b495653bb452039cc38818c8792acdc6a1c732b6f4554": {
"describe": {
"columns": [
{
"name": "exists",
"ordinal": 0,
"type_info": "Bool"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Text"
]
}
},
"query": "SELECT EXISTS (SELECT 1 from librepages_deploy_event_type WHERE name = $1)"
},
"f651da8f411b7977cb87dd8d4bd5d167661d7ef1d865747e76219453d386d593": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar"
]
}
},
"query": "INSERT INTO librepages_deploy_event_type\n (name) VALUES ($1) ON CONFLICT (name) DO NOTHING;"
},
"faa4170a309f19a4abf1ca3f8dd3c0526945aa00f028ebf8bd7063825d448f5b": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Varchar",
"Text",
"Varchar"
]
}
},
"query": "INSERT INTO librepages_users\n (name , password, email) VALUES ($1, $2, $3)"
}
"db": "PostgreSQL"
}

View File

@ -1,282 +0,0 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use actix_identity::Identity;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use tracing::info;
use url::Url;
use super::get_auth_middleware;
use crate::{errors::*, AppCtx};
pub mod routes {
use crate::ctx::Ctx;
pub struct Forgejo {
pub add_webhook: &'static str,
pub view_webhook: &'static str,
pub list_webhooks: &'static str,
pub webhook: &'static str,
}
impl Forgejo {
pub const fn new() -> Self {
Self {
add_webhook: "/api/v1/forgejo/webhook/add",
list_webhooks: "/api/v1/forgejo/webhook/add",
view_webhook: "/api/v1/forgejo/webhook/view/{auth_token}",
webhook: "/api/v1/forgejo/webhook/event/new",
}
}
pub fn get_view(&self, auth_token: &str) -> String {
self.view_webhook.replace("{auth_token}", auth_token)
}
pub fn get_webhook_url(&self, ctx: &Ctx, auth_token: &str) -> String {
format!(
"https://{}{}?auth={auth_token}",
&ctx.settings.server.domain, self.webhook
)
}
}
}
#[derive(Serialize, Deserialize)]
pub struct AddWebhook {
pub forgejo_url: Url,
}
#[actix_web_codegen_const_routes::post(
path = "crate::V1_API_ROUTES.forgejo.add_webhook",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Add webhook" skip(id, ctx, payload))]
async fn add_webhook(
ctx: AppCtx,
id: Identity,
payload: web::Json<AddWebhook>,
) -> ServiceResult<impl Responder> {
info!(
"Adding webhook for Forgejo instance: {}",
payload.forgejo_url.as_str()
);
let owner = id.identity().unwrap();
let payload = payload.into_inner();
let hook = ctx.db.new_webhook(payload.forgejo_url, &owner).await?;
Ok(HttpResponse::Ok().json(hook))
}
#[actix_web_codegen_const_routes::get(
path = "crate::V1_API_ROUTES.forgejo.list_webhooks",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Delete webhook" skip(id, ctx))]
async fn list_webhooks(ctx: AppCtx, id: Identity) -> ServiceResult<impl Responder> {
let owner = id.identity().unwrap();
info!("Getting all webhooks created by {}", owner);
let hooks = ctx.db.list_all_webhooks_with_owner(&owner).await?;
Ok(HttpResponse::Ok().json(hooks))
}
#[actix_web_codegen_const_routes::get(
path = "crate::V1_API_ROUTES.forgejo.view_webhook",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Delete webhook" skip(id, ctx, path))]
async fn view_webhook(
ctx: AppCtx,
id: Identity,
path: web::Path<String>,
) -> ServiceResult<impl Responder> {
let path = path.into_inner();
let owner = id.identity().unwrap();
info!("Gitting webhook webhook for Forgejo instance: {}", path,);
let hook = ctx.db.get_webhook_with_owner(&path, &owner).await?;
Ok(HttpResponse::Ok().json(hook))
}
#[derive(Serialize, Deserialize)]
struct Auth {
auth: String,
}
#[actix_web_codegen_const_routes::post(path = "crate::V1_API_ROUTES.forgejo.webhook")]
#[tracing::instrument(name = "Update ", skip(body, ctx, req, q))]
async fn webhook(
ctx: AppCtx,
body: web::Bytes,
req: HttpRequest,
q: web::Query<Auth>,
) -> ServiceResult<impl Responder> {
ctx.process_webhook(&body, &req, &q.auth).await?;
Ok(HttpResponse::Ok())
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(add_webhook);
cfg.service(view_webhook);
cfg.service(list_webhooks);
cfg.service(webhook);
}
#[cfg(test)]
mod tests {
use actix_web::{error::ResponseError, http::StatusCode, test};
use hmac::Mac;
use crate::ctx::api::v1::forgejo::{HmacSha256, WebhookPayload};
use crate::db::ForgejoWebhook;
use crate::tests;
use crate::*;
use super::*;
#[actix_rt::test]
async fn test_api_forgejo_webhook() {
const NAME: &str = "apiforgejowebhookuser";
const PASSWORD: &str = "longpasswordasdfa2";
const EMAIL: &str = "apiforgejowebhookuser@a.com";
let (_dir, ctx) = tests::get_ctx().await;
let _ = ctx.delete_user(NAME, PASSWORD).await;
let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await;
let page = ctx.add_test_site(NAME.into()).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(ctx).await;
let payload = AddWebhook {
forgejo_url: Url::parse("https://git.batnsense.net").unwrap(),
};
let add_webhook_resp = test::call_service(
&app,
post_request!(&payload, V1_API_ROUTES.forgejo.add_webhook)
.cookie(cookies.clone())
.to_request(),
)
.await;
check_status!(add_webhook_resp, StatusCode::OK);
let response: ForgejoWebhook = actix_web::test::read_body_json(add_webhook_resp).await;
assert_eq!(response.forgejo_url, payload.forgejo_url);
let view_webhook_resp = get_request!(
&app,
&V1_API_ROUTES.forgejo.get_view(&response.auth_token),
cookies.clone()
);
check_status!(view_webhook_resp, StatusCode::OK);
let hook: ForgejoWebhook = actix_web::test::read_body_json(view_webhook_resp).await;
assert_eq!(hook, response);
let list_all_webhooks_resp =
get_request!(&app, V1_API_ROUTES.forgejo.list_webhooks, cookies.clone());
check_status!(list_all_webhooks_resp, StatusCode::OK);
let hooks: Vec<ForgejoWebhook> =
actix_web::test::read_body_json(list_all_webhooks_resp).await;
assert_eq!(vec![hook.clone()], hooks);
let webhook_url = format!("{}?auth={}", V1_API_ROUTES.forgejo.webhook, hook.auth_token);
// test webhook
let mut webhook_payload = WebhookPayload::default();
webhook_payload.reference = format!("refs/origin/{}", page.branch);
webhook_payload.repository.html_url = page.repo;
let body = serde_json::to_string(&webhook_payload).unwrap();
let body = body.as_bytes();
let mut mac = HmacSha256::new_from_slice(hook.forgejo_webhook_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(body);
let res = mac.finalize();
let sig = res.into_bytes();
let sig = hex::encode(&sig[..]);
let post_to_webhook_resp = test::call_service(
&app,
post_request!(&webhook_payload, &webhook_url)
.insert_header(("X-Gitea-Delivery", "foobar213randomuuid"))
.insert_header(("X-Gitea-Signature", sig.clone()))
.insert_header(("X-Gitea-Event", "push"))
.cookie(cookies.clone())
.to_request(),
)
.await;
check_status!(post_to_webhook_resp, StatusCode::OK);
// no webhook
let fake_webhook_url = format!(
"{}?auth={}",
V1_API_ROUTES.forgejo.webhook, hook.forgejo_webhook_secret
);
let body = serde_json::to_string(&webhook_payload).unwrap();
let body = body.as_bytes();
let mut mac =
HmacSha256::new_from_slice(b"nosecret").expect("HMAC can take key of any size");
mac.update(body);
let res = mac.finalize();
let fake_sig = res.into_bytes();
let fake_sig = hex::encode(&fake_sig[..]);
let post_to_no_exist_webhook_resp = test::call_service(
&app,
post_request!(&webhook_payload, &fake_webhook_url)
.insert_header(("X-Gitea-Delivery", "foobar213randomuuid"))
.insert_header(("X-Gitea-Signature", fake_sig))
.insert_header(("X-Gitea-Event", "push"))
.cookie(cookies.clone())
.to_request(),
)
.await;
let err = ServiceError::WebhookNotFound;
assert_eq!(post_to_no_exist_webhook_resp.status(), err.status_code());
let resp_err: ErrorToResponse =
actix_web::test::read_body_json(post_to_no_exist_webhook_resp).await;
assert_eq!(resp_err.error, err.to_string());
// no website
let mut webhook_payload = WebhookPayload::default();
webhook_payload.reference = format!("refs/origin/{}", page.branch);
webhook_payload.repository.html_url = "https://no-exist-git.example.org".into();
let body = serde_json::to_string(&webhook_payload).unwrap();
let body = body.as_bytes();
let mut mac = HmacSha256::new_from_slice(hook.forgejo_webhook_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(body);
let res = mac.finalize();
let sig = res.into_bytes();
let sig = hex::encode(&sig[..]);
let post_to_no_website_webhook_resp = test::call_service(
&app,
post_request!(&webhook_payload, &webhook_url)
.insert_header(("X-Gitea-Delivery", "foobar213randomuuid"))
.insert_header(("X-Gitea-Signature", sig.clone()))
.insert_header(("X-Gitea-Event", "push"))
.cookie(cookies.clone())
.to_request(),
)
.await;
let err = ServiceError::WebsiteNotFound;
assert_eq!(post_to_no_website_webhook_resp.status(), err.status_code());
let resp_err: ErrorToResponse =
actix_web::test::read_body_json(post_to_no_website_webhook_resp).await;
assert_eq!(resp_err.error, err.to_string());
}
}

View File

@ -20,7 +20,6 @@ use serde::Deserialize;
pub mod account;
pub mod auth;
pub mod forgejo;
pub mod meta;
pub mod pages;
pub mod routes;
@ -31,7 +30,6 @@ pub fn services(cfg: &mut ServiceConfig) {
auth::services(cfg);
account::services(cfg);
meta::services(cfg);
forgejo::services(cfg);
pages::services(cfg);
}

View File

@ -19,7 +19,6 @@ use actix_auth_middleware::GetLoginRoute;
use crate::serve::routes::Serve;
use super::forgejo::routes::Forgejo;
use super::meta::routes::Meta;
use super::pages::routes::Deploy;
@ -93,7 +92,6 @@ pub struct Routes {
pub account: Account,
/// Meta routes
pub meta: Meta,
pub forgejo: Forgejo,
pub deploy: Deploy,
pub serve: Serve,
}
@ -105,7 +103,6 @@ impl Routes {
auth: Auth::new(),
account: Account::new(),
meta: Meta::new(),
forgejo: Forgejo::new(),
deploy: Deploy::new(),
serve: Serve::new(),
}

View File

@ -30,13 +30,11 @@ pub struct Conductor {
}
impl Conductor {
pub fn new(settings: Settings, client: Option<Client>) -> Self {
let client = if let Some(client) = client {
client
} else {
Client::new()
};
Self { client, settings }
pub fn new(settings: Settings) -> Self {
Self {
client: Client::new(),
settings,
}
}
async fn tx(&self, e: &EventType) -> ServiceResult<()> {
for c in self.settings.conductors.iter() {
@ -81,7 +79,7 @@ mod tests {
#[actix_rt::test]
pub async fn test_conductor() {
let settings = Settings::new().unwrap();
let c = Conductor::new(settings.clone(), None);
let c = Conductor::new(settings.clone());
c.delete_site("example.org".into()).await.unwrap();
let page = Page {
secret: "foo".into(),

View File

@ -1,204 +0,0 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use actix_web::web;
use actix_web::HttpRequest;
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use tracing::{info, warn};
use url::Url;
use crate::ctx::Ctx;
use crate::errors::ServiceError;
use crate::errors::ServiceResult;
pub type HmacSha256 = Hmac<Sha256>;
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct CommitPerson {
pub name: String,
pub email: String,
pub username: String,
}
#[derive(Serialize, Deserialize, Default, Debug, Clone, Eq, PartialEq)]
pub struct Commit {
pub id: String,
pub message: String,
pub url: String,
pub author: CommitPerson,
pub committer: CommitPerson,
pub verification: serde_json::Value,
pub timestamp: String,
pub added: serde_json::Value,
pub removed: serde_json::Value,
pub modified: serde_json::Value,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Person {
pub id: usize,
pub login: String,
pub full_name: String,
pub email: String,
pub avatar_url: String,
pub language: String,
pub is_admin: bool,
pub last_login: String,
pub created: String,
pub restricted: bool,
pub active: bool,
pub prohibit_login: bool,
pub location: String,
pub website: String,
pub description: String,
pub visibility: String,
pub followers_count: usize,
pub following_count: usize,
pub starred_repos_count: usize,
pub username: String,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Permissions {
pub admin: bool,
pub push: bool,
pub pull: bool,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct InternalTracker {
pub enable_time_tracker: bool,
pub allow_only_contributors_to_track_time: bool,
pub enable_issue_dependencies: bool,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct Repository {
pub id: usize,
pub owner: Person,
pub name: String,
pub full_name: String,
pub description: String,
pub empty: bool,
pub private: bool,
pub fork: bool,
pub template: bool,
pub parent: Option<serde_json::Value>,
pub mirror: bool,
pub size: usize,
pub html_url: String,
pub ssh_url: String,
pub clone_url: String,
pub original_url: String,
pub website: String,
pub stars_count: usize,
pub forks_count: usize,
pub watchers_count: usize,
pub open_issues_count: usize,
pub open_pr_counter: usize,
pub release_counter: usize,
pub default_branch: String,
pub archived: bool,
pub created_at: String,
pub updated_at: String,
pub permissions: Permissions,
pub has_issues: bool,
pub internal_tracker: InternalTracker,
pub has_wiki: bool,
pub has_pull_requests: bool,
pub has_projects: bool,
pub ignore_whitespace_conflicts: bool,
pub allow_merge_commits: bool,
pub allow_rebase: bool,
pub allow_rebase_explicit: bool,
pub allow_squash_merge: bool,
pub default_merge_style: String,
pub avatar_url: String,
pub internal: bool,
pub mirror_interval: String,
pub mirror_updated: String,
pub repo_transfer: Option<serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
pub struct WebhookPayload {
#[serde(rename(serialize = "ref", deserialize = "ref"))]
pub reference: String,
pub before: String,
pub after: String,
pub compare_url: String,
pub repository: Repository,
pub pusher: Person,
pub sender: Person,
}
impl Ctx {
pub async fn process_webhook(
&self,
body: &web::Bytes,
req: &HttpRequest,
auth_token: &str,
) -> ServiceResult<()> {
let headers = req.headers();
let _uuid = headers.get("X-Gitea-Delivery").unwrap();
let sig = headers.get("X-Gitea-Signature").unwrap();
let sig = hex::decode(sig).unwrap();
let event_type = headers.get("X-Gitea-Event").unwrap();
let payload: WebhookPayload = serde_json::from_slice(body).unwrap();
let hook = self.db.get_webhook(auth_token).await?;
for url in [
&payload.repository.html_url,
&payload.repository.ssh_url,
&payload.repository.clone_url,
] {
if self.db.site_with_repository_exists(url).await? {
let mut mac = HmacSha256::new_from_slice(hook.forgejo_webhook_secret.as_bytes())?;
mac.update(body);
mac.verify_slice(&sig[..])?;
let site = self.db.get_site_from_repo_url(url).await?;
self.db
.webhook_link_site(auth_token, &Url::parse(&site.repo_url)?)
.await?;
if payload.reference.contains(&site.branch) {
info!(
"[webhook][forgejo/gitea] received update {:?} from {url} repository on deployed branch",
event_type
);
self.update_site(&site.site_secret, Some(site.branch))
.await?;
} else {
info!(
"[webhook][forgejo/gitea] received update {:?} from {url} repository on non-deployed branch {}",
event_type,
payload.reference
);
}
return Ok(());
}
}
warn!(
"[webhook][forgejo/gitea] stray update from {} repository",
payload.repository.html_url
);
Err(ServiceError::WebsiteNotFound)
}
}

View File

@ -16,7 +16,6 @@
*/
pub mod account;
pub mod auth;
pub mod forgejo;
pub mod pages;
#[cfg(test)]

51
src/ctx/gitea.rs Normal file
View File

@ -0,0 +1,51 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use serde::{Deserialize, Serialize};
use url::Url;
use crate::ctx::Ctx;
use crate::db::AddGiteaInstance;
use crate::errors::ServiceResult;
impl Ctx {
pub async fn init_gitea_instance(&self, info: &AddGiteaInstance) -> ServiceResult<()> {
let mut url = info.url.clone();
url.set_path("/.well-known/openid-configuration");
let res: OIDCConfiguration = self
.client
.get(url)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
self.db.new_gitea_instance(&info).await?;
self.db
.new_gitea_oidc_configuration(&info.url, &res)
.await?;
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct OIDCConfiguration {
pub authorization_endpoint: Url,
pub token_endpoint: Url,
pub userinfo_endpoint: Url,
pub introspection_endpoint: Url,
}

View File

@ -24,6 +24,7 @@ use reqwest::Client;
use tracing::info;
pub mod api;
pub mod gitea;
use crate::conductor::Conductor;
@ -54,8 +55,7 @@ impl Ctx {
pub async fn new(settings: Settings) -> Arc<Self> {
let creds = Self::get_creds();
let c = creds.clone();
let client = Client::default();
let conductor = Conductor::new(settings.clone(), Some(client.clone()));
let conductor = Conductor::new(settings.clone());
#[allow(unused_variables)]
let init = thread::spawn(move || {
@ -68,12 +68,13 @@ impl Ctx {
#[cfg(not(debug_assertions))]
init.join();
let client = Client::new();
Arc::new(Self {
settings,
client,
db,
creds,
conductor,
client,
})
}
}

429
src/db.rs
View File

@ -26,8 +26,8 @@ use tracing::error;
use url::Url;
use uuid::Uuid;
use crate::ctx::gitea::OIDCConfiguration;
use crate::errors::*;
use crate::utils;
/// Connect to databse
pub enum ConnectionOptions {
@ -50,7 +50,6 @@ impl ConnectionOptions {
async fn connect(self) -> ServiceResult<Database> {
let pool = match self {
Self::Fresh(fresh) => {
tracing::info!("DATABASE URL: {}", fresh.url);
let mut connect_options =
sqlx::postgres::PgConnectOptions::from_str(&fresh.url).unwrap();
if fresh.disable_logging {
@ -276,53 +275,6 @@ impl Database {
Ok(())
}
pub async fn get_site_from_repo_url(&self, repo_url: &str) -> ServiceResult<Site> {
struct S {
repo_url: String,
branch: String,
hostname: String,
owned_by: i32,
site_secret: String,
pub_id: Uuid,
}
let site = sqlx::query_as!(
S,
"SELECT repo_url, site_secret, branch, hostname, owned_by, pub_id
FROM librepages_sites
WHERE repo_url = $1
AND deleted = false;
",
repo_url,
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?;
struct Owner {
name: String,
}
let owner = sqlx::query_as!(
Owner,
"SELECT name FROM librepages_users WHERE ID = $1",
site.owned_by
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?;
let site = Site {
site_secret: site.site_secret,
branch: site.branch,
hostname: site.hostname,
owner: owner.name,
repo_url: site.repo_url,
pub_id: site.pub_id,
};
Ok(site)
}
pub async fn get_site_from_pub_id(&self, pub_id: Uuid, owner: String) -> ServiceResult<Site> {
struct S {
repo_url: String,
@ -480,24 +432,6 @@ impl Database {
Ok(resp)
}
/// check if site with repository exists
pub async fn site_with_repository_exists(&self, url: &str) -> ServiceResult<bool> {
let res = sqlx::query!(
"SELECT EXISTS (SELECT 1 from librepages_sites WHERE repo_url = $1)",
url,
)
.fetch_one(&self.pool)
.await
.map_err(map_register_err)?;
let mut resp = false;
if let Some(x) = res.exists {
resp = x;
}
Ok(resp)
}
/// check if event type exists
async fn event_type_exists(&self, event: &Event) -> ServiceResult<bool> {
let res = sqlx::query!(
@ -690,133 +624,103 @@ impl Database {
Ok(events)
}
/// register a new webhook
pub async fn new_webhook(
&self,
forgejo_url: Url,
owner: &str,
) -> ServiceResult<ForgejoWebhook> {
let hook = ForgejoWebhook::new(forgejo_url);
pub async fn new_gitea_instance(&self, payload: &AddGiteaInstance) -> ServiceResult<()> {
sqlx::query!(
"INSERT INTO librepages_forgejo_webhooks
(forgejo_url , auth_token, forgejo_webhook_secret, owned_by) VALUES ($1, $2, $3,
(SELECT ID FROM librepages_users WHERE name = $4)
)",
hook.forgejo_url.as_str(),
&hook.auth_token,
&hook.forgejo_webhook_secret,
owner,
"INSERT INTO librepages_gitea_instances
(url , client_id, client_secret) VALUES ($1, $2, $3)",
&payload.url.as_str(),
payload.client_id,
payload.client_secret,
)
.execute(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::AccountNotFound))?;
Ok(hook)
}
pub async fn list_all_webhooks_with_owner(
&self,
owner: &str,
) -> ServiceResult<Vec<ForgejoWebhook>> {
let mut db_hooks = sqlx::query_as!(
InnerForgejoWebhook,
"SELECT
forgejo_url, auth_token, forgejo_webhook_secret
FROM
librepages_forgejo_webhooks
WHERE
owned_by = (SELECT ID FROM librepages_users WHERE name = $1);
",
owner
)
.fetch_all(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
let mut hooks = Vec::with_capacity(db_hooks.len());
for hook in db_hooks.drain(0..) {
hooks.push(hook.to_webhook()?)
}
Ok(hooks)
}
pub async fn get_webhook_with_owner(
&self,
auth_token: &str,
owner: &str,
) -> ServiceResult<ForgejoWebhook> {
let h = sqlx::query_as!(
InnerForgejoWebhook,
"SELECT
forgejo_url, auth_token, forgejo_webhook_secret
FROM
librepages_forgejo_webhooks
WHERE
auth_token = $1
AND
owned_by = (SELECT ID FROM librepages_users WHERE name = $2);
",
auth_token,
owner
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
h.to_webhook()
}
pub async fn get_webhook(&self, auth_token: &str) -> ServiceResult<ForgejoWebhook> {
let h = sqlx::query_as!(
InnerForgejoWebhook,
"SELECT forgejo_url, auth_token, forgejo_webhook_secret
FROM librepages_forgejo_webhooks
WHERE auth_token = $1
",
auth_token,
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
h.to_webhook()
}
/// register a webhook against a site
pub async fn webhook_link_site(&self, auth_token: &str, repo_url: &Url) -> ServiceResult<()> {
struct Site {
id: i32,
}
let sites = sqlx::query_as!(
Site,
"SELECT ID FROM librepages_sites WHERE repo_url = $1",
repo_url.as_str()
)
.fetch_all(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::WebsiteNotFound))?;
for site in sites {
sqlx::query!(
"INSERT INTO librepages_forgejo_webhook_site_mapping
(site_id, forgejo_webhook_id) VALUES (
(SELECT ID FROM librepages_sites WHERE repo_url = $1 AND ID = $2),
(SELECT ID FROM librepages_forgejo_webhooks WHERE auth_token = $3)
) ON CONFLICT (site_id, forgejo_webhook_id) DO NOTHING;",
repo_url.as_str(),
site.id,
auth_token
)
.execute(&self.pool)
.await
//.unwrap();
.map_err(|e| map_row_not_found_err(e, ServiceError::WebhookNotFound))?;
}
.map_err(map_register_err)?;
Ok(())
}
}
pub async fn delete_gitea_instance(&self, url: &Url) -> ServiceResult<()> {
sqlx::query!(
"DELETE FROM librepages_gitea_instances WHERE url = ($1)",
url.as_str()
)
.execute(&self.pool)
.await
.map_err(map_register_err)?;
Ok(())
}
pub async fn get_gitea_password(&self, url: &Url) -> ServiceResult<GiteaInstance> {
let res = sqlx::query_as!(
GiteaInstance,
"SELECT client_id, client_secret FROM librepages_gitea_instances WHERE url = ($1)",
url.as_str()
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::GiteaInstanceNotFound))?;
Ok(res)
}
pub async fn new_gitea_oidc_configuration(
&self,
url: &Url,
payload: &OIDCConfiguration,
) -> ServiceResult<()> {
sqlx::query!(
"INSERT INTO librepages_gitea_oidc_configuration
(
gitea_instance, authorization_endpoint,
token_endpoint, userinfo_endpoint,
introspection_endpoint
) VALUES (
(SELECT ID FROM librepages_gitea_instances WHERE url = $1)
, $2, $3, $4, $5
)",
&url.as_str(),
&payload.authorization_endpoint.as_str(),
&payload.token_endpoint.as_str(),
&payload.userinfo_endpoint.as_str(),
&payload.introspection_endpoint.as_str(),
)
.execute(&self.pool)
.await
.map_err(map_register_err)?;
Ok(())
}
pub async fn get_gitea_oidc_configuration(
&self,
url: &Url,
) -> ServiceResult<OIDCConfiguration> {
struct OIDCConfigurationInner {
authorization_endpoint: String,
token_endpoint: String,
userinfo_endpoint: String,
introspection_endpoint: String,
}
let res = sqlx::query_as!(
OIDCConfigurationInner,
"SELECT
authorization_endpoint, token_endpoint,
userinfo_endpoint, introspection_endpoint
FROM
librepages_gitea_oidc_configuration
WHERE
gitea_instance = (SELECT ID FROM librepages_gitea_instances WHERE url = $1)",
url.as_str()
)
.fetch_one(&self.pool)
.await
.map_err(|e| map_row_not_found_err(e, ServiceError::GiteaInstanceNotFound))?;
let res = OIDCConfiguration {
authorization_endpoint: Url::parse(&res.authorization_endpoint)?,
token_endpoint: Url::parse(&res.token_endpoint)?,
userinfo_endpoint: Url::parse(&res.userinfo_endpoint)?,
introspection_endpoint: Url::parse(&res.introspection_endpoint)?,
};
Ok(res)
}
}
struct InnerSite {
site_secret: String,
repo_url: String,
@ -927,36 +831,16 @@ pub struct LibrePagesEvent {
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ForgejoWebhook {
pub forgejo_url: Url,
pub forgejo_webhook_secret: String,
pub auth_token: String,
pub struct GiteaInstance {
pub client_id: String,
pub client_secret: String,
}
impl ForgejoWebhook {
fn new(forgejo_url: Url) -> Self {
Self {
forgejo_url,
forgejo_webhook_secret: utils::get_random(40),
auth_token: utils::get_random(40),
}
}
}
struct InnerForgejoWebhook {
forgejo_url: String,
auth_token: String,
forgejo_webhook_secret: String,
}
impl InnerForgejoWebhook {
fn to_webhook(self) -> ServiceResult<ForgejoWebhook> {
Ok(ForgejoWebhook {
forgejo_url: Url::parse(&self.forgejo_url)?,
auth_token: self.auth_token,
forgejo_webhook_secret: self.forgejo_webhook_secret,
})
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AddGiteaInstance {
pub url: Url,
pub client_id: String,
pub client_secret: String,
}
fn now_unix_time_stamp() -> OffsetDateTime {
@ -997,6 +881,13 @@ fn map_register_err(e: sqlx::Error) -> ServiceError {
ServiceError::UsernameTaken
} else if msg.contains("librepages_users_email_key") {
ServiceError::EmailTaken
} else if msg.contains("librepages_gitea_instances_url_key")
|| msg.contains("librepages_gitea_oidc_configuration_authorization_endpoint_key")
|| msg.contains("librepages_gitea_oidc_configuration_token_endpoint_key")
|| msg.contains("librepages_gitea_oidc_configuration_userinfo_endpoint_key")
|| msg.contains("librepages_gitea_oidc_configuration_introspection_endpoint_key")
{
ServiceError::GiteaInstanceRegistered
} else {
error!("{}", msg);
ServiceError::InternalServerError
@ -1178,7 +1069,7 @@ mod tests {
let site = Site {
site_secret: "foobar".into(),
repo_url: "https://git.test_db_sites.example.org/LibrePages/librepages.git".into(),
repo_url: "https://git.batsense.net/LibrePages/librepages.git".into(),
branch: "librepages".into(),
hostname: "db_works.tests.librepages.librepages.org".into(),
pub_id: Uuid::new_v4(),
@ -1187,20 +1078,12 @@ mod tests {
// test if hostname exists. Should be false
assert!(!db.hostname_exists(&site.hostname).await.unwrap());
assert!(!db
.site_with_repository_exists(&site.repo_url)
.await
.unwrap());
// testing adding site
db.add_site(&site).await.unwrap();
// test if hostname exists. Should be true
assert!(db.hostname_exists(&site.hostname).await.unwrap());
assert!(db
.site_with_repository_exists(&site.repo_url)
.await
.unwrap());
// get site
let db_site = db.get_site(p.username, &site.hostname).await.unwrap();
@ -1212,12 +1095,6 @@ mod tests {
db.get_site_from_secret(&site.site_secret).await.unwrap()
);
// get site by repo_url
assert_eq!(
db_site,
db.get_site_from_repo_url(&site.repo_url).await.unwrap()
);
// list all sites owned by user
let db_sites = db.list_all_sites(p.username).await.unwrap();
assert_eq!(db_sites.len(), 1);
@ -1264,36 +1141,76 @@ mod tests {
);
assert_eq!(latest_update_event_id_from_db.id, latest_update_event_id);
// add webhook
let forgejo_url = Url::parse("https://example.org").unwrap();
let hook = db.new_webhook(forgejo_url, NAME).await.unwrap();
assert_eq!(hook, db.get_webhook(&hook.auth_token).await.unwrap());
assert_eq!(
vec![hook.clone()],
db.list_all_webhooks_with_owner(NAME).await.unwrap()
);
assert_eq!(
hook,
db.get_webhook_with_owner(&hook.auth_token, NAME)
.await
.unwrap()
);
assert_eq!(
db.get_webhook(&hook.forgejo_webhook_secret).await.err(),
Some(ServiceError::WebhookNotFound)
);
db.webhook_link_site(&hook.auth_token, &Url::parse(&site.repo_url).unwrap())
.await
.unwrap();
db.webhook_link_site(&hook.auth_token, &Url::parse(&site.repo_url).unwrap())
.await
.unwrap();
// delete site
db.delete_site(p.username, &site.hostname).await.unwrap();
// test if hostname exists. Should be false
assert!(!db.hostname_exists(&site.hostname).await.unwrap());
}
#[actix_rt::test]
pub async fn test_gitea_instance_methods() {
let settings = Settings::new().unwrap();
let pool_options = PgPoolOptions::new().max_connections(1);
let db = ConnectionOptions::Fresh(Fresh {
pool_options,
url: settings.database.url.clone(),
disable_logging: !settings.debug,
})
.connect()
.await
.unwrap();
assert!(db.ping().await);
let url = Url::parse("https://test_gitea_instance_methods.example.org").unwrap();
let client_id = "longid";
let client_secret = "longsecret";
let _ = db.delete_gitea_instance(&url).await;
let payload = AddGiteaInstance {
client_secret: client_secret.into(),
client_id: client_id.into(),
url: url.clone(),
};
db.new_gitea_instance(&payload).await.unwrap();
assert_eq!(
db.new_gitea_instance(&payload).await.err(),
Some(ServiceError::GiteaInstanceRegistered)
);
let res = db.get_gitea_password(&url).await.unwrap();
assert_eq!(res.client_id, client_id);
assert_eq!(res.client_secret, client_secret);
let oidc_config = OIDCConfiguration {
authorization_endpoint: Url::parse("https://example.org/authorization_endpoint")
.unwrap(),
token_endpoint: Url::parse("https://example.org/token_endpoint").unwrap(),
userinfo_endpoint: Url::parse("https://exapmle.org/userinfo_endpoint").unwrap(),
introspection_endpoint: Url::parse("https://exapmle.org/introspection_endpoint")
.unwrap(),
};
db.new_gitea_oidc_configuration(&url, &oidc_config)
.await
.unwrap();
assert_eq!(
db.new_gitea_oidc_configuration(&url, &oidc_config)
.await
.err(),
Some(ServiceError::GiteaInstanceRegistered)
);
assert_eq!(
db.get_gitea_oidc_configuration(&url).await.unwrap(),
oidc_config
);
db.delete_gitea_instance(&url).await.unwrap();
assert_eq!(
db.get_gitea_password(&url).await.err(),
Some(ServiceError::GiteaInstanceNotFound)
);
}
}

View File

@ -28,8 +28,6 @@ use argon2_creds::errors::CredsError;
use config::ConfigError as ConfigErrorInner;
use derive_more::{Display, Error};
use git2::Error as GitError;
use hmac::digest::InvalidLength;
use hmac::digest::MacError;
use serde::{Deserialize, Serialize};
use url::ParseError;
@ -181,23 +179,13 @@ pub enum ServiceError {
/// passwords don't match
PasswordsDontMatch,
/// Webhook not found
#[display(fmt = "Webhook not found")]
WebhookNotFound,
}
/// Gitea instance is registered
#[display(fmt = "Gitea instance is registered")]
GiteaInstanceRegistered,
impl From<InvalidLength> for ServiceError {
#[cfg(not(tarpaulin_include))]
fn from(_: InvalidLength) -> ServiceError {
ServiceError::InternalServerError
}
}
impl From<MacError> for ServiceError {
#[cfg(not(tarpaulin_include))]
fn from(_: MacError) -> ServiceError {
ServiceError::WebhookNotFound
}
/// Gitea instance not found
#[display(fmt = "Gitea instance not found")]
GiteaInstanceNotFound,
}
impl From<ParseError> for ServiceError {
@ -272,7 +260,9 @@ impl ResponseError for ServiceError {
ServiceError::ClosedForRegistration => StatusCode::FORBIDDEN, //FORBIDDEN,
ServiceError::NotAnEmail => StatusCode::BAD_REQUEST, //BADREQUEST,
ServiceError::WrongPassword => StatusCode::UNAUTHORIZED, //UNAUTHORIZED,
ServiceError::WebhookNotFound => StatusCode::NOT_FOUND, //NOT FOUND,
//
ServiceError::GiteaInstanceRegistered => StatusCode::BAD_REQUEST,
ServiceError::GiteaInstanceNotFound => StatusCode::NOT_FOUND,
}
}
}

118
src/pages/auth/gitea/add.rs Normal file
View File

@ -0,0 +1,118 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_web::http::header::ContentType;
use tera::Context;
use crate::db::AddGiteaInstance;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub struct GiteaAddInstanceTemplate {
ctx: RefCell<Context>,
}
pub const GITEA_ADD_INSTANCE: TemplateFile =
TemplateFile::new("gitea_add_instance", "pages/auth/gitea/add.html");
impl CtxError for GiteaAddInstanceTemplate {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl GiteaAddInstanceTemplate {
pub fn new(settings: &Settings, payload: Option<&AddGiteaInstance>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(payload) = payload {
ctx.borrow_mut().insert(PAYLOAD_KEY, payload);
}
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(GITEA_ADD_INSTANCE.name, &self.ctx.borrow())
.unwrap()
}
pub fn page(s: &Settings) -> String {
let p = Self::new(s, None);
p.render()
}
}
#[actix_web_codegen_const_routes::get(path = "PAGES.auth.gitea.add")]
#[tracing::instrument(name = "Serve add Gitea instance page", skip(ctx))]
pub async fn get_gitea_add_instance(ctx: AppCtx) -> impl Responder {
let login = GiteaAddInstanceTemplate::page(&ctx.settings);
let html = ContentType::html();
HttpResponse::Ok().content_type(html).body(login)
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_gitea_add_instance);
cfg.service(post_gitea_add_instance);
}
#[actix_web_codegen_const_routes::post(path = "PAGES.auth.gitea.add")]
#[tracing::instrument(name = "Submit new Gitea instance", skip(payload, ctx))]
pub async fn post_gitea_add_instance(
payload: web::Form<AddGiteaInstance>,
ctx: AppCtx,
) -> PageResult<impl Responder, GiteaAddInstanceTemplate> {
let payload = payload.into_inner();
ctx.init_gitea_instance(&payload).await.map_err(|e| {
PageError::new(
GiteaAddInstanceTemplate::new(&ctx.settings, Some(&payload)),
e,
)
})?;
Ok(HttpResponse::Found()
.insert_header((http::header::LOCATION, PAGES.dash.home))
.finish())
}
#[cfg(test)]
mod tests {
use url::Url;
use super::GiteaAddInstanceTemplate;
use crate::db::AddGiteaInstance;
use crate::errors::*;
use crate::pages::errors::*;
use crate::settings::Settings;
#[test]
fn gitea_add_instnace_page_renders() {
let settings = Settings::new().unwrap();
GiteaAddInstanceTemplate::page(&settings);
let payload = AddGiteaInstance {
client_id: "foo".into(),
client_secret: "foo".into(),
url: Url::parse("https://example.org").unwrap(),
};
let page = GiteaAddInstanceTemplate::new(&settings, Some(&payload));
page.with_error(&ReadableError::new(&ServiceError::WrongPassword));
page.render();
}
}

View File

@ -0,0 +1,32 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use actix_web::*;
pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
pub mod add;
pub fn register_templates(t: &mut tera::Tera) {
for template in [add::GITEA_ADD_INSTANCE].iter() {
template.register(t).expect(template.name);
}
}
pub fn services(cfg: &mut web::ServiceConfig) {
add::services(cfg)
}

View File

@ -0,0 +1,118 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_web::http::header::ContentType;
use tera::Context;
use crate::db::AddGiteaInstance;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub struct GiteaAddInstanceTemplate {
ctx: RefCell<Context>,
}
pub const GITEA_SEARCH_INSTANCE: TemplateFile =
TemplateFile::new("gitea_add_instance", "pages/auth/gitea/add.html");
impl CtxError for GiteaAddInstanceTemplate {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl GiteaAddInstanceTemplate {
pub fn new(settings: &Settings, payload: Option<&AddGiteaInstance>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(payload) = payload {
ctx.borrow_mut().insert(PAYLOAD_KEY, payload);
}
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(GITEA_SEARCH_INSTANCE.name, &self.ctx.borrow())
.unwrap()
}
pub fn page(s: &Settings) -> String {
let p = Self::new(s, None);
p.render()
}
}
#[actix_web_codegen_const_routes::get(path = "PAGES.auth.gitea.add")]
#[tracing::instrument(name = "Serve add Gitea instance page", skip(ctx))]
pub async fn get_gitea_add_instance(ctx: AppCtx) -> impl Responder {
let login = GiteaAddInstanceTemplate::page(&ctx.settings);
let html = ContentType::html();
HttpResponse::Ok().content_type(html).body(login)
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_gitea_add_instance);
cfg.service(post_gitea_add_instance);
}
#[actix_web_codegen_const_routes::post(path = "PAGES.auth.gitea.add")]
#[tracing::instrument(name = "Submit new Gitea instance", skip(payload, ctx))]
pub async fn post_gitea_add_instance(
payload: web::Form<AddGiteaInstance>,
ctx: AppCtx,
) -> PageResult<impl Responder, GiteaAddInstanceTemplate> {
let payload = payload.into_inner();
ctx.init_gitea_instance(&payload).await.map_err(|e| {
PageError::new(
GiteaAddInstanceTemplate::new(&ctx.settings, Some(&payload)),
e,
)
})?;
Ok(HttpResponse::Found()
.insert_header((http::header::LOCATION, PAGES.dash.home))
.finish())
}
#[cfg(test)]
mod tests {
use url::Url;
use super::GiteaAddInstanceTemplate;
use crate::db::AddGiteaInstance;
use crate::errors::*;
use crate::pages::errors::*;
use crate::settings::Settings;
#[test]
fn gitea_add_instnace_page_renders() {
let settings = Settings::new().unwrap();
GiteaAddInstanceTemplate::page(&settings);
let payload = AddGiteaInstance {
client_id: "foo".into(),
client_secret: "foo".into(),
url: Url::parse("https://example.org").unwrap(),
};
let page = GiteaAddInstanceTemplate::new(&settings, Some(&payload));
page.with_error(&ReadableError::new(&ServiceError::WrongPassword));
page.render();
}
}

View File

@ -19,6 +19,7 @@ use actix_web::*;
pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
pub mod gitea;
pub mod login;
pub mod register;
#[cfg(test)]
@ -30,12 +31,14 @@ pub fn register_templates(t: &mut tera::Tera) {
for template in [AUTH_BASE, login::LOGIN, register::REGISTER].iter() {
template.register(t).expect(template.name);
}
gitea::register_templates(t);
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(signout);
register::services(cfg);
login::services(cfg);
gitea::services(cfg);
}
#[actix_web_codegen_const_routes::get(

View File

@ -1,193 +0,0 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use tera::Context;
use tracing::info;
use super::get_auth_middleware;
use crate::api::v1::forgejo::AddWebhook;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_FORGEJO_WEBHOOK_ADD: TemplateFile =
TemplateFile::new("dash_forgejo_webhook_add", "pages/dash/forgejo/add.html");
pub struct Add {
ctx: RefCell<Context>,
}
impl CtxError for Add {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl Add {
pub fn new(settings: &Settings) -> Self {
let ctx = RefCell::new(context(settings));
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_FORGEJO_WEBHOOK_ADD.name, &self.ctx.borrow())
.unwrap()
}
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.forgejo_webhook.add",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Dashboard add forgejo webhook webpage", skip(ctx))]
pub async fn get_add_forgejo_webhook(ctx: AppCtx) -> PageResult<impl Responder, Add> {
let add = Add::new(&ctx.settings).render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(add))
}
#[actix_web_codegen_const_routes::post(
path = "PAGES.dash.forgejo_webhook.add",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(
name = "Post Dashboard add Forgejo webhook webpage",
skip(ctx, id, payload)
)]
pub async fn post_add_forgejo_webhook(
ctx: AppCtx,
id: Identity,
payload: web::Form<AddWebhook>,
) -> PageResult<impl Responder, Add> {
let owner = id.identity().unwrap();
let payload = payload.into_inner();
info!(
"Adding webhook for Forgejo instance: {}",
payload.forgejo_url.as_str()
);
let hook = ctx
.db
.new_webhook(payload.forgejo_url, &owner)
.await
.map_err(|e| PageError::new(Add::new(&ctx.settings), e))?;
Ok(HttpResponse::Found()
.append_header((
http::header::LOCATION,
PAGES.dash.forgejo_webhook.get_view(&hook.auth_token),
))
.finish())
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_add_forgejo_webhook);
cfg.service(post_add_forgejo_webhook);
}
#[cfg(test)]
mod tests {
use actix_web::http::StatusCode;
use actix_web::test;
use url::Url;
use crate::api::v1::forgejo::AddWebhook;
use crate::ctx::ArcCtx;
use crate::tests;
use crate::*;
use super::PAGES;
#[actix_rt::test]
async fn postgres_dashboadr_add_forgejo_webhook_works() {
let (_, ctx) = tests::get_ctx().await;
dashboadr_add_forgejo_webhook_works(ctx.clone()).await;
}
async fn dashboadr_add_forgejo_webhook_works(ctx: ArcCtx) {
const NAME: &str = "testdashwebhookforgejoadduser";
const EMAIL: &str = "testdashwebhookforgejoadduser@foo.com";
const PASSWORD: &str = "longpassword";
let _ = ctx.delete_user(NAME, PASSWORD).await;
let (_, signin_resp) = ctx.register_and_signin(NAME, EMAIL, PASSWORD).await;
let cookies = get_cookie!(signin_resp);
let app = get_app!(ctx.clone()).await;
let resp = get_request!(&app, PAGES.dash.forgejo_webhook.add, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains("Add Forgejo Webhook"));
let payload = AddWebhook {
forgejo_url: Url::parse("https://git.batsense.net").unwrap(),
};
let add_webhook = test::call_service(
&app,
post_request!(&payload, PAGES.dash.forgejo_webhook.add, FORM)
.cookie(cookies.clone())
.to_request(),
)
.await;
assert_eq!(add_webhook.status(), StatusCode::FOUND);
let mut hooks = ctx.db.list_all_webhooks_with_owner(NAME).await.unwrap();
let hook = hooks.pop().unwrap();
// let mut event = ctx.db.list(&site.hostname).await.unwrap();
// let event = event.pop().unwrap();
let headers = add_webhook.headers();
let view_webhook_url = PAGES.dash.forgejo_webhook.get_view(&hook.auth_token);
assert_eq!(
headers.get(actix_web::http::header::LOCATION).unwrap(),
&view_webhook_url
);
// list webhooks
let resp = get_request!(&app, PAGES.dash.forgejo_webhook.list, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains(hook.forgejo_url.as_str()));
// view webhook
let resp = get_request!(&app, &view_webhook_url, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains("****"));
assert!(res.contains(
&crate::V1_API_ROUTES
.forgejo
.get_webhook_url(&ctx, &hook.auth_token)
));
let show_forgejo_webhook_secret =
format!("{view_webhook_url}?show_forgejo_webhook_secret=true");
let resp = get_request!(&app, &show_forgejo_webhook_secret, cookies.clone());
assert_eq!(resp.status(), StatusCode::OK);
let res = String::from_utf8(test::read_body(resp).await.to_vec()).unwrap();
assert!(res.contains(&hook.forgejo_webhook_secret));
}
}

View File

@ -1,93 +0,0 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use tera::Context;
use super::get_auth_middleware;
use crate::errors::ServiceResult;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_FORGEJO_WEBHOOK_LIST: TemplateFile =
TemplateFile::new("dash_forgejo_webhook_list", "pages/dash/forgejo/list.html");
pub struct List {
ctx: RefCell<Context>,
}
impl CtxError for List {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl List {
pub fn new(settings: &Settings, hooks: Option<&[TemplateForgejoWebhook]>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(hooks) = hooks {
ctx.borrow_mut().insert(PAYLOAD_KEY, hooks);
}
Self { ctx }
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_FORGEJO_WEBHOOK_LIST.name, &self.ctx.borrow())
.unwrap()
}
}
async fn get_webhook_data(
ctx: &AppCtx,
id: &Identity,
) -> ServiceResult<Vec<TemplateForgejoWebhook>> {
let db_hooks = ctx
.db
.list_all_webhooks_with_owner(&id.identity().unwrap())
.await?;
let mut hooks = Vec::with_capacity(db_hooks.len());
for hook in db_hooks {
hooks.push(TemplateForgejoWebhook::new(ctx, hook));
}
Ok(hooks)
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.forgejo_webhook.list",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "List all Forgejo webhooks", skip(ctx, id))]
pub async fn list_hooks(ctx: AppCtx, id: Identity) -> PageResult<impl Responder, List> {
let sites = get_webhook_data(&ctx, &id)
.await
.map_err(|e| PageError::new(List::new(&ctx.settings, None), e))?;
let home = List::new(&ctx.settings, Some(&sites)).render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(home))
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(list_hooks);
}

View File

@ -1,69 +0,0 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use actix_web::*;
use serde::{Deserialize, Serialize};
use super::get_auth_middleware;
pub use super::home::TemplateSite;
pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
use crate::ctx::Ctx;
use crate::db::ForgejoWebhook;
pub mod add;
pub mod list;
pub mod view;
pub fn register_templates(t: &mut tera::Tera) {
add::DASH_FORGEJO_WEBHOOK_ADD
.register(t)
.expect(add::DASH_FORGEJO_WEBHOOK_ADD.name);
list::DASH_FORGEJO_WEBHOOK_LIST
.register(t)
.expect(list::DASH_FORGEJO_WEBHOOK_LIST.name);
view::DASH_FORGEJO_WEBHOOK_VIEW
.register(t)
.expect(view::DASH_FORGEJO_WEBHOOK_VIEW.name);
}
pub fn services(cfg: &mut web::ServiceConfig) {
add::services(cfg);
list::services(cfg);
view::services(cfg);
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct TemplateForgejoWebhook {
pub webhook: ForgejoWebhook,
pub view: String,
pub url: String,
}
impl TemplateForgejoWebhook {
pub fn new(ctx: &Ctx, hook: ForgejoWebhook) -> Self {
let view = PAGES.dash.forgejo_webhook.get_view(&hook.auth_token);
let url = crate::V1_API_ROUTES
.forgejo
.get_webhook_url(ctx, &hook.auth_token);
Self {
webhook: hook,
view,
url,
}
}
}

View File

@ -1,108 +0,0 @@
/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* 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 <https://www.gnu.org/licenses/>.
*/
use std::cell::RefCell;
use actix_identity::Identity;
use actix_web::http::header::ContentType;
use serde::{Deserialize, Serialize};
use tera::Context;
use super::get_auth_middleware;
use crate::pages::errors::*;
use crate::settings::Settings;
use crate::AppCtx;
pub use super::*;
pub const DASH_FORGEJO_WEBHOOK_VIEW: TemplateFile =
TemplateFile::new("dash_forgejo_webhook_view", "pages/dash/forgejo/view.html");
const SHOW_FORGEJO_WEBHOOK_SECRET_KEY: &str = "show_forgejo_webhook_secret";
pub struct View {
ctx: RefCell<Context>,
}
impl CtxError for View {
fn with_error(&self, e: &ReadableError) -> String {
self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
}
}
impl View {
pub fn new(settings: &Settings, payload: Option<TemplateForgejoWebhook>) -> Self {
let ctx = RefCell::new(context(settings));
if let Some(payload) = payload {
ctx.borrow_mut().insert(PAYLOAD_KEY, &payload);
}
Self { ctx }
}
pub fn show_forgejo_webhook_secret(&mut self) {
self.ctx
.borrow_mut()
.insert(SHOW_FORGEJO_WEBHOOK_SECRET_KEY, &true);
}
pub fn render(&self) -> String {
TEMPLATES
.render(DASH_FORGEJO_WEBHOOK_VIEW.name, &self.ctx.borrow())
.unwrap()
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct ViewOptions {
show_forgejo_webhook_secret: Option<bool>,
}
#[actix_web_codegen_const_routes::get(
path = "PAGES.dash.forgejo_webhook.view",
wrap = "get_auth_middleware()"
)]
#[tracing::instrument(name = "Dashboard Forgejo webhook webpage", skip(ctx, id))]
pub async fn get_view_site(
ctx: AppCtx,
id: Identity,
path: web::Path<String>,
query: web::Query<ViewOptions>,
) -> PageResult<impl Responder, View> {
let auth_token = path.into_inner();
let owner = id.identity().unwrap();
let hook = ctx
.db
.get_webhook_with_owner(&auth_token, &owner)
.await
.map_err(|e| PageError::new(View::new(&ctx.settings, None), e))?;
let payload = TemplateForgejoWebhook::new(&ctx, hook);
let mut page = View::new(&ctx.settings, Some(payload));
if let Some(true) = query.show_forgejo_webhook_secret {
page.show_forgejo_webhook_secret();
}
let add = page.render();
let html = ContentType::html();
Ok(HttpResponse::Ok().content_type(html).body(add))
}
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(get_view_site);
}

View File

@ -24,7 +24,6 @@ pub use super::{context, Footer, TemplateFile, PAGES, PAYLOAD_KEY, TEMPLATES};
use crate::db::Event;
use crate::db::LibrePagesEvent;
pub mod forgejo;
pub mod home;
pub mod sites;
@ -50,11 +49,9 @@ impl From<LibrePagesEvent> for TemplateSiteEvent {
pub fn register_templates(t: &mut tera::Tera) {
home::DASH_HOME.register(t).expect(home::DASH_HOME.name);
sites::register_templates(t);
forgejo::register_templates(t);
}
pub fn services(cfg: &mut web::ServiceConfig) {
home::services(cfg);
sites::services(cfg);
forgejo::services(cfg);
}

View File

@ -41,6 +41,25 @@ impl Pages {
}
}
#[derive(Serialize)]
/// Gitea authentication routes
pub struct Gitea {
/// add Gitea instance route
pub add: &'static str,
/// search Gitea instance route
pub search: &'static str,
}
impl Gitea {
/// create new instance of Authentication route
pub const fn new() -> Self {
let add = "/gitea/add";
let search = "/gitea/search";
Self { add, search }
}
}
#[derive(Serialize)]
/// Authentication routes
pub struct Auth {
@ -50,6 +69,8 @@ pub struct Auth {
pub login: &'static str,
/// registration route
pub register: &'static str,
/// gitea authentication routes
pub gitea: Gitea,
}
impl Auth {
@ -58,10 +79,12 @@ impl Auth {
let login = "/login";
let logout = "/logout";
let register = "/join";
let gitea = Gitea::new();
Auth {
logout,
login,
register,
gitea,
}
}
}
@ -72,7 +95,6 @@ pub struct Dash {
/// home route
pub home: &'static str,
pub site: DashSite,
pub forgejo_webhook: ForgejoWebhook,
}
impl Dash {
@ -80,37 +102,7 @@ impl Dash {
pub const fn new() -> Dash {
let home = "/dash";
let site = DashSite::new();
let forgejo_webhook = ForgejoWebhook::new();
Dash {
home,
site,
forgejo_webhook,
}
}
}
#[derive(Serialize)]
/// Dashboard ForgejoWebhook routes
pub struct ForgejoWebhook {
/// add forgejo webhook route
pub add: &'static str,
/// view forgejo webhook route
pub view: &'static str,
/// list forgejo webhooks route
pub list: &'static str,
}
impl ForgejoWebhook {
/// create new instance of ForgejoWebhook route
pub const fn new() -> ForgejoWebhook {
let add = "/dash/forgejo/webhook/add";
let list = "/dash/forgejo/webhook/list";
let view = "/dash/forgejo/webhook/view/{auth_token}";
ForgejoWebhook { add, view, list }
}
pub fn get_view(&self, auth_token: &str) -> String {
self.view.replace("{auth_token}", auth_token)
Dash { home, site }
}
}

View File

@ -136,6 +136,15 @@ impl Settings {
Err(e) => warn!("couldn't interpret PORT: {}", e),
}
if let Ok(val) = env::var("DATABASE_URL") {
let url = Url::parse(&val).expect("couldn't parse Database URL");
s = s.set_override("database.url", url.to_string()).unwrap();
let database_type = DBType::from_url(&url).unwrap();
s = s
.set_override("database.database_type", database_type.to_string())
.unwrap();
}
let intermediate_config = s.build_cloned().unwrap();
s = s
@ -162,15 +171,6 @@ impl Settings {
)
.expect("Couldn't set database url");
if let Ok(val) = env::var("DATABASE_URL") {
let url = Url::parse(&val).expect("couldn't parse Database URL");
s = s.set_override("database.url", url.to_string()).unwrap();
let database_type = DBType::from_url(&url).unwrap();
s = s
.set_override("database.database_type", database_type.to_string())
.unwrap();
}
let settings = s.build()?.try_deserialize::<Settings>()?;
settings.check_url();

View File

@ -16,11 +16,6 @@
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.dash.site.add }}">New Site</a>
</div>
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.dash.forgejo_webhook.list }}">Webhooks</a>
</div>
<div class="nav__link-container">
<a class="nav__link" rel="noreferrer" href="{{ page.auth.logout }}">Log out</a>
</div>

View File

@ -0,0 +1,62 @@
{% extends 'authbase' %}
{% block login %}
<h2>Add Gitea Instance</h2>
<form action="{{ page.auth.gitea.add }}" method="POST" class="auth-form" accept-charset="utf-8">
{% include "error_comp" %}
<label class="auth-form__label" for="url">
Gitea URL
<input
class="auth-form__input"
name="url"
autofocus
required
id="url"
type="url"
{% if payload.url %}
value={{ payload.url }}
{% endif %}
/>
</label>
<label class="auth-form__label" for="client_id">
Client ID
<input
class="auth-form__input"
name="client_id"
autofocus
required
id="client_id"
type="text"
{% if payload.client_id %}
value={{ payload.client_id }}
{% endif %}
/>
</label>
<label class="auth-form__label" for="client_secret">
Client Secret
<input
class="auth-form__input"
name="client_secret"
required
id="client_secret"
type="password"
{% if payload.client_secret %}
value={{ payload.client_secret }}
{% endif %}
/>
</label>
<div class="auth-form__action-container">
<button class="auth-form__submit" type="submit">Login</button>
</div>
</form>
<!--
<p class="auth-form__alt-action">
New to LibrePages?
<a href="{{ page.auth.register }}">Create an account </a>
</p>
-->
{% endblock %}

View File

@ -0,0 +1,62 @@
{% extends 'authbase' %}
{% block login %}
<h2>Add Gitea Instance</h2>
<form action="{{ page.auth.gitea.add }}" method="POST" class="auth-form" accept-charset="utf-8">
{% include "error_comp" %}
<label class="auth-form__label" for="url">
Gitea URL
<input
class="auth-form__input"
name="url"
autofocus
required
id="url"
type="url"
{% if payload.url %}
value={{ payload.url }}
{% endif %}
/>
</label>
<label class="auth-form__label" for="client_id">
Client ID
<input
class="auth-form__input"
name="client_id"
autofocus
required
id="client_id"
type="text"
{% if payload.client_id %}
value={{ payload.client_id }}
{% endif %}
/>
</label>
<label class="auth-form__label" for="client_secret">
Client Secret
<input
class="auth-form__input"
name="client_secret"
required
id="client_secret"
type="password"
{% if payload.client_secret %}
value={{ payload.client_secret }}
{% endif %}
/>
</label>
<div class="auth-form__action-container">
<button class="auth-form__submit" type="submit">Login</button>
</div>
</form>
<!--
<p class="auth-form__alt-action">
New to LibrePages?
<a href="{{ page.auth.register }}">Create an account </a>
</p>
-->
{% endblock %}

View File

@ -1,23 +0,0 @@
{% extends 'base' %}{% block title %} Add Forgejo Webhook{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="add-site__container">
<form class="auth-form" action="{{ page.dash.forgejo_webhook.add }}" method="POST">
<label class="auth-form__label" for="forgejo_url">
Forgejo instance URL
<input
type="url"
name="forgejo_url"
id="forgejo_url"
class="auth-form__input"
/>
</label>
<div class="auth-form__action-container">
<button class="auth-form__submit" type="submit">Add Webhook</button>
</div>
</form>
</div>
</main>
{% endblock main %}

View File

@ -1,33 +0,0 @@
{% extends 'base' %}{% block title %} Forgejo Webhooks{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="sites__collection">
<div class="sites__actions">
<a class="sites__actions__new-site" href="{{ page.dash.forgejo_webhook.add }}">
<button>Add New Forgejo Webhook</button>
</a>
</div>
{% if payload|length > 0 %}
{% for hook in payload %}
<a href="{{ hook.view }}" class="site__container">
<div class="site__info--head">
<img
class="site__container--preview"
src="{{ hook.webhook.forgejo_url }}/favicon.ico"
alt="Webhook icon"
/>
<div class="site__info--column">
<p><b>{{ hook.webhook.forgejo_url }}</b></p>
<p>Forgejo instance {{ hook.webhook.forgejo_url }}</p>
</div>
</div>
</a>
{% endfor %}
{% else %}
<p class="sites__banner">Nothing to show, click <a href="{{page.dash.forgejo_webhook.add}}">here</a> to add new Forgejo webhook!</p>
{% endif %}
</div>
</main>
{% endblock main %}

View File

@ -1,32 +0,0 @@
{% extends 'base' %}{% block title %} {{ payload.webhook.forgejo_url }}{% endblock title %} {% block nav
%} {% include "auth_nav" %} {% endblock nav %} {% block main %}
<main class="sites__main">
<div class="add-site__container">
<section>
<table>
<tr>
<th>Webhook URL</th>
<td>{{ payload.url }}</td>
</tr>
<tr>
<th>Secret</th>
<td>
{% if show_forgejo_webhook_secret %}
{{ payload.webhook.forgejo_webhook_secret }} <a href="{{ payload.view }}">Hide</a>
{% else %}
****
<a href="{{ payload.view }}?show_forgejo_webhook_secret=true">
Show
</a>
{% endif %}
</td>
</tr>
</table>
</section>
</div>
</main>
{% endblock main %}

View File

@ -15,7 +15,7 @@
<img
class="site__container--preview"
src="{{ deployment.site.hostname }}/favicon.ico"
alt="Website icon"
alt="{{ deployment.site.hostname }}'s favicon"
/>
<div class="site__info--column">
<p><b>{{ deployment.site.hostname }}</b></p>

View File

@ -167,15 +167,6 @@ version = "0.2.125"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"
[[package]]
name = "librepages"
version = "0.1.0"
dependencies = [
"cache-buster",
"serde",
"serde_json",
]
[[package]]
name = "mime"
version = "0.3.16"
@ -192,6 +183,15 @@ dependencies = [
"unicase",
]
[[package]]
name = "pages"
version = "0.1.0"
dependencies = [
"cache-buster",
"serde",
"serde_json",
]
[[package]]
name = "proc-macro2"
version = "1.0.38"

View File

@ -1,11 +1,11 @@
[package]
name = "librepages"
name = "pages"
version = "0.1.0"
edition = "2021"
homepage = "https://git.batsense.net/LibrePages/librepages"
repository = "https://git.batsense.net/LibrePages/librepages"
documentation = "https://github.con/realaravinth/librepages"
readme = "https://git.batsense.net/LibrePages/librepages/blob/master/README.md"
homepage = "https://github.com/realaravinth/pages"
repository = "https://github.com/realaravinth/pages"
documentation = "https://github.con/realaravinth/pages"
readme = "https://github.com/realaravinth/pages/blob/master/README.md"
license = "AGPLv3 or later version"
authors = ["realaravinth <realaravinth@batsense.net>"]