Skip to contentSkip to conversation

b4: allow using xoauth2/bearer token to authenticate to SMTP servers

PATCH Applied Dmitry Torokhov 3 participants 11 messages Mar 6 – Mar 13

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 b4: allow using xoauth2/bearer token to authenticate to SMTP servers

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

---
 src/b4/__init__.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
src/b4/__init__.py +7 -3
index eab290b..9a5d25b 100644
@@ -4312,8 +4312,8 @@ def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL
 
         # If we got to this point, we should do authentication,
         # unless smtpauth is set to a special "none" value
-        smtpauth = str(sconfig.get('smtpauth', ''))
-        if smtpauth.lower() == 'none':
+        smtpauth = str(sconfig.get('smtpauth', '')).lower()
+        if smtpauth == 'none':
             return smtp, fromaddr
 
         auser = str(sconfig.get('smtpuser', ''))
@@ -4331,7 +4331,11 @@ def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL
                 raise smtplib.SMTPException('No password specified for connecting to %s', server)
         if auser and apass:
             # Let any exceptions bubble up
-            smtp.login(auser, apass)
+            if smtpauth in ('oauth', 'oauth2', 'xoauth2'):
+                auth_str = f'user={auser}\x01auth=Bearer {apass}\x01\x01'
+                smtp.auth('XOAUTH2', lambda: auth_str)
+            else:
+                smtp.login(auser, apass)
     else:
         # We assume you know what you're doing if you don't need encryption
         smtp = smtplib.SMTP(server, port)
Signature · 1 line
2.53.0.473.g4a7958ca14-goog
#1 lore raw
Quoted 5 lines · Dmitry Torokhov

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

Hmm... we do have another series already for XOAUTH2 support:
https://lore.kernel.org/tools/[email protected]/

However, it's outstanding with a few requests. I wonder if we can take this one as a first patch and then build the other series on top of this.

Cc'ing Tomas on this.

src/b4/__init__.py def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL · line 4336

Quoted 12 lines
src/b4/__init__.py +3 -1
index eab290b..9a5d25b 100644
@@ -4331,7 +4331,11 @@ def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL
                 raise smtplib.SMTPException('No password specified for connecting to %s', server)
         if auser and apass:
             # Let any exceptions bubble up
-            smtp.login(auser, apass)
+            if smtpauth in ('oauth', 'oauth2', 'xoauth2'):
+                auth_str = f'user={auser}\x01auth=Bearer {apass}\x01\x01'
+                smtp.auth('XOAUTH2', lambda: auth_str)

This is what the agent tells me about this, and it seems valid.

smtplib.SMTP.auth() calls authobject(challenge) with a positional bytes argument when the server replies 334 (the XOAUTH2 error-detail challenge). Because this lambda accepts no arguments, that call raises TypeError, masking the real authentication error.

Suggest:
smtp.auth('XOAUTH2', lambda x=None: auth_str if x is None else '')

This way the initial response (no args) returns the auth string, and a 334 challenge returns an empty string so the server sends its real error code.

I'm happy to take this with this fix, but I'm also going to wait on Tomas's thoughts.

Thanks!

Signature · 1 line
KR
#2 lore raw
Quoted 31 lines · Konstantin Ryabitsev
Quoted 5 lines · Dmitry Torokhov

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

Hmm... we do have another series already for XOAUTH2 support:
https://lore.kernel.org/tools/[email protected]/

However, it's outstanding with a few requests. I wonder if we can take this one as a first patch and then build the other series on top of this.

Cc'ing Tomas on this.

src/b4/__init__.py def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL · line 4336

Quoted 12 lines
src/b4/__init__.py +3 -1
index eab290b..9a5d25b 100644
@@ -4331,7 +4331,11 @@ def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL
                 raise smtplib.SMTPException('No password specified for connecting to %s', server)
         if auser and apass:
             # Let any exceptions bubble up
-            smtp.login(auser, apass)
+            if smtpauth in ('oauth', 'oauth2', 'xoauth2'):
+                auth_str = f'user={auser}\x01auth=Bearer {apass}\x01\x01'
+                smtp.auth('XOAUTH2', lambda: auth_str)

This is what the agent tells me about this, and it seems valid.

