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
26
hub/AUTH.md
Normal file
26
hub/AUTH.md
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# GitHub sign-in
|
||||
|
||||
Configure `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` together in the protected service environment. GitHub Apps and OAuth Apps both support this user authorization flow; the GitHub App private signing key is unnecessary at runtime. Register this exact callback:
|
||||
|
||||
`https://central.loki-code.dev/v1/auth/github/callback`
|
||||
|
||||
The configured `PUBLIC_BASE_URL` determines redirects. Request headers and arbitrary return URLs cannot change them. No repository, private email or installation permission is requested.
|
||||
|
||||
## Browser contract
|
||||
|
||||
- Navigate to `GET /v1/auth/github/start` to begin authorization.
|
||||
- `GET /v1/auth/github/callback` consumes a matching, browser-bound attempt and redirects to `/account`.
|
||||
- `GET /v1/auth/session` returns `{authenticated:false}` or `{authenticated:true,user,csrf_token}`. Use same-origin credentials and never persist this response in local storage.
|
||||
- `POST /v1/auth/logout` requires the exact `Origin` and the session's `X-CSRF-Token`.
|
||||
|
||||
All responses are `no-store`. Cookies use `__Host-` names, Secure, HttpOnly, Path=/ and SameSite=Lax. Login attempts expire after ten minutes and use random state and S256 PKCE. Attempts are consumed atomically before exchanging authorization codes. Sessions expire seven days after creation; SQLite stores only token hashes. GitHub access tokens are used once to fetch `/user`, then discarded.
|
||||
|
||||
Accounts bind to GitHub's numeric user ID. Renaming a GitHub account cannot move it to another Vnox account. Email addresses never implicitly link accounts. This web session currently does not replace the desktop client's local cryptographic identity.
|
||||
|
||||
## Operation
|
||||
|
||||
The Hub binds only to loopback. Its reverse proxy must overwrite `X-Forwarded-For`; it supplies the login rate-limit identity. Use the supplied Nginx configuration: authentication paths disable access/error logging to prevent callback codes and state entering logs. Do not enable request-body, query-string, Authorization or Cookie tracing in application logs.
|
||||
|
||||
Back up SQLite with the issuer identity, protect backups as credentials, and apply the account-deletion policy to them. Expired attempts/sessions are pruned on new login attempts; expiry is independently enforced on every consumption/read. Revoking a GitHub authorization does not currently revoke an already created Vnox session; sign out or delete its database session to revoke it.
|
||||
|
||||
`cargo test -p vnox-hub` exercises the complete local browser flow against an injected provider, wrong-browser/replay/expiry rejection and logout CSRF. A real GitHub login requires the account owner to authorize in their browser; automated tests never impersonate consent.
|
||||
|
|
@ -24,6 +24,12 @@ sqlx = { version = "0.9", default-features = false, features = ["sqlite", "runti
|
|||
lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] }
|
||||
url = "2"
|
||||
|
||||
reqwest.workspace = true
|
||||
sha2.workspace = true
|
||||
oauth2 = { version = "5", default-features = false, features = ["timing-resistant-secret-traits"] }
|
||||
cookie = "0.18"
|
||||
subtle = "2.6"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
|
|
|||
24
hub/migrations/0002_github_auth.sql
Normal file
24
hub/migrations/0002_github_auth.sql
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
ALTER TABLE accounts ADD COLUMN display_name TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE accounts ADD COLUMN avatar_url TEXT;
|
||||
CREATE TABLE external_identities (
|
||||
provider TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES accounts(user_id) ON DELETE CASCADE,
|
||||
linked_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(provider, subject)
|
||||
);
|
||||
CREATE TABLE oauth_attempts (
|
||||
state_hash TEXT PRIMARY KEY,
|
||||
browser_hash TEXT NOT NULL,
|
||||
pkce_verifier TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX oauth_attempt_expiry ON oauth_attempts(expires_at);
|
||||
CREATE TABLE web_sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES accounts(user_id) ON DELETE CASCADE,
|
||||
csrf_token TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX web_session_expiry ON web_sessions(expires_at);
|
||||
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",
|
||||
|
|
|
|||
334
hub/tests/auth.rs
Normal file
334
hub/tests/auth.rs
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use oauth2::{CsrfToken, PkceCodeChallenge};
|
||||
use std::sync::Arc;
|
||||
use tower::ServiceExt;
|
||||
use vnox_hub::{
|
||||
auth::{
|
||||
self,
|
||||
provider::{GitHubProfile, IdentityProvider, ProviderError},
|
||||
store,
|
||||
},
|
||||
database,
|
||||
identity::Issuer,
|
||||
web::{self, HubState},
|
||||
};
|
||||
struct Fake;
|
||||
impl IdentityProvider for Fake {
|
||||
fn authorize(&self, state: CsrfToken, _: PkceCodeChallenge) -> url::Url {
|
||||
let mut u = url::Url::parse("https://github.com/login/oauth/authorize").unwrap();
|
||||
u.query_pairs_mut().append_pair("state", state.secret());
|
||||
u
|
||||
}
|
||||
fn identify<'a>(
|
||||
&'a self,
|
||||
code: &'a str,
|
||||
verifier: &'a str,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn std::future::Future<Output = Result<GitHubProfile, ProviderError>> + Send + 'a>,
|
||||
> {
|
||||
Box::pin(async move {
|
||||
assert_eq!(code, "code");
|
||||
assert!(!verifier.is_empty());
|
||||
Ok(GitHubProfile {
|
||||
id: 123,
|
||||
login: "person".into(),
|
||||
name: Some("Person".into()),
|
||||
avatar_url: None,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
async fn setup(enabled: bool) -> (tempfile::TempDir, Arc<HubState>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
let issuer = Issuer::load_or_create(dir.path()).unwrap();
|
||||
let pool = database::open(dir.path(), &issuer).await.unwrap();
|
||||
let auth = auth::AuthService::with_provider(
|
||||
pool.clone(),
|
||||
url::Url::parse("https://central.loki-code.dev").unwrap(),
|
||||
if enabled { Some(Arc::new(Fake)) } else { None },
|
||||
);
|
||||
(
|
||||
dir,
|
||||
Arc::new(HubState {
|
||||
database: pool,
|
||||
auth: Arc::new(auth),
|
||||
issuer,
|
||||
smtp_configured: false,
|
||||
started: std::time::Instant::now(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn login_browser_binding_replay_session_and_csrf() {
|
||||
let (_dir, state) = setup(true).await;
|
||||
let app = web::router(state.clone());
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/auth/github/start")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::SEE_OTHER);
|
||||
let browser = response.headers()["set-cookie"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert!(
|
||||
response.headers()["set-cookie"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.contains("HttpOnly")
|
||||
);
|
||||
let redirect = url::Url::parse(response.headers()["location"].to_str().unwrap()).unwrap();
|
||||
let csrf = redirect
|
||||
.query_pairs()
|
||||
.find(|(k, _)| k == "state")
|
||||
.unwrap()
|
||||
.1
|
||||
.to_string();
|
||||
let callback = format!("/v1/auth/github/callback?code=code&state={csrf}");
|
||||
let rejected = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(&callback)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rejected.status(), StatusCode::BAD_REQUEST);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(&callback)
|
||||
.header("cookie", &browser)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
response.headers()["location"],
|
||||
"https://central.loki-code.dev/account"
|
||||
);
|
||||
let session = response
|
||||
.headers()
|
||||
.get_all("set-cookie")
|
||||
.iter()
|
||||
.find(|v| v.to_str().unwrap().starts_with("__Host-vnox_session="))
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let replay = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(&callback)
|
||||
.header("cookie", browser)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(replay.status(), StatusCode::BAD_REQUEST);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/auth/session")
|
||||
.header("cookie", &session)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap();
|
||||
assert_eq!(json["authenticated"], true);
|
||||
let rejected = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/auth/logout")
|
||||
.header("cookie", &session)
|
||||
.header("origin", "https://central.loki-code.dev")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rejected.status(), StatusCode::FORBIDDEN);
|
||||
let ok = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/auth/logout")
|
||||
.header("cookie", &session)
|
||||
.header("origin", "https://central.loki-code.dev")
|
||||
.header("x-csrf-token", json["csrf_token"].as_str().unwrap())
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ok.status(), StatusCode::NO_CONTENT);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM web_sessions")
|
||||
.fetch_one(&state.database)
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn expired_attempt_and_identity_stability() {
|
||||
let (_dir, state) = setup(false).await;
|
||||
store::create_attempt(&state.database, "state", "browser", "verifier")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
store::consume_attempt(&state.database, "state", "wrong")
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
sqlx::query("UPDATE oauth_attempts SET expires_at=0")
|
||||
.execute(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
store::consume_attempt(&state.database, "state", "browser")
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let mut profile = GitHubProfile {
|
||||
id: 987,
|
||||
login: "old".into(),
|
||||
name: None,
|
||||
avatar_url: None,
|
||||
};
|
||||
let a = store::upsert_identity(&state.database, &profile)
|
||||
.await
|
||||
.unwrap();
|
||||
profile.login = "changed".into();
|
||||
let b = store::upsert_identity(&state.database, &profile)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(a.user_id, b.user_id);
|
||||
let response = web::router(state)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/auth/github/start")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn blocked_login_ip_cannot_spend_other_visitors_global_budget() {
|
||||
let (_dir, state) = setup(false).await;
|
||||
for _ in 0..20 {
|
||||
assert!(state.auth.allow("192.0.2.1"));
|
||||
}
|
||||
for _ in 0..400 {
|
||||
assert!(!state.auth.allow("192.0.2.1"));
|
||||
}
|
||||
assert!(state.auth.allow("192.0.2.2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_provider_uses_fixed_callback_and_s256_without_repository_scopes() {
|
||||
let origin = url::Url::parse("https://central.loki-code.dev").unwrap();
|
||||
let provider = auth::provider::GitHubProvider::new(
|
||||
&auth::GitHubConfig {
|
||||
client_id: "public-fixture-id".into(),
|
||||
client_secret: "fixture-secret-not-real".into(),
|
||||
},
|
||||
&origin,
|
||||
)
|
||||
.unwrap();
|
||||
let (challenge, _) = PkceCodeChallenge::new_random_sha256();
|
||||
let target = provider.authorize(CsrfToken::new("fixture-state".into()), challenge);
|
||||
assert_eq!(target.host_str(), Some("github.com"));
|
||||
let pairs = target
|
||||
.query_pairs()
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
assert_eq!(
|
||||
pairs["redirect_uri"],
|
||||
"https://central.loki-code.dev/v1/auth/github/callback"
|
||||
);
|
||||
assert_eq!(pairs["code_challenge_method"], "S256");
|
||||
assert!(!pairs["code_challenge"].is_empty());
|
||||
assert_eq!(pairs["state"], "fixture-state");
|
||||
assert!(!pairs.contains_key("scope"));
|
||||
assert!(!target.as_str().contains("fixture-secret-not-real"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_session_is_hashed_and_expiry_is_enforced_without_cleanup() {
|
||||
let (_dir, state) = setup(false).await;
|
||||
let user = store::upsert_identity(
|
||||
&state.database,
|
||||
&GitHubProfile {
|
||||
id: 456,
|
||||
login: "fixture".into(),
|
||||
name: None,
|
||||
avatar_url: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (raw, _) = store::create_session(&state.database, &user.user_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let persisted: String = sqlx::query_scalar("SELECT token_hash FROM web_sessions")
|
||||
.fetch_one(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(persisted, store::hash(&raw));
|
||||
assert_ne!(persisted, raw);
|
||||
assert!(
|
||||
store::get_session(&state.database, &raw)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
sqlx::query("UPDATE web_sessions SET expires_at=0")
|
||||
.execute(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
store::get_session(&state.database, &raw)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
|
@ -96,6 +96,14 @@ async fn state() -> (TempDir, Arc<HubState>) {
|
|||
(
|
||||
directory,
|
||||
Arc::new(HubState {
|
||||
auth: Arc::new(
|
||||
vnox_hub::auth::AuthService::new(
|
||||
pool.clone(),
|
||||
url::Url::parse("https://central.loki-code.dev").unwrap(),
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
database: pool,
|
||||
issuer,
|
||||
smtp_configured: true,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue