feat: sign in to Copilot, ChatGPT, and Mistral Vibe
Three provider kinds have a browser sign-in, but the add-provider dialog only accepted a pasted key. A per-account login record now runs the adapter's InteractiveLogin on the server, reports the instruction, URL, and code to the dialog, and stores the credential before the browser sees completion. The credential never reaches the client. The dialog gets a sign-in stage for flow kinds, with a link, a copyable code, and retry after failure. Closing the dialog cancels the flow. ChatGPT's callback lands on the server's loopback port, and the instruction names the port to forward.
This commit is contained in:
1 parent
369075a842
commit
f5087220da
12 files changed
+927
-23
No files matched your search
@@ -40,6 +40,14 @@ pub fn router(state: Shared) -> Router {
|
||||
"/provider-configs",
|
||||
get(settings::list_providers).post(settings::create_provider),
|
||||
)
|
||||
.route(
|
||||
"/provider-configs/login",
|
||||
post(settings::start_provider_login),
|
||||
)
|
||||
.route(
|
||||
"/provider-configs/login/{id}",
|
||||
get(settings::provider_login_status).delete(settings::cancel_provider_login),
|
||||
)
|
||||
.route("/provider-configs/{id}", delete(settings::delete_provider))
|
||||
.route(
|
||||
"/provider-configs/{id}/models",
|
||||
|
||||
+152
-5
@@ -6,7 +6,8 @@ use std::time::Duration;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::{HeaderValue, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use rhema_sandbox::Sandbox;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -27,10 +28,17 @@ const KINDS: &[&str] = &[
|
||||
"zai",
|
||||
"mistral",
|
||||
"mistral-vibe",
|
||||
"copilot",
|
||||
"chatgpt",
|
||||
"opencode",
|
||||
"llama-cpp",
|
||||
];
|
||||
|
||||
/// Kinds whose credential comes from a browser sign-in instead of a
|
||||
/// pasted key. The adapter owns the protocol; the server owns the
|
||||
/// record the browser polls and stores the token it produces.
|
||||
pub const FLOW_KINDS: &[&str] = &["copilot", "chatgpt", "mistral-vibe"];
|
||||
|
||||
/// The caller's provider configurations.
|
||||
pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
|
||||
let conn = state.db.conn();
|
||||
@@ -48,7 +56,11 @@ pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppR
|
||||
})
|
||||
})?;
|
||||
let configs = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Json(json!({ "providers": configs, "kinds": KINDS })))
|
||||
Ok(Json(json!({
|
||||
"providers": configs,
|
||||
"kinds": KINDS,
|
||||
"flow_kinds": FLOW_KINDS,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -90,10 +102,36 @@ pub async fn create_provider(
|
||||
if body.kind == "llama-cpp" && base_url.is_none() {
|
||||
return Err(AppError::bad_request("llama.cpp needs a server url"));
|
||||
}
|
||||
if matches!(body.kind.as_str(), "copilot" | "chatgpt") && base_url.is_some() {
|
||||
return Err(AppError::bad_request("this provider has no base url"));
|
||||
}
|
||||
if body.kind != "llama-cpp" && body.api_key.trim().is_empty() {
|
||||
return Err(AppError::bad_request("an api key is required"));
|
||||
}
|
||||
let sealed = state.secrets.seal_str(body.api_key.trim())?;
|
||||
let id = insert_provider(
|
||||
&state,
|
||||
&user.user.id,
|
||||
name,
|
||||
&body.kind,
|
||||
&model,
|
||||
base_url.as_deref(),
|
||||
body.api_key.trim(),
|
||||
)?;
|
||||
Ok(Json(json!({ "id": id })))
|
||||
}
|
||||
|
||||
/// Seals and stores one provider row. The callers validate the kind
|
||||
/// and credential first; this only owns the encryption and the insert.
|
||||
fn insert_provider(
|
||||
state: &Shared,
|
||||
account_id: &str,
|
||||
name: &str,
|
||||
kind: &str,
|
||||
model: &str,
|
||||
base_url: Option<&str>,
|
||||
api_key: &str,
|
||||
) -> AppResult<String> {
|
||||
let sealed = state.secrets.seal_str(api_key)?;
|
||||
let id = random_id(12);
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO provider_configs (id, account_id, name, kind, model, base_url,
|
||||
@@ -101,18 +139,110 @@ pub async fn create_provider(
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
user.user.id,
|
||||
account_id,
|
||||
name,
|
||||
body.kind,
|
||||
kind,
|
||||
model,
|
||||
base_url,
|
||||
sealed,
|
||||
crate::util::now_ms()
|
||||
],
|
||||
)?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The adapter behind a flow kind. `None` means the kind takes a pasted
|
||||
/// key; [`FLOW_KINDS`] is the list the browser uses to choose a stage.
|
||||
fn login_flow(kind: &str) -> Option<Box<dyn rhema_provider::InteractiveLogin>> {
|
||||
match kind {
|
||||
"copilot" => Some(Box::new(rhema_provider_copilot::CopilotLogin::new())),
|
||||
// The ChatGPT callback lands on the server's loopback port; a
|
||||
// server cannot open the user's browser for them.
|
||||
"chatgpt" => Some(Box::new(
|
||||
rhema_provider_chatgpt::ChatGptLogin::new().with_open_browser(false),
|
||||
)),
|
||||
"mistral-vibe" => Some(Box::new(rhema_provider_mistral::MistralVibeLogin::new())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct StartProviderLogin {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// Starts a browser sign-in for a flow kind. The provider row appears
|
||||
/// only when the flow completes; the browser polls the returned id for
|
||||
/// instructions and the final provider id.
|
||||
pub async fn start_provider_login(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Json(body): Json<StartProviderLogin>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
if user.user.kind != "user" {
|
||||
return Err(AppError::forbidden("create an account to add a provider"));
|
||||
}
|
||||
let name = body.name.trim();
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request("name must be 1 to 60 characters"));
|
||||
}
|
||||
let Some(flow) = login_flow(&body.kind) else {
|
||||
return Err(AppError::bad_request(
|
||||
"this provider does not have a sign-in flow",
|
||||
));
|
||||
};
|
||||
let complete_state = state.clone();
|
||||
let account_id = user.user.id.clone();
|
||||
let provider_name = name.to_owned();
|
||||
let provider_kind = body.kind.clone();
|
||||
let complete: crate::login::Complete = Box::new(move |token: &str| {
|
||||
if token.trim().is_empty() {
|
||||
return Err("the sign-in returned no credential".to_owned());
|
||||
}
|
||||
insert_provider(
|
||||
&complete_state,
|
||||
&account_id,
|
||||
&provider_name,
|
||||
&provider_kind,
|
||||
"",
|
||||
None,
|
||||
token.trim(),
|
||||
)
|
||||
.map_err(|err| err.message)
|
||||
});
|
||||
let id = state.logins.start(&user.user.id, flow, complete);
|
||||
Ok(Json(json!({ "id": id })))
|
||||
}
|
||||
|
||||
/// The flow's last update, for its owner only.
|
||||
pub async fn provider_login_status(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Response> {
|
||||
let snapshot = state
|
||||
.logins
|
||||
.snapshot(&user.user.id, &id)
|
||||
.ok_or_else(|| AppError::not_found("sign-in not found"))?;
|
||||
let mut response = Json(snapshot).into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Cancels a flow and forgets its record. A completed flow's provider
|
||||
/// row stays; only the sign-in record goes.
|
||||
pub async fn cancel_provider_login(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
state.logins.cancel(&user.user.id, &id);
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
/// The provider's live model catalog. The registry builds the same
|
||||
/// adapter a turn uses and asks it for the rows a coding agent can
|
||||
/// drive; the model-facts decorator fills price, context, and vision
|
||||
@@ -392,3 +522,20 @@ pub async fn test_target(
|
||||
Err(err) => Ok(Json(json!({ "ok": false, "detail": err.to_string() }))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_flow_kind_has_an_adapter() {
|
||||
for kind in FLOW_KINDS {
|
||||
assert!(login_flow(kind).is_some(), "{kind} has no login flow");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyed_kind_has_no_login_flow() {
|
||||
assert!(login_flow("anthropic").is_none());
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
//! Provider sign-in flows running on the server.
|
||||
//!
|
||||
//! A flow is an `InteractiveLogin` from a provider adapter plus a
|
||||
//! per-account record of what it last told the browser. The browser
|
||||
//! polls the record, never the provider, and the completed credential
|
||||
//! goes straight into the secret box through the caller's closure.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use rhema_provider::{InteractiveLogin, LoginInstruction, LoginSink, LoginUpdate};
|
||||
use serde::Serialize;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
/// How long a flow record survives. The adapters time out after ten
|
||||
/// minutes; this leaves room to read a result before the sweep.
|
||||
const FLOW_TTL_MS: i64 = 15 * 60 * 1000;
|
||||
|
||||
/// The account's running and finished sign-in flows.
|
||||
#[derive(Default)]
|
||||
pub struct Logins {
|
||||
flows: Mutex<HashMap<String, Arc<LoginFlow>>>,
|
||||
}
|
||||
|
||||
/// What a client sees when it polls one flow.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct LoginSnapshot {
|
||||
pub status: LoginPhase,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub instruction: Option<LoginStep>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub provider_id: Option<String>,
|
||||
}
|
||||
|
||||
/// The phase a flow is in. The terminal phases never leave once set.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum LoginPhase {
|
||||
#[default]
|
||||
Starting,
|
||||
Instruct,
|
||||
Waiting,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl LoginPhase {
|
||||
fn terminal(self) -> bool {
|
||||
matches!(self, Self::Completed | Self::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
/// The instruction in a form the browser can render.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct LoginStep {
|
||||
pub text: String,
|
||||
pub url: Option<String>,
|
||||
pub code: Option<String>,
|
||||
}
|
||||
|
||||
/// The caller's completion hook: seal and store the credential, and
|
||||
/// return the new provider id, or the reason it could not.
|
||||
pub type Complete = Box<dyn FnOnce(&str) -> Result<String, String> + Send>;
|
||||
|
||||
/// One flow and the last update it reported.
|
||||
struct LoginFlow {
|
||||
account_id: String,
|
||||
created_at: i64,
|
||||
inner: Mutex<Inner>,
|
||||
task: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Inner {
|
||||
phase: LoginPhase,
|
||||
instruction: Option<LoginStep>,
|
||||
message: Option<String>,
|
||||
provider_id: Option<String>,
|
||||
}
|
||||
|
||||
impl LoginFlow {
|
||||
fn new(account_id: String) -> Self {
|
||||
Self {
|
||||
account_id,
|
||||
created_at: crate::util::now_ms(),
|
||||
inner: Mutex::new(Inner::default()),
|
||||
task: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> LoginSnapshot {
|
||||
let inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
|
||||
LoginSnapshot {
|
||||
status: inner.phase,
|
||||
instruction: inner.instruction.clone(),
|
||||
message: inner.message.clone(),
|
||||
provider_id: inner.provider_id.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_task(&self, handle: JoinHandle<()>) {
|
||||
*self.task.lock().unwrap_or_else(|err| err.into_inner()) = Some(handle);
|
||||
}
|
||||
|
||||
fn terminal(&self) -> bool {
|
||||
self.inner
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.phase
|
||||
.terminal()
|
||||
}
|
||||
|
||||
fn instruct(&self, step: LoginStep) {
|
||||
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if inner.phase.terminal() {
|
||||
return;
|
||||
}
|
||||
inner.phase = LoginPhase::Instruct;
|
||||
inner.instruction = Some(step);
|
||||
inner.message = None;
|
||||
}
|
||||
|
||||
fn waiting(&self, text: String) {
|
||||
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if inner.phase.terminal() {
|
||||
return;
|
||||
}
|
||||
inner.phase = LoginPhase::Waiting;
|
||||
inner.message = Some(text);
|
||||
}
|
||||
|
||||
fn completed(&self, provider_id: String) {
|
||||
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if inner.phase.terminal() {
|
||||
return;
|
||||
}
|
||||
inner.phase = LoginPhase::Completed;
|
||||
inner.message = None;
|
||||
inner.provider_id = Some(provider_id);
|
||||
}
|
||||
|
||||
fn failed(&self, message: String) {
|
||||
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if inner.phase.terminal() {
|
||||
return;
|
||||
}
|
||||
inner.phase = LoginPhase::Failed;
|
||||
inner.message = Some(message);
|
||||
}
|
||||
|
||||
/// A flow that returns without a terminal update leaves a record
|
||||
/// stuck in `waiting`; this closes it.
|
||||
fn finish_if_running(&self) {
|
||||
let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if inner.phase.terminal() {
|
||||
return;
|
||||
}
|
||||
inner.phase = LoginPhase::Failed;
|
||||
inner.message = Some("the sign-in ended without a result".to_owned());
|
||||
}
|
||||
|
||||
fn cancel(&self, message: &str) {
|
||||
// Mark the record first: a completion that lands while the task
|
||||
// unwinds sees a terminal phase and skips the credential.
|
||||
self.failed(message.to_owned());
|
||||
if let Some(task) = self
|
||||
.task
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.take()
|
||||
{
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sink that writes a flow's updates into its record, and stores
|
||||
/// the credential when the adapter completes.
|
||||
struct FlowSink {
|
||||
flow: Arc<LoginFlow>,
|
||||
complete: Option<Complete>,
|
||||
}
|
||||
|
||||
impl LoginSink for FlowSink {
|
||||
fn update(&mut self, update: LoginUpdate) {
|
||||
match update {
|
||||
LoginUpdate::Instruct(LoginInstruction { text, url, code }) => {
|
||||
self.flow.instruct(LoginStep { text, url, code });
|
||||
}
|
||||
LoginUpdate::Waiting(text) => self.flow.waiting(text),
|
||||
LoginUpdate::Failed(message) => self.flow.failed(message),
|
||||
LoginUpdate::Completed(token) => {
|
||||
let Some(complete) = self.complete.take() else {
|
||||
return;
|
||||
};
|
||||
// A canceled flow was removed from the map; the adapter
|
||||
// may still report completion before its task unwinds.
|
||||
if self.flow.terminal() {
|
||||
return;
|
||||
}
|
||||
match complete(&token) {
|
||||
Ok(provider_id) => self.flow.completed(provider_id),
|
||||
Err(message) => self.flow.failed(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Logins {
|
||||
/// Starts `flow` for `account_id`. `complete` runs once, on the
|
||||
/// flow's credential, and its result is what the browser sees.
|
||||
pub fn start(
|
||||
&self,
|
||||
account_id: &str,
|
||||
flow: Box<dyn InteractiveLogin>,
|
||||
complete: Complete,
|
||||
) -> String {
|
||||
self.sweep();
|
||||
let id = crate::util::random_id(12);
|
||||
let record = Arc::new(LoginFlow::new(account_id.to_owned()));
|
||||
self.flows
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.insert(id.clone(), record.clone());
|
||||
let task_record = record.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut sink = FlowSink {
|
||||
flow: task_record.clone(),
|
||||
complete: Some(complete),
|
||||
};
|
||||
flow.run(&mut sink).await;
|
||||
task_record.finish_if_running();
|
||||
});
|
||||
record.set_task(handle);
|
||||
id
|
||||
}
|
||||
|
||||
/// The flow's last update, when it belongs to `account_id`.
|
||||
pub fn snapshot(&self, account_id: &str, id: &str) -> Option<LoginSnapshot> {
|
||||
let flow = self
|
||||
.flows
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.get(id)
|
||||
.cloned()?;
|
||||
(flow.account_id == account_id).then(|| flow.snapshot())
|
||||
}
|
||||
|
||||
/// Ends and forgets a flow. Only its owner can do it.
|
||||
pub fn cancel(&self, account_id: &str, id: &str) -> bool {
|
||||
let flow = self
|
||||
.flows
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.get(id)
|
||||
.cloned();
|
||||
let Some(flow) = flow else {
|
||||
return false;
|
||||
};
|
||||
if flow.account_id != account_id {
|
||||
return false;
|
||||
}
|
||||
self.flows
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.remove(id);
|
||||
flow.cancel("the sign-in was canceled");
|
||||
true
|
||||
}
|
||||
|
||||
/// Drops records that outlived the adapters' own timeouts.
|
||||
fn sweep(&self) {
|
||||
let now = crate::util::now_ms();
|
||||
let stale: Vec<(String, Arc<LoginFlow>)> = self
|
||||
.flows
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.iter()
|
||||
.filter(|(_, flow)| now - flow.created_at > FLOW_TTL_MS)
|
||||
.map(|(id, flow)| (id.clone(), flow.clone()))
|
||||
.collect();
|
||||
if stale.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut flows = self.flows.lock().unwrap_or_else(|err| err.into_inner());
|
||||
for (id, flow) in stale {
|
||||
flows.remove(&id);
|
||||
flow.cancel("the sign-in expired");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn step() -> LoginStep {
|
||||
LoginStep {
|
||||
text: "open the page".to_owned(),
|
||||
url: Some("https://example.com/device".to_owned()),
|
||||
code: Some("ABCD-1234".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_keeps_the_instruction_visible() {
|
||||
let flow = LoginFlow::new("acct".to_owned());
|
||||
flow.instruct(step());
|
||||
flow.waiting("waiting for the browser".to_owned());
|
||||
let snapshot = flow.snapshot();
|
||||
assert_eq!(snapshot.status, LoginPhase::Waiting);
|
||||
assert_eq!(
|
||||
snapshot.instruction.expect("instruction").code.as_deref(),
|
||||
Some("ABCD-1234")
|
||||
);
|
||||
assert_eq!(snapshot.message.as_deref(), Some("waiting for the browser"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_terminal_phase_never_moves_again() {
|
||||
let flow = LoginFlow::new("acct".to_owned());
|
||||
flow.completed("provider".to_owned());
|
||||
flow.failed("too late".to_owned());
|
||||
flow.waiting("too late".to_owned());
|
||||
let snapshot = flow.snapshot();
|
||||
assert_eq!(snapshot.status, LoginPhase::Completed);
|
||||
assert_eq!(snapshot.provider_id.as_deref(), Some("provider"));
|
||||
assert_eq!(snapshot.message, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flow_that_returns_early_is_closed() {
|
||||
let flow = LoginFlow::new("acct".to_owned());
|
||||
flow.instruct(step());
|
||||
flow.finish_if_running();
|
||||
let snapshot = flow.snapshot();
|
||||
assert_eq!(snapshot.status, LoginPhase::Failed);
|
||||
assert_eq!(
|
||||
snapshot.message.as_deref(),
|
||||
Some("the sign-in ended without a result")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn another_account_cannot_read_or_cancel_the_flow() {
|
||||
let logins = Logins::default();
|
||||
let flow: Box<dyn InteractiveLogin> = Box::new(Immediate);
|
||||
let id = logins.start("owner", flow, Box::new(|_| Ok("provider".to_owned())));
|
||||
assert!(logins.snapshot("other", &id).is_none());
|
||||
assert!(!logins.cancel("other", &id));
|
||||
assert!(logins.snapshot("owner", &id).is_some());
|
||||
}
|
||||
|
||||
struct Immediate;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl InteractiveLogin for Immediate {
|
||||
async fn run(&self, _sink: &mut dyn LoginSink) {}
|
||||
}
|
||||
|
||||
struct Completes;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl InteractiveLogin for Completes {
|
||||
async fn run(&self, sink: &mut dyn LoginSink) {
|
||||
sink.update(LoginUpdate::Completed("the-token".to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_completion_hook_stores_the_credential_and_names_the_provider() {
|
||||
let logins = Logins::default();
|
||||
let id = logins.start(
|
||||
"owner",
|
||||
Box::new(Completes),
|
||||
Box::new(|token| {
|
||||
assert_eq!(token, "the-token");
|
||||
Ok("provider".to_owned())
|
||||
}),
|
||||
);
|
||||
for _ in 0..10 {
|
||||
if logins
|
||||
.snapshot("owner", &id)
|
||||
.is_some_and(|snapshot| snapshot.status == LoginPhase::Completed)
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let snapshot = logins.snapshot("owner", &id).expect("snapshot");
|
||||
assert_eq!(snapshot.status, LoginPhase::Completed);
|
||||
assert_eq!(snapshot.provider_id.as_deref(), Some("provider"));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod config;
|
||||
mod crypto;
|
||||
mod db;
|
||||
mod error;
|
||||
mod login;
|
||||
mod models;
|
||||
mod presence;
|
||||
mod preview;
|
||||
@@ -45,6 +46,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
rooms: Default::default(),
|
||||
previews: Default::default(),
|
||||
presence: Default::default(),
|
||||
logins: Default::default(),
|
||||
});
|
||||
let app = api::router(state).layer(TraceLayer::new_for_http());
|
||||
let listener = tokio::net::TcpListener::bind(&config.listen).await?;
|
||||
|
||||
@@ -127,6 +127,7 @@ pub struct AppState {
|
||||
pub rooms: RoomRunner,
|
||||
pub previews: PreviewTunnels,
|
||||
pub presence: crate::presence::Presence,
|
||||
pub logins: crate::login::Logins,
|
||||
}
|
||||
|
||||
/// The state behind an `Arc`.
|
||||
|
||||
Reference in new issue
Block a user