Quoted 4 lines

smtplib.SMTP.auth() calls authobject(challenge) with a positional bytes argument when the server replies 334 (the XOAUTH2 error-detail challenge). Because this lambda accepts no arguments, that call raises TypeError, masking the real authentication error.

Right, I guess because of implicit initial_response_ok argument to smtp.auth() when I tested it the lambda was called without arguments and the authentication went through (with gmail).

Quoted 10 lines

Suggest:
smtp.auth('XOAUTH2', lambda x=None: auth_str if x is None else '')

This way the initial response (no args) returns the auth string, and a 334 challenge returns an empty string so the server sends its real error code.

I'm happy to take this with this fix, but I'm also going to wait on Tomas's thoughts.

Totally fine with me.

Thanks.

Signature · 1 line
Dmitry
#3 lore raw

Hi,

Quoted 7 lines · Dmitry Torokhov
Quoted 6 lines · Konstantin Ryabitsev
Quoted 5 lines · Dmitry Torokhov

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

Quoted 8 lines
Quoted 8 lines

Hmm... we do have another series already for XOAUTH2 support:
https://lore.kernel.org/tools/[email protected]/

However, it's outstanding with a few requests. I wonder if we can take this one as a first patch and then build the other series on top of this.

Cc'ing Tomas on this.

Perhaps I'm missing something but this approach looks to me more like a workaround. I'm not seeing how it handles the oauth2 lifecycle expiration which is typically within hours. The other series handles that with a helper that will update the token transparently as needed.

I will return shortly with updates to my original series.

Thanks,

Tomas

Quoted 36 lines
Quoted 15 lines

src/b4/__init__.py def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL · line 4336

