1 //! [`SiGitAuth`]: siGit Code's sign-in as an `ed-acp` [`AuthProvider`].
2 //!
3 //! The same browser flow `sigit` runs in an editor (OAuth with PKCE against `sigit.si/oauth`,
4 //! public client `sigit-code-cli`), and the same stored session, so there is one OAuth client
5 //! to register and one place a token lives. The loopback listener receives the code; the
6 //! authorize URL goes to the client as a URL-mode elicitation when it offers one, so the page
7 //! opens where the user is looking.
8
9 use agent_client_protocol::schema::v1::{
10 AuthMethod, AuthMethodAgent, CompleteElicitationNotification, CreateElicitationRequest,
11 CreateElicitationResponse, ElicitationAction, ElicitationRequestScope, ElicitationUrlMode,
12 ErrorCode, RequestId,
13 };
14 use agent_client_protocol::{Client, ConnectionTo};
15 use async_trait::async_trait;
16 use ed_acp::{AuthCtx, AuthProvider, LlmConfig, Provider};
17
18 use crate::browser_auth::{self, Flow};
19 use crate::credentials;
20 use crate::profile::INFO;
21
22 /// The id of the auth method, as the client sends it in `authenticate`.
23 pub const METHOD_ID: &str = "sigit";
24
25 /// Default API root of siGit Code Cloud; `SIGIT_CLOUD_URL` overrides it.
26 const DEFAULT_CLOUD_URL: &str = "https://sigit.si/api/v1";
27
28 /// The inference endpoint: `SIGIT_CLOUD_URL` or `https://sigit.si/api/v1`.
29 pub fn cloud_base_url() -> String {
30 std::env::var("SIGIT_CLOUD_URL")
31 .ok()
32 .filter(|url| !url.trim().is_empty())
33 .unwrap_or_else(|| DEFAULT_CLOUD_URL.to_string())
34 .trim_end_matches('/')
35 .to_string()
36 }
37
38 /// The model a session starts on: `SIGIT_AGENT_MODEL`, else the profile's default tier.
39 fn default_model() -> String {
40 std::env::var(INFO.env.var("MODEL"))
41 .ok()
42 .filter(|model| !model.trim().is_empty())
43 .unwrap_or_else(|| INFO.env.default_model.to_string())
44 }
45
46 pub struct SiGitAuth;
47
48 #[async_trait]
49 impl AuthProvider for SiGitAuth {
50 fn method(&self) -> AuthMethod {
51 AuthMethod::Agent(
52 AuthMethodAgent::new(METHOD_ID, "Sign in to siGit Code")
53 .description("Opens sigit.si in your browser to sign in to siGit Code Cloud."),
54 )
55 }
56
57 fn llm_config(&self) -> Option<LlmConfig> {
58 let token = credentials::load_token()?;
59 Some(LlmConfig {
60 provider: Provider::OpenAi,
61 base_url: cloud_base_url(),
62 api_key: Some(token),
63 model: default_model(),
64 })
65 }
66
67 async fn authenticate(&self, ctx: AuthCtx<'_>) -> agent_client_protocol::Result<()> {
68 // An existing session clears the gate without sending anyone to a browser they
69 // didn't ask for.
70 if let Some(token) = credentials::load_token()
71 && session_is_valid(&token).await
72 {
73 log::info!("authenticate: the stored session is still valid");
74 return Ok(());
75 }
76
77 // There is no way to take a pasted code back from here, so this is the loopback
78 // variant or nothing.
79 let flow = browser_auth::begin();
80 if !flow.is_loopback() {
81 return Err(error(
82 "Could not open a local port to receive the sign-in. Run `sigit login` in a \
83 terminal instead.",
84 ));
85 }
86
87 let outcome = if ctx.client_offers_url_elicitation() {
88 sign_in_via_client(ctx.connection, ctx.request_id, flow).await
89 } else {
90 log::info!(
91 "authenticate: opening the browser at {}",
92 flow.authorize_url()
93 );
94 if !browser_auth::open_browser(flow.authorize_url()) {
95 log::warn!("authenticate: no browser could be launched");
96 }
97 browser_auth::complete_loopback(flow).await
98 };
99
100 match outcome {
101 Ok(email) => {
102 log::info!("authenticate: signed in as {email}");
103 Ok(())
104 }
105 Err(reason) => Err(error(format!(
106 "Sign-in did not complete ({reason}). Try again, or create an account at \
107 https://sigit.si."
108 ))),
109 }
110 }
111
112 async fn logout(&self) -> anyhow::Result<()> {
113 credentials::clear();
114 Ok(())
115 }
116 }
117
118 fn error(message: impl Into<String>) -> agent_client_protocol::Error {
119 agent_client_protocol::Error::new(ErrorCode::InternalError.into(), message.into())
120 }
121
122 /// Whether `token` is still accepted by the account API.
123 async fn session_is_valid(token: &str) -> bool {
124 let base = std::env::var("SIGIT_API_URL")
125 .ok()
126 .filter(|url| !url.trim().is_empty())
127 .unwrap_or_else(|| "https://sigit.si".to_string());
128 let url = format!("{}/api/v1/user", base.trim_end_matches('/'));
129 match reqwest::Client::new()
130 .get(url)
131 .bearer_auth(token)
132 .timeout(std::time::Duration::from_secs(15))
133 .send()
134 .await
135 {
136 Ok(response) => response.status().is_success(),
137 Err(error) => {
138 log::warn!("authenticate: could not verify the stored session ({error})");
139 false
140 }
141 }
142 }
143
144 /// The loopback sign-in with the client showing the page: the authorize URL goes out as a
145 /// URL-mode elicitation, so the user sees where they are being sent and the client opens it,
146 /// which also works where this process cannot launch a browser. A user who declines ends the
147 /// sign-in; a client that fails the request gets a browser opened from here. Once the code is
148 /// redeemed the client is told the elicitation is complete.
149 async fn sign_in_via_client(
150 connection: &ConnectionTo<Client>,
151 request_id: RequestId,
152 flow: Flow,
153 ) -> Result<String, String> {
154 let url = flow.authorize_url().to_string();
155 let elicitation_id = uuid::Uuid::new_v4().to_string();
156 log::info!("authenticate: asking the client to open {url}");
157 let ask = connection
158 .send_request(CreateElicitationRequest::new(
159 ElicitationUrlMode::new(
160 ElicitationRequestScope::new(request_id),
161 elicitation_id.clone(),
162 url.clone(),
163 ),
164 "Sign in to siGit Code in your browser to use siGit Code Cloud.",
165 ))
166 .block_task();
167 let sign_in = browser_auth::complete_loopback(flow);
168 tokio::pin!(sign_in);
169
170 // The page can be finished before the client gets round to answering.
171 enum First {
172 Answer(agent_client_protocol::Result<CreateElicitationResponse>),
173 SignedIn(Result<String, String>),
174 }
175 let first = tokio::select! {
176 answer = ask => First::Answer(answer),
177 result = &mut sign_in => First::SignedIn(result),
178 };
179 let result = match first {
180 First::SignedIn(result) => result,
181 First::Answer(Ok(response)) => match response.action {
182 ElicitationAction::Accept(_) => sign_in.await,
183 _ => Err("the sign-in page was not opened".to_string()),
184 },
185 First::Answer(Err(error)) => {
186 log::warn!("authenticate: the client could not show the sign-in page ({error})");
187 if !browser_auth::open_browser(&url) {
188 log::warn!("authenticate: no browser could be launched");
189 }
190 sign_in.await
191 }
192 };
193 if result.is_ok() {
194 connection
195 .send_notification(CompleteElicitationNotification::new(elicitation_id))
196 .ok();
197 }
198 result
199 }
200
201 #[cfg(test)]
202 mod tests {
203 use super::*;
204
205 #[test]
206 fn the_method_is_an_agent_method_named_sigit() {
207 let method = SiGitAuth.method();
208 assert_eq!(&*method.id().0, METHOD_ID);
209 assert!(matches!(method, AuthMethod::Agent(_)));
210 }
211
212 #[test]
213 fn the_cloud_url_defaults_to_the_api_root_and_drops_a_trailing_slash() {
214 // Not set in a test run; the override is covered by `cloud_base_url`'s own branch.
215 if std::env::var_os("SIGIT_CLOUD_URL").is_none() {
216 assert_eq!(cloud_base_url(), "https://sigit.si/api/v1");
217 }
218 }
219 }