Compare commits

..

1 Commits

Author SHA1 Message Date
8750d950d9 Add renovate.json 2025-01-16 00:39:01 +00:00
15 changed files with 7 additions and 3550 deletions

2
.gitignore vendored
View File

@ -1,3 +1 @@
storage storage
.idea
target

3145
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +0,0 @@
[package]
name = "matrix_gateway"
version = "0.1.0"
edition = "2021"
[dependencies]
log = "0.4.25"
env_logger = "0.11.6"
clap = { version = "4.5.26", features = ["derive", "env"] }
lazy_static = "1.5.0"
anyhow = "1.0.95"
serde = { version = "1.0.217", features = ["derive"] }
rust-s3 = "0.36.0-beta.2"
actix-web = "4"
actix-session = { version = "0.10.1", features = ["redis-session"] }
light-openid = "1.0.2"
thiserror = "2.0.11"
rand = "0.9.0-beta.3"

View File

@ -4,7 +4,7 @@ WIP project
## Setup dev environment ## Setup dev environment
``` ```
mkdir -p storage/postgres storage/synapse storage/minio mkdir -p storage/postgres storage/synapse
docker compose up docker compose up
``` ```
@ -12,11 +12,8 @@ URLs:
* Element: http://localhost:8080/ * Element: http://localhost:8080/
* Synapse: http://localhost:8448/ * Synapse: http://localhost:8448/
* OpenID configuration: http://127.0.0.1:9001/dex/.well-known/openid-configuration * OpenID configuration: http://127.0.0.1:9001/dex/.well-known/openid-configuration
* Minio console: http://localhost:9002/
Auto-created Matrix accounts: Auto-created Matrix accounts:
* `admin1` : `admin1` * `admin1` : `admin1`
* `user1` : `user1` * `user1` : `user1`
Minio administration credentials: `minioadmin` : `minioadmin`

View File

@ -63,25 +63,3 @@ services:
volumes: volumes:
- ./docker/dex:/conf:ro - ./docker/dex:/conf:ro
command: ["dex", "serve", "/conf/dex.config.yaml"] command: ["dex", "serve", "/conf/dex.config.yaml"]
minio:
image: quay.io/minio/minio
command: minio server --console-address ":9002" /data
ports:
- 9000:9000/tcp
- 9002:9002/tcp
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
volumes:
# You may store the database tables in a local folder..
- ./storage/minio:/data
redis:
image: redis:alpine
command: redis-server --requirepass ${REDIS_PASS:-secretredis}
ports:
- 6379:6379
volumes:
- ./storage/redis-data:/data
- ./storage/redis-conf:/usr/local/etc/redis/redis.conf

View File

@ -22,5 +22,5 @@ staticClients:
- id: foo - id: foo
secret: bar secret: bar
redirectURIs: redirectURIs:
- http://localhost:8000/oidc_cb - http://localhost:3000/oidc_cb
name: Project name: Project

3
renovate.json Normal file
View File

@ -0,0 +1,3 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
}

View File