Quoted 13 lines
src/b4/__init__.py +3 -1
index eab290b..9a5d25b 100644
@@ -4331,7 +4331,11 @@ def get_smtp(dryrun: bool = False) -> Tuple[Union[smtplib.SMTP, smtplib.SMTP_SSL
                  raise smtplib.SMTPException('No password specified for connecting to %s', server)
          if auser and apass:
              # Let any exceptions bubble up
-            smtp.login(auser, apass)
+            if smtpauth in ('oauth', 'oauth2', 'xoauth2'):
+                auth_str = f'user={auser}\x01auth=Bearer {apass}\x01\x01'
+                smtp.auth('XOAUTH2', lambda: auth_str)

This is what the agent tells me about this, and it seems valid.

Quoted 4 lines

smtplib.SMTP.auth() calls authobject(challenge) with a positional bytes argument when the server replies 334 (the XOAUTH2 error-detail challenge). Because this lambda accepts no arguments, that call raises TypeError, masking the real authentication error.

Right, I guess because of implicit initial_response_ok argument to smtp.auth() when I tested it the lambda was called without arguments and the authentication went through (with gmail).

Quoted 9 lines

Suggest:
smtp.auth('XOAUTH2', lambda x=None: auth_str if x is None else '')

This way the initial response (no args) returns the auth string, and a 334 challenge returns an empty string so the server sends its real error code.

I'm happy to take this with this fix, but I'm also going to wait on Tomas's thoughts.

Totally fine with me.

Thanks.

#4 lore raw

Hi Tomas,

Quoted 17 lines · Tomas Melin

Hi,

Quoted 14 lines · Dmitry Torokhov
Quoted 13 lines · Konstantin Ryabitsev
Quoted 5 lines · Dmitry Torokhov

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

Hmm... we do have another series already for XOAUTH2 support:
https://lore.kernel.org/tools/[email protected]/

However, it's outstanding with a few requests. I wonder if we can take this one as a first patch and then build the other series on top of this.

Quoted 6 lines
Quoted 1 line
Quoted 1 line

Cc'ing Tomas on this.

Perhaps I'm missing something but this approach looks to me more like a workaround. I'm not seeing how it handles the oauth2 lifecycle expiration which is typically within hours. The other series handles that with a helper that will update the token transparently as needed.

In my setup "git credential" returns bearer token that should last enough for this b4 run. Next time b4 runs "git credential" will request a new bearer token if previous one expired. It is not expected that the token is stored in the configuration file. It looks like git-credential-email behavior should also be compatible with this use.

However looking at your patch I do not understand why you want to parse configuration and run the helpers directly instead of having "git credential" return the data for you and rely on it to figure out what helper to use and how. It gets protocol, username, and host and should be able to figure out what should be returned. It is not b4's role to interact directly with git helpers.

I also do not see any traces of handling lifetime expiration in your patch either... Not that it is needed IMO.

Thanks.

Signature · 1 line
Dmitry
#5 lore raw

Hi,

Quoted 25 lines · Dmitry Torokhov

Hi Tomas,

Quoted 17 lines · Tomas Melin

Hi,

Quoted 14 lines · Dmitry Torokhov
Quoted 13 lines · Konstantin Ryabitsev
Quoted 5 lines · Dmitry Torokhov

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

Hmm... we do have another series already for XOAUTH2 support:
https://lore.kernel.org/tools/[email protected]/

However, it's outstanding with a few requests. I wonder if we can take this one as a first patch and then build the other series on top of this.

Quoted 5 lines
Quoted 1 line
Quoted 1 line

Cc'ing Tomas on this.

Perhaps I'm missing something but this approach looks to me more like a workaround. I'm not seeing how it handles the oauth2 lifecycle expiration which is typically within hours. The other series handles that with a helper that will update the token transparently as needed.

Quoted 5 lines

In my setup "git credential" returns bearer token that should last enough for this b4 run. Next time b4 runs "git credential" will request a new bearer token if previous one expired. It is not expected that the token is stored in the configuration file. It looks like git-credential-email behavior should also be compatible with this use.

In your case, how do you provide the new token to git credential?

How does you .gitconfig for this look like?

Quoted 6 lines

However looking at your patch I do not understand why you want to parse configuration and run the helpers directly instead of having "git credential" return the data for you and rely on it to figure out what helper to use and how. It gets protocol, username, and host and should be able to figure out what should be returned. It is not b4's role to interact directly with git helpers.

git-send-email also requires similar integration with external helpers https://git-scm.com/docs/git-send-email#_sending_patches

thanks,

Tomas

Quoted 6 lines

I also do not see any traces of handling lifetime expiration in your patch either... Not that it is needed IMO.

Thanks.

#6 lore raw
Quoted 28 lines · Tomas Melin

Hi,

Quoted 25 lines · Dmitry Torokhov

Hi Tomas,

Quoted 22 lines · Tomas Melin

Hi,

Quoted 7 lines · Dmitry Torokhov
Quoted 6 lines · Konstantin Ryabitsev
Quoted 5 lines · Dmitry Torokhov

Allow using XOAUTH2 as an authentication protocol and assume that when XOAUTH2 is specified the password is actually a bearer token (typically not stored in the config but rather returned via "git credentials".

Recognize "oauth", "oauth2" as aliases for "xoauth2".

Quoted 8 lines
Quoted 8 lines

Hmm... we do have another series already for XOAUTH2 support:
https://lore.kernel.org/tools/[email protected]/

However, it's outstanding with a few requests. I wonder if we can take this one as a first patch and then build the other series on top of this.

Cc'ing Tomas on this.

Perhaps I'm missing something but this approach looks to me more like a workaround. I'm not seeing how it handles the oauth2 lifecycle expiration which is typically within hours. The other series handles that with a helper that will update the token transparently as needed.

Quoted 7 lines
Quoted 5 lines

In my setup "git credential" returns bearer token that should last enough for this b4 run. Next time b4 runs "git credential" will request a new bearer token if previous one expired. It is not expected that the token is stored in the configuration file. It looks like git-credential-email behavior should also be compatible with this use.

In your case, how do you provide the new token to git credential?

git credential itself calls into configured helpers and the helper does this. You do not need to replicate this logic in other places.

Quoted 2 lines

How does you .gitconfig for this look like?

global  sendemail.smtpserver smtp.gmail.com
global  sendemail.smtpserverport 587
global  sendemail.smtpencryption tls
global  sendemail.smtpuser [email protected]
global  sendemail.thread true
global  sendemail.bcc [email protected]
global  sendemail.suppresscc self
global  credential.helper cache --timeout=3000
global  credential.helper local-helper
local   sendemail.smtpuser [email protected]
local   sendemail.smtpauth XOAUTH2
local   sendemail.bcc [email protected]

The local-helper is a custom python script that behaves similarly to the gmail credential helper, but the difference that it supports different credential stores - either based on secret storage API or GPG-based so I can move my configuration between a headless workstation, a VM, or my laptop easily.

The beauty of credential helpers is that if they do not know how to handle the request they simply skip it so that the next one might be able to resolve it.

Quoted 10 lines
Quoted 7 lines

However looking at your patch I do not understand why you want to parse configuration and run the helpers directly instead of having "git credential" return the data for you and rely on it to figure out what helper to use and how. It gets protocol, username, and host and should be able to figure out what should be returned. It is not b4's role to interact directly with git helpers.

git-send-email also requires similar integration with external helpers
https://git-scm.com/docs/git-send-email#_sending_patches

No, it says that git-send-email makes use of "git credential", it does not say that it calls out directly to any helpers. In fact, this is git-send-email code:

	$auth = Git::credential({
		'protocol' => 'smtp',
		'host' => smtp_host_string(),
		'username' => $smtp_authuser,
		# if there's no password, "git credential fill" will
		# give us one, otherwise it'll just pass this one.
		'password' => $smtp_authpass
	}, sub {
		my $cred = shift;
		my $result;
		my $error;

		# catch all SMTP auth error in a unified eval block
		eval {
			if ($smtp_auth) {
				my $sasl = Authen::SASL->new(
					mechanism => $smtp_auth,
					callback => {
						user     => $cred->{'username'},
						pass     => $cred->{'password'},
						authname => $cred->{'username'},
					}
				);
				$result = $smtp->auth($sasl);
			} else {
				$result = $smtp->auth($cred->{'username'}, $cred->{'password'});
			}
			1; # ensure true value is returned if no exception is thrown
		} or do {
			$error = $@ || 'Unknown error';
		};

		return ($error
			? handle_smtp_error($error)
			: ($result ? 1 : 0));
	});

As you can see it does exactly what my patch does: it calls to "git credential" and expects something resolving a secret (password) in return. Then XOAUTH2.pm SASL module takes that secret and produces that "user=$username\001auth=Bearer $token\001\001" string that is needed to authenticate.

BTW, I am not sure why you are using smtp.docmd() and not smtp.auth()...

Thanks.

Signature · 1 line
Dmitry
#7 lore raw

Hi,

Quoted 29 lines · Dmitry Torokhov
Quoted 5 lines · Tomas Melin

Hi,

Quoted 1 line · Dmitry Torokhov

In your case, how do you provide the new token to git credential?

git credential itself calls into configured helpers and the helper does this. You do not need to replicate this logic in other places.

Quoted 1 line

How does you .gitconfig for this look like?

global  sendemail.smtpserver smtp.gmail.com
global  sendemail.smtpserverport 587
global  sendemail.smtpencryption tls
global  sendemail.smtpuser [email protected]
global  sendemail.thread true
global  sendemail.bcc [email protected]
global  sendemail.suppresscc self
global  credential.helper cache --timeout=3000
global  credential.helper local-helper
local   sendemail.smtpuser [email protected]
local   sendemail.smtpauth XOAUTH2
local   sendemail.bcc [email protected]

The local-helper is a custom python script that behaves similarly to the gmail credential helper, but the difference that it supports different credential stores - either based on secret storage API or GPG-based so I can move my configuration between a headless workstation, a VM, or my laptop easily.

Quoted 3 lines

The beauty of credential helpers is that if they do not know how to handle the request they simply skip it so that the next one might be able to resolve it.

Yes, indeed then this looks like a cleaner solution to the authentication process and

the approach proposed in your patch should be taken instead of my initial attempt.

FWIW I tested this out, but for some reason I was occasionally not getting the

token back, instead it falls back to password authentication prompt (which then fails).

Thanks,

Tomas

Quoted 60 lines
Quoted 9 lines
Quoted 7 lines

However looking at your patch I do not understand why you want to parse configuration and run the helpers directly instead of having "git credential" return the data for you and rely on it to figure out what helper to use and how. It gets protocol, username, and host and should be able to figure out what should be returned. It is not b4's role to interact directly with git helpers.

git-send-email also requires similar integration with external helpers
https://git-scm.com/docs/git-send-email#_sending_patches

No, it says that git-send-email makes use of "git credential", it does not say that it calls out directly to any helpers. In fact, this is git-send-email code:

	$auth = Git::credential({
		'protocol' => 'smtp',
		'host' => smtp_host_string(),
		'username' => $smtp_authuser,
		# if there's no password, "git credential fill" will
		# give us one, otherwise it'll just pass this one.
		'password' => $smtp_authpass
	}, sub {
		my $cred = shift;
		my $result;
		my $error;

		# catch all SMTP auth error in a unified eval block
		eval {
			if ($smtp_auth) {
				my $sasl = Authen::SASL->new(
					mechanism => $smtp_auth,
					callback => {
						user     => $cred->{'username'},
						pass     => $cred->{'password'},
						authname => $cred->{'username'},
					}
				);
				$result = $smtp->auth($sasl);
			} else {
				$result = $smtp->auth($cred->{'username'}, $cred->{'password'});
			}
			1; # ensure true value is returned if no exception is thrown
		} or do {
			$error = $@ || 'Unknown error';
		};

		return ($error
			? handle_smtp_error($error)
			: ($result ? 1 : 0));
	});

As you can see it does exactly what my patch does: it calls to "git credential" and expects something resolving a secret (password) in return. Then XOAUTH2.pm SASL module takes that secret and produces that "user=$username\001auth=Bearer $token\001\001" string that is needed to authenticate.

BTW, I am not sure why you are using smtp.docmd() and not smtp.auth()...

Thanks.

#8 lore raw

Hi Tomas,

Quoted 39 lines · Tomas Melin

Hi,

Quoted 29 lines · Dmitry Torokhov
Quoted 5 lines · Tomas Melin

Hi,

Quoted 1 line · Dmitry Torokhov

In your case, how do you provide the new token to git credential?

git credential itself calls into configured helpers and the helper does this. You do not need to replicate this logic in other places.

Quoted 1 line

How does you .gitconfig for this look like?

global  sendemail.smtpserver smtp.gmail.com
global  sendemail.smtpserverport 587
global  sendemail.smtpencryption tls
global  sendemail.smtpuser [email protected]
global  sendemail.thread true
global  sendemail.bcc [email protected]
global  sendemail.suppresscc self
global  credential.helper cache --timeout=3000
global  credential.helper local-helper
local   sendemail.smtpuser [email protected]
local   sendemail.smtpauth XOAUTH2
local   sendemail.bcc [email protected]

The local-helper is a custom python script that behaves similarly to the gmail credential helper, but the difference that it supports different credential stores - either based on secret storage API or GPG-based so I can move my configuration between a headless workstation, a VM, or my laptop easily.

Quoted 3 lines

The beauty of credential helpers is that if they do not know how to handle the request they simply skip it so that the next one might be able to resolve it.

Yes, indeed then this looks like a cleaner solution to the authentication process and

Quoted 8 lines

the approach proposed in your patch should be taken instead of my initial attempt.

FWIW I tested this out, but for some reason I was occasionally not getting the

token back, instead it falls back to password authentication prompt (which then fails).

Hmm, this is weird. I've had the setup with the "git credential", my credential helper, and "git send-email" for the last few years and I did not observe this issue... Maybe one of the helpers is flaky? You can call "git credential" from a script like this to test:

#!/bin/bash
#
git credential fill << ENDOFDATA | sed -n 's/^password=\(.*\)/\1/ p' protocol=smtp
host=gmail.com
username=${1}
ENDOFDATA

to see how reliable it is. Obviously adjust host and other details as needed.

Thanks.

Signature · 1 line
Dmitry
#9 lore raw
In reply to Tomas Melin
Quoted 7 lines · Tomas Melin
Quoted 3 lines

The beauty of credential helpers is that if they do not know how to handle the request they simply skip it so that the next one might be able to resolve it.

Yes, indeed then this looks like a cleaner solution to the authentication process and the approach proposed in your patch should be taken instead of my initial attempt.

OK, I will take Dmitry's patch, then. Thanks!

-K