Skip to main content

couchbase_core/
authenticator.rs

1/*
2 *
3 *  * Copyright (c) 2025 Couchbase, Inc.
4 *  *
5 *  * Licensed under the Apache License, Version 2.0 (the "License");
6 *  * you may not use this file except in compliance with the License.
7 *  * You may obtain a copy of the License at
8 *  *
9 *  *    http://www.apache.org/licenses/LICENSE-2.0
10 *  *
11 *  * Unless required by applicable law or agreed to in writing, software
12 *  * distributed under the License is distributed on an "AS IS" BASIS,
13 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  * See the License for the specific language governing permissions and
15 *  * limitations under the License.
16 *
17 */
18
19use crate::auth_mechanism::AuthMechanism;
20use crate::error::Result;
21use crate::service_type::ServiceType;
22use std::fmt::{Debug, Display};
23
24#[derive(Clone, PartialEq, Hash)]
25#[non_exhaustive]
26pub enum Authenticator {
27    PasswordAuthenticator(PasswordAuthenticator),
28    CertificateAuthenticator(CertificateAuthenticator),
29    /// **Stability: Uncommitted** This API may change in the future.
30    JwtAuthenticator(JwtAuthenticator),
31}
32
33impl Display for Authenticator {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Authenticator::PasswordAuthenticator(_) => write!(f, "PasswordAuthenticator"),
37            Authenticator::CertificateAuthenticator(_) => {
38                write!(f, "CertificateAuthenticator")
39            }
40            Authenticator::JwtAuthenticator(_) => write!(f, "JwtAuthenticator"),
41        }
42    }
43}
44
45#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
46pub struct UserPassPair {
47    pub username: String,
48    pub password: String,
49}
50
51#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
52pub struct PasswordAuthenticator {
53    pub username: String,
54    pub password: String,
55}
56
57impl PasswordAuthenticator {
58    pub fn get_credentials(
59        &self,
60        _service_type: &ServiceType,
61        _host_port: String,
62    ) -> Result<UserPassPair> {
63        Ok(UserPassPair {
64            username: self.username.clone(),
65            password: self.password.clone(),
66        })
67    }
68
69    pub fn get_auth_mechanisms(&self, tls_enabled: bool) -> Vec<AuthMechanism> {
70        if tls_enabled {
71            vec![AuthMechanism::Plain]
72        } else {
73            vec![
74                AuthMechanism::ScramSha512,
75                AuthMechanism::ScramSha256,
76                AuthMechanism::ScramSha1,
77            ]
78        }
79    }
80}
81
82impl From<PasswordAuthenticator> for Authenticator {
83    fn from(value: PasswordAuthenticator) -> Self {
84        Authenticator::PasswordAuthenticator(value)
85    }
86}
87
88// CertificateAuthenticator expects the TlsConfig provided in AgentConfig to contain the certificate chain and private key.
89#[derive(Clone, PartialEq, Eq, Hash)]
90pub struct CertificateAuthenticator {}
91
92impl CertificateAuthenticator {
93    pub fn get_credentials(
94        &self,
95        _service_type: &ServiceType,
96        _host_port: String,
97    ) -> Result<UserPassPair> {
98        Ok(UserPassPair {
99            username: String::new(), // No username for certificate auth
100            password: String::new(), // No password for certificate auth
101        })
102    }
103}
104
105impl From<CertificateAuthenticator> for Authenticator {
106    fn from(value: CertificateAuthenticator) -> Self {
107        Authenticator::CertificateAuthenticator(value)
108    }
109}
110
111/// JwtAuthenticator uses a JWT token to authenticate with the server.
112///
113/// **Stability: Uncommitted**
114///
115/// This API may change in the future.
116#[derive(Clone, PartialEq, Hash)]
117pub struct JwtAuthenticator {
118    pub token: String,
119}
120
121impl JwtAuthenticator {
122    pub fn get_token(&self) -> &str {
123        &self.token
124    }
125
126    pub fn get_auth_mechanisms(&self) -> Vec<AuthMechanism> {
127        vec![AuthMechanism::OAuthBearer]
128    }
129}
130
131impl From<JwtAuthenticator> for Authenticator {
132    fn from(value: JwtAuthenticator) -> Self {
133        Authenticator::JwtAuthenticator(value)
134    }
135}