1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
mod auth_server;
use auth_server::*;
use colored::Colorize;
use hyper::{server::conn::http1::Builder, service::service_fn};
use hyper_util::server::graceful::GracefulShutdown;

use crate::{
    commands::AsyncCliCommand,
    config::{UpdateRegistry, UserRegistry, WasmerConfig, WasmerEnv},
};
use futures_util::{stream::FuturesUnordered, StreamExt};
use std::{path::PathBuf, time::Duration};
use wasmer_backend_api::{types::Nonce, WasmerClient};

#[derive(Debug, Clone)]
enum AuthorizationState {
    TokenSuccess(String),
    Cancelled,
    TimedOut,
    UnknownMethod,
}

/// Subcommand for log in a user into Wasmer (using a browser or provided a token)
#[derive(Debug, Clone, clap::Parser)]
pub struct Login {
    /// Variable to login without opening a browser
    #[clap(long, name = "no-browser", default_value = "false")]
    pub no_browser: bool,

    // This is a copy of [`WasmerEnv`] to allow users to specify
    // the token as a parameter rather than as a flag.
    /// Set Wasmer's home directory
    #[clap(long, env = "WASMER_DIR", default_value = crate::config::DEFAULT_WASMER_DIR.as_os_str())]
    pub wasmer_dir: PathBuf,

    /// The directory cached artefacts are saved to.
    #[clap(long, env = "WASMER_CACHE_DIR", default_value = crate::config::DEFAULT_WASMER_CACHE_DIR.as_os_str())]
    pub cache_dir: PathBuf,

    /// The API token to use when communicating with the registry (inferred from the environment by default)
    #[clap(env = "WASMER_TOKEN")]
    pub token: Option<String>,

    /// Change the current registry
    #[clap(long, env = "WASMER_REGISTRY")]
    pub registry: Option<UserRegistry>,
}

impl Login {
    fn get_token_from_env_or_user(
        &self,
        env: &WasmerEnv,
    ) -> Result<AuthorizationState, anyhow::Error> {
        if let Some(token) = &self.token {
            return Ok(AuthorizationState::TokenSuccess(token.clone()));
        }

        let public_url = env.registry_public_url()?;

        let login_prompt = match public_url.domain() {
            Some(d) => {
                format!("Please paste the login token from https://{d}/settings/access-tokens")
            }
            _ => "Please paste the login token".to_string(),
        };

        #[cfg(test)]
        {
            Ok(AuthorizationState::TokenSuccess(login_prompt))
        }
        #[cfg(not(test))]
        {
            let token = dialoguer::Input::new()
                .with_prompt(&login_prompt)
                .interact_text()?;
            Ok(AuthorizationState::TokenSuccess(token))
        }
    }

    async fn get_token_from_browser(
        &self,
        client: &WasmerClient,
    ) -> anyhow::Result<AuthorizationState> {
        let (listener, server_url) = setup_listener().await?;

        let (server_shutdown_tx, mut server_shutdown_rx) = tokio::sync::mpsc::channel::<bool>(1);
        let (token_tx, mut token_rx) = tokio::sync::mpsc::channel::<AuthorizationState>(1);

        // Create a new AppContext
        let app_context = BrowserAuthContext {
            server_shutdown_tx,
            token_tx,
        };

        let Nonce { auth_url, .. } =
            wasmer_backend_api::query::create_nonce(client, "wasmer-cli".to_string(), server_url)
                .await?
                .ok_or_else(|| {
                    anyhow::anyhow!("The backend did not return any nonce to auth the login!")
                })?;

        // if failed to open the browser, then don't error out just print the auth_url with a message
        println!("Opening auth link in your default browser: {}", &auth_url);
        opener::open_browser(&auth_url).unwrap_or_else(|_| {
            println!(
                "⚠️ Failed to open the browser.\n
            Please open the url: {}",
                &auth_url
            );
        });

        // Jump through hyper 1.0's hoops...
        let graceful = GracefulShutdown::new();

        let http = Builder::new();

        let mut futs = FuturesUnordered::new();

        let service = service_fn(move |req| service_router(app_context.clone(), req));

        print!("Waiting for session... ");

        // start the server
        loop {
            tokio::select! {
                Result::Ok((stream, _addr)) = listener.accept() => {
                    let io = hyper_util::rt::tokio::TokioIo::new(stream);
                    let conn = http.serve_connection(io, service.clone());
                    // watch this connection
                    let fut = graceful.watch(conn);
                    futs.push(async move {
                        if let Err(e) = fut.await {
                            eprintln!("Error serving connection: {e:?}");
                        }
                    });
                },

                _ = futs.next() => {}

                _ = server_shutdown_rx.recv() => {
                    // stop the accept loop
                    break;
                }
            }
        }

        // receive the token from the server
        let token = token_rx
            .recv()
            .await
            .ok_or_else(|| anyhow::anyhow!("❌ Failed to receive token from localhost"))?;

        Ok(token)
    }