@ -1,157 +0,0 @@
use clap::Parser;
use s3::creds::Credentials;
use s3::{Bucket, Region};
/// GeneIT backend API
#[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)]
pub struct AppConfig {
/// Listen address
#[clap(short, long, env, default_value = "0.0.0.0:8000")]
pub listen_address: String,
/// Website origin
#[clap(short, long, env, default_value = "http://localhost:8000")]
pub website_origin: String,
/// Proxy IP, might end with a star "*"
#[clap(short, long, env)]
pub proxy_ip: Option<String>,
/// Matrix API origin
#[clap(short, long, env, default_value = "http://127.0.0.1:8448")]
pub matrix_api: String,
/// Redis connection hostname
#[clap(long, env, default_value = "localhost")]
redis_hostname: String,
/// Redis connection port
#[clap(long, env, default_value_t = 6379)]
redis_port: u16,
/// Redis database number
#[clap(long, env, default_value_t = 0)]
redis_db_number: i64,
/// Redis username
#[clap(long, env)]
redis_username: Option<String>,
/// Redis password
#[clap(long, env, default_value = "secretredis")]
redis_password: String,
/// URL where the OpenID configuration can be found
#[arg(
long,
env,
default_value = "http://localhost:9001/dex/.well-known/openid-configuration"
)]
pub oidc_configuration_url: String,
/// OpenID client ID
#[arg(long, env, default_value = "foo")]
pub oidc_client_id: String,
/// OpenID client secret
#[arg(long, env, default_value = "bar")]
pub oidc_client_secret: String,
/// OpenID login redirect URL
#[arg(long, env, default_value = "APP_ORIGIN/oidc_cb")]
oidc_redirect_url: String,
/// S3 Bucket name
#[arg(long, env, default_value = "matrix-gw")]
s3_bucket_name: String,
/// S3 region (if not using Minio)
#[arg(long, env, default_value = "eu-central-1")]
s3_region: String,
/// S3 API endpoint
#[arg(long, env, default_value = "http://localhost:9000")]
s3_endpoint: String,
/// S3 access key
#[arg(long, env, default_value = "topsecret")]
s3_access_key: String,
/// S3 secret key
#[arg(long, env, default_value = "topsecret")]
s3_secret_key: String,
/// S3 skip auto create bucket if not existing
#[arg(long, env)]
pub s3_skip_auto_create_bucket: bool,
}
lazy_static::lazy_static! {
static ref ARGS: AppConfig = {
AppConfig::parse()
};
}
impl AppConfig {
/// Get parsed command line arguments
pub fn get() -> &'static AppConfig {
&ARGS
}
/// Get Redis connection configuration
pub fn redis_connection_string(&self) -> String {
format!(
"redis://{}:{}@{}:{}/{}",
self.redis_username.as_deref().unwrap_or(""),
self.redis_password,
self.redis_hostname,
self.redis_port,
self.redis_db_number
)
}
/// Get OpenID providers configuration
pub fn openid_provider(&self) -> OIDCProvider<'_> {
OIDCProvider {
client_id: self.oidc_client_id.as_str(),
client_secret: self.oidc_client_secret.as_str(),
configuration_url: self.oidc_configuration_url.as_str(),
redirect_url: self
.oidc_redirect_url
.replace("APP_ORIGIN", &self.website_origin),
}
}
/// Get s3 bucket credentials
pub fn s3_credentials(&self) -> anyhow::Result<Credentials> {
Ok(Credentials::new(
Some(&self.s3_access_key),
Some(&self.s3_secret_key),
None,
None,
None,
)?)
}
/// Get S3 bucket
pub fn s3_bucket(&self) -> anyhow::Result<Box<Bucket>> {
Ok(Bucket::new(
&self.s3_bucket_name,
Region::Custom {
region: self.s3_region.to_string(),
endpoint: self.s3_endpoint.to_string(),
},
self.s3_credentials()?,
)?
.with_path_style())
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct OIDCProvider<'a> {
pub client_id: &'a str,
pub client_secret: &'a str,
pub configuration_url: &'a str,
pub redirect_url: String,
}

View File

@ -1,5 +0,0 @@
/// Session key for OpenID login state
pub const STATE_KEY: &str = "oidc-state";
/// Session key for user information
pub const USER_SESSION_KEY: &str = "user";

View File

@ -1,5 +0,0 @@
pub mod app_config;
pub mod constants;
pub mod server;
pub mod user;
pub mod utils;

View File

@ -1,41 +0,0 @@
use actix_session::{storage::RedisSessionStore, SessionMiddleware};
use actix_web::cookie::Key;
use actix_web::{web, App, HttpServer};
use matrix_gateway::app_config::AppConfig;
use matrix_gateway::server::web_ui;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
// FIXME : not scalable
let secret_key = Key::generate();
let redis_store = RedisSessionStore::new(AppConfig::get().redis_connection_string())
.await
.expect("Failed to connect to Redis!");
log::info!(
"Starting to listen on {} for {}",
AppConfig::get().listen_address,
AppConfig::get().website_origin
);
HttpServer::new(move || {
App::new()
// Add session management to your application using Redis for session state storage
.wrap(SessionMiddleware::new(
redis_store.clone(),
secret_key.clone(),
))
// Web configuration routes
.route("/", web::get().to(web_ui::home))
.route("/oidc_cb", web::get().to(web_ui::oidc_cb))
.route("/sign_out", web::get().to(web_ui::sign_out))
// API routes
// TODO
})
.bind(&AppConfig::get().listen_address)?
.run()
.await
}

