Skip to content

Commit c5322be

Browse files
committed
✨ SASL OAUTHBEARER: Add mechanism [🚧 more tests]
Also, GS2Header was extracted from OAuthBearerAuthenticator. It's not much right now, but it will be re-used in the implementation of other mechanisms, e.g. `SCRAM-SHA-*`.
1 parent f0b0d04 commit c5322be

File tree

4 files changed

+301
-0
lines changed

4 files changed

+301
-0
lines changed

lib/net/imap/sasl.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ class IMAP
3333
# +PLAIN+:: See PlainAuthenticator.
3434
# Login using clear-text username and password.
3535
#
36+
# +OAUTHBEARER+:: See OAuthBearerAuthenticator.
37+
# Login using an OAUTH2 Bearer token. This is the
38+
# standard mechanism for using OAuth2 with \SASL, but it
39+
# is not yet deployed as widely as +XOAUTH2+.
40+
#
3641
# +XOAUTH2+:: See XOAuth2Authenticator.
3742
# Login using a username and OAuth2 access token.
3843
# Non-standard and obsoleted by +OAUTHBEARER+, but widely
@@ -71,8 +76,10 @@ module SASL
7176
sasl_dir = File.expand_path("sasl", __dir__)
7277
autoload :Authenticator, "#{sasl_dir}/authenticator"
7378
autoload :Authenticators, "#{sasl_dir}/authenticators"
79+
autoload :GS2Header, "#{sasl_dir}/gs2_header"
7480
autoload :AnonymousAuthenticator, "#{sasl_dir}/anonymous_authenticator"
7581
autoload :ExternalAuthenticator, "#{sasl_dir}/external_authenticator"
82+
autoload :OAuthBearerAuthenticator, "#{sasl_dir}/oauthbearer_authenticator"
7683
autoload :PlainAuthenticator, "#{sasl_dir}/plain_authenticator"
7784
autoload :XOAuth2Authenticator, "#{sasl_dir}/xoauth2_authenticator"
7885

@@ -85,6 +92,7 @@ def self.authenticators
8592
@authenticators ||= SASL::Authenticators.new.tap do |registry|
8693
registry.add_authenticator "Anonymous"
8794
registry.add_authenticator "External"
95+
registry.add_authenticator "OAuthBearer"
8896
registry.add_authenticator "Plain"
8997
registry.add_authenticator "XOAuth2"
9098
registry.add_authenticator "Login" # deprecated