    async fn do_login(&self, env: &WasmerEnv) -> anyhow::Result<AuthorizationState> {
        let client = env.client_unauthennticated()?;

        let should_login =
            if let Some(user) = wasmer_backend_api::query::current_user(&client).await? {
                #[cfg(not(test))]
                {
                    println!(
                        "You are already logged in as {} in registry {}.",
                        user.username.bold(),
                        env.registry_public_url()?.host_str().unwrap().bold()
                    );
                    let theme = dialoguer::theme::ColorfulTheme::default();
                    let dialog = dialoguer::Confirm::with_theme(&theme).with_prompt("Login again?");

                    dialog.interact()?
                }
                #[cfg(test)]
                {
                    // prevent unused binding warning
                    _ = user;

                    false
                }
            } else {
                true
            };

        if !should_login {
            Ok(AuthorizationState::Cancelled)
        } else if self.no_browser {
            self.get_token_from_env_or_user(env)
        } else {
            // switch between two methods of getting the token.
            // start two async processes, 10 minute timeout and get token from browser. Whichever finishes first, use that.
            let timeout_future = tokio::time::sleep(Duration::from_secs(60 * 10));
            tokio::select! {
             _ = timeout_future => {
                     Ok(AuthorizationState::TimedOut)
                 },
                 token = self.get_token_from_browser(&client) => {
                    token
                 }
            }
        }
    }

    async fn login_and_save(&self, env: &WasmerEnv, token: String) -> anyhow::Result<String> {
        let registry = env.registry_endpoint()?;
        let mut config = WasmerConfig::from_file(env.dir())
            .map_err(|e| anyhow::anyhow!("config from file: {e}"))?;
        config
            .registry
            .set_current_registry(registry.as_ref())
            .await;
        config.registry.set_login_token_for_registry(
            &config.registry.get_current_registry(),
            &token,
            UpdateRegistry::Update,
        );
        let path = WasmerConfig::get_file_location(env.dir());
        config.save(path)?;

        // This will automatically read the config again, picking up the new edits.
        let client = env.client()?;

        wasmer_backend_api::query::current_user(&client)
            .await?
            .map(|v| v.username)
            .ok_or_else(|| anyhow::anyhow!("Not logged in!"))
    }

    pub(crate) fn get_wasmer_env(&self) -> WasmerEnv {
        WasmerEnv::new(
            self.wasmer_dir.clone(),
            self.cache_dir.clone(),
            self.token.clone(),
            self.registry.clone(),
        )
    }
}

#[async_trait::async_trait]
impl AsyncCliCommand for Login {
    type Output = ();