View File

@ -1,37 +0,0 @@
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use std::error::Error;
pub mod web_ui;
#[derive(thiserror::Error, Debug)]
pub enum HttpFailure {
#[error("this resource requires higher privileges")]
Forbidden,
#[error("this resource was not found")]
NotFound,
#[error("an unhandled session insert error occurred")]
SessionInsertError(#[from] actix_session::SessionInsertError),
#[error("an unhandled session error occurred")]
SessionError(#[from] actix_session::SessionGetError),
#[error("an unspecified open id error occurred: {0}")]
OpenID(Box<dyn Error>),
#[error("an unspecified internal error occurred: {0}")]
InternalError(#[from] anyhow::Error),
}
impl ResponseError for HttpFailure {
fn status_code(&self) -> StatusCode {
match &self {
Self::Forbidden => StatusCode::FORBIDDEN,
Self::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
pub type HttpResult = std::result::Result<HttpResponse, HttpFailure>;

View File

@ -1,96 +0,0 @@
use crate::app_config::AppConfig;
use crate::constants::{STATE_KEY, USER_SESSION_KEY};
use crate::server::{HttpFailure, HttpResult};
use crate::user::{User, UserID};
use crate::utils;
use actix_session::Session;
use actix_web::{web, HttpResponse};
use light_openid::primitives::OpenIDConfig;
/// Main route
pub async fn home(session: Session) -> HttpResult {
// Get user information, requesting authentication if information is missing
let Some(user): Option<User> = session.get(USER_SESSION_KEY)? else {
// Generate auth state
let state = utils::rand_str(50);
session.insert(STATE_KEY, &state)?;
let oidc = AppConfig::get().openid_provider();
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
.await
.map_err(HttpFailure::OpenID)?;
let auth_url = config.gen_authorization_url(oidc.client_id, &state, &oidc.redirect_url);
return Ok(HttpResponse::Found()
.append_header(("location", auth_url))
.finish());
};
Ok(HttpResponse::Ok().body("You are authenticated!"))
}
#[derive(serde::Deserialize)]
pub struct AuthCallbackQuery {
code: String,
state: String,
}
/// Authenticate user callback
pub async fn oidc_cb(session: Session, query: web::Query<AuthCallbackQuery>) -> HttpResult {
if session.get(STATE_KEY)? != Some(query.state.to_string()) {
return Ok(HttpResponse::BadRequest()
.append_header(("content-type", "text/html"))
.body("State mismatch! <a href='/'>Try again</a>"));
}
let oidc = AppConfig::get().openid_provider();
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
.await
.map_err(HttpFailure::OpenID)?;
let (token, _) = match config
.request_token(
oidc.client_id,
oidc.client_secret,
&query.code,
&oidc.redirect_url,
)
.await
{
Ok(t) => t,
Err(e) => {
log::error!("Failed to request user token! {e}");
return Ok(HttpResponse::BadRequest()
.append_header(("content-type", "text/html"))
.body("Authentication failed! <a href='/'>Try again</a>"));
}
};
let (user, _) = config
.request_user_info(&token)
.await
.map_err(HttpFailure::OpenID)?;
let user = User {
id: UserID(user.sub),
name: user.name.unwrap_or("no_name".to_string()),
email: user.email.unwrap_or("no@mail.com".to_string()),
};
log::info!("Successful authentication as {:?}", user);
session.insert(USER_SESSION_KEY, user)?;
Ok(HttpResponse::Found()
.insert_header(("location", "/"))
.finish())
}
/// De-authenticate user
pub async fn sign_out(session: Session) -> HttpResult {
session.remove(USER_SESSION_KEY);
Ok(HttpResponse::Found()
.insert_header(("location", "/"))
.finish())
}

View File

@ -1,9 +0,0 @@
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct UserID(pub String);
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct User {
pub id: UserID,
pub name: String,
pub email: String,
}

View File

@ -1,6 +0,0 @@
use rand::distr::{Alphanumeric, SampleString};
// Generate a random string of a given size
pub fn rand_str(len: usize) -> String {
Alphanumeric.sample_string(&mut rand::rng(), len)
}