lib/net/imap/sasl/gs2_header.rb

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# frozen_string_literal: true
2+
3+
module Net
4+
class IMAP < Protocol
5+
module SASL
6+
7+
# Several mechanisms start with a GS2 header:
8+
# * +GS2-*+
9+
# * +SCRAM-*+ --- ScramAuthenticator
10+
# * +OPENID20+
11+
# * +SAML20+
12+
# * +OAUTH10A+
13+
# * +OAUTHBEARER+ --- OAuthBearerAuthenticator
14+
#
15+
# Classes that include this must implement +#authzid+.
16+
module GS2Header
17+
NO_NULL_CHARS = /\A[^\x00]+\z/u.freeze # :nodoc:
18+
19+
##
20+
# Matches {RFC5801 §4}[https://www.rfc-editor.org/rfc/rfc5801#section-4]
21+
# +saslname+. The output from gs2_saslname_encode matches this Regexp.
22+
RFC5801_SASLNAME = /\A(?:[^,=\x00]|=2C|=3D)+\z/u.freeze
23+
24+
# The {RFC5801 §4}[https://www.rfc-editor.org/rfc/rfc5801#section-4]
25+
# +gs2-header+, which prefixes the #initial_client_response.
26+
#
27+
# >>>
28+
# <em>Note: the actual GS2 header includes an optional flag to
29+
# indicate that the GSS mechanism is not "standard", but since all of
30+
# the SASL mechanisms using GS2 are "standard", we don't include that
31+
# flag. A class for a nonstandard GSSAPI mechanism should prefix with
32+
# "+F,+".</em>
33+
def gs2_header
34+
"#{gs2_cb_flag},#{gs2_authzid},"
35+
end
36+
37+
# The {RFC5801 §4}[https://www.rfc-editor.org/rfc/rfc5801#section-4]
38+
# +gs2-cb-flag+:
39+
#
40+
# "+n+":: The client doesn't support channel binding.
41+
# "+y+":: The client does support channel binding
42+
# but thinks the server does not.
43+
# "+p+":: The client requires channel binding.
44+
# The selected channel binding follows "+p=+".
45+
#
46+
# The default always returns "+n+". A mechanism that supports channel
47+
# binding must override this method.
48+
#
49+
def gs2_cb_flag; "n" end
50+
51+
# The {RFC5801 §4}[https://www.rfc-editor.org/rfc/rfc5801#section-4]
52+
# +gs2-authzid+ header, when +#authzid+ is not empty.
53+
#
54+
# If +#authzid+ is empty or +nil+, an empty string is returned.
55+
def gs2_authzid
56+
return "" if authzid.nil? || authzid == ""
57+
"a=#{gs2_saslname_encode(authzid)}"
58+
end
59+
60+
module_function
61+
62+
# Encodes +str+ to match RFC5801_SASLNAME.
63+
#
64+
#--
65+
# TODO: validate NO_NULL_CHARS and valid UTF-8 in the attr_writer.
66+
def gs2_saslname_encode(str)
67+
str = str.encode("UTF-8")
68+
# Regexp#match raises "invalid byte sequence" for invalid UTF-8
69+
NO_NULL_CHARS.match str or
70+
raise ArgumentError, "invalid saslname: %p" % [str]
71+
str
72+
.gsub(?=, "=3D")
73+
.gsub(?,, "=2C")
74+
end
75+
76+
end
77+
end
78+
end
79+
end
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "authenticator"
4+
require_relative "gs2_header"
5+
6+
module Net
7+
class IMAP < Protocol
8+
module SASL
9+
10+
# Abstract base class for the SASL mechanisms defined in
11+
# RFC7628[https://tools.ietf.org/html/rfc7628]:
12+
# * OAUTHBEARER[rdoc-ref:OAuthBearerAuthenticator]
13+
# * OAUTH10A
14+
class OAuthAuthenticator < Authenticator
15+
include GS2Header
16+
17+
# Creates an OAuthBearerAuthenticator or OAuth10aAuthenticator.
18+
#
19+
# * +_subclass_var_+ — the subclass's required parameter.
20+
# * #authzid ― Identity to act as or on behalf of.
21+
# * #host — Hostname to which the client connected.
22+
# * #port — Service port to which the client connected.
23+
# * #mthd — HTTP method
24+
# * #path — HTTP path data
25+
# * #post — HTTP post data
26+
# * #qs — HTTP query string
27+
#
28+
# All properties here are optional. See the child classes for their
29+
# required parameter(s).
30+
#
31+
def initialize(arg1_authzid = nil, _ = nil, arg3_authzid = nil,
32+
authzid: nil, host: nil, port: nil,
33+
mthd: nil, path: nil, post: nil, qs: nil, **)
34+
super
35+
propinit(:authzid, authzid, arg1_authzid, arg3_authzid)
36+
self.host = host
37+
self.port = port
38+
self.mthd = mthd
39+
self.path = path
40+
self.post = post
41+
self.qs = qs
42+
@done = false
43+
end
44+
45+
##
46+
# Authorization identity: an identity to act as or on behalf of.
47+
#
48+
# For the OAuth-based mechanisms, authcid is implicitly set by the
49+
# #auth_payload. It may be useful to make it explicit, which allows the
50+
# server to verify the credentials match the identity. The gs2_header
51+
# MAY include the username associated with the resource being accessed,
52+
# the "authzid".
53+
#
54+
# It is worth noting that application protocols are allowed to require
55+
# an authzid, as are specific server implementations.
56+
#
57+
# See also: PlainAuthenticator#authzid, DigestMD5Authenticator#authzid.
58+
property :authzid
59+
60+
##
61+
# Hostname to which the client connected.
62+
property :host
63+
64+
##
65+
# Service port to which the client connected.
66+
property :port
67+
68+
##
69+
# HTTP method. (optional)
70+
property :mthd
71+
72+
##
73+
# HTTP path data. (optional)
74+
property :path
75+
76+
##
77+
# HTTP post data. (optional)
78+
property :post
79+
80+
##
81+
# The query string. (optional)
82+
property :qs
83+
84+
# Stores the most recent server "challenge". When authentication fails,
85+
# this may hold information about the failure reason, as JSON.
86+
attr_reader :last_server_response
87+
88+
##
89+
# Returns initial_client_response the first time, then "<tt>^A</tt>".
90+
def process(data)
91+
@last_server_response = data
92+
return "\1" if done?
93+
initial_client_response
94+
ensure
95+
@done = true
96+
end
97+
98+
##
99+
# Returns true when the initial client response was sent.
100+
#
101+
# The authentication should not succeed unless this returns true, but it
102+
# does *not* indicate success.
103+
def done?; @done end
104+
105+
# The {RFC7628 §3.1}[https://www.rfc-editor.org/rfc/rfc7628#section-3.1]
106+
# formatted response.
107+
def initial_client_response
108+
[gs2_header, *kv_pairs.map {|kv| kv.join("=") }, "\1"].join("\1")
109+
end
110+
111+
# The key value pairs which follow gs2_header, as a Hash.
112+
def kv_pairs
113+
{
114+
host: host, port: port, mthd: mthd, path: path, post: post, qs: qs,
115+
auth: auth_payload, # auth_payload is implemented by subclasses
116+
}.compact
117+
end
118+
119+
# What would be sent in the HTTP Authorization header.
120+
#
121+
# <b>Implemented by subclasses.</b>
122+
def auth_payload; raise NotImplementedError, "implement in subclass" end
123+
124+
end
125+
126+
# Authenticator for the "+OAUTHBEARER+" SASL mechanism, specified in
127+
# RFC7628[https://tools.ietf.org/html/rfc7628]. Use via
128+
# Net::IMAP#authenticate.
129+
#
130+
# TODO...
131+
#
132+
# OAuth 2.0 bearer tokens, as described in [RFC6750].
133+
# RFC6750 uses Transport Layer Security (TLS) [RFC5246] to
134+
# secure the protocol interaction between the client and the
135+
# resource server.
136+
#
137+
# TLS MUST be used for +OAUTHBEARER+ to protect the bearer token.
138+
class OAuthBearerAuthenticator < OAuthAuthenticator
139+
140+
##
141+
# :call-seq:
142+
# new(authzid, oauth2_token, **) -> auth_ctx
143+
# new(oauth2_token:, authzid: nil, **) -> auth_ctx
144+
# new(**) {|propname, auth_ctx| propval } -> auth_ctx
145+
#
146+
# Creates an Authenticator for the "+OAUTHBEARER+" SASL mechanism.
147+
#
148+
# Called by Net::IMAP#authenticate and similar methods on other clients.
149+
#
150+
# === Properties
151+
#
152+
# * #oauth2_token — An OAuth2 bearer token or access token. *Required*
153+
# * #authzid ― Identity to act as or on behalf of.
154+
# * #host — Hostname to which the client connected.
155+
# * #port — Service port to which the client connected.
156+
# * See other, rarely used properties on OAuthAuthenticator.
157+
#
158+
# Although only #oauth2_token is required, specific server
159+
# implementations may additionally require #authzid, #host, and #port.
160+
#
161+
# See the documentation on each property method for more details.
162+
#
163+
# All three properties may be sent as either positional or keyword
164+
# arguments. See Net::IMAP::SASL::Authenticator@Properties for a
165+
# detailed description of property assignment, lazy loading, and
166+
# callbacks.
167+
#
168+
def initialize(id1=nil, arg2_token=nil, id3=nil, oauth2_token: nil, **)
169+
super # handles authzid, host, port, callback, etc
170+
propinit(:oauth2_token, oauth2_token, arg2_token, required: true)
171+
self.host = host
172+
end
173+
174+
##
175+
# An OAuth2 bearer token, which is generally the same as the standard
176+
# access_token.
177+
property :oauth2_token
178+
179+
# :call-seq:
180+
# initial_response? -> true
181+
#
182+
# +OAUTHBEARER+ sends an initial client response.
183+
def initial_response?; true end
184+
185+
# What would be sent in the HTTP Authorization header.
186+
def auth_payload; "Bearer #{oauth2_token}" end
187+
188+
end
189+
end
190+
191+
end
192+
end

test/net/imap/test_imap_authenticators.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,28 @@ def test_plain_no_null_chars
3737
assert_raise(ArgumentError) { plain("u", "p", authzid: "bad\0authz") }
3838
end
3939

40+
# ----------------------
41+
# OAUTHBEARER
42+
# ----------------------
43+
44+
def test_oauthbearer_authenticator_matches_mechanism
45+
assert_kind_of(Net::IMAP::SASL::OAuthBearerAuthenticator,
46+
Net::IMAP::SASL.authenticator("OAUTHBEARER", nil, "tok"))
47+
end
48+
49+
def oauthbearer(*args, **kwargs, &block)
50+
Net::IMAP::SASL.authenticator("OAUTHBEARER", *args, **kwargs, &block)
51+
end
52+
53+
def test_oauthbearer_response
54+
assert_equal(
55+
"n,[email protected],\1host=server.example.com\1port=587\1" \
56+
"auth=Bearer mF_9.B5f-4.1JqM\1\1",
57+
oauthbearer("[email protected]", "mF_9.B5f-4.1JqM",
58+
host: "server.example.com", port: 587).process(nil)
59+
)
60+
end
61+
4062
# ----------------------
4163
# XOAUTH2
4264
# ----------------------

0 commit comments

Comments
 (0)