    async fn run_async(self) -> Result<Self::Output, anyhow::Error> {
        let env = self.get_wasmer_env();

        let auth_state = match &self.token {
            Some(token) => AuthorizationState::TokenSuccess(token.clone()),
            None => self.do_login(&env).await?,
        };

        match auth_state {
            AuthorizationState::TokenSuccess(token) => {
                match self.login_and_save(&env, token).await {
                    Ok(s) => {
                        print!("Done!");
                        println!("\n{} Login for Wasmer user {:?} saved","✔".green().bold(), s)
                    }
                    Err(_) => print!(
                        "Warning: no user found on {:?} with the provided token.\nToken saved regardless.",
                        env.registry_public_url()
                    ),
                }
            }
            AuthorizationState::TimedOut => {
                print!("Timed out (10 mins exceeded)");
            }
            AuthorizationState::Cancelled => {
                println!("Cancelled by the user");
            }
            AuthorizationState::UnknownMethod => {
                println!("Error: unknown method\n");
            }
        };

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use clap::CommandFactory;
    use tempfile::TempDir;

    use crate::commands::CliCommand;

    use super::*;

    #[test]
    fn interactive_login() {
        let temp = TempDir::new().unwrap();
        let login = Login {
            no_browser: true,
            registry: Some("wasmer.wtf".into()),
            wasmer_dir: temp.path().to_path_buf(),
            token: None,
            cache_dir: temp.path().join("cache").to_path_buf(),
        };
        let env = login.get_wasmer_env();

        let token = login.get_token_from_env_or_user(&env).unwrap();
        match token {
            AuthorizationState::TokenSuccess(token) => {
                assert_eq!(
                    token,
                    "Please paste the login token from https://wasmer.wtf/settings/access-tokens"
                );
            }
            AuthorizationState::Cancelled
            | AuthorizationState::TimedOut
            | AuthorizationState::UnknownMethod => {
                panic!("Should not reach here")
            }
        }
    }

    #[test]
    fn login_with_token() {
        let temp = TempDir::new().unwrap();
        let login = Login {
            no_browser: true,
            registry: Some("wasmer.wtf".into()),
            wasmer_dir: temp.path().to_path_buf(),
            token: Some("abc".to_string()),
            cache_dir: temp.path().join("cache").to_path_buf(),
        };
        let env = login.get_wasmer_env();

        let token = login.get_token_from_env_or_user(&env).unwrap();

        match token {
            AuthorizationState::TokenSuccess(token) => {
                assert_eq!(token, "abc");
            }
            AuthorizationState::Cancelled
            | AuthorizationState::TimedOut
            | AuthorizationState::UnknownMethod => {
                panic!("Should not reach here")
            }
        }
    }

    #[test]
    fn in_sync_with_wasmer_env() {
        let wasmer_env = WasmerEnv::command();
        let login = Login::command();

        // All options except --token should be the same
        let wasmer_env_opts: Vec<_> = wasmer_env
            .get_opts()
            .filter(|arg| arg.get_id() != "token")
            .collect();
        let login_opts: Vec<_> = login.get_opts().collect();

        assert_eq!(wasmer_env_opts, login_opts);

        // The token argument should have the same message, even if it is an
        // argument rather than a --flag.
        let wasmer_env_token_help = wasmer_env
            .get_opts()
            .find(|arg| arg.get_id() == "token")
            .unwrap()
            .get_help()
            .unwrap()
            .to_string();
        let login_token_help = login
            .get_positionals()
            .find(|arg| arg.get_id() == "token")
            .unwrap()
            .get_help()
            .unwrap()
            .to_string();
        assert_eq!(wasmer_env_token_help, login_token_help);
    }

    /// Regression test for panics on API errors.
    /// See https://github.com/wasmerio/wasmer/issues/4147.
    #[test]
    fn login_with_invalid_token_does_not_panic() {
        let cmd = Login {
            no_browser: true,
            wasmer_dir: crate::config::DEFAULT_WASMER_DIR.clone(),
            registry: Some("http://localhost:11".to_string().into()),
            token: Some("invalid".to_string()),
            cache_dir: crate::config::DEFAULT_WASMER_CACHE_DIR.clone(),
        };

        let res = cmd.run();
        // The CLI notices that either the registry is unreachable or the token is not tied to any
        // user. It shows a warning to the user, but does not return with an error code.
        //
        //  ------ i.e. this will fail
        // |
        // v
        // assert!(res.is_err());
        assert!(res.is_ok());
    }
}