Line data Source code
1 : use super::{ComputeCredentials, ComputeUserInfo};
2 : use crate::{
3 : auth::{self, backend::ComputeCredentialKeys, AuthFlow},
4 : compute,
5 : config::AuthenticationConfig,
6 : console::AuthSecret,
7 : context::RequestMonitoring,
8 : sasl,
9 : stream::{PqStream, Stream},
10 : };
11 : use tokio::io::{AsyncRead, AsyncWrite};
12 : use tracing::{info, warn};
13 :
14 6 : pub(super) async fn authenticate(
15 6 : ctx: &RequestMonitoring,
16 6 : creds: ComputeUserInfo,
17 6 : client: &mut PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
18 6 : config: &'static AuthenticationConfig,
19 6 : secret: AuthSecret,
20 6 : ) -> auth::Result<ComputeCredentials> {
21 6 : let flow = AuthFlow::new(client);
22 6 : let scram_keys = match secret {
23 : #[cfg(any(test, feature = "testing"))]
24 : AuthSecret::Md5(_) => {
25 0 : info!("auth endpoint chooses MD5");
26 0 : return Err(auth::AuthError::bad_auth_method("MD5"));
27 : }
28 6 : AuthSecret::Scram(secret) => {
29 6 : info!("auth endpoint chooses SCRAM");
30 6 : let scram = auth::Scram(&secret, ctx);
31 :
32 6 : let auth_outcome = tokio::time::timeout(
33 6 : config.scram_protocol_timeout,
34 6 : async {
35 6 :
36 6 : flow.begin(scram).await.map_err(|error| {
37 0 : warn!(?error, "error sending scram acknowledgement");
38 0 : error
39 12 : })?.authenticate().await.map_err(|error| {
40 0 : warn!(?error, "error processing scram messages");
41 0 : error
42 6 : })
43 6 : }
44 6 : )
45 12 : .await
46 6 : .map_err(|e| {
47 0 : warn!("error processing scram messages error = authentication timed out, execution time exceeded {} seconds", config.scram_protocol_timeout.as_secs());
48 0 : auth::AuthError::user_timeout(e)
49 6 : })??;
50 :
51 6 : let client_key = match auth_outcome {
52 6 : sasl::Outcome::Success(key) => key,
53 0 : sasl::Outcome::Failure(reason) => {
54 0 : info!("auth backend failed with an error: {reason}");
55 0 : return Err(auth::AuthError::auth_failed(&*creds.user));
56 : }
57 : };
58 :
59 6 : compute::ScramKeys {
60 6 : client_key: client_key.as_bytes(),
61 6 : server_key: secret.server_key.as_bytes(),
62 6 : }
63 6 : }
64 6 : };
65 6 :
66 6 : Ok(ComputeCredentials {
67 6 : info: creds,
68 6 : keys: ComputeCredentialKeys::AuthKeys(tokio_postgres::config::AuthKeys::ScramSha256(
69 6 : scram_keys,
70 6 : )),
71 6 : })
72 6 : }
|