feat: add GitHub sign-in and channel webhooks
This commit is contained in:
parent
45e89f9826
commit
ff9c8f330e
36 changed files with 3240 additions and 24 deletions
77
hub/src/auth/mod.rs
Normal file
77
hub/src/auth/mod.rs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
pub mod provider;
|
||||
mod routes;
|
||||
pub mod store;
|
||||
|
||||
use sqlx::SqlitePool;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
use provider::{GitHubProvider, IdentityProvider};
|
||||
pub use routes::router;
|
||||
|
||||
/// Secrets are never Debug/Serialize and never sent to browser or community nodes.
|
||||
pub struct GitHubConfig {
|
||||
pub client_id: String,
|
||||
pub client_secret: String,
|
||||
}
|
||||
|
||||
pub struct AuthService {
|
||||
pub pool: SqlitePool,
|
||||
pub origin: Url,
|
||||
pub provider: Option<Arc<dyn IdentityProvider>>,
|
||||
limits: Mutex<HashMap<String, (i64, u32)>>,
|
||||
}
|
||||
|
||||
impl AuthService {
|
||||
pub fn new(
|
||||
pool: SqlitePool,
|
||||
origin: Url,
|
||||
config: Option<&GitHubConfig>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let provider = config
|
||||
.map(|config| {
|
||||
GitHubProvider::new(config, &origin)
|
||||
.map(|provider| Arc::new(provider) as Arc<dyn IdentityProvider>)
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(Self::with_provider(pool, origin, provider))
|
||||
}
|
||||
pub fn with_provider(
|
||||
pool: SqlitePool,
|
||||
origin: Url,
|
||||
provider: Option<Arc<dyn IdentityProvider>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
pool,
|
||||
origin,
|
||||
provider,
|
||||
limits: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
pub fn configured(&self) -> bool {
|
||||
self.provider.is_some()
|
||||
}
|
||||
pub fn allow(&self, ip: &str) -> bool {
|
||||
let Ok(mut limits) = self.limits.lock() else {
|
||||
return false;
|
||||
};
|
||||
let now = store::now();
|
||||
limits.retain(|_, (start, _)| now - *start < 60);
|
||||
if limits.len() > 4096 {
|
||||
return false;
|
||||
}
|
||||
if limits.get(ip).is_some_and(|(_, count)| *count >= 20) {
|
||||
return false;
|
||||
}
|
||||
let global = limits.entry("global".into()).or_insert((now, 0));
|
||||
if global.1 >= 300 {
|
||||
return false;
|
||||
}
|
||||
global.1 += 1;
|
||||
limits.entry(ip.to_owned()).or_insert((now, 0)).1 += 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
155
hub/src/auth/provider.rs
Normal file
155
hub/src/auth/provider.rs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
use std::{future::Future, pin::Pin, time::Duration};
|
||||
|
||||
use oauth2::{
|
||||
AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointNotSet,
|
||||
EndpointSet, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, TokenResponse, TokenUrl,
|
||||
basic::BasicClient,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use url::Url;
|
||||
|
||||
use super::GitHubConfig;
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub struct GitHubProfile {
|
||||
pub id: u64,
|
||||
pub login: String,
|
||||
pub name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProviderError;
|
||||
impl std::fmt::Display for ProviderError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("GitHub authentication failed")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ProviderError {}
|
||||
|
||||
pub trait IdentityProvider: Send + Sync {
|
||||
fn authorize(&self, state: CsrfToken, challenge: PkceCodeChallenge) -> Url;
|
||||
fn identify<'a>(
|
||||
&'a self,
|
||||
code: &'a str,
|
||||
verifier: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<GitHubProfile, ProviderError>> + Send + 'a>>;
|
||||
}
|
||||
|
||||
type Client = BasicClient<EndpointSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointSet>;
|
||||
pub struct GitHubProvider {
|
||||
oauth: Client,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
impl GitHubProvider {
|
||||
pub fn new(config: &GitHubConfig, origin: &Url) -> anyhow::Result<Self> {
|
||||
let callback = origin.join("/v1/auth/github/callback")?;
|
||||
Ok(Self {
|
||||
oauth: BasicClient::new(ClientId::new(config.client_id.clone()))
|
||||
.set_client_secret(ClientSecret::new(config.client_secret.clone()))
|
||||
.set_auth_type(AuthType::RequestBody)
|
||||
.set_auth_uri(AuthUrl::new(
|
||||
"https://github.com/login/oauth/authorize".into(),
|
||||
)?)
|
||||
.set_token_uri(TokenUrl::new(
|
||||
"https://github.com/login/oauth/access_token".into(),
|
||||
)?)
|
||||
.set_redirect_uri(RedirectUrl::new(callback.to_string())?),
|
||||
http: reqwest::Client::builder()
|
||||
.https_only(true)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.no_proxy()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(15))
|
||||
.user_agent("Vnox-Central/0.1")
|
||||
.build()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl IdentityProvider for GitHubProvider {
|
||||
fn authorize(&self, state: CsrfToken, challenge: PkceCodeChallenge) -> Url {
|
||||
// Public identity only: no repository/private-email/offline access scopes.
|
||||
self.oauth
|
||||
.authorize_url(|| state)
|
||||
.set_pkce_challenge(challenge)
|
||||
.url()
|
||||
.0
|
||||
}
|
||||
|
||||
fn identify<'a>(
|
||||
&'a self,
|
||||
code: &'a str,
|
||||
verifier: &'a str,
|
||||
) -> Pin<Box<dyn Future<Output = Result<GitHubProfile, ProviderError>> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let http = self.http.clone();
|
||||
let transport = move |request: oauth2::HttpRequest| {
|
||||
let http = http.clone();
|
||||
async move {
|
||||
let (parts, body) = request.into_parts();
|
||||
let response = http
|
||||
.request(parts.method, parts.uri.to_string())
|
||||
.headers(parts.headers)
|
||||
.body(body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| ProviderError)?;
|
||||
let mut builder = oauth2::http::Response::builder().status(response.status());
|
||||
for (name, value) in response.headers() {
|
||||
builder = builder.header(name, value);
|
||||
}
|
||||
let body = bounded_body(response, 32 * 1024).await?;
|
||||
builder.body(body).map_err(|_| ProviderError)
|
||||
}
|
||||
};
|
||||
let token = self
|
||||
.oauth
|
||||
.exchange_code(AuthorizationCode::new(code.into()))
|
||||
.set_pkce_verifier(PkceCodeVerifier::new(verifier.into()))
|
||||
.request_async(&transport)
|
||||
.await
|
||||
.map_err(|_| ProviderError)?;
|
||||
let response = self
|
||||
.http
|
||||
.get("https://api.github.com/user")
|
||||
.header(reqwest::header::ACCEPT, "application/vnd.github+json")
|
||||
.bearer_auth(token.access_token().secret())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| ProviderError)?;
|
||||
if !response.status().is_success() {
|
||||
return Err(ProviderError);
|
||||
}
|
||||
let profile: GitHubProfile =
|
||||
serde_json::from_slice(&bounded_body(response, 64 * 1024).await?)
|
||||
.map_err(|_| ProviderError)?;
|
||||
if profile.id == 0 || profile.login.is_empty() || profile.login.len() > 100 {
|
||||
return Err(ProviderError);
|
||||
}
|
||||
Ok(profile)
|
||||
// Provider tokens are dropped: no permanent storage or forwarding to clients/nodes.
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn bounded_body(
|
||||
mut response: reqwest::Response,
|
||||
maximum: usize,
|
||||
) -> Result<Vec<u8>, ProviderError> {
|
||||
if response
|
||||
.content_length()
|
||||
.is_some_and(|length| length > maximum as u64)
|
||||
{
|
||||
return Err(ProviderError);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await.map_err(|_| ProviderError)? {
|
||||
if body.len().saturating_add(chunk.len()) > maximum {
|
||||
return Err(ProviderError);
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
186
hub/src/auth/routes.rs
Normal file
186
hub/src/auth/routes.rs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
use super::{AuthService, store};
|
||||
use crate::web::HubState;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use cookie::{Cookie, SameSite};
|
||||
use oauth2::{CsrfToken, PkceCodeChallenge};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use subtle::ConstantTimeEq;
|
||||
const BROWSER: &str = "__Host-vnox_oauth";
|
||||
const SESSION: &str = "__Host-vnox_session";
|
||||
pub fn router() -> Router<Arc<HubState>> {
|
||||
Router::new()
|
||||
.route("/v1/auth/github/start", get(start))
|
||||
.route("/v1/auth/github/callback", get(callback))
|
||||
.route("/v1/auth/session", get(session))
|
||||
.route("/v1/auth/logout", post(logout))
|
||||
}
|
||||
fn failure(status: StatusCode, code: &'static str) -> Response {
|
||||
(status, Json(json!({"error":code}))).into_response()
|
||||
}
|
||||
fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
let mut found = None;
|
||||
let mut size = 0;
|
||||
for value in headers.get_all(header::COOKIE) {
|
||||
size += value.len();
|
||||
if size > 8192 {
|
||||
return None;
|
||||
}
|
||||
for part in value.to_str().ok()?.split(';') {
|
||||
let parsed = Cookie::parse(part.trim().to_owned()).ok()?;
|
||||
if parsed.name() == name {
|
||||
if found.is_some()
|
||||
|| parsed.value().len() != 64
|
||||
|| !parsed.value().bytes().all(|c| c.is_ascii_hexdigit())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
found = Some(parsed.value().to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
fn set_cookie(response: &mut Response, name: &'static str, value: String, ttl: i64) {
|
||||
let value = Cookie::build((name, value))
|
||||
.secure(true)
|
||||
.http_only(true)
|
||||
.same_site(SameSite::Lax)
|
||||
.path("/")
|
||||
.max_age(cookie::time::Duration::seconds(ttl))
|
||||
.build()
|
||||
.to_string();
|
||||
response
|
||||
.headers_mut()
|
||||
.append(header::SET_COOKIE, value.parse().expect("generated cookie"));
|
||||
}
|
||||
fn allowed(auth: &AuthService, headers: &HeaderMap) -> bool {
|
||||
// The loopback-only service trusts only the reverse proxy, which overwrites this header.
|
||||
let ip = headers
|
||||
.get("x-forwarded-for")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.parse::<std::net::IpAddr>().ok())
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_else(|| "local".into());
|
||||
auth.allow(&ip)
|
||||
}
|
||||
async fn start(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
|
||||
let auth = &state.auth;
|
||||
let Some(provider) = &auth.provider else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "github_not_configured");
|
||||
};
|
||||
if !allowed(auth, &headers) {
|
||||
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
|
||||
}
|
||||
let csrf = CsrfToken::new_random();
|
||||
let browser = store::token();
|
||||
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
if store::create_attempt(&auth.pool, csrf.secret(), &browser, verifier.secret())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
}
|
||||
let mut response = Redirect::to(provider.authorize(csrf, challenge).as_str()).into_response();
|
||||
set_cookie(&mut response, BROWSER, browser, store::LOGIN_TTL);
|
||||
response
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Callback {
|
||||
code: Option<String>,
|
||||
state: Option<String>,
|
||||
}
|
||||
async fn callback(
|
||||
State(state): State<Arc<HubState>>,
|
||||
headers: HeaderMap,
|
||||
Query(query): Query<Callback>,
|
||||
) -> Response {
|
||||
let auth = &state.auth;
|
||||
let Some(provider) = &auth.provider else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "github_not_configured");
|
||||
};
|
||||
if !allowed(auth, &headers) {
|
||||
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
|
||||
}
|
||||
let (Some(code), Some(csrf), Some(browser)) =
|
||||
(query.code, query.state, cookie(&headers, BROWSER))
|
||||
else {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_login");
|
||||
};
|
||||
if code.is_empty() || code.len() > 1024 || csrf.len() > 256 {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_login");
|
||||
}
|
||||
let Ok(Some(verifier)) = store::consume_attempt(&auth.pool, &csrf, &browser).await else {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_login");
|
||||
};
|
||||
let Ok(profile) = provider.identify(&code, &verifier).await else {
|
||||
return failure(StatusCode::BAD_GATEWAY, "github_login_failed");
|
||||
};
|
||||
let Ok(user) = store::upsert_identity(&auth.pool, &profile).await else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
};
|
||||
let Ok((token, _)) = store::create_session(&auth.pool, &user.user_id).await else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
};
|
||||
if let Some(old) = cookie(&headers, SESSION) {
|
||||
let _ = sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
|
||||
.bind(store::hash(&old))
|
||||
.execute(&auth.pool)
|
||||
.await;
|
||||
}
|
||||
let mut response =
|
||||
Redirect::to(auth.origin.join("account").expect("fixed path").as_str()).into_response();
|
||||
set_cookie(&mut response, SESSION, token, store::SESSION_TTL);
|
||||
set_cookie(&mut response, BROWSER, String::new(), 0);
|
||||
response
|
||||
}
|
||||
async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
|
||||
if let Some(token) = cookie(&headers, SESSION) {
|
||||
match store::get_session(&state.auth.pool, &token).await {
|
||||
Ok(Some((user, csrf))) => {
|
||||
return Json(json!({"authenticated":true,"user":user,"csrf_token":csrf}))
|
||||
.into_response();
|
||||
}
|
||||
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Json(json!({"authenticated":false})).into_response()
|
||||
}
|
||||
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
|
||||
let origin = state.auth.origin.origin().ascii_serialization();
|
||||
if headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) != Some(origin.as_str()) {
|
||||
return failure(StatusCode::FORBIDDEN, "invalid_origin");
|
||||
}
|
||||
let Some(token) = cookie(&headers, SESSION) else {
|
||||
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
|
||||
};
|
||||
let Ok(Some((_, csrf))) = store::get_session(&state.auth.pool, &token).await else {
|
||||
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
|
||||
};
|
||||
let supplied = headers
|
||||
.get("x-csrf-token")
|
||||
.map(|v| v.as_bytes())
|
||||
.unwrap_or_default();
|
||||
if !bool::from(csrf.as_bytes().ct_eq(supplied)) {
|
||||
return failure(StatusCode::FORBIDDEN, "invalid_csrf");
|
||||
}
|
||||
if sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
|
||||
.bind(store::hash(&token))
|
||||
.execute(&state.auth.pool)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
}
|
||||
let mut response = StatusCode::NO_CONTENT.into_response();
|
||||
set_cookie(&mut response, SESSION, String::new(), 0);
|
||||
response
|
||||
}
|
||||
156
hub/src/auth/store.rs
Normal file
156
hub/src/auth/store.rs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::SqlitePool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::provider::GitHubProfile;
|
||||
|
||||
pub const LOGIN_TTL: i64 = 600;
|
||||
pub const SESSION_TTL: i64 = 7 * 24 * 60 * 60;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
|
||||
pub struct User {
|
||||
pub user_id: String,
|
||||
pub handle: String,
|
||||
pub display_name: String,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
pub fn hash(value: &str) -> String {
|
||||
hex::encode(Sha256::digest(value.as_bytes()))
|
||||
}
|
||||
pub fn token() -> String {
|
||||
use rand::Rng;
|
||||
let mut bytes = [0; 32];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
hex::encode(bytes)
|
||||
}
|
||||
pub fn now() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64
|
||||
}
|
||||
|
||||
pub async fn cleanup(pool: &SqlitePool) -> anyhow::Result<()> {
|
||||
sqlx::query("DELETE FROM oauth_attempts WHERE expires_at<=?")
|
||||
.bind(now())
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM web_sessions WHERE expires_at<=?")
|
||||
.bind(now())
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn create_attempt(
|
||||
pool: &SqlitePool,
|
||||
state: &str,
|
||||
browser: &str,
|
||||
verifier: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
cleanup(pool).await?;
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM oauth_attempts")
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
anyhow::ensure!(count < 4096, "login capacity reached");
|
||||
sqlx::query("INSERT INTO oauth_attempts(state_hash,browser_hash,pkce_verifier,expires_at) VALUES(?,?,?,?)")
|
||||
.bind(hash(state)).bind(hash(browser)).bind(verifier).bind(now()+LOGIN_TTL).execute(pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn consume_attempt(
|
||||
pool: &SqlitePool,
|
||||
state: &str,
|
||||
browser: &str,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
Ok(sqlx::query_scalar("DELETE FROM oauth_attempts WHERE state_hash=? AND browser_hash=? AND expires_at>? RETURNING pkce_verifier")
|
||||
.bind(hash(state)).bind(hash(browser)).bind(now()).fetch_optional(pool).await?)
|
||||
}
|
||||
|
||||
pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyhow::Result<User> {
|
||||
let subject = profile.id.to_string();
|
||||
if let Some(user) = lookup_identity(pool, &subject).await? {
|
||||
return Ok(user);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
// Generated stable handle avoids claiming a privileged/reused handle from another provider.
|
||||
let handle = format!("u_{}", id.simple());
|
||||
let name = profile
|
||||
.name
|
||||
.as_deref()
|
||||
.unwrap_or(&profile.login)
|
||||
.chars()
|
||||
.take(100)
|
||||
.collect::<String>();
|
||||
let avatar = profile.avatar_url.as_deref().filter(|value| {
|
||||
url::Url::parse(value).is_ok_and(|url| {
|
||||
url.scheme() == "https"
|
||||
&& url.host_str() == Some("avatars.githubusercontent.com")
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
})
|
||||
});
|
||||
let mut transaction = pool.begin().await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO accounts(user_id,handle,created_at,display_name,avatar_url) VALUES(?,?,?,?,?)",
|
||||
)
|
||||
.bind(id.to_string())
|
||||
.bind(handle)
|
||||
.bind(now())
|
||||
.bind(name)
|
||||
.bind(avatar)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let inserted = sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES('github.com',?,?,?) ON CONFLICT(provider,subject) DO NOTHING")
|
||||
.bind(&subject).bind(id.to_string()).bind(now()).execute(&mut *transaction).await?;
|
||||
if inserted.rows_affected() == 0 {
|
||||
transaction.rollback().await?;
|
||||
} else {
|
||||
transaction.commit().await?;
|
||||
}
|
||||
lookup_identity(pool, &subject)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("identity transaction failed"))
|
||||
}
|
||||
|
||||
async fn lookup_identity(pool: &SqlitePool, subject: &str) -> anyhow::Result<Option<User>> {
|
||||
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url FROM accounts a JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider='github.com' AND e.subject=?")
|
||||
.bind(subject).fetch_optional(pool).await?)
|
||||
}
|
||||
|
||||
pub async fn create_session(pool: &SqlitePool, user_id: &str) -> anyhow::Result<(String, String)> {
|
||||
let session = token();
|
||||
let csrf = token();
|
||||
sqlx::query("INSERT INTO web_sessions(token_hash,user_id,csrf_token,created_at,expires_at) VALUES(?,?,?,?,?)")
|
||||
.bind(hash(&session)).bind(user_id).bind(&csrf).bind(now()).bind(now()+SESSION_TTL).execute(pool).await?;
|
||||
Ok((session, csrf))
|
||||
}
|
||||
|
||||
pub async fn get_session(
|
||||
pool: &SqlitePool,
|
||||
session: &str,
|
||||
) -> anyhow::Result<Option<(User, String)>> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
user_id: String,
|
||||
handle: String,
|
||||
display_name: String,
|
||||
avatar_url: Option<String>,
|
||||
csrf_token: String,
|
||||
}
|
||||
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id WHERE s.token_hash=? AND s.expires_at>?")
|
||||
.bind(hash(session)).bind(now()).fetch_optional(pool).await?;
|
||||
Ok(row.map(|r| {
|
||||
(
|
||||
User {
|
||||
user_id: r.user_id,
|
||||
handle: r.handle,
|
||||
display_name: r.display_name,
|
||||
avatar_url: r.avatar_url,
|
||||
},
|
||||
r.csrf_token,
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ pub struct Config {
|
|||
pub data_dir: PathBuf,
|
||||
pub origin: Url,
|
||||
pub smtp: Option<SmtpConfig>,
|
||||
pub github: Option<crate::auth::GitHubConfig>,
|
||||
}
|
||||
|
||||
/// SMTP credentials are only read from the service environment, never command arguments.
|
||||
|
|
@ -72,7 +73,23 @@ impl Config {
|
|||
from: get("MAIL_FROM").unwrap_or_else(|| "Vnox <noreply@loki-code.dev>".into()),
|
||||
})
|
||||
};
|
||||
let github = match (get("GITHUB_CLIENT_ID"), get("GITHUB_CLIENT_SECRET")) {
|
||||
(None, None) => None,
|
||||
(Some(id), Some(secret))
|
||||
if !id.is_empty()
|
||||
&& !secret.is_empty()
|
||||
&& !id.chars().any(char::is_whitespace)
|
||||
&& !secret.chars().any(char::is_whitespace) =>
|
||||
{
|
||||
Some(crate::auth::GitHubConfig {
|
||||
client_id: id,
|
||||
client_secret: secret,
|
||||
})
|
||||
}
|
||||
_ => bail!("GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET must be configured together"),
|
||||
};
|
||||
Ok(Self {
|
||||
github,
|
||||
bind,
|
||||
origin,
|
||||
smtp,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
pub mod auth;
|
||||
pub mod config;
|
||||
pub mod database;
|
||||
pub mod identity;
|
||||
|
|
|
|||
|
|
@ -47,6 +47,11 @@ async fn main() -> Result<()> {
|
|||
mail::Mailer::new(smtp)?;
|
||||
}
|
||||
let state = Arc::new(web::HubState {
|
||||
auth: Arc::new(vnox_hub::auth::AuthService::new(
|
||||
database.clone(),
|
||||
config.origin.clone(),
|
||||
config.github.as_ref(),
|
||||
)?),
|
||||
database,
|
||||
issuer,
|
||||
smtp_configured: config.smtp.is_some(),
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ use crate::identity::Issuer;
|
|||
|
||||
pub struct HubState {
|
||||
pub database: SqlitePool,
|
||||
pub auth: Arc<crate::auth::AuthService>,
|
||||
pub issuer: Issuer,
|
||||
pub smtp_configured: bool,
|
||||
pub started: Instant,
|
||||
|
|
@ -23,6 +24,7 @@ pub struct HubState {
|
|||
|
||||
pub fn router(state: Arc<HubState>) -> Router {
|
||||
Router::new()
|
||||
.merge(crate::auth::router())
|
||||
.route("/", get(index))
|
||||
.route("/health", get(health))
|
||||
.route("/ready", get(ready))
|
||||
|
|
@ -74,7 +76,7 @@ async fn info(State(state): State<Arc<HubState>>) -> Json<Value> {
|
|||
"smtp": {"configured": state.smtp_configured, "public_send_endpoint": false},
|
||||
"capabilities": {
|
||||
"email_auth": "not_enabled",
|
||||
"github_auth": "not_enabled",
|
||||
"github_auth": if state.auth.configured() { "enabled" } else { "not_enabled" },
|
||||
"server_registry": "not_enabled",
|
||||
"friends": "not_enabled",
|
||||
"direct_messages": "not_enabled",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue