Skip to content

Commit 861f7fa

Browse files
committed
MEX
1 parent 81db8d2 commit 861f7fa

File tree

5 files changed

+2856
-0
lines changed

5 files changed

+2856
-0
lines changed

msal/mex.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
#------------------------------------------------------------------------------
2+
#
3+
# Copyright (c) Microsoft Corporation.
4+
# All rights reserved.
5+
#
6+
# This code is licensed under the MIT License.
7+
#
8+
# Permission is hereby granted, free of charge, to any person obtaining a copy
9+
# of this software and associated documentation files(the "Software"), to deal
10+
# in the Software without restriction, including without limitation the rights
11+
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
12+
# copies of the Software, and to permit persons to whom the Software is
13+
# furnished to do so, subject to the following conditions :
14+
#
15+
# The above copyright notice and this permission notice shall be included in
16+
# all copies or substantial portions of the Software.
17+
#
18+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
21+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
# THE SOFTWARE.
25+
#
26+
#------------------------------------------------------------------------------
27+
28+
try:
29+
from urllib.parse import urlparse
30+
except:
31+
from urlparse import urlparse
32+
try:
33+
from xml.etree import cElementTree as ET
34+
except ImportError:
35+
from xml.etree import ElementTree as ET
36+
37+
import requests
38+
39+
40+
def _xpath_of_root(route_to_leaf):
41+
# Construct an xpath suitable to find a root node which has a specified leaf
42+
return '/'.join(route_to_leaf + ['..'] * (len(route_to_leaf)-1))
43+
44+
def send_request(mex_endpoint, **kwargs):
45+
mex_document = requests.get(
46+
mex_endpoint, headers={'Content-Type': 'application/soap+xml'},
47+
**kwargs).text
48+
return Mex(mex_document).get_wstrust_username_password_endpoint()
49+
50+
51+
class Mex(object):
52+
53+
NS = { # Also used by wstrust_*.py
54+
'wsdl': 'http://schemas.xmlsoap.org/wsdl/',
55+
'sp': 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702',
56+
'sp2005': 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy',
57+
'wsu': 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd',
58+
'wsa': 'http://www.w3.org/2005/08/addressing', # Duplicate?
59+
'wsa10': 'http://www.w3.org/2005/08/addressing',
60+
'http': 'http://schemas.microsoft.com/ws/06/2004/policy/http',
61+
'soap12': 'http://schemas.xmlsoap.org/wsdl/soap12/',
62+
'wsp': 'http://schemas.xmlsoap.org/ws/2004/09/policy',
63+
's': 'http://www.w3.org/2003/05/soap-envelope',
64+
'wst': 'http://docs.oasis-open.org/ws-sx/ws-trust/200512',
65+
'trust': "http://docs.oasis-open.org/ws-sx/ws-trust/200512", # Duplicate?
66+
'saml': "urn:oasis:names:tc:SAML:1.0:assertion",
67+
'wst2005': 'http://schemas.xmlsoap.org/ws/2005/02/trust', # was named "t"
68+
}
69+
ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'
70+
ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'
71+
72+
def __init__(self, mex_document):
73+
self.dom = ET.fromstring(mex_document)
74+
75+
def _get_policy_ids(self, components_to_leaf, binding_xpath):
76+
id_attr = '{%s}Id' % self.NS['wsu']
77+
return set(["#{}".format(policy.get(id_attr))
78+
for policy in self.dom.findall(_xpath_of_root(components_to_leaf), self.NS)
79+
# If we did not find any binding, this is potentially bad.
80+
if policy.find(binding_xpath, self.NS) is not None])
81+
82+
def _get_username_password_policy_ids(self):
83+
path = ['wsp:Policy', 'wsp:ExactlyOne', 'wsp:All',
84+
'sp:SignedEncryptedSupportingTokens', 'wsp:Policy',
85+
'sp:UsernameToken', 'wsp:Policy', 'sp:WssUsernameToken10']
86+
policies = self._get_policy_ids(path, './/sp:TransportBinding')
87+
path2005 = ['wsp:Policy', 'wsp:ExactlyOne', 'wsp:All',
88+
'sp2005:SignedSupportingTokens', 'wsp:Policy',
89+
'sp2005:UsernameToken', 'wsp:Policy', 'sp2005:WssUsernameToken10']
90+
policies.update(self._get_policy_ids(path2005, './/sp2005:TransportBinding'))
91+
return policies
92+
93+
def _get_iwa_policy_ids(self):
94+
return self._get_policy_ids(
95+
['wsp:Policy', 'wsp:ExactlyOne', 'wsp:All', 'http:NegotiateAuthentication'],
96+
'.//sp2005:TransportBinding')
97+
98+
def _get_bindings(self):
99+
bindings = {} # {binding_name: {"policy_uri": "...", "version": "..."}}
100+
for binding in self.dom.findall("wsdl:binding", self.NS):
101+
if (binding.find('soap12:binding', self.NS).get("transport") !=
102+
'http://schemas.xmlsoap.org/soap/http'):
103+
continue
104+
action = binding.find(
105+
'wsdl:operation/soap12:operation', self.NS).get("soapAction")
106+
for pr in binding.findall("wsp:PolicyReference", self.NS):
107+
bindings[binding.get("name")] = {
108+
"policy_uri": pr.get("URI"), "action": action}
109+
return bindings
110+
111+
def _get_endpoints(self, bindings, policy_ids):
112+
endpoints = []
113+
for port in self.dom.findall('wsdl:service/wsdl:port', self.NS):
114+
binding_name = port.get("binding").split(':')[-1] # Should have 2 parts
115+
binding = bindings.get(binding_name)
116+
if binding and binding["policy_uri"] in policy_ids:
117+
address = port.find('wsa10:EndpointReference/wsa10:Address', self.NS)
118+
if address is not None and address.text.lower().startswith("https://"):
119+
endpoints.append(
120+
{"address": address.text, "action": binding["action"]})
121+
return endpoints
122+
123+
def get_wstrust_username_password_endpoint(self):
124+
"""Returns {"address": "https://...", "action": "the soapAction value"}"""
125+
endpoints = self._get_endpoints(
126+
self._get_bindings(), self._get_username_password_policy_ids())
127+
for e in endpoints:
128+
if e["action"] == self.ACTION_13:
129+
return e # Historically, we prefer ACTION_13 a.k.a. WsTrust13
130+
return endpoints[0] if endpoints else None
131+

0 commit comments

Comments
 (0)