summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
blob: 048525483ac5d2e2cd9f3036d800e1dbd03eb41d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//-----------------------------------------------------------------------
// <copyright file="ExtensionsBindingElementTests.cs" company="Andrew Arnott">
//     Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
	using System;
	using System.Collections.Generic;
	using System.Diagnostics.Contracts;
	using System.Linq;
	using System.Text.RegularExpressions;
	using DotNetOpenAuth.Messaging;
	using DotNetOpenAuth.OpenId;
	using DotNetOpenAuth.OpenId.ChannelElements;
	using DotNetOpenAuth.OpenId.Extensions;
	using DotNetOpenAuth.OpenId.Messages;
	using DotNetOpenAuth.OpenId.RelyingParty;
	using DotNetOpenAuth.Test.Mocks;
	using DotNetOpenAuth.Test.OpenId.Extensions;
	using NUnit.Framework;

	[TestFixture]
	public class ExtensionsBindingElementTests : OpenIdTestBase {
		private StandardOpenIdExtensionFactory factory;
		private ExtensionsBindingElement rpElement;
		private IProtocolMessageWithExtensions request;

		[SetUp]
		public override void SetUp() {
			base.SetUp();

			this.factory = new StandardOpenIdExtensionFactory();
			this.factory.RegisterExtension(MockOpenIdExtension.Factory);
			this.rpElement = new ExtensionsBindingElementRelyingParty(this.factory, new RelyingPartySecuritySettings());
			this.rpElement.Channel = new TestChannel(this.MessageDescriptions);
			this.request = new SignedResponseRequest(Protocol.Default.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate);
		}

		[TestCase]
		public void RoundTripFullStackTest() {
			IOpenIdMessageExtension request = new MockOpenIdExtension("requestPart", "requestData");
			IOpenIdMessageExtension response = new MockOpenIdExtension("responsePart", "responseData");
			ExtensionTestUtilities.Roundtrip(
				Protocol.Default,
				new IOpenIdMessageExtension[] { request },
				new IOpenIdMessageExtension[] { response });
		}

		[TestCase]
		public void ExtensionFactory() {
			Assert.AreSame(this.factory, this.rpElement.ExtensionFactory);
		}

		[TestCase, ExpectedException(typeof(ArgumentNullException))]
		public void PrepareMessageForSendingNull() {
			this.rpElement.ProcessOutgoingMessage(null);
		}

		/// <summary>
		/// Verifies that false is returned when a non-extendable message is sent.
		/// </summary>
		[TestCase]
		public void PrepareMessageForSendingNonExtendableMessage() {
			IProtocolMessage request = new AssociateDiffieHellmanRequest(Protocol.Default.Version, OpenIdTestBase.OPUri);
			Assert.IsNull(this.rpElement.ProcessOutgoingMessage(request));
		}

		[TestCase]
		public void PrepareMessageForSending() {
			this.request.Extensions.Add(new MockOpenIdExtension("part", "extra"));
			Assert.IsNotNull(this.rpElement.ProcessOutgoingMessage(this.request));

			string alias = GetAliases(this.request.ExtraData).Single();
			Assert.AreEqual(MockOpenIdExtension.MockTypeUri, this.request.ExtraData["openid.ns." + alias]);
			Assert.AreEqual("part", this.request.ExtraData["openid." + alias + ".Part"]);
			Assert.AreEqual("extra", this.request.ExtraData["openid." + alias + ".data"]);
		}

		[TestCase]
		public void PrepareMessageForReceiving() {
			this.request.ExtraData["openid.ns.mock"] = MockOpenIdExtension.MockTypeUri;
			this.request.ExtraData["openid.mock.Part"] = "part";
			this.request.ExtraData["openid.mock.data"] = "extra";
			Assert.IsNotNull(this.rpElement.ProcessIncomingMessage(this.request));
			MockOpenIdExtension ext = this.request.Extensions.OfType<MockOpenIdExtension>().Single();
			Assert.AreEqual("part", ext.Part);
			Assert.AreEqual("extra", ext.Data);
		}

		/// <summary>
		/// Verifies that extension responses are included in the OP's signature.
		/// </summary>
		[TestCase]
		public void ExtensionResponsesAreSigned() {
			Protocol protocol = Protocol.Default;
			var op = this.CreateProvider();
			IndirectSignedResponse response = this.CreateResponseWithExtensions(protocol);
			op.Channel.PrepareResponse(response);
			ITamperResistantOpenIdMessage signedResponse = (ITamperResistantOpenIdMessage)response;
			string extensionAliasKey = signedResponse.ExtraData.Single(kv => kv.Value == MockOpenIdExtension.MockTypeUri).Key;
			Assert.IsTrue(extensionAliasKey.StartsWith("openid.ns."));
			string extensionAlias = extensionAliasKey.Substring("openid.ns.".Length);

			// Make sure that the extension members and the alias=namespace declaration are all signed.
			Assert.IsNotNull(signedResponse.SignedParameterOrder);
			string[] signedParameters = signedResponse.SignedParameterOrder.Split(',');
			Assert.IsTrue(signedParameters.Contains(extensionAlias + ".Part"));
			Assert.IsTrue(signedParameters.Contains(extensionAlias + ".data"));
			Assert.IsTrue(signedParameters.Contains("ns." + extensionAlias));
		}

		/// <summary>
		/// Verifies that unsigned extension responses (where any or all fields are unsigned) are ignored.
		/// </summary>
		[TestCase]
		public void ExtensionsAreIdentifiedAsSignedOrUnsigned() {
			Protocol protocol = Protocol.Default;
			OpenIdCoordinator coordinator = new OpenIdCoordinator(
				rp => {
					RegisterMockExtension(rp.Channel);
					var response = rp.Channel.ReadFromRequest<IndirectSignedResponse>();
					Assert.AreEqual(1, response.SignedExtensions.Count(), "Signed extension should have been received.");
					Assert.AreEqual(0, response.UnsignedExtensions.Count(), "No unsigned extension should be present.");
					response = rp.Channel.ReadFromRequest<IndirectSignedResponse>();
					Assert.AreEqual(0, response.SignedExtensions.Count(), "No signed extension should have been received.");
					Assert.AreEqual(1, response.UnsignedExtensions.Count(), "Unsigned extension should have been received.");
				},
				op => {
					RegisterMockExtension(op.Channel);
					op.Channel.Respond(CreateResponseWithExtensions(protocol));
					op.Respond(op.GetRequest()); // check_auth
					op.SecuritySettings.SignOutgoingExtensions = false;
					op.Channel.Respond(CreateResponseWithExtensions(protocol));
					op.Respond(op.GetRequest()); // check_auth
				});
			coordinator.Run();
		}

		/// <summary>
		/// Verifies that two extensions with the same TypeURI cannot be applied to the same message.
		/// </summary>
		/// <remarks>
		/// OpenID Authentication 2.0 section 12 states that
		/// "A namespace MUST NOT be assigned more than one alias in the same message".
		/// </remarks>
		[TestCase]
		public void TwoExtensionsSameTypeUri() {
			IOpenIdMessageExtension request1 = new MockOpenIdExtension("requestPart1", "requestData1");
			IOpenIdMessageExtension request2 = new MockOpenIdExtension("requestPart2", "requestData2");
			try {
				ExtensionTestUtilities.Roundtrip(
					Protocol.Default,
					new IOpenIdMessageExtension[] { request1, request2 },
					new IOpenIdMessageExtension[0]);
				Assert.Fail("Expected ProtocolException not thrown.");
			} catch (AssertionException ex) {
				Assert.IsInstanceOf<ProtocolException>(ex.InnerException);
			}
		}

		private static IEnumerable<string> GetAliases(IDictionary<string, string> extraData) {
			Regex regex = new Regex(@"^openid\.ns\.(\w+)");
			return from key in extraData.Keys
				   let m = regex.Match(key)
				   where m.Success
				   select m.Groups[1].Value;
		}

		private static void RegisterMockExtension(Channel channel) {
			Contract.Requires<ArgumentNullException>(channel != null);

			ExtensionTestUtilities.RegisterExtension(channel, MockOpenIdExtension.Factory);
		}

		/// <summary>
		/// Creates a response message with one extensions.
		/// </summary>
		/// <param name="protocol">The protocol to construct the message with.</param>
		/// <returns>The message ready to send from OP to RP.</returns>
		private IndirectSignedResponse CreateResponseWithExtensions(Protocol protocol) {
			Contract.Requires<ArgumentNullException>(protocol != null);

			IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri);
			response.ProviderEndpoint = OPUri;
			response.Extensions.Add(new MockOpenIdExtension("pv", "ev"));
			return response;
		}
	